BlueGit

ict rusty-teams

feat(kvt): ophalen van organisatie-emoji-metadata (WIP, lokale back-up)

Snapshot van het werk zolang git.kvt.nl onbereikbaar is.

hephaestus

Authored 2026-11-28 · 2 days ago

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