BlueGit

ict rusty-teams

Merge commit '373157c1' into kvt/integratie

hephaestus

Authored 2026-11-28 · 2 days ago

Hash
4a09ee1f222ac6370737ef8a3c8fbf9a8425edc7
23 files changed +1472 −68
KVT-FORK.md +20 −0
@@ -355,6 +355,26 @@ Dit is geen KVT-specifiek gedrag: dezelfde Graph-payload geldt voor elke tenant.
355 355 | Eigen bestanden | — |
356 356 | Upstream aangeraakt | `crates/graph/src/models.rs`, `crates/core/src/mapping.rs`, `crates/chatsvc/src/reactions.rs`, `crates/chatsvc/src/links.rs`, `crates/app-state/src/rows.rs`, `crates/app-state/src/reaction_model.rs`, `crates/app/src/views/reaction_pills.rs`, `crates/app-base/locales/app.yml` |
357 357
358
359 ### Organisatie-emoji in kiezer en berichten — upstream-kandidaat
360
361 De officiële webclient haalt de tenantlijst op via CSA
362 `GET /api/csa/{region}/api/v1/customemoji/metadata` met het bestaande CSA-token
363 (`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`). In een bericht
364 gaat een custom emoji als `<img itemtype="http://schema.skype.com/CustomEmoji" itemid="naam;objectId" …>`.
365 Een reactie gebruikt dezelfde sleutel `naam;objectId`. We cachen de lijst 30 minuten
366 in de store, met optionele delta via `x-ms-continuation`.
367
368 Aannames die nog live getest moeten worden: host (`teams.cloud.microsoft`, het CSA-host
369 van de andere calls hier), regio (`emea`), en of het CSA-token zonder extra scope volstaat.
370 De optionele Graph-beta-route `teamwork/messaging/customEmojis` is niet gebruikt.
371
372 | | |
373 |---|---|
374 | Wat | Organisatie-emoji ophalen en cachen, tab in emoji- en reactiekiezer, zoeken op naam, invoegen en verzenden in het officiële HTML-formaat, plus demomodus |
375 | Eigen bestanden | — |
376 | Upstream aangeraakt | `crates/chatsvc/src/custom_emojis.rs`, `crates/core/src/org_emojis.rs`, `crates/core/src/remote.rs`, `crates/core/src/spans.rs`, `crates/app-state/src/org_emojis.rs`, `crates/app-state/src/demo.rs`, `crates/app-state/src/stored_outgoing.rs`, `crates/app-base/src/remote_image.rs`, `crates/app/src/views/fun_picker.rs`, `crates/app/src/views/reaction_picker.rs`, `crates/app/src/views/attachment_tray.rs`, `crates/app/src/views/composer.rs`, `crates/app-base/locales/app.yml` |
377
358 378 ## Eigen modules in het kort
359 379
360 380
@@ -355,6 +355,26 @@ Dit is geen KVT-specifiek gedrag: dezelfde Graph-payload geldt voor elke tenant.
355| Eigen bestanden | — |
355| Eigen bestanden | — |
356| Upstream aangeraakt | `crates/graph/src/models.rs`, `crates/core/src/mapping.rs`, `crates/chatsvc/src/reactions.rs`, `crates/chatsvc/src/links.rs`, `crates/app-state/src/rows.rs`, `crates/app-state/src/reaction_model.rs`, `crates/app/src/views/reaction_pills.rs`, `crates/app-base/locales/app.yml` |
356| Upstream aangeraakt | `crates/graph/src/models.rs`, `crates/core/src/mapping.rs`, `crates/chatsvc/src/reactions.rs`, `crates/chatsvc/src/links.rs`, `crates/app-state/src/rows.rs`, `crates/app-state/src/reaction_model.rs`, `crates/app/src/views/reaction_pills.rs`, `crates/app-base/locales/app.yml` |
357
357
358
359### Organisatie-emoji in kiezer en berichten — upstream-kandidaat
360
361De officiële webclient haalt de tenantlijst op via CSA
362`GET /api/csa/{region}/api/v1/customemoji/metadata` met het bestaande CSA-token
363(`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`). In een bericht
364gaat een custom emoji als `<img itemtype="http://schema.skype.com/CustomEmoji" itemid="naam;objectId" …>`.
365Een reactie gebruikt dezelfde sleutel `naam;objectId`. We cachen de lijst 30 minuten
366in de store, met optionele delta via `x-ms-continuation`.
367
368Aannames die nog live getest moeten worden: host (`teams.cloud.microsoft`, het CSA-host
369van de andere calls hier), regio (`emea`), en of het CSA-token zonder extra scope volstaat.
370De optionele Graph-beta-route `teamwork/messaging/customEmojis` is niet gebruikt.
371
372| | |
373|---|---|
374| Wat | Organisatie-emoji ophalen en cachen, tab in emoji- en reactiekiezer, zoeken op naam, invoegen en verzenden in het officiële HTML-formaat, plus demomodus |
375| Eigen bestanden | — |
376| Upstream aangeraakt | `crates/chatsvc/src/custom_emojis.rs`, `crates/core/src/org_emojis.rs`, `crates/core/src/remote.rs`, `crates/core/src/spans.rs`, `crates/app-state/src/org_emojis.rs`, `crates/app-state/src/demo.rs`, `crates/app-state/src/stored_outgoing.rs`, `crates/app-base/src/remote_image.rs`, `crates/app/src/views/fun_picker.rs`, `crates/app/src/views/reaction_picker.rs`, `crates/app/src/views/attachment_tray.rs`, `crates/app/src/views/composer.rs`, `crates/app-base/locales/app.yml` |
377
358## Eigen modules in het kort
378## Eigen modules in het kort
359
379
360
380
crates/app-base/locales/app.yml +77 −0
@@ -115,6 +115,83 @@ reaction:
115 115 de: Organisations-Emoji
116 116 nl: Organisatie-emoji
117 117
118 fun_picker:
119 tab:
120 emoji:
121 en: Emoji
122 de: Emoji
123 nl: Emoji
124 gif:
125 en: GIF
126 de: GIF
127 nl: GIF
128 sticker:
129 en: Sticker
130 de: Sticker
131 nl: Sticker
132 org:
133 en: Organization
134 de: Organisation
135 nl: Organisatie
136 search:
137 emoji:
138 en: Search emoji
139 de: Emoji suchen
140 nl: Emoji zoeken
141 gif:
142 en: Search GIFs
143 de: GIFs suchen
144 nl: GIFs zoeken
145 sticker:
146 en: Search stickers
147 de: Sticker suchen
148 nl: Stickers zoeken
149 org:
150 en: Search organization emoji
151 de: Organisations-Emoji suchen
152 nl: Organisatie-emoji zoeken
153 org:
154 empty:
155 en: No organization emoji
156 de: Keine Organisations-Emojis
157 nl: Geen organisatie-emoji
158 empty_query:
159 en: "No organization emoji for \"%{query}\""
160 de: "Keine Organisations-Emojis zu \"%{query}\""
161 nl: "Geen organisatie-emoji voor \"%{query}\""
162 failed:
163 en: Organization emoji could not be loaded.
164 de: Organisations-Emojis konnten nicht geladen werden.
165 nl: Organisatie-emoji konden niet worden geladen.
166 retry:
167 en: Try again
168 de: Erneut versuchen
169 nl: Opnieuw proberen
170 reaction_picker:
171 tab:
172 emoji:
173 en: Emoji
174 de: Emoji
175 nl: Emoji
176 org:
177 en: Organization
178 de: Organisation
179 nl: Organisatie
180 search:
181 org:
182 en: Search organization emoji
183 de: Organisations-Emoji suchen
184 nl: Organisatie-emoji zoeken
185 org:
186 empty:
187 en: No organization emoji
188 de: Keine Organisations-Emojis
189 nl: Geen organisatie-emoji
190 empty_query:
191 en: "No organization emoji for \"%{query}\""
192 de: "Keine Organisations-Emojis zu \"%{query}\""
193 nl: "Geen organisatie-emoji voor \"%{query}\""
194
118 195
119 196 settings:
120 197 search:
@@ -115,6 +115,83 @@ reaction:
115 de: Organisations-Emoji
115 de: Organisations-Emoji
116 nl: Organisatie-emoji
116 nl: Organisatie-emoji
117
117
118fun_picker:
119 tab:
120 emoji:
121 en: Emoji
122 de: Emoji
123 nl: Emoji
124 gif:
125 en: GIF
126 de: GIF
127 nl: GIF
128 sticker:
129 en: Sticker
130 de: Sticker
131 nl: Sticker
132 org:
133 en: Organization
134 de: Organisation
135 nl: Organisatie
136 search:
137 emoji:
138 en: Search emoji
139 de: Emoji suchen
140 nl: Emoji zoeken
141 gif:
142 en: Search GIFs
143 de: GIFs suchen
144 nl: GIFs zoeken
145 sticker:
146 en: Search stickers
147 de: Sticker suchen
148 nl: Stickers zoeken
149 org:
150 en: Search organization emoji
151 de: Organisations-Emoji suchen
152 nl: Organisatie-emoji zoeken
153 org:
154 empty:
155 en: No organization emoji
156 de: Keine Organisations-Emojis
157 nl: Geen organisatie-emoji
158 empty_query:
159 en: "No organization emoji for \"%{query}\""
160 de: "Keine Organisations-Emojis zu \"%{query}\""
161 nl: "Geen organisatie-emoji voor \"%{query}\""
162 failed:
163 en: Organization emoji could not be loaded.
164 de: Organisations-Emojis konnten nicht geladen werden.
165 nl: Organisatie-emoji konden niet worden geladen.
166 retry:
167 en: Try again
168 de: Erneut versuchen
169 nl: Opnieuw proberen
170reaction_picker:
171 tab:
172 emoji:
173 en: Emoji
174 de: Emoji
175 nl: Emoji
176 org:
177 en: Organization
178 de: Organisation
179 nl: Organisatie
180 search:
181 org:
182 en: Search organization emoji
183 de: Organisations-Emoji suchen
184 nl: Organisatie-emoji zoeken
185 org:
186 empty:
187 en: No organization emoji
188 de: Keine Organisations-Emojis
189 nl: Geen organisatie-emoji
190 empty_query:
191 en: "No organization emoji for \"%{query}\""
192 de: "Keine Organisations-Emojis zu \"%{query}\""
193 nl: "Geen organisatie-emoji voor \"%{query}\""
194
118
195
119settings:
196settings:
120 search:
197 search:
crates/app-base/src/remote_image.rs +54 −13
@@ -1,5 +1,5 @@
1 1 use gpui_kit::{ImageSource, SharedString};
2 use teams_core::{Gif, ImageRef};
2 use teams_core::{Gif, ImageRef, OrgEmoji, custom_emoji_html};
3 3
4 4 use crate::stickers::Sticker;
5 5
@@ -8,10 +8,11 @@ const STICKER_SIZE: u32 = 250;
8 8 const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";
9 9 const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";
10 10
11 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
11 #[derive(Debug, Clone, PartialEq, Eq)]
12 12 pub enum RemoteKind {
13 13 Gif,
14 14 Sticker,
15 CustomEmoji { object_id: String },
15 16 }
16 17
17 18 /// A GIF or sticker the message points at by URL; nothing is uploaded.
@@ -46,18 +47,42 @@ impl RemoteImage {
46 47 }
47 48 }
48 49
50 pub fn custom_emoji(emoji: &OrgEmoji) -> Self {
51 RemoteImage {
52 kind: RemoteKind::CustomEmoji {
53 object_id: emoji.document_id.clone(),
54 },
55 url: emoji.image_url(),
56 title: emoji.name.clone(),
57 width: 20,
58 height: 20,
59 }
60 }
61
62 pub fn is_custom_emoji(&self) -> bool {
63 matches!(self.kind, RemoteKind::CustomEmoji { .. })
64 }
65
49 66 pub fn html(&self) -> String {
50 let itemtype = match self.kind {
51 RemoteKind::Gif => GIF_ITEMTYPE,
52 RemoteKind::Sticker => STICKER_ITEMTYPE,
53 };
54 format!(
55 "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{itemtype}\">",
56 teams_core::escape_html(&self.url),
57 self.width,
58 self.height,
59 teams_core::escape_html(&self.title),
60 )
67 match &self.kind {
68 RemoteKind::CustomEmoji { object_id } => {
69 custom_emoji_html(&self.title, object_id, &self.url)
70 }
71 RemoteKind::Gif => format!(
72 "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{GIF_ITEMTYPE}\">",
73 teams_core::escape_html(&self.url),
74 self.width,
75 self.height,
76 teams_core::escape_html(&self.title),
77 ),
78 RemoteKind::Sticker => format!(
79 "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{STICKER_ITEMTYPE}\">",
80 teams_core::escape_html(&self.url),
81 self.width,
82 self.height,
83 teams_core::escape_html(&self.title),
84 ),
85 }
61 86 }
62 87
63 88 pub fn image_ref(&self) -> ImageRef {
@@ -131,4 +156,20 @@ mod tests {
131 156 assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">"));
132 157 assert!(html.contains("clippy-250x250"));
133 158 }
159
160 #[test]
161 fn custom_emoji_html_uses_the_official_itemtype_and_itemid() {
162 let emoji = OrgEmoji {
163 id: "em-1".into(),
164 document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
165 name: "absolute-cinema".into(),
166 keywords: vec![],
167 source: None,
168 };
169 let html = RemoteImage::custom_emoji(&emoji).html();
170 assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\""));
171 assert!(html.contains("itemid=\"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\""));
172 assert!(html.contains("width=\"20\" height=\"20\""));
173 assert!(html.contains("/views/imgt2_anim"));
174 }
134 175 }
@@ -1,5 +1,5 @@
1use gpui_kit::{ImageSource, SharedString};
1use gpui_kit::{ImageSource, SharedString};
2use teams_core::{Gif, ImageRef};
2use teams_core::{Gif, ImageRef, OrgEmoji, custom_emoji_html};
3
3
4use crate::stickers::Sticker;
4use crate::stickers::Sticker;
5
5
@@ -8,10 +8,11 @@ const STICKER_SIZE: u32 = 250;
8const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";
8const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";
9const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";
9const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";
10
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum RemoteKind {
12pub enum RemoteKind {
13 Gif,
13 Gif,
14 Sticker,
14 Sticker,
15 CustomEmoji { object_id: String },
15}
16}
16
17
17/// A GIF or sticker the message points at by URL; nothing is uploaded.
18/// A GIF or sticker the message points at by URL; nothing is uploaded.
@@ -46,18 +47,42 @@ impl RemoteImage {
46 }
47 }
47 }
48 }
48
49
50 pub fn custom_emoji(emoji: &OrgEmoji) -> Self {
51 RemoteImage {
52 kind: RemoteKind::CustomEmoji {
53 object_id: emoji.document_id.clone(),
54 },
55 url: emoji.image_url(),
56 title: emoji.name.clone(),
57 width: 20,
58 height: 20,
59 }
60 }
61
62 pub fn is_custom_emoji(&self) -> bool {
63 matches!(self.kind, RemoteKind::CustomEmoji { .. })
64 }
65
49 pub fn html(&self) -> String {
66 pub fn html(&self) -> String {
50 let itemtype = match self.kind {
67 match &self.kind {
51 RemoteKind::Gif => GIF_ITEMTYPE,
68 RemoteKind::CustomEmoji { object_id } => {
52 RemoteKind::Sticker => STICKER_ITEMTYPE,
69 custom_emoji_html(&self.title, object_id, &self.url)
53 };
70 }
54 format!(
71 RemoteKind::Gif => format!(
55 "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{itemtype}\">",
72 "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{GIF_ITEMTYPE}\">",
56 teams_core::escape_html(&self.url),
73 teams_core::escape_html(&self.url),
57 self.width,
74 self.width,
58 self.height,
75 self.height,
59 teams_core::escape_html(&self.title),
76 teams_core::escape_html(&self.title),
60 )
77 ),
78 RemoteKind::Sticker => format!(
79 "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{STICKER_ITEMTYPE}\">",
80 teams_core::escape_html(&self.url),
81 self.width,
82 self.height,
83 teams_core::escape_html(&self.title),
84 ),
85 }
61 }
86 }
62
87
63 pub fn image_ref(&self) -> ImageRef {
88 pub fn image_ref(&self) -> ImageRef {
@@ -131,4 +156,20 @@ mod tests {
131 assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">"));
156 assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">"));
132 assert!(html.contains("clippy-250x250"));
157 assert!(html.contains("clippy-250x250"));
133 }
158 }
159
160 #[test]
161 fn custom_emoji_html_uses_the_official_itemtype_and_itemid() {
162 let emoji = OrgEmoji {
163 id: "em-1".into(),
164 document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
165 name: "absolute-cinema".into(),
166 keywords: vec![],
167 source: None,
168 };
169 let html = RemoteImage::custom_emoji(&emoji).html();
170 assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\""));
171 assert!(html.contains("itemid=\"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\""));
172 assert!(html.contains("width=\"20\" height=\"20\""));
173 assert!(html.contains("/views/imgt2_anim"));
174 }
134}
175}
crates/app-state/src/demo.rs +136 −1
@@ -13,7 +13,8 @@ use store::{
13 13 use teams_core::{
14 14 ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot,
15 15 CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
16 LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource, PinnedMessage,
16 LinkPreview, MentionCandidate, NOTES_CHAT_ID, OrgEmoji, PersonCandidate, PersonSource, PinnedMessage,
17 custom_emoji_html,
17 18 SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
18 19 };
19 20
@@ -24,6 +25,7 @@ use crate::demo_gifs;
24 25 use crate::message_actions::ForwardSource;
25 26
26 27 static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
28 static DEMO_ORG_EMOJIS: OnceLock<Vec<OrgEmoji>> = OnceLock::new();
27 29
28 30 pub const DEMO_USER_ID: &str = "demo-me";
29 31 const DEMO_USER_NAME: &str = "Dana Demo";
@@ -595,6 +597,101 @@ fn image_directory() -> PathBuf {
595 597 std::env::temp_dir().join("rusty-teams-demo")
596 598 }
597 599
600 pub const DEMO_ORG_KOFIE_ID: &str = "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
601 pub const DEMO_ORG_SHIPIT_ID: &str = "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
602 pub const DEMO_ORG_HIGHFIVE_ID: &str = "0-weu-d1-cccccccccccccccccccccccccccccccc";
603 pub const DEMO_ORG_FEEST_ID: &str = "0-weu-d1-dddddddddddddddddddddddddddddddd";
604
605 pub fn org_emoji_demo_url(name: &str) -> String {
606 format!("demo://org-emoji-{name}")
607 }
608
609 pub fn org_emoji_source(object_id: &str) -> Option<String> {
610 DEMO_ORG_EMOJIS
611 .get()
612 .into_iter()
613 .flatten()
614 .find(|emoji| emoji.document_id == object_id)
615 .and_then(|emoji| emoji.source.clone())
616 }
617
618 pub fn org_emoji_image_url(object_id: &str) -> Option<String> {
619 DEMO_ORG_EMOJIS
620 .get()
621 .into_iter()
622 .flatten()
623 .find(|emoji| emoji.document_id == object_id)
624 .map(|emoji| org_emoji_demo_url(&emoji.name))
625 }
626
627 pub fn ensure_org_emojis() -> Vec<OrgEmoji> {
628 if let Some(emojis) = DEMO_ORG_EMOJIS.get() {
629 return emojis.clone();
630 }
631 let emojis = generate_org_emojis(&image_directory());
632 let _ = DEMO_ORG_EMOJIS.set(emojis.clone());
633 emojis
634 }
635
636 fn demo_org_emoji_html(name: &str, document_id: &str) -> String {
637 custom_emoji_html(name, document_id, &org_emoji_demo_url(name))
638 }
639
640 pub fn org_emojis() -> Vec<OrgEmoji> {
641 ensure_org_emojis()
642 }
643
644 pub fn search_org_emojis(query: &str) -> Vec<OrgEmoji> {
645 org_emojis()
646 .into_iter()
647 .filter(|emoji| emoji.matches(query))
648 .collect()
649 }
650
651 fn generate_org_emojis(directory: &std::path::Path) -> Vec<OrgEmoji> {
652 const FACES: [(&str, &str, &str, [u8; 3], &[&str]); 4] = [
653 ("demo-koffie", "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "koffie", [166, 92, 46], &["koffie", "coffee"]),
654 ("demo-shipit", "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "ship-it", [47, 133, 90], &["ship", "lancering"]),
655 ("demo-highfive", "0-weu-d1-cccccccccccccccccccccccccccccccc", "high-five", [196, 92, 58], &["highfive", "team"]),
656 ("demo-feest", "0-weu-d1-dddddddddddddddddddddddddddddddd", "feest", [126, 68, 173], &["feest", "party"]),
657 ];
658 let mut emojis = Vec::new();
659 let _ = std::fs::create_dir_all(directory);
660 for (id, document_id, name, color, keywords) in FACES {
661 let path = directory.join(format!("org-emoji-{name}.png"));
662 let png = encode_rgb(32, 32, |column, row| {
663 let dx = column as i32 - 16;
664 let dy = row as i32 - 16;
665 if dx * dx + dy * dy <= 13 * 13 {
666 if (dx + dy) < -6 {
667 [
668 color[0].saturating_add(40).min(255),
669 color[1].saturating_add(40).min(255),
670 color[2].saturating_add(40).min(255),
671 ]
672 } else {
673 color
674 }
675 } else {
676 [255, 255, 255]
677 }
678 });
679 let source = if std::fs::write(&path, png).is_ok() {
680 Some(path.to_string_lossy().into_owned())
681 } else {
682 None
683 };
684 emojis.push(OrgEmoji {
685 id: id.to_owned(),
686 document_id: document_id.to_owned(),
687 name: name.to_owned(),
688 keywords: keywords.iter().map(|keyword| (*keyword).to_owned()).collect(),
689 source,
690 });
691 }
692 emojis
693 }
694
598 695 pub fn search_gifs(query: &str) -> Vec<Gif> {
599 696 let query = query.trim().to_lowercase();
600 697 SEARCHABLE_GIFS
@@ -847,6 +944,7 @@ pub fn activity_snapshot() -> ActivitySnapshot {
847 944 }
848 945
849 946 pub fn seed(store: &Store) {
947 let _ = ensure_org_emojis();
850 948 let chats: Vec<ChatRecord> = demo_chats()
851 949 .into_iter()
852 950 .map(|demo| ChatRecord {
@@ -1092,6 +1190,14 @@ pub fn seed_directory(state: &mut AppState) {
1092 1190 state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path);
1093 1191 }
1094 1192 let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
1193 let org_emojis = ensure_org_emojis();
1194 for emoji in &org_emojis {
1195 if let Some(path) = emoji.source.as_deref() {
1196 state
1197 .directory
1198 .set_image(&org_emoji_demo_url(&emoji.name), std::path::Path::new(path));
1199 }
1200 }
1095 1201 state.directory.set_image(
1096 1202 demo_gifs::RECEIVED_GIF_KEY,
1097 1203 &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
@@ -2033,6 +2139,35 @@ fn release_messages() -> Vec<MessageRecord> {
2033 2139 "[]",
2034 2140 false,
2035 2141 ),
2142 {
2143 let org = reactions_json(vec![
2144 reaction(
2145 &format!("koffie;{DEMO_ORG_KOFIE_ID}"),
2146 &[
2147 (MARA_ID, mara_name, at(0, 13, 58)),
2148 (JONAS_ID, jonas_name, at(0, 13, 59)),
2149 ],
2150 ),
2151 reaction(
2152 &format!("feest;{DEMO_ORG_FEEST_ID}"),
2153 &[(PRIYA_ID, priya_name, at(0, 14, 0))],
2154 ),
2155 ]);
2156 message(
2157 chat,
2158 "m13",
2159 None,
2160 me,
2161 at(0, 13, 56),
2162 &format!(
2163 "<p>De organisatie-emoji staan erin, bijvoorbeeld {} bij de koffie en {} als we live gaan.</p>",
2164 demo_org_emoji_html("koffie", DEMO_ORG_KOFIE_ID),
2165 demo_org_emoji_html("ship-it", DEMO_ORG_SHIPIT_ID),
2166 ),
2167 &org,
2168 false,
2169 )
2170 },
2036 2171 ]
2037 2172 }
2038 2173
@@ -13,7 +13,8 @@ use store::{
13use teams_core::{
13use teams_core::{
14 ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot,
14 ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot,
15 CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
15 CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
16 LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource, PinnedMessage,
16 LinkPreview, MentionCandidate, NOTES_CHAT_ID, OrgEmoji, PersonCandidate, PersonSource, PinnedMessage,
17 custom_emoji_html,
17 SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
18 SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
18};
19};
19
20
@@ -24,6 +25,7 @@ use crate::demo_gifs;
24use crate::message_actions::ForwardSource;
25use crate::message_actions::ForwardSource;
25
26
26static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
27static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
28static DEMO_ORG_EMOJIS: OnceLock<Vec<OrgEmoji>> = OnceLock::new();
27
29
28pub const DEMO_USER_ID: &str = "demo-me";
30pub const DEMO_USER_ID: &str = "demo-me";
29const DEMO_USER_NAME: &str = "Dana Demo";
31const DEMO_USER_NAME: &str = "Dana Demo";
@@ -595,6 +597,101 @@ fn image_directory() -> PathBuf {
595 std::env::temp_dir().join("rusty-teams-demo")
597 std::env::temp_dir().join("rusty-teams-demo")
596}
598}
597
599
600pub const DEMO_ORG_KOFIE_ID: &str = "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
601pub const DEMO_ORG_SHIPIT_ID: &str = "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
602pub const DEMO_ORG_HIGHFIVE_ID: &str = "0-weu-d1-cccccccccccccccccccccccccccccccc";
603pub const DEMO_ORG_FEEST_ID: &str = "0-weu-d1-dddddddddddddddddddddddddddddddd";
604
605pub fn org_emoji_demo_url(name: &str) -> String {
606 format!("demo://org-emoji-{name}")
607}
608
609pub fn org_emoji_source(object_id: &str) -> Option<String> {
610 DEMO_ORG_EMOJIS
611 .get()
612 .into_iter()
613 .flatten()
614 .find(|emoji| emoji.document_id == object_id)
615 .and_then(|emoji| emoji.source.clone())
616}
617
618pub fn org_emoji_image_url(object_id: &str) -> Option<String> {
619 DEMO_ORG_EMOJIS
620 .get()
621 .into_iter()
622 .flatten()
623 .find(|emoji| emoji.document_id == object_id)
624 .map(|emoji| org_emoji_demo_url(&emoji.name))
625}
626
627pub fn ensure_org_emojis() -> Vec<OrgEmoji> {
628 if let Some(emojis) = DEMO_ORG_EMOJIS.get() {
629 return emojis.clone();
630 }
631 let emojis = generate_org_emojis(&image_directory());
632 let _ = DEMO_ORG_EMOJIS.set(emojis.clone());
633 emojis
634}
635
636fn demo_org_emoji_html(name: &str, document_id: &str) -> String {
637 custom_emoji_html(name, document_id, &org_emoji_demo_url(name))
638}
639
640pub fn org_emojis() -> Vec<OrgEmoji> {
641 ensure_org_emojis()
642}
643
644pub fn search_org_emojis(query: &str) -> Vec<OrgEmoji> {
645 org_emojis()
646 .into_iter()
647 .filter(|emoji| emoji.matches(query))
648 .collect()
649}
650
651fn generate_org_emojis(directory: &std::path::Path) -> Vec<OrgEmoji> {
652 const FACES: [(&str, &str, &str, [u8; 3], &[&str]); 4] = [
653 ("demo-koffie", "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "koffie", [166, 92, 46], &["koffie", "coffee"]),
654 ("demo-shipit", "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "ship-it", [47, 133, 90], &["ship", "lancering"]),
655 ("demo-highfive", "0-weu-d1-cccccccccccccccccccccccccccccccc", "high-five", [196, 92, 58], &["highfive", "team"]),
656 ("demo-feest", "0-weu-d1-dddddddddddddddddddddddddddddddd", "feest", [126, 68, 173], &["feest", "party"]),
657 ];
658 let mut emojis = Vec::new();
659 let _ = std::fs::create_dir_all(directory);
660 for (id, document_id, name, color, keywords) in FACES {
661 let path = directory.join(format!("org-emoji-{name}.png"));
662 let png = encode_rgb(32, 32, |column, row| {
663 let dx = column as i32 - 16;
664 let dy = row as i32 - 16;
665 if dx * dx + dy * dy <= 13 * 13 {
666 if (dx + dy) < -6 {
667 [
668 color[0].saturating_add(40).min(255),
669 color[1].saturating_add(40).min(255),
670 color[2].saturating_add(40).min(255),
671 ]
672 } else {
673 color
674 }
675 } else {
676 [255, 255, 255]
677 }
678 });
679 let source = if std::fs::write(&path, png).is_ok() {
680 Some(path.to_string_lossy().into_owned())
681 } else {
682 None
683 };
684 emojis.push(OrgEmoji {
685 id: id.to_owned(),
686 document_id: document_id.to_owned(),
687 name: name.to_owned(),
688 keywords: keywords.iter().map(|keyword| (*keyword).to_owned()).collect(),
689 source,
690 });
691 }
692 emojis
693}
694
598pub fn search_gifs(query: &str) -> Vec<Gif> {
695pub fn search_gifs(query: &str) -> Vec<Gif> {
599 let query = query.trim().to_lowercase();
696 let query = query.trim().to_lowercase();
600 SEARCHABLE_GIFS
697 SEARCHABLE_GIFS
@@ -847,6 +944,7 @@ pub fn activity_snapshot() -> ActivitySnapshot {
847}
944}
848
945
849pub fn seed(store: &Store) {
946pub fn seed(store: &Store) {
947 let _ = ensure_org_emojis();
850 let chats: Vec<ChatRecord> = demo_chats()
948 let chats: Vec<ChatRecord> = demo_chats()
851 .into_iter()
949 .into_iter()
852 .map(|demo| ChatRecord {
950 .map(|demo| ChatRecord {
@@ -1092,6 +1190,14 @@ pub fn seed_directory(state: &mut AppState) {
1092 state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path);
1190 state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path);
1093 }
1191 }
1094 let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
1192 let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
1193 let org_emojis = ensure_org_emojis();
1194 for emoji in &org_emojis {
1195 if let Some(path) = emoji.source.as_deref() {
1196 state
1197 .directory
1198 .set_image(&org_emoji_demo_url(&emoji.name), std::path::Path::new(path));
1199 }
1200 }
1095 state.directory.set_image(
1201 state.directory.set_image(
1096 demo_gifs::RECEIVED_GIF_KEY,
1202 demo_gifs::RECEIVED_GIF_KEY,
1097 &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
1203 &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
@@ -2033,6 +2139,35 @@ fn release_messages() -> Vec<MessageRecord> {
2033 "[]",
2139 "[]",
2034 false,
2140 false,
2035 ),
2141 ),
2142 {
2143 let org = reactions_json(vec![
2144 reaction(
2145 &format!("koffie;{DEMO_ORG_KOFIE_ID}"),
2146 &[
2147 (MARA_ID, mara_name, at(0, 13, 58)),
2148 (JONAS_ID, jonas_name, at(0, 13, 59)),
2149 ],
2150 ),
2151 reaction(
2152 &format!("feest;{DEMO_ORG_FEEST_ID}"),
2153 &[(PRIYA_ID, priya_name, at(0, 14, 0))],
2154 ),
2155 ]);
2156 message(
2157 chat,
2158 "m13",
2159 None,
2160 me,
2161 at(0, 13, 56),
2162 &format!(
2163 "<p>De organisatie-emoji staan erin, bijvoorbeeld {} bij de koffie en {} als we live gaan.</p>",
2164 demo_org_emoji_html("koffie", DEMO_ORG_KOFIE_ID),
2165 demo_org_emoji_html("ship-it", DEMO_ORG_SHIPIT_ID),
2166 ),
2167 &org,
2168 false,
2169 )
2170 },
2036 ]
2171 ]
2037}
2172}
2038
2173
crates/app-state/src/lib.rs +1 −0
@@ -45,6 +45,7 @@ pub mod message_actions;
45 45 pub mod notice;
46 46 pub mod notify;
47 47 mod org_actions;
48 pub mod org_emojis;
48 49 pub mod org_watch;
49 50 pub mod outbox;
50 51 pub mod outgoing;
@@ -45,6 +45,7 @@ pub mod message_actions;
45pub mod notice;
45pub mod notice;
46pub mod notify;
46pub mod notify;
47mod org_actions;
47mod org_actions;
48pub mod org_emojis;
48pub mod org_watch;
49pub mod org_watch;
49pub mod outbox;
50pub mod outbox;
50pub mod outgoing;
51pub mod outgoing;
crates/app-state/src/org_emojis.rs added +67 −0
@@ -0,0 +1,67 @@
1 use std::sync::Arc;
2
3 use teams_core::OrgEmoji;
4 use tokio::sync::oneshot;
5
6 use crate::backend::Engine;
7 use crate::{demo, runtime};
8
9 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
10 pub enum OrgEmojiError {
11 Failed,
12 }
13
14 pub type OrgEmojiList = oneshot::Receiver<Result<Vec<OrgEmoji>, OrgEmojiError>>;
15
16 /// Demo mode answers with fabricated organisation emojis. A live session
17 /// uses the cached CSA catalogue, refreshing when it is older than 30 minutes.
18 pub fn list(engine: Option<Arc<Engine>>, demo_mode: bool, force: bool) -> OrgEmojiList {
19 if demo_mode {
20 return runtime::spawn(async move { Ok(demo::org_emojis()) });
21 }
22 let Some(engine) = engine else {
23 let (sender, receiver) = oneshot::channel();
24 let _ = sender.send(Err(OrgEmojiError::Failed));
25 return receiver;
26 };
27 runtime::spawn(async move {
28 engine
29 .list_org_emojis(force)
30 .await
31 .map_err(|_| OrgEmojiError::Failed)
32 })
33 }
34
35 pub fn filter<'a>(emojis: &'a [OrgEmoji], query: &str) -> Vec<&'a OrgEmoji> {
36 emojis
37 .iter()
38 .filter(|emoji| emoji.matches(query))
39 .collect()
40 }
41
42 #[cfg(test)]
43 mod tests {
44 use super::*;
45
46 #[test]
47 fn demo_catalogue_is_searchable_by_name_and_keyword() {
48 let emojis = crate::demo::org_emojis();
49 assert!(emojis.len() >= 4);
50 assert!(emojis.iter().any(|emoji| emoji.name == "koffie"));
51 assert!(filter(&emojis, "ship").iter().any(|emoji| emoji.name == "ship-it"));
52 assert!(filter(&emojis, "lancering").iter().any(|emoji| emoji.name == "ship-it"));
53 assert!(filter(&emojis, "zzz").is_empty());
54 for emoji in &emojis {
55 assert!(emoji.document_id.starts_with("0-"));
56 let source = emoji.source.as_deref().expect("demo writes a local png");
57 assert!(std::path::Path::new(source).is_file());
58 }
59 let key = format!("koffie;{}", crate::demo::DEMO_ORG_KOFIE_ID);
60 let image = crate::rows::custom_emoji_image(&key).expect("demo koffie");
61 assert_eq!(image.url, crate::demo::org_emoji_demo_url("koffie"));
62 assert!(!image.url.contains("custo"), "{}", image.url);
63 assert_eq!(image.alt.as_deref(), Some("koffie"));
64 let source = crate::demo::org_emoji_source(crate::demo::DEMO_ORG_KOFIE_ID).expect("source");
65 assert!(std::path::Path::new(&source).is_file());
66 }
67 }
@@ -0,0 +1,67 @@
1use std::sync::Arc;
2
3use teams_core::OrgEmoji;
4use tokio::sync::oneshot;
5
6use crate::backend::Engine;
7use crate::{demo, runtime};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum OrgEmojiError {
11 Failed,
12}
13
14pub type OrgEmojiList = oneshot::Receiver<Result<Vec<OrgEmoji>, OrgEmojiError>>;
15
16/// Demo mode answers with fabricated organisation emojis. A live session
17/// uses the cached CSA catalogue, refreshing when it is older than 30 minutes.
18pub fn list(engine: Option<Arc<Engine>>, demo_mode: bool, force: bool) -> OrgEmojiList {
19 if demo_mode {
20 return runtime::spawn(async move { Ok(demo::org_emojis()) });
21 }
22 let Some(engine) = engine else {
23 let (sender, receiver) = oneshot::channel();
24 let _ = sender.send(Err(OrgEmojiError::Failed));
25 return receiver;
26 };
27 runtime::spawn(async move {
28 engine
29 .list_org_emojis(force)
30 .await
31 .map_err(|_| OrgEmojiError::Failed)
32 })
33}
34
35pub fn filter<'a>(emojis: &'a [OrgEmoji], query: &str) -> Vec<&'a OrgEmoji> {
36 emojis
37 .iter()
38 .filter(|emoji| emoji.matches(query))
39 .collect()
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 #[test]
47 fn demo_catalogue_is_searchable_by_name_and_keyword() {
48 let emojis = crate::demo::org_emojis();
49 assert!(emojis.len() >= 4);
50 assert!(emojis.iter().any(|emoji| emoji.name == "koffie"));
51 assert!(filter(&emojis, "ship").iter().any(|emoji| emoji.name == "ship-it"));
52 assert!(filter(&emojis, "lancering").iter().any(|emoji| emoji.name == "ship-it"));
53 assert!(filter(&emojis, "zzz").is_empty());
54 for emoji in &emojis {
55 assert!(emoji.document_id.starts_with("0-"));
56 let source = emoji.source.as_deref().expect("demo writes a local png");
57 assert!(std::path::Path::new(source).is_file());
58 }
59 let key = format!("koffie;{}", crate::demo::DEMO_ORG_KOFIE_ID);
60 let image = crate::rows::custom_emoji_image(&key).expect("demo koffie");
61 assert_eq!(image.url, crate::demo::org_emoji_demo_url("koffie"));
62 assert!(!image.url.contains("custo"), "{}", image.url);
63 assert_eq!(image.alt.as_deref(), Some("koffie"));
64 let source = crate::demo::org_emoji_source(crate::demo::DEMO_ORG_KOFIE_ID).expect("source");
65 assert!(std::path::Path::new(&source).is_file());
66 }
67}
crates/app-state/src/rows.rs +1 −1
@@ -75,7 +75,7 @@ pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {
75 75 };
76 76 Some(ImageRef {
77 77 id: emoji.object_id.to_owned(),
78 url: emoji.image_url(),
78 url: crate::demo::org_emoji_image_url(&emoji.object_id).unwrap_or_else(|| emoji.image_url()),
79 79 width: None,
80 80 height: None,
81 81 alt: Some(emoji.name.to_owned()),
@@ -75,7 +75,7 @@ pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {
75 };
75 };
76 Some(ImageRef {
76 Some(ImageRef {
77 id: emoji.object_id.to_owned(),
77 id: emoji.object_id.to_owned(),
78 url: emoji.image_url(),
78 url: crate::demo::org_emoji_image_url(&emoji.object_id).unwrap_or_else(|| emoji.image_url()),
79 width: None,
79 width: None,
80 height: None,
80 height: None,
81 alt: Some(emoji.name.to_owned()),
81 alt: Some(emoji.name.to_owned()),
crates/app-state/src/stored_outgoing.rs +19 −1
@@ -25,6 +25,7 @@ enum StoredObject {
25 25 Inline,
26 26 Gif(StoredRemote),
27 27 Sticker(StoredRemote),
28 CustomEmoji(StoredRemote),
28 29 }
29 30
30 31 #[derive(Serialize, Deserialize)]
@@ -33,6 +34,8 @@ struct StoredRemote {
33 34 title: String,
34 35 width: u32,
35 36 height: u32,
37 #[serde(default)]
38 object_id: Option<String>,
36 39 }
37 40
38 41 #[derive(Serialize, Deserialize)]
@@ -87,10 +90,15 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
87 90 title: remote.title.clone(),
88 91 width: remote.width,
89 92 height: remote.height,
93 object_id: match &remote.kind {
94 RemoteKind::CustomEmoji { object_id } => Some(object_id.clone()),
95 _ => None,
96 },
90 97 };
91 objects.push(match remote.kind {
98 objects.push(match &remote.kind {
92 99 RemoteKind::Gif => StoredObject::Gif(stored),
93 100 RemoteKind::Sticker => StoredObject::Sticker(stored),
101 RemoteKind::CustomEmoji { .. } => StoredObject::CustomEmoji(stored),
94 102 });
95 103 }
96 104 }
@@ -129,6 +137,12 @@ fn inline_image(stored: &AttachmentImage) -> Option<OutgoingImage> {
129 137 }
130 138
131 139 fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {
140 let kind = match kind {
141 RemoteKind::CustomEmoji { .. } => RemoteKind::CustomEmoji {
142 object_id: stored.object_id.unwrap_or_default(),
143 },
144 other => other,
145 };
132 146 OutgoingImage::Remote(RemoteImage {
133 147 kind,
134 148 url: stored.url,
@@ -157,6 +171,10 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
157 171 StoredObject::Inline => inline.next().and_then(inline_image),
158 172 StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)),
159 173 StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)),
174 StoredObject::CustomEmoji(stored) => {
175 let object_id = stored.object_id.clone().unwrap_or_default();
176 Some(remote_image(RemoteKind::CustomEmoji { object_id }, stored))
177 }
160 178 })
161 179 .collect();
162 180 Some(Outgoing {
@@ -25,6 +25,7 @@ enum StoredObject {
25 Inline,
25 Inline,
26 Gif(StoredRemote),
26 Gif(StoredRemote),
27 Sticker(StoredRemote),
27 Sticker(StoredRemote),
28 CustomEmoji(StoredRemote),
28}
29}
29
30
30#[derive(Serialize, Deserialize)]
31#[derive(Serialize, Deserialize)]
@@ -33,6 +34,8 @@ struct StoredRemote {
33 title: String,
34 title: String,
34 width: u32,
35 width: u32,
35 height: u32,
36 height: u32,
37 #[serde(default)]
38 object_id: Option<String>,
36}
39}
37
40
38#[derive(Serialize, Deserialize)]
41#[derive(Serialize, Deserialize)]
@@ -87,10 +90,15 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
87 title: remote.title.clone(),
90 title: remote.title.clone(),
88 width: remote.width,
91 width: remote.width,
89 height: remote.height,
92 height: remote.height,
93 object_id: match &remote.kind {
94 RemoteKind::CustomEmoji { object_id } => Some(object_id.clone()),
95 _ => None,
96 },
90 };
97 };
91 objects.push(match remote.kind {
98 objects.push(match &remote.kind {
92 RemoteKind::Gif => StoredObject::Gif(stored),
99 RemoteKind::Gif => StoredObject::Gif(stored),
93 RemoteKind::Sticker => StoredObject::Sticker(stored),
100 RemoteKind::Sticker => StoredObject::Sticker(stored),
101 RemoteKind::CustomEmoji { .. } => StoredObject::CustomEmoji(stored),
94 });
102 });
95 }
103 }
96 }
104 }
@@ -129,6 +137,12 @@ fn inline_image(stored: &AttachmentImage) -> Option<OutgoingImage> {
129}
137}
130
138
131fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {
139fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {
140 let kind = match kind {
141 RemoteKind::CustomEmoji { .. } => RemoteKind::CustomEmoji {
142 object_id: stored.object_id.unwrap_or_default(),
143 },
144 other => other,
145 };
132 OutgoingImage::Remote(RemoteImage {
146 OutgoingImage::Remote(RemoteImage {
133 kind,
147 kind,
134 url: stored.url,
148 url: stored.url,
@@ -157,6 +171,10 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
157 StoredObject::Inline => inline.next().and_then(inline_image),
171 StoredObject::Inline => inline.next().and_then(inline_image),
158 StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)),
172 StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)),
159 StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)),
173 StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)),
174 StoredObject::CustomEmoji(stored) => {
175 let object_id = stored.object_id.clone().unwrap_or_default();
176 Some(remote_image(RemoteKind::CustomEmoji { object_id }, stored))
177 }
160 })
178 })
161 .collect();
179 .collect();
162 Some(Outgoing {
180 Some(Outgoing {
crates/app-ui-kit/src/render/blocks.rs +3 −1
@@ -4,7 +4,9 @@ use teams_core::{FontSize, PROFILE_LINK_PREFIX, Span};
4 4
5 5 pub const IMAGE_PLACEHOLDER: &str = "[image]";
6 6 pub const CODE_PADDING: &str = "\u{2004}";
7 pub const EMOJI_PLACEHOLDER: &str = "\u{25a0}\u{25a0}";
7 // Invisible width reservation. Black squares stay visible as dark bars
8 // beside the overlaid image when a color font or missed highlight paints them.
9 pub const EMOJI_PLACEHOLDER: &str = "\u{2003}\u{2003}";
8 10 const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
9 11 const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
10 12 const BASE_FONT_PIXELS: f32 = 14.;
@@ -4,7 +4,9 @@ use teams_core::{FontSize, PROFILE_LINK_PREFIX, Span};
4
4
5pub const IMAGE_PLACEHOLDER: &str = "[image]";
5pub const IMAGE_PLACEHOLDER: &str = "[image]";
6pub const CODE_PADDING: &str = "\u{2004}";
6pub const CODE_PADDING: &str = "\u{2004}";
7pub const EMOJI_PLACEHOLDER: &str = "\u{25a0}\u{25a0}";
7// Invisible width reservation. Black squares stay visible as dark bars
8// beside the overlaid image when a color font or missed highlight paints them.
9pub const EMOJI_PLACEHOLDER: &str = "\u{2003}\u{2003}";
8const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
10const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
9const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
11const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
10const BASE_FONT_PIXELS: f32 = 14.;
12const BASE_FONT_PIXELS: f32 = 14.;
crates/app-ui-kit/src/render/elements.rs +5 −12
@@ -452,13 +452,6 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
452 452 .into_iter()
453 453 .map(|range| (range, emoji_family.clone())),
454 454 )
455 .chain(
456 inline
457 .segments
458 .iter()
459 .filter(|segment| segment.emoji.is_some())
460 .map(|segment| (segment.range.clone(), emoji_family.clone())),
461 )
462 455 .collect();
463 456 font_overrides.sort_by_key(|(range, _)| range.start);
464 457 let keycaps = keycap_ranges(&inline.text);
@@ -501,11 +494,11 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
501 494 },
502 495 None => highlight_for(segment.style, own),
503 496 },
504 family: if segment.emoji.is_some() {
505 Some(SharedString::from(theme::EMOJI_FONT_FAMILY))
506 } else {
507 segment.style.code.then(|| mono.clone())
508 },
497 family: segment
498 .style
499 .code
500 .then(|| mono.clone())
501 .filter(|_| segment.emoji.is_none()),
509 502 scale: segment.style.font_scale(),
510 503 raise: segment.style.baseline_raise(),
511 504 })
@@ -452,13 +452,6 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
452 .into_iter()
452 .into_iter()
453 .map(|range| (range, emoji_family.clone())),
453 .map(|range| (range, emoji_family.clone())),
454 )
454 )
455 .chain(
456 inline
457 .segments
458 .iter()
459 .filter(|segment| segment.emoji.is_some())
460 .map(|segment| (segment.range.clone(), emoji_family.clone())),
461 )
462 .collect();
455 .collect();
463 font_overrides.sort_by_key(|(range, _)| range.start);
456 font_overrides.sort_by_key(|(range, _)| range.start);
464 let keycaps = keycap_ranges(&inline.text);
457 let keycaps = keycap_ranges(&inline.text);
@@ -501,11 +494,11 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
501 },
494 },
502 None => highlight_for(segment.style, own),
495 None => highlight_for(segment.style, own),
503 },
496 },
504 family: if segment.emoji.is_some() {
497 family: segment
505 Some(SharedString::from(theme::EMOJI_FONT_FAMILY))
498 .style
506 } else {
499 .code
507 segment.style.code.then(|| mono.clone())
500 .then(|| mono.clone())
508 },
501 .filter(|_| segment.emoji.is_none()),
509 scale: segment.style.font_scale(),
502 scale: segment.style.font_scale(),
510 raise: segment.style.baseline_raise(),
503 raise: segment.style.baseline_raise(),
511 })
504 })
crates/app/src/views/attachment_tray.rs +36 −3
@@ -174,6 +174,19 @@ impl ItemKind {
174 174 fn is_object(&self) -> bool {
175 175 matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))
176 176 }
177
178 fn is_custom_emoji(&self) -> bool {
179 matches!(self, ItemKind::Remote(remote) if remote.is_custom_emoji())
180 }
181 }
182
183 impl AttachmentTray {
184 pub fn attachment_count(&self) -> usize {
185 self.items
186 .iter()
187 .filter(|item| !item.kind.is_custom_emoji())
188 .count()
189 }
177 190 }
178 191
179 192 impl TrayItem {
@@ -269,7 +282,7 @@ impl AttachmentTray {
269 282 /// `None` when the tray is full.
270 283 pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {
271 284 self.notice = None;
272 if self.items.len() >= MAX_ATTACHMENTS {
285 if !remote.is_custom_emoji() && self.attachment_count() >= MAX_ATTACHMENTS {
273 286 self.notice = Some(limit_notice(1));
274 287 return None;
275 288 }
@@ -303,7 +316,7 @@ impl AttachmentTray {
303 316 reference: FileReference,
304 317 ) -> Option<u64> {
305 318 self.notice = None;
306 if self.items.len() >= MAX_ATTACHMENTS {
319 if self.attachment_count() >= MAX_ATTACHMENTS {
307 320 self.notice = Some(limit_notice(1));
308 321 return None;
309 322 }
@@ -327,7 +340,7 @@ impl AttachmentTray {
327 340 self.notice = None;
328 341 let accepted = names
329 342 .len()
330 .min(MAX_ATTACHMENTS.saturating_sub(self.items.len()));
343 .min(MAX_ATTACHMENTS.saturating_sub(self.attachment_count()));
331 344 let ids = names[..accepted]
332 345 .iter()
333 346 .map(|name| self.push(name.clone(), 0, ItemKind::Reading))
@@ -1476,6 +1489,26 @@ mod tests {
1476 1489 assert!(tray.notice().is_some());
1477 1490 }
1478 1491
1492 fn org_emoji() -> RemoteImage {
1493 RemoteImage::custom_emoji(&teams_core::OrgEmoji {
1494 id: "em-1".into(),
1495 document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
1496 name: "ship-it".into(),
1497 keywords: vec![],
1498 source: None,
1499 })
1500 }
1501
1502 #[test]
1503 fn a_full_tray_still_accepts_a_custom_emoji() {
1504 let mut tray = AttachmentTray::default();
1505 for _ in 0..MAX_ATTACHMENTS {
1506 assert!(tray.add_remote(gif("Wave")).is_some());
1507 }
1508 assert!(tray.add_remote(org_emoji()).is_some());
1509 assert!(tray.add_remote(gif("Wave")).is_none());
1510 }
1511
1479 1512 #[test]
1480 1513 fn images_come_back_in_the_order_asked_for_and_only_when_known() {
1481 1514 let mut tray = AttachmentTray::default();
@@ -174,6 +174,19 @@ impl ItemKind {
174 fn is_object(&self) -> bool {
174 fn is_object(&self) -> bool {
175 matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))
175 matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))
176 }
176 }
177
178 fn is_custom_emoji(&self) -> bool {
179 matches!(self, ItemKind::Remote(remote) if remote.is_custom_emoji())
180 }
181}
182
183impl AttachmentTray {
184 pub fn attachment_count(&self) -> usize {
185 self.items
186 .iter()
187 .filter(|item| !item.kind.is_custom_emoji())
188 .count()
189 }
177}
190}
178
191
179impl TrayItem {
192impl TrayItem {
@@ -269,7 +282,7 @@ impl AttachmentTray {
269 /// `None` when the tray is full.
282 /// `None` when the tray is full.
270 pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {
283 pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {
271 self.notice = None;
284 self.notice = None;
272 if self.items.len() >= MAX_ATTACHMENTS {
285 if !remote.is_custom_emoji() && self.attachment_count() >= MAX_ATTACHMENTS {
273 self.notice = Some(limit_notice(1));
286 self.notice = Some(limit_notice(1));
274 return None;
287 return None;
275 }
288 }
@@ -303,7 +316,7 @@ impl AttachmentTray {
303 reference: FileReference,
316 reference: FileReference,
304 ) -> Option<u64> {
317 ) -> Option<u64> {
305 self.notice = None;
318 self.notice = None;
306 if self.items.len() >= MAX_ATTACHMENTS {
319 if self.attachment_count() >= MAX_ATTACHMENTS {
307 self.notice = Some(limit_notice(1));
320 self.notice = Some(limit_notice(1));
308 return None;
321 return None;
309 }
322 }
@@ -327,7 +340,7 @@ impl AttachmentTray {
327 self.notice = None;
340 self.notice = None;
328 let accepted = names
341 let accepted = names
329 .len()
342 .len()
330 .min(MAX_ATTACHMENTS.saturating_sub(self.items.len()));
343 .min(MAX_ATTACHMENTS.saturating_sub(self.attachment_count()));
331 let ids = names[..accepted]
344 let ids = names[..accepted]
332 .iter()
345 .iter()
333 .map(|name| self.push(name.clone(), 0, ItemKind::Reading))
346 .map(|name| self.push(name.clone(), 0, ItemKind::Reading))
@@ -1476,6 +1489,26 @@ mod tests {
1476 assert!(tray.notice().is_some());
1489 assert!(tray.notice().is_some());
1477 }
1490 }
1478
1491
1492 fn org_emoji() -> RemoteImage {
1493 RemoteImage::custom_emoji(&teams_core::OrgEmoji {
1494 id: "em-1".into(),
1495 document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
1496 name: "ship-it".into(),
1497 keywords: vec![],
1498 source: None,
1499 })
1500 }
1501
1502 #[test]
1503 fn a_full_tray_still_accepts_a_custom_emoji() {
1504 let mut tray = AttachmentTray::default();
1505 for _ in 0..MAX_ATTACHMENTS {
1506 assert!(tray.add_remote(gif("Wave")).is_some());
1507 }
1508 assert!(tray.add_remote(org_emoji()).is_some());
1509 assert!(tray.add_remote(gif("Wave")).is_none());
1510 }
1511
1479 #[test]
1512 #[test]
1480 fn images_come_back_in_the_order_asked_for_and_only_when_known() {
1513 fn images_come_back_in_the_order_asked_for_and_only_when_known() {
1481 let mut tray = AttachmentTray::default();
1514 let mut tray = AttachmentTray::default();
crates/app/src/views/composer.rs +4 −2
@@ -2120,7 +2120,7 @@ impl Composer {
2120 2120
2121 2121 /// Images that no longer sit in the text give way to new attachments.
2122 2122 fn make_room(&mut self, needed: usize, cx: &App) {
2123 if self.tray.items().len() + needed > MAX_ATTACHMENTS {
2123 if self.tray.attachment_count() + needed > MAX_ATTACHMENTS {
2124 2124 let referenced: Vec<u64> = self
2125 2125 .input
2126 2126 .read(cx)
@@ -2187,7 +2187,9 @@ impl Composer {
2187 2187 window: &mut Window,
2188 2188 cx: &mut Context<Self>,
2189 2189 ) {
2190 self.make_room(1, cx);
2190 if !image.is_custom_emoji() {
2191 self.make_room(1, cx);
2192 }
2191 2193 if let Some(id) = self.tray.add_remote(image) {
2192 2194 self.insert_image_token(id, window, cx);
2193 2195 }
@@ -2120,7 +2120,7 @@ impl Composer {
2120
2120
2121 /// Images that no longer sit in the text give way to new attachments.
2121 /// Images that no longer sit in the text give way to new attachments.
2122 fn make_room(&mut self, needed: usize, cx: &App) {
2122 fn make_room(&mut self, needed: usize, cx: &App) {
2123 if self.tray.items().len() + needed > MAX_ATTACHMENTS {
2123 if self.tray.attachment_count() + needed > MAX_ATTACHMENTS {
2124 let referenced: Vec<u64> = self
2124 let referenced: Vec<u64> = self
2125 .input
2125 .input
2126 .read(cx)
2126 .read(cx)
@@ -2187,7 +2187,9 @@ impl Composer {
2187 window: &mut Window,
2187 window: &mut Window,
2188 cx: &mut Context<Self>,
2188 cx: &mut Context<Self>,
2189 ) {
2189 ) {
2190 self.make_room(1, cx);
2190 if !image.is_custom_emoji() {
2191 self.make_room(1, cx);
2192 }
2191 if let Some(id) = self.tray.add_remote(image) {
2193 if let Some(id) = self.tray.add_remote(image) {
2192 self.insert_image_token(id, window, cx);
2194 self.insert_image_token(id, window, cx);
2193 }
2195 }
crates/app/src/views/fun_picker.rs +211 −17
@@ -11,13 +11,17 @@ use gpui_kit::component::{
11 11 };
12 12 use gpui_kit::prelude::FluentBuilder as _;
13 13 use gpui_kit::*;
14 use teams_core::Gif;
14 use gpui_kit::component::tooltip::Tooltip;
15 use std::collections::HashMap;
16 use teams_core::{Gif, OrgEmoji};
15 17
16 18 use super::skin_tone_choices::{tone_badge, tone_choices};
17 19 use crate::app_state::AppState;
18 20 use crate::emoji;
19 21 use crate::emoticons;
20 22 use crate::gifs::{self, GifError};
23 use crate::i18n::{tr, tr_args};
24 use crate::org_emojis::{self, OrgEmojiError};
21 25 use crate::remote_image::{RemoteImage, image_source};
22 26 use crate::stickers::{self, Sticker};
23 27 use crate::theme;
@@ -39,6 +43,10 @@ const GIF_MIN_HEIGHT: f32 = 48.;
39 43 const GIF_MAX_HEIGHT: f32 = 200.;
40 44 const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];
41 45 const STICKER_COLUMNS: usize = 4;
46 const ORG_COLUMNS: usize = 8;
47 const ORG_GAP: f32 = 4.;
48 const ORG_CELL: f32 =
49 (CONTENT_WIDTH - ORG_GAP * (ORG_COLUMNS - 1) as f32) / ORG_COLUMNS as f32;
42 50 const STICKER_GAP: f32 = 6.;
43 51 const POPULAR_LABEL: &str = "Beliebt";
44 52 const TILE_RADIUS: f32 = 6.;
@@ -48,16 +56,18 @@ enum Tab {
48 56 Emoji,
49 57 Gif,
50 58 Sticker,
59 Org,
51 60 }
52 61
53 62 impl Tab {
54 const ALL: [Tab; 3] = [Tab::Emoji, Tab::Gif, Tab::Sticker];
63 const ALL: [Tab; 4] = [Tab::Emoji, Tab::Gif, Tab::Sticker, Tab::Org];
55 64
56 65 fn key(self) -> &'static str {
57 66 match self {
58 67 Tab::Emoji => "emoji",
59 68 Tab::Gif => "gif",
60 69 Tab::Sticker => "sticker",
70 Tab::Org => "org",
61 71 }
62 72 }
63 73
@@ -65,20 +75,38 @@ impl Tab {
65 75 Tab::ALL.into_iter().find(|tab| tab.key() == key)
66 76 }
67 77
68 fn label(self) -> &'static str {
69 match self {
70 Tab::Emoji => "Emoji",
71 Tab::Gif => "GIF",
72 Tab::Sticker => "Sticker",
73 }
78 fn label(self) -> String {
79 tr(match self {
80 Tab::Emoji => "fun_picker.tab.emoji",
81 Tab::Gif => "fun_picker.tab.gif",
82 Tab::Sticker => "fun_picker.tab.sticker",
83 Tab::Org => "fun_picker.tab.org",
84 })
74 85 }
75 86
76 fn placeholder(self) -> &'static str {
77 match self {
78 Tab::Emoji => "Emoji suchen",
79 Tab::Gif => "GIFs suchen",
80 Tab::Sticker => "Sticker suchen",
81 }
87 fn placeholder(self) -> String {
88 tr(match self {
89 Tab::Emoji => "fun_picker.search.emoji",
90 Tab::Gif => "fun_picker.search.gif",
91 Tab::Sticker => "fun_picker.search.sticker",
92 Tab::Org => "fun_picker.search.org",
93 })
94 }
95 }
96
97 enum OrgState {
98 Loading,
99 Ready(Vec<OrgEmoji>),
100 Failed,
101 }
102
103 fn org_empty_message(query: &str) -> String {
104 if query.is_empty() {
105 tr("fun_picker.org.empty")
106 } else {
107 let mut args = HashMap::new();
108 args.insert("query".into(), query.to_owned());
109 tr_args("fun_picker.org.empty_query", &args)
82 110 }
83 111 }
84 112
@@ -122,6 +150,10 @@ pub struct FunPicker {
122 150 chip: StickerChip,
123 151 sticker_rows: Vec<Vec<&'static Sticker>>,
124 152 sticker_scroll: UniformListScrollHandle,
153 org: OrgState,
154 org_generation: u64,
155 org_task: Option<Task<()>>,
156 org_scroll: UniformListScrollHandle,
125 157 _subscription: Subscription,
126 158 }
127 159
@@ -218,6 +250,10 @@ impl FunPicker {
218 250 chip: StickerChip::Popular,
219 251 sticker_rows: sticker_rows("", StickerChip::Popular),
220 252 sticker_scroll: UniformListScrollHandle::new(),
253 org: OrgState::Loading,
254 org_generation: 0,
255 org_task: None,
256 org_scroll: UniformListScrollHandle::new(),
221 257 _subscription: subscription,
222 258 }
223 259 }
@@ -271,6 +307,7 @@ impl FunPicker {
271 307 self.sticker_rows = sticker_rows(&self.query, self.chip);
272 308 self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top);
273 309 }
310 Tab::Org => self.load_org_emojis(cx),
274 311 }
275 312 cx.notify();
276 313 }
@@ -279,7 +316,7 @@ impl FunPicker {
279 316 &mut self,
280 317 input: &Entity<InputState>,
281 318 event: &InputEvent,
282 _: &mut Window,
319 window: &mut Window,
283 320 cx: &mut Context<Self>,
284 321 ) {
285 322 match event {
@@ -299,6 +336,12 @@ impl FunPicker {
299 336 self.pick_emoji(&glyph, cx);
300 337 }
301 338 }
339 InputEvent::PressEnter { .. } if self.tab == Tab::Org => {
340 if let Some(emoji) = self.visible_org_emojis().first().cloned() {
341 let image = RemoteImage::custom_emoji(&emoji);
342 self.pick_image(image, window, cx);
343 }
344 }
302 345 _ => {}
303 346 }
304 347 }
@@ -391,11 +434,11 @@ impl FunPicker {
391 434 div()
392 435 .id(("fun-picker-tab", tab as usize))
393 436 .h(px(32.))
394 .px(px(14.))
437 .px(px(8.))
395 438 .flex()
396 439 .items_center()
397 440 .cursor_pointer()
398 .text_size(px(13.))
441 .text_size(px(12.))
399 442 .font_weight(FontWeight::SEMIBOLD)
400 443 .border_b_2()
401 444 .border_color(if selected {
@@ -729,6 +772,156 @@ impl FunPicker {
729 772 .child(div().flex_1().min_h_0().child(grid))
730 773 .into_any_element()
731 774 }
775
776 fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
777 match &self.org {
778 OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)
779 .into_iter()
780 .cloned()
781 .collect(),
782 _ => Vec::new(),
783 }
784 }
785
786 fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
787 if matches!(self.org, OrgState::Ready(_)) {
788 self.org_scroll.scroll_to_item(0, ScrollStrategy::Top);
789 return;
790 }
791 self.org_generation += 1;
792 let generation = self.org_generation;
793 self.org = OrgState::Loading;
794 let (demo, engine) = {
795 let state = self.app.read(cx);
796 (state.mode.demo, state.engine.clone())
797 };
798 self.org_task = Some(cx.spawn(async move |this, cx| {
799 let outcome = org_emojis::list(engine, demo, false)
800 .await
801 .unwrap_or(Err(OrgEmojiError::Failed));
802 this.update(cx, |this, cx| {
803 if this.org_generation != generation {
804 return;
805 }
806 this.org = match outcome {
807 Ok(emojis) => OrgState::Ready(emojis),
808 Err(_) => OrgState::Failed,
809 };
810 this.org_scroll.scroll_to_item(0, ScrollStrategy::Top);
811 cx.notify();
812 })
813 .ok();
814 }));
815 }
816
817 fn reload_org_emojis(&mut self, cx: &mut Context<Self>) {
818 self.org = OrgState::Loading;
819 self.load_org_emojis(cx);
820 }
821
822 fn org_tile(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
823 let picked = RemoteImage::custom_emoji(emoji);
824 let name = emoji.name.clone();
825 let label = name.clone();
826 v_flex()
827 .id(("fun-picker-org", index))
828 .w(px(ORG_CELL))
829 .flex_none()
830 .items_center()
831 .gap(px(2.))
832 .p(px(2.))
833 .rounded(px(TILE_RADIUS))
834 .cursor_pointer()
835 .hover(|tile| tile.bg(theme::popup_hover()))
836 .child(
837 img(bounded(image_source(&emoji.image_url())))
838 .size(px(ORG_CELL - 8.))
839 .object_fit(ObjectFit::Contain),
840 )
841 .child(
842 div()
843 .w(px(ORG_CELL))
844 .overflow_hidden()
845 .text_ellipsis()
846 .text_center()
847 .text_size(px(9.))
848 .text_color(theme::text_muted())
849 .child(label),
850 )
851 .tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
852 .on_click(cx.listener(move |this, _, window, cx| {
853 this.pick_image(picked.clone(), window, cx)
854 }))
855 .into_any_element()
856 }
857
858 fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
859 match &self.org {
860 OrgState::Loading => Self::message(String::new())
861 .child(
862 div()
863 .size_full()
864 .flex()
865 .items_center()
866 .justify_center()
867 .text_color(theme::text_muted())
868 .child("…"),
869 )
870 .into_any_element(),
871 OrgState::Failed => Self::message(tr("fun_picker.org.failed"))
872 .child(
873 div()
874 .id("fun-picker-org-retry")
875 .h(px(28.))
876 .px(px(12.))
877 .flex()
878 .items_center()
879 .rounded(px(6.))
880 .bg(theme::popup_hover())
881 .text_color(theme::text())
882 .cursor_pointer()
883 .hover(|button| button.bg(theme::border_strong()))
884 .child(tr("fun_picker.org.retry"))
885 .on_click(cx.listener(|this, _, _, cx| this.reload_org_emojis(cx))),
886 )
887 .into_any_element(),
888 OrgState::Ready(emojis) => {
889 let visible = org_emojis::filter(emojis.as_slice(), &self.query);
890 if visible.is_empty() {
891 return Self::message(org_empty_message(&self.query)).into_any_element();
892 }
893 let rows: Vec<Vec<OrgEmoji>> = visible
894 .into_iter()
895 .cloned()
896 .collect::<Vec<_>>()
897 .chunks(ORG_COLUMNS)
898 .map(|chunk| chunk.to_vec())
899 .collect();
900 uniform_list(
901 "fun-picker-org-list",
902 rows.len(),
903 cx.processor(move |this, range: std::ops::Range<usize>, _, cx| {
904 range
905 .map(|index| {
906 let tiles = rows[index].iter().enumerate().map(|(column, emoji)| {
907 this.org_tile(emoji, index * ORG_COLUMNS + column, cx)
908 });
909 h_flex()
910 .h(px(ORG_CELL + 16. + ORG_GAP))
911 .gap(px(ORG_GAP))
912 .children(tiles)
913 .into_any_element()
914 })
915 .collect::<Vec<_>>()
916 }),
917 )
918 .track_scroll(&self.org_scroll)
919 .size_full()
920 .into_any_element()
921 }
922 }
923 }
924
732 925 }
733 926
734 927 impl Render for FunPicker {
@@ -738,6 +931,7 @@ impl Render for FunPicker {
738 931 Tab::Emoji => self.render_emoji(cx),
739 932 Tab::Gif => self.render_gifs(cx),
740 933 Tab::Sticker => self.render_stickers(cx),
934 Tab::Org => self.render_org(cx),
741 935 };
742 936 v_flex()
743 937 .w(px(WIDTH))
@@ -11,13 +11,17 @@ use gpui_kit::component::{
11};
11};
12use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::prelude::FluentBuilder as _;
13use gpui_kit::*;
13use gpui_kit::*;
14use teams_core::Gif;
14use gpui_kit::component::tooltip::Tooltip;
15use std::collections::HashMap;
16use teams_core::{Gif, OrgEmoji};
15
17
16use super::skin_tone_choices::{tone_badge, tone_choices};
18use super::skin_tone_choices::{tone_badge, tone_choices};
17use crate::app_state::AppState;
19use crate::app_state::AppState;
18use crate::emoji;
20use crate::emoji;
19use crate::emoticons;
21use crate::emoticons;
20use crate::gifs::{self, GifError};
22use crate::gifs::{self, GifError};
23use crate::i18n::{tr, tr_args};
24use crate::org_emojis::{self, OrgEmojiError};
21use crate::remote_image::{RemoteImage, image_source};
25use crate::remote_image::{RemoteImage, image_source};
22use crate::stickers::{self, Sticker};
26use crate::stickers::{self, Sticker};
23use crate::theme;
27use crate::theme;
@@ -39,6 +43,10 @@ const GIF_MIN_HEIGHT: f32 = 48.;
39const GIF_MAX_HEIGHT: f32 = 200.;
43const GIF_MAX_HEIGHT: f32 = 200.;
40const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];
44const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];
41const STICKER_COLUMNS: usize = 4;
45const STICKER_COLUMNS: usize = 4;
46const ORG_COLUMNS: usize = 8;
47const ORG_GAP: f32 = 4.;
48const ORG_CELL: f32 =
49 (CONTENT_WIDTH - ORG_GAP * (ORG_COLUMNS - 1) as f32) / ORG_COLUMNS as f32;
42const STICKER_GAP: f32 = 6.;
50const STICKER_GAP: f32 = 6.;
43const POPULAR_LABEL: &str = "Beliebt";
51const POPULAR_LABEL: &str = "Beliebt";
44const TILE_RADIUS: f32 = 6.;
52const TILE_RADIUS: f32 = 6.;
@@ -48,16 +56,18 @@ enum Tab {
48 Emoji,
56 Emoji,
49 Gif,
57 Gif,
50 Sticker,
58 Sticker,
59 Org,
51}
60}
52
61
53impl Tab {
62impl Tab {
54 const ALL: [Tab; 3] = [Tab::Emoji, Tab::Gif, Tab::Sticker];
63 const ALL: [Tab; 4] = [Tab::Emoji, Tab::Gif, Tab::Sticker, Tab::Org];
55
64
56 fn key(self) -> &'static str {
65 fn key(self) -> &'static str {
57 match self {
66 match self {
58 Tab::Emoji => "emoji",
67 Tab::Emoji => "emoji",
59 Tab::Gif => "gif",
68 Tab::Gif => "gif",
60 Tab::Sticker => "sticker",
69 Tab::Sticker => "sticker",
70 Tab::Org => "org",
61 }
71 }
62 }
72 }
63
73
@@ -65,20 +75,38 @@ impl Tab {
65 Tab::ALL.into_iter().find(|tab| tab.key() == key)
75 Tab::ALL.into_iter().find(|tab| tab.key() == key)
66 }
76 }
67
77
68 fn label(self) -> &'static str {
78 fn label(self) -> String {
69 match self {
79 tr(match self {
70 Tab::Emoji => "Emoji",
80 Tab::Emoji => "fun_picker.tab.emoji",
71 Tab::Gif => "GIF",
81 Tab::Gif => "fun_picker.tab.gif",
72 Tab::Sticker => "Sticker",
82 Tab::Sticker => "fun_picker.tab.sticker",
73 }
83 Tab::Org => "fun_picker.tab.org",
84 })
74 }
85 }
75
86
76 fn placeholder(self) -> &'static str {
87 fn placeholder(self) -> String {
77 match self {
88 tr(match self {
78 Tab::Emoji => "Emoji suchen",
89 Tab::Emoji => "fun_picker.search.emoji",
79 Tab::Gif => "GIFs suchen",
90 Tab::Gif => "fun_picker.search.gif",
80 Tab::Sticker => "Sticker suchen",
91 Tab::Sticker => "fun_picker.search.sticker",
81 }
92 Tab::Org => "fun_picker.search.org",
93 })
94 }
95}
96
97enum OrgState {
98 Loading,
99 Ready(Vec<OrgEmoji>),
100 Failed,
101}
102
103fn org_empty_message(query: &str) -> String {
104 if query.is_empty() {
105 tr("fun_picker.org.empty")
106 } else {
107 let mut args = HashMap::new();
108 args.insert("query".into(), query.to_owned());
109 tr_args("fun_picker.org.empty_query", &args)
82 }
110 }
83}
111}
84
112
@@ -122,6 +150,10 @@ pub struct FunPicker {
122 chip: StickerChip,
150 chip: StickerChip,
123 sticker_rows: Vec<Vec<&'static Sticker>>,
151 sticker_rows: Vec<Vec<&'static Sticker>>,
124 sticker_scroll: UniformListScrollHandle,
152 sticker_scroll: UniformListScrollHandle,
153 org: OrgState,
154 org_generation: u64,
155 org_task: Option<Task<()>>,
156 org_scroll: UniformListScrollHandle,
125 _subscription: Subscription,
157 _subscription: Subscription,
126}
158}
127
159
@@ -218,6 +250,10 @@ impl FunPicker {
218 chip: StickerChip::Popular,
250 chip: StickerChip::Popular,
219 sticker_rows: sticker_rows("", StickerChip::Popular),
251 sticker_rows: sticker_rows("", StickerChip::Popular),
220 sticker_scroll: UniformListScrollHandle::new(),
252 sticker_scroll: UniformListScrollHandle::new(),
253 org: OrgState::Loading,
254 org_generation: 0,
255 org_task: None,
256 org_scroll: UniformListScrollHandle::new(),
221 _subscription: subscription,
257 _subscription: subscription,
222 }
258 }
223 }
259 }
@@ -271,6 +307,7 @@ impl FunPicker {
271 self.sticker_rows = sticker_rows(&self.query, self.chip);
307 self.sticker_rows = sticker_rows(&self.query, self.chip);
272 self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top);
308 self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top);
273 }
309 }
310 Tab::Org => self.load_org_emojis(cx),
274 }
311 }
275 cx.notify();
312 cx.notify();
276 }
313 }
@@ -279,7 +316,7 @@ impl FunPicker {
279 &mut self,
316 &mut self,
280 input: &Entity<InputState>,
317 input: &Entity<InputState>,
281 event: &InputEvent,
318 event: &InputEvent,
282 _: &mut Window,
319 window: &mut Window,
283 cx: &mut Context<Self>,
320 cx: &mut Context<Self>,
284 ) {
321 ) {
285 match event {
322 match event {
@@ -299,6 +336,12 @@ impl FunPicker {
299 self.pick_emoji(&glyph, cx);
336 self.pick_emoji(&glyph, cx);
300 }
337 }
301 }
338 }
339 InputEvent::PressEnter { .. } if self.tab == Tab::Org => {
340 if let Some(emoji) = self.visible_org_emojis().first().cloned() {
341 let image = RemoteImage::custom_emoji(&emoji);
342 self.pick_image(image, window, cx);
343 }
344 }
302 _ => {}
345 _ => {}
303 }
346 }
304 }
347 }
@@ -391,11 +434,11 @@ impl FunPicker {
391 div()
434 div()
392 .id(("fun-picker-tab", tab as usize))
435 .id(("fun-picker-tab", tab as usize))
393 .h(px(32.))
436 .h(px(32.))
394 .px(px(14.))
437 .px(px(8.))
395 .flex()
438 .flex()
396 .items_center()
439 .items_center()
397 .cursor_pointer()
440 .cursor_pointer()
398 .text_size(px(13.))
441 .text_size(px(12.))
399 .font_weight(FontWeight::SEMIBOLD)
442 .font_weight(FontWeight::SEMIBOLD)
400 .border_b_2()
443 .border_b_2()
401 .border_color(if selected {
444 .border_color(if selected {
@@ -729,6 +772,156 @@ impl FunPicker {
729 .child(div().flex_1().min_h_0().child(grid))
772 .child(div().flex_1().min_h_0().child(grid))
730 .into_any_element()
773 .into_any_element()
731 }
774 }
775
776 fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
777 match &self.org {
778 OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)
779 .into_iter()
780 .cloned()
781 .collect(),
782 _ => Vec::new(),
783 }
784 }
785
786 fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
787 if matches!(self.org, OrgState::Ready(_)) {
788 self.org_scroll.scroll_to_item(0, ScrollStrategy::Top);
789 return;
790 }
791 self.org_generation += 1;
792 let generation = self.org_generation;
793 self.org = OrgState::Loading;
794 let (demo, engine) = {
795 let state = self.app.read(cx);
796 (state.mode.demo, state.engine.clone())
797 };
798 self.org_task = Some(cx.spawn(async move |this, cx| {
799 let outcome = org_emojis::list(engine, demo, false)
800 .await
801 .unwrap_or(Err(OrgEmojiError::Failed));
802 this.update(cx, |this, cx| {
803 if this.org_generation != generation {
804 return;
805 }
806 this.org = match outcome {
807 Ok(emojis) => OrgState::Ready(emojis),
808 Err(_) => OrgState::Failed,
809 };
810 this.org_scroll.scroll_to_item(0, ScrollStrategy::Top);
811 cx.notify();
812 })
813 .ok();
814 }));
815 }
816
817 fn reload_org_emojis(&mut self, cx: &mut Context<Self>) {
818 self.org = OrgState::Loading;
819 self.load_org_emojis(cx);
820 }
821
822 fn org_tile(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
823 let picked = RemoteImage::custom_emoji(emoji);
824 let name = emoji.name.clone();
825 let label = name.clone();
826 v_flex()
827 .id(("fun-picker-org", index))
828 .w(px(ORG_CELL))
829 .flex_none()
830 .items_center()
831 .gap(px(2.))
832 .p(px(2.))
833 .rounded(px(TILE_RADIUS))
834 .cursor_pointer()
835 .hover(|tile| tile.bg(theme::popup_hover()))
836 .child(
837 img(bounded(image_source(&emoji.image_url())))
838 .size(px(ORG_CELL - 8.))
839 .object_fit(ObjectFit::Contain),
840 )
841 .child(
842 div()
843 .w(px(ORG_CELL))
844 .overflow_hidden()
845 .text_ellipsis()
846 .text_center()
847 .text_size(px(9.))
848 .text_color(theme::text_muted())
849 .child(label),
850 )
851 .tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
852 .on_click(cx.listener(move |this, _, window, cx| {
853 this.pick_image(picked.clone(), window, cx)
854 }))
855 .into_any_element()
856 }
857
858 fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
859 match &self.org {
860 OrgState::Loading => Self::message(String::new())
861 .child(
862 div()
863 .size_full()
864 .flex()
865 .items_center()
866 .justify_center()
867 .text_color(theme::text_muted())
868 .child("…"),
869 )
870 .into_any_element(),
871 OrgState::Failed => Self::message(tr("fun_picker.org.failed"))
872 .child(
873 div()
874 .id("fun-picker-org-retry")
875 .h(px(28.))
876 .px(px(12.))
877 .flex()
878 .items_center()
879 .rounded(px(6.))
880 .bg(theme::popup_hover())
881 .text_color(theme::text())
882 .cursor_pointer()
883 .hover(|button| button.bg(theme::border_strong()))
884 .child(tr("fun_picker.org.retry"))
885 .on_click(cx.listener(|this, _, _, cx| this.reload_org_emojis(cx))),
886 )
887 .into_any_element(),
888 OrgState::Ready(emojis) => {
889 let visible = org_emojis::filter(emojis.as_slice(), &self.query);
890 if visible.is_empty() {
891 return Self::message(org_empty_message(&self.query)).into_any_element();
892 }
893 let rows: Vec<Vec<OrgEmoji>> = visible
894 .into_iter()
895 .cloned()
896 .collect::<Vec<_>>()
897 .chunks(ORG_COLUMNS)
898 .map(|chunk| chunk.to_vec())
899 .collect();
900 uniform_list(
901 "fun-picker-org-list",
902 rows.len(),
903 cx.processor(move |this, range: std::ops::Range<usize>, _, cx| {
904 range
905 .map(|index| {
906 let tiles = rows[index].iter().enumerate().map(|(column, emoji)| {
907 this.org_tile(emoji, index * ORG_COLUMNS + column, cx)
908 });
909 h_flex()
910 .h(px(ORG_CELL + 16. + ORG_GAP))
911 .gap(px(ORG_GAP))
912 .children(tiles)
913 .into_any_element()
914 })
915 .collect::<Vec<_>>()
916 }),
917 )
918 .track_scroll(&self.org_scroll)
919 .size_full()
920 .into_any_element()
921 }
922 }
923 }
924
732}
925}
733
926
734impl Render for FunPicker {
927impl Render for FunPicker {
@@ -738,6 +931,7 @@ impl Render for FunPicker {
738 Tab::Emoji => self.render_emoji(cx),
931 Tab::Emoji => self.render_emoji(cx),
739 Tab::Gif => self.render_gifs(cx),
932 Tab::Gif => self.render_gifs(cx),
740 Tab::Sticker => self.render_stickers(cx),
933 Tab::Sticker => self.render_stickers(cx),
934 Tab::Org => self.render_org(cx),
741 };
935 };
742 v_flex()
936 v_flex()
743 .w(px(WIDTH))
937 .w(px(WIDTH))
crates/app/src/views/reaction_picker.rs +223 −10
@@ -1,4 +1,4 @@
1 use std::collections::HashSet;
1 use std::collections::{HashMap, HashSet};
2 2 use std::rc::Rc;
3 3
4 4 use gpui_kit::base::PopoverState;
@@ -21,6 +21,11 @@ use crate::emoji;
21 21 use crate::emoticons;
22 22 use crate::rows::reaction_glyph;
23 23 use crate::theme;
24 use crate::i18n::{tr, tr_args};
25 use crate::org_emojis::{self, OrgEmojiError};
26 use crate::remote_image::image_source;
27 use crate::views::image_memory::bounded;
28 use teams_core::OrgEmoji;
24 29
25 30 const PICKER_QUICK: [&str; 6] = [
26 31 "\u{1F44D}",
@@ -52,6 +57,30 @@ const PICKER_WIDTH: f32 = 296.;
52 57 const CELL_SIZE: f32 = 32.;
53 58 const GRID_COLUMNS: usize = 8;
54 59 const GRID_LIMIT: usize = 32;
60 const ORG_COLUMNS: usize = 8;
61
62 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
63 enum Tab {
64 Emoji,
65 Org,
66 }
67
68 enum OrgState {
69 Loading,
70 Ready(Vec<OrgEmoji>),
71 Failed,
72 }
73
74 fn org_empty_message(query: &str) -> String {
75 if query.is_empty() {
76 tr("reaction_picker.org.empty")
77 } else {
78 let mut args = HashMap::new();
79 args.insert("query".into(), query.to_owned());
80 tr_args("reaction_picker.org.empty_query", &args)
81 }
82 }
83
55 84
56 85 pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
57 86 pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;
@@ -73,6 +102,10 @@ pub struct ReactionPicker {
73 102 skin_tone: u8,
74 103 tone_menu: Option<(String, Point<Pixels>)>,
75 104 customizing: bool,
105 tab: Tab,
106 org: OrgState,
107 org_generation: u64,
108 org_task: Option<Task<()>>,
76 109 _subscription: Subscription,
77 110 }
78 111
@@ -95,6 +128,10 @@ impl ReactionPicker {
95 128 skin_tone: 0,
96 129 tone_menu: None,
97 130 customizing: false,
131 tab: Tab::Emoji,
132 org: OrgState::Loading,
133 org_generation: 0,
134 org_task: None,
98 135 _subscription: subscription,
99 136 }
100 137 }
@@ -131,10 +168,15 @@ impl ReactionPicker {
131 168 cx.notify();
132 169 });
133 170 self.query.clear();
171 self.tab = Tab::Emoji;
134 172 self.input.update(cx, |state, cx| {
135 173 state.set_value("", window, cx);
174 state.set_placeholder("Search emoji", window, cx);
136 175 state.focus(window, cx);
137 176 });
177 if !self.customizing {
178 self.load_org_emojis(cx);
179 }
138 180 cx.notify();
139 181 }
140 182
@@ -151,7 +193,12 @@ impl ReactionPicker {
151 193 cx.notify();
152 194 }
153 195 InputEvent::PressEnter { .. } => {
154 if let Some(first) = self.results(cx).first().cloned() {
196 let first = if self.tab == Tab::Org {
197 self.visible_org_emojis().first().map(|emoji| emoji.key())
198 } else {
199 self.results(cx).first().cloned()
200 };
201 if let Some(first) = first {
155 202 self.pick(&first, false, window, cx);
156 203 }
157 204 }
@@ -315,6 +362,154 @@ impl ReactionPicker {
315 362 this.pick(&picked, event.modifiers().shift, window, cx)
316 363 }))
317 364 }
365
366 fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
367 match &self.org {
368 OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)
369 .into_iter()
370 .cloned()
371 .collect(),
372 _ => Vec::new(),
373 }
374 }
375
376 fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
377 if tab == self.tab {
378 return;
379 }
380 self.tab = tab;
381 let placeholder = if tab == Tab::Org {
382 tr("reaction_picker.search.org")
383 } else {
384 "Search emoji".to_owned()
385 };
386 self.input.update(cx, |state, cx| {
387 state.set_placeholder(placeholder, window, cx);
388 state.focus(window, cx);
389 });
390 if tab == Tab::Org {
391 self.load_org_emojis(cx);
392 }
393 cx.notify();
394 }
395
396 fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
397 if matches!(self.org, OrgState::Ready(_)) {
398 return;
399 }
400 self.org_generation += 1;
401 let generation = self.org_generation;
402 self.org = OrgState::Loading;
403 let (demo, engine) = {
404 let state = self.app.read(cx);
405 (state.mode.demo, state.engine.clone())
406 };
407 self.org_task = Some(cx.spawn(async move |this, cx| {
408 let outcome = org_emojis::list(engine, demo, false)
409 .await
410 .unwrap_or(Err(OrgEmojiError::Failed));
411 this.update(cx, |this, cx| {
412 if this.org_generation != generation {
413 return;
414 }
415 this.org = match outcome {
416 Ok(emojis) => OrgState::Ready(emojis),
417 Err(_) => OrgState::Failed,
418 };
419 cx.notify();
420 })
421 .ok();
422 }));
423 }
424
425 fn tab_button(&self, tab: Tab, label_key: &str, cx: &mut Context<Self>) -> Stateful<Div> {
426 let selected = tab == self.tab;
427 div()
428 .id(("reaction-picker-tab", tab as usize))
429 .h(px(26.))
430 .px(px(8.))
431 .flex()
432 .items_center()
433 .cursor_pointer()
434 .text_size(px(12.))
435 .font_weight(FontWeight::SEMIBOLD)
436 .border_b_2()
437 .border_color(if selected {
438 theme::accent()
439 } else {
440 transparent_black()
441 })
442 .text_color(if selected {
443 theme::accent_text()
444 } else {
445 theme::text_muted()
446 })
447 .hover(|button| button.text_color(theme::text_strong()))
448 .child(tr(label_key))
449 .on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
450 }
451
452 fn org_cell(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
453 let key = emoji.key();
454 let name = emoji.name.clone();
455 let selected = self.selected.contains(&key);
456 div()
457 .id(("reaction-picker-org", index))
458 .size(px(CELL_SIZE))
459 .flex_none()
460 .p(px(3.))
461 .rounded(px(6.))
462 .cursor_pointer()
463 .when(selected, |cell| cell.bg(theme::reaction_on_own()))
464 .hover(|cell| cell.bg(theme::popup_hover()))
465 .child(
466 img(bounded(image_source(&emoji.image_url())))
467 .size_full()
468 .object_fit(ObjectFit::Contain),
469 )
470 .tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
471 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
472 this.pick(&key, event.modifiers().shift, window, cx)
473 }))
474 .into_any_element()
475 }
476
477 fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
478 match &self.org {
479 OrgState::Loading => div()
480 .text_size(px(11.))
481 .text_color(theme::text_muted())
482 .child("…")
483 .into_any_element(),
484 OrgState::Failed => div()
485 .text_size(px(11.))
486 .text_color(theme::text_muted())
487 .child(tr("fun_picker.org.failed"))
488 .into_any_element(),
489 OrgState::Ready(_) => {
490 let visible = self.visible_org_emojis();
491 if visible.is_empty() {
492 return div()
493 .text_size(px(11.))
494 .text_color(theme::text_muted())
495 .child(org_empty_message(&self.query))
496 .into_any_element();
497 }
498 let mut rows = Vec::new();
499 let mut row = Vec::new();
500 for (index, emoji) in visible.iter().enumerate() {
501 row.push(self.org_cell(emoji, index, cx));
502 if row.len() == ORG_COLUMNS {
503 rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));
504 }
505 }
506 if !row.is_empty() {
507 rows.push(h_flex().gap(px(2.)).children(row));
508 }
509 v_flex().gap(px(2.)).children(rows).into_any_element()
510 }
511 }
512 }
318 513 }
319 514
320 515 impl Render for ReactionPicker {
@@ -343,11 +538,35 @@ impl Render for ReactionPicker {
343 538 if !row.is_empty() {
344 539 rows.push(h_flex().gap(px(2.)).children(row));
345 540 }
541 let tabs = (!self.customizing).then(|| {
542 h_flex()
543 .flex_none()
544 .gap(px(2.))
545 .child(self.tab_button(Tab::Emoji, "reaction_picker.tab.emoji", cx))
546 .child(self.tab_button(Tab::Org, "reaction_picker.tab.org", cx))
547 });
548 let body = if self.tab == Tab::Org && !self.customizing {
549 self.render_org(cx)
550 } else {
551 v_flex()
552 .gap(px(2.))
553 .child(
554 div()
555 .text_size(px(11.))
556 .text_color(theme::text_muted())
557 .child(label),
558 )
559 .child(v_flex().gap(px(2.)).children(rows))
560 .into_any_element()
561 };
346 562 v_flex()
347 563 .w(px(PICKER_WIDTH))
348 564 .gap(px(8.))
349 565 .p(px(8.))
350 .child(h_flex().gap(px(2.)).children(quick))
566 .children(tabs)
567 .when(self.tab != Tab::Org || self.customizing, |picker| {
568 picker.child(h_flex().gap(px(2.)).children(quick))
569 })
351 570 .child(
352 571 h_flex()
353 572 .gap(px(4.))
@@ -365,13 +584,7 @@ impl Render for ReactionPicker {
365 584 )
366 585 .children(self.customize_button(cx)),
367 586 )
368 .child(
369 div()
370 .text_size(px(11.))
371 .text_color(theme::text_muted())
372 .child(label),
373 )
374 .child(v_flex().gap(px(2.)).children(rows))
587 .child(body)
375 588 .children(self.tone_menu(cx))
376 589 }
377 590 }
@@ -1,4 +1,4 @@
1use std::collections::HashSet;
1use std::collections::{HashMap, HashSet};
2use std::rc::Rc;
2use std::rc::Rc;
3
3
4use gpui_kit::base::PopoverState;
4use gpui_kit::base::PopoverState;
@@ -21,6 +21,11 @@ use crate::emoji;
21use crate::emoticons;
21use crate::emoticons;
22use crate::rows::reaction_glyph;
22use crate::rows::reaction_glyph;
23use crate::theme;
23use crate::theme;
24use crate::i18n::{tr, tr_args};
25use crate::org_emojis::{self, OrgEmojiError};
26use crate::remote_image::image_source;
27use crate::views::image_memory::bounded;
28use teams_core::OrgEmoji;
24
29
25const PICKER_QUICK: [&str; 6] = [
30const PICKER_QUICK: [&str; 6] = [
26 "\u{1F44D}",
31 "\u{1F44D}",
@@ -52,6 +57,30 @@ const PICKER_WIDTH: f32 = 296.;
52const CELL_SIZE: f32 = 32.;
57const CELL_SIZE: f32 = 32.;
53const GRID_COLUMNS: usize = 8;
58const GRID_COLUMNS: usize = 8;
54const GRID_LIMIT: usize = 32;
59const GRID_LIMIT: usize = 32;
60const ORG_COLUMNS: usize = 8;
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63enum Tab {
64 Emoji,
65 Org,
66}
67
68enum OrgState {
69 Loading,
70 Ready(Vec<OrgEmoji>),
71 Failed,
72}
73
74fn org_empty_message(query: &str) -> String {
75 if query.is_empty() {
76 tr("reaction_picker.org.empty")
77 } else {
78 let mut args = HashMap::new();
79 args.insert("query".into(), query.to_owned());
80 tr_args("reaction_picker.org.empty_query", &args)
81 }
82}
83
55
84
56pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
85pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
57pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;
86pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;
@@ -73,6 +102,10 @@ pub struct ReactionPicker {
73 skin_tone: u8,
102 skin_tone: u8,
74 tone_menu: Option<(String, Point<Pixels>)>,
103 tone_menu: Option<(String, Point<Pixels>)>,
75 customizing: bool,
104 customizing: bool,
105 tab: Tab,
106 org: OrgState,
107 org_generation: u64,
108 org_task: Option<Task<()>>,
76 _subscription: Subscription,
109 _subscription: Subscription,
77}
110}
78
111
@@ -95,6 +128,10 @@ impl ReactionPicker {
95 skin_tone: 0,
128 skin_tone: 0,
96 tone_menu: None,
129 tone_menu: None,
97 customizing: false,
130 customizing: false,
131 tab: Tab::Emoji,
132 org: OrgState::Loading,
133 org_generation: 0,
134 org_task: None,
98 _subscription: subscription,
135 _subscription: subscription,
99 }
136 }
100 }
137 }
@@ -131,10 +168,15 @@ impl ReactionPicker {
131 cx.notify();
168 cx.notify();
132 });
169 });
133 self.query.clear();
170 self.query.clear();
171 self.tab = Tab::Emoji;
134 self.input.update(cx, |state, cx| {
172 self.input.update(cx, |state, cx| {
135 state.set_value("", window, cx);
173 state.set_value("", window, cx);
174 state.set_placeholder("Search emoji", window, cx);
136 state.focus(window, cx);
175 state.focus(window, cx);
137 });
176 });
177 if !self.customizing {
178 self.load_org_emojis(cx);
179 }
138 cx.notify();
180 cx.notify();
139 }
181 }
140
182
@@ -151,7 +193,12 @@ impl ReactionPicker {
151 cx.notify();
193 cx.notify();
152 }
194 }
153 InputEvent::PressEnter { .. } => {
195 InputEvent::PressEnter { .. } => {
154 if let Some(first) = self.results(cx).first().cloned() {
196 let first = if self.tab == Tab::Org {
197 self.visible_org_emojis().first().map(|emoji| emoji.key())
198 } else {
199 self.results(cx).first().cloned()
200 };
201 if let Some(first) = first {
155 self.pick(&first, false, window, cx);
202 self.pick(&first, false, window, cx);
156 }
203 }
157 }
204 }
@@ -315,6 +362,154 @@ impl ReactionPicker {
315 this.pick(&picked, event.modifiers().shift, window, cx)
362 this.pick(&picked, event.modifiers().shift, window, cx)
316 }))
363 }))
317 }
364 }
365
366 fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
367 match &self.org {
368 OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)
369 .into_iter()
370 .cloned()
371 .collect(),
372 _ => Vec::new(),
373 }
374 }
375
376 fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
377 if tab == self.tab {
378 return;
379 }
380 self.tab = tab;
381 let placeholder = if tab == Tab::Org {
382 tr("reaction_picker.search.org")
383 } else {
384 "Search emoji".to_owned()
385 };
386 self.input.update(cx, |state, cx| {
387 state.set_placeholder(placeholder, window, cx);
388 state.focus(window, cx);
389 });
390 if tab == Tab::Org {
391 self.load_org_emojis(cx);
392 }
393 cx.notify();
394 }
395
396 fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
397 if matches!(self.org, OrgState::Ready(_)) {
398 return;
399 }
400 self.org_generation += 1;
401 let generation = self.org_generation;
402 self.org = OrgState::Loading;
403 let (demo, engine) = {
404 let state = self.app.read(cx);
405 (state.mode.demo, state.engine.clone())
406 };
407 self.org_task = Some(cx.spawn(async move |this, cx| {
408 let outcome = org_emojis::list(engine, demo, false)
409 .await
410 .unwrap_or(Err(OrgEmojiError::Failed));
411 this.update(cx, |this, cx| {
412 if this.org_generation != generation {
413 return;
414 }
415 this.org = match outcome {
416 Ok(emojis) => OrgState::Ready(emojis),
417 Err(_) => OrgState::Failed,
418 };
419 cx.notify();
420 })
421 .ok();
422 }));
423 }
424
425 fn tab_button(&self, tab: Tab, label_key: &str, cx: &mut Context<Self>) -> Stateful<Div> {
426 let selected = tab == self.tab;
427 div()
428 .id(("reaction-picker-tab", tab as usize))
429 .h(px(26.))
430 .px(px(8.))
431 .flex()
432 .items_center()
433 .cursor_pointer()
434 .text_size(px(12.))
435 .font_weight(FontWeight::SEMIBOLD)
436 .border_b_2()
437 .border_color(if selected {
438 theme::accent()
439 } else {
440 transparent_black()
441 })
442 .text_color(if selected {
443 theme::accent_text()
444 } else {
445 theme::text_muted()
446 })
447 .hover(|button| button.text_color(theme::text_strong()))
448 .child(tr(label_key))
449 .on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
450 }
451
452 fn org_cell(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
453 let key = emoji.key();
454 let name = emoji.name.clone();
455 let selected = self.selected.contains(&key);
456 div()
457 .id(("reaction-picker-org", index))
458 .size(px(CELL_SIZE))
459 .flex_none()
460 .p(px(3.))
461 .rounded(px(6.))
462 .cursor_pointer()
463 .when(selected, |cell| cell.bg(theme::reaction_on_own()))
464 .hover(|cell| cell.bg(theme::popup_hover()))
465 .child(
466 img(bounded(image_source(&emoji.image_url())))
467 .size_full()
468 .object_fit(ObjectFit::Contain),
469 )
470 .tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
471 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
472 this.pick(&key, event.modifiers().shift, window, cx)
473 }))
474 .into_any_element()
475 }
476
477 fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
478 match &self.org {
479 OrgState::Loading => div()
480 .text_size(px(11.))
481 .text_color(theme::text_muted())
482 .child("…")
483 .into_any_element(),
484 OrgState::Failed => div()
485 .text_size(px(11.))
486 .text_color(theme::text_muted())
487 .child(tr("fun_picker.org.failed"))
488 .into_any_element(),
489 OrgState::Ready(_) => {
490 let visible = self.visible_org_emojis();
491 if visible.is_empty() {
492 return div()
493 .text_size(px(11.))
494 .text_color(theme::text_muted())
495 .child(org_empty_message(&self.query))
496 .into_any_element();
497 }
498 let mut rows = Vec::new();
499 let mut row = Vec::new();
500 for (index, emoji) in visible.iter().enumerate() {
501 row.push(self.org_cell(emoji, index, cx));
502 if row.len() == ORG_COLUMNS {
503 rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));
504 }
505 }
506 if !row.is_empty() {
507 rows.push(h_flex().gap(px(2.)).children(row));
508 }
509 v_flex().gap(px(2.)).children(rows).into_any_element()
510 }
511 }
512 }
318}
513}
319
514
320impl Render for ReactionPicker {
515impl Render for ReactionPicker {
@@ -343,11 +538,35 @@ impl Render for ReactionPicker {
343 if !row.is_empty() {
538 if !row.is_empty() {
344 rows.push(h_flex().gap(px(2.)).children(row));
539 rows.push(h_flex().gap(px(2.)).children(row));
345 }
540 }
541 let tabs = (!self.customizing).then(|| {
542 h_flex()
543 .flex_none()
544 .gap(px(2.))
545 .child(self.tab_button(Tab::Emoji, "reaction_picker.tab.emoji", cx))
546 .child(self.tab_button(Tab::Org, "reaction_picker.tab.org", cx))
547 });
548 let body = if self.tab == Tab::Org && !self.customizing {
549 self.render_org(cx)
550 } else {
551 v_flex()
552 .gap(px(2.))
553 .child(
554 div()
555 .text_size(px(11.))
556 .text_color(theme::text_muted())
557 .child(label),
558 )
559 .child(v_flex().gap(px(2.)).children(rows))
560 .into_any_element()
561 };
346 v_flex()
562 v_flex()
347 .w(px(PICKER_WIDTH))
563 .w(px(PICKER_WIDTH))
348 .gap(px(8.))
564 .gap(px(8.))
349 .p(px(8.))
565 .p(px(8.))
350 .child(h_flex().gap(px(2.)).children(quick))
566 .children(tabs)
567 .when(self.tab != Tab::Org || self.customizing, |picker| {
568 picker.child(h_flex().gap(px(2.)).children(quick))
569 })
351 .child(
570 .child(
352 h_flex()
571 h_flex()
353 .gap(px(4.))
572 .gap(px(4.))
@@ -365,13 +584,7 @@ impl Render for ReactionPicker {
365 )
584 )
366 .children(self.customize_button(cx)),
585 .children(self.customize_button(cx)),
367 )
586 )
368 .child(
587 .child(body)
369 div()
370 .text_size(px(11.))
371 .text_color(theme::text_muted())
372 .child(label),
373 )
374 .child(v_flex().gap(px(2.)).children(rows))
375 .children(self.tone_menu(cx))
588 .children(self.tone_menu(cx))
376 }
589 }
377}
590}
crates/chatsvc/src/custom_emojis.rs added +387 −0
@@ -0,0 +1,387 @@
1 use serde::{Deserialize, Serialize};
2 use serde_json::Value;
3 use session::{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 #[serde(default, skip_serializing_if = "Option::is_none")]
28 pub source: Option<String>,
29 }
30
31 impl 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)]
66 pub struct OrgEmojiCatalog {
67 pub emojis: Vec<OrgEmoji>,
68 pub deleted_ids: Vec<String>,
69 pub continuation: Option<String>,
70 }
71
72 pub struct CustomEmojis<T: CsaTransport = SessionTransport> {
73 transport: T,
74 url: String,
75 }
76
77 impl CustomEmojis<SessionTransport> {
78 pub fn new(session: &Session) -> Self {
79 CustomEmojis::with_transport(SessionTransport::new(session), DEFAULT_REGION)
80 }
81 }
82
83 impl<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.
114 pub 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
123 pub 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.
155 pub 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
179 enum ParsedEmoticon {
180 Live(OrgEmoji),
181 Deleted(String),
182 Skip,
183 }
184
185 fn 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
241 fn 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
249 fn escape_attr(value: &str) -> String {
250 value
251 .replace('&', "&amp;")
252 .replace('<', "&lt;")
253 .replace('>', "&gt;")
254 .replace('"', "&quot;")
255 }
256
257 #[cfg(test)]
258 mod tests {
259 use std::sync::Mutex;
260
261 use serde_json::Value;
262 use session::{ApiResponse, Method};
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 }
@@ -0,0 +1,387 @@
1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use session::{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, Method};
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}
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}
crates/core/src/lib.rs +2 −1
@@ -36,6 +36,7 @@ mod folders;
36 36 mod forward_sync;
37 37 mod forwarded;
38 38 mod gifs;
39 mod org_emojis;
39 40 mod hidden_chats;
40 41 mod image_size;
41 42 mod images;
@@ -127,7 +128,7 @@ pub use chatsvc::{
127 128 pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};
128 129 pub use chatsvc::{
129 130 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
130 ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage,
131 ForwardResult, Gif, OrgEmoji, OrgEmojiCatalog, PinnedMessage, custom_emoji_html, PostFollowState, PresenceStatus, SavedMessage,
131 132 ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind,
132 133 WorkLocationSource,
133 134 };
@@ -36,6 +36,7 @@ mod folders;
36mod forward_sync;
36mod forward_sync;
37mod forwarded;
37mod forwarded;
38mod gifs;
38mod gifs;
39mod org_emojis;
39mod hidden_chats;
40mod hidden_chats;
40mod image_size;
41mod image_size;
41mod images;
42mod images;
@@ -127,7 +128,7 @@ pub use chatsvc::{
127pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};
128pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};
128pub use chatsvc::{
129pub use chatsvc::{
129 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
130 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
130 ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage,
131 ForwardResult, Gif, OrgEmoji, OrgEmojiCatalog, PinnedMessage, custom_emoji_html, PostFollowState, PresenceStatus, SavedMessage,
131 ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind,
132 ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind,
132 WorkLocationSource,
133 WorkLocationSource,
133};
134};
crates/core/src/org_emojis.rs added +124 −0
@@ -0,0 +1,124 @@
1 use chrono::{Duration, Utc};
2 use store::Store;
3
4 use chatsvc::{OrgEmoji, OrgEmojiCatalog, merge_catalog};
5
6 use crate::engine::SyncEngine;
7 use crate::error::Result;
8 use crate::remote::Remote;
9
10 pub const META_ORG_EMOJIS: &str = "org_emojis";
11 pub const META_ORG_EMOJIS_AT: &str = "org_emojis_at";
12 const CACHE_TTL: Duration = Duration::minutes(30);
13
14 impl<R: Remote> SyncEngine<R> {
15 /// Fresh catalogue from the store when it is younger than 30 minutes.
16 /// Otherwise a CSA refresh (delta when a continuation token is cached),
17 /// falling back to the stale cache if the network call fails.
18 pub async fn list_org_emojis(&self, force: bool) -> Result<Vec<OrgEmoji>> {
19 let now = Utc::now();
20 if !force {
21 if let Some(fresh) = cached_if_fresh(&self.store, now)? {
22 return Ok(fresh.emojis);
23 }
24 }
25 let previous = load_catalog(&self.store)?.unwrap_or_default();
26 let use_delta = !force
27 && previous
28 .continuation
29 .as_deref()
30 .is_some_and(|token| !token.is_empty());
31 let incoming = if use_delta {
32 match self
33 .remote
34 .list_org_emojis(previous.continuation.as_deref())
35 .await
36 {
37 Ok(page) => page,
38 Err(_) => match self.remote.list_org_emojis(None).await {
39 Ok(page) => page,
40 Err(error) => return stale_or_err(previous, error),
41 },
42 }
43 } else {
44 match self.remote.list_org_emojis(None).await {
45 Ok(page) => page,
46 Err(error) => return stale_or_err(previous, error),
47 }
48 };
49 let merged = merge_catalog(&previous.emojis, incoming, !use_delta);
50 save_catalog(&self.store, &merged, now)?;
51 Ok(merged.emojis)
52 }
53 }
54
55 fn stale_or_err(previous: OrgEmojiCatalog, error: crate::error::Error) -> Result<Vec<OrgEmoji>> {
56 if previous.emojis.is_empty() {
57 Err(error)
58 } else {
59 Ok(previous.emojis)
60 }
61 }
62
63 pub fn cached_if_fresh(store: &Store, now: chrono::DateTime<Utc>) -> Result<Option<OrgEmojiCatalog>> {
64 let Some(cached_at) = store.meta_time(META_ORG_EMOJIS_AT)? else {
65 return Ok(None);
66 };
67 if now.signed_duration_since(cached_at) >= CACHE_TTL {
68 return Ok(None);
69 }
70 load_catalog(store)
71 }
72
73 pub fn load_catalog(store: &Store) -> Result<Option<OrgEmojiCatalog>> {
74 let Some(json) = store.meta(META_ORG_EMOJIS)? else {
75 return Ok(None);
76 };
77 Ok(serde_json::from_str(&json).ok())
78 }
79
80 pub fn save_catalog(
81 store: &Store,
82 catalog: &OrgEmojiCatalog,
83 now: chrono::DateTime<Utc>,
84 ) -> Result<()> {
85 let json = serde_json::to_string(catalog).map_err(|error| crate::error::Error::Folders(error.to_string()))?;
86 store.set_meta(META_ORG_EMOJIS, &json)?;
87 store.set_meta_time(META_ORG_EMOJIS_AT, now)?;
88 Ok(())
89 }
90
91 #[cfg(test)]
92 mod tests {
93 use chatsvc::OrgEmoji;
94 use chrono::TimeZone;
95 use store::Store;
96
97 use super::*;
98
99 fn emoji(id: &str, name: &str) -> OrgEmoji {
100 OrgEmoji {
101 id: id.to_owned(),
102 document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".to_owned(),
103 name: name.to_owned(),
104 keywords: vec![],
105 source: None,
106 }
107 }
108
109 #[test]
110 fn store_returns_a_fresh_catalogue_and_hides_a_stale_one() {
111 let store = Store::open_in_memory().unwrap();
112 let t0 = Utc.with_ymd_and_hms(2026, 5, 3, 12, 0, 0).unwrap();
113 let catalog = OrgEmojiCatalog {
114 emojis: vec![emoji("em-1", "ship-it")],
115 deleted_ids: vec![],
116 continuation: Some("42".into()),
117 };
118 save_catalog(&store, &catalog, t0).unwrap();
119 let fresh = cached_if_fresh(&store, t0 + Duration::minutes(29)).unwrap().unwrap();
120 assert_eq!(fresh.emojis[0].name, "ship-it");
121 assert!(cached_if_fresh(&store, t0 + Duration::minutes(31)).unwrap().is_none());
122 assert_eq!(load_catalog(&store).unwrap().unwrap().continuation.as_deref(), Some("42"));
123 }
124 }
@@ -0,0 +1,124 @@
1use chrono::{Duration, Utc};
2use store::Store;
3
4use chatsvc::{OrgEmoji, OrgEmojiCatalog, merge_catalog};
5
6use crate::engine::SyncEngine;
7use crate::error::Result;
8use crate::remote::Remote;
9
10pub const META_ORG_EMOJIS: &str = "org_emojis";
11pub const META_ORG_EMOJIS_AT: &str = "org_emojis_at";
12const CACHE_TTL: Duration = Duration::minutes(30);
13
14impl<R: Remote> SyncEngine<R> {
15 /// Fresh catalogue from the store when it is younger than 30 minutes.
16 /// Otherwise a CSA refresh (delta when a continuation token is cached),
17 /// falling back to the stale cache if the network call fails.
18 pub async fn list_org_emojis(&self, force: bool) -> Result<Vec<OrgEmoji>> {
19 let now = Utc::now();
20 if !force {
21 if let Some(fresh) = cached_if_fresh(&self.store, now)? {
22 return Ok(fresh.emojis);
23 }
24 }
25 let previous = load_catalog(&self.store)?.unwrap_or_default();
26 let use_delta = !force
27 && previous
28 .continuation
29 .as_deref()
30 .is_some_and(|token| !token.is_empty());
31 let incoming = if use_delta {
32 match self
33 .remote
34 .list_org_emojis(previous.continuation.as_deref())
35 .await
36 {
37 Ok(page) => page,
38 Err(_) => match self.remote.list_org_emojis(None).await {
39 Ok(page) => page,
40 Err(error) => return stale_or_err(previous, error),
41 },
42 }
43 } else {
44 match self.remote.list_org_emojis(None).await {
45 Ok(page) => page,
46 Err(error) => return stale_or_err(previous, error),
47 }
48 };
49 let merged = merge_catalog(&previous.emojis, incoming, !use_delta);
50 save_catalog(&self.store, &merged, now)?;
51 Ok(merged.emojis)
52 }
53}
54
55fn stale_or_err(previous: OrgEmojiCatalog, error: crate::error::Error) -> Result<Vec<OrgEmoji>> {
56 if previous.emojis.is_empty() {
57 Err(error)
58 } else {
59 Ok(previous.emojis)
60 }
61}
62
63pub fn cached_if_fresh(store: &Store, now: chrono::DateTime<Utc>) -> Result<Option<OrgEmojiCatalog>> {
64 let Some(cached_at) = store.meta_time(META_ORG_EMOJIS_AT)? else {
65 return Ok(None);
66 };
67 if now.signed_duration_since(cached_at) >= CACHE_TTL {
68 return Ok(None);
69 }
70 load_catalog(store)
71}
72
73pub fn load_catalog(store: &Store) -> Result<Option<OrgEmojiCatalog>> {
74 let Some(json) = store.meta(META_ORG_EMOJIS)? else {
75 return Ok(None);
76 };
77 Ok(serde_json::from_str(&json).ok())
78}
79
80pub fn save_catalog(
81 store: &Store,
82 catalog: &OrgEmojiCatalog,
83 now: chrono::DateTime<Utc>,
84) -> Result<()> {
85 let json = serde_json::to_string(catalog).map_err(|error| crate::error::Error::Folders(error.to_string()))?;
86 store.set_meta(META_ORG_EMOJIS, &json)?;
87 store.set_meta_time(META_ORG_EMOJIS_AT, now)?;
88 Ok(())
89}
90
91#[cfg(test)]
92mod tests {
93 use chatsvc::OrgEmoji;
94 use chrono::TimeZone;
95 use store::Store;
96
97 use super::*;
98
99 fn emoji(id: &str, name: &str) -> OrgEmoji {
100 OrgEmoji {
101 id: id.to_owned(),
102 document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".to_owned(),
103 name: name.to_owned(),
104 keywords: vec![],
105 source: None,
106 }
107 }
108
109 #[test]
110 fn store_returns_a_fresh_catalogue_and_hides_a_stale_one() {
111 let store = Store::open_in_memory().unwrap();
112 let t0 = Utc.with_ymd_and_hms(2026, 5, 3, 12, 0, 0).unwrap();
113 let catalog = OrgEmojiCatalog {
114 emojis: vec![emoji("em-1", "ship-it")],
115 deleted_ids: vec![],
116 continuation: Some("42".into()),
117 };
118 save_catalog(&store, &catalog, t0).unwrap();
119 let fresh = cached_if_fresh(&store, t0 + Duration::minutes(29)).unwrap().unwrap();
120 assert_eq!(fresh.emojis[0].name, "ship-it");
121 assert!(cached_if_fresh(&store, t0 + Duration::minutes(31)).unwrap().is_none());
122 assert_eq!(load_catalog(&store).unwrap().unwrap().continuation.as_deref(), Some("42"));
123 }
124}
crates/core/src/remote.rs +13 −1
@@ -14,7 +14,7 @@ use chatsvc::{
14 14 use chatsvc::{
15 15 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
16 16 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
17 InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,
17 InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, CustomEmojis, OrgEmojiCatalog,
18 18 MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
19 19 PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus,
20 20 Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote,
@@ -615,6 +615,10 @@ pub trait Remote {
615 615 Err(Error::Unsupported("GIF search"))
616 616 }
617 617
618 async fn list_org_emojis(&self, _continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
619 Err(Error::Unsupported("custom emoji catalogue"))
620 }
621
618 622 async fn server_search_init(
619 623 &self,
620 624 _identity: &SearchIdentity,
@@ -1635,6 +1639,14 @@ impl Remote for Graph {
1635 1639 Ok(Gifs::new(self.session()).search(query).await?)
1636 1640 }
1637 1641
1642 async fn list_org_emojis(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
1643 let client = CustomEmojis::new(self.session());
1644 match continuation.map(str::trim).filter(|token| !token.is_empty()) {
1645 Some(token) => Ok(client.list_since(token).await?),
1646 None => Ok(client.list().await?),
1647 }
1648 }
1649
1638 1650 async fn server_search_init(
1639 1651 &self,
1640 1652 identity: &SearchIdentity,
@@ -14,7 +14,7 @@ use chatsvc::{
14use chatsvc::{
14use chatsvc::{
15 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
15 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
16 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
16 ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
17 InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,
17 InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, CustomEmojis, OrgEmojiCatalog,
18 MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
18 MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
19 PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus,
19 PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus,
20 Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote,
20 Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote,
@@ -615,6 +615,10 @@ pub trait Remote {
615 Err(Error::Unsupported("GIF search"))
615 Err(Error::Unsupported("GIF search"))
616 }
616 }
617
617
618 async fn list_org_emojis(&self, _continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
619 Err(Error::Unsupported("custom emoji catalogue"))
620 }
621
618 async fn server_search_init(
622 async fn server_search_init(
619 &self,
623 &self,
620 _identity: &SearchIdentity,
624 _identity: &SearchIdentity,
@@ -1635,6 +1639,14 @@ impl Remote for Graph {
1635 Ok(Gifs::new(self.session()).search(query).await?)
1639 Ok(Gifs::new(self.session()).search(query).await?)
1636 }
1640 }
1637
1641
1642 async fn list_org_emojis(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
1643 let client = CustomEmojis::new(self.session());
1644 match continuation.map(str::trim).filter(|token| !token.is_empty()) {
1645 Some(token) => Ok(client.list_since(token).await?),
1646 None => Ok(client.list().await?),
1647 }
1648 }
1649
1638 async fn server_search_init(
1650 async fn server_search_init(
1639 &self,
1651 &self,
1640 identity: &SearchIdentity,
1652 identity: &SearchIdentity,
crates/core/src/spans.rs +23 −3
@@ -79,6 +79,7 @@ const BLOCK_ELEMENTS: [&str; 12] = [
79 79 const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
80 80 const LANGUAGE_PREFIX: &str = "language-";
81 81 const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
82 const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";
82 83 const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
83 84 const MAX_HEADING_LEVEL: u8 = 3;
84 85 const MARK_BACKGROUND: u32 = 0xffff00;
@@ -448,9 +449,28 @@ fn push_custom_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {
448 449
449 450 fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {
450 451 let value = element.value();
451 let is_emoji = value
452 .attr("itemtype")
453 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
452 let itemtype = value.attr("itemtype").unwrap_or("");
453 if itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) {
454 let name = value
455 .attr("alt")
456 .or_else(|| {
457 value
458 .attr("itemid")
459 .and_then(|itemid| itemid.split_once(';').map(|(name, _)| name))
460 })
461 .unwrap_or_default()
462 .to_owned();
463 if let Some(source) = value.attr("src").filter(|source| !source.is_empty()) {
464 spans.push(Span::CustomEmoji {
465 name,
466 url: source.to_owned(),
467 });
468 } else if !name.is_empty() {
469 push_text(spans, &format!(":{name}:"));
470 }
471 return;
472 }
473 let is_emoji = itemtype.contains(EMOJI_ITEMTYPE);
454 474 if is_emoji {
455 475 if let Some(alt) = value.attr("alt") {
456 476 push_text(spans, &without_repeated_skin_tone(alt));
@@ -79,6 +79,7 @@ const BLOCK_ELEMENTS: [&str; 12] = [
79const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
79const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
80const LANGUAGE_PREFIX: &str = "language-";
80const LANGUAGE_PREFIX: &str = "language-";
81const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
81const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
82const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";
82const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
83const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
83const MAX_HEADING_LEVEL: u8 = 3;
84const MAX_HEADING_LEVEL: u8 = 3;
84const MARK_BACKGROUND: u32 = 0xffff00;
85const MARK_BACKGROUND: u32 = 0xffff00;
@@ -448,9 +449,28 @@ fn push_custom_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {
448
449
449fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {
450fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {
450 let value = element.value();
451 let value = element.value();
451 let is_emoji = value
452 let itemtype = value.attr("itemtype").unwrap_or("");
452 .attr("itemtype")
453 if itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) {
453 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
454 let name = value
455 .attr("alt")
456 .or_else(|| {
457 value
458 .attr("itemid")
459 .and_then(|itemid| itemid.split_once(';').map(|(name, _)| name))
460 })
461 .unwrap_or_default()
462 .to_owned();
463 if let Some(source) = value.attr("src").filter(|source| !source.is_empty()) {
464 spans.push(Span::CustomEmoji {
465 name,
466 url: source.to_owned(),
467 });
468 } else if !name.is_empty() {
469 push_text(spans, &format!(":{name}:"));
470 }
471 return;
472 }
473 let is_emoji = itemtype.contains(EMOJI_ITEMTYPE);
454 if is_emoji {
474 if is_emoji {
455 if let Some(alt) = value.attr("alt") {
475 if let Some(alt) = value.attr("alt") {
456 push_text(spans, &without_repeated_skin_tone(alt));
476 push_text(spans, &without_repeated_skin_tone(alt));
crates/core/src/stored.rs +8 −2
@@ -16,6 +16,7 @@ use crate::mentions::MentionInput;
16 16 use crate::spans::{Span, html_to_spans};
17 17
18 18 const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
19 const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";
19 20 const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
20 21 const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";
21 22 const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";
@@ -318,6 +319,10 @@ fn inline_reply_quote(record: &MessageRecord) -> Option<QuoteInfo> {
318 319 })
319 320 }
320 321
322 fn is_emoji_itemtype(itemtype: &str) -> bool {
323 itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) || itemtype.contains(EMOJI_ITEMTYPE)
324 }
325
321 326 pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
322 327 if record.deleted {
323 328 return Vec::new();
@@ -336,7 +341,7 @@ pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
336 341 let value = element.value();
337 342 let is_emoji = value
338 343 .attr("itemtype")
339 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
344 .is_some_and(is_emoji_itemtype);
340 345 let src = value.attr("src").filter(|src| !src.is_empty());
341 346 let Some(url) = (match value.name() {
342 347 "img" if !is_emoji => src.map(str::to_owned),
@@ -384,7 +389,7 @@ pub fn edit_preserved(record: &MessageRecord) -> EditPreserved {
384 389 let value = element.value();
385 390 let is_emoji = value
386 391 .attr("itemtype")
387 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
392 .is_some_and(is_emoji_itemtype);
388 393 match value.name() {
389 394 "img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => {
390 395 preserved
@@ -991,6 +996,7 @@ mod tests {
991 996 r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
992 997 r#"<img itemtype="http://schema.skype.com/AMSImage" src="https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo" width="64" height="auto">"#,
993 998 r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
999 r#"<img itemtype="http://schema.skype.com/CustomEmoji" itemid="koffie;0-weu-d1-aaa" src="demo://org-emoji-koffie" alt="koffie" width="20" height="20">"#,
994 1000 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
995 1001 );
996 1002 let found = images(&record(html, "[]"));
@@ -16,6 +16,7 @@ use crate::mentions::MentionInput;
16use crate::spans::{Span, html_to_spans};
16use crate::spans::{Span, html_to_spans};
17
17
18const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
18const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
19const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";
19const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
20const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
20const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";
21const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";
21const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";
22const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";
@@ -318,6 +319,10 @@ fn inline_reply_quote(record: &MessageRecord) -> Option<QuoteInfo> {
318 })
319 })
319}
320}
320
321
322fn is_emoji_itemtype(itemtype: &str) -> bool {
323 itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) || itemtype.contains(EMOJI_ITEMTYPE)
324}
325
321pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
326pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
322 if record.deleted {
327 if record.deleted {
323 return Vec::new();
328 return Vec::new();
@@ -336,7 +341,7 @@ pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
336 let value = element.value();
341 let value = element.value();
337 let is_emoji = value
342 let is_emoji = value
338 .attr("itemtype")
343 .attr("itemtype")
339 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
344 .is_some_and(is_emoji_itemtype);
340 let src = value.attr("src").filter(|src| !src.is_empty());
345 let src = value.attr("src").filter(|src| !src.is_empty());
341 let Some(url) = (match value.name() {
346 let Some(url) = (match value.name() {
342 "img" if !is_emoji => src.map(str::to_owned),
347 "img" if !is_emoji => src.map(str::to_owned),
@@ -384,7 +389,7 @@ pub fn edit_preserved(record: &MessageRecord) -> EditPreserved {
384 let value = element.value();
389 let value = element.value();
385 let is_emoji = value
390 let is_emoji = value
386 .attr("itemtype")
391 .attr("itemtype")
387 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
392 .is_some_and(is_emoji_itemtype);
388 match value.name() {
393 match value.name() {
389 "img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => {
394 "img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => {
390 preserved
395 preserved
@@ -991,6 +996,7 @@ mod tests {
991 r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
996 r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
992 r#"<img itemtype="http://schema.skype.com/AMSImage" src="https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo" width="64" height="auto">"#,
997 r#"<img itemtype="http://schema.skype.com/AMSImage" src="https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo" width="64" height="auto">"#,
993 r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
998 r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
999 r#"<img itemtype="http://schema.skype.com/CustomEmoji" itemid="koffie;0-weu-d1-aaa" src="demo://org-emoji-koffie" alt="koffie" width="20" height="20">"#,
994 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
1000 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
995 );
1001 );
996 let found = images(&record(html, "[]"));
1002 let found = images(&record(html, "[]"));
crates/core/tests/spans.rs +10 −0
@@ -539,4 +539,14 @@ fn org_emoji_keep_their_image_and_name() {
539 539 html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"),
540 540 vec![text(":crying_cat:")]
541 541 );
542 let official = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim";
543 assert_eq!(
544 html_to_spans(&format!(
545 r#"<p><img alt="absolute-cinema" itemid="absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8" itemtype="http://schema.skype.com/CustomEmoji" src="{official}" width="20" height="20"></p>"#
546 )),
547 vec![Span::CustomEmoji {
548 name: "absolute-cinema".to_owned(),
549 url: official.to_owned(),
550 }]
551 );
542 552 }
@@ -539,4 +539,14 @@ fn org_emoji_keep_their_image_and_name() {
539 html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"),
539 html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"),
540 vec![text(":crying_cat:")]
540 vec![text(":crying_cat:")]
541 );
541 );
542 let official = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim";
543 assert_eq!(
544 html_to_spans(&format!(
545 r#"<p><img alt="absolute-cinema" itemid="absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8" itemtype="http://schema.skype.com/CustomEmoji" src="{official}" width="20" height="20"></p>"#
546 )),
547 vec![Span::CustomEmoji {
548 name: "absolute-cinema".to_owned(),
549 url: official.to_owned(),
550 }]
551 );
542}
552}