use serde::{Deserialize, Serialize}; use serde_json::Value; use session::{Request, Session}; use crate::error::Result; use crate::messages::ensure_success; use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport}; use crate::reactions::CustomEmoji; /// Official web client (2024): `GET /api/csa/{region}/api/v1/customemoji/metadata` /// with the CSA bearer (`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`). /// Optional `x-ms-continuation` asks for changes since the previous `continuationToken`. /// We use the same path on `teams.cloud.microsoft` (the host of every other CSA call here) /// and `DEFAULT_REGION` (`emea`). Live check: the host, the region, and the token audience. const METADATA_PATH: &str = "customemoji/metadata"; const CONTINUATION_HEADER: &str = "x-ms-continuation"; const CUSTOM_CATEGORY: &str = "customEmoji"; const ITEMTYPE: &str = "http://schema.skype.com/CustomEmoji"; const DISPLAY_SIZE: u32 = 20; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct OrgEmoji { pub id: String, pub document_id: String, pub name: String, pub keywords: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option, } impl OrgEmoji { pub fn key(&self) -> String { format!("{};{}", self.name, self.document_id) } pub fn image_url(&self) -> String { if let Some(source) = &self.source { return source.clone(); } CustomEmoji { name: self.name.clone(), object_id: self.document_id.clone(), } .image_url() } pub fn html(&self) -> String { custom_emoji_html(&self.name, &self.document_id, &self.image_url()) } pub fn matches(&self, query: &str) -> bool { let query = query.trim(); if query.is_empty() { return true; } let query = query.to_ascii_lowercase(); self.name.to_ascii_lowercase().contains(&query) || self .keywords .iter() .any(|keyword| keyword.to_ascii_lowercase().contains(&query)) } } #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct OrgEmojiCatalog { pub emojis: Vec, pub deleted_ids: Vec, pub continuation: Option, } pub struct CustomEmojis { transport: T, url: String, } impl CustomEmojis { pub fn new(session: &Session) -> Self { CustomEmojis::with_transport(SessionTransport::new(session), DEFAULT_REGION) } } impl CustomEmojis { pub fn with_transport(transport: T, region: &str) -> Self { CustomEmojis { transport, url: format!("https://teams.cloud.microsoft/api/csa/{region}/api/v1/{METADATA_PATH}"), } } /// A request without `x-ms-continuation` returns the full catalogue. pub async fn list(&self) -> Result { self.fetch(None).await } pub async fn list_since(&self, continuation: &str) -> Result { self.fetch(Some(continuation)).await } async fn fetch(&self, continuation: Option<&str>) -> Result { let mut request = Request::get(&self.url); if let Some(token) = continuation.map(str::trim).filter(|token| !token.is_empty()) { request .headers .push((CONTINUATION_HEADER.to_owned(), token.to_owned())); } let answer = self.transport.send(request).await?; ensure_success(&answer)?; Ok(parse_metadata(&answer.body)) } } /// The HTML the official client accepts when a custom emoji is sent in a message. pub fn custom_emoji_html(name: &str, object_id: &str, source: &str) -> String { format!( "\"{alt}\"", alt = escape_attr(name), itemid = escape_attr(&format!("{name};{object_id}")), src = escape_attr(source), ) } pub fn parse_metadata(body: &Value) -> OrgEmojiCatalog { let continuation = continuation_token(body.get("continuationToken")); let mut emojis = Vec::new(); let mut deleted_ids = Vec::new(); let entries = body .get("categories") .and_then(Value::as_array) .into_iter() .flatten() .filter(|category| category.get("id").and_then(Value::as_str) == Some(CUSTOM_CATEGORY)) .flat_map(|category| { category .get("emoticons") .and_then(Value::as_array) .into_iter() .flatten() }); for entry in entries { match parse_emoticon(entry) { ParsedEmoticon::Live(emoji) => emojis.push(emoji), ParsedEmoticon::Deleted(id) => deleted_ids.push(id), ParsedEmoticon::Skip => {} } } OrgEmojiCatalog { emojis, deleted_ids, continuation, } } /// Apply a delta (or a full list) to a previously cached catalogue. pub fn merge_catalog(previous: &[OrgEmoji], incoming: OrgEmojiCatalog, full: bool) -> OrgEmojiCatalog { if full { return incoming; } let mut by_id: std::collections::HashMap = previous .iter() .cloned() .map(|emoji| (emoji.id.clone(), emoji)) .collect(); for id in &incoming.deleted_ids { by_id.remove(id); } for emoji in incoming.emojis { by_id.insert(emoji.id.clone(), emoji); } let mut emojis: Vec = by_id.into_values().collect(); emojis.sort_by(|left, right| left.name.cmp(&right.name).then(left.id.cmp(&right.id))); OrgEmojiCatalog { emojis, deleted_ids: Vec::new(), continuation: incoming.continuation, } } enum ParsedEmoticon { Live(OrgEmoji), Deleted(String), Skip, } fn parse_emoticon(entry: &Value) -> ParsedEmoticon { let id = entry .get("id") .and_then(Value::as_str) .map(str::trim) .filter(|id| !id.is_empty()) .map(str::to_owned); if entry.get("isDeleted").and_then(Value::as_bool) == Some(true) { return id.map(ParsedEmoticon::Deleted).unwrap_or(ParsedEmoticon::Skip); } let Some(document_id) = entry .get("documentId") .and_then(Value::as_str) .map(str::trim) .filter(|id| crate::links::is_ams_object_id(id)) else { return ParsedEmoticon::Skip; }; let Some(name) = entry .get("shortcuts") .and_then(Value::as_array) .into_iter() .flatten() .filter_map(Value::as_str) .map(str::trim) .find(|name| !name.is_empty()) .or_else(|| { entry .get("description") .and_then(Value::as_str) .map(str::trim) .filter(|name| !name.is_empty()) }) .map(str::to_owned) else { return ParsedEmoticon::Skip; }; let keywords = entry .get("keywords") .and_then(Value::as_array) .into_iter() .flatten() .filter_map(Value::as_str) .map(str::trim) .filter(|keyword| !keyword.is_empty()) .map(str::to_owned) .collect(); ParsedEmoticon::Live(OrgEmoji { id: id.unwrap_or_else(|| document_id.to_owned()), document_id: document_id.to_owned(), name, keywords, source: None, }) } fn continuation_token(value: Option<&Value>) -> Option { match value { Some(Value::String(text)) => Some(text.clone()).filter(|text| !text.is_empty()), Some(Value::Number(number)) => Some(number.to_string()), _ => None, } } fn escape_attr(value: &str) -> String { value .replace('&', "&") .replace('<', "<") .replace('>', ">") .replace('"', """) } #[cfg(test)] mod tests { use std::sync::Mutex; use serde_json::Value; use session::{ApiResponse, Method}; use super::*; struct Canned { body: Value, requests: Mutex>, } impl CsaTransport for &Canned { async fn send(&self, request: Request) -> Result { self.requests.lock().unwrap().push(request); Ok(ApiResponse { status: 200, body: self.body.clone(), retry_after: None, }) } } fn fixture() -> Value { serde_json::from_str(include_str!("../tests/fixtures/custom_emoji_metadata.json")).unwrap() } #[test] fn metadata_keeps_live_emoticons_and_skips_deleted_or_unsafe_ids() { let catalog = parse_metadata(&fixture()); assert_eq!(catalog.continuation.as_deref(), Some("42")); let names: Vec<&str> = catalog.emojis.iter().map(|emoji| emoji.name.as_str()).collect(); assert_eq!(names, ["absolute-cinema", "tsignal"]); assert!(catalog.emojis.iter().all(|emoji| crate::links::is_ams_object_id(&emoji.document_id))); assert!(catalog.emojis[0].matches("cinema")); assert!(catalog.emojis[0].matches("movie")); assert!(!catalog.emojis[0].matches("tsignal")); assert_eq!(catalog.deleted_ids, ["em-gone"]); } #[test] fn merge_catalog_removes_deleted_ids_and_keeps_the_rest() { let previous = vec![ OrgEmoji { id: "em-1".into(), document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(), name: "absolute-cinema".into(), keywords: vec!["cinema".into()], source: None, }, OrgEmoji { id: "em-gone".into(), document_id: "0-weu-d1-deadbeefdeadbeefdeadbeefdeadbeef".into(), name: "old-one".into(), keywords: vec![], source: None, }, ]; let incoming = OrgEmojiCatalog { emojis: vec![OrgEmoji { id: "em-2".into(), document_id: "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853".into(), name: "tsignal".into(), keywords: vec!["tsignal".into()], source: None, }], deleted_ids: vec!["em-gone".into()], continuation: Some("43".into()), }; let merged = merge_catalog(&previous, incoming, false); let names: Vec<&str> = merged.emojis.iter().map(|emoji| emoji.name.as_str()).collect(); assert_eq!(names, ["absolute-cinema", "tsignal"]); assert!(merged.deleted_ids.is_empty()); assert_eq!(merged.continuation.as_deref(), Some("43")); } #[test] fn html_names_the_custom_emoji_itemtype_and_itemid() { let html = custom_emoji_html( "say \"hi\" & ", "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8", "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim", ); assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\"")); assert!(html.contains("itemid=\"say "hi" & <wave>;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\"")); assert!(html.contains("alt=\"say "hi" & <wave>\"")); assert!(html.contains("width=\"20\" height=\"20\"")); assert!(html.contains("style=\"width:20px;height:20px;\"")); assert!(html.contains("/views/imgt2_anim")); } #[tokio::test] async fn list_uses_the_csa_metadata_path_and_omits_continuation_for_a_full_fetch() { let transport = Canned { body: fixture(), requests: Mutex::new(Vec::new()), }; let client = CustomEmojis::with_transport(&transport, "emea"); let catalog = client.list().await.unwrap(); assert_eq!(catalog.emojis.len(), 2); let sent = transport.requests.lock().unwrap(); assert_eq!( sent[0].url, "https://teams.cloud.microsoft/api/csa/emea/api/v1/customemoji/metadata" ); assert_eq!(sent[0].method, Method::Get); assert!( sent[0] .headers .iter() .all(|(name, _)| name != CONTINUATION_HEADER) ); } #[tokio::test] async fn list_since_sends_the_continuation_header() { let transport = Canned { body: fixture(), requests: Mutex::new(Vec::new()), }; let client = CustomEmojis::with_transport(&transport, "emea"); client.list_since("42").await.unwrap(); let sent = transport.requests.lock().unwrap(); assert_eq!( sent[0].headers, vec![(CONTINUATION_HEADER.to_owned(), "42".to_owned())] ); } }