BlueGit

ict rusty-teams

feat(chats): read and write chats through the Teams chat service, no Outlook tab

- chats, members, messages from chatsvc, CSA and MT, converted to the Graph shape
- send, quote, images (AMS), files, mentions, edit, read/unread, hide via chatsvc
- 1:1 chats by member pair, groups via chatsvc threads
- recap, transcripts and attendance read recording events from chatsvc
- old Graph hostedContents image links resolve to their AMS url
- App::Outlook removed from session, browser and webview; leftover Outlook tabs are closed
- unused Graph chat endpoints and Remote chat write methods removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-13 · 2 weeks ago

Hash
380b92978bcc82b9569281355c2b12755e31a6a7
Parent
f333e333
49 files changed +2923 −1256
Cargo.lock +1 −0
@@ -9201,6 +9201,7 @@ dependencies = [
9201 9201 name = "teams-core"
9202 9202 version = "0.3.0"
9203 9203 dependencies = [
9204 "base64 0.22.1",
9204 9205 "chatsvc",
9205 9206 "chrono",
9206 9207 "futures-util",
@@ -9201,6 +9201,7 @@ dependencies = [
9201name = "teams-core"
9201name = "teams-core"
9202version = "0.3.0"
9202version = "0.3.0"
9203dependencies = [
9203dependencies = [
9204 "base64 0.22.1",
9204 "chatsvc",
9205 "chatsvc",
9205 "chrono",
9206 "chrono",
9206 "futures-util",
9207 "futures-util",
README.md +1 −1
@@ -89,7 +89,7 @@
89 89 | Platform | State |
90 90 |---|---|
91 91 | 🪟 Windows | Main target. Login through an embedded WebView2 |
92 | 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. The app opens an Outlook on the web tab next to Teams when missing (some tenants grant chat scopes only to Outlook). Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Built-in login without Chrome is planned |
92 | 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Built-in login without Chrome is planned |
93 93 | 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
94 94
95 95 The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
@@ -89,7 +89,7 @@
89| Platform | State |
89| Platform | State |
90|---|---|
90|---|---|
91| 🪟 Windows | Main target. Login through an embedded WebView2 |
91| 🪟 Windows | Main target. Login through an embedded WebView2 |
92| 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. The app opens an Outlook on the web tab next to Teams when missing (some tenants grant chat scopes only to Outlook). Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Built-in login without Chrome is planned |
92| 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Built-in login without Chrome is planned |
93| 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
93| 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
94
94
95The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
95The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
crates/browser/src/browser.rs +7 −30
@@ -81,13 +81,8 @@ pub struct Browser {
81 81 inner: Arc<Inner>,
82 82 }
83 83
84 pub(crate) fn start_urls_for(headless: bool) -> Vec<String> {
85 let urls = APPS.iter().map(|app| app.start_url().to_owned());
86 if headless {
87 urls.take(1).collect()
88 } else {
89 urls.collect()
90 }
84 pub(crate) fn start_urls() -> Vec<String> {
85 APPS.iter().map(|app| app.start_url().to_owned()).collect()
91 86 }
92 87
93 88 pub(crate) fn jitter_between(min: Duration, max: Duration, random: u64) -> Duration {
@@ -264,14 +259,9 @@ impl Browser {
264 259 if self.is_visible_managed() && self.is_running().await {
265 260 return Ok(());
266 261 }
267 // Always open Teams alone for login: opening Outlook alongside Teams sends Outlook to
268 // login.microsoftonline.com?prompt=select_account before Teams has an SSO cookie, leaving
269 // that second tab stuck on login even after Teams finishes signing in. Headless mode and
270 // CdpTransport open Outlook silently once Teams is signed in.
271 262 self.inner.wanted.store(true, Ordering::SeqCst);
272 263 self.stop_locked(false).await?;
273 self.launch_with_urls_locked(false, start_urls_for(true))
274 .await
264 self.launch_with_urls_locked(false, start_urls()).await
275 265 }
276 266
277 267 pub async fn headless(&self) -> Result<(), BrowserError> {
@@ -361,7 +351,7 @@ impl Browser {
361 351 )
362 352 .await?;
363 353 let attached = targets::attached_target_ids(&result);
364 for id in targets::duplicate_app_tab_ids(&tabs, &attached) {
354 for id in targets::closable_tab_ids(&tabs, &attached) {
365 355 let path = format!("/json/close/{id}");
366 356 http::request(self.inner.config.port, "GET", &path, HTTP_TIMEOUT).await?;
367 357 }
@@ -382,8 +372,7 @@ impl Browser {
382 372 }
383 373
384 374 async fn launch_locked(&self, headless: bool) -> Result<(), BrowserError> {
385 self.launch_with_urls_locked(headless, start_urls_for(headless))
386 .await
375 self.launch_with_urls_locked(headless, start_urls()).await
387 376 }
388 377
389 378 async fn launch_with_urls_locked(
@@ -411,11 +400,6 @@ impl Browser {
411 400 }
412 401 std::fs::write(&config.mode_file, mode.file_content())?;
413 402 self.wait_until_running().await?;
414 if headless {
415 for app in APPS.into_iter().skip(1) {
416 self.open_tab(app).await?;
417 }
418 }
419 403 Ok(())
420 404 }
421 405
@@ -547,14 +531,7 @@ mod tests {
547 531 }
548 532
549 533 #[test]
550 fn headless_gets_one_start_url_visible_gets_both() {
551 assert_eq!(start_urls_for(true), ["https://teams.cloud.microsoft/"]);
552 assert_eq!(
553 start_urls_for(false),
554 [
555 "https://teams.cloud.microsoft/",
556 "https://outlook.office.com/mail/"
557 ]
558 );
534 fn only_teams_starts() {
535 assert_eq!(start_urls(), ["https://teams.cloud.microsoft/"]);
559 536 }
560 537 }
@@ -81,13 +81,8 @@ pub struct Browser {
81 inner: Arc<Inner>,
81 inner: Arc<Inner>,
82}
82}
83
83
84pub(crate) fn start_urls_for(headless: bool) -> Vec<String> {
84pub(crate) fn start_urls() -> Vec<String> {
85 let urls = APPS.iter().map(|app| app.start_url().to_owned());
85 APPS.iter().map(|app| app.start_url().to_owned()).collect()
86 if headless {
87 urls.take(1).collect()
88 } else {
89 urls.collect()
90 }
91}
86}
92
87
93pub(crate) fn jitter_between(min: Duration, max: Duration, random: u64) -> Duration {
88pub(crate) fn jitter_between(min: Duration, max: Duration, random: u64) -> Duration {
@@ -264,14 +259,9 @@ impl Browser {
264 if self.is_visible_managed() && self.is_running().await {
259 if self.is_visible_managed() && self.is_running().await {
265 return Ok(());
260 return Ok(());
266 }
261 }
267 // Always open Teams alone for login: opening Outlook alongside Teams sends Outlook to
268 // login.microsoftonline.com?prompt=select_account before Teams has an SSO cookie, leaving
269 // that second tab stuck on login even after Teams finishes signing in. Headless mode and
270 // CdpTransport open Outlook silently once Teams is signed in.
271 self.inner.wanted.store(true, Ordering::SeqCst);
262 self.inner.wanted.store(true, Ordering::SeqCst);
272 self.stop_locked(false).await?;
263 self.stop_locked(false).await?;
273 self.launch_with_urls_locked(false, start_urls_for(true))
264 self.launch_with_urls_locked(false, start_urls()).await
274 .await
275 }
265 }
276
266
277 pub async fn headless(&self) -> Result<(), BrowserError> {
267 pub async fn headless(&self) -> Result<(), BrowserError> {
@@ -361,7 +351,7 @@ impl Browser {
361 )
351 )
362 .await?;
352 .await?;
363 let attached = targets::attached_target_ids(&result);
353 let attached = targets::attached_target_ids(&result);
364 for id in targets::duplicate_app_tab_ids(&tabs, &attached) {
354 for id in targets::closable_tab_ids(&tabs, &attached) {
365 let path = format!("/json/close/{id}");
355 let path = format!("/json/close/{id}");
366 http::request(self.inner.config.port, "GET", &path, HTTP_TIMEOUT).await?;
356 http::request(self.inner.config.port, "GET", &path, HTTP_TIMEOUT).await?;
367 }
357 }
@@ -382,8 +372,7 @@ impl Browser {
382 }
372 }
383
373
384 async fn launch_locked(&self, headless: bool) -> Result<(), BrowserError> {
374 async fn launch_locked(&self, headless: bool) -> Result<(), BrowserError> {
385 self.launch_with_urls_locked(headless, start_urls_for(headless))
375 self.launch_with_urls_locked(headless, start_urls()).await
386 .await
387 }
376 }
388
377
389 async fn launch_with_urls_locked(
378 async fn launch_with_urls_locked(
@@ -411,11 +400,6 @@ impl Browser {
411 }
400 }
412 std::fs::write(&config.mode_file, mode.file_content())?;
401 std::fs::write(&config.mode_file, mode.file_content())?;
413 self.wait_until_running().await?;
402 self.wait_until_running().await?;
414 if headless {
415 for app in APPS.into_iter().skip(1) {
416 self.open_tab(app).await?;
417 }
418 }
419 Ok(())
403 Ok(())
420 }
404 }
421
405
@@ -547,14 +531,7 @@ mod tests {
547 }
531 }
548
532
549 #[test]
533 #[test]
550 fn headless_gets_one_start_url_visible_gets_both() {
534 fn only_teams_starts() {
551 assert_eq!(start_urls_for(true), ["https://teams.cloud.microsoft/"]);
535 assert_eq!(start_urls(), ["https://teams.cloud.microsoft/"]);
552 assert_eq!(
553 start_urls_for(false),
554 [
555 "https://teams.cloud.microsoft/",
556 "https://outlook.office.com/mail/"
557 ]
558 );
559 }
536 }
560}
537}
crates/browser/src/targets.rs +22 −17
@@ -6,42 +6,39 @@ use url::Url;
6 6 use crate::error::BrowserError;
7 7
8 8 const LOGIN_HOSTS: [&str; 2] = ["login.microsoftonline.com", "login.live.com"];
9 /// Outlook tabs earlier versions opened next to Teams; nothing uses them any more.
10 const RETIRED_HOSTS: [&str; 2] = ["outlook.office.com", "outlook.cloud.microsoft"];
9 11
10 12 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
11 13 #[serde(rename_all = "lowercase")]
12 14 pub enum App {
13 15 Teams,
14 Outlook,
15 16 }
16 17
17 pub const APPS: [App; 2] = [App::Teams, App::Outlook];
18 pub const APPS: [App; 1] = [App::Teams];
18 19
19 20 impl App {
20 21 pub fn start_url(self) -> &'static str {
21 22 match self {
22 23 App::Teams => "https://teams.cloud.microsoft/",
23 App::Outlook => "https://outlook.office.com/mail/",
24 24 }
25 25 }
26 26
27 27 fn park_path(self) -> &'static str {
28 28 match self {
29 29 App::Teams => "/robots.txt",
30 App::Outlook => "/owa/favicon.ico",
31 30 }
32 31 }
33 32
34 33 fn hosts(self) -> &'static [&'static str] {
35 34 match self {
36 35 App::Teams => &["teams.cloud.microsoft", "teams.microsoft.com"],
37 App::Outlook => &["outlook.office.com", "outlook.cloud.microsoft"],
38 36 }
39 37 }
40 38
41 39 pub fn name(self) -> &'static str {
42 40 match self {
43 41 App::Teams => "teams",
44 App::Outlook => "outlook",
45 42 }
46 43 }
47 44 }
@@ -167,8 +164,17 @@ pub(crate) fn attached_target_ids(result: &serde_json::Value) -> HashSet<String>
167 164 .collect()
168 165 }
169 166
170 pub(crate) fn duplicate_app_tab_ids(tabs: &[Tab], attached: &HashSet<String>) -> Vec<String> {
171 let mut duplicates = Vec::new();
167 pub(crate) fn closable_tab_ids(tabs: &[Tab], attached: &HashSet<String>) -> Vec<String> {
168 let mut duplicates: Vec<String> = tabs
169 .iter()
170 .filter(|tab| !attached.contains(&tab.id))
171 .filter(|tab| {
172 tab.host
173 .as_deref()
174 .is_some_and(|host| RETIRED_HOSTS.contains(&host))
175 })
176 .map(|tab| tab.id.clone())
177 .collect();
172 178 for app in APPS {
173 179 let mut candidates: Vec<&Tab> = tabs.iter().filter(|tab| tab.app == Some(app)).collect();
174 180 candidates.sort_by_key(|tab| (!attached.contains(&tab.id), tab.parked));
@@ -206,7 +212,7 @@ mod tests {
206 212 fn keeps_pages_only_and_hosts_only() {
207 213 let tabs = parse_tabs(LIST.as_bytes()).unwrap();
208 214 assert_eq!(tabs.len(), 2);
209 assert_eq!(tabs[0].app, Some(App::Outlook));
215 assert_eq!(tabs[0].app, None);
210 216 assert_eq!(tabs[0].host.as_deref(), Some("outlook.cloud.microsoft"));
211 217 assert_eq!(tabs[1].app, Some(App::Teams));
212 218 assert_eq!(login_state(&tabs), LoginState::NotRequired);
@@ -249,7 +255,6 @@ mod tests {
249 255 app_tab(&tabs, App::Teams).map(|tab| tab.id.as_str()),
250 256 Some("T")
251 257 );
252 assert!(app_tab(&tabs, App::Outlook).is_none());
253 258 }
254 259
255 260 fn page(id: &str, url: &str) -> Tab {
@@ -268,11 +273,11 @@ mod tests {
268 273 )
269 274 .unwrap();
270 275 assert!(tabs[0].parked && tabs[0].app == Some(App::Teams));
271 assert!(tabs[1].parked && tabs[1].app == Some(App::Outlook));
276 assert!(tabs[1].app.is_none());
272 277 assert!(!tabs[2].parked && tabs[2].app == Some(App::Teams));
273 278 assert!(!tabs[3].parked && tabs[3].app.is_none());
274 assert!(tabs[..2].iter().all(|tab| !tab.login));
275 assert_eq!(login_state(&tabs[..2]), LoginState::NotRequired);
279 assert!(tabs[..1].iter().all(|tab| !tab.login));
280 assert_eq!(login_state(&tabs[..1]), LoginState::NotRequired);
276 281 assert_eq!(
277 282 app_tab(&tabs[..1], App::Teams).map(|tab| tab.id.as_str()),
278 283 Some("T")
@@ -289,9 +294,9 @@ mod tests {
289 294 page("l", "https://login.microsoftonline.com/"),
290 295 ];
291 296 let attached: HashSet<String> = ["b".to_owned()].into();
292 assert_eq!(duplicate_app_tab_ids(&tabs, &attached), ["a", "c"]);
293 let both: HashSet<String> = ["a".to_owned(), "b".to_owned()].into();
294 assert_eq!(duplicate_app_tab_ids(&tabs, &both), ["c"]);
297 assert_eq!(closable_tab_ids(&tabs, &attached), ["o", "a", "c"]);
298 let both: HashSet<String> = ["a".to_owned(), "b".to_owned(), "o".to_owned()].into();
299 assert_eq!(closable_tab_ids(&tabs, &both), ["c"]);
295 300 }
296 301
297 302 #[test]
@@ -301,7 +306,7 @@ mod tests {
301 306 page("a", "https://teams.cloud.microsoft/v2/"),
302 307 page("b", "https://teams.cloud.microsoft/v2/"),
303 308 ];
304 assert_eq!(duplicate_app_tab_ids(&tabs, &HashSet::new()), ["b", "p"]);
309 assert_eq!(closable_tab_ids(&tabs, &HashSet::new()), ["b", "p"]);
305 310 }
306 311
307 312 #[test]
@@ -6,42 +6,39 @@ use url::Url;
6use crate::error::BrowserError;
6use crate::error::BrowserError;
7
7
8const LOGIN_HOSTS: [&str; 2] = ["login.microsoftonline.com", "login.live.com"];
8const LOGIN_HOSTS: [&str; 2] = ["login.microsoftonline.com", "login.live.com"];
9/// Outlook tabs earlier versions opened next to Teams; nothing uses them any more.
10const RETIRED_HOSTS: [&str; 2] = ["outlook.office.com", "outlook.cloud.microsoft"];
9
11
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
11#[serde(rename_all = "lowercase")]
13#[serde(rename_all = "lowercase")]
12pub enum App {
14pub enum App {
13 Teams,
15 Teams,
14 Outlook,
15}
16}
16
17
17pub const APPS: [App; 2] = [App::Teams, App::Outlook];
18pub const APPS: [App; 1] = [App::Teams];
18
19
19impl App {
20impl App {
20 pub fn start_url(self) -> &'static str {
21 pub fn start_url(self) -> &'static str {
21 match self {
22 match self {
22 App::Teams => "https://teams.cloud.microsoft/",
23 App::Teams => "https://teams.cloud.microsoft/",
23 App::Outlook => "https://outlook.office.com/mail/",
24 }
24 }
25 }
25 }
26
26
27 fn park_path(self) -> &'static str {
27 fn park_path(self) -> &'static str {
28 match self {
28 match self {
29 App::Teams => "/robots.txt",
29 App::Teams => "/robots.txt",
30 App::Outlook => "/owa/favicon.ico",
31 }
30 }
32 }
31 }
33
32
34 fn hosts(self) -> &'static [&'static str] {
33 fn hosts(self) -> &'static [&'static str] {
35 match self {
34 match self {
36 App::Teams => &["teams.cloud.microsoft", "teams.microsoft.com"],
35 App::Teams => &["teams.cloud.microsoft", "teams.microsoft.com"],
37 App::Outlook => &["outlook.office.com", "outlook.cloud.microsoft"],
38 }
36 }
39 }
37 }
40
38
41 pub fn name(self) -> &'static str {
39 pub fn name(self) -> &'static str {
42 match self {
40 match self {
43 App::Teams => "teams",
41 App::Teams => "teams",
44 App::Outlook => "outlook",
45 }
42 }
46 }
43 }
47}
44}
@@ -167,8 +164,17 @@ pub(crate) fn attached_target_ids(result: &serde_json::Value) -> HashSet<String>
167 .collect()
164 .collect()
168}
165}
169
166
170pub(crate) fn duplicate_app_tab_ids(tabs: &[Tab], attached: &HashSet<String>) -> Vec<String> {
167pub(crate) fn closable_tab_ids(tabs: &[Tab], attached: &HashSet<String>) -> Vec<String> {
171 let mut duplicates = Vec::new();
168 let mut duplicates: Vec<String> = tabs
169 .iter()
170 .filter(|tab| !attached.contains(&tab.id))
171 .filter(|tab| {
172 tab.host
173 .as_deref()
174 .is_some_and(|host| RETIRED_HOSTS.contains(&host))
175 })
176 .map(|tab| tab.id.clone())
177 .collect();
172 for app in APPS {
178 for app in APPS {
173 let mut candidates: Vec<&Tab> = tabs.iter().filter(|tab| tab.app == Some(app)).collect();
179 let mut candidates: Vec<&Tab> = tabs.iter().filter(|tab| tab.app == Some(app)).collect();
174 candidates.sort_by_key(|tab| (!attached.contains(&tab.id), tab.parked));
180 candidates.sort_by_key(|tab| (!attached.contains(&tab.id), tab.parked));
@@ -206,7 +212,7 @@ mod tests {
206 fn keeps_pages_only_and_hosts_only() {
212 fn keeps_pages_only_and_hosts_only() {
207 let tabs = parse_tabs(LIST.as_bytes()).unwrap();
213 let tabs = parse_tabs(LIST.as_bytes()).unwrap();
208 assert_eq!(tabs.len(), 2);
214 assert_eq!(tabs.len(), 2);
209 assert_eq!(tabs[0].app, Some(App::Outlook));
215 assert_eq!(tabs[0].app, None);
210 assert_eq!(tabs[0].host.as_deref(), Some("outlook.cloud.microsoft"));
216 assert_eq!(tabs[0].host.as_deref(), Some("outlook.cloud.microsoft"));
211 assert_eq!(tabs[1].app, Some(App::Teams));
217 assert_eq!(tabs[1].app, Some(App::Teams));
212 assert_eq!(login_state(&tabs), LoginState::NotRequired);
218 assert_eq!(login_state(&tabs), LoginState::NotRequired);
@@ -249,7 +255,6 @@ mod tests {
249 app_tab(&tabs, App::Teams).map(|tab| tab.id.as_str()),
255 app_tab(&tabs, App::Teams).map(|tab| tab.id.as_str()),
250 Some("T")
256 Some("T")
251 );
257 );
252 assert!(app_tab(&tabs, App::Outlook).is_none());
253 }
258 }
254
259
255 fn page(id: &str, url: &str) -> Tab {
260 fn page(id: &str, url: &str) -> Tab {
@@ -268,11 +273,11 @@ mod tests {
268 )
273 )
269 .unwrap();
274 .unwrap();
270 assert!(tabs[0].parked && tabs[0].app == Some(App::Teams));
275 assert!(tabs[0].parked && tabs[0].app == Some(App::Teams));
271 assert!(tabs[1].parked && tabs[1].app == Some(App::Outlook));
276 assert!(tabs[1].app.is_none());
272 assert!(!tabs[2].parked && tabs[2].app == Some(App::Teams));
277 assert!(!tabs[2].parked && tabs[2].app == Some(App::Teams));
273 assert!(!tabs[3].parked && tabs[3].app.is_none());
278 assert!(!tabs[3].parked && tabs[3].app.is_none());
274 assert!(tabs[..2].iter().all(|tab| !tab.login));
279 assert!(tabs[..1].iter().all(|tab| !tab.login));
275 assert_eq!(login_state(&tabs[..2]), LoginState::NotRequired);
280 assert_eq!(login_state(&tabs[..1]), LoginState::NotRequired);
276 assert_eq!(
281 assert_eq!(
277 app_tab(&tabs[..1], App::Teams).map(|tab| tab.id.as_str()),
282 app_tab(&tabs[..1], App::Teams).map(|tab| tab.id.as_str()),
278 Some("T")
283 Some("T")
@@ -289,9 +294,9 @@ mod tests {
289 page("l", "https://login.microsoftonline.com/"),
294 page("l", "https://login.microsoftonline.com/"),
290 ];
295 ];
291 let attached: HashSet<String> = ["b".to_owned()].into();
296 let attached: HashSet<String> = ["b".to_owned()].into();
292 assert_eq!(duplicate_app_tab_ids(&tabs, &attached), ["a", "c"]);
297 assert_eq!(closable_tab_ids(&tabs, &attached), ["o", "a", "c"]);
293 let both: HashSet<String> = ["a".to_owned(), "b".to_owned()].into();
298 let both: HashSet<String> = ["a".to_owned(), "b".to_owned(), "o".to_owned()].into();
294 assert_eq!(duplicate_app_tab_ids(&tabs, &both), ["c"]);
299 assert_eq!(closable_tab_ids(&tabs, &both), ["c"]);
295 }
300 }
296
301
297 #[test]
302 #[test]
@@ -301,7 +306,7 @@ mod tests {
301 page("a", "https://teams.cloud.microsoft/v2/"),
306 page("a", "https://teams.cloud.microsoft/v2/"),
302 page("b", "https://teams.cloud.microsoft/v2/"),
307 page("b", "https://teams.cloud.microsoft/v2/"),
303 ];
308 ];
304 assert_eq!(duplicate_app_tab_ids(&tabs, &HashSet::new()), ["b", "p"]);
309 assert_eq!(closable_tab_ids(&tabs, &HashSet::new()), ["b", "p"]);
305 }
310 }
306
311
307 #[test]
312 #[test]
crates/browser/tests/mock_server.rs +22 −19
@@ -63,20 +63,20 @@ async fn status_reports_login_required() {
63 63 }
64 64
65 65 #[tokio::test]
66 async fn ensure_running_starts_headless_with_one_url_and_opens_the_second_tab() {
66 async fn ensure_running_starts_headless_with_the_teams_tab_only() {
67 67 let harness = harness().await;
68 68 harness.browser.ensure_running().await.unwrap();
69 69 let launches = harness.launcher.requests.lock().unwrap().clone();
70 70 assert_eq!(launches.len(), 1);
71 71 assert!(launches[0].headless);
72 72 assert_eq!(launches[0].start_urls, [TEAMS]);
73 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
73 assert_eq!(harness.mock.urls(), [TEAMS]);
74 74 assert_eq!(
75 75 std::fs::read_to_string(&harness.mode_file).unwrap(),
76 76 "headless"
77 77 );
78 78 assert!(
79 harness
79 !harness
80 80 .mock
81 81 .requests()
82 82 .contains(&"PUT /json/new".to_owned())
@@ -86,10 +86,10 @@ async fn ensure_running_starts_headless_with_one_url_and_opens_the_second_tab()
86 86 #[tokio::test]
87 87 async fn ensure_running_on_a_running_browser_opens_only_missing_tabs() {
88 88 let harness = harness().await;
89 harness.mock.start(&[TEAMS]).await;
89 harness.mock.start(&[OUTLOOK]).await;
90 90 harness.browser.ensure_running().await.unwrap();
91 91 assert!(harness.launcher.requests.lock().unwrap().is_empty());
92 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
92 assert_eq!(harness.mock.urls(), [OUTLOOK, TEAMS]);
93 93 harness.browser.ensure_tabs().await.unwrap();
94 94 assert_eq!(harness.mock.urls().len(), 2);
95 95 }
@@ -329,7 +329,7 @@ async fn watchdog_ignores_the_gap_during_a_login_window_restart() {
329 329 #[tokio::test]
330 330 async fn parked_tabs_are_the_app_tab_not_missing_and_not_login() {
331 331 let harness = harness().await;
332 harness.mock.start(&[PARKED_TEAMS, PARKED_OUTLOOK]).await;
332 harness.mock.start(&[PARKED_TEAMS]).await;
333 333 let status = harness.browser.status().await.unwrap();
334 334 assert!(
335 335 status
@@ -339,7 +339,7 @@ async fn parked_tabs_are_the_app_tab_not_missing_and_not_login() {
339 339 );
340 340 assert_eq!(status.login_state, LoginState::NotRequired);
341 341 harness.browser.ensure_running().await.unwrap();
342 assert_eq!(harness.mock.urls(), [PARKED_TEAMS, PARKED_OUTLOOK]);
342 assert_eq!(harness.mock.urls(), [PARKED_TEAMS]);
343 343 }
344 344
345 345 #[tokio::test]
@@ -354,18 +354,21 @@ async fn wake_navigates_the_parked_app_tab_to_its_start_url() {
354 354 .requests()
355 355 .contains(&"CDP Page.navigate".to_owned())
356 356 );
357 harness.browser.wake(App::Outlook).await.unwrap();
358 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
359 357 let status = harness.browser.status().await.unwrap();
360 assert!(status.tabs.iter().all(|tab| !tab.parked));
358 assert!(
359 status
360 .tabs
361 .iter()
362 .all(|tab| tab.app.is_none() || !tab.parked)
363 );
361 364 }
362 365
363 366 #[tokio::test]
364 367 async fn wake_opens_the_tab_when_the_app_has_none() {
365 368 let harness = harness().await;
366 harness.mock.start(&[TEAMS]).await;
367 harness.browser.wake(App::Outlook).await.unwrap();
368 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
369 harness.mock.start(&[OUTLOOK]).await;
370 harness.browser.wake(App::Teams).await.unwrap();
371 assert_eq!(harness.mock.urls(), [OUTLOOK, TEAMS]);
369 372 }
370 373
371 374 #[tokio::test]
@@ -378,7 +381,7 @@ async fn jittered_recheck_adopts_a_chrome_another_launcher_started() {
378 381 mock.start(&[TEAMS, OUTLOOK]).await;
379 382 ensure.await.unwrap().unwrap();
380 383 assert!(harness.launcher.requests.lock().unwrap().is_empty());
381 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
384 assert_eq!(harness.mock.urls(), [TEAMS]);
382 385 }
383 386
384 387 #[tokio::test]
@@ -387,17 +390,17 @@ async fn a_foreign_chrome_taking_the_port_during_launch_is_adopted_and_deduped()
387 390 harness.mock.set_attached(&["P0"]);
388 391 *harness.launcher.foreign.lock().unwrap() = Some(vec![TEAMS, TEAMS, OUTLOOK]);
389 392 harness.browser.ensure_running().await.unwrap();
390 assert_eq!(harness.mock.tab_ids(), ["P0", "P2"]);
391 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
393 assert_eq!(harness.mock.tab_ids(), ["P0"]);
394 assert_eq!(harness.mock.urls(), [TEAMS]);
392 395 }
393 396
394 397 #[tokio::test]
395 398 async fn dedupe_closes_unattached_duplicates_after_a_launch() {
396 399 let harness = harness().await;
397 *harness.launcher.foreign.lock().unwrap() = Some(vec![TEAMS, TEAMS, OUTLOOK, OUTLOOK]);
400 *harness.launcher.foreign.lock().unwrap() = Some(vec![TEAMS, TEAMS, PARKED_TEAMS]);
398 401 harness.mock.set_attached(&["P1"]);
399 402 harness.browser.ensure_running().await.unwrap();
400 assert_eq!(harness.mock.tab_ids(), ["P1", "P2"]);
403 assert_eq!(harness.mock.tab_ids(), ["P1"]);
401 404 }
402 405
403 406 #[tokio::test]
@@ -405,7 +408,7 @@ async fn dedupe_never_closes_login_or_foreign_tabs() {
405 408 let harness = harness().await;
406 409 *harness.launcher.foreign.lock().unwrap() = Some(vec![TEAMS, LOGIN, "about:blank"]);
407 410 harness.browser.ensure_running().await.unwrap();
408 assert_eq!(harness.mock.urls(), [TEAMS, LOGIN, "about:blank", OUTLOOK]);
411 assert_eq!(harness.mock.urls(), [TEAMS, LOGIN, "about:blank"]);
409 412 }
410 413
411 414 #[tokio::test]
@@ -63,20 +63,20 @@ async fn status_reports_login_required() {
63}
63}
64
64
65#[tokio::test]
65#[tokio::test]
66async fn ensure_running_starts_headless_with_one_url_and_opens_the_second_tab() {
66async fn ensure_running_starts_headless_with_the_teams_tab_only() {
67 let harness = harness().await;
67 let harness = harness().await;
68 harness.browser.ensure_running().await.unwrap();
68 harness.browser.ensure_running().await.unwrap();
69 let launches = harness.launcher.requests.lock().unwrap().clone();
69 let launches = harness.launcher.requests.lock().unwrap().clone();
70 assert_eq!(launches.len(), 1);
70 assert_eq!(launches.len(), 1);
71 assert!(launches[0].headless);
71 assert!(launches[0].headless);
72 assert_eq!(launches[0].start_urls, [TEAMS]);
72 assert_eq!(launches[0].start_urls, [TEAMS]);
73 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
73 assert_eq!(harness.mock.urls(), [TEAMS]);
74 assert_eq!(
74 assert_eq!(
75 std::fs::read_to_string(&harness.mode_file).unwrap(),
75 std::fs::read_to_string(&harness.mode_file).unwrap(),
76 "headless"
76 "headless"
77 );
77 );
78 assert!(
78 assert!(
79 harness
79 !harness
80 .mock
80 .mock
81 .requests()
81 .requests()
82 .contains(&"PUT /json/new".to_owned())
82 .contains(&"PUT /json/new".to_owned())
@@ -86,10 +86,10 @@ async fn ensure_running_starts_headless_with_one_url_and_opens_the_second_tab()
86#[tokio::test]
86#[tokio::test]
87async fn ensure_running_on_a_running_browser_opens_only_missing_tabs() {
87async fn ensure_running_on_a_running_browser_opens_only_missing_tabs() {
88 let harness = harness().await;
88 let harness = harness().await;
89 harness.mock.start(&[TEAMS]).await;
89 harness.mock.start(&[OUTLOOK]).await;
90 harness.browser.ensure_running().await.unwrap();
90 harness.browser.ensure_running().await.unwrap();
91 assert!(harness.launcher.requests.lock().unwrap().is_empty());
91 assert!(harness.launcher.requests.lock().unwrap().is_empty());
92 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
92 assert_eq!(harness.mock.urls(), [OUTLOOK, TEAMS]);
93 harness.browser.ensure_tabs().await.unwrap();
93 harness.browser.ensure_tabs().await.unwrap();
94 assert_eq!(harness.mock.urls().len(), 2);
94 assert_eq!(harness.mock.urls().len(), 2);
95}
95}
@@ -329,7 +329,7 @@ async fn watchdog_ignores_the_gap_during_a_login_window_restart() {
329#[tokio::test]
329#[tokio::test]
330async fn parked_tabs_are_the_app_tab_not_missing_and_not_login() {
330async fn parked_tabs_are_the_app_tab_not_missing_and_not_login() {
331 let harness = harness().await;
331 let harness = harness().await;
332 harness.mock.start(&[PARKED_TEAMS, PARKED_OUTLOOK]).await;
332 harness.mock.start(&[PARKED_TEAMS]).await;
333 let status = harness.browser.status().await.unwrap();
333 let status = harness.browser.status().await.unwrap();
334 assert!(
334 assert!(
335 status
335 status
@@ -339,7 +339,7 @@ async fn parked_tabs_are_the_app_tab_not_missing_and_not_login() {
339 );
339 );
340 assert_eq!(status.login_state, LoginState::NotRequired);
340 assert_eq!(status.login_state, LoginState::NotRequired);
341 harness.browser.ensure_running().await.unwrap();
341 harness.browser.ensure_running().await.unwrap();
342 assert_eq!(harness.mock.urls(), [PARKED_TEAMS, PARKED_OUTLOOK]);
342 assert_eq!(harness.mock.urls(), [PARKED_TEAMS]);
343}
343}
344
344
345#[tokio::test]
345#[tokio::test]
@@ -354,18 +354,21 @@ async fn wake_navigates_the_parked_app_tab_to_its_start_url() {
354 .requests()
354 .requests()
355 .contains(&"CDP Page.navigate".to_owned())
355 .contains(&"CDP Page.navigate".to_owned())
356 );
356 );
357 harness.browser.wake(App::Outlook).await.unwrap();
358 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
359 let status = harness.browser.status().await.unwrap();
357 let status = harness.browser.status().await.unwrap();
360 assert!(status.tabs.iter().all(|tab| !tab.parked));
358 assert!(
359 status
360 .tabs
361 .iter()
362 .all(|tab| tab.app.is_none() || !tab.parked)
363 );
361}
364}
362
365
363#[tokio::test]
366#[tokio::test]
364async fn wake_opens_the_tab_when_the_app_has_none() {
367async fn wake_opens_the_tab_when_the_app_has_none() {
365 let harness = harness().await;
368 let harness = harness().await;
366 harness.mock.start(&[TEAMS]).await;
369 harness.mock.start(&[OUTLOOK]).await;
367 harness.browser.wake(App::Outlook).await.unwrap();
370 harness.browser.wake(App::Teams).await.unwrap();
368 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
371 assert_eq!(harness.mock.urls(), [OUTLOOK, TEAMS]);
369}
372}
370
373
371#[tokio::test]
374#[tokio::test]
@@ -378,7 +381,7 @@ async fn jittered_recheck_adopts_a_chrome_another_launcher_started() {
378 mock.start(&[TEAMS, OUTLOOK]).await;
381 mock.start(&[TEAMS, OUTLOOK]).await;
379 ensure.await.unwrap().unwrap();
382 ensure.await.unwrap().unwrap();
380 assert!(harness.launcher.requests.lock().unwrap().is_empty());
383 assert!(harness.launcher.requests.lock().unwrap().is_empty());
381 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
384 assert_eq!(harness.mock.urls(), [TEAMS]);
382}
385}
383
386
384#[tokio::test]
387#[tokio::test]
@@ -387,17 +390,17 @@ async fn a_foreign_chrome_taking_the_port_during_launch_is_adopted_and_deduped()
387 harness.mock.set_attached(&["P0"]);
390 harness.mock.set_attached(&["P0"]);
388 *harness.launcher.foreign.lock().unwrap() = Some(vec![TEAMS, TEAMS, OUTLOOK]);
391 *harness.launcher.foreign.lock().unwrap() = Some(vec![TEAMS, TEAMS, OUTLOOK]);
389 harness.browser.ensure_running().await.unwrap();
392 harness.browser.ensure_running().await.unwrap();
390 assert_eq!(harness.mock.tab_ids(), ["P0", "P2"]);
393 assert_eq!(harness.mock.tab_ids(), ["P0"]);
391 assert_eq!(harness.mock.urls(), [TEAMS, OUTLOOK]);
394 assert_eq!(harness.mock.urls(), [TEAMS]);
392}
395}
393
396
394#[tokio::test]
397#[tokio::test]
395async fn dedupe_closes_unattached_duplicates_after_a_launch() {
398async fn dedupe_closes_unattached_duplicates_after_a_launch() {
396 let harness = harness().await;
399 let harness = harness().await;
397 *harness.launcher.foreign.lock().unwrap() = Some(vec![TEAMS, TEAMS, OUTLOOK, OUTLOOK]);
400 *harness.launcher.foreign.lock().unwrap() = Some(vec![TEAMS, TEAMS, PARKED_TEAMS]);
398 harness.mock.set_attached(&["P1"]);
401 harness.mock.set_attached(&["P1"]);
399 harness.browser.ensure_running().await.unwrap();
402 harness.browser.ensure_running().await.unwrap();
400 assert_eq!(harness.mock.tab_ids(), ["P1", "P2"]);
403 assert_eq!(harness.mock.tab_ids(), ["P1"]);
401}
404}
402
405
403#[tokio::test]
406#[tokio::test]
@@ -405,7 +408,7 @@ async fn dedupe_never_closes_login_or_foreign_tabs() {
405 let harness = harness().await;
408 let harness = harness().await;
406 *harness.launcher.foreign.lock().unwrap() = Some(vec![TEAMS, LOGIN, "about:blank"]);
409 *harness.launcher.foreign.lock().unwrap() = Some(vec![TEAMS, LOGIN, "about:blank"]);
407 harness.browser.ensure_running().await.unwrap();
410 harness.browser.ensure_running().await.unwrap();
408 assert_eq!(harness.mock.urls(), [TEAMS, LOGIN, "about:blank", OUTLOOK]);
411 assert_eq!(harness.mock.urls(), [TEAMS, LOGIN, "about:blank"]);
409}
412}
410
413
411#[tokio::test]
414#[tokio::test]
crates/calling/src/background.rs +1 −1
@@ -8,7 +8,7 @@ use crate::error::{Error, Result};
8 8
9 9 pub const CATALOG_URL: &str = chatsvc::teams_cdn::BACKGROUND_CATALOG_URL;
10 10 pub const CDN_ROOT: &str = chatsvc::teams_cdn::ROOT;
11 const FETCH_SCOPE: &str = "Chat.Read";
11 const FETCH_SCOPE: &str = "User.ReadBasic.All";
12 12 const MAX_SIDE: u32 = 1920;
13 13 const CATALOG_FILE: &str = "config.json";
14 14 const THUMBNAIL_DIR: &str = "thumbnails";
@@ -8,7 +8,7 @@ use crate::error::{Error, Result};
8
8
9pub const CATALOG_URL: &str = chatsvc::teams_cdn::BACKGROUND_CATALOG_URL;
9pub const CATALOG_URL: &str = chatsvc::teams_cdn::BACKGROUND_CATALOG_URL;
10pub const CDN_ROOT: &str = chatsvc::teams_cdn::ROOT;
10pub const CDN_ROOT: &str = chatsvc::teams_cdn::ROOT;
11const FETCH_SCOPE: &str = "Chat.Read";
11const FETCH_SCOPE: &str = "User.ReadBasic.All";
12const MAX_SIDE: u32 = 1920;
12const MAX_SIDE: u32 = 1920;
13const CATALOG_FILE: &str = "config.json";
13const CATALOG_FILE: &str = "config.json";
14const THUMBNAIL_DIR: &str = "thumbnails";
14const THUMBNAIL_DIR: &str = "thumbnails";
crates/chatsvc/src/chat_listing.rs added +229 −0
@@ -0,0 +1,229 @@
1 use serde_json::Value;
2 use session::{Request, Scope, Session};
3
4 use crate::error::{Error, Result};
5 use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6 use crate::pins::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, DEFAULT_REGION, SessionTransport};
7
8 const VIEW: &str = "view=msnp24Equivalent";
9 const NEWEST_ANCHOR_SLACK_MS: i64 = 60_000;
10
11 /// One page of the conversation list as the chat service sends it; `next_url` lists older conversations.
12 #[derive(Debug, Clone, PartialEq)]
13 pub struct ConversationPage {
14 pub conversations: Vec<Value>,
15 pub next_url: Option<String>,
16 }
17
18 #[derive(Debug, Clone, PartialEq)]
19 pub struct MessagePage {
20 pub messages: Vec<Value>,
21 pub has_older: bool,
22 }
23
24 /// One chat with its members and meeting details, from the chat service aggregator.
25 pub async fn aggregator_chat(session: &Session, chat_id: &str) -> Result<Value> {
26 let url = format!(
27 "https://teams.cloud.microsoft/api/csa/{DEFAULT_REGION}/api/v1/teams/users/me/chats/{}",
28 encode(chat_id)
29 );
30 let transport = SessionTransport::with_scope(session, Scope::new(CSA_RESOURCE, CSA_SCOPE));
31 let answer = transport.send(Request::get(url)).await?;
32 ensure_success(&answer)?;
33 Ok(answer.body)
34 }
35
36 /// Raw reads of chats, threads and messages for the native chat path.
37 pub struct ChatListing<T: MessageTransport = SessionMessageTransport> {
38 transport: T,
39 region: String,
40 }
41
42 impl ChatListing<SessionMessageTransport> {
43 pub fn new(session: &Session) -> Self {
44 ChatListing::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
45 }
46 }
47
48 impl<T: MessageTransport> ChatListing<T> {
49 pub fn with_transport(transport: T, region: &str) -> Self {
50 ChatListing {
51 transport,
52 region: region.to_owned(),
53 }
54 }
55
56 fn conversations_url(&self) -> String {
57 format!(
58 "https://teams.cloud.microsoft/api/chatsvc/{}/v1/users/ME/conversations",
59 self.region
60 )
61 }
62
63 pub fn first_page_url(&self, page_size: usize) -> String {
64 format!("{}?{VIEW}&pageSize={page_size}", self.conversations_url())
65 }
66
67 pub async fn page(&self, url: &str) -> Result<ConversationPage> {
68 let body = self.get(url).await?;
69 let conversations = body
70 .get("conversations")
71 .and_then(Value::as_array)
72 .cloned()
73 .ok_or_else(|| Error::UnexpectedAnswer("no conversations list".into()))?;
74 let next_url = body
75 .pointer("/_metadata/backwardLink")
76 .and_then(Value::as_str)
77 .filter(|link| !link.is_empty() && *link != url && !conversations.is_empty())
78 .map(str::to_owned);
79 Ok(ConversationPage {
80 conversations,
81 next_url,
82 })
83 }
84
85 pub async fn conversation(&self, conversation_id: &str) -> Result<Value> {
86 let url = format!(
87 "{}/{}?{VIEW}",
88 self.conversations_url(),
89 encode(conversation_id)
90 );
91 self.get(&url).await
92 }
93
94 /// The thread with its members; members carry ids and roles but no names.
95 pub async fn thread(&self, thread_id: &str) -> Result<Value> {
96 let url = format!(
97 "https://teams.cloud.microsoft/api/chatsvc/{}/v1/threads/{}?{VIEW}",
98 self.region,
99 encode(thread_id)
100 );
101 self.get(&url).await
102 }
103
104 /// Newest arrival first; with `before_ms` only messages that arrived before it.
105 /// The plain message list is ordered by last change, so an edit would move an old message into the newest page.
106 pub async fn messages(
107 &self,
108 conversation_id: &str,
109 before_ms: Option<i64>,
110 page_size: usize,
111 ) -> Result<MessagePage> {
112 let base = format!(
113 "{}/{}/messages",
114 self.conversations_url(),
115 encode(conversation_id)
116 );
117 let anchor_ms = before_ms.map_or_else(
118 || chrono::Utc::now().timestamp_millis() + NEWEST_ANCHOR_SLACK_MS,
119 |before_ms| before_ms - 1,
120 );
121 let url = format!(
122 "{base}/epochTimeStamp/{anchor_ms}?pageSize={page_size}&direction=BACKWARD&includeMetadata=true&locationType=Primary"
123 );
124 let body = self.get(&url).await?;
125 let messages: Vec<Value> = body
126 .get("messages")
127 .and_then(Value::as_array)
128 .cloned()
129 .ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?
130 .into_iter()
131 .filter(|message| before_ms.is_none_or(|before| arrival_ms(message) < Some(before)))
132 .collect();
133 let has_older = body
134 .pointer("/_metadata/backwardLink")
135 .and_then(Value::as_str)
136 .is_some_and(|link| !link.is_empty())
137 && !messages.is_empty();
138 Ok(MessagePage {
139 messages,
140 has_older,
141 })
142 }
143
144 pub async fn message(&self, conversation_id: &str, message_id: &str) -> Result<Value> {
145 let url = format!(
146 "{}/{}/messages/{}?{VIEW}",
147 self.conversations_url(),
148 encode(conversation_id),
149 encode(message_id)
150 );
151 self.get(&url).await
152 }
153
154 async fn get(&self, url: &str) -> Result<Value> {
155 let answer = self.transport.send(Request::get(url)).await?;
156 ensure_success(&answer)?;
157 Ok(answer.body)
158 }
159 }
160
161 fn arrival_ms(message: &Value) -> Option<i64> {
162 crate::json_id::id_text(message.get("id")?)?.parse().ok()
163 }
164
165 #[cfg(test)]
166 mod tests {
167 use std::collections::VecDeque;
168 use std::sync::Mutex;
169
170 use serde_json::json;
171 use session::ApiResponse;
172
173 use super::*;
174
175 struct Canned {
176 answers: Mutex<VecDeque<Value>>,
177 requests: Mutex<Vec<String>>,
178 }
179
180 impl MessageTransport for &Canned {
181 async fn send(&self, request: Request) -> Result<ApiResponse> {
182 self.requests.lock().unwrap().push(request.url.clone());
183 Ok(ApiResponse {
184 status: 200,
185 body: self.answers.lock().unwrap().pop_front().unwrap_or_default(),
186 retry_after: None,
187 })
188 }
189 }
190
191 fn canned(answers: Vec<Value>) -> Canned {
192 Canned {
193 answers: Mutex::new(answers.into()),
194 requests: Mutex::new(Vec::new()),
195 }
196 }
197
198 #[tokio::test]
199 async fn a_page_links_to_older_conversations() {
200 let transport = canned(vec![json!({
201 "conversations": [{"id": "19:a@thread.v2"}],
202 "_metadata": {"backwardLink": "https://next"},
203 })]);
204 let listing = ChatListing::with_transport(&transport, "emea");
205 let page = listing.page(&listing.first_page_url(50)).await.unwrap();
206 assert_eq!(page.conversations.len(), 1);
207 assert_eq!(page.next_url.as_deref(), Some("https://next"));
208 assert_eq!(
209 transport.requests.lock().unwrap()[0],
210 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations?view=msnp24Equivalent&pageSize=50"
211 );
212 }
213
214 #[tokio::test]
215 async fn older_messages_end_before_the_anchor() {
216 let transport = canned(vec![json!({
217 "messages": [{"id": "1000"}, {"id": "900"}],
218 "_metadata": {"backwardLink": "https://older"},
219 })]);
220 let listing = ChatListing::with_transport(&transport, "emea");
221 let page = listing
222 .messages("19:a@thread.v2", Some(1000), 20)
223 .await
224 .unwrap();
225 assert_eq!(page.messages, vec![json!({"id": "900"})]);
226 assert!(page.has_older);
227 assert!(transport.requests.lock().unwrap()[0].contains("/messages/epochTimeStamp/999?"));
228 }
229 }
@@ -0,0 +1,229 @@
1use serde_json::Value;
2use session::{Request, Scope, Session};
3
4use crate::error::{Error, Result};
5use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6use crate::pins::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, DEFAULT_REGION, SessionTransport};
7
8const VIEW: &str = "view=msnp24Equivalent";
9const NEWEST_ANCHOR_SLACK_MS: i64 = 60_000;
10
11/// One page of the conversation list as the chat service sends it; `next_url` lists older conversations.
12#[derive(Debug, Clone, PartialEq)]
13pub struct ConversationPage {
14 pub conversations: Vec<Value>,
15 pub next_url: Option<String>,
16}
17
18#[derive(Debug, Clone, PartialEq)]
19pub struct MessagePage {
20 pub messages: Vec<Value>,
21 pub has_older: bool,
22}
23
24/// One chat with its members and meeting details, from the chat service aggregator.
25pub async fn aggregator_chat(session: &Session, chat_id: &str) -> Result<Value> {
26 let url = format!(
27 "https://teams.cloud.microsoft/api/csa/{DEFAULT_REGION}/api/v1/teams/users/me/chats/{}",
28 encode(chat_id)
29 );
30 let transport = SessionTransport::with_scope(session, Scope::new(CSA_RESOURCE, CSA_SCOPE));
31 let answer = transport.send(Request::get(url)).await?;
32 ensure_success(&answer)?;
33 Ok(answer.body)
34}
35
36/// Raw reads of chats, threads and messages for the native chat path.
37pub struct ChatListing<T: MessageTransport = SessionMessageTransport> {
38 transport: T,
39 region: String,
40}
41
42impl ChatListing<SessionMessageTransport> {
43 pub fn new(session: &Session) -> Self {
44 ChatListing::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
45 }
46}
47
48impl<T: MessageTransport> ChatListing<T> {
49 pub fn with_transport(transport: T, region: &str) -> Self {
50 ChatListing {
51 transport,
52 region: region.to_owned(),
53 }
54 }
55
56 fn conversations_url(&self) -> String {
57 format!(
58 "https://teams.cloud.microsoft/api/chatsvc/{}/v1/users/ME/conversations",
59 self.region
60 )
61 }
62
63 pub fn first_page_url(&self, page_size: usize) -> String {
64 format!("{}?{VIEW}&pageSize={page_size}", self.conversations_url())
65 }
66
67 pub async fn page(&self, url: &str) -> Result<ConversationPage> {
68 let body = self.get(url).await?;
69 let conversations = body
70 .get("conversations")
71 .and_then(Value::as_array)
72 .cloned()
73 .ok_or_else(|| Error::UnexpectedAnswer("no conversations list".into()))?;
74 let next_url = body
75 .pointer("/_metadata/backwardLink")
76 .and_then(Value::as_str)
77 .filter(|link| !link.is_empty() && *link != url && !conversations.is_empty())
78 .map(str::to_owned);
79 Ok(ConversationPage {
80 conversations,
81 next_url,
82 })
83 }
84
85 pub async fn conversation(&self, conversation_id: &str) -> Result<Value> {
86 let url = format!(
87 "{}/{}?{VIEW}",
88 self.conversations_url(),
89 encode(conversation_id)
90 );
91 self.get(&url).await
92 }
93
94 /// The thread with its members; members carry ids and roles but no names.
95 pub async fn thread(&self, thread_id: &str) -> Result<Value> {
96 let url = format!(
97 "https://teams.cloud.microsoft/api/chatsvc/{}/v1/threads/{}?{VIEW}",
98 self.region,
99 encode(thread_id)
100 );
101 self.get(&url).await
102 }
103
104 /// Newest arrival first; with `before_ms` only messages that arrived before it.
105 /// The plain message list is ordered by last change, so an edit would move an old message into the newest page.
106 pub async fn messages(
107 &self,
108 conversation_id: &str,
109 before_ms: Option<i64>,
110 page_size: usize,
111 ) -> Result<MessagePage> {
112 let base = format!(
113 "{}/{}/messages",
114 self.conversations_url(),
115 encode(conversation_id)
116 );
117 let anchor_ms = before_ms.map_or_else(
118 || chrono::Utc::now().timestamp_millis() + NEWEST_ANCHOR_SLACK_MS,
119 |before_ms| before_ms - 1,
120 );
121 let url = format!(
122 "{base}/epochTimeStamp/{anchor_ms}?pageSize={page_size}&direction=BACKWARD&includeMetadata=true&locationType=Primary"
123 );
124 let body = self.get(&url).await?;
125 let messages: Vec<Value> = body
126 .get("messages")
127 .and_then(Value::as_array)
128 .cloned()
129 .ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?
130 .into_iter()
131 .filter(|message| before_ms.is_none_or(|before| arrival_ms(message) < Some(before)))
132 .collect();
133 let has_older = body
134 .pointer("/_metadata/backwardLink")
135 .and_then(Value::as_str)
136 .is_some_and(|link| !link.is_empty())
137 && !messages.is_empty();
138 Ok(MessagePage {
139 messages,
140 has_older,
141 })
142 }
143
144 pub async fn message(&self, conversation_id: &str, message_id: &str) -> Result<Value> {
145 let url = format!(
146 "{}/{}/messages/{}?{VIEW}",
147 self.conversations_url(),
148 encode(conversation_id),
149 encode(message_id)
150 );
151 self.get(&url).await
152 }
153
154 async fn get(&self, url: &str) -> Result<Value> {
155 let answer = self.transport.send(Request::get(url)).await?;
156 ensure_success(&answer)?;
157 Ok(answer.body)
158 }
159}
160
161fn arrival_ms(message: &Value) -> Option<i64> {
162 crate::json_id::id_text(message.get("id")?)?.parse().ok()
163}
164
165#[cfg(test)]
166mod tests {
167 use std::collections::VecDeque;
168 use std::sync::Mutex;
169
170 use serde_json::json;
171 use session::ApiResponse;
172
173 use super::*;
174
175 struct Canned {
176 answers: Mutex<VecDeque<Value>>,
177 requests: Mutex<Vec<String>>,
178 }
179
180 impl MessageTransport for &Canned {
181 async fn send(&self, request: Request) -> Result<ApiResponse> {
182 self.requests.lock().unwrap().push(request.url.clone());
183 Ok(ApiResponse {
184 status: 200,
185 body: self.answers.lock().unwrap().pop_front().unwrap_or_default(),
186 retry_after: None,
187 })
188 }
189 }
190
191 fn canned(answers: Vec<Value>) -> Canned {
192 Canned {
193 answers: Mutex::new(answers.into()),
194 requests: Mutex::new(Vec::new()),
195 }
196 }
197
198 #[tokio::test]
199 async fn a_page_links_to_older_conversations() {
200 let transport = canned(vec![json!({
201 "conversations": [{"id": "19:a@thread.v2"}],
202 "_metadata": {"backwardLink": "https://next"},
203 })]);
204 let listing = ChatListing::with_transport(&transport, "emea");
205 let page = listing.page(&listing.first_page_url(50)).await.unwrap();
206 assert_eq!(page.conversations.len(), 1);
207 assert_eq!(page.next_url.as_deref(), Some("https://next"));
208 assert_eq!(
209 transport.requests.lock().unwrap()[0],
210 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations?view=msnp24Equivalent&pageSize=50"
211 );
212 }
213
214 #[tokio::test]
215 async fn older_messages_end_before_the_anchor() {
216 let transport = canned(vec![json!({
217 "messages": [{"id": "1000"}, {"id": "900"}],
218 "_metadata": {"backwardLink": "https://older"},
219 })]);
220 let listing = ChatListing::with_transport(&transport, "emea");
221 let page = listing
222 .messages("19:a@thread.v2", Some(1000), 20)
223 .await
224 .unwrap();
225 assert_eq!(page.messages, vec![json!({"id": "900"})]);
226 assert!(page.has_older);
227 assert!(transport.requests.lock().unwrap()[0].contains("/messages/epochTimeStamp/999?"));
228 }
229}
crates/chatsvc/src/graph_events.rs added +339 −0
@@ -0,0 +1,339 @@
1 use chrono::{DateTime, Utc};
2 use serde_json::{Value, json};
3
4 const STARTED_TYPE: &str = "#microsoft.graph.callStartedEventMessageDetail";
5 const ENDED_TYPE: &str = "#microsoft.graph.callEndedEventMessageDetail";
6 const RECORDING_TYPE: &str = "#microsoft.graph.callRecordingEventMessageDetail";
7 const TRANSCRIPT_TYPE: &str = "#microsoft.graph.callTranscriptEventMessageDetail";
8 const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
9 const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
10 const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
11 const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";
12 const MEETING_CHAT_PREFIX: &str = "19:meeting_";
13 const ALL_HISTORY: &str = "0001-01-01T00:00:00Z";
14
15 /// The Graph `eventDetail` of a chat service system message; `None` for events Graph does not list.
16 pub fn event_detail(
17 message_type: &str,
18 content: &str,
19 conversation_id: &str,
20 sender_id: Option<&str>,
21 ) -> Option<Value> {
22 match message_type {
23 "Event/Call" => call_detail(content, conversation_id, sender_id),
24 "RichText/Media_CallRecording" => recording_detail(content),
25 "RichText/Media_CallTranscript" => transcript_detail(content),
26 "ThreadActivity/AddMember" => added_detail(content),
27 "ThreadActivity/DeleteMember" => Some(json!({
28 "@odata.type": MEMBERS_DELETED_TYPE,
29 "members": targets(content),
30 "initiator": user(tag_text(content, "initiator")),
31 })),
32 "ThreadActivity/MemberLeft" => left_detail(content),
33 "ThreadActivity/TopicUpdate" if !conversation_id.starts_with(MEETING_CHAT_PREFIX) => {
34 Some(json!({
35 "@odata.type": CHAT_RENAMED_TYPE,
36 "chatDisplayName": tag_text(content, "value").map(|topic| unescape(topic.trim())),
37 "initiator": user(tag_text(content, "initiator")),
38 }))
39 }
40 _ => None,
41 }
42 }
43
44 /// The recording and call events of a chat service message page, as a Graph `{"value": [...]}` page.
45 pub fn graph_event_page(conversation_id: &str, chatsvc_page: &Value) -> Value {
46 let events: Vec<Value> = chatsvc_page["messages"]
47 .as_array()
48 .into_iter()
49 .flatten()
50 .filter_map(|message| {
51 let message_type = message["messagetype"].as_str()?;
52 if !is_event(message_type) {
53 return None;
54 }
55 let sender_id = message["from"]
56 .as_str()
57 .map(|from| user_id(from.rsplit('/').next().unwrap_or(from)));
58 let detail = event_detail(
59 message_type,
60 message["content"].as_str().unwrap_or_default(),
61 conversation_id,
62 sender_id,
63 )?;
64 let created = ["originalarrivaltime", "composetime"]
65 .iter()
66 .find_map(|key| message[*key].as_str())
67 .and_then(|stamp| DateTime::parse_from_rfc3339(stamp).ok())
68 .map(|stamp| stamp.with_timezone(&Utc).to_rfc3339());
69 Some(json!({
70 "id": crate::json_id::id_text(&message["id"])?,
71 "createdDateTime": created,
72 "eventDetail": detail,
73 }))
74 })
75 .collect();
76 json!({"value": events})
77 }
78
79 pub fn is_event(message_type: &str) -> bool {
80 message_type == "Event/Call"
81 || message_type.starts_with("ThreadActivity/")
82 || message_type == "RichText/Media_CallRecording"
83 || message_type == "RichText/Media_CallTranscript"
84 }
85
86 fn call_detail(content: &str, conversation_id: &str, sender_id: Option<&str>) -> Option<Value> {
87 let kind = if has_flag(content, "ended") {
88 ENDED_TYPE
89 } else {
90 STARTED_TYPE
91 };
92 let parts: Vec<&str> = content.split("<part ").skip(1).collect();
93 let participants: Vec<Value> = parts
94 .iter()
95 .filter_map(|part| {
96 let identity = attribute(&format!(" {part}"), "identity")?.to_owned();
97 let name = tag_text(part, "displayName")
98 .map(|name| unescape(name.trim()))
99 .filter(|name| !name.is_empty());
100 Some(json!({"participant": {"user": {"id": user_id(&identity), "displayName": name}}}))
101 })
102 .collect();
103 let longest = parts
104 .iter()
105 .filter_map(|part| tag_text(part, "duration")?.trim().parse::<f64>().ok())
106 .fold(None, |longest: Option<f64>, seconds| {
107 Some(longest.map_or(seconds, |known| known.max(seconds)))
108 });
109 let event_type = tag_text(content, "callEventType").unwrap_or_default();
110 let meeting = event_type.to_ascii_lowercase().contains("meeting")
111 || conversation_id.starts_with(MEETING_CHAT_PREFIX)
112 || tag_text(content, "meetingType").is_some_and(|kind| !kind.trim().is_empty());
113 Some(json!({
114 "@odata.type": kind,
115 "callId": tag_text(content, "callId")?.trim(),
116 "callDuration": longest.map(|seconds| format!("PT{}S", seconds.round() as u64)),
117 "callEventType": if meeting { "meeting" } else { "call" },
118 "callParticipants": participants,
119 "initiator": user(sender_id),
120 }))
121 }
122
123 fn recording_detail(content: &str) -> Option<Value> {
124 let status = element_attribute(content, "RecordingStatus", "status")?;
125 let status = match status.to_ascii_lowercase().as_str() {
126 "started" | "initial" => "initial",
127 "chunkfinished" => "chunkFinished",
128 "success" => "success",
129 _ => return None,
130 };
131 let name = element_attribute(content, "OriginalName", "v")
132 .map(unescape)
133 .or_else(|| tag_text(content, "Title").map(unescape));
134 Some(json!({
135 "@odata.type": RECORDING_TYPE,
136 "callId": identifier(content, "callId")?,
137 "callRecordingStatus": status,
138 "callRecordingDisplayName": name,
139 "callRecordingUrl": element_attribute(content, "a", "href").map(unescape),
140 "callRecordingDuration": element_attribute(content, "RecordingContent", "duration").and_then(iso_duration),
141 "meetingOrganizer": user(element_attribute(content, "MeetingOrganizerId", "value")),
142 "initiator": user(element_attribute(content, "RecordingInitiatorId", "value")),
143 }))
144 }
145
146 fn transcript_detail(content: &str) -> Option<Value> {
147 let call_id =
148 identifier(content, "callId").or_else(|| tag_text(content, "callId").map(str::trim))?;
149 Some(json!({
150 "@odata.type": TRANSCRIPT_TYPE,
151 "callId": call_id,
152 "meetingOrganizer": user(element_attribute(content, "MeetingOrganizerId", "value")),
153 }))
154 }
155
156 fn added_detail(content: &str) -> Option<Value> {
157 let members = targets(content);
158 if members.as_array().is_none_or(Vec::is_empty) {
159 return None;
160 }
161 let visible_from = tag_text(content, "sharehistorytime")
162 .and_then(|time| time.trim().parse::<i64>().ok())
163 .and_then(|millis| match millis {
164 0 => Some(ALL_HISTORY.to_owned()),
165 millis if millis > 0 => {
166 DateTime::<Utc>::from_timestamp_millis(millis).map(|time| time.to_rfc3339())
167 }
168 _ => None,
169 });
170 Some(json!({
171 "@odata.type": MEMBERS_ADDED_TYPE,
172 "members": members,
173 "initiator": user(tag_text(content, "initiator")),
174 "visibleHistoryStartDateTime": visible_from,
175 }))
176 }
177
178 fn left_detail(content: &str) -> Option<Value> {
179 let detail: Value = serde_json::from_str(content).ok()?;
180 let members: Vec<Value> = detail["members"]
181 .as_array()?
182 .iter()
183 .filter_map(|member| {
184 let id = member["id"].as_str()?;
185 let name = member["friendlyname"]
186 .as_str()
187 .filter(|name| !name.is_empty());
188 Some(json!({"id": user_id(id), "displayName": name}))
189 })
190 .collect();
191 (!members.is_empty()).then(|| {
192 json!({
193 "@odata.type": MEMBERS_LEFT_TYPE,
194 "members": members,
195 "initiator": user(detail["initiator"].as_str()),
196 })
197 })
198 }
199
200 fn targets(content: &str) -> Value {
201 Value::Array(
202 tag_texts(content, "target")
203 .into_iter()
204 .map(str::trim)
205 .filter(|target| target.starts_with("8:"))
206 .map(|target| json!({"id": user_id(target), "displayName": null}))
207 .collect(),
208 )
209 }
210
211 fn user(mri: Option<&str>) -> Value {
212 match mri.map(str::trim).filter(|mri| !mri.is_empty()) {
213 Some(mri) => json!({"user": {"id": user_id(mri), "displayName": null}}),
214 None => Value::Null,
215 }
216 }
217
218 /// Graph names people and bots by the id after the last `:` of the MRI (`8:orgid:`, `28:`, `8:teamsvisitor:`).
219 pub fn user_id(mri: &str) -> &str {
220 mri.rsplit(':').next().unwrap_or(mri)
221 }
222
223 fn has_flag(content: &str, name: &str) -> bool {
224 content.contains(&format!("<{name}/>")) || content.contains(&format!("<{name} />"))
225 }
226
227 fn iso_duration(text: &str) -> Option<String> {
228 let mut parts = text.split(':').rev();
229 let seconds: f64 = parts.next()?.parse().ok()?;
230 let minutes: u64 = parts.next().map_or(Some(0), |part| part.parse().ok())?;
231 let hours: u64 = parts.next().map_or(Some(0), |part| part.parse().ok())?;
232 Some(format!("PT{hours}H{minutes}M{}S", seconds.round() as u64))
233 }
234
235 pub fn tag_text<'a>(content: &'a str, tag: &str) -> Option<&'a str> {
236 tag_texts(content, tag).into_iter().next()
237 }
238
239 fn tag_texts<'a>(content: &'a str, tag: &str) -> Vec<&'a str> {
240 let open = format!("<{tag}>");
241 let close = format!("</{tag}>");
242 let mut found = Vec::new();
243 let mut rest = content;
244 while let Some(start) = rest.find(&open) {
245 let after = &rest[start + open.len()..];
246 let Some(end) = after.find(&close) else {
247 break;
248 };
249 found.push(&after[..end]);
250 rest = &after[end + close.len()..];
251 }
252 found
253 }
254
255 fn element_attribute<'a>(content: &'a str, element: &str, name: &str) -> Option<&'a str> {
256 let open = format!("<{element} ");
257 let start = content.find(&open)?;
258 let tag_end = content[start..].find('>')? + start;
259 attribute(&content[start..tag_end], name)
260 }
261
262 fn identifier<'a>(content: &'a str, kind: &str) -> Option<&'a str> {
263 let marker = format!("type=\"{kind}\"");
264 let mut rest = content;
265 while let Some(start) = rest.find("<Id ") {
266 let tag_end = rest[start..].find('>')? + start;
267 let tag = &rest[start..tag_end];
268 if tag.contains(&marker) {
269 return attribute(tag, "value").filter(|value| !value.is_empty());
270 }
271 rest = &rest[tag_end..];
272 }
273 None
274 }
275
276 pub fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
277 let mut search = 0;
278 while let Some(found) = tag[search..].find(name) {
279 let start = search + found;
280 let before = tag[..start].chars().last();
281 let after = &tag[start + name.len()..];
282 if before.is_some_and(char::is_whitespace)
283 && let Some(value) = after.strip_prefix("=\"")
284 {
285 return value.find('"').map(|end| &value[..end]);
286 }
287 search = start + name.len();
288 }
289 None
290 }
291
292 pub fn unescape(text: &str) -> String {
293 text.replace("&lt;", "<")
294 .replace("&gt;", ">")
295 .replace("&quot;", "\"")
296 .replace("&apos;", "'")
297 .replace("&#39;", "'")
298 .replace("&nbsp;", " ")
299 .replace("&amp;", "&")
300 }
301
302 #[cfg(test)]
303 mod tests {
304 use serde_json::json;
305
306 use super::*;
307
308 #[test]
309 fn a_recording_page_reads_like_a_graph_page() {
310 let content = r#"<URIObject type="Video.2/CallRecording.1"><RecordingStatus status="Success" code="200"></RecordingStatus><a href="https://contoso.sharepoint.com/:v:/rec">Play</a><OriginalName v="Daily.mp4" /><Identifiers><Id type="callId" value="call-1" /></Identifiers></URIObject>"#;
311 let page = json!({"messages": [
312 {"id": "1751975663649", "messagetype": "RichText/Media_CallRecording", "content": content, "originalarrivaltime": "2026-11-04T10:32:30.000Z", "from": "https://x/contacts/8:orgid:ann"},
313 {"id": "1751975663650", "messagetype": "RichText/Html", "content": "<p>hi</p>"},
314 ]});
315 let graph = graph_event_page("19:a@thread.v2", &page);
316 let events = graph["value"].as_array().unwrap();
317 assert_eq!(events.len(), 1);
318 assert_eq!(events[0]["id"], "1751975663649");
319 assert_eq!(
320 events[0]["eventDetail"]["callRecordingUrl"],
321 "https://contoso.sharepoint.com/:v:/rec"
322 );
323 assert_eq!(events[0]["createdDateTime"], "2026-11-04T10:32:30+00:00");
324 }
325
326 #[test]
327 fn pins_and_file_events_are_left_out() {
328 assert!(
329 event_detail(
330 "ThreadActivity/PinnedItemsUpdate",
331 "{}",
332 "19:a@thread.v2",
333 None
334 )
335 .is_none()
336 );
337 assert_eq!(json!(null), user(Some(" ")));
338 }
339 }
@@ -0,0 +1,339 @@
1use chrono::{DateTime, Utc};
2use serde_json::{Value, json};
3
4const STARTED_TYPE: &str = "#microsoft.graph.callStartedEventMessageDetail";
5const ENDED_TYPE: &str = "#microsoft.graph.callEndedEventMessageDetail";
6const RECORDING_TYPE: &str = "#microsoft.graph.callRecordingEventMessageDetail";
7const TRANSCRIPT_TYPE: &str = "#microsoft.graph.callTranscriptEventMessageDetail";
8const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
9const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
10const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
11const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";
12const MEETING_CHAT_PREFIX: &str = "19:meeting_";
13const ALL_HISTORY: &str = "0001-01-01T00:00:00Z";
14
15/// The Graph `eventDetail` of a chat service system message; `None` for events Graph does not list.
16pub fn event_detail(
17 message_type: &str,
18 content: &str,
19 conversation_id: &str,
20 sender_id: Option<&str>,
21) -> Option<Value> {
22 match message_type {
23 "Event/Call" => call_detail(content, conversation_id, sender_id),
24 "RichText/Media_CallRecording" => recording_detail(content),
25 "RichText/Media_CallTranscript" => transcript_detail(content),
26 "ThreadActivity/AddMember" => added_detail(content),
27 "ThreadActivity/DeleteMember" => Some(json!({
28 "@odata.type": MEMBERS_DELETED_TYPE,
29 "members": targets(content),
30 "initiator": user(tag_text(content, "initiator")),
31 })),
32 "ThreadActivity/MemberLeft" => left_detail(content),
33 "ThreadActivity/TopicUpdate" if !conversation_id.starts_with(MEETING_CHAT_PREFIX) => {
34 Some(json!({
35 "@odata.type": CHAT_RENAMED_TYPE,
36 "chatDisplayName": tag_text(content, "value").map(|topic| unescape(topic.trim())),
37 "initiator": user(tag_text(content, "initiator")),
38 }))
39 }
40 _ => None,
41 }
42}
43
44/// The recording and call events of a chat service message page, as a Graph `{"value": [...]}` page.
45pub fn graph_event_page(conversation_id: &str, chatsvc_page: &Value) -> Value {
46 let events: Vec<Value> = chatsvc_page["messages"]
47 .as_array()
48 .into_iter()
49 .flatten()
50 .filter_map(|message| {
51 let message_type = message["messagetype"].as_str()?;
52 if !is_event(message_type) {
53 return None;
54 }
55 let sender_id = message["from"]
56 .as_str()
57 .map(|from| user_id(from.rsplit('/').next().unwrap_or(from)));
58 let detail = event_detail(
59 message_type,
60 message["content"].as_str().unwrap_or_default(),
61 conversation_id,
62 sender_id,
63 )?;
64 let created = ["originalarrivaltime", "composetime"]
65 .iter()
66 .find_map(|key| message[*key].as_str())
67 .and_then(|stamp| DateTime::parse_from_rfc3339(stamp).ok())
68 .map(|stamp| stamp.with_timezone(&Utc).to_rfc3339());
69 Some(json!({
70 "id": crate::json_id::id_text(&message["id"])?,
71 "createdDateTime": created,
72 "eventDetail": detail,
73 }))
74 })
75 .collect();
76 json!({"value": events})
77}
78
79pub fn is_event(message_type: &str) -> bool {
80 message_type == "Event/Call"
81 || message_type.starts_with("ThreadActivity/")
82 || message_type == "RichText/Media_CallRecording"
83 || message_type == "RichText/Media_CallTranscript"
84}
85
86fn call_detail(content: &str, conversation_id: &str, sender_id: Option<&str>) -> Option<Value> {
87 let kind = if has_flag(content, "ended") {
88 ENDED_TYPE
89 } else {
90 STARTED_TYPE
91 };
92 let parts: Vec<&str> = content.split("<part ").skip(1).collect();
93 let participants: Vec<Value> = parts
94 .iter()
95 .filter_map(|part| {
96 let identity = attribute(&format!(" {part}"), "identity")?.to_owned();
97 let name = tag_text(part, "displayName")
98 .map(|name| unescape(name.trim()))
99 .filter(|name| !name.is_empty());
100 Some(json!({"participant": {"user": {"id": user_id(&identity), "displayName": name}}}))
101 })
102 .collect();
103 let longest = parts
104 .iter()
105 .filter_map(|part| tag_text(part, "duration")?.trim().parse::<f64>().ok())
106 .fold(None, |longest: Option<f64>, seconds| {
107 Some(longest.map_or(seconds, |known| known.max(seconds)))
108 });
109 let event_type = tag_text(content, "callEventType").unwrap_or_default();
110 let meeting = event_type.to_ascii_lowercase().contains("meeting")
111 || conversation_id.starts_with(MEETING_CHAT_PREFIX)
112 || tag_text(content, "meetingType").is_some_and(|kind| !kind.trim().is_empty());
113 Some(json!({
114 "@odata.type": kind,
115 "callId": tag_text(content, "callId")?.trim(),
116 "callDuration": longest.map(|seconds| format!("PT{}S", seconds.round() as u64)),
117 "callEventType": if meeting { "meeting" } else { "call" },
118 "callParticipants": participants,
119 "initiator": user(sender_id),
120 }))
121}
122
123fn recording_detail(content: &str) -> Option<Value> {
124 let status = element_attribute(content, "RecordingStatus", "status")?;
125 let status = match status.to_ascii_lowercase().as_str() {
126 "started" | "initial" => "initial",
127 "chunkfinished" => "chunkFinished",
128 "success" => "success",
129 _ => return None,
130 };
131 let name = element_attribute(content, "OriginalName", "v")
132 .map(unescape)
133 .or_else(|| tag_text(content, "Title").map(unescape));
134 Some(json!({
135 "@odata.type": RECORDING_TYPE,
136 "callId": identifier(content, "callId")?,
137 "callRecordingStatus": status,
138 "callRecordingDisplayName": name,
139 "callRecordingUrl": element_attribute(content, "a", "href").map(unescape),
140 "callRecordingDuration": element_attribute(content, "RecordingContent", "duration").and_then(iso_duration),
141 "meetingOrganizer": user(element_attribute(content, "MeetingOrganizerId", "value")),
142 "initiator": user(element_attribute(content, "RecordingInitiatorId", "value")),
143 }))
144}
145
146fn transcript_detail(content: &str) -> Option<Value> {
147 let call_id =
148 identifier(content, "callId").or_else(|| tag_text(content, "callId").map(str::trim))?;
149 Some(json!({
150 "@odata.type": TRANSCRIPT_TYPE,
151 "callId": call_id,
152 "meetingOrganizer": user(element_attribute(content, "MeetingOrganizerId", "value")),
153 }))
154}
155
156fn added_detail(content: &str) -> Option<Value> {
157 let members = targets(content);
158 if members.as_array().is_none_or(Vec::is_empty) {
159 return None;
160 }
161 let visible_from = tag_text(content, "sharehistorytime")
162 .and_then(|time| time.trim().parse::<i64>().ok())
163 .and_then(|millis| match millis {
164 0 => Some(ALL_HISTORY.to_owned()),
165 millis if millis > 0 => {
166 DateTime::<Utc>::from_timestamp_millis(millis).map(|time| time.to_rfc3339())
167 }
168 _ => None,
169 });
170 Some(json!({
171 "@odata.type": MEMBERS_ADDED_TYPE,
172 "members": members,
173 "initiator": user(tag_text(content, "initiator")),
174 "visibleHistoryStartDateTime": visible_from,
175 }))
176}
177
178fn left_detail(content: &str) -> Option<Value> {
179 let detail: Value = serde_json::from_str(content).ok()?;
180 let members: Vec<Value> = detail["members"]
181 .as_array()?
182 .iter()
183 .filter_map(|member| {
184 let id = member["id"].as_str()?;
185 let name = member["friendlyname"]
186 .as_str()
187 .filter(|name| !name.is_empty());
188 Some(json!({"id": user_id(id), "displayName": name}))
189 })
190 .collect();
191 (!members.is_empty()).then(|| {
192 json!({
193 "@odata.type": MEMBERS_LEFT_TYPE,
194 "members": members,
195 "initiator": user(detail["initiator"].as_str()),
196 })
197 })
198}
199
200fn targets(content: &str) -> Value {
201 Value::Array(
202 tag_texts(content, "target")
203 .into_iter()
204 .map(str::trim)
205 .filter(|target| target.starts_with("8:"))
206 .map(|target| json!({"id": user_id(target), "displayName": null}))
207 .collect(),
208 )
209}
210
211fn user(mri: Option<&str>) -> Value {
212 match mri.map(str::trim).filter(|mri| !mri.is_empty()) {
213 Some(mri) => json!({"user": {"id": user_id(mri), "displayName": null}}),
214 None => Value::Null,
215 }
216}
217
218/// Graph names people and bots by the id after the last `:` of the MRI (`8:orgid:`, `28:`, `8:teamsvisitor:`).
219pub fn user_id(mri: &str) -> &str {
220 mri.rsplit(':').next().unwrap_or(mri)
221}
222
223fn has_flag(content: &str, name: &str) -> bool {
224 content.contains(&format!("<{name}/>")) || content.contains(&format!("<{name} />"))
225}
226
227fn iso_duration(text: &str) -> Option<String> {
228 let mut parts = text.split(':').rev();
229 let seconds: f64 = parts.next()?.parse().ok()?;
230 let minutes: u64 = parts.next().map_or(Some(0), |part| part.parse().ok())?;
231 let hours: u64 = parts.next().map_or(Some(0), |part| part.parse().ok())?;
232 Some(format!("PT{hours}H{minutes}M{}S", seconds.round() as u64))
233}
234
235pub fn tag_text<'a>(content: &'a str, tag: &str) -> Option<&'a str> {
236 tag_texts(content, tag).into_iter().next()
237}
238
239fn tag_texts<'a>(content: &'a str, tag: &str) -> Vec<&'a str> {
240 let open = format!("<{tag}>");
241 let close = format!("</{tag}>");
242 let mut found = Vec::new();
243 let mut rest = content;
244 while let Some(start) = rest.find(&open) {
245 let after = &rest[start + open.len()..];
246 let Some(end) = after.find(&close) else {
247 break;
248 };
249 found.push(&after[..end]);
250 rest = &after[end + close.len()..];
251 }
252 found
253}
254
255fn element_attribute<'a>(content: &'a str, element: &str, name: &str) -> Option<&'a str> {
256 let open = format!("<{element} ");
257 let start = content.find(&open)?;
258 let tag_end = content[start..].find('>')? + start;
259 attribute(&content[start..tag_end], name)
260}
261
262fn identifier<'a>(content: &'a str, kind: &str) -> Option<&'a str> {
263 let marker = format!("type=\"{kind}\"");
264 let mut rest = content;
265 while let Some(start) = rest.find("<Id ") {
266 let tag_end = rest[start..].find('>')? + start;
267 let tag = &rest[start..tag_end];
268 if tag.contains(&marker) {
269 return attribute(tag, "value").filter(|value| !value.is_empty());
270 }
271 rest = &rest[tag_end..];
272 }
273 None
274}
275
276pub fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
277 let mut search = 0;
278 while let Some(found) = tag[search..].find(name) {
279 let start = search + found;
280 let before = tag[..start].chars().last();
281 let after = &tag[start + name.len()..];
282 if before.is_some_and(char::is_whitespace)
283 && let Some(value) = after.strip_prefix("=\"")
284 {
285 return value.find('"').map(|end| &value[..end]);
286 }
287 search = start + name.len();
288 }
289 None
290}
291
292pub fn unescape(text: &str) -> String {
293 text.replace("&lt;", "<")
294 .replace("&gt;", ">")
295 .replace("&quot;", "\"")
296 .replace("&apos;", "'")
297 .replace("&#39;", "'")
298 .replace("&nbsp;", " ")
299 .replace("&amp;", "&")
300}
301
302#[cfg(test)]
303mod tests {
304 use serde_json::json;
305
306 use super::*;
307
308 #[test]
309 fn a_recording_page_reads_like_a_graph_page() {
310 let content = r#"<URIObject type="Video.2/CallRecording.1"><RecordingStatus status="Success" code="200"></RecordingStatus><a href="https://contoso.sharepoint.com/:v:/rec">Play</a><OriginalName v="Daily.mp4" /><Identifiers><Id type="callId" value="call-1" /></Identifiers></URIObject>"#;
311 let page = json!({"messages": [
312 {"id": "1751975663649", "messagetype": "RichText/Media_CallRecording", "content": content, "originalarrivaltime": "2026-11-04T10:32:30.000Z", "from": "https://x/contacts/8:orgid:ann"},
313 {"id": "1751975663650", "messagetype": "RichText/Html", "content": "<p>hi</p>"},
314 ]});
315 let graph = graph_event_page("19:a@thread.v2", &page);
316 let events = graph["value"].as_array().unwrap();
317 assert_eq!(events.len(), 1);
318 assert_eq!(events[0]["id"], "1751975663649");
319 assert_eq!(
320 events[0]["eventDetail"]["callRecordingUrl"],
321 "https://contoso.sharepoint.com/:v:/rec"
322 );
323 assert_eq!(events[0]["createdDateTime"], "2026-11-04T10:32:30+00:00");
324 }
325
326 #[test]
327 fn pins_and_file_events_are_left_out() {
328 assert!(
329 event_detail(
330 "ThreadActivity/PinnedItemsUpdate",
331 "{}",
332 "19:a@thread.v2",
333 None
334 )
335 .is_none()
336 );
337 assert_eq!(json!(null), user(Some(" ")));
338 }
339}
crates/chatsvc/src/json_id.rs +1 −1
@@ -1,6 +1,6 @@
1 1 use serde_json::{Number, Value};
2 2
3 pub(crate) fn id_text(value: &Value) -> Option<String> {
3 pub fn id_text(value: &Value) -> Option<String> {
4 4 match value {
5 5 Value::String(text) if !text.is_empty() => Some(text.clone()),
6 6 Value::Number(number) => Some(integer_text(number)),
@@ -1,6 +1,6 @@
1use serde_json::{Number, Value};
1use serde_json::{Number, Value};
2
2
3pub(crate) fn id_text(value: &Value) -> Option<String> {
3pub fn id_text(value: &Value) -> Option<String> {
4 match value {
4 match value {
5 Value::String(text) if !text.is_empty() => Some(text.clone()),
5 Value::String(text) if !text.is_empty() => Some(text.clone()),
6 Value::Number(number) => Some(integer_text(number)),
6 Value::Number(number) => Some(integer_text(number)),
crates/chatsvc/src/lib.rs +7 −1
@@ -7,6 +7,7 @@ pub mod calllog;
7 7 pub mod cards;
8 8 pub mod channel_notifications;
9 9 pub mod channel_visibility;
10 pub mod chat_listing;
10 11 pub mod chat_notifications;
11 12 pub mod chat_settings;
12 13 pub mod compose_copilot;
@@ -18,7 +19,9 @@ mod error;
18 19 pub mod forward;
19 20 pub mod gifs;
20 21 pub mod google_calendar;
22 pub mod graph_events;
21 23 mod json_id;
24 pub use json_id::id_text;
22 25 pub mod language_settings;
23 26 pub mod links;
24 27 mod mask;
@@ -44,6 +47,7 @@ pub mod teams_cdn;
44 47 pub mod thread_activity;
45 48 pub mod transcripts;
46 49 pub mod translate;
50 pub mod user_profiles;
47 51 pub mod window;
48 52
49 53 pub use activity_feed::{
@@ -63,6 +67,7 @@ pub use cards::{
63 67 };
64 68 pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
65 69 pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
70 pub use chat_listing::{ChatListing, ConversationPage, MessagePage, aggregator_chat};
66 71 pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};
67 72 pub use chat_settings::{
68 73 ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,
@@ -85,7 +90,7 @@ pub use language_settings::{
85 90 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
86 91 parse_language_settings, target_patch,
87 92 };
88 pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
93 pub use links::{LinkImage, LinkInfo, MessageLinks, hosted_content_image_url, is_link_image_url};
89 94 pub use mask::mask_conversation_id;
90 95 pub use members::{
91 96 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
@@ -136,4 +141,5 @@ pub use translate::{
136 141 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
137 142 TranslationStatus, TranslationTrigger, Translator, language_code,
138 143 };
144 pub use user_profiles::{UserProfile, UserProfiles};
139 145 pub use window::{MessageWindow, WindowDirection};
@@ -7,6 +7,7 @@ pub mod calllog;
7pub mod cards;
7pub mod cards;
8pub mod channel_notifications;
8pub mod channel_notifications;
9pub mod channel_visibility;
9pub mod channel_visibility;
10pub mod chat_listing;
10pub mod chat_notifications;
11pub mod chat_notifications;
11pub mod chat_settings;
12pub mod chat_settings;
12pub mod compose_copilot;
13pub mod compose_copilot;
@@ -18,7 +19,9 @@ mod error;
18pub mod forward;
19pub mod forward;
19pub mod gifs;
20pub mod gifs;
20pub mod google_calendar;
21pub mod google_calendar;
22pub mod graph_events;
21mod json_id;
23mod json_id;
24pub use json_id::id_text;
22pub mod language_settings;
25pub mod language_settings;
23pub mod links;
26pub mod links;
24mod mask;
27mod mask;
@@ -44,6 +47,7 @@ pub mod teams_cdn;
44pub mod thread_activity;
47pub mod thread_activity;
45pub mod transcripts;
48pub mod transcripts;
46pub mod translate;
49pub mod translate;
50pub mod user_profiles;
47pub mod window;
51pub mod window;
48
52
49pub use activity_feed::{
53pub use activity_feed::{
@@ -63,6 +67,7 @@ pub use cards::{
63};
67};
64pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
68pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
65pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
69pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
70pub use chat_listing::{ChatListing, ConversationPage, MessagePage, aggregator_chat};
66pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};
71pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};
67pub use chat_settings::{
72pub use chat_settings::{
68 ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,
73 ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,
@@ -85,7 +90,7 @@ pub use language_settings::{
85 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
90 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
86 parse_language_settings, target_patch,
91 parse_language_settings, target_patch,
87};
92};
88pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
93pub use links::{LinkImage, LinkInfo, MessageLinks, hosted_content_image_url, is_link_image_url};
89pub use mask::mask_conversation_id;
94pub use mask::mask_conversation_id;
90pub use members::{
95pub use members::{
91 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
96 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
@@ -136,4 +141,5 @@ pub use translate::{
136 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
141 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
137 TranslationStatus, TranslationTrigger, Translator, language_code,
142 TranslationStatus, TranslationTrigger, Translator, language_code,
138};
143};
144pub use user_profiles::{UserProfile, UserProfiles};
139pub use window::{MessageWindow, WindowDirection};
145pub use window::{MessageWindow, WindowDirection};
crates/chatsvc/src/members.rs +63 −1
@@ -1,7 +1,7 @@
1 1 use serde_json::{Value, json};
2 2 use session::{Method, Request, Session};
3 3
4 use crate::error::Result;
4 use crate::error::{Error, Result};
5 5 use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6 6 use crate::pins::DEFAULT_REGION;
7 7
@@ -83,6 +83,36 @@ pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Re
83 83 ))
84 84 }
85 85
86 pub fn create_group_request(region: &str, user_ids: &[String], topic: Option<&str>) -> Request {
87 let members: Vec<Value> = user_ids
88 .iter()
89 .map(|user_id| json!({"id": user_mri(user_id), "role": MEMBER_ROLE}))
90 .collect();
91 let mut properties = json!({
92 "threadType": "chat",
93 "fixedRoster": false,
94 "uniquerosterthread": false,
95 "chatFilesIndexId": "2",
96 });
97 if let Some(topic) = topic.map(str::trim).filter(|topic| !topic.is_empty()) {
98 properties["topic"] = json!(topic);
99 }
100 Request::with_body(
101 Method::Post,
102 threads_url(region),
103 json!({"members": members, "properties": properties}),
104 )
105 }
106
107 fn created_thread_id(body: &Value) -> Option<String> {
108 let location = body.get("location")?.as_str()?;
109 let last = location.split('?').next()?.rsplit('/').next()?;
110 let decoded = percent_encoding::percent_decode_str(last)
111 .decode_utf8()
112 .ok()?;
113 decoded.starts_with("19:").then(|| decoded.into_owned())
114 }
115
86 116 /// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.
87 117 pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {
88 118 Request::with_body(
@@ -147,6 +177,15 @@ impl<T: MessageTransport> ThreadMembers<T> {
147 177 ensure_success(&self.transport.send(request).await?)
148 178 }
149 179
180 /// Teams' `createThread` for a group chat; answers with the new thread id.
181 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
182 let request = create_group_request(&self.region, user_ids, topic);
183 let answer = self.transport.send(request).await?;
184 ensure_success(&answer)?;
185 created_thread_id(&answer.body)
186 .ok_or_else(|| Error::UnexpectedAnswer("thread creation has no location".into()))
187 }
188
150 189 pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {
151 190 let request = topic_request(&self.region, thread_id, topic);
152 191 ensure_success(&self.transport.send(request).await?)
@@ -155,6 +194,29 @@ impl<T: MessageTransport> ThreadMembers<T> {
155 194
156 195 #[cfg(test)]
157 196 mod tests {
197 #[test]
198 fn a_group_thread_lists_everyone_as_admin_and_reads_its_id_from_the_location() {
199 let request = create_group_request("emea", &["me".into(), "ann".into()], Some(" Plan "));
200 assert_eq!(
201 request.url,
202 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads"
203 );
204 let body = request.body.unwrap();
205 assert_eq!(
206 body["members"][1],
207 json!({"id": "8:orgid:ann", "role": "Admin"})
208 );
209 assert_eq!(body["properties"]["topic"], "Plan");
210 assert_eq!(
211 created_thread_id(&json!({"location": "https://emea.ng.msg.teams.microsoft.com/v1/threads/19%3Aabc%40thread.v2"})).as_deref(),
212 Some("19:abc@thread.v2")
213 );
214 assert_eq!(
215 created_thread_id(&json!({"location": "https://x/v1/threads/oops"})),
216 None
217 );
218 }
219
158 220 use std::sync::Mutex;
159 221
160 222 use session::ApiResponse;
@@ -1,7 +1,7 @@
1use serde_json::{Value, json};
1use serde_json::{Value, json};
2use session::{Method, Request, Session};
2use session::{Method, Request, Session};
3
3
4use crate::error::Result;
4use crate::error::{Error, Result};
5use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
5use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6use crate::pins::DEFAULT_REGION;
6use crate::pins::DEFAULT_REGION;
7
7
@@ -83,6 +83,36 @@ pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Re
83 ))
83 ))
84}
84}
85
85
86pub fn create_group_request(region: &str, user_ids: &[String], topic: Option<&str>) -> Request {
87 let members: Vec<Value> = user_ids
88 .iter()
89 .map(|user_id| json!({"id": user_mri(user_id), "role": MEMBER_ROLE}))
90 .collect();
91 let mut properties = json!({
92 "threadType": "chat",
93 "fixedRoster": false,
94 "uniquerosterthread": false,
95 "chatFilesIndexId": "2",
96 });
97 if let Some(topic) = topic.map(str::trim).filter(|topic| !topic.is_empty()) {
98 properties["topic"] = json!(topic);
99 }
100 Request::with_body(
101 Method::Post,
102 threads_url(region),
103 json!({"members": members, "properties": properties}),
104 )
105}
106
107fn created_thread_id(body: &Value) -> Option<String> {
108 let location = body.get("location")?.as_str()?;
109 let last = location.split('?').next()?.rsplit('/').next()?;
110 let decoded = percent_encoding::percent_decode_str(last)
111 .decode_utf8()
112 .ok()?;
113 decoded.starts_with("19:").then(|| decoded.into_owned())
114}
115
86/// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.
116/// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.
87pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {
117pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {
88 Request::with_body(
118 Request::with_body(
@@ -147,6 +177,15 @@ impl<T: MessageTransport> ThreadMembers<T> {
147 ensure_success(&self.transport.send(request).await?)
177 ensure_success(&self.transport.send(request).await?)
148 }
178 }
149
179
180 /// Teams' `createThread` for a group chat; answers with the new thread id.
181 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
182 let request = create_group_request(&self.region, user_ids, topic);
183 let answer = self.transport.send(request).await?;
184 ensure_success(&answer)?;
185 created_thread_id(&answer.body)
186 .ok_or_else(|| Error::UnexpectedAnswer("thread creation has no location".into()))
187 }
188
150 pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {
189 pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {
151 let request = topic_request(&self.region, thread_id, topic);
190 let request = topic_request(&self.region, thread_id, topic);
152 ensure_success(&self.transport.send(request).await?)
191 ensure_success(&self.transport.send(request).await?)
@@ -155,6 +194,29 @@ impl<T: MessageTransport> ThreadMembers<T> {
155
194
156#[cfg(test)]
195#[cfg(test)]
157mod tests {
196mod tests {
197 #[test]
198 fn a_group_thread_lists_everyone_as_admin_and_reads_its_id_from_the_location() {
199 let request = create_group_request("emea", &["me".into(), "ann".into()], Some(" Plan "));
200 assert_eq!(
201 request.url,
202 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads"
203 );
204 let body = request.body.unwrap();
205 assert_eq!(
206 body["members"][1],
207 json!({"id": "8:orgid:ann", "role": "Admin"})
208 );
209 assert_eq!(body["properties"]["topic"], "Plan");
210 assert_eq!(
211 created_thread_id(&json!({"location": "https://emea.ng.msg.teams.microsoft.com/v1/threads/19%3Aabc%40thread.v2"})).as_deref(),
212 Some("19:abc@thread.v2")
213 );
214 assert_eq!(
215 created_thread_id(&json!({"location": "https://x/v1/threads/oops"})),
216 None
217 );
218 }
219
158 use std::sync::Mutex;
220 use std::sync::Mutex;
159
221
160 use session::ApiResponse;
222 use session::ApiResponse;
crates/chatsvc/src/messages.rs +16 −1
@@ -140,9 +140,24 @@ impl<T: MessageTransport> Messages<T> {
140 140 conversation: &ConversationRef,
141 141 message_id: &str,
142 142 html: &str,
143 ) -> Result<()> {
144 self.edit_message_with_mentions(conversation, message_id, html, None)
145 .await
146 }
147
148 /// `mentions` is the JSON text of the chatsvc mention entries for the spans in `html`.
149 pub async fn edit_message_with_mentions(
150 &self,
151 conversation: &ConversationRef,
152 message_id: &str,
153 html: &str,
154 mentions: Option<&str>,
143 155 ) -> Result<()> {
144 156 let url = self.message_url(conversation, message_id);
145 let body = edit_body(message_id, html);
157 let mut body = edit_body(message_id, html);
158 if let Some(mentions) = mentions {
159 body["properties"]["mentions"] = json!(mentions);
160 }
146 161 let mut answer = self.put(&url, &body).await?;
147 162 if answer.status == 404 {
148 163 tokio::time::sleep(self.retry_delay).await;
@@ -140,9 +140,24 @@ impl<T: MessageTransport> Messages<T> {
140 conversation: &ConversationRef,
140 conversation: &ConversationRef,
141 message_id: &str,
141 message_id: &str,
142 html: &str,
142 html: &str,
143 ) -> Result<()> {
144 self.edit_message_with_mentions(conversation, message_id, html, None)
145 .await
146 }
147
148 /// `mentions` is the JSON text of the chatsvc mention entries for the spans in `html`.
149 pub async fn edit_message_with_mentions(
150 &self,
151 conversation: &ConversationRef,
152 message_id: &str,
153 html: &str,
154 mentions: Option<&str>,
143 ) -> Result<()> {
155 ) -> Result<()> {
144 let url = self.message_url(conversation, message_id);
156 let url = self.message_url(conversation, message_id);
145 let body = edit_body(message_id, html);
157 let mut body = edit_body(message_id, html);
158 if let Some(mentions) = mentions {
159 body["properties"]["mentions"] = json!(mentions);
160 }
146 let mut answer = self.put(&url, &body).await?;
161 let mut answer = self.put(&url, &body).await?;
147 if answer.status == 404 {
162 if answer.status == 404 {
148 tokio::time::sleep(self.retry_delay).await;
163 tokio::time::sleep(self.retry_delay).await;
crates/chatsvc/src/recap.rs +19 −70
@@ -6,19 +6,17 @@ use chrono::{DateTime, Utc};
6 6 use serde_json::Value;
7 7 use session::{Method, Request, Scope, Session};
8 8
9 use crate::graph_events::graph_event_page;
9 10 use crate::messages::encode;
10 use crate::pins::DEFAULT_REGION;
11 11 use crate::transcripts::{
12 TranscriptError, TranscriptTurn, Transcripts, newest_transcript, parse_transcript_list,
13 parse_turns, share_id, site_origin,
12 TranscriptError, TranscriptTurn, Transcripts, chatsvc_failure, newest_transcript,
13 parse_transcript_list, parse_turns, share_id, site_origin,
14 14 };
15 15
16 16 const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail";
17 17 const RECORDING_SUCCESS: &str = "success";
18 const MESSAGES_SCOPE: &str = "Chat.Read";
19 18 const SITE_SCOPE: &str = ".default";
20 19 const ATTENDANCE_SCOPE: &str = "OnlineMeetingArtifact.Read.All";
21 const MAX_MESSAGE_PAGES: usize = 40;
22 20 const AUDIO_ONLY_MARKER: &str = "videoContent=\"CurtainOnly\"";
23 21 const ORIGINAL_NAME_OPEN: &str = "<OriginalName v=\"";
24 22
@@ -86,58 +84,20 @@ impl<'a> Recap<'a> {
86 84 }
87 85
88 86 pub async fn occurrences(&self, thread_id: &str) -> Result<Vec<Occurrence>, TranscriptError> {
89 let scope = Scope::graph(MESSAGES_SCOPE);
90 let mut url = format!(
91 "{}/v1.0/chats/{}/messages?$top=50&$orderby=createdDateTime desc",
92 session::GRAPH,
93 encode(thread_id)
94 );
95 87 let mut found = Vec::new();
96 for _ in 0..MAX_MESSAGE_PAGES {
97 let page = self
98 .transcripts
99 .get(&url, &scope, TranscriptError::NoRecording)
100 .await?;
101 found.extend(parse_occurrences(&page));
102 match page.get("@odata.nextLink").and_then(Value::as_str) {
103 Some(next) => url = next.to_owned(),
104 None => break,
105 }
106 }
107 let audio_only_names = self.audio_only_names(thread_id).await;
88 let mut audio_only_names = HashSet::new();
89 self.transcripts
90 .visit_message_pages(thread_id, |page| {
91 found.extend(parse_occurrences(&graph_event_page(thread_id, page)));
92 audio_only_names.extend(parse_audio_only_names(page));
93 false
94 })
95 .await?;
108 96 let occurrences = sorted_occurrences(with_audio_only(found, &audio_only_names));
109 97 let deleted = self.deleted_recordings(&occurrences).await;
110 98 Ok(without_deleted(occurrences, &deleted))
111 99 }
112 100
113 async fn audio_only_names(&self, thread_id: &str) -> HashSet<String> {
114 let scope = Scope::new(session::IC3, "Teams.AccessAsUser.All");
115 let mut url = format!(
116 "https://teams.cloud.microsoft/api/chatsvc/{DEFAULT_REGION}/v1/users/ME/conversations/{}/messages?view=msnp24Equivalent&pageSize=200",
117 encode(thread_id)
118 );
119 let mut names = HashSet::new();
120 for _ in 0..MAX_MESSAGE_PAGES {
121 let Ok(page) = self
122 .transcripts
123 .get(&url, &scope, TranscriptError::NoRecording)
124 .await
125 else {
126 break;
127 };
128 names.extend(parse_audio_only_names(&page));
129 match page
130 .pointer("/_metadata/backwardLink")
131 .and_then(Value::as_str)
132 .filter(|link| !link.is_empty() && *link != url)
133 {
134 Some(next) => url = next.to_owned(),
135 None => break,
136 }
137 }
138 names
139 }
140
141 101 async fn deleted_recordings(&self, occurrences: &[Occurrence]) -> HashSet<String> {
142 102 let mut deleted = HashSet::new();
143 103 let sites: BTreeSet<String> = occurrences
@@ -281,28 +241,17 @@ impl<'a> Recap<'a> {
281 241 }
282 242
283 243 pub async fn attendance(&self, thread_id: &str) -> Result<Attendance, TranscriptError> {
284 let graph_scope = Scope::graph(MESSAGES_SCOPE);
285 let chat = match self
286 .transcripts
287 .get(
288 &format!(
289 "{}/v1.0/chats/{}?$select=onlineMeetingInfo",
290 session::GRAPH,
291 encode(thread_id)
292 ),
293 &graph_scope,
294 TranscriptError::NoRecording,
295 )
296 .await
297 {
244 let chat = match crate::chat_listing::aggregator_chat(self.session, thread_id).await {
298 245 Ok(chat) => chat,
299 Err(TranscriptError::NoRecording | TranscriptError::AccessDenied) => {
300 return Ok(Attendance::TurnedOff);
301 }
302 Err(error) => return Err(error),
246 Err(error) => match chatsvc_failure(error) {
247 TranscriptError::NoRecording | TranscriptError::AccessDenied => {
248 return Ok(Attendance::TurnedOff);
249 }
250 error => return Err(error),
251 },
303 252 };
304 253 let Some(join_url) = chat
305 .pointer("/onlineMeetingInfo/joinWebUrl")
254 .pointer("/meetingInformation/meetingJoinUrl")
306 255 .and_then(Value::as_str)
307 256 else {
308 257 return Ok(Attendance::TurnedOff);
@@ -6,19 +6,17 @@ use chrono::{DateTime, Utc};
6use serde_json::Value;
6use serde_json::Value;
7use session::{Method, Request, Scope, Session};
7use session::{Method, Request, Scope, Session};
8
8
9use crate::graph_events::graph_event_page;
9use crate::messages::encode;
10use crate::messages::encode;
10use crate::pins::DEFAULT_REGION;
11use crate::transcripts::{
11use crate::transcripts::{
12 TranscriptError, TranscriptTurn, Transcripts, newest_transcript, parse_transcript_list,
12 TranscriptError, TranscriptTurn, Transcripts, chatsvc_failure, newest_transcript,
13 parse_turns, share_id, site_origin,
13 parse_transcript_list, parse_turns, share_id, site_origin,
14};
14};
15
15
16const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail";
16const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail";
17const RECORDING_SUCCESS: &str = "success";
17const RECORDING_SUCCESS: &str = "success";
18const MESSAGES_SCOPE: &str = "Chat.Read";
19const SITE_SCOPE: &str = ".default";
18const SITE_SCOPE: &str = ".default";
20const ATTENDANCE_SCOPE: &str = "OnlineMeetingArtifact.Read.All";
19const ATTENDANCE_SCOPE: &str = "OnlineMeetingArtifact.Read.All";
21const MAX_MESSAGE_PAGES: usize = 40;
22const AUDIO_ONLY_MARKER: &str = "videoContent=\"CurtainOnly\"";
20const AUDIO_ONLY_MARKER: &str = "videoContent=\"CurtainOnly\"";
23const ORIGINAL_NAME_OPEN: &str = "<OriginalName v=\"";
21const ORIGINAL_NAME_OPEN: &str = "<OriginalName v=\"";
24
22
@@ -86,58 +84,20 @@ impl<'a> Recap<'a> {
86 }
84 }
87
85
88 pub async fn occurrences(&self, thread_id: &str) -> Result<Vec<Occurrence>, TranscriptError> {
86 pub async fn occurrences(&self, thread_id: &str) -> Result<Vec<Occurrence>, TranscriptError> {
89 let scope = Scope::graph(MESSAGES_SCOPE);
90 let mut url = format!(
91 "{}/v1.0/chats/{}/messages?$top=50&$orderby=createdDateTime desc",
92 session::GRAPH,
93 encode(thread_id)
94 );
95 let mut found = Vec::new();
87 let mut found = Vec::new();
96 for _ in 0..MAX_MESSAGE_PAGES {
88 let mut audio_only_names = HashSet::new();
97 let page = self
89 self.transcripts
98 .transcripts
90 .visit_message_pages(thread_id, |page| {
99 .get(&url, &scope, TranscriptError::NoRecording)
91 found.extend(parse_occurrences(&graph_event_page(thread_id, page)));
100 .await?;
92 audio_only_names.extend(parse_audio_only_names(page));
101 found.extend(parse_occurrences(&page));
93 false
102 match page.get("@odata.nextLink").and_then(Value::as_str) {
94 })
103 Some(next) => url = next.to_owned(),
95 .await?;
104 None => break,
105 }
106 }
107 let audio_only_names = self.audio_only_names(thread_id).await;
108 let occurrences = sorted_occurrences(with_audio_only(found, &audio_only_names));
96 let occurrences = sorted_occurrences(with_audio_only(found, &audio_only_names));
109 let deleted = self.deleted_recordings(&occurrences).await;
97 let deleted = self.deleted_recordings(&occurrences).await;
110 Ok(without_deleted(occurrences, &deleted))
98 Ok(without_deleted(occurrences, &deleted))
111 }
99 }
112
100
113 async fn audio_only_names(&self, thread_id: &str) -> HashSet<String> {
114 let scope = Scope::new(session::IC3, "Teams.AccessAsUser.All");
115 let mut url = format!(
116 "https://teams.cloud.microsoft/api/chatsvc/{DEFAULT_REGION}/v1/users/ME/conversations/{}/messages?view=msnp24Equivalent&pageSize=200",
117 encode(thread_id)
118 );
119 let mut names = HashSet::new();
120 for _ in 0..MAX_MESSAGE_PAGES {
121 let Ok(page) = self
122 .transcripts
123 .get(&url, &scope, TranscriptError::NoRecording)
124 .await
125 else {
126 break;
127 };
128 names.extend(parse_audio_only_names(&page));
129 match page
130 .pointer("/_metadata/backwardLink")
131 .and_then(Value::as_str)
132 .filter(|link| !link.is_empty() && *link != url)
133 {
134 Some(next) => url = next.to_owned(),
135 None => break,
136 }
137 }
138 names
139 }
140
141 async fn deleted_recordings(&self, occurrences: &[Occurrence]) -> HashSet<String> {
101 async fn deleted_recordings(&self, occurrences: &[Occurrence]) -> HashSet<String> {
142 let mut deleted = HashSet::new();
102 let mut deleted = HashSet::new();
143 let sites: BTreeSet<String> = occurrences
103 let sites: BTreeSet<String> = occurrences
@@ -281,28 +241,17 @@ impl<'a> Recap<'a> {
281 }
241 }
282
242
283 pub async fn attendance(&self, thread_id: &str) -> Result<Attendance, TranscriptError> {
243 pub async fn attendance(&self, thread_id: &str) -> Result<Attendance, TranscriptError> {
284 let graph_scope = Scope::graph(MESSAGES_SCOPE);
244 let chat = match crate::chat_listing::aggregator_chat(self.session, thread_id).await {
285 let chat = match self
286 .transcripts
287 .get(
288 &format!(
289 "{}/v1.0/chats/{}?$select=onlineMeetingInfo",
290 session::GRAPH,
291 encode(thread_id)
292 ),
293 &graph_scope,
294 TranscriptError::NoRecording,
295 )
296 .await
297 {
298 Ok(chat) => chat,
245 Ok(chat) => chat,
299 Err(TranscriptError::NoRecording | TranscriptError::AccessDenied) => {
246 Err(error) => match chatsvc_failure(error) {
300 return Ok(Attendance::TurnedOff);
247 TranscriptError::NoRecording | TranscriptError::AccessDenied => {
301 }
248 return Ok(Attendance::TurnedOff);
302 Err(error) => return Err(error),
249 }
250 error => return Err(error),
251 },
303 };
252 };
304 let Some(join_url) = chat
253 let Some(join_url) = chat
305 .pointer("/onlineMeetingInfo/joinWebUrl")
254 .pointer("/meetingInformation/meetingJoinUrl")
306 .and_then(Value::as_str)
255 .and_then(Value::as_str)
307 else {
256 else {
308 return Ok(Attendance::TurnedOff);
257 return Ok(Attendance::TurnedOff);
crates/chatsvc/src/transcripts.rs +53 −16
@@ -1,15 +1,19 @@
1 1 use base64::Engine as _;
2 2 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
3 use serde_json::Value;
3 use serde_json::{Value, json};
4 4 use session::{Scope, Session};
5 5
6 use crate::chat_listing::ChatListing;
7 use crate::error::Error;
8 use crate::graph_events::graph_event_page;
9 use crate::json_id::id_text;
6 10 use crate::messages::encode;
7 11
8 12 const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail";
9 13 const RECORDING_SUCCESS: &str = "success";
10 const MESSAGES_SCOPE: &str = "Chat.Read";
11 14 const SITE_SCOPE: &str = ".default";
12 15 const MAX_MESSAGE_PAGES: usize = 40;
16 const MESSAGE_PAGE_SIZE: usize = 200;
13 17 const UNKNOWN_SPEAKER: &str = "?";
14 18
15 19 #[derive(Debug, Clone, PartialEq)]
@@ -97,23 +101,45 @@ impl<'a> Transcripts<'a> {
97 101 }
98 102
99 103 async fn find_recording(&self, thread_id: &str) -> Result<Recording, TranscriptError> {
100 let scope = Scope::graph(MESSAGES_SCOPE);
101 let mut url = format!(
102 "{}/v1.0/chats/{}/messages?$top=50&$orderby=createdDateTime desc",
103 session::GRAPH,
104 encode(thread_id)
105 );
106 for _ in 0..MAX_MESSAGE_PAGES {
107 let page = self.get(&url, &scope, TranscriptError::NoRecording).await?;
108 if let Some(recording) = find_recording(&page) {
109 return Ok(recording);
104 let mut recording = None;
105 self.visit_message_pages(thread_id, |page| {
106 recording = find_recording(&graph_event_page(thread_id, page));
107 recording.is_some()
108 })
109 .await?;
110 recording.ok_or(TranscriptError::NoRecording)
111 }
112
113 /// Chat service message pages, newest arrival first, until `visit` returns true.
114 pub(crate) async fn visit_message_pages(
115 &self,
116 thread_id: &str,
117 mut visit: impl FnMut(&Value) -> bool,
118 ) -> Result<(), TranscriptError> {
119 let listing = ChatListing::new(self.session);
120 let mut before_ms = None;
121 for page_index in 0..MAX_MESSAGE_PAGES {
122 let page = match listing
123 .messages(thread_id, before_ms, MESSAGE_PAGE_SIZE)
124 .await
125 {
126 Ok(page) => page,
127 Err(error) if page_index == 0 => return Err(chatsvc_failure(error)),
128 Err(_) => break,
129 };
130 if visit(&json!({"messages": page.messages})) {
131 break;
110 132 }
111 match page.get("@odata.nextLink").and_then(Value::as_str) {
112 Some(next) => url = next.to_owned(),
113 None => break,
133 before_ms = page
134 .messages
135 .iter()
136 .filter_map(|message| id_text(&message["id"])?.parse::<i64>().ok())
137 .min();
138 if !page.has_older || before_ms.is_none() {
139 break;
114 140 }
115 141 }
116 Err(TranscriptError::NoRecording)
142 Ok(())
117 143 }
118 144
119 145 async fn item_url(
@@ -165,6 +191,17 @@ impl<'a> Transcripts<'a> {
165 191 }
166 192 }
167 193
194 pub(crate) fn chatsvc_failure(error: Error) -> TranscriptError {
195 match error {
196 Error::Session(session::Error::Api {
197 status: 403 | 401, ..
198 }) => TranscriptError::AccessDenied,
199 Error::Session(session::Error::Api { status: 404, .. }) => TranscriptError::NoRecording,
200 Error::Session(error) => TranscriptError::Request(error),
201 _ => TranscriptError::NoRecording,
202 }
203 }
204
168 205 pub fn find_recording(messages_json: &Value) -> Option<Recording> {
169 206 messages_json
170 207 .get("value")?
@@ -1,15 +1,19 @@
1use base64::Engine as _;
1use base64::Engine as _;
2use base64::engine::general_purpose::URL_SAFE_NO_PAD;
2use base64::engine::general_purpose::URL_SAFE_NO_PAD;
3use serde_json::Value;
3use serde_json::{Value, json};
4use session::{Scope, Session};
4use session::{Scope, Session};
5
5
6use crate::chat_listing::ChatListing;
7use crate::error::Error;
8use crate::graph_events::graph_event_page;
9use crate::json_id::id_text;
6use crate::messages::encode;
10use crate::messages::encode;
7
11
8const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail";
12const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail";
9const RECORDING_SUCCESS: &str = "success";
13const RECORDING_SUCCESS: &str = "success";
10const MESSAGES_SCOPE: &str = "Chat.Read";
11const SITE_SCOPE: &str = ".default";
14const SITE_SCOPE: &str = ".default";
12const MAX_MESSAGE_PAGES: usize = 40;
15const MAX_MESSAGE_PAGES: usize = 40;
16const MESSAGE_PAGE_SIZE: usize = 200;
13const UNKNOWN_SPEAKER: &str = "?";
17const UNKNOWN_SPEAKER: &str = "?";
14
18
15#[derive(Debug, Clone, PartialEq)]
19#[derive(Debug, Clone, PartialEq)]
@@ -97,23 +101,45 @@ impl<'a> Transcripts<'a> {
97 }
101 }
98
102
99 async fn find_recording(&self, thread_id: &str) -> Result<Recording, TranscriptError> {
103 async fn find_recording(&self, thread_id: &str) -> Result<Recording, TranscriptError> {
100 let scope = Scope::graph(MESSAGES_SCOPE);
104 let mut recording = None;
101 let mut url = format!(
105 self.visit_message_pages(thread_id, |page| {
102 "{}/v1.0/chats/{}/messages?$top=50&$orderby=createdDateTime desc",
106 recording = find_recording(&graph_event_page(thread_id, page));
103 session::GRAPH,
107 recording.is_some()
104 encode(thread_id)
108 })
105 );
109 .await?;
106 for _ in 0..MAX_MESSAGE_PAGES {
110 recording.ok_or(TranscriptError::NoRecording)
107 let page = self.get(&url, &scope, TranscriptError::NoRecording).await?;
111 }
108 if let Some(recording) = find_recording(&page) {
112
109 return Ok(recording);
113 /// Chat service message pages, newest arrival first, until `visit` returns true.
114 pub(crate) async fn visit_message_pages(
115 &self,
116 thread_id: &str,
117 mut visit: impl FnMut(&Value) -> bool,
118 ) -> Result<(), TranscriptError> {
119 let listing = ChatListing::new(self.session);
120 let mut before_ms = None;
121 for page_index in 0..MAX_MESSAGE_PAGES {
122 let page = match listing
123 .messages(thread_id, before_ms, MESSAGE_PAGE_SIZE)
124 .await
125 {
126 Ok(page) => page,
127 Err(error) if page_index == 0 => return Err(chatsvc_failure(error)),
128 Err(_) => break,
129 };
130 if visit(&json!({"messages": page.messages})) {
131 break;
110 }
132 }
111 match page.get("@odata.nextLink").and_then(Value::as_str) {
133 before_ms = page
112 Some(next) => url = next.to_owned(),
134 .messages
113 None => break,
135 .iter()
136 .filter_map(|message| id_text(&message["id"])?.parse::<i64>().ok())
137 .min();
138 if !page.has_older || before_ms.is_none() {
139 break;
114 }
140 }
115 }
141 }
116 Err(TranscriptError::NoRecording)
142 Ok(())
117 }
143 }
118
144
119 async fn item_url(
145 async fn item_url(
@@ -165,6 +191,17 @@ impl<'a> Transcripts<'a> {
165 }
191 }
166}
192}
167
193
194pub(crate) fn chatsvc_failure(error: Error) -> TranscriptError {
195 match error {
196 Error::Session(session::Error::Api {
197 status: 403 | 401, ..
198 }) => TranscriptError::AccessDenied,
199 Error::Session(session::Error::Api { status: 404, .. }) => TranscriptError::NoRecording,
200 Error::Session(error) => TranscriptError::Request(error),
201 _ => TranscriptError::NoRecording,
202 }
203}
204
168pub fn find_recording(messages_json: &Value) -> Option<Recording> {
205pub fn find_recording(messages_json: &Value) -> Option<Recording> {
169 messages_json
206 messages_json
170 .get("value")?
207 .get("value")?
crates/chatsvc/src/user_profiles.rs added +153 −0
@@ -0,0 +1,153 @@
1 use serde_json::{Value, json};
2 use session::{Method, Request, SPACES, Scope, Session};
3
4 use crate::error::Result;
5 use crate::language_settings::with_headers;
6 use crate::messages::ensure_success;
7 use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
9 const SKYPE_SCOPE: &str = "user_impersonation";
10 const ORGID_PREFIX: &str = "8:orgid:";
11 const PROFILE_QUERY: &str =
12 "isMailAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true";
13 const PROFILES_PER_REQUEST: usize = 100;
14
15 #[derive(Debug, Clone, PartialEq, Eq)]
16 pub struct UserProfile {
17 pub user_id: String,
18 pub display_name: Option<String>,
19 pub email: Option<String>,
20 pub user_principal_name: Option<String>,
21 pub job_title: Option<String>,
22 pub department: Option<String>,
23 }
24
25 pub struct UserProfiles<T: CsaTransport = SessionTransport> {
26 transport: T,
27 url: String,
28 }
29
30 impl UserProfiles<SessionTransport> {
31 pub fn new(session: &Session) -> Self {
32 let transport = SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE));
33 UserProfiles::with_transport(transport, DEFAULT_REGION)
34 }
35 }
36
37 impl<T: CsaTransport> UserProfiles<T> {
38 pub fn with_transport(transport: T, region: &str) -> Self {
39 UserProfiles {
40 transport,
41 url: format!(
42 "https://teams.cloud.microsoft/api/mt/{region}/beta/users/fetchShortProfile?{PROFILE_QUERY}"
43 ),
44 }
45 }
46
47 pub async fn fetch(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> {
48 let mut profiles = Vec::new();
49 for chunk in user_ids.chunks(PROFILES_PER_REQUEST) {
50 let mris: Vec<Value> = chunk
51 .iter()
52 .map(|user_id| json!(format!("{ORGID_PREFIX}{user_id}")))
53 .collect();
54 let answer = self
55 .transport
56 .send(with_headers(Request::with_body(
57 Method::Post,
58 self.url.clone(),
59 Value::Array(mris),
60 )))
61 .await?;
62 ensure_success(&answer)?;
63 profiles.extend(parse_user_profiles(&answer.body));
64 }
65 Ok(profiles)
66 }
67 }
68
69 pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> {
70 body.get("value")
71 .and_then(Value::as_array)
72 .map(Vec::as_slice)
73 .unwrap_or_default()
74 .iter()
75 .filter_map(|profile| {
76 let user_id = profile
77 .get("objectId")
78 .and_then(Value::as_str)
79 .filter(|id| !id.is_empty())
80 .or_else(|| {
81 profile
82 .get("mri")
83 .and_then(Value::as_str)?
84 .strip_prefix(ORGID_PREFIX)
85 })?
86 .to_owned();
87 Some(UserProfile {
88 user_id,
89 display_name: text(profile, "displayName"),
90 email: text(profile, "email"),
91 user_principal_name: text(profile, "userPrincipalName"),
92 job_title: text(profile, "jobTitle"),
93 department: text(profile, "department"),
94 })
95 })
96 .collect()
97 }
98
99 fn text(profile: &Value, key: &str) -> Option<String> {
100 profile
101 .get(key)
102 .and_then(Value::as_str)
103 .map(str::trim)
104 .filter(|text| !text.is_empty())
105 .map(str::to_owned)
106 }
107
108 #[cfg(test)]
109 mod tests {
110 use std::sync::Mutex;
111
112 use session::ApiResponse;
113
114 use super::*;
115
116 struct Canned {
117 requests: Mutex<Vec<Request>>,
118 }
119
120 impl CsaTransport for &Canned {
121 async fn send(&self, request: Request) -> Result<ApiResponse> {
122 self.requests.lock().unwrap().push(request);
123 Ok(ApiResponse {
124 status: 200,
125 body: json!({"value": [
126 {"mri": "8:orgid:ann", "objectId": "ann", "displayName": "Ann Example", "email": "ann@example.com"},
127 {"mri": "8:orgid:bob", "displayName": " "},
128 ]}),
129 retry_after: None,
130 })
131 }
132 }
133
134 #[tokio::test]
135 async fn profiles_post_mris_and_read_names() {
136 let canned = Canned {
137 requests: Mutex::new(Vec::new()),
138 };
139 let profiles = UserProfiles::with_transport(&canned, "emea")
140 .fetch(&["ann".into(), "bob".into()])
141 .await
142 .unwrap();
143 assert_eq!(profiles[0].display_name.as_deref(), Some("Ann Example"));
144 assert_eq!(profiles[0].email.as_deref(), Some("ann@example.com"));
145 assert_eq!(profiles[1].user_id, "bob");
146 assert_eq!(profiles[1].display_name, None);
147 let requests = canned.requests.lock().unwrap();
148 assert_eq!(
149 requests[0].body,
150 Some(json!(["8:orgid:ann", "8:orgid:bob"]))
151 );
152 }
153 }
@@ -0,0 +1,153 @@
1use serde_json::{Value, json};
2use session::{Method, Request, SPACES, Scope, Session};
3
4use crate::error::Result;
5use crate::language_settings::with_headers;
6use crate::messages::ensure_success;
7use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
9const SKYPE_SCOPE: &str = "user_impersonation";
10const ORGID_PREFIX: &str = "8:orgid:";
11const PROFILE_QUERY: &str =
12 "isMailAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true";
13const PROFILES_PER_REQUEST: usize = 100;
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct UserProfile {
17 pub user_id: String,
18 pub display_name: Option<String>,
19 pub email: Option<String>,
20 pub user_principal_name: Option<String>,
21 pub job_title: Option<String>,
22 pub department: Option<String>,
23}
24
25pub struct UserProfiles<T: CsaTransport = SessionTransport> {
26 transport: T,
27 url: String,
28}
29
30impl UserProfiles<SessionTransport> {
31 pub fn new(session: &Session) -> Self {
32 let transport = SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE));
33 UserProfiles::with_transport(transport, DEFAULT_REGION)
34 }
35}
36
37impl<T: CsaTransport> UserProfiles<T> {
38 pub fn with_transport(transport: T, region: &str) -> Self {
39 UserProfiles {
40 transport,
41 url: format!(
42 "https://teams.cloud.microsoft/api/mt/{region}/beta/users/fetchShortProfile?{PROFILE_QUERY}"
43 ),
44 }
45 }
46
47 pub async fn fetch(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> {
48 let mut profiles = Vec::new();
49 for chunk in user_ids.chunks(PROFILES_PER_REQUEST) {
50 let mris: Vec<Value> = chunk
51 .iter()
52 .map(|user_id| json!(format!("{ORGID_PREFIX}{user_id}")))
53 .collect();
54 let answer = self
55 .transport
56 .send(with_headers(Request::with_body(
57 Method::Post,
58 self.url.clone(),
59 Value::Array(mris),
60 )))
61 .await?;
62 ensure_success(&answer)?;
63 profiles.extend(parse_user_profiles(&answer.body));
64 }
65 Ok(profiles)
66 }
67}
68
69pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> {
70 body.get("value")
71 .and_then(Value::as_array)
72 .map(Vec::as_slice)
73 .unwrap_or_default()
74 .iter()
75 .filter_map(|profile| {
76 let user_id = profile
77 .get("objectId")
78 .and_then(Value::as_str)
79 .filter(|id| !id.is_empty())
80 .or_else(|| {
81 profile
82 .get("mri")
83 .and_then(Value::as_str)?
84 .strip_prefix(ORGID_PREFIX)
85 })?
86 .to_owned();
87 Some(UserProfile {
88 user_id,
89 display_name: text(profile, "displayName"),
90 email: text(profile, "email"),
91 user_principal_name: text(profile, "userPrincipalName"),
92 job_title: text(profile, "jobTitle"),
93 department: text(profile, "department"),
94 })
95 })
96 .collect()
97}
98
99fn text(profile: &Value, key: &str) -> Option<String> {
100 profile
101 .get(key)
102 .and_then(Value::as_str)
103 .map(str::trim)
104 .filter(|text| !text.is_empty())
105 .map(str::to_owned)
106}
107
108#[cfg(test)]
109mod tests {
110 use std::sync::Mutex;
111
112 use session::ApiResponse;
113
114 use super::*;
115
116 struct Canned {
117 requests: Mutex<Vec<Request>>,
118 }
119
120 impl CsaTransport for &Canned {
121 async fn send(&self, request: Request) -> Result<ApiResponse> {
122 self.requests.lock().unwrap().push(request);
123 Ok(ApiResponse {
124 status: 200,
125 body: json!({"value": [
126 {"mri": "8:orgid:ann", "objectId": "ann", "displayName": "Ann Example", "email": "ann@example.com"},
127 {"mri": "8:orgid:bob", "displayName": " "},
128 ]}),
129 retry_after: None,
130 })
131 }
132 }
133
134 #[tokio::test]
135 async fn profiles_post_mris_and_read_names() {
136 let canned = Canned {
137 requests: Mutex::new(Vec::new()),
138 };
139 let profiles = UserProfiles::with_transport(&canned, "emea")
140 .fetch(&["ann".into(), "bob".into()])
141 .await
142 .unwrap();
143 assert_eq!(profiles[0].display_name.as_deref(), Some("Ann Example"));
144 assert_eq!(profiles[0].email.as_deref(), Some("ann@example.com"));
145 assert_eq!(profiles[1].user_id, "bob");
146 assert_eq!(profiles[1].display_name, None);
147 let requests = canned.requests.lock().unwrap();
148 assert_eq!(
149 requests[0].body,
150 Some(json!(["8:orgid:ann", "8:orgid:bob"]))
151 );
152 }
153}
crates/cli/src/main.rs +5 −1
@@ -54,7 +54,11 @@ async fn run(arguments: Arguments) -> BoxedResult<()> {
54 54 }
55 55 Command::Chats { limit } => {
56 56 let me = graph.me().await?;
57 for chat in graph.list_chats(limit).await? {
57 let chats = teams_core::native::NativeChats::new(graph.session())
58 .first_page(limit)
59 .await?
60 .items;
61 for chat in chats {
58 62 let last = chat
59 63 .last_message_time()
60 64 .map(|time| time.format("%Y-%m-%d %H:%M UTC").to_string())
@@ -54,7 +54,11 @@ async fn run(arguments: Arguments) -> BoxedResult<()> {
54 }
54 }
55 Command::Chats { limit } => {
55 Command::Chats { limit } => {
56 let me = graph.me().await?;
56 let me = graph.me().await?;
57 for chat in graph.list_chats(limit).await? {
57 let chats = teams_core::native::NativeChats::new(graph.session())
58 .first_page(limit)
59 .await?
60 .items;
61 for chat in chats {
58 let last = chat
62 let last = chat
59 .last_message_time()
63 .last_message_time()
60 .map(|time| time.format("%Y-%m-%d %H:%M UTC").to_string())
64 .map(|time| time.format("%Y-%m-%d %H:%M UTC").to_string())
crates/core/Cargo.toml +1 −0
@@ -12,6 +12,7 @@ name = "teams_core"
12 12 chatsvc.workspace = true
13 13 chrono.workspace = true
14 14 iana-time-zone = "0.1"
15 base64.workspace = true
15 16 futures-util.workspace = true
16 17 graph.workspace = true
17 18 percent-encoding.workspace = true
@@ -12,6 +12,7 @@ name = "teams_core"
12chatsvc.workspace = true
12chatsvc.workspace = true
13chrono.workspace = true
13chrono.workspace = true
14iana-time-zone = "0.1"
14iana-time-zone = "0.1"
15base64.workspace = true
15futures-util.workspace = true
16futures-util.workspace = true
16graph.workspace = true
17graph.workspace = true
17percent-encoding.workspace = true
18percent-encoding.workspace = true
crates/core/examples/notes_read_probe.rs deleted +0 −106
@@ -1,106 +0,0 @@
1 use chatsvc::conversations::thread_url;
2 use graph::Graph;
3 use serde_json::Value;
4 use session::{DEFAULT_ENDPOINT, IC3, Request, Scope, Session};
5 use teams_core::NOTES_CHAT_ID;
6
7 const LISTING_URL: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations?view=msnp24Equivalent&pageSize=200";
8
9 #[tokio::main]
10 async fn main() {
11 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
12 let session = Session::connect(&endpoint).await.expect("browser");
13 let graph = Graph::new(session.clone());
14
15 match graph.chat_messages(NOTES_CHAT_ID, None, 5).await {
16 Ok(page) => {
17 println!(
18 "# graph messages: {} (next: {})",
19 page.items.len(),
20 page.next_link.is_some()
21 );
22 for message in &page.items {
23 println!(
24 " {} {:?} type={:?} deleted={}",
25 message.id,
26 message.created_date_time,
27 message.message_type,
28 message.deleted_date_time.is_some()
29 );
30 }
31 }
32 Err(error) => println!("# graph messages failed: {error}"),
33 }
34
35 let scope = Scope::new(IC3, "Teams.AccessAsUser.All");
36 let mut url = Some(LISTING_URL.to_owned());
37 let mut pages = 0;
38 while let Some(current) = url.take() {
39 pages += 1;
40 let body = get(&session, &current, &scope).await;
41 let found = body["conversations"]
42 .as_array()
43 .into_iter()
44 .flatten()
45 .find(|conversation| conversation["id"].as_str() == Some(NOTES_CHAT_ID))
46 .cloned();
47 if let Some(conversation) = found {
48 println!("# listing page {pages}: notes conversation found");
49 describe(&conversation);
50 break;
51 }
52 url = body
53 .pointer("/_metadata/backwardLink")
54 .and_then(Value::as_str)
55 .filter(|next| !next.is_empty() && *next != current)
56 .map(str::to_owned);
57 if url.is_none() {
58 println!("# notes conversation not in the listing ({pages} pages)");
59 }
60 }
61
62 let thread = get(&session, &thread_url("emea", NOTES_CHAT_ID), &scope).await;
63 println!("# thread GET");
64 describe(&thread);
65 }
66
67 async fn get(session: &Session, url: &str, scope: &Scope) -> Value {
68 let answer = session
69 .batch(&[Request::get(url)], scope)
70 .await
71 .expect("chatsvc")
72 .remove(0);
73 println!("# GET status {}", answer.status);
74 answer.body
75 }
76
77 fn describe(conversation: &Value) {
78 println!(" id={}", conversation["id"]);
79 println!(
80 " type={} version={}",
81 conversation["type"], conversation["version"]
82 );
83 for group in ["properties", "threadProperties"] {
84 if let Some(fields) = conversation[group].as_object() {
85 for (key, value) in fields {
86 let shown = match value {
87 Value::String(text) if text.len() > 80 => format!("<{} chars>", text.len()),
88 other => other.to_string(),
89 };
90 println!(" {group}.{key} = {shown}");
91 }
92 }
93 }
94 let last = &conversation["lastMessage"];
95 println!(
96 " lastMessage id={} messagetype={} from={} arrival={} content_len={}",
97 last["id"],
98 last["messagetype"],
99 last["from"]
100 .as_str()
101 .map(|from| from.rsplit('/').next().unwrap_or(""))
102 .unwrap_or("-"),
103 last["originalarrivaltime"],
104 last["content"].as_str().map(str::len).unwrap_or(0)
105 );
106 }
@@ -1,106 +0,0 @@
1use chatsvc::conversations::thread_url;
2use graph::Graph;
3use serde_json::Value;
4use session::{DEFAULT_ENDPOINT, IC3, Request, Scope, Session};
5use teams_core::NOTES_CHAT_ID;
6
7const LISTING_URL: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations?view=msnp24Equivalent&pageSize=200";
8
9#[tokio::main]
10async fn main() {
11 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
12 let session = Session::connect(&endpoint).await.expect("browser");
13 let graph = Graph::new(session.clone());
14
15 match graph.chat_messages(NOTES_CHAT_ID, None, 5).await {
16 Ok(page) => {
17 println!(
18 "# graph messages: {} (next: {})",
19 page.items.len(),
20 page.next_link.is_some()
21 );
22 for message in &page.items {
23 println!(
24 " {} {:?} type={:?} deleted={}",
25 message.id,
26 message.created_date_time,
27 message.message_type,
28 message.deleted_date_time.is_some()
29 );
30 }
31 }
32 Err(error) => println!("# graph messages failed: {error}"),
33 }
34
35 let scope = Scope::new(IC3, "Teams.AccessAsUser.All");
36 let mut url = Some(LISTING_URL.to_owned());
37 let mut pages = 0;
38 while let Some(current) = url.take() {
39 pages += 1;
40 let body = get(&session, &current, &scope).await;
41 let found = body["conversations"]
42 .as_array()
43 .into_iter()
44 .flatten()
45 .find(|conversation| conversation["id"].as_str() == Some(NOTES_CHAT_ID))
46 .cloned();
47 if let Some(conversation) = found {
48 println!("# listing page {pages}: notes conversation found");
49 describe(&conversation);
50 break;
51 }
52 url = body
53 .pointer("/_metadata/backwardLink")
54 .and_then(Value::as_str)
55 .filter(|next| !next.is_empty() && *next != current)
56 .map(str::to_owned);
57 if url.is_none() {
58 println!("# notes conversation not in the listing ({pages} pages)");
59 }
60 }
61
62 let thread = get(&session, &thread_url("emea", NOTES_CHAT_ID), &scope).await;
63 println!("# thread GET");
64 describe(&thread);
65}
66
67async fn get(session: &Session, url: &str, scope: &Scope) -> Value {
68 let answer = session
69 .batch(&[Request::get(url)], scope)
70 .await
71 .expect("chatsvc")
72 .remove(0);
73 println!("# GET status {}", answer.status);
74 answer.body
75}
76
77fn describe(conversation: &Value) {
78 println!(" id={}", conversation["id"]);
79 println!(
80 " type={} version={}",
81 conversation["type"], conversation["version"]
82 );
83 for group in ["properties", "threadProperties"] {
84 if let Some(fields) = conversation[group].as_object() {
85 for (key, value) in fields {
86 let shown = match value {
87 Value::String(text) if text.len() > 80 => format!("<{} chars>", text.len()),
88 other => other.to_string(),
89 };
90 println!(" {group}.{key} = {shown}");
91 }
92 }
93 }
94 let last = &conversation["lastMessage"];
95 println!(
96 " lastMessage id={} messagetype={} from={} arrival={} content_len={}",
97 last["id"],
98 last["messagetype"],
99 last["from"]
100 .as_str()
101 .map(|from| from.rsplit('/').next().unwrap_or(""))
102 .unwrap_or("-"),
103 last["originalarrivaltime"],
104 last["content"].as_str().map(str::len).unwrap_or(0)
105 );
106}
crates/core/examples/table_html_probe.rs +1 −12
@@ -2,7 +2,6 @@ use std::time::Duration;
2 2
3 3 use chatsvc::{ConversationRef, Messages};
4 4 use chrono::Utc;
5 use graph::{Graph, MessageExtras};
6 5 use serde_json::{Value, json};
7 6 use session::{DEFAULT_ENDPOINT, IC3, Method, Request, Scope, Session};
8 7 use teams_core::{Draft, NOTES_CHAT_ID, Table};
@@ -26,17 +25,7 @@ async fn main() {
26 25 let html = draft.to_html();
27 26 println!("# composer html\n{html}\n");
28 27
29 let via_chatsvc = std::env::args().any(|argument| argument == "--chatsvc");
30 let message_id = if via_chatsvc {
31 send_via_chatsvc(&session, &html).await
32 } else {
33 let sent = Graph::new(session.clone())
34 .send_chat_message(NOTES_CHAT_ID, &html, &[], &MessageExtras::default())
35 .await
36 .expect("graph send to 48:notes");
37 println!("# sent via graph");
38 sent.id
39 };
28 let message_id = send_via_chatsvc(&session, &html).await;
40 29 println!("# sent id {message_id}");
41 30
42 31 tokio::time::sleep(Duration::from_secs(2)).await;
@@ -2,7 +2,6 @@ use std::time::Duration;
2
2
3use chatsvc::{ConversationRef, Messages};
3use chatsvc::{ConversationRef, Messages};
4use chrono::Utc;
4use chrono::Utc;
5use graph::{Graph, MessageExtras};
6use serde_json::{Value, json};
5use serde_json::{Value, json};
7use session::{DEFAULT_ENDPOINT, IC3, Method, Request, Scope, Session};
6use session::{DEFAULT_ENDPOINT, IC3, Method, Request, Scope, Session};
8use teams_core::{Draft, NOTES_CHAT_ID, Table};
7use teams_core::{Draft, NOTES_CHAT_ID, Table};
@@ -26,17 +25,7 @@ async fn main() {
26 let html = draft.to_html();
25 let html = draft.to_html();
27 println!("# composer html\n{html}\n");
26 println!("# composer html\n{html}\n");
28
27
29 let via_chatsvc = std::env::args().any(|argument| argument == "--chatsvc");
28 let message_id = send_via_chatsvc(&session, &html).await;
30 let message_id = if via_chatsvc {
31 send_via_chatsvc(&session, &html).await
32 } else {
33 let sent = Graph::new(session.clone())
34 .send_chat_message(NOTES_CHAT_ID, &html, &[], &MessageExtras::default())
35 .await
36 .expect("graph send to 48:notes");
37 println!("# sent via graph");
38 sent.id
39 };
40 println!("# sent id {message_id}");
29 println!("# sent id {message_id}");
41
30
42 tokio::time::sleep(Duration::from_secs(2)).await;
31 tokio::time::sleep(Duration::from_secs(2)).await;
crates/core/src/actions.rs +51 −63
@@ -17,7 +17,7 @@ use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
17 17 use crate::notes_chat::is_notes_chat;
18 18 use crate::remote::Remote;
19 19 use crate::scheduled::NOTES_CHAT_ID;
20 use crate::teams_quote::{chatsvc_mention_html, quote_reply_properties, teams_quote};
20 use crate::teams_quote::{mention_entries, teams_quote};
21 21
22 22 impl<R: Remote> SyncEngine<R> {
23 23 pub async fn send_message(
@@ -60,9 +60,17 @@ impl<R: Remote> SyncEngine<R> {
60 60 let (html, mentions) = outgoing(&conversation, html, mentions)?;
61 61 let sent = match (conversation, thread_root_id) {
62 62 (Conversation::Chat, None) => {
63 self.remote
64 .send_chat_message(conversation_id, &html, &mentions, extras)
65 .await?
63 let sent = self
64 .send_via_chatsvc(
65 &ConversationRef::chat(conversation_id),
66 None,
67 &html,
68 &mentions,
69 extras,
70 None,
71 )
72 .await?;
73 return self.cache_sent(conversation_id, &sent.message, &html, extras);
66 74 }
67 75 (Conversation::Channel { team_id }, Some(root_id)) => {
68 76 self.remote
@@ -171,9 +179,9 @@ impl<R: Remote> SyncEngine<R> {
171 179 .await?
172 180 }
173 181 _ => {
174 self.remote
175 .reply_with_quote(conversation_id, message_id, &html, &mentions, extras)
182 self.send_via_chatsvc(&chatsvc_conversation, None, &html, &mentions, extras, None)
176 183 .await?
184 .message
177 185 }
178 186 };
179 187 self.cache_sent(conversation_id, &sent, &html, extras)
@@ -447,13 +455,19 @@ impl<R: Remote> SyncEngine<R> {
447 455 if let Conversation::Channel { .. } = self.resolve(conversation_id).await? {
448 456 return self.mark_channel_read(conversation_id).await;
449 457 }
450 let user_id = self.my_user_id().await?;
451 let tenant_id = self.my_tenant_id(conversation_id).await?;
458 let now = Utc::now();
459 let last_message_at = self
460 .store
461 .chat(conversation_id)?
462 .and_then(|chat| chat.last_message_at)
463 .unwrap_or(now);
452 464 self.remote
453 .mark_chat_read(conversation_id, &user_id, &tenant_id)
465 .set_read_horizon(
466 conversation_id,
467 &read_horizon::read_up_to(last_message_at, now),
468 )
454 469 .await?;
455 let now = Utc::now();
456 if is_notes_chat(conversation_id) {
470 if is_notes_chat(conversation_id) || self.has_unread_bookmark(conversation_id) {
457 471 self.remote
458 472 .set_read_bookmark(conversation_id, &read_horizon::cleared_bookmark(now))
459 473 .await?;
@@ -510,25 +524,25 @@ impl<R: Remote> SyncEngine<R> {
510 524 message_created_at: DateTime<Utc>,
511 525 ) -> Result<()> {
512 526 let last_read_at = message_created_at - Duration::milliseconds(1);
513 if is_notes_chat(chat_id) {
514 let bookmark = read_horizon::bookmark_at(
515 message_created_at,
516 &self.message_id_at(chat_id, message_created_at)?,
517 Utc::now(),
518 );
519 self.remote.set_read_bookmark(chat_id, &bookmark).await?;
520 } else {
521 let user_id = self.my_user_id().await?;
522 let tenant_id = self.my_tenant_id(chat_id).await?;
523 self.remote
524 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
525 .await?;
526 }
527 let bookmark = read_horizon::bookmark_at(
528 message_created_at,
529 &self.message_id_at(chat_id, message_created_at)?,
530 Utc::now(),
531 );
532 self.remote.set_read_bookmark(chat_id, &bookmark).await?;
527 533 self.store.mark_chat_unread(chat_id, last_read_at)?;
528 534 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
529 535 Ok(())
530 536 }
531 537
538 fn has_unread_bookmark(&self, chat_id: &str) -> bool {
539 self.chat_states
540 .lock()
541 .unwrap()
542 .get(chat_id)
543 .is_some_and(|state| state.read.bookmark_message_set)
544 }
545
532 546 fn message_id_at(&self, chat_id: &str, created_at: DateTime<Utc>) -> Result<String> {
533 547 Ok(self
534 548 .store
@@ -569,9 +583,9 @@ impl<R: Remote> SyncEngine<R> {
569 583 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
570 584 return Ok(());
571 585 }
572 let user_id = self.my_user_id().await?;
573 let tenant_id = self.my_tenant_id(chat_id).await?;
574 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
586 self.remote
587 .set_chat_hidden_at(chat_id, Some(Utc::now().timestamp_millis()))
588 .await?;
575 589 let hidden_after = self
576 590 .store
577 591 .chat(chat_id)?
@@ -589,11 +603,7 @@ impl<R: Remote> SyncEngine<R> {
589 603 self.refresh_sidebar_full().await?;
590 604 return Ok(());
591 605 }
592 let user_id = self.my_user_id().await?;
593 let tenant_id = self.my_tenant_id(chat_id).await?;
594 self.remote
595 .unhide_chat(chat_id, &user_id, &tenant_id)
596 .await?;
606 self.remote.set_chat_hidden_at(chat_id, None).await?;
597 607 let now = Utc::now();
598 608 self.with_locally_hidden(|locally| locally.unhide(chat_id, now))?;
599 609 self.refresh_sidebar_full().await?;
@@ -846,7 +856,7 @@ impl<R: Remote> SyncEngine<R> {
846 856 self.seed_images(&seeds)
847 857 }
848 858
849 /// `None` when Teams' shape cannot be written here (images, files, team mentions, no quote).
859 /// `None` when Teams' shape cannot be written here (channel images or files, team mentions, no quote).
850 860 async fn quote_reply_via_chatsvc(
851 861 &self,
852 862 conversation: &ConversationRef,
@@ -856,42 +866,20 @@ impl<R: Remote> SyncEngine<R> {
856 866 mentions: &[OutgoingMention],
857 867 extras: &MessageExtras,
858 868 ) -> Result<Option<(graph::Message, String)>> {
859 if !extras.images.is_empty() || !extras.files.is_empty() {
869 let in_chat = matches!(conversation, ConversationRef::Chat { .. });
870 if !in_chat && (!extras.images.is_empty() || !extras.files.is_empty()) {
860 871 return Ok(None);
861 872 }
862 873 let Some(quote) = teams_quote(quoted) else {
863 874 return Ok(None);
864 875 };
865 let Some(properties) = quote_reply_properties(&quote, mentions, extras.importance) else {
876 if mention_entries(mentions).is_none() {
866 877 return Ok(None);
867 };
868 self.ensure_display_name().await?;
869 let me = self
870 .me()
871 .ok_or(Error::Unsupported("a quote reply before sign-in"))?;
872 let content = format!("{}{}", quote.html, chatsvc_mention_html(html, mentions));
873 let message_id = self
874 .remote
875 .post_chatsvc_message(conversation, &content, &me.display_name, &properties)
878 }
879 let sent = self
880 .send_via_chatsvc(conversation, root_id, html, mentions, extras, Some(&quote))
876 881 .await?;
877 let created_at = message_id
878 .parse::<i64>()
879 .ok()
880 .and_then(DateTime::from_timestamp_millis)
881 .unwrap_or_else(Utc::now);
882 let cached_html = format!("{}{html}", quote.html);
883 let sent = serde_json::from_value(serde_json::json!({
884 "id": message_id,
885 "messageType": "message",
886 "createdDateTime": created_at.to_rfc3339(),
887 "replyToId": root_id,
888 "importance": extras.importance,
889 "from": {"user": {"id": me.user_id, "displayName": me.display_name}},
890 "body": {"contentType": "html", "content": cached_html},
891 "mentions": mentions.iter().map(OutgoingMention::to_json).collect::<Vec<_>>(),
892 }))
893 .map_err(|_| Error::Unsupported("a chatsvc reply without a message shape"))?;
894 Ok(Some((sent, cached_html)))
882 Ok(Some((sent.message, sent.html)))
895 883 }
896 884
897 885 pub(crate) fn cache_sent(
@@ -17,7 +17,7 @@ use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
17use crate::notes_chat::is_notes_chat;
17use crate::notes_chat::is_notes_chat;
18use crate::remote::Remote;
18use crate::remote::Remote;
19use crate::scheduled::NOTES_CHAT_ID;
19use crate::scheduled::NOTES_CHAT_ID;
20use crate::teams_quote::{chatsvc_mention_html, quote_reply_properties, teams_quote};
20use crate::teams_quote::{mention_entries, teams_quote};
21
21
22impl<R: Remote> SyncEngine<R> {
22impl<R: Remote> SyncEngine<R> {
23 pub async fn send_message(
23 pub async fn send_message(
@@ -60,9 +60,17 @@ impl<R: Remote> SyncEngine<R> {
60 let (html, mentions) = outgoing(&conversation, html, mentions)?;
60 let (html, mentions) = outgoing(&conversation, html, mentions)?;
61 let sent = match (conversation, thread_root_id) {
61 let sent = match (conversation, thread_root_id) {
62 (Conversation::Chat, None) => {
62 (Conversation::Chat, None) => {
63 self.remote
63 let sent = self
64 .send_chat_message(conversation_id, &html, &mentions, extras)
64 .send_via_chatsvc(
65 .await?
65 &ConversationRef::chat(conversation_id),
66 None,
67 &html,
68 &mentions,
69 extras,
70 None,
71 )
72 .await?;
73 return self.cache_sent(conversation_id, &sent.message, &html, extras);
66 }
74 }
67 (Conversation::Channel { team_id }, Some(root_id)) => {
75 (Conversation::Channel { team_id }, Some(root_id)) => {
68 self.remote
76 self.remote
@@ -171,9 +179,9 @@ impl<R: Remote> SyncEngine<R> {
171 .await?
179 .await?
172 }
180 }
173 _ => {
181 _ => {
174 self.remote
182 self.send_via_chatsvc(&chatsvc_conversation, None, &html, &mentions, extras, None)
175 .reply_with_quote(conversation_id, message_id, &html, &mentions, extras)
176 .await?
183 .await?
184 .message
177 }
185 }
178 };
186 };
179 self.cache_sent(conversation_id, &sent, &html, extras)
187 self.cache_sent(conversation_id, &sent, &html, extras)
@@ -447,13 +455,19 @@ impl<R: Remote> SyncEngine<R> {
447 if let Conversation::Channel { .. } = self.resolve(conversation_id).await? {
455 if let Conversation::Channel { .. } = self.resolve(conversation_id).await? {
448 return self.mark_channel_read(conversation_id).await;
456 return self.mark_channel_read(conversation_id).await;
449 }
457 }
450 let user_id = self.my_user_id().await?;
458 let now = Utc::now();
451 let tenant_id = self.my_tenant_id(conversation_id).await?;
459 let last_message_at = self
460 .store
461 .chat(conversation_id)?
462 .and_then(|chat| chat.last_message_at)
463 .unwrap_or(now);
452 self.remote
464 self.remote
453 .mark_chat_read(conversation_id, &user_id, &tenant_id)
465 .set_read_horizon(
466 conversation_id,
467 &read_horizon::read_up_to(last_message_at, now),
468 )
454 .await?;
469 .await?;
455 let now = Utc::now();
470 if is_notes_chat(conversation_id) || self.has_unread_bookmark(conversation_id) {
456 if is_notes_chat(conversation_id) {
457 self.remote
471 self.remote
458 .set_read_bookmark(conversation_id, &read_horizon::cleared_bookmark(now))
472 .set_read_bookmark(conversation_id, &read_horizon::cleared_bookmark(now))
459 .await?;
473 .await?;
@@ -510,25 +524,25 @@ impl<R: Remote> SyncEngine<R> {
510 message_created_at: DateTime<Utc>,
524 message_created_at: DateTime<Utc>,
511 ) -> Result<()> {
525 ) -> Result<()> {
512 let last_read_at = message_created_at - Duration::milliseconds(1);
526 let last_read_at = message_created_at - Duration::milliseconds(1);
513 if is_notes_chat(chat_id) {
527 let bookmark = read_horizon::bookmark_at(
514 let bookmark = read_horizon::bookmark_at(
528 message_created_at,
515 message_created_at,
529 &self.message_id_at(chat_id, message_created_at)?,
516 &self.message_id_at(chat_id, message_created_at)?,
530 Utc::now(),
517 Utc::now(),
531 );
518 );
532 self.remote.set_read_bookmark(chat_id, &bookmark).await?;
519 self.remote.set_read_bookmark(chat_id, &bookmark).await?;
520 } else {
521 let user_id = self.my_user_id().await?;
522 let tenant_id = self.my_tenant_id(chat_id).await?;
523 self.remote
524 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
525 .await?;
526 }
527 self.store.mark_chat_unread(chat_id, last_read_at)?;
533 self.store.mark_chat_unread(chat_id, last_read_at)?;
528 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
534 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
529 Ok(())
535 Ok(())
530 }
536 }
531
537
538 fn has_unread_bookmark(&self, chat_id: &str) -> bool {
539 self.chat_states
540 .lock()
541 .unwrap()
542 .get(chat_id)
543 .is_some_and(|state| state.read.bookmark_message_set)
544 }
545
532 fn message_id_at(&self, chat_id: &str, created_at: DateTime<Utc>) -> Result<String> {
546 fn message_id_at(&self, chat_id: &str, created_at: DateTime<Utc>) -> Result<String> {
533 Ok(self
547 Ok(self
534 .store
548 .store
@@ -569,9 +583,9 @@ impl<R: Remote> SyncEngine<R> {
569 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
583 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
570 return Ok(());
584 return Ok(());
571 }
585 }
572 let user_id = self.my_user_id().await?;
586 self.remote
573 let tenant_id = self.my_tenant_id(chat_id).await?;
587 .set_chat_hidden_at(chat_id, Some(Utc::now().timestamp_millis()))
574 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
588 .await?;
575 let hidden_after = self
589 let hidden_after = self
576 .store
590 .store
577 .chat(chat_id)?
591 .chat(chat_id)?
@@ -589,11 +603,7 @@ impl<R: Remote> SyncEngine<R> {
589 self.refresh_sidebar_full().await?;
603 self.refresh_sidebar_full().await?;
590 return Ok(());
604 return Ok(());
591 }
605 }
592 let user_id = self.my_user_id().await?;
606 self.remote.set_chat_hidden_at(chat_id, None).await?;
593 let tenant_id = self.my_tenant_id(chat_id).await?;
594 self.remote
595 .unhide_chat(chat_id, &user_id, &tenant_id)
596 .await?;
597 let now = Utc::now();
607 let now = Utc::now();
598 self.with_locally_hidden(|locally| locally.unhide(chat_id, now))?;
608 self.with_locally_hidden(|locally| locally.unhide(chat_id, now))?;
599 self.refresh_sidebar_full().await?;
609 self.refresh_sidebar_full().await?;
@@ -846,7 +856,7 @@ impl<R: Remote> SyncEngine<R> {
846 self.seed_images(&seeds)
856 self.seed_images(&seeds)
847 }
857 }
848
858
849 /// `None` when Teams' shape cannot be written here (images, files, team mentions, no quote).
859 /// `None` when Teams' shape cannot be written here (channel images or files, team mentions, no quote).
850 async fn quote_reply_via_chatsvc(
860 async fn quote_reply_via_chatsvc(
851 &self,
861 &self,
852 conversation: &ConversationRef,
862 conversation: &ConversationRef,
@@ -856,42 +866,20 @@ impl<R: Remote> SyncEngine<R> {
856 mentions: &[OutgoingMention],
866 mentions: &[OutgoingMention],
857 extras: &MessageExtras,
867 extras: &MessageExtras,
858 ) -> Result<Option<(graph::Message, String)>> {
868 ) -> Result<Option<(graph::Message, String)>> {
859 if !extras.images.is_empty() || !extras.files.is_empty() {
869 let in_chat = matches!(conversation, ConversationRef::Chat { .. });
870 if !in_chat && (!extras.images.is_empty() || !extras.files.is_empty()) {
860 return Ok(None);
871 return Ok(None);
861 }
872 }
862 let Some(quote) = teams_quote(quoted) else {
873 let Some(quote) = teams_quote(quoted) else {
863 return Ok(None);
874 return Ok(None);
864 };
875 };
865 let Some(properties) = quote_reply_properties(&quote, mentions, extras.importance) else {
876 if mention_entries(mentions).is_none() {
866 return Ok(None);
877 return Ok(None);
867 };
878 }
868 self.ensure_display_name().await?;
879 let sent = self
869 let me = self
880 .send_via_chatsvc(conversation, root_id, html, mentions, extras, Some(&quote))
870 .me()
871 .ok_or(Error::Unsupported("a quote reply before sign-in"))?;
872 let content = format!("{}{}", quote.html, chatsvc_mention_html(html, mentions));
873 let message_id = self
874 .remote
875 .post_chatsvc_message(conversation, &content, &me.display_name, &properties)
876 .await?;
881 .await?;
877 let created_at = message_id
882 Ok(Some((sent.message, sent.html)))
878 .parse::<i64>()
879 .ok()
880 .and_then(DateTime::from_timestamp_millis)
881 .unwrap_or_else(Utc::now);
882 let cached_html = format!("{}{html}", quote.html);
883 let sent = serde_json::from_value(serde_json::json!({
884 "id": message_id,
885 "messageType": "message",
886 "createdDateTime": created_at.to_rfc3339(),
887 "replyToId": root_id,
888 "importance": extras.importance,
889 "from": {"user": {"id": me.user_id, "displayName": me.display_name}},
890 "body": {"contentType": "html", "content": cached_html},
891 "mentions": mentions.iter().map(OutgoingMention::to_json).collect::<Vec<_>>(),
892 }))
893 .map_err(|_| Error::Unsupported("a chatsvc reply without a message shape"))?;
894 Ok(Some((sent, cached_html)))
895 }
883 }
896
884
897 pub(crate) fn cache_sent(
885 pub(crate) fn cache_sent(
crates/core/src/chat_send.rs added +226 −0
@@ -0,0 +1,226 @@
1 use chatsvc::ConversationRef;
2 use chatsvc::ams::AmsImage;
3 use chrono::{DateTime, Utc};
4 use graph::{FileReference, HostedImage, MessageExtras, OutgoingMention};
5 use serde_json::{Value, json};
6
7 use crate::engine::SyncEngine;
8 use crate::error::{Error, Result};
9 use crate::remote::Remote;
10 use crate::teams_quote::{TeamsQuote, chatsvc_mention_html, message_properties};
11
12 const AMS_IMAGE_ITEMTYPE: &str = "http://schema.skype.com/AMSImage";
13 const FILE_ITEMTYPE: &str = "http://schema.skype.com/File";
14 const HOSTED_PREFIX: &str = "../hostedContents/";
15 const HOSTED_SUFFIX: &str = "/$value";
16 const SITE_SEGMENTS: [&str; 2] = ["/personal/", "/sites/"];
17
18 /// What was posted, in Graph form for the cache, and the html the cache keeps.
19 pub(crate) struct ChatsvcSent {
20 pub message: graph::Message,
21 pub html: String,
22 }
23
24 impl<R: Remote> SyncEngine<R> {
25 /// Posts like Teams web: mention spans, AMS images and the `files` property; `quote` puts a reply quote first.
26 pub(crate) async fn send_via_chatsvc(
27 &self,
28 conversation: &ConversationRef,
29 root_id: Option<&str>,
30 html: &str,
31 mentions: &[OutgoingMention],
32 extras: &MessageExtras,
33 quote: Option<&TeamsQuote>,
34 ) -> Result<ChatsvcSent> {
35 let properties = message_properties(
36 quote,
37 mentions,
38 extras.importance,
39 &files_property(&extras.files),
40 )
41 .ok_or(Error::Unsupported(
42 "a team, channel or tag mention in a chat",
43 ))?;
44 self.ensure_display_name().await?;
45 let me = self
46 .me()
47 .ok_or(Error::Unsupported("sending before sign-in"))?;
48 let conversation_id = conversation.conversation_id();
49 let mut uploaded = Vec::new();
50 for image in &extras.images {
51 uploaded.push(
52 self.remote
53 .upload_ams_image(&conversation_id, &image.bytes, &image_file_name(image))
54 .await?,
55 );
56 }
57 let body = with_ams_images(html, &uploaded);
58 let quote_html = quote.map(|quote| quote.html.as_str()).unwrap_or_default();
59 let content = format!("{quote_html}{}", chatsvc_mention_html(&body, mentions));
60 let message_id = self
61 .remote
62 .post_chatsvc_message(conversation, &content, &me.display_name, &properties)
63 .await?;
64 let created_at = message_id
65 .parse::<i64>()
66 .ok()
67 .and_then(DateTime::from_timestamp_millis)
68 .unwrap_or_else(Utc::now);
69 let cached_html = format!("{quote_html}{body}");
70 let attachments: Vec<Value> = extras
71 .files
72 .iter()
73 .map(|file| {
74 json!({
75 "id": file.attachment_id,
76 "contentType": "reference",
77 "contentUrl": file.content_url,
78 "name": file.name,
79 })
80 })
81 .collect();
82 let message = serde_json::from_value(json!({
83 "id": message_id,
84 "messageType": "message",
85 "createdDateTime": created_at.to_rfc3339(),
86 "replyToId": root_id,
87 "importance": extras.importance,
88 "from": {"user": {"id": me.user_id, "displayName": me.display_name}},
89 "body": {"contentType": "html", "content": cached_html},
90 "mentions": mentions.iter().map(OutgoingMention::to_json).collect::<Vec<_>>(),
91 "attachments": attachments,
92 }))
93 .map_err(|_| Error::Unsupported("a chatsvc send without a message shape"))?;
94 Ok(ChatsvcSent {
95 message,
96 html: cached_html,
97 })
98 }
99 }
100
101 fn image_file_name(image: &HostedImage) -> String {
102 let extension = image
103 .content_type
104 .rsplit('/')
105 .next()
106 .filter(|extension| !extension.is_empty())
107 .unwrap_or("png");
108 format!("image.{extension}")
109 }
110
111 /// Swaps each Graph `../hostedContents/{n}/$value` image for its AMS upload; images not placed in the text go last.
112 fn with_ams_images(html: &str, uploaded: &[AmsImage]) -> String {
113 let mut body = html.to_owned();
114 for (index, image) in uploaded.iter().enumerate() {
115 let tag = format!(
116 "<img itemtype=\"{AMS_IMAGE_ITEMTYPE}\" itemscope=\"\" src=\"{}\" itemid=\"{}\" alt=\"image\">",
117 image.url, image.object_id
118 );
119 let placeholder = format!("{HOSTED_PREFIX}{}{HOSTED_SUFFIX}", index + 1);
120 match image_tag_around(&body, &placeholder) {
121 Some((start, end)) => body.replace_range(start..end, &tag),
122 None => body.push_str(&format!("<p>{tag}</p>")),
123 }
124 }
125 body
126 }
127
128 fn image_tag_around(html: &str, source: &str) -> Option<(usize, usize)> {
129 let at = html.find(&format!("\"{source}\""))?;
130 let start = html[..at].rfind("<img")?;
131 let end = html[at..].find('>')? + at + 1;
132 Some((start, end))
133 }
134
135 /// The `files` property Teams writes for a shared OneDrive or SharePoint file.
136 fn files_property(files: &[FileReference]) -> Value {
137 Value::Array(
138 files
139 .iter()
140 .map(|file| {
141 let file_type = file
142 .name
143 .rsplit_once('.')
144 .map(|(_, extension)| extension.to_ascii_lowercase())
145 .unwrap_or_default();
146 json!({
147 "@type": FILE_ITEMTYPE,
148 "version": 2,
149 "id": file.attachment_id,
150 "itemid": file.attachment_id,
151 "baseUrl": site_url(&file.content_url),
152 "type": file_type,
153 "fileType": file_type,
154 "title": file.name,
155 "fileName": file.name,
156 "state": "active",
157 "objectUrl": file.content_url,
158 "fileInfo": {
159 "itemId": null,
160 "fileUrl": file.content_url,
161 "siteUrl": site_url(&file.content_url),
162 "serverRelativeUrl": "",
163 "shareUrl": null,
164 "shareId": null,
165 },
166 "fileChicletState": {"serviceName": "p2p", "state": "active"},
167 "permissionScope": "users",
168 })
169 })
170 .collect(),
171 )
172 }
173
174 /// `https://tenant-my.sharepoint.com/personal/ann/` for a file under that site.
175 fn site_url(url: &str) -> String {
176 SITE_SEGMENTS
177 .iter()
178 .find_map(|segment| {
179 let start = url.find(segment)? + segment.len();
180 let end = url[start..].find('/')? + start + 1;
181 Some(url[..end].to_owned())
182 })
183 .unwrap_or_default()
184 }
185
186 #[cfg(test)]
187 mod tests {
188 use super::*;
189
190 fn uploaded(object_id: &str) -> AmsImage {
191 AmsImage {
192 object_id: object_id.into(),
193 url: format!("https://ams.example/{object_id}"),
194 }
195 }
196
197 #[test]
198 fn hosted_images_become_ams_images_in_place_or_last() {
199 let html = r#"<p>a<img src="../hostedContents/2/$value" width="20">b</p>"#;
200 let body = with_ams_images(html, &[uploaded("one"), uploaded("two")]);
201 assert_eq!(
202 body,
203 r#"<p>a<img itemtype="http://schema.skype.com/AMSImage" itemscope="" src="https://ams.example/two" itemid="two" alt="image">b</p><p><img itemtype="http://schema.skype.com/AMSImage" itemscope="" src="https://ams.example/one" itemid="one" alt="image"></p>"#
204 );
205 }
206
207 #[test]
208 fn a_file_names_its_site() {
209 let files = files_property(&[FileReference {
210 attachment_id: "guid-1".into(),
211 content_url:
212 "https://contoso-my.sharepoint.com/personal/ann_contoso_com/Documents/Plan.DOCX"
213 .into(),
214 name: "Plan.DOCX".into(),
215 }]);
216 assert_eq!(
217 files[0]["baseUrl"],
218 "https://contoso-my.sharepoint.com/personal/ann_contoso_com/"
219 );
220 assert_eq!(files[0]["fileType"], "docx");
221 assert_eq!(
222 files[0]["fileInfo"]["fileUrl"],
223 "https://contoso-my.sharepoint.com/personal/ann_contoso_com/Documents/Plan.DOCX"
224 );
225 }
226 }
@@ -0,0 +1,226 @@
1use chatsvc::ConversationRef;
2use chatsvc::ams::AmsImage;
3use chrono::{DateTime, Utc};
4use graph::{FileReference, HostedImage, MessageExtras, OutgoingMention};
5use serde_json::{Value, json};
6
7use crate::engine::SyncEngine;
8use crate::error::{Error, Result};
9use crate::remote::Remote;
10use crate::teams_quote::{TeamsQuote, chatsvc_mention_html, message_properties};
11
12const AMS_IMAGE_ITEMTYPE: &str = "http://schema.skype.com/AMSImage";
13const FILE_ITEMTYPE: &str = "http://schema.skype.com/File";
14const HOSTED_PREFIX: &str = "../hostedContents/";
15const HOSTED_SUFFIX: &str = "/$value";
16const SITE_SEGMENTS: [&str; 2] = ["/personal/", "/sites/"];
17
18/// What was posted, in Graph form for the cache, and the html the cache keeps.
19pub(crate) struct ChatsvcSent {
20 pub message: graph::Message,
21 pub html: String,
22}
23
24impl<R: Remote> SyncEngine<R> {
25 /// Posts like Teams web: mention spans, AMS images and the `files` property; `quote` puts a reply quote first.
26 pub(crate) async fn send_via_chatsvc(
27 &self,
28 conversation: &ConversationRef,
29 root_id: Option<&str>,
30 html: &str,
31 mentions: &[OutgoingMention],
32 extras: &MessageExtras,
33 quote: Option<&TeamsQuote>,
34 ) -> Result<ChatsvcSent> {
35 let properties = message_properties(
36 quote,
37 mentions,
38 extras.importance,
39 &files_property(&extras.files),
40 )
41 .ok_or(Error::Unsupported(
42 "a team, channel or tag mention in a chat",
43 ))?;
44 self.ensure_display_name().await?;
45 let me = self
46 .me()
47 .ok_or(Error::Unsupported("sending before sign-in"))?;
48 let conversation_id = conversation.conversation_id();
49 let mut uploaded = Vec::new();
50 for image in &extras.images {
51 uploaded.push(
52 self.remote
53 .upload_ams_image(&conversation_id, &image.bytes, &image_file_name(image))
54 .await?,
55 );
56 }
57 let body = with_ams_images(html, &uploaded);
58 let quote_html = quote.map(|quote| quote.html.as_str()).unwrap_or_default();
59 let content = format!("{quote_html}{}", chatsvc_mention_html(&body, mentions));
60 let message_id = self
61 .remote
62 .post_chatsvc_message(conversation, &content, &me.display_name, &properties)
63 .await?;
64 let created_at = message_id
65 .parse::<i64>()
66 .ok()
67 .and_then(DateTime::from_timestamp_millis)
68 .unwrap_or_else(Utc::now);
69 let cached_html = format!("{quote_html}{body}");
70 let attachments: Vec<Value> = extras
71 .files
72 .iter()
73 .map(|file| {
74 json!({
75 "id": file.attachment_id,
76 "contentType": "reference",
77 "contentUrl": file.content_url,
78 "name": file.name,
79 })
80 })
81 .collect();
82 let message = serde_json::from_value(json!({
83 "id": message_id,
84 "messageType": "message",
85 "createdDateTime": created_at.to_rfc3339(),
86 "replyToId": root_id,
87 "importance": extras.importance,
88 "from": {"user": {"id": me.user_id, "displayName": me.display_name}},
89 "body": {"contentType": "html", "content": cached_html},
90 "mentions": mentions.iter().map(OutgoingMention::to_json).collect::<Vec<_>>(),
91 "attachments": attachments,
92 }))
93 .map_err(|_| Error::Unsupported("a chatsvc send without a message shape"))?;
94 Ok(ChatsvcSent {
95 message,
96 html: cached_html,
97 })
98 }
99}
100
101fn image_file_name(image: &HostedImage) -> String {
102 let extension = image
103 .content_type
104 .rsplit('/')
105 .next()
106 .filter(|extension| !extension.is_empty())
107 .unwrap_or("png");
108 format!("image.{extension}")
109}
110
111/// Swaps each Graph `../hostedContents/{n}/$value` image for its AMS upload; images not placed in the text go last.
112fn with_ams_images(html: &str, uploaded: &[AmsImage]) -> String {
113 let mut body = html.to_owned();
114 for (index, image) in uploaded.iter().enumerate() {
115 let tag = format!(
116 "<img itemtype=\"{AMS_IMAGE_ITEMTYPE}\" itemscope=\"\" src=\"{}\" itemid=\"{}\" alt=\"image\">",
117 image.url, image.object_id
118 );
119 let placeholder = format!("{HOSTED_PREFIX}{}{HOSTED_SUFFIX}", index + 1);
120 match image_tag_around(&body, &placeholder) {
121 Some((start, end)) => body.replace_range(start..end, &tag),
122 None => body.push_str(&format!("<p>{tag}</p>")),
123 }
124 }
125 body
126}
127
128fn image_tag_around(html: &str, source: &str) -> Option<(usize, usize)> {
129 let at = html.find(&format!("\"{source}\""))?;
130 let start = html[..at].rfind("<img")?;
131 let end = html[at..].find('>')? + at + 1;
132 Some((start, end))
133}
134
135/// The `files` property Teams writes for a shared OneDrive or SharePoint file.
136fn files_property(files: &[FileReference]) -> Value {
137 Value::Array(
138 files
139 .iter()
140 .map(|file| {
141 let file_type = file
142 .name
143 .rsplit_once('.')
144 .map(|(_, extension)| extension.to_ascii_lowercase())
145 .unwrap_or_default();
146 json!({
147 "@type": FILE_ITEMTYPE,
148 "version": 2,
149 "id": file.attachment_id,
150 "itemid": file.attachment_id,
151 "baseUrl": site_url(&file.content_url),
152 "type": file_type,
153 "fileType": file_type,
154 "title": file.name,
155 "fileName": file.name,
156 "state": "active",
157 "objectUrl": file.content_url,
158 "fileInfo": {
159 "itemId": null,
160 "fileUrl": file.content_url,
161 "siteUrl": site_url(&file.content_url),
162 "serverRelativeUrl": "",
163 "shareUrl": null,
164 "shareId": null,
165 },
166 "fileChicletState": {"serviceName": "p2p", "state": "active"},
167 "permissionScope": "users",
168 })
169 })
170 .collect(),
171 )
172}
173
174/// `https://tenant-my.sharepoint.com/personal/ann/` for a file under that site.
175fn site_url(url: &str) -> String {
176 SITE_SEGMENTS
177 .iter()
178 .find_map(|segment| {
179 let start = url.find(segment)? + segment.len();
180 let end = url[start..].find('/')? + start + 1;
181 Some(url[..end].to_owned())
182 })
183 .unwrap_or_default()
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 fn uploaded(object_id: &str) -> AmsImage {
191 AmsImage {
192 object_id: object_id.into(),
193 url: format!("https://ams.example/{object_id}"),
194 }
195 }
196
197 #[test]
198 fn hosted_images_become_ams_images_in_place_or_last() {
199 let html = r#"<p>a<img src="../hostedContents/2/$value" width="20">b</p>"#;
200 let body = with_ams_images(html, &[uploaded("one"), uploaded("two")]);
201 assert_eq!(
202 body,
203 r#"<p>a<img itemtype="http://schema.skype.com/AMSImage" itemscope="" src="https://ams.example/two" itemid="two" alt="image">b</p><p><img itemtype="http://schema.skype.com/AMSImage" itemscope="" src="https://ams.example/one" itemid="one" alt="image"></p>"#
204 );
205 }
206
207 #[test]
208 fn a_file_names_its_site() {
209 let files = files_property(&[FileReference {
210 attachment_id: "guid-1".into(),
211 content_url:
212 "https://contoso-my.sharepoint.com/personal/ann_contoso_com/Documents/Plan.DOCX"
213 .into(),
214 name: "Plan.DOCX".into(),
215 }]);
216 assert_eq!(
217 files[0]["baseUrl"],
218 "https://contoso-my.sharepoint.com/personal/ann_contoso_com/"
219 );
220 assert_eq!(files[0]["fileType"], "docx");
221 assert_eq!(
222 files[0]["fileInfo"]["fileUrl"],
223 "https://contoso-my.sharepoint.com/personal/ann_contoso_com/Documents/Plan.DOCX"
224 );
225 }
226}
crates/core/src/lib.rs +2 −0
@@ -18,6 +18,7 @@ mod channel_mentions;
18 18 mod channel_sync;
19 19 mod channel_visibility;
20 20 mod chat_paging;
21 mod chat_send;
21 22 mod chat_settings_sync;
22 23 mod cloud_files;
23 24 mod copilot;
@@ -49,6 +50,7 @@ mod mentions;
49 50 mod message_actions;
50 51 mod message_link;
51 52 mod message_window;
53 pub mod native;
52 54 mod notes_chat;
53 55 mod people;
54 56 mod presence;
@@ -18,6 +18,7 @@ mod channel_mentions;
18mod channel_sync;
18mod channel_sync;
19mod channel_visibility;
19mod channel_visibility;
20mod chat_paging;
20mod chat_paging;
21mod chat_send;
21mod chat_settings_sync;
22mod chat_settings_sync;
22mod cloud_files;
23mod cloud_files;
23mod copilot;
24mod copilot;
@@ -49,6 +50,7 @@ mod mentions;
49mod message_actions;
50mod message_actions;
50mod message_link;
51mod message_link;
51mod message_window;
52mod message_window;
53pub mod native;
52mod notes_chat;
54mod notes_chat;
53mod people;
55mod people;
54mod presence;
56mod presence;
crates/core/src/native/chat.rs added +309 −0
@@ -0,0 +1,309 @@
1 use chrono::{DateTime, Utc};
2 use graph::Chat;
3 use serde_json::{Value, json};
4
5 use super::message::graph_message_json;
6
7 const ORGID_PREFIX: &str = "8:orgid:";
8 const ONE_ON_ONE_SUFFIX: &str = "@unq.gbl.spaces";
9 const OWNER_ROLE: &str = "admin";
10
11 /// A chat member before its name is known.
12 #[derive(Debug, Clone, PartialEq, Eq)]
13 pub struct NativeMember {
14 pub user_id: String,
15 pub owner: bool,
16 pub name: Option<String>,
17 }
18
19 /// Graph lists chats, meetings and 1:1s; channels, teams and the service streams stay out.
20 pub fn chat_type(conversation: &Value) -> Option<&'static str> {
21 let id = conversation["id"].as_str()?;
22 if id.ends_with(ONE_ON_ONE_SUFFIX) {
23 return Some("oneOnOne");
24 }
25 let thread = &conversation["threadProperties"];
26 match thread["productThreadType"].as_str() {
27 Some("OneToOneChat") => return Some("oneOnOne"),
28 Some("Meeting") => return Some("meeting"),
29 Some("Chat") => return Some("group"),
30 Some(_) => return None,
31 None => {}
32 }
33 match thread["threadType"].as_str() {
34 Some("chat") if id.starts_with("19:") => Some("group"),
35 Some("meeting") => Some("meeting"),
36 _ => None,
37 }
38 }
39
40 /// The two user ids of a `19:{a}_{b}@unq.gbl.spaces` chat.
41 pub fn one_on_one_ids(chat_id: &str) -> Option<[String; 2]> {
42 let pair = chat_id
43 .strip_prefix("19:")?
44 .strip_suffix(ONE_ON_ONE_SUFFIX)?;
45 let (first, second) = pair.split_once('_')?;
46 Some([first.to_owned(), second.to_owned()])
47 }
48
49 pub fn thread_members(thread: &Value) -> Vec<NativeMember> {
50 thread["members"]
51 .as_array()
52 .into_iter()
53 .flatten()
54 .filter_map(|member| {
55 let user_id = member["id"].as_str()?.strip_prefix(ORGID_PREFIX)?;
56 Some(NativeMember {
57 user_id: user_id.to_owned(),
58 owner: member["role"]
59 .as_str()
60 .is_some_and(|role| role.eq_ignore_ascii_case(OWNER_ROLE)),
61 name: None,
62 })
63 })
64 .collect()
65 }
66
67 pub fn graph_member(member: &NativeMember, email: Option<&str>) -> Value {
68 json!({
69 "id": member.user_id,
70 "userId": member.user_id,
71 "displayName": member.name,
72 "email": email,
73 "roles": if member.owner { vec!["owner"] } else { Vec::new() },
74 })
75 }
76
77 /// A chat service conversation in the shape of a Graph chat with `members` and `lastMessagePreview`.
78 pub fn graph_chat(conversation: &Value, members: Vec<Value>) -> Option<Chat> {
79 let id = conversation["id"].as_str()?;
80 let kind = chat_type(conversation)?;
81 let thread = &conversation["threadProperties"];
82 let created = millis_text(&thread["createdat"]);
83 let read = chatsvc::ReadHorizon::from_conversation(conversation);
84 let preview = preview(id, &conversation["lastMessage"]);
85 let last_updated = preview
86 .as_ref()
87 .and_then(|preview| preview["createdDateTime"].as_str().map(str::to_owned))
88 .or_else(|| created.clone());
89 serde_json::from_value(json!({
90 "id": id,
91 "topic": thread["topic"].as_str().filter(|topic| !topic.trim().is_empty()),
92 "chatType": kind,
93 "createdDateTime": created,
94 "lastUpdatedDateTime": last_updated,
95 "members": members,
96 "lastMessagePreview": preview,
97 "viewpoint": {
98 "lastMessageReadDateTime": read_time(read.consumed_until_ms),
99 "isHidden": null,
100 },
101 }))
102 .ok()
103 }
104
105 /// One chat from the chat service aggregator (`teams/users/me/chats/{id}`), which also has the meeting link.
106 pub fn graph_chat_from_aggregator(chat: &Value, members: Vec<Value>) -> Option<Chat> {
107 let id = chat["id"].as_str()?;
108 let kind = if chat["isOneOnOne"].as_bool() == Some(true) || id.ends_with(ONE_ON_ONE_SUFFIX) {
109 "oneOnOne"
110 } else if chat["chatType"].as_str() == Some("meeting") {
111 "meeting"
112 } else {
113 "group"
114 };
115 let preview = preview(id, &chat["lastMessage"]);
116 let read_ms = chat
117 .pointer("/consumptionHorizon/originalArrivalTime")
118 .and_then(Value::as_i64)
119 .unwrap_or(0);
120 serde_json::from_value(json!({
121 "id": id,
122 "topic": chat["title"].as_str().filter(|topic| !topic.trim().is_empty() && kind != "oneOnOne"),
123 "chatType": kind,
124 "createdDateTime": chat["createdAt"].as_str().and_then(rfc3339),
125 "lastUpdatedDateTime": preview.as_ref().and_then(|preview| preview["createdDateTime"].as_str().map(str::to_owned)),
126 "members": members,
127 "lastMessagePreview": preview,
128 "viewpoint": {"lastMessageReadDateTime": read_time(read_ms), "isHidden": null},
129 "onlineMeetingInfo": {"joinWebUrl": chat.pointer("/meetingInformation/meetingJoinUrl")},
130 }))
131 .ok()
132 }
133
134 pub fn aggregator_members(chat: &Value) -> Vec<NativeMember> {
135 chat["members"]
136 .as_array()
137 .into_iter()
138 .flatten()
139 .filter_map(|member| {
140 let user_id = member["mri"].as_str()?.strip_prefix(ORGID_PREFIX)?;
141 Some(NativeMember {
142 user_id: user_id.to_owned(),
143 owner: member["role"]
144 .as_str()
145 .is_some_and(|role| role.eq_ignore_ascii_case(OWNER_ROLE)),
146 name: member["friendlyName"]
147 .as_str()
148 .map(str::trim)
149 .filter(|name| !name.is_empty())
150 .map(str::to_owned),
151 })
152 })
153 .collect()
154 }
155
156 /// Graph previews every last message; one the record mapping skips still dates the chat.
157 fn preview(conversation_id: &str, last_message: &Value) -> Option<Value> {
158 if last_message
159 .as_object()
160 .is_none_or(|object| object.is_empty())
161 {
162 return None;
163 }
164 graph_message_json(conversation_id, last_message).or_else(|| {
165 let id = chatsvc::id_text(last_message.get("id")?)?;
166 let time = [
167 "originalarrivaltime",
168 "originalArrivalTime",
169 "composetime",
170 "composeTime",
171 ]
172 .iter()
173 .find_map(|key| last_message[*key].as_str())
174 .and_then(rfc3339)?;
175 Some(json!({"id": id, "messageType": "systemEventMessage", "createdDateTime": time}))
176 })
177 }
178
179 fn read_time(millis: i64) -> Option<String> {
180 (millis > 0)
181 .then(|| DateTime::<Utc>::from_timestamp_millis(millis))
182 .flatten()
183 .map(|time| time.to_rfc3339())
184 }
185
186 fn millis_text(value: &Value) -> Option<String> {
187 let millis = value.as_i64().or_else(|| value.as_str()?.parse().ok())?;
188 read_time(millis)
189 }
190
191 fn rfc3339(text: &str) -> Option<String> {
192 DateTime::parse_from_rfc3339(text)
193 .ok()
194 .map(|time| time.with_timezone(&Utc).to_rfc3339())
195 }
196
197 #[cfg(test)]
198 mod tests {
199 use serde_json::json;
200
201 use super::*;
202 use crate::mapping::chat_record;
203
204 fn conversation(id: &str, product: &str) -> Value {
205 json!({
206 "id": id,
207 "properties": {"consumptionhorizon": "1794474789021;1794474789021;1"},
208 "threadProperties": {"productThreadType": product, "topic": "Plan", "createdat": "1790000000000"},
209 "lastMessage": {
210 "id": "1794474789021",
211 "messagetype": "RichText/Html",
212 "content": "<p>hi</p>",
213 "from": "https://x/contacts/8:orgid:ann",
214 "imdisplayname": "Ann",
215 "originalarrivaltime": "2026-11-12T09:13:09.021Z",
216 },
217 })
218 }
219
220 #[test]
221 fn channels_and_streams_are_not_chats() {
222 assert_eq!(
223 chat_type(&conversation("19:a@thread.tacv2", "TeamsStandardChannel")),
224 None
225 );
226 assert_eq!(
227 chat_type(&conversation("48:notifications", "StreamOfNotifications")),
228 None
229 );
230 assert_eq!(
231 chat_type(&conversation("19:a@thread.v2", "Meeting")),
232 Some("meeting")
233 );
234 assert_eq!(
235 chat_type(&json!({"id": "19:ann_bob@unq.gbl.spaces"})),
236 Some("oneOnOne")
237 );
238 }
239
240 #[test]
241 fn a_read_group_chat_maps_to_a_record() {
242 let members = vec![
243 graph_member(
244 &NativeMember {
245 user_id: "me".into(),
246 owner: true,
247 name: Some("Me".into()),
248 },
249 None,
250 ),
251 graph_member(
252 &NativeMember {
253 user_id: "ann".into(),
254 owner: false,
255 name: Some("Ann Example".into()),
256 },
257 None,
258 ),
259 ];
260 let chat = graph_chat(&conversation("19:a@thread.v2", "Chat"), members).unwrap();
261 let record = chat_record(&chat, "me");
262 assert_eq!(record.title, "Plan");
263 assert_eq!(record.kind, "group");
264 assert_eq!(record.member_summary, "Ann Example");
265 assert_eq!(record.last_message_preview.as_deref(), Some("hi"));
266 assert!(!record.unread);
267 assert!(chat.members[0].is_owner());
268 }
269
270 #[test]
271 fn an_unmapped_last_message_still_dates_the_chat() {
272 let mut pinned = conversation("19:a@thread.v2", "Chat");
273 pinned["lastMessage"]["messagetype"] = json!("ThreadActivity/PinnedItemsUpdate");
274 let chat = graph_chat(&pinned, Vec::new()).unwrap();
275 assert!(chat.last_message_time().is_some());
276 }
277
278 #[test]
279 fn the_aggregator_chat_has_the_meeting_link() {
280 let chat = json!({
281 "id": "19:meeting_x@thread.v2",
282 "chatType": "meeting",
283 "title": "Daily",
284 "members": [{"mri": "8:orgid:ann", "role": "Admin", "friendlyName": "Ann"}],
285 "meetingInformation": {"meetingJoinUrl": "https://teams.microsoft.com/l/meetup-join/x"},
286 "lastMessage": {"id": "1", "messageType": "Text", "content": "hi", "from": "8:orgid:ann", "originalArrivalTime": "2026-11-12T09:13:09.021Z"},
287 });
288 let members: Vec<Value> = aggregator_members(&chat)
289 .iter()
290 .map(|member| graph_member(member, None))
291 .collect();
292 let graph = graph_chat_from_aggregator(&chat, members).unwrap();
293 assert_eq!(graph.chat_type, "meeting");
294 assert_eq!(graph.members[0].display_name.as_deref(), Some("Ann"));
295 assert_eq!(
296 graph.online_meeting_info.unwrap().join_web_url.as_deref(),
297 Some("https://teams.microsoft.com/l/meetup-join/x")
298 );
299 }
300
301 #[test]
302 fn one_on_one_ids_split_the_pair() {
303 assert_eq!(
304 one_on_one_ids("19:ann_bob@unq.gbl.spaces"),
305 Some(["ann".to_owned(), "bob".to_owned()])
306 );
307 assert_eq!(one_on_one_ids("19:a@thread.v2"), None);
308 }
309 }
@@ -0,0 +1,309 @@
1use chrono::{DateTime, Utc};
2use graph::Chat;
3use serde_json::{Value, json};
4
5use super::message::graph_message_json;
6
7const ORGID_PREFIX: &str = "8:orgid:";
8const ONE_ON_ONE_SUFFIX: &str = "@unq.gbl.spaces";
9const OWNER_ROLE: &str = "admin";
10
11/// A chat member before its name is known.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct NativeMember {
14 pub user_id: String,
15 pub owner: bool,
16 pub name: Option<String>,
17}
18
19/// Graph lists chats, meetings and 1:1s; channels, teams and the service streams stay out.
20pub fn chat_type(conversation: &Value) -> Option<&'static str> {
21 let id = conversation["id"].as_str()?;
22 if id.ends_with(ONE_ON_ONE_SUFFIX) {
23 return Some("oneOnOne");
24 }
25 let thread = &conversation["threadProperties"];
26 match thread["productThreadType"].as_str() {
27 Some("OneToOneChat") => return Some("oneOnOne"),
28 Some("Meeting") => return Some("meeting"),
29 Some("Chat") => return Some("group"),
30 Some(_) => return None,
31 None => {}
32 }
33 match thread["threadType"].as_str() {
34 Some("chat") if id.starts_with("19:") => Some("group"),
35 Some("meeting") => Some("meeting"),
36 _ => None,
37 }
38}
39
40/// The two user ids of a `19:{a}_{b}@unq.gbl.spaces` chat.
41pub fn one_on_one_ids(chat_id: &str) -> Option<[String; 2]> {
42 let pair = chat_id
43 .strip_prefix("19:")?
44 .strip_suffix(ONE_ON_ONE_SUFFIX)?;
45 let (first, second) = pair.split_once('_')?;
46 Some([first.to_owned(), second.to_owned()])
47}
48
49pub fn thread_members(thread: &Value) -> Vec<NativeMember> {
50 thread["members"]
51 .as_array()
52 .into_iter()
53 .flatten()
54 .filter_map(|member| {
55 let user_id = member["id"].as_str()?.strip_prefix(ORGID_PREFIX)?;
56 Some(NativeMember {
57 user_id: user_id.to_owned(),
58 owner: member["role"]
59 .as_str()
60 .is_some_and(|role| role.eq_ignore_ascii_case(OWNER_ROLE)),
61 name: None,
62 })
63 })
64 .collect()
65}
66
67pub fn graph_member(member: &NativeMember, email: Option<&str>) -> Value {
68 json!({
69 "id": member.user_id,
70 "userId": member.user_id,
71 "displayName": member.name,
72 "email": email,
73 "roles": if member.owner { vec!["owner"] } else { Vec::new() },
74 })
75}
76
77/// A chat service conversation in the shape of a Graph chat with `members` and `lastMessagePreview`.
78pub fn graph_chat(conversation: &Value, members: Vec<Value>) -> Option<Chat> {
79 let id = conversation["id"].as_str()?;
80 let kind = chat_type(conversation)?;
81 let thread = &conversation["threadProperties"];
82 let created = millis_text(&thread["createdat"]);
83 let read = chatsvc::ReadHorizon::from_conversation(conversation);
84 let preview = preview(id, &conversation["lastMessage"]);
85 let last_updated = preview
86 .as_ref()
87 .and_then(|preview| preview["createdDateTime"].as_str().map(str::to_owned))
88 .or_else(|| created.clone());
89 serde_json::from_value(json!({
90 "id": id,
91 "topic": thread["topic"].as_str().filter(|topic| !topic.trim().is_empty()),
92 "chatType": kind,
93 "createdDateTime": created,
94 "lastUpdatedDateTime": last_updated,
95 "members": members,
96 "lastMessagePreview": preview,
97 "viewpoint": {
98 "lastMessageReadDateTime": read_time(read.consumed_until_ms),
99 "isHidden": null,
100 },
101 }))
102 .ok()
103}
104
105/// One chat from the chat service aggregator (`teams/users/me/chats/{id}`), which also has the meeting link.
106pub fn graph_chat_from_aggregator(chat: &Value, members: Vec<Value>) -> Option<Chat> {
107 let id = chat["id"].as_str()?;
108 let kind = if chat["isOneOnOne"].as_bool() == Some(true) || id.ends_with(ONE_ON_ONE_SUFFIX) {
109 "oneOnOne"
110 } else if chat["chatType"].as_str() == Some("meeting") {
111 "meeting"
112 } else {
113 "group"
114 };
115 let preview = preview(id, &chat["lastMessage"]);
116 let read_ms = chat
117 .pointer("/consumptionHorizon/originalArrivalTime")
118 .and_then(Value::as_i64)
119 .unwrap_or(0);
120 serde_json::from_value(json!({
121 "id": id,
122 "topic": chat["title"].as_str().filter(|topic| !topic.trim().is_empty() && kind != "oneOnOne"),
123 "chatType": kind,
124 "createdDateTime": chat["createdAt"].as_str().and_then(rfc3339),
125 "lastUpdatedDateTime": preview.as_ref().and_then(|preview| preview["createdDateTime"].as_str().map(str::to_owned)),
126 "members": members,
127 "lastMessagePreview": preview,
128 "viewpoint": {"lastMessageReadDateTime": read_time(read_ms), "isHidden": null},
129 "onlineMeetingInfo": {"joinWebUrl": chat.pointer("/meetingInformation/meetingJoinUrl")},
130 }))
131 .ok()
132}
133
134pub fn aggregator_members(chat: &Value) -> Vec<NativeMember> {
135 chat["members"]
136 .as_array()
137 .into_iter()
138 .flatten()
139 .filter_map(|member| {
140 let user_id = member["mri"].as_str()?.strip_prefix(ORGID_PREFIX)?;
141 Some(NativeMember {
142 user_id: user_id.to_owned(),
143 owner: member["role"]
144 .as_str()
145 .is_some_and(|role| role.eq_ignore_ascii_case(OWNER_ROLE)),
146 name: member["friendlyName"]
147 .as_str()
148 .map(str::trim)
149 .filter(|name| !name.is_empty())
150 .map(str::to_owned),
151 })
152 })
153 .collect()
154}
155
156/// Graph previews every last message; one the record mapping skips still dates the chat.
157fn preview(conversation_id: &str, last_message: &Value) -> Option<Value> {
158 if last_message
159 .as_object()
160 .is_none_or(|object| object.is_empty())
161 {
162 return None;
163 }
164 graph_message_json(conversation_id, last_message).or_else(|| {
165 let id = chatsvc::id_text(last_message.get("id")?)?;
166 let time = [
167 "originalarrivaltime",
168 "originalArrivalTime",
169 "composetime",
170 "composeTime",
171 ]
172 .iter()
173 .find_map(|key| last_message[*key].as_str())
174 .and_then(rfc3339)?;
175 Some(json!({"id": id, "messageType": "systemEventMessage", "createdDateTime": time}))
176 })
177}
178
179fn read_time(millis: i64) -> Option<String> {
180 (millis > 0)
181 .then(|| DateTime::<Utc>::from_timestamp_millis(millis))
182 .flatten()
183 .map(|time| time.to_rfc3339())
184}
185
186fn millis_text(value: &Value) -> Option<String> {
187 let millis = value.as_i64().or_else(|| value.as_str()?.parse().ok())?;
188 read_time(millis)
189}
190
191fn rfc3339(text: &str) -> Option<String> {
192 DateTime::parse_from_rfc3339(text)
193 .ok()
194 .map(|time| time.with_timezone(&Utc).to_rfc3339())
195}
196
197#[cfg(test)]
198mod tests {
199 use serde_json::json;
200
201 use super::*;
202 use crate::mapping::chat_record;
203
204 fn conversation(id: &str, product: &str) -> Value {
205 json!({
206 "id": id,
207 "properties": {"consumptionhorizon": "1794474789021;1794474789021;1"},
208 "threadProperties": {"productThreadType": product, "topic": "Plan", "createdat": "1790000000000"},
209 "lastMessage": {
210 "id": "1794474789021",
211 "messagetype": "RichText/Html",
212 "content": "<p>hi</p>",
213 "from": "https://x/contacts/8:orgid:ann",
214 "imdisplayname": "Ann",
215 "originalarrivaltime": "2026-11-12T09:13:09.021Z",
216 },
217 })
218 }
219
220 #[test]
221 fn channels_and_streams_are_not_chats() {
222 assert_eq!(
223 chat_type(&conversation("19:a@thread.tacv2", "TeamsStandardChannel")),
224 None
225 );
226 assert_eq!(
227 chat_type(&conversation("48:notifications", "StreamOfNotifications")),
228 None
229 );
230 assert_eq!(
231 chat_type(&conversation("19:a@thread.v2", "Meeting")),
232 Some("meeting")
233 );
234 assert_eq!(
235 chat_type(&json!({"id": "19:ann_bob@unq.gbl.spaces"})),
236 Some("oneOnOne")
237 );
238 }
239
240 #[test]
241 fn a_read_group_chat_maps_to_a_record() {
242 let members = vec![
243 graph_member(
244 &NativeMember {
245 user_id: "me".into(),
246 owner: true,
247 name: Some("Me".into()),
248 },
249 None,
250 ),
251 graph_member(
252 &NativeMember {
253 user_id: "ann".into(),
254 owner: false,
255 name: Some("Ann Example".into()),
256 },
257 None,
258 ),
259 ];
260 let chat = graph_chat(&conversation("19:a@thread.v2", "Chat"), members).unwrap();
261 let record = chat_record(&chat, "me");
262 assert_eq!(record.title, "Plan");
263 assert_eq!(record.kind, "group");
264 assert_eq!(record.member_summary, "Ann Example");
265 assert_eq!(record.last_message_preview.as_deref(), Some("hi"));
266 assert!(!record.unread);
267 assert!(chat.members[0].is_owner());
268 }
269
270 #[test]
271 fn an_unmapped_last_message_still_dates_the_chat() {
272 let mut pinned = conversation("19:a@thread.v2", "Chat");
273 pinned["lastMessage"]["messagetype"] = json!("ThreadActivity/PinnedItemsUpdate");
274 let chat = graph_chat(&pinned, Vec::new()).unwrap();
275 assert!(chat.last_message_time().is_some());
276 }
277
278 #[test]
279 fn the_aggregator_chat_has_the_meeting_link() {
280 let chat = json!({
281 "id": "19:meeting_x@thread.v2",
282 "chatType": "meeting",
283 "title": "Daily",
284 "members": [{"mri": "8:orgid:ann", "role": "Admin", "friendlyName": "Ann"}],
285 "meetingInformation": {"meetingJoinUrl": "https://teams.microsoft.com/l/meetup-join/x"},
286 "lastMessage": {"id": "1", "messageType": "Text", "content": "hi", "from": "8:orgid:ann", "originalArrivalTime": "2026-11-12T09:13:09.021Z"},
287 });
288 let members: Vec<Value> = aggregator_members(&chat)
289 .iter()
290 .map(|member| graph_member(member, None))
291 .collect();
292 let graph = graph_chat_from_aggregator(&chat, members).unwrap();
293 assert_eq!(graph.chat_type, "meeting");
294 assert_eq!(graph.members[0].display_name.as_deref(), Some("Ann"));
295 assert_eq!(
296 graph.online_meeting_info.unwrap().join_web_url.as_deref(),
297 Some("https://teams.microsoft.com/l/meetup-join/x")
298 );
299 }
300
301 #[test]
302 fn one_on_one_ids_split_the_pair() {
303 assert_eq!(
304 one_on_one_ids("19:ann_bob@unq.gbl.spaces"),
305 Some(["ann".to_owned(), "bob".to_owned()])
306 );
307 assert_eq!(one_on_one_ids("19:a@thread.v2"), None);
308 }
309}
crates/core/src/native/markup.rs added +301 −0
@@ -0,0 +1,301 @@
1 use std::collections::HashMap;
2
3 pub(crate) use chatsvc::graph_events::{attribute, unescape};
4
5 const MENTION_ITEMTYPE: &str = "schema.skype.com/Mention";
6 const INPUT_EXTENSION_ITEMTYPE: &str = "schema.skype.com/InputExtension";
7 const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";
8 const EMOTICON_CLASS: &str = "animated-emoticon";
9 const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
10
11 /// A chat service body in the shape Graph serves it: `<at>` mentions and `<attachment>` markers.
12 #[derive(Debug, Default, PartialEq, Eq)]
13 pub(crate) struct GraphBody {
14 pub html: String,
15 pub mention_texts: HashMap<String, String>,
16 pub forwards: Vec<String>,
17 pub quotes: Vec<QuotedMessage>,
18 }
19
20 /// A Teams reply quote, which Graph serves as a `messageReference` attachment.
21 #[derive(Debug, PartialEq, Eq)]
22 pub(crate) struct QuotedMessage {
23 pub message_id: String,
24 pub sender_mri: Option<String>,
25 pub sender_name: Option<String>,
26 pub preview: String,
27 }
28
29 /// `forward_ids` name the `<attachment>` that replaces each forward quote, in order.
30 pub(crate) fn graph_body(content: &str, forward_ids: &[String]) -> GraphBody {
31 let mut body = GraphBody::default();
32 let mut rest = content;
33 while let Some(start) = rest.find('<') {
34 body.html.push_str(&rest[..start]);
35 rest = &rest[start..];
36 let Some(element) = Element::open_at(rest) else {
37 body.html.push('<');
38 rest = &rest[1..];
39 continue;
40 };
41 let itemtype = attribute(element.tag, "itemtype").unwrap_or_default();
42 let class = attribute(element.tag, "class").unwrap_or_default();
43 let Some(rewrite) = Rewrite::of(element.name, itemtype, class) else {
44 body.html.push_str(element.tag);
45 rest = &rest[element.tag.len()..];
46 continue;
47 };
48 let Some((inner, after)) = element.inner_and_rest(rest) else {
49 body.html.push_str(element.tag);
50 rest = &rest[element.tag.len()..];
51 continue;
52 };
53 let item_id = attribute(element.tag, "itemid").unwrap_or_default();
54 match rewrite {
55 Rewrite::Mention => {
56 let text = plain_text(inner);
57 body.mention_texts.insert(item_id.to_owned(), text);
58 body.html
59 .push_str(&format!("<at id=\"{item_id}\">{inner}</at>"));
60 }
61 Rewrite::Emoticon => match emoji_tag(inner) {
62 Some(tag) => body.html.push_str(&tag),
63 None => body.html.push_str(&rest[..rest.len() - after.len()]),
64 },
65 Rewrite::Reply if !item_id.is_empty() => {
66 body.html
67 .push_str(&format!("<attachment id=\"{item_id}\"></attachment>"));
68 body.quotes.push(quoted_message(item_id, inner));
69 }
70 Rewrite::Reply => body.html.push_str(&rest[..rest.len() - after.len()]),
71 Rewrite::Card => body
72 .html
73 .push_str(&format!("<attachment id=\"{item_id}\"></attachment>")),
74 Rewrite::Forward => {
75 match forward_ids.get(body.forwards.len()) {
76 Some(id) => body
77 .html
78 .push_str(&format!("<attachment id=\"{id}\"></attachment>")),
79 None => body.html.push_str(&rest[..rest.len() - after.len()]),
80 }
81 body.forwards.push(inner.to_owned());
82 }
83 }
84 rest = after;
85 }
86 body.html.push_str(rest);
87 body
88 }
89
90 #[derive(Clone, Copy)]
91 enum Rewrite {
92 Mention,
93 Emoticon,
94 Reply,
95 Card,
96 Forward,
97 }
98
99 impl Rewrite {
100 fn of(name: &str, itemtype: &str, class: &str) -> Option<Rewrite> {
101 match name {
102 "span" if itemtype.contains(MENTION_ITEMTYPE) => Some(Rewrite::Mention),
103 "span" if class.contains(EMOTICON_CLASS) => Some(Rewrite::Emoticon),
104 "span" if itemtype.contains(INPUT_EXTENSION_ITEMTYPE) => Some(Rewrite::Card),
105 "blockquote" if itemtype.contains(FORWARD_ITEMTYPE) => Some(Rewrite::Forward),
106 "blockquote" if itemtype.contains(REPLY_ITEMTYPE) => Some(Rewrite::Reply),
107 _ => None,
108 }
109 }
110 }
111
112 struct Element<'a> {
113 name: &'a str,
114 tag: &'a str,
115 }
116
117 impl<'a> Element<'a> {
118 fn open_at(text: &'a str) -> Option<Element<'a>> {
119 let end = text.find('>')? + 1;
120 let tag = &text[..end];
121 let name_end = tag[1..].find(|character: char| {
122 character.is_whitespace() || character == '>' || character == '/'
123 })? + 1;
124 let name = &tag[1..name_end];
125 (!name.is_empty()
126 && name
127 .chars()
128 .all(|character| character.is_ascii_alphanumeric()))
129 .then_some(Element { name, tag })
130 }
131
132 /// The text between this element's tags and what follows its closing tag, nested elements of the same name included.
133 fn inner_and_rest(&self, text: &'a str) -> Option<(&'a str, &'a str)> {
134 let open = format!("<{}", self.name);
135 let close = format!("</{}>", self.name);
136 let inner_start = self.tag.len();
137 let mut depth = 1;
138 let mut position = inner_start;
139 while depth > 0 {
140 let next_close = text[position..].find(&close)? + position;
141 match text[position..].find(&open).map(|found| found + position) {
142 Some(next_open)
143 if next_open < next_close && opens_element(text, next_open, &open) =>
144 {
145 depth += 1;
146 position = next_open + open.len();
147 }
148 _ => {
149 depth -= 1;
150 if depth == 0 {
151 return Some((
152 &text[inner_start..next_close],
153 &text[next_close + close.len()..],
154 ));
155 }
156 position = next_close + close.len();
157 }
158 }
159 }
160 None
161 }
162 }
163
164 fn quoted_message(message_id: &str, inner: &str) -> QuotedMessage {
165 let property = |name: &str| -> Option<(&str, &str)> {
166 let marker = format!("itemprop=\"{name}\"");
167 let at = inner.find(&marker)?;
168 let tag_start = inner[..at].rfind('<')?;
169 let element = Element::open_at(&inner[tag_start..])?;
170 let (content, _) = element.inner_and_rest(&inner[tag_start..])?;
171 Some((element.tag, content))
172 };
173 let sender = property("mri");
174 QuotedMessage {
175 message_id: message_id.to_owned(),
176 sender_mri: sender
177 .and_then(|(tag, _)| attribute(tag, "itemid"))
178 .filter(|mri| !mri.is_empty())
179 .map(str::to_owned),
180 sender_name: sender
181 .map(|(_, content)| plain_text(content))
182 .filter(|name| !name.is_empty()),
183 preview: property("preview")
184 .map(|(_, content)| plain_text(content))
185 .unwrap_or_default(),
186 }
187 }
188
189 /// Graph's `<emoji>` for a Teams emoticon span, read from the emoji image inside it.
190 fn emoji_tag(inner: &str) -> Option<String> {
191 let start = inner.find("<img")?;
192 let end = inner[start..].find('>')? + start;
193 let image = &inner[start..end];
194 let id = attribute(image, "itemid")?;
195 let alt = attribute(image, "alt").unwrap_or_default();
196 let title = attribute(image, "title").unwrap_or_default();
197 Some(format!(
198 "<emoji id=\"{id}\" alt=\"{alt}\" title=\"{title}\"></emoji>"
199 ))
200 }
201
202 fn opens_element(text: &str, at: usize, open: &str) -> bool {
203 text[at + open.len()..]
204 .chars()
205 .next()
206 .is_some_and(|next| next.is_whitespace() || next == '>')
207 }
208
209 pub(crate) fn plain_text(html: &str) -> String {
210 let mut text = String::new();
211 let mut in_tag = false;
212 for character in html.chars() {
213 match character {
214 '<' => in_tag = true,
215 '>' => in_tag = false,
216 _ if !in_tag => text.push(character),
217 _ => {}
218 }
219 }
220 unescape(text.trim())
221 }
222
223 #[cfg(test)]
224 mod tests {
225 use super::*;
226
227 #[test]
228 fn mention_spans_become_at_tags() {
229 let body = graph_body(
230 r#"<p>hi <span itemtype="http://schema.skype.com/Mention" itemscope="" itemid="0">Ada &amp; Co</span>!</p>"#,
231 &[],
232 );
233 assert_eq!(body.html, r#"<p>hi <at id="0">Ada &amp; Co</at>!</p>"#);
234 assert_eq!(body.mention_texts["0"], "Ada & Co");
235 }
236
237 #[test]
238 fn emoticon_spans_stay_and_nested_spans_close_right() {
239 let html = r#"<p><span itemtype="http://schema.skype.com/Mention" itemid="1"><span>Bo</span></span> <span title="Smile" type="(smile)" class="animated-emoticon-20-smile" itemscope=""><img itemtype="http://schema.skype.com/Emoji" alt="🙂"></span></p>"#;
240 let body = graph_body(html, &[]);
241 assert!(
242 body.html
243 .starts_with(r#"<p><at id="1"><span>Bo</span></at> <span title="Smile""#)
244 );
245 assert_eq!(body.mention_texts["1"], "Bo");
246 }
247
248 #[test]
249 fn emoticon_spans_become_graph_emoji() {
250 let html = r#"<p>ok<span title="Smile" type="(smile)" class="animated-emoticon-20-smile" itemscope=""><img itemscope="" itemtype="http://schema.skype.com/Emoji" itemid="smile" src="https://x/e.png" title="Smile" alt="🙂"></span></p>"#;
251 assert_eq!(
252 graph_body(html, &[]).html,
253 r#"<p>ok<emoji id="smile" alt="🙂" title="Smile"></emoji></p>"#
254 );
255 }
256
257 #[test]
258 fn reply_quotes_become_message_references() {
259 let html = r#"<blockquote itemscope="" itemtype="http://schema.skype.com/Reply" itemid="1751975663649"><strong itemprop="mri" itemid="8:orgid:ann">Ann</strong><span itemprop="time" itemid="1751975663649"></span><p itemprop="preview">old &amp; true</p></blockquote><p>new</p>"#;
260 let body = graph_body(html, &[]);
261 assert_eq!(
262 body.html,
263 r#"<attachment id="1751975663649"></attachment><p>new</p>"#
264 );
265 assert_eq!(
266 body.quotes,
267 vec![QuotedMessage {
268 message_id: "1751975663649".into(),
269 sender_mri: Some("8:orgid:ann".into()),
270 sender_name: Some("Ann".into()),
271 preview: "old & true".into(),
272 }]
273 );
274 }
275
276 #[test]
277 fn card_placeholders_and_forwards_become_attachment_markers() {
278 let html = r#"<p>see</p><span itemid="card-1" itemscope="" itemtype="http://schema.skype.com/InputExtension"><span itemprop="cardId"></span></span><blockquote itemtype="http://schema.skype.com/Forward"><p>old</p></blockquote>"#;
279 let body = graph_body(html, &["m7".to_owned()]);
280 assert_eq!(
281 body.html,
282 r#"<p>see</p><attachment id="card-1"></attachment><attachment id="m7"></attachment>"#
283 );
284 assert_eq!(body.forwards, vec!["<p>old</p>".to_owned()]);
285 }
286
287 #[test]
288 fn a_forward_without_context_keeps_its_quote() {
289 let html =
290 r#"<blockquote itemtype="http://schema.skype.com/Forward"><p>old</p></blockquote>"#;
291 assert_eq!(graph_body(html, &[]).html, html);
292 }
293
294 #[test]
295 fn broken_markup_is_kept() {
296 assert_eq!(
297 graph_body("a < b <span itemtype=\"x\">", &[]).html,
298 "a < b <span itemtype=\"x\">"
299 );
300 }
301 }
@@ -0,0 +1,301 @@
1use std::collections::HashMap;
2
3pub(crate) use chatsvc::graph_events::{attribute, unescape};
4
5const MENTION_ITEMTYPE: &str = "schema.skype.com/Mention";
6const INPUT_EXTENSION_ITEMTYPE: &str = "schema.skype.com/InputExtension";
7const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";
8const EMOTICON_CLASS: &str = "animated-emoticon";
9const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
10
11/// A chat service body in the shape Graph serves it: `<at>` mentions and `<attachment>` markers.
12#[derive(Debug, Default, PartialEq, Eq)]
13pub(crate) struct GraphBody {
14 pub html: String,
15 pub mention_texts: HashMap<String, String>,
16 pub forwards: Vec<String>,
17 pub quotes: Vec<QuotedMessage>,
18}
19
20/// A Teams reply quote, which Graph serves as a `messageReference` attachment.
21#[derive(Debug, PartialEq, Eq)]
22pub(crate) struct QuotedMessage {
23 pub message_id: String,
24 pub sender_mri: Option<String>,
25 pub sender_name: Option<String>,
26 pub preview: String,
27}
28
29/// `forward_ids` name the `<attachment>` that replaces each forward quote, in order.
30pub(crate) fn graph_body(content: &str, forward_ids: &[String]) -> GraphBody {
31 let mut body = GraphBody::default();
32 let mut rest = content;
33 while let Some(start) = rest.find('<') {
34 body.html.push_str(&rest[..start]);
35 rest = &rest[start..];
36 let Some(element) = Element::open_at(rest) else {
37 body.html.push('<');
38 rest = &rest[1..];
39 continue;
40 };
41 let itemtype = attribute(element.tag, "itemtype").unwrap_or_default();
42 let class = attribute(element.tag, "class").unwrap_or_default();
43 let Some(rewrite) = Rewrite::of(element.name, itemtype, class) else {
44 body.html.push_str(element.tag);
45 rest = &rest[element.tag.len()..];
46 continue;
47 };
48 let Some((inner, after)) = element.inner_and_rest(rest) else {
49 body.html.push_str(element.tag);
50 rest = &rest[element.tag.len()..];
51 continue;
52 };
53 let item_id = attribute(element.tag, "itemid").unwrap_or_default();
54 match rewrite {
55 Rewrite::Mention => {
56 let text = plain_text(inner);
57 body.mention_texts.insert(item_id.to_owned(), text);
58 body.html
59 .push_str(&format!("<at id=\"{item_id}\">{inner}</at>"));
60 }
61 Rewrite::Emoticon => match emoji_tag(inner) {
62 Some(tag) => body.html.push_str(&tag),
63 None => body.html.push_str(&rest[..rest.len() - after.len()]),
64 },
65 Rewrite::Reply if !item_id.is_empty() => {
66 body.html
67 .push_str(&format!("<attachment id=\"{item_id}\"></attachment>"));
68 body.quotes.push(quoted_message(item_id, inner));
69 }
70 Rewrite::Reply => body.html.push_str(&rest[..rest.len() - after.len()]),
71 Rewrite::Card => body
72 .html
73 .push_str(&format!("<attachment id=\"{item_id}\"></attachment>")),
74 Rewrite::Forward => {
75 match forward_ids.get(body.forwards.len()) {
76 Some(id) => body
77 .html
78 .push_str(&format!("<attachment id=\"{id}\"></attachment>")),
79 None => body.html.push_str(&rest[..rest.len() - after.len()]),
80 }
81 body.forwards.push(inner.to_owned());
82 }
83 }
84 rest = after;
85 }
86 body.html.push_str(rest);
87 body
88}
89
90#[derive(Clone, Copy)]
91enum Rewrite {
92 Mention,
93 Emoticon,
94 Reply,
95 Card,
96 Forward,
97}
98
99impl Rewrite {
100 fn of(name: &str, itemtype: &str, class: &str) -> Option<Rewrite> {
101 match name {
102 "span" if itemtype.contains(MENTION_ITEMTYPE) => Some(Rewrite::Mention),
103 "span" if class.contains(EMOTICON_CLASS) => Some(Rewrite::Emoticon),
104 "span" if itemtype.contains(INPUT_EXTENSION_ITEMTYPE) => Some(Rewrite::Card),
105 "blockquote" if itemtype.contains(FORWARD_ITEMTYPE) => Some(Rewrite::Forward),
106 "blockquote" if itemtype.contains(REPLY_ITEMTYPE) => Some(Rewrite::Reply),
107 _ => None,
108 }
109 }
110}
111
112struct Element<'a> {
113 name: &'a str,
114 tag: &'a str,
115}
116
117impl<'a> Element<'a> {
118 fn open_at(text: &'a str) -> Option<Element<'a>> {
119 let end = text.find('>')? + 1;
120 let tag = &text[..end];
121 let name_end = tag[1..].find(|character: char| {
122 character.is_whitespace() || character == '>' || character == '/'
123 })? + 1;
124 let name = &tag[1..name_end];
125 (!name.is_empty()
126 && name
127 .chars()
128 .all(|character| character.is_ascii_alphanumeric()))
129 .then_some(Element { name, tag })
130 }
131
132 /// The text between this element's tags and what follows its closing tag, nested elements of the same name included.
133 fn inner_and_rest(&self, text: &'a str) -> Option<(&'a str, &'a str)> {
134 let open = format!("<{}", self.name);
135 let close = format!("</{}>", self.name);
136 let inner_start = self.tag.len();
137 let mut depth = 1;
138 let mut position = inner_start;
139 while depth > 0 {
140 let next_close = text[position..].find(&close)? + position;
141 match text[position..].find(&open).map(|found| found + position) {
142 Some(next_open)
143 if next_open < next_close && opens_element(text, next_open, &open) =>
144 {
145 depth += 1;
146 position = next_open + open.len();
147 }
148 _ => {
149 depth -= 1;
150 if depth == 0 {
151 return Some((
152 &text[inner_start..next_close],
153 &text[next_close + close.len()..],
154 ));
155 }
156 position = next_close + close.len();
157 }
158 }
159 }
160 None
161 }
162}
163
164fn quoted_message(message_id: &str, inner: &str) -> QuotedMessage {
165 let property = |name: &str| -> Option<(&str, &str)> {
166 let marker = format!("itemprop=\"{name}\"");
167 let at = inner.find(&marker)?;
168 let tag_start = inner[..at].rfind('<')?;
169 let element = Element::open_at(&inner[tag_start..])?;
170 let (content, _) = element.inner_and_rest(&inner[tag_start..])?;
171 Some((element.tag, content))
172 };
173 let sender = property("mri");
174 QuotedMessage {
175 message_id: message_id.to_owned(),
176 sender_mri: sender
177 .and_then(|(tag, _)| attribute(tag, "itemid"))
178 .filter(|mri| !mri.is_empty())
179 .map(str::to_owned),
180 sender_name: sender
181 .map(|(_, content)| plain_text(content))
182 .filter(|name| !name.is_empty()),
183 preview: property("preview")
184 .map(|(_, content)| plain_text(content))
185 .unwrap_or_default(),
186 }
187}
188
189/// Graph's `<emoji>` for a Teams emoticon span, read from the emoji image inside it.
190fn emoji_tag(inner: &str) -> Option<String> {
191 let start = inner.find("<img")?;
192 let end = inner[start..].find('>')? + start;
193 let image = &inner[start..end];
194 let id = attribute(image, "itemid")?;
195 let alt = attribute(image, "alt").unwrap_or_default();
196 let title = attribute(image, "title").unwrap_or_default();
197 Some(format!(
198 "<emoji id=\"{id}\" alt=\"{alt}\" title=\"{title}\"></emoji>"
199 ))
200}
201
202fn opens_element(text: &str, at: usize, open: &str) -> bool {
203 text[at + open.len()..]
204 .chars()
205 .next()
206 .is_some_and(|next| next.is_whitespace() || next == '>')
207}
208
209pub(crate) fn plain_text(html: &str) -> String {
210 let mut text = String::new();
211 let mut in_tag = false;
212 for character in html.chars() {
213 match character {
214 '<' => in_tag = true,
215 '>' => in_tag = false,
216 _ if !in_tag => text.push(character),
217 _ => {}
218 }
219 }
220 unescape(text.trim())
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226
227 #[test]
228 fn mention_spans_become_at_tags() {
229 let body = graph_body(
230 r#"<p>hi <span itemtype="http://schema.skype.com/Mention" itemscope="" itemid="0">Ada &amp; Co</span>!</p>"#,
231 &[],
232 );
233 assert_eq!(body.html, r#"<p>hi <at id="0">Ada &amp; Co</at>!</p>"#);
234 assert_eq!(body.mention_texts["0"], "Ada & Co");
235 }
236
237 #[test]
238 fn emoticon_spans_stay_and_nested_spans_close_right() {
239 let html = r#"<p><span itemtype="http://schema.skype.com/Mention" itemid="1"><span>Bo</span></span> <span title="Smile" type="(smile)" class="animated-emoticon-20-smile" itemscope=""><img itemtype="http://schema.skype.com/Emoji" alt="🙂"></span></p>"#;
240 let body = graph_body(html, &[]);
241 assert!(
242 body.html
243 .starts_with(r#"<p><at id="1"><span>Bo</span></at> <span title="Smile""#)
244 );
245 assert_eq!(body.mention_texts["1"], "Bo");
246 }
247
248 #[test]
249 fn emoticon_spans_become_graph_emoji() {
250 let html = r#"<p>ok<span title="Smile" type="(smile)" class="animated-emoticon-20-smile" itemscope=""><img itemscope="" itemtype="http://schema.skype.com/Emoji" itemid="smile" src="https://x/e.png" title="Smile" alt="🙂"></span></p>"#;
251 assert_eq!(
252 graph_body(html, &[]).html,
253 r#"<p>ok<emoji id="smile" alt="🙂" title="Smile"></emoji></p>"#
254 );
255 }
256
257 #[test]
258 fn reply_quotes_become_message_references() {
259 let html = r#"<blockquote itemscope="" itemtype="http://schema.skype.com/Reply" itemid="1751975663649"><strong itemprop="mri" itemid="8:orgid:ann">Ann</strong><span itemprop="time" itemid="1751975663649"></span><p itemprop="preview">old &amp; true</p></blockquote><p>new</p>"#;
260 let body = graph_body(html, &[]);
261 assert_eq!(
262 body.html,
263 r#"<attachment id="1751975663649"></attachment><p>new</p>"#
264 );
265 assert_eq!(
266 body.quotes,
267 vec![QuotedMessage {
268 message_id: "1751975663649".into(),
269 sender_mri: Some("8:orgid:ann".into()),
270 sender_name: Some("Ann".into()),
271 preview: "old & true".into(),
272 }]
273 );
274 }
275
276 #[test]
277 fn card_placeholders_and_forwards_become_attachment_markers() {
278 let html = r#"<p>see</p><span itemid="card-1" itemscope="" itemtype="http://schema.skype.com/InputExtension"><span itemprop="cardId"></span></span><blockquote itemtype="http://schema.skype.com/Forward"><p>old</p></blockquote>"#;
279 let body = graph_body(html, &["m7".to_owned()]);
280 assert_eq!(
281 body.html,
282 r#"<p>see</p><attachment id="card-1"></attachment><attachment id="m7"></attachment>"#
283 );
284 assert_eq!(body.forwards, vec!["<p>old</p>".to_owned()]);
285 }
286
287 #[test]
288 fn a_forward_without_context_keeps_its_quote() {
289 let html =
290 r#"<blockquote itemtype="http://schema.skype.com/Forward"><p>old</p></blockquote>"#;
291 assert_eq!(graph_body(html, &[]).html, html);
292 }
293
294 #[test]
295 fn broken_markup_is_kept() {
296 assert_eq!(
297 graph_body("a < b <span itemtype=\"x\">", &[]).html,
298 "a < b <span itemtype=\"x\">"
299 );
300 }
301}
crates/core/src/native/message.rs added +478 −0
@@ -0,0 +1,478 @@
1 use base64::Engine;
2 use base64::engine::general_purpose::STANDARD;
3 use chrono::{DateTime, Utc};
4 use graph::Message;
5 use serde_json::{Value, json};
6
7 use super::markup::graph_body;
8 use crate::forwarded::FORWARDED_CONTENT_TYPE;
9 use chatsvc::graph_events::{event_detail, is_event, user_id};
10
11 const BOT_PREFIX: &str = "28:";
12 const FORWARD_CONTEXT: &str = "originalMessageContext";
13 const ANNOTATION_KEYS: [&str; 3] = ["follow", "star", "acks"];
14 const SWIFT_MARKER: &str = "<Swift b64=\"";
15
16 /// A chat service message as Graph would serve it, so the record mapping stays the same for both sources.
17 pub fn graph_message(conversation_id: &str, native: &Value) -> Option<Message> {
18 serde_json::from_value(graph_message_json(conversation_id, native)?).ok()
19 }
20
21 pub(crate) fn graph_message_json(conversation_id: &str, native: &Value) -> Option<Value> {
22 let message_type = text(native, &["messagetype", "messageType"])?;
23 let id = chatsvc::id_text(native.get("id")?)?;
24 let properties = &native["properties"];
25 let created = time(
26 native,
27 &[
28 "originalarrivaltime",
29 "originalArrivalTime",
30 "composetime",
31 "composeTime",
32 ],
33 )?;
34 let content = text(native, &["content"]).unwrap_or_default();
35 let sender = sender(native);
36 let sender_user_id = sender
37 .pointer("/user/id")
38 .and_then(Value::as_str)
39 .map(str::to_owned);
40 let mut message = json!({
41 "id": id,
42 "createdDateTime": created,
43 "lastModifiedDateTime": millis(&native["version"]).map(|time| time.to_rfc3339()).unwrap_or_else(|| created.clone()),
44 "lastEditedDateTime": millis(&properties["edittime"]).map(|time| time.to_rfc3339()),
45 "deletedDateTime": millis(&properties["deletetime"]).map(|time| time.to_rfc3339()),
46 "from": sender,
47 "importance": text(properties, &["importance"]),
48 "subject": text(properties, &["subject"]),
49 "reactions": reactions(native),
50 });
51 if is_event(message_type) {
52 message["messageType"] = json!("systemEventMessage");
53 message["eventDetail"] = event_detail(
54 message_type,
55 content,
56 conversation_id,
57 sender_user_id.as_deref(),
58 )?;
59 message["from"] = Value::Null;
60 message["body"] = json!({"contentType": "html", "content": ""});
61 return Some(message);
62 }
63 if !is_user_message(message_type) {
64 return None;
65 }
66 message["messageType"] = json!("message");
67 let forwards = forward_contexts(properties);
68 let forward_ids: Vec<String> = forwards.iter().map(|context| context.id.clone()).collect();
69 let body = graph_body(&content.replace("\r\n", "\n"), &forward_ids);
70 let mut attachments = file_attachments(properties);
71 attachments.extend(card_attachments(properties));
72 if message_type == "RichText/Media_Card" {
73 attachments.extend(swift_attachments(content));
74 }
75 attachments.extend(body.quotes.iter().map(|quote| {
76 json!({
77 "id": quote.message_id,
78 "contentType": "messageReference",
79 "content": json!({
80 "messageId": quote.message_id,
81 "messagePreview": quote.preview,
82 "messageSender": quote.sender_mri.as_deref().map(|mri| json!({"user": {"id": user_id(mri), "displayName": quote.sender_name}})),
83 }).to_string(),
84 })
85 }));
86 attachments.extend(
87 forwards
88 .iter()
89 .zip(&body.forwards)
90 .map(|(context, inner)| context.attachment(inner)),
91 );
92 let mut html = if message_type == "RichText/Media_Card" {
93 String::new()
94 } else {
95 body.html
96 };
97 for marker in &attachments {
98 let Some(attachment_id) = marker["id"].as_str() else {
99 continue;
100 };
101 let tag = format!("<attachment id=\"{attachment_id}\"></attachment>");
102 if !html.contains(&tag) {
103 html.push_str(&tag);
104 }
105 }
106 message["body"] = json!({
107 "contentType": if message_type == "Text" { "text" } else { "html" },
108 "content": html,
109 });
110 message["mentions"] = mentions(properties, &body.mention_texts);
111 message["attachments"] = Value::Array(attachments);
112 Some(message)
113 }
114
115 fn is_user_message(message_type: &str) -> bool {
116 message_type == "Text" || message_type.starts_with("RichText")
117 }
118
119 fn sender(native: &Value) -> Value {
120 let Some(mri) = text(native, &["from"]).and_then(|from| from.rsplit('/').next()) else {
121 return Value::Null;
122 };
123 let name = text(native, &["imdisplayname", "imDisplayName"])
124 .map(str::trim)
125 .filter(|name| !name.is_empty());
126 if let Some(bot_id) = mri.strip_prefix(BOT_PREFIX) {
127 return json!({"application": {"id": bot_id, "displayName": name}});
128 }
129 if mri.starts_with("8:") {
130 return json!({"user": {"id": user_id(mri), "displayName": name}});
131 }
132 Value::Null
133 }
134
135 fn reactions(native: &Value) -> Value {
136 let emotions = chatsvc::parse_message_emotions(&json!({"messages": [native]}));
137 Value::Array(
138 emotions
139 .into_iter()
140 .flat_map(|message| message.reactions)
141 .filter(|reaction| !ANNOTATION_KEYS.contains(&reaction.key.as_str()))
142 .map(|reaction| {
143 json!({
144 "reactionType": chatsvc::reaction_glyph_for_key(&reaction.key).unwrap_or(reaction.key),
145 "createdDateTime": reaction.time_ms.and_then(DateTime::<Utc>::from_timestamp_millis).map(|time| time.to_rfc3339()),
146 "user": {"user": {"id": reaction.user_id, "displayName": null}},
147 })
148 })
149 .collect(),
150 )
151 }
152
153 fn mentions(properties: &Value, texts: &std::collections::HashMap<String, String>) -> Value {
154 Value::Array(
155 json_list(&properties["mentions"])
156 .iter()
157 .filter_map(|mention| {
158 let item_id = chatsvc::id_text(mention.get("itemid")?)?;
159 let mri = mention["mri"].as_str().unwrap_or_default();
160 let name = mention["displayName"].as_str().map(str::to_owned);
161 let identity = json!({"id": user_id(mri), "displayName": name});
162 let mentioned = match mention["mentionType"].as_str().unwrap_or("person") {
163 _ if mri.starts_with("19:") => json!({"conversation": {"id": mri, "displayName": name, "conversationIdentityType": "chat"}}),
164 "tag" => json!({"tag": identity}),
165 "channel" | "team" => json!({"conversation": identity}),
166 _ if mri.starts_with(BOT_PREFIX) => json!({"application": {"id": &mri[BOT_PREFIX.len()..], "displayName": name}}),
167 _ => json!({"user": identity}),
168 };
169 Some(json!({
170 "id": item_id.parse::<i64>().ok()?,
171 "mentionText": texts.get(&item_id).cloned().or(name),
172 "mentioned": mentioned,
173 }))
174 })
175 .collect(),
176 )
177 }
178
179 fn file_attachments(properties: &Value) -> Vec<Value> {
180 json_list(&properties["files"])
181 .iter()
182 .filter_map(|file| {
183 let id = text(file, &["itemid", "id"])?;
184 let url = file
185 .pointer("/fileInfo/fileUrl")
186 .and_then(Value::as_str)
187 .or_else(|| text(file, &["objectUrl"]))?;
188 Some(json!({
189 "id": id,
190 "contentType": "reference",
191 "contentUrl": url,
192 "name": text(file, &["fileName", "title"]),
193 }))
194 })
195 .collect()
196 }
197
198 fn card_attachments(properties: &Value) -> Vec<Value> {
199 json_list(&properties["cards"])
200 .iter()
201 .filter_map(|card| {
202 let content = match &card["content"] {
203 Value::String(text) => text.clone(),
204 Value::Null => return None,
205 other => other.to_string(),
206 };
207 Some(json!({
208 "id": text(card, &["cardClientId"]),
209 "contentType": text(card, &["contentType"]).unwrap_or("application/vnd.microsoft.card.adaptive"),
210 "content": content,
211 "teamsAppId": text(card, &["appId"]),
212 }))
213 })
214 .collect()
215 }
216
217 fn swift_attachments(content: &str) -> Vec<Value> {
218 let Some(start) = content
219 .find(SWIFT_MARKER)
220 .map(|start| start + SWIFT_MARKER.len())
221 else {
222 return Vec::new();
223 };
224 let Some(encoded) = content[start..].split('"').next() else {
225 return Vec::new();
226 };
227 let Some(swift) = STANDARD
228 .decode(encoded)
229 .ok()
230 .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
231 else {
232 return Vec::new();
233 };
234 swift["attachments"]
235 .as_array()
236 .into_iter()
237 .flatten()
238 .enumerate()
239 .filter_map(|(index, attachment)| {
240 let content = match &attachment["content"] {
241 Value::String(text) => text.clone(),
242 Value::Null => return None,
243 other => other.to_string(),
244 };
245 Some(json!({
246 "id": format!("swift-{index}"),
247 "contentType": text(attachment, &["contentType"]),
248 "content": content,
249 }))
250 })
251 .collect()
252 }
253
254 struct ForwardContext {
255 id: String,
256 conversation_id: Option<String>,
257 sender_id: Option<String>,
258 sent_at: Option<String>,
259 }
260
261 impl ForwardContext {
262 fn attachment(&self, inner_html: &str) -> Value {
263 json!({
264 "id": self.id,
265 "contentType": FORWARDED_CONTENT_TYPE,
266 "content": json!({
267 "originalMessageId": self.id,
268 "originalMessageContent": inner_html,
269 "originalConversationId": self.conversation_id,
270 "originalSentDateTime": self.sent_at,
271 "originalMessageSender": self.sender_id.as_ref().map(|id| json!({"user": {"id": id, "displayName": null}})),
272 }).to_string(),
273 })
274 }
275 }
276
277 fn forward_contexts(properties: &Value) -> Vec<ForwardContext> {
278 (0..)
279 .map(|index| match index {
280 0 => FORWARD_CONTEXT.to_owned(),
281 index => format!("{FORWARD_CONTEXT}{index}"),
282 })
283 .map_while(|key| {
284 properties
285 .get(&key)
286 .filter(|context| context.is_object())
287 .cloned()
288 })
289 .filter_map(|context| {
290 Some(ForwardContext {
291 id: chatsvc::id_text(context.get("messageId")?)?,
292 conversation_id: text(&context, &["originalThreadId"]).map(str::to_owned),
293 sender_id: text(&context, &["originalSender"]).map(|mri| user_id(mri).to_owned()),
294 sent_at: text(&context, &["originalSentTime"]).map(str::to_owned),
295 })
296 })
297 .collect()
298 }
299
300 /// Chat service properties carry lists either as JSON text or as arrays.
301 fn json_list(value: &Value) -> Vec<Value> {
302 match value {
303 Value::Array(items) => items.clone(),
304 Value::String(text) => serde_json::from_str::<Value>(text)
305 .ok()
306 .and_then(|parsed| parsed.as_array().cloned())
307 .unwrap_or_default(),
308 _ => Vec::new(),
309 }
310 }
311
312 fn text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
313 keys.iter()
314 .find_map(|key| value.get(*key)?.as_str())
315 .filter(|text| !text.is_empty())
316 }
317
318 fn time(value: &Value, keys: &[&str]) -> Option<String> {
319 let text = text(value, keys)?;
320 DateTime::parse_from_rfc3339(text)
321 .ok()
322 .map(|time| time.with_timezone(&Utc).to_rfc3339())
323 }
324
325 fn millis(value: &Value) -> Option<DateTime<Utc>> {
326 let millis = value.as_i64().or_else(|| value.as_str()?.parse().ok())?;
327 (millis > 0)
328 .then(|| DateTime::<Utc>::from_timestamp_millis(millis))
329 .flatten()
330 }
331
332 #[cfg(test)]
333 mod tests {
334 use serde_json::json;
335
336 use super::*;
337 use crate::mapping::message_record;
338
339 const CHAT: &str = "19:chat@thread.v2";
340
341 fn native(message_type: &str, content: &str, properties: Value) -> Value {
342 json!({
343 "id": "1794474789021",
344 "messagetype": message_type,
345 "content": content,
346 "from": "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/contacts/8:orgid:ann",
347 "imdisplayname": "Ann Example",
348 "originalarrivaltime": "2026-11-12T09:13:09.0210000Z",
349 "composetime": "2026-11-12T09:13:09.0210000Z",
350 "version": "1794474789021",
351 "properties": properties,
352 })
353 }
354
355 #[test]
356 fn a_rich_text_message_maps_like_graph() {
357 let message = native(
358 "RichText/Html",
359 r#"<p>hi <span itemtype="http://schema.skype.com/Mention" itemscope="" itemid="0">Bo</span></p>"#,
360 json!({
361 "mentions": r#"[{"@type":"http://schema.skype.com/Mention","itemid":0,"mri":"8:orgid:bob","mentionType":"person","displayName":"Bo Sample"}]"#,
362 "emotions": [{"key": "like", "users": [{"mri": "8:orgid:bob", "time": 1794474799021i64, "value": "1"}]}],
363 "edittime": 1794474799021i64,
364 "importance": "high",
365 }),
366 );
367 let graph = graph_message(CHAT, &message).unwrap();
368 assert_eq!(graph.from.as_ref().unwrap().user_id(), Some("ann"));
369 assert_eq!(
370 graph.from.as_ref().unwrap().display_name(),
371 Some("Ann Example")
372 );
373 assert_eq!(graph.mentions[0].mention_text.as_deref(), Some("Bo"));
374 assert_eq!(graph.reactions[0].reaction_type, "👍");
375 let record = message_record(CHAT, &graph).unwrap();
376 assert_eq!(record.message_id, "1794474789021");
377 assert_eq!(record.body_html, r#"<p>hi <at id="0">Bo</at></p>"#);
378 assert!(record.edited_at.is_some());
379 assert!(record.mentions_json.contains("\"user_id\":\"bob\""));
380 assert_eq!(record.importance, store::MessageImportance::High);
381 }
382
383 #[test]
384 fn files_and_cards_become_attachments() {
385 let message = native(
386 "RichText/Html",
387 r#"<p>see</p><span itemid="c1" itemscope="" itemtype="http://schema.skype.com/InputExtension"><span itemprop="cardId"></span></span>"#,
388 json!({
389 "files": r#"[{"itemid":"f1","fileName":"plan.docx","fileInfo":{"fileUrl":"https://contoso.sharepoint.com/plan.docx"}}]"#,
390 "cards": [{"cardClientId": "c1", "appId": "app", "contentType": "application/vnd.microsoft.card.adaptive", "content": {"type": "AdaptiveCard", "body": []}}],
391 }),
392 );
393 let graph = graph_message(CHAT, &message).unwrap();
394 let kinds: Vec<_> = graph
395 .attachments
396 .iter()
397 .map(|attachment| attachment.content_type.clone().unwrap())
398 .collect();
399 assert_eq!(
400 kinds,
401 vec!["reference", "application/vnd.microsoft.card.adaptive"]
402 );
403 assert_eq!(graph.attachments[0].name.as_deref(), Some("plan.docx"));
404 let html = graph.body.unwrap().content.unwrap();
405 assert_eq!(
406 html,
407 r#"<p>see</p><attachment id="c1"></attachment><attachment id="f1"></attachment>"#
408 );
409 }
410
411 #[test]
412 fn a_forward_carries_the_original() {
413 let message = native(
414 "RichText/Html",
415 r#"<blockquote itemtype="http://schema.skype.com/Forward"><p>old</p></blockquote>"#,
416 json!({"originalMessageContext": {"messageId": 1793274845211i64, "originalSender": "8:orgid:bob", "originalSentTime": "2026-10-29T11:54:05.211Z", "originalThreadId": "19:other@thread.v2"}}),
417 );
418 let graph = graph_message(CHAT, &message).unwrap();
419 let forward = &graph.attachments[0];
420 assert_eq!(
421 forward.content_type.as_deref(),
422 Some(FORWARDED_CONTENT_TYPE)
423 );
424 let content: Value = serde_json::from_str(forward.content.as_deref().unwrap()).unwrap();
425 assert_eq!(content["originalMessageId"], "1793274845211");
426 assert_eq!(content["originalMessageContent"], "<p>old</p>");
427 assert_eq!(content["originalMessageSender"]["user"]["id"], "bob");
428 }
429
430 #[test]
431 fn a_deleted_message_is_deleted() {
432 let graph = graph_message(
433 CHAT,
434 &native("RichText/Html", "", json!({"deletetime": 1794474799021i64})),
435 )
436 .unwrap();
437 assert!(graph.is_deleted());
438 }
439
440 #[test]
441 fn a_bot_card_is_decoded() {
442 let swift = STANDARD.encode(r#"{"type":"message/card","attachments":[{"contentType":"application/vnd.microsoft.card.adaptive","content":{"type":"AdaptiveCard"}}]}"#);
443 let mut message = native(
444 "RichText/Media_Card",
445 &format!(r#"<URIObject type="SWIFT.1"><Swift b64="{swift}"/></URIObject>"#),
446 json!({}),
447 );
448 message["from"] = json!("https://x/contacts/28:bot-1");
449 let graph = graph_message(CHAT, &message).unwrap();
450 assert_eq!(graph.from.as_ref().unwrap().application_id(), Some("bot-1"));
451 assert_eq!(graph.attachments.len(), 1);
452 assert!(
453 graph.attachments[0]
454 .content
455 .as_deref()
456 .unwrap()
457 .contains("AdaptiveCard")
458 );
459 }
460
461 #[test]
462 fn controls_are_skipped_and_events_kept() {
463 assert!(graph_message(CHAT, &native("Control/Typing", "", json!({}))).is_none());
464 let call = native(
465 "Event/Call",
466 "<ended/><partlist count=\"0\"></partlist><callId>c</callId>",
467 json!({}),
468 );
469 let graph = graph_message(CHAT, &call).unwrap();
470 assert_eq!(graph.message_type.as_deref(), Some("systemEventMessage"));
471 assert!(
472 message_record(CHAT, &graph)
473 .unwrap()
474 .call_event_json
475 .is_some()
476 );
477 }
478 }
@@ -0,0 +1,478 @@
1use base64::Engine;
2use base64::engine::general_purpose::STANDARD;
3use chrono::{DateTime, Utc};
4use graph::Message;
5use serde_json::{Value, json};
6
7use super::markup::graph_body;
8use crate::forwarded::FORWARDED_CONTENT_TYPE;
9use chatsvc::graph_events::{event_detail, is_event, user_id};
10
11const BOT_PREFIX: &str = "28:";
12const FORWARD_CONTEXT: &str = "originalMessageContext";
13const ANNOTATION_KEYS: [&str; 3] = ["follow", "star", "acks"];
14const SWIFT_MARKER: &str = "<Swift b64=\"";
15
16/// A chat service message as Graph would serve it, so the record mapping stays the same for both sources.
17pub fn graph_message(conversation_id: &str, native: &Value) -> Option<Message> {
18 serde_json::from_value(graph_message_json(conversation_id, native)?).ok()
19}
20
21pub(crate) fn graph_message_json(conversation_id: &str, native: &Value) -> Option<Value> {
22 let message_type = text(native, &["messagetype", "messageType"])?;
23 let id = chatsvc::id_text(native.get("id")?)?;
24 let properties = &native["properties"];
25 let created = time(
26 native,
27 &[
28 "originalarrivaltime",
29 "originalArrivalTime",
30 "composetime",
31 "composeTime",
32 ],
33 )?;
34 let content = text(native, &["content"]).unwrap_or_default();
35 let sender = sender(native);
36 let sender_user_id = sender
37 .pointer("/user/id")
38 .and_then(Value::as_str)
39 .map(str::to_owned);
40 let mut message = json!({
41 "id": id,
42 "createdDateTime": created,
43 "lastModifiedDateTime": millis(&native["version"]).map(|time| time.to_rfc3339()).unwrap_or_else(|| created.clone()),
44 "lastEditedDateTime": millis(&properties["edittime"]).map(|time| time.to_rfc3339()),
45 "deletedDateTime": millis(&properties["deletetime"]).map(|time| time.to_rfc3339()),
46 "from": sender,
47 "importance": text(properties, &["importance"]),
48 "subject": text(properties, &["subject"]),
49 "reactions": reactions(native),
50 });
51 if is_event(message_type) {
52 message["messageType"] = json!("systemEventMessage");
53 message["eventDetail"] = event_detail(
54 message_type,
55 content,
56 conversation_id,
57 sender_user_id.as_deref(),
58 )?;
59 message["from"] = Value::Null;
60 message["body"] = json!({"contentType": "html", "content": ""});
61 return Some(message);
62 }
63 if !is_user_message(message_type) {
64 return None;
65 }
66 message["messageType"] = json!("message");
67 let forwards = forward_contexts(properties);
68 let forward_ids: Vec<String> = forwards.iter().map(|context| context.id.clone()).collect();
69 let body = graph_body(&content.replace("\r\n", "\n"), &forward_ids);
70 let mut attachments = file_attachments(properties);
71 attachments.extend(card_attachments(properties));
72 if message_type == "RichText/Media_Card" {
73 attachments.extend(swift_attachments(content));
74 }
75 attachments.extend(body.quotes.iter().map(|quote| {
76 json!({
77 "id": quote.message_id,
78 "contentType": "messageReference",
79 "content": json!({
80 "messageId": quote.message_id,
81 "messagePreview": quote.preview,
82 "messageSender": quote.sender_mri.as_deref().map(|mri| json!({"user": {"id": user_id(mri), "displayName": quote.sender_name}})),
83 }).to_string(),
84 })
85 }));
86 attachments.extend(
87 forwards
88 .iter()
89 .zip(&body.forwards)
90 .map(|(context, inner)| context.attachment(inner)),
91 );
92 let mut html = if message_type == "RichText/Media_Card" {
93 String::new()
94 } else {
95 body.html
96 };
97 for marker in &attachments {
98 let Some(attachment_id) = marker["id"].as_str() else {
99 continue;
100 };
101 let tag = format!("<attachment id=\"{attachment_id}\"></attachment>");
102 if !html.contains(&tag) {
103 html.push_str(&tag);
104 }
105 }
106 message["body"] = json!({
107 "contentType": if message_type == "Text" { "text" } else { "html" },
108 "content": html,
109 });
110 message["mentions"] = mentions(properties, &body.mention_texts);
111 message["attachments"] = Value::Array(attachments);
112 Some(message)
113}
114
115fn is_user_message(message_type: &str) -> bool {
116 message_type == "Text" || message_type.starts_with("RichText")
117}
118
119fn sender(native: &Value) -> Value {
120 let Some(mri) = text(native, &["from"]).and_then(|from| from.rsplit('/').next()) else {
121 return Value::Null;
122 };
123 let name = text(native, &["imdisplayname", "imDisplayName"])
124 .map(str::trim)
125 .filter(|name| !name.is_empty());
126 if let Some(bot_id) = mri.strip_prefix(BOT_PREFIX) {
127 return json!({"application": {"id": bot_id, "displayName": name}});
128 }
129 if mri.starts_with("8:") {
130 return json!({"user": {"id": user_id(mri), "displayName": name}});
131 }
132 Value::Null
133}
134
135fn reactions(native: &Value) -> Value {
136 let emotions = chatsvc::parse_message_emotions(&json!({"messages": [native]}));
137 Value::Array(
138 emotions
139 .into_iter()
140 .flat_map(|message| message.reactions)
141 .filter(|reaction| !ANNOTATION_KEYS.contains(&reaction.key.as_str()))
142 .map(|reaction| {
143 json!({
144 "reactionType": chatsvc::reaction_glyph_for_key(&reaction.key).unwrap_or(reaction.key),
145 "createdDateTime": reaction.time_ms.and_then(DateTime::<Utc>::from_timestamp_millis).map(|time| time.to_rfc3339()),
146 "user": {"user": {"id": reaction.user_id, "displayName": null}},
147 })
148 })
149 .collect(),
150 )
151}
152
153fn mentions(properties: &Value, texts: &std::collections::HashMap<String, String>) -> Value {
154 Value::Array(
155 json_list(&properties["mentions"])
156 .iter()
157 .filter_map(|mention| {
158 let item_id = chatsvc::id_text(mention.get("itemid")?)?;
159 let mri = mention["mri"].as_str().unwrap_or_default();
160 let name = mention["displayName"].as_str().map(str::to_owned);
161 let identity = json!({"id": user_id(mri), "displayName": name});
162 let mentioned = match mention["mentionType"].as_str().unwrap_or("person") {
163 _ if mri.starts_with("19:") => json!({"conversation": {"id": mri, "displayName": name, "conversationIdentityType": "chat"}}),
164 "tag" => json!({"tag": identity}),
165 "channel" | "team" => json!({"conversation": identity}),
166 _ if mri.starts_with(BOT_PREFIX) => json!({"application": {"id": &mri[BOT_PREFIX.len()..], "displayName": name}}),
167 _ => json!({"user": identity}),
168 };
169 Some(json!({
170 "id": item_id.parse::<i64>().ok()?,
171 "mentionText": texts.get(&item_id).cloned().or(name),
172 "mentioned": mentioned,
173 }))
174 })
175 .collect(),
176 )
177}
178
179fn file_attachments(properties: &Value) -> Vec<Value> {
180 json_list(&properties["files"])
181 .iter()
182 .filter_map(|file| {
183 let id = text(file, &["itemid", "id"])?;
184 let url = file
185 .pointer("/fileInfo/fileUrl")
186 .and_then(Value::as_str)
187 .or_else(|| text(file, &["objectUrl"]))?;
188 Some(json!({
189 "id": id,
190 "contentType": "reference",
191 "contentUrl": url,
192 "name": text(file, &["fileName", "title"]),
193 }))
194 })
195 .collect()
196}
197
198fn card_attachments(properties: &Value) -> Vec<Value> {
199 json_list(&properties["cards"])
200 .iter()
201 .filter_map(|card| {
202 let content = match &card["content"] {
203 Value::String(text) => text.clone(),
204 Value::Null => return None,
205 other => other.to_string(),
206 };
207 Some(json!({
208 "id": text(card, &["cardClientId"]),
209 "contentType": text(card, &["contentType"]).unwrap_or("application/vnd.microsoft.card.adaptive"),
210 "content": content,
211 "teamsAppId": text(card, &["appId"]),
212 }))
213 })
214 .collect()
215}
216
217fn swift_attachments(content: &str) -> Vec<Value> {
218 let Some(start) = content
219 .find(SWIFT_MARKER)
220 .map(|start| start + SWIFT_MARKER.len())
221 else {
222 return Vec::new();
223 };
224 let Some(encoded) = content[start..].split('"').next() else {
225 return Vec::new();
226 };
227 let Some(swift) = STANDARD
228 .decode(encoded)
229 .ok()
230 .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
231 else {
232 return Vec::new();
233 };
234 swift["attachments"]
235 .as_array()
236 .into_iter()
237 .flatten()
238 .enumerate()
239 .filter_map(|(index, attachment)| {
240 let content = match &attachment["content"] {
241 Value::String(text) => text.clone(),
242 Value::Null => return None,
243 other => other.to_string(),
244 };
245 Some(json!({
246 "id": format!("swift-{index}"),
247 "contentType": text(attachment, &["contentType"]),
248 "content": content,
249 }))
250 })
251 .collect()
252}
253
254struct ForwardContext {
255 id: String,
256 conversation_id: Option<String>,
257 sender_id: Option<String>,
258 sent_at: Option<String>,
259}
260
261impl ForwardContext {
262 fn attachment(&self, inner_html: &str) -> Value {
263 json!({
264 "id": self.id,
265 "contentType": FORWARDED_CONTENT_TYPE,
266 "content": json!({
267 "originalMessageId": self.id,
268 "originalMessageContent": inner_html,
269 "originalConversationId": self.conversation_id,
270 "originalSentDateTime": self.sent_at,
271 "originalMessageSender": self.sender_id.as_ref().map(|id| json!({"user": {"id": id, "displayName": null}})),
272 }).to_string(),
273 })
274 }
275}
276
277fn forward_contexts(properties: &Value) -> Vec<ForwardContext> {
278 (0..)
279 .map(|index| match index {
280 0 => FORWARD_CONTEXT.to_owned(),
281 index => format!("{FORWARD_CONTEXT}{index}"),
282 })
283 .map_while(|key| {
284 properties
285 .get(&key)
286 .filter(|context| context.is_object())
287 .cloned()
288 })
289 .filter_map(|context| {
290 Some(ForwardContext {
291 id: chatsvc::id_text(context.get("messageId")?)?,
292 conversation_id: text(&context, &["originalThreadId"]).map(str::to_owned),
293 sender_id: text(&context, &["originalSender"]).map(|mri| user_id(mri).to_owned()),
294 sent_at: text(&context, &["originalSentTime"]).map(str::to_owned),
295 })
296 })
297 .collect()
298}
299
300/// Chat service properties carry lists either as JSON text or as arrays.
301fn json_list(value: &Value) -> Vec<Value> {
302 match value {
303 Value::Array(items) => items.clone(),
304 Value::String(text) => serde_json::from_str::<Value>(text)
305 .ok()
306 .and_then(|parsed| parsed.as_array().cloned())
307 .unwrap_or_default(),
308 _ => Vec::new(),
309 }
310}
311
312fn text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
313 keys.iter()
314 .find_map(|key| value.get(*key)?.as_str())
315 .filter(|text| !text.is_empty())
316}
317
318fn time(value: &Value, keys: &[&str]) -> Option<String> {
319 let text = text(value, keys)?;
320 DateTime::parse_from_rfc3339(text)
321 .ok()
322 .map(|time| time.with_timezone(&Utc).to_rfc3339())
323}
324
325fn millis(value: &Value) -> Option<DateTime<Utc>> {
326 let millis = value.as_i64().or_else(|| value.as_str()?.parse().ok())?;
327 (millis > 0)
328 .then(|| DateTime::<Utc>::from_timestamp_millis(millis))
329 .flatten()
330}
331
332#[cfg(test)]
333mod tests {
334 use serde_json::json;
335
336 use super::*;
337 use crate::mapping::message_record;
338
339 const CHAT: &str = "19:chat@thread.v2";
340
341 fn native(message_type: &str, content: &str, properties: Value) -> Value {
342 json!({
343 "id": "1794474789021",
344 "messagetype": message_type,
345 "content": content,
346 "from": "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/contacts/8:orgid:ann",
347 "imdisplayname": "Ann Example",
348 "originalarrivaltime": "2026-11-12T09:13:09.0210000Z",
349 "composetime": "2026-11-12T09:13:09.0210000Z",
350 "version": "1794474789021",
351 "properties": properties,
352 })
353 }
354
355 #[test]
356 fn a_rich_text_message_maps_like_graph() {
357 let message = native(
358 "RichText/Html",
359 r#"<p>hi <span itemtype="http://schema.skype.com/Mention" itemscope="" itemid="0">Bo</span></p>"#,
360 json!({
361 "mentions": r#"[{"@type":"http://schema.skype.com/Mention","itemid":0,"mri":"8:orgid:bob","mentionType":"person","displayName":"Bo Sample"}]"#,
362 "emotions": [{"key": "like", "users": [{"mri": "8:orgid:bob", "time": 1794474799021i64, "value": "1"}]}],
363 "edittime": 1794474799021i64,
364 "importance": "high",
365 }),
366 );
367 let graph = graph_message(CHAT, &message).unwrap();
368 assert_eq!(graph.from.as_ref().unwrap().user_id(), Some("ann"));
369 assert_eq!(
370 graph.from.as_ref().unwrap().display_name(),
371 Some("Ann Example")
372 );
373 assert_eq!(graph.mentions[0].mention_text.as_deref(), Some("Bo"));
374 assert_eq!(graph.reactions[0].reaction_type, "👍");
375 let record = message_record(CHAT, &graph).unwrap();
376 assert_eq!(record.message_id, "1794474789021");
377 assert_eq!(record.body_html, r#"<p>hi <at id="0">Bo</at></p>"#);
378 assert!(record.edited_at.is_some());
379 assert!(record.mentions_json.contains("\"user_id\":\"bob\""));
380 assert_eq!(record.importance, store::MessageImportance::High);
381 }
382
383 #[test]
384 fn files_and_cards_become_attachments() {
385 let message = native(
386 "RichText/Html",
387 r#"<p>see</p><span itemid="c1" itemscope="" itemtype="http://schema.skype.com/InputExtension"><span itemprop="cardId"></span></span>"#,
388 json!({
389 "files": r#"[{"itemid":"f1","fileName":"plan.docx","fileInfo":{"fileUrl":"https://contoso.sharepoint.com/plan.docx"}}]"#,
390 "cards": [{"cardClientId": "c1", "appId": "app", "contentType": "application/vnd.microsoft.card.adaptive", "content": {"type": "AdaptiveCard", "body": []}}],
391 }),
392 );
393 let graph = graph_message(CHAT, &message).unwrap();
394 let kinds: Vec<_> = graph
395 .attachments
396 .iter()
397 .map(|attachment| attachment.content_type.clone().unwrap())
398 .collect();
399 assert_eq!(
400 kinds,
401 vec!["reference", "application/vnd.microsoft.card.adaptive"]
402 );
403 assert_eq!(graph.attachments[0].name.as_deref(), Some("plan.docx"));
404 let html = graph.body.unwrap().content.unwrap();
405 assert_eq!(
406 html,
407 r#"<p>see</p><attachment id="c1"></attachment><attachment id="f1"></attachment>"#
408 );
409 }
410
411 #[test]
412 fn a_forward_carries_the_original() {
413 let message = native(
414 "RichText/Html",
415 r#"<blockquote itemtype="http://schema.skype.com/Forward"><p>old</p></blockquote>"#,
416 json!({"originalMessageContext": {"messageId": 1793274845211i64, "originalSender": "8:orgid:bob", "originalSentTime": "2026-10-29T11:54:05.211Z", "originalThreadId": "19:other@thread.v2"}}),
417 );
418 let graph = graph_message(CHAT, &message).unwrap();
419 let forward = &graph.attachments[0];
420 assert_eq!(
421 forward.content_type.as_deref(),
422 Some(FORWARDED_CONTENT_TYPE)
423 );
424 let content: Value = serde_json::from_str(forward.content.as_deref().unwrap()).unwrap();
425 assert_eq!(content["originalMessageId"], "1793274845211");
426 assert_eq!(content["originalMessageContent"], "<p>old</p>");
427 assert_eq!(content["originalMessageSender"]["user"]["id"], "bob");
428 }
429
430 #[test]
431 fn a_deleted_message_is_deleted() {
432 let graph = graph_message(
433 CHAT,
434 &native("RichText/Html", "", json!({"deletetime": 1794474799021i64})),
435 )
436 .unwrap();
437 assert!(graph.is_deleted());
438 }
439
440 #[test]
441 fn a_bot_card_is_decoded() {
442 let swift = STANDARD.encode(r#"{"type":"message/card","attachments":[{"contentType":"application/vnd.microsoft.card.adaptive","content":{"type":"AdaptiveCard"}}]}"#);
443 let mut message = native(
444 "RichText/Media_Card",
445 &format!(r#"<URIObject type="SWIFT.1"><Swift b64="{swift}"/></URIObject>"#),
446 json!({}),
447 );
448 message["from"] = json!("https://x/contacts/28:bot-1");
449 let graph = graph_message(CHAT, &message).unwrap();
450 assert_eq!(graph.from.as_ref().unwrap().application_id(), Some("bot-1"));
451 assert_eq!(graph.attachments.len(), 1);
452 assert!(
453 graph.attachments[0]
454 .content
455 .as_deref()
456 .unwrap()
457 .contains("AdaptiveCard")
458 );
459 }
460
461 #[test]
462 fn controls_are_skipped_and_events_kept() {
463 assert!(graph_message(CHAT, &native("Control/Typing", "", json!({}))).is_none());
464 let call = native(
465 "Event/Call",
466 "<ended/><partlist count=\"0\"></partlist><callId>c</callId>",
467 json!({}),
468 );
469 let graph = graph_message(CHAT, &call).unwrap();
470 assert_eq!(graph.message_type.as_deref(), Some("systemEventMessage"));
471 assert!(
472 message_record(CHAT, &graph)
473 .unwrap()
474 .call_event_json
475 .is_some()
476 );
477 }
478}
crates/core/src/native/mod.rs added +99 −0
@@ -0,0 +1,99 @@
1 mod chat;
2 mod markup;
3 mod message;
4 mod source;
5
6 pub use chat::{NativeMember, chat_type, graph_chat, graph_chat_from_aggregator};
7 pub use message::graph_message;
8 pub use source::{NativeChats, known_profile};
9
10 #[cfg(test)]
11 mod event_tests {
12 use chatsvc::graph_events::event_detail;
13
14 use crate::call_event::{CallEvent, CallPhase, CallType};
15 use crate::roster_event::{RosterChange, RosterEvent, SharedHistory};
16
17 #[test]
18 fn an_ended_call_lists_participants_and_the_longest_duration() {
19 let content = r#"<ended/><partlist alt="" count="2"><part identity="28:ann"><name>8:orgid:ann</name><displayName>Ann</displayName><duration>61</duration></part><part identity="8:orgid:bob"><name>8:orgid:bob</name><displayName></displayName><duration>125</duration></part></partlist><callEventType>meeting</callEventType><callId>call-1</callId>"#;
20 let detail =
21 event_detail("Event/Call", content, "19:meeting_x@thread.v2", Some("ann")).unwrap();
22 let event = CallEvent::from_graph(&detail).unwrap();
23 assert_eq!(event.phase, CallPhase::Ended);
24 assert_eq!(event.call_type, CallType::Meeting);
25 assert_eq!(event.call_id, "call-1");
26 assert_eq!(event.duration_seconds, Some(125));
27 assert_eq!(event.participant_ids, vec!["ann", "bob"]);
28 assert_eq!(event.initiator_id.as_deref(), Some("ann"));
29 }
30
31 #[test]
32 fn a_call_without_end_is_a_started_call() {
33 let content = "<partlist alt=\"\"></partlist><meetingDetails><meetingType>Scheduled</meetingType></meetingDetails><callId>call-3</callId>";
34 let detail = event_detail("Event/Call", content, "19:a@thread.v2", Some("ann")).unwrap();
35 let event = CallEvent::from_graph(&detail).unwrap();
36 assert_eq!(event.phase, CallPhase::Started);
37 assert_eq!(event.call_type, CallType::Meeting);
38 }
39
40 #[test]
41 fn a_saved_recording_names_its_file_and_link() {
42 let content = r#"<URIObject type="Video.2/CallRecording.1"><RecordingStatus status="Success" code="200"></RecordingStatus><Title>Daily</Title><a href="https://contoso.sharepoint.com/:v:/rec">Play</a><OriginalName v="Daily-20261104_103230-Meeting Recording.mp4" /><MeetingOrganizerId value="8:orgid:boss" /><Identifiers><Id type="callId" value="call-2" /></Identifiers><RecordingContent duration="0:08:51.02"></RecordingContent></URIObject>"#;
43 let detail = event_detail(
44 "RichText/Media_CallRecording",
45 content,
46 "19:a@thread.v2",
47 None,
48 )
49 .unwrap();
50 let event = CallEvent::from_graph(&detail).unwrap();
51 assert_eq!(event.phase, CallPhase::RecordingSaved);
52 assert_eq!(event.call_id, "call-2");
53 assert_eq!(event.duration_seconds, Some(531));
54 let recording = event.recording.unwrap();
55 assert_eq!(recording.title().as_deref(), Some("Daily"));
56 assert_eq!(
57 recording.url.as_deref(),
58 Some("https://contoso.sharepoint.com/:v:/rec")
59 );
60 assert_eq!(recording.organizer_id.as_deref(), Some("boss"));
61 }
62
63 #[test]
64 fn added_members_carry_the_shared_history() {
65 let content = "<addmember><eventtime>1</eventtime><initiator>8:orgid:boss</initiator><target>8:orgid:ann</target><detailedtargetinfo><id>8:orgid:ann</id></detailedtargetinfo><sharehistorytime>0</sharehistorytime></addmember>";
66 let detail =
67 event_detail("ThreadActivity/AddMember", content, "19:a@thread.v2", None).unwrap();
68 let event = RosterEvent::from_graph(&detail, None).unwrap();
69 assert_eq!(event.change, RosterChange::Added);
70 assert_eq!(event.member_ids, vec!["ann"]);
71 assert_eq!(event.initiator_id.as_deref(), Some("boss"));
72 assert_eq!(event.history, SharedHistory::All);
73 }
74
75 #[test]
76 fn leaving_and_renaming_read_like_graph() {
77 let left = r#"{"eventtime":1,"initiator":"8:orgid:ann","members":[{"friendlyname":"Ann","id":"8:orgid:ann"}]}"#;
78 let detail =
79 event_detail("ThreadActivity/MemberLeft", left, "19:a@thread.v2", None).unwrap();
80 assert_eq!(
81 RosterEvent::from_graph(&detail, None).unwrap().change,
82 RosterChange::Left
83 );
84 let topic = "<topicupdate><eventtime>1</eventtime><initiator>8:orgid:ann</initiator><value>Plan &amp; do</value></topicupdate>";
85 let detail =
86 event_detail("ThreadActivity/TopicUpdate", topic, "19:a@thread.v2", None).unwrap();
87 let renamed = RosterEvent::from_graph(&detail, None).unwrap();
88 assert_eq!(renamed.topic.as_deref(), Some("Plan & do"));
89 assert!(
90 event_detail(
91 "ThreadActivity/TopicUpdate",
92 topic,
93 "19:meeting_x@thread.v2",
94 None
95 )
96 .is_none()
97 );
98 }
99 }
@@ -0,0 +1,99 @@
1mod chat;
2mod markup;
3mod message;
4mod source;
5
6pub use chat::{NativeMember, chat_type, graph_chat, graph_chat_from_aggregator};
7pub use message::graph_message;
8pub use source::{NativeChats, known_profile};
9
10#[cfg(test)]
11mod event_tests {
12 use chatsvc::graph_events::event_detail;
13
14 use crate::call_event::{CallEvent, CallPhase, CallType};
15 use crate::roster_event::{RosterChange, RosterEvent, SharedHistory};
16
17 #[test]
18 fn an_ended_call_lists_participants_and_the_longest_duration() {
19 let content = r#"<ended/><partlist alt="" count="2"><part identity="28:ann"><name>8:orgid:ann</name><displayName>Ann</displayName><duration>61</duration></part><part identity="8:orgid:bob"><name>8:orgid:bob</name><displayName></displayName><duration>125</duration></part></partlist><callEventType>meeting</callEventType><callId>call-1</callId>"#;
20 let detail =
21 event_detail("Event/Call", content, "19:meeting_x@thread.v2", Some("ann")).unwrap();
22 let event = CallEvent::from_graph(&detail).unwrap();
23 assert_eq!(event.phase, CallPhase::Ended);
24 assert_eq!(event.call_type, CallType::Meeting);
25 assert_eq!(event.call_id, "call-1");
26 assert_eq!(event.duration_seconds, Some(125));
27 assert_eq!(event.participant_ids, vec!["ann", "bob"]);
28 assert_eq!(event.initiator_id.as_deref(), Some("ann"));
29 }
30
31 #[test]
32 fn a_call_without_end_is_a_started_call() {
33 let content = "<partlist alt=\"\"></partlist><meetingDetails><meetingType>Scheduled</meetingType></meetingDetails><callId>call-3</callId>";
34 let detail = event_detail("Event/Call", content, "19:a@thread.v2", Some("ann")).unwrap();
35 let event = CallEvent::from_graph(&detail).unwrap();
36 assert_eq!(event.phase, CallPhase::Started);
37 assert_eq!(event.call_type, CallType::Meeting);
38 }
39
40 #[test]
41 fn a_saved_recording_names_its_file_and_link() {
42 let content = r#"<URIObject type="Video.2/CallRecording.1"><RecordingStatus status="Success" code="200"></RecordingStatus><Title>Daily</Title><a href="https://contoso.sharepoint.com/:v:/rec">Play</a><OriginalName v="Daily-20261104_103230-Meeting Recording.mp4" /><MeetingOrganizerId value="8:orgid:boss" /><Identifiers><Id type="callId" value="call-2" /></Identifiers><RecordingContent duration="0:08:51.02"></RecordingContent></URIObject>"#;
43 let detail = event_detail(
44 "RichText/Media_CallRecording",
45 content,
46 "19:a@thread.v2",
47 None,
48 )
49 .unwrap();
50 let event = CallEvent::from_graph(&detail).unwrap();
51 assert_eq!(event.phase, CallPhase::RecordingSaved);
52 assert_eq!(event.call_id, "call-2");
53 assert_eq!(event.duration_seconds, Some(531));
54 let recording = event.recording.unwrap();
55 assert_eq!(recording.title().as_deref(), Some("Daily"));
56 assert_eq!(
57 recording.url.as_deref(),
58 Some("https://contoso.sharepoint.com/:v:/rec")
59 );
60 assert_eq!(recording.organizer_id.as_deref(), Some("boss"));
61 }
62
63 #[test]
64 fn added_members_carry_the_shared_history() {
65 let content = "<addmember><eventtime>1</eventtime><initiator>8:orgid:boss</initiator><target>8:orgid:ann</target><detailedtargetinfo><id>8:orgid:ann</id></detailedtargetinfo><sharehistorytime>0</sharehistorytime></addmember>";
66 let detail =
67 event_detail("ThreadActivity/AddMember", content, "19:a@thread.v2", None).unwrap();
68 let event = RosterEvent::from_graph(&detail, None).unwrap();
69 assert_eq!(event.change, RosterChange::Added);
70 assert_eq!(event.member_ids, vec!["ann"]);
71 assert_eq!(event.initiator_id.as_deref(), Some("boss"));
72 assert_eq!(event.history, SharedHistory::All);
73 }
74
75 #[test]
76 fn leaving_and_renaming_read_like_graph() {
77 let left = r#"{"eventtime":1,"initiator":"8:orgid:ann","members":[{"friendlyname":"Ann","id":"8:orgid:ann"}]}"#;
78 let detail =
79 event_detail("ThreadActivity/MemberLeft", left, "19:a@thread.v2", None).unwrap();
80 assert_eq!(
81 RosterEvent::from_graph(&detail, None).unwrap().change,
82 RosterChange::Left
83 );
84 let topic = "<topicupdate><eventtime>1</eventtime><initiator>8:orgid:ann</initiator><value>Plan &amp; do</value></topicupdate>";
85 let detail =
86 event_detail("ThreadActivity/TopicUpdate", topic, "19:a@thread.v2", None).unwrap();
87 let renamed = RosterEvent::from_graph(&detail, None).unwrap();
88 assert_eq!(renamed.topic.as_deref(), Some("Plan & do"));
89 assert!(
90 event_detail(
91 "ThreadActivity/TopicUpdate",
92 topic,
93 "19:meeting_x@thread.v2",
94 None
95 )
96 .is_none()
97 );
98 }
99}
crates/core/src/native/source.rs added +284 −0
@@ -0,0 +1,284 @@
1 use std::collections::HashMap;
2 use std::sync::{LazyLock, Mutex};
3
4 use chatsvc::{ChatListing, UserProfile, UserProfiles};
5 use chrono::{DateTime, Utc};
6 use futures_util::{StreamExt, stream};
7 use graph::{Chat, Member, Message};
8 use serde_json::Value;
9 use session::Session;
10
11 use super::chat::{
12 NativeMember, aggregator_members, chat_type, graph_chat, graph_chat_from_aggregator,
13 graph_member, one_on_one_ids, thread_members,
14 };
15 use super::message::graph_message;
16 use crate::error::{Error, Result};
17 use crate::remote::{ChatsPage, RemotePage};
18
19 const THREADS_IN_FLIGHT: usize = 6;
20 const OLDER_PAGE_MARKER: &str = "chatsvc:older";
21
22 /// Profiles looked up so far; `None` when the directory does not know the id, such as a bot.
23 static PROFILES: LazyLock<Mutex<HashMap<String, Option<UserProfile>>>> =
24 LazyLock::new(|| Mutex::new(HashMap::new()));
25 /// Thread members by chat, kept while the thread's roster version stays the same.
26 static ROSTERS: LazyLock<Mutex<HashMap<String, (String, Vec<NativeMember>)>>> =
27 LazyLock::new(|| Mutex::new(HashMap::new()));
28
29 /// Chats, members and messages read from the Teams chat service instead of Graph.
30 pub struct NativeChats<'a> {
31 session: &'a Session,
32 }
33
34 impl<'a> NativeChats<'a> {
35 pub fn new(session: &'a Session) -> Self {
36 NativeChats { session }
37 }
38
39 pub async fn first_page(&self, page_size: usize) -> Result<ChatsPage> {
40 let url = ChatListing::new(self.session).first_page_url(page_size);
41 self.page(&url).await
42 }
43
44 pub async fn page(&self, url: &str) -> Result<ChatsPage> {
45 let listing = ChatListing::new(self.session);
46 let page = listing.page(url).await?;
47 let conversations: Vec<&Value> = page
48 .conversations
49 .iter()
50 .filter(|conversation| chat_type(conversation).is_some())
51 .collect();
52 let keys: Vec<(String, String)> = conversations
53 .iter()
54 .map(|conversation| {
55 (
56 conversation["id"].as_str().unwrap_or_default().to_owned(),
57 conversation["threadProperties"]["rosterVersion"].to_string(),
58 )
59 })
60 .collect();
61 let rosters: Vec<Vec<NativeMember>> = stream::iter(keys)
62 .map(|(chat_id, version)| self.roster(&listing, chat_id, version))
63 .buffered(THREADS_IN_FLIGHT)
64 .collect()
65 .await;
66 let user_ids: Vec<String> = rosters
67 .iter()
68 .flatten()
69 .map(|member| member.user_id.clone())
70 .collect();
71 self.learn_profiles(&user_ids).await;
72 let items = conversations
73 .into_iter()
74 .zip(rosters)
75 .filter_map(|(conversation, roster)| graph_chat(conversation, self.named(roster, true)))
76 .collect();
77 Ok(ChatsPage {
78 items,
79 next_link: page.next_url,
80 })
81 }
82
83 pub async fn chat(&self, chat_id: &str) -> Result<Chat> {
84 let chat = chatsvc::aggregator_chat(self.session, chat_id).await?;
85 let mut members = aggregator_members(&chat);
86 let user_ids: Vec<String> = members
87 .iter()
88 .map(|member| member.user_id.clone())
89 .collect();
90 self.learn_profiles(&user_ids).await;
91 for member in &mut members {
92 if member.name.is_none() {
93 member.name = profile_name(&member.user_id);
94 }
95 }
96 let members = members
97 .iter()
98 .map(|member| graph_member(member, profile_email(&member.user_id).as_deref()))
99 .collect();
100 graph_chat_from_aggregator(&chat, members)
101 .ok_or_else(|| Error::Unsupported("a chat the chat service aggregator cannot describe"))
102 }
103
104 /// A chat just created here, before the chat service lists it.
105 pub async fn created_chat(
106 &self,
107 chat_id: &str,
108 kind: &str,
109 topic: Option<&str>,
110 user_ids: &[String],
111 ) -> Result<Chat> {
112 self.learn_profiles(user_ids).await;
113 let members: Vec<NativeMember> = user_ids
114 .iter()
115 .map(|user_id| NativeMember {
116 user_id: user_id.clone(),
117 owner: kind != "oneOnOne",
118 name: None,
119 })
120 .collect();
121 serde_json::from_value(serde_json::json!({
122 "id": chat_id,
123 "topic": topic,
124 "chatType": kind,
125 "createdDateTime": Utc::now().to_rfc3339(),
126 "members": self.named(members, false),
127 }))
128 .map_err(|_| Error::Unsupported("a new chat without a Graph shape"))
129 }
130
131 pub async fn members(&self, chat_id: &str) -> Result<Vec<Member>> {
132 let listing = ChatListing::new(self.session);
133 let thread = listing.thread(chat_id).await?;
134 let members = thread_members(&thread);
135 let user_ids: Vec<String> = members
136 .iter()
137 .map(|member| member.user_id.clone())
138 .collect();
139 self.learn_profiles(&user_ids).await;
140 let named = self.named(members, false);
141 Ok(named
142 .into_iter()
143 .filter_map(|member| serde_json::from_value(member).ok())
144 .collect())
145 }
146
147 pub async fn messages(
148 &self,
149 chat_id: &str,
150 before: Option<DateTime<Utc>>,
151 page_size: usize,
152 ) -> Result<RemotePage> {
153 let page = ChatListing::new(self.session)
154 .messages(
155 chat_id,
156 before.map(|time| time.timestamp_millis()),
157 page_size,
158 )
159 .await?;
160 Ok(RemotePage {
161 items: page
162 .messages
163 .iter()
164 .filter_map(|message| graph_message(chat_id, message))
165 .collect(),
166 next_link: page.has_older.then(|| OLDER_PAGE_MARKER.to_owned()),
167 })
168 }
169
170 pub async fn message(&self, chat_id: &str, message_id: &str) -> Result<Message> {
171 let native = ChatListing::new(self.session)
172 .message(chat_id, message_id)
173 .await?;
174 graph_message(chat_id, &native).ok_or(Error::Unsupported(
175 "a chat service message without a Graph shape",
176 ))
177 }
178
179 async fn roster(
180 &self,
181 listing: &ChatListing,
182 chat_id: String,
183 version: String,
184 ) -> Vec<NativeMember> {
185 let chat_id = chat_id.as_str();
186 if chat_id.is_empty() {
187 return Vec::new();
188 }
189 if let Some(pair) = one_on_one_ids(chat_id) {
190 return pair
191 .into_iter()
192 .map(|user_id| NativeMember {
193 user_id,
194 owner: false,
195 name: None,
196 })
197 .collect();
198 }
199 if let Some((known, members)) = ROSTERS.lock().unwrap().get(chat_id)
200 && *known == version
201 {
202 return members.clone();
203 }
204 match listing.thread(chat_id).await {
205 Ok(thread) => {
206 let members = thread_members(&thread);
207 ROSTERS
208 .lock()
209 .unwrap()
210 .insert(chat_id.to_owned(), (version, members.clone()));
211 members
212 }
213 Err(_) => ROSTERS
214 .lock()
215 .unwrap()
216 .get(chat_id)
217 .map(|(_, members)| members.clone())
218 .unwrap_or_default(),
219 }
220 }
221
222 async fn learn_profiles(&self, user_ids: &[String]) {
223 let unknown: Vec<String> = {
224 let known = PROFILES.lock().unwrap();
225 let mut unknown: Vec<String> = user_ids
226 .iter()
227 .filter(|user_id| !known.contains_key(*user_id))
228 .cloned()
229 .collect();
230 unknown.sort();
231 unknown.dedup();
232 unknown
233 };
234 if unknown.is_empty() {
235 return;
236 }
237 let Ok(profiles) = UserProfiles::new(self.session).fetch(&unknown).await else {
238 return;
239 };
240 let mut known = PROFILES.lock().unwrap();
241 for user_id in unknown {
242 known.insert(user_id, None);
243 }
244 for profile in profiles {
245 known.insert(profile.user_id.clone(), Some(profile));
246 }
247 }
248
249 /// `drop_unknown` leaves out ids the directory does not know, which in a 1:1 is a bot.
250 fn named(&self, members: Vec<NativeMember>, drop_unknown: bool) -> Vec<Value> {
251 let known = PROFILES.lock().unwrap();
252 members
253 .into_iter()
254 .filter(|member| !drop_unknown || !matches!(known.get(&member.user_id), Some(None)))
255 .map(|mut member| {
256 let profile = known.get(&member.user_id).cloned().flatten();
257 if member.name.is_none() {
258 member.name = profile
259 .as_ref()
260 .and_then(|profile| profile.display_name.clone());
261 }
262 graph_member(
263 &member,
264 profile
265 .as_ref()
266 .and_then(|profile| profile.email.as_deref()),
267 )
268 })
269 .collect()
270 }
271 }
272
273 /// What the directory lookups learned about a user, for callers outside the chat path.
274 pub fn known_profile(user_id: &str) -> Option<UserProfile> {
275 PROFILES.lock().unwrap().get(user_id).cloned().flatten()
276 }
277
278 fn profile_name(user_id: &str) -> Option<String> {
279 known_profile(user_id).and_then(|profile| profile.display_name)
280 }
281
282 fn profile_email(user_id: &str) -> Option<String> {
283 known_profile(user_id).and_then(|profile| profile.email)
284 }
@@ -0,0 +1,284 @@
1use std::collections::HashMap;
2use std::sync::{LazyLock, Mutex};
3
4use chatsvc::{ChatListing, UserProfile, UserProfiles};
5use chrono::{DateTime, Utc};
6use futures_util::{StreamExt, stream};
7use graph::{Chat, Member, Message};
8use serde_json::Value;
9use session::Session;
10
11use super::chat::{
12 NativeMember, aggregator_members, chat_type, graph_chat, graph_chat_from_aggregator,
13 graph_member, one_on_one_ids, thread_members,
14};
15use super::message::graph_message;
16use crate::error::{Error, Result};
17use crate::remote::{ChatsPage, RemotePage};
18
19const THREADS_IN_FLIGHT: usize = 6;
20const OLDER_PAGE_MARKER: &str = "chatsvc:older";
21
22/// Profiles looked up so far; `None` when the directory does not know the id, such as a bot.
23static PROFILES: LazyLock<Mutex<HashMap<String, Option<UserProfile>>>> =
24 LazyLock::new(|| Mutex::new(HashMap::new()));
25/// Thread members by chat, kept while the thread's roster version stays the same.
26static ROSTERS: LazyLock<Mutex<HashMap<String, (String, Vec<NativeMember>)>>> =
27 LazyLock::new(|| Mutex::new(HashMap::new()));
28
29/// Chats, members and messages read from the Teams chat service instead of Graph.
30pub struct NativeChats<'a> {
31 session: &'a Session,
32}
33
34impl<'a> NativeChats<'a> {
35 pub fn new(session: &'a Session) -> Self {
36 NativeChats { session }
37 }
38
39 pub async fn first_page(&self, page_size: usize) -> Result<ChatsPage> {
40 let url = ChatListing::new(self.session).first_page_url(page_size);
41 self.page(&url).await
42 }
43
44 pub async fn page(&self, url: &str) -> Result<ChatsPage> {
45 let listing = ChatListing::new(self.session);
46 let page = listing.page(url).await?;
47 let conversations: Vec<&Value> = page
48 .conversations
49 .iter()
50 .filter(|conversation| chat_type(conversation).is_some())
51 .collect();
52 let keys: Vec<(String, String)> = conversations
53 .iter()
54 .map(|conversation| {
55 (
56 conversation["id"].as_str().unwrap_or_default().to_owned(),
57 conversation["threadProperties"]["rosterVersion"].to_string(),
58 )
59 })
60 .collect();
61 let rosters: Vec<Vec<NativeMember>> = stream::iter(keys)
62 .map(|(chat_id, version)| self.roster(&listing, chat_id, version))
63 .buffered(THREADS_IN_FLIGHT)
64 .collect()
65 .await;
66 let user_ids: Vec<String> = rosters
67 .iter()
68 .flatten()
69 .map(|member| member.user_id.clone())
70 .collect();
71 self.learn_profiles(&user_ids).await;
72 let items = conversations
73 .into_iter()
74 .zip(rosters)
75 .filter_map(|(conversation, roster)| graph_chat(conversation, self.named(roster, true)))
76 .collect();
77 Ok(ChatsPage {
78 items,
79 next_link: page.next_url,
80 })
81 }
82
83 pub async fn chat(&self, chat_id: &str) -> Result<Chat> {
84 let chat = chatsvc::aggregator_chat(self.session, chat_id).await?;
85 let mut members = aggregator_members(&chat);
86 let user_ids: Vec<String> = members
87 .iter()
88 .map(|member| member.user_id.clone())
89 .collect();
90 self.learn_profiles(&user_ids).await;
91 for member in &mut members {
92 if member.name.is_none() {
93 member.name = profile_name(&member.user_id);
94 }
95 }
96 let members = members
97 .iter()
98 .map(|member| graph_member(member, profile_email(&member.user_id).as_deref()))
99 .collect();
100 graph_chat_from_aggregator(&chat, members)
101 .ok_or_else(|| Error::Unsupported("a chat the chat service aggregator cannot describe"))
102 }
103
104 /// A chat just created here, before the chat service lists it.
105 pub async fn created_chat(
106 &self,
107 chat_id: &str,
108 kind: &str,
109 topic: Option<&str>,
110 user_ids: &[String],
111 ) -> Result<Chat> {
112 self.learn_profiles(user_ids).await;
113 let members: Vec<NativeMember> = user_ids
114 .iter()
115 .map(|user_id| NativeMember {
116 user_id: user_id.clone(),
117 owner: kind != "oneOnOne",
118 name: None,
119 })
120 .collect();
121 serde_json::from_value(serde_json::json!({
122 "id": chat_id,
123 "topic": topic,
124 "chatType": kind,
125 "createdDateTime": Utc::now().to_rfc3339(),
126 "members": self.named(members, false),
127 }))
128 .map_err(|_| Error::Unsupported("a new chat without a Graph shape"))
129 }
130
131 pub async fn members(&self, chat_id: &str) -> Result<Vec<Member>> {
132 let listing = ChatListing::new(self.session);
133 let thread = listing.thread(chat_id).await?;
134 let members = thread_members(&thread);
135 let user_ids: Vec<String> = members
136 .iter()
137 .map(|member| member.user_id.clone())
138 .collect();
139 self.learn_profiles(&user_ids).await;
140 let named = self.named(members, false);
141 Ok(named
142 .into_iter()
143 .filter_map(|member| serde_json::from_value(member).ok())
144 .collect())
145 }
146
147 pub async fn messages(
148 &self,
149 chat_id: &str,
150 before: Option<DateTime<Utc>>,
151 page_size: usize,
152 ) -> Result<RemotePage> {
153 let page = ChatListing::new(self.session)
154 .messages(
155 chat_id,
156 before.map(|time| time.timestamp_millis()),
157 page_size,
158 )
159 .await?;
160 Ok(RemotePage {
161 items: page
162 .messages
163 .iter()
164 .filter_map(|message| graph_message(chat_id, message))
165 .collect(),
166 next_link: page.has_older.then(|| OLDER_PAGE_MARKER.to_owned()),
167 })
168 }
169
170 pub async fn message(&self, chat_id: &str, message_id: &str) -> Result<Message> {
171 let native = ChatListing::new(self.session)
172 .message(chat_id, message_id)
173 .await?;
174 graph_message(chat_id, &native).ok_or(Error::Unsupported(
175 "a chat service message without a Graph shape",
176 ))
177 }
178
179 async fn roster(
180 &self,
181 listing: &ChatListing,
182 chat_id: String,
183 version: String,
184 ) -> Vec<NativeMember> {
185 let chat_id = chat_id.as_str();
186 if chat_id.is_empty() {
187 return Vec::new();
188 }
189 if let Some(pair) = one_on_one_ids(chat_id) {
190 return pair
191 .into_iter()
192 .map(|user_id| NativeMember {
193 user_id,
194 owner: false,
195 name: None,
196 })
197 .collect();
198 }
199 if let Some((known, members)) = ROSTERS.lock().unwrap().get(chat_id)
200 && *known == version
201 {
202 return members.clone();
203 }
204 match listing.thread(chat_id).await {
205 Ok(thread) => {
206 let members = thread_members(&thread);
207 ROSTERS
208 .lock()
209 .unwrap()
210 .insert(chat_id.to_owned(), (version, members.clone()));
211 members
212 }
213 Err(_) => ROSTERS
214 .lock()
215 .unwrap()
216 .get(chat_id)
217 .map(|(_, members)| members.clone())
218 .unwrap_or_default(),
219 }
220 }
221
222 async fn learn_profiles(&self, user_ids: &[String]) {
223 let unknown: Vec<String> = {
224 let known = PROFILES.lock().unwrap();
225 let mut unknown: Vec<String> = user_ids
226 .iter()
227 .filter(|user_id| !known.contains_key(*user_id))
228 .cloned()
229 .collect();
230 unknown.sort();
231 unknown.dedup();
232 unknown
233 };
234 if unknown.is_empty() {
235 return;
236 }
237 let Ok(profiles) = UserProfiles::new(self.session).fetch(&unknown).await else {
238 return;
239 };
240 let mut known = PROFILES.lock().unwrap();
241 for user_id in unknown {
242 known.insert(user_id, None);
243 }
244 for profile in profiles {
245 known.insert(profile.user_id.clone(), Some(profile));
246 }
247 }
248
249 /// `drop_unknown` leaves out ids the directory does not know, which in a 1:1 is a bot.
250 fn named(&self, members: Vec<NativeMember>, drop_unknown: bool) -> Vec<Value> {
251 let known = PROFILES.lock().unwrap();
252 members
253 .into_iter()
254 .filter(|member| !drop_unknown || !matches!(known.get(&member.user_id), Some(None)))
255 .map(|mut member| {
256 let profile = known.get(&member.user_id).cloned().flatten();
257 if member.name.is_none() {
258 member.name = profile
259 .as_ref()
260 .and_then(|profile| profile.display_name.clone());
261 }
262 graph_member(
263 &member,
264 profile
265 .as_ref()
266 .and_then(|profile| profile.email.as_deref()),
267 )
268 })
269 .collect()
270 }
271}
272
273/// What the directory lookups learned about a user, for callers outside the chat path.
274pub fn known_profile(user_id: &str) -> Option<UserProfile> {
275 PROFILES.lock().unwrap().get(user_id).cloned().flatten()
276}
277
278fn profile_name(user_id: &str) -> Option<String> {
279 known_profile(user_id).and_then(|profile| profile.display_name)
280}
281
282fn profile_email(user_id: &str) -> Option<String> {
283 known_profile(user_id).and_then(|profile| profile.email)
284}
crates/core/src/remote.rs +75 −90
@@ -29,9 +29,10 @@ use graph::{
29 29 };
30 30
31 31 use crate::error::{Error, Result};
32 use crate::native::NativeChats;
32 33 use crate::profile::PersonProfile;
33 34
34 pub const CHATSVC_CHAT_WRITES: bool = false;
35 pub const CHATSVC_CHAT_WRITES: bool = true;
35 36 const URGENT_ACK_EMOTION: &str = "acks";
36 37
37 38 #[derive(Debug, Clone)]
@@ -102,13 +103,6 @@ pub trait Remote {
102 103 channel_id: &str,
103 104 root_ids: &[String],
104 105 ) -> Result<Vec<Result<Vec<Message>>>>;
105 async fn send_chat_message(
106 &self,
107 chat_id: &str,
108 html: &str,
109 mentions: &[OutgoingMention],
110 extras: &MessageExtras,
111 ) -> Result<Message>;
112 106 async fn send_channel_message(
113 107 &self,
114 108 team_id: &str,
@@ -147,16 +141,6 @@ pub trait Remote {
147 141 message_id: &str,
148 142 cards: &str,
149 143 ) -> Result<()>;
150 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
151 async fn mark_chat_unread(
152 &self,
153 chat_id: &str,
154 user_id: &str,
155 tenant_id: &str,
156 last_read_at: DateTime<Utc>,
157 ) -> Result<()>;
158 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
159 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
160 144 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()>;
161 145 async fn add_chat_members(
162 146 &self,
@@ -213,17 +197,6 @@ pub trait Remote {
213 197 Err(Error::Unsupported("channel description"))
214 198 }
215 199
216 async fn reply_with_quote(
217 &self,
218 _chat_id: &str,
219 _quoted_message_id: &str,
220 _html: &str,
221 _mentions: &[OutgoingMention],
222 _extras: &MessageExtras,
223 ) -> Result<Message> {
224 Err(Error::Unsupported("a quoted reply"))
225 }
226
227 200 async fn channel_files_folder(&self, _team_id: &str, _channel_id: &str) -> Result<DriveFolder> {
228 201 Err(Error::Unsupported("a channel files folder"))
229 202 }
@@ -697,19 +670,19 @@ impl Remote for Graph {
697 670 }
698 671
699 672 async fn chats_page(&self, top: usize) -> Result<ChatsPage> {
700 Ok(Graph::chats_page(self, top).await?.into())
673 NativeChats::new(self.session()).first_page(top).await
701 674 }
702 675
703 676 async fn chats_at(&self, next_link: &str) -> Result<ChatsPage> {
704 Ok(Graph::chats_at(self, next_link).await?.into())
677 NativeChats::new(self.session()).page(next_link).await
705 678 }
706 679
707 680 async fn chat(&self, chat_id: &str) -> Result<Chat> {
708 Ok(Graph::chat(self, chat_id).await?)
681 NativeChats::new(self.session()).chat(chat_id).await
709 682 }
710 683
711 684 async fn chat_members(&self, chat_id: &str) -> Result<Vec<Member>> {
712 Ok(Graph::chat_members(self, chat_id).await?)
685 NativeChats::new(self.session()).members(chat_id).await
713 686 }
714 687
715 688 async fn joined_teams(&self) -> Result<Vec<Team>> {
@@ -730,13 +703,15 @@ impl Remote for Graph {
730 703 before: Option<DateTime<Utc>>,
731 704 top: usize,
732 705 ) -> Result<RemotePage> {
733 Ok(Graph::chat_messages(self, chat_id, before, top)
734 .await?
735 .into())
706 NativeChats::new(self.session())
707 .messages(chat_id, before, top)
708 .await
736 709 }
737 710
738 711 async fn chat_message(&self, chat_id: &str, message_id: &str) -> Result<Message> {
739 Ok(Graph::chat_message(self, chat_id, message_id).await?)
712 NativeChats::new(self.session())
713 .message(chat_id, message_id)
714 .await
740 715 }
741 716
742 717 async fn channel_messages(
@@ -803,16 +778,6 @@ impl Remote for Graph {
803 778 .collect())
804 779 }
805 780
806 async fn send_chat_message(
807 &self,
808 chat_id: &str,
809 html: &str,
810 mentions: &[OutgoingMention],
811 extras: &MessageExtras,
812 ) -> Result<Message> {
813 Ok(Graph::send_chat_message(self, chat_id, html, mentions, extras).await?)
814 }
815
816 781 async fn send_channel_message(
817 782 &self,
818 783 team_id: &str,
@@ -877,28 +842,6 @@ impl Remote for Graph {
877 842 .await?)
878 843 }
879 844
880 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
881 Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)
882 }
883
884 async fn mark_chat_unread(
885 &self,
886 chat_id: &str,
887 user_id: &str,
888 tenant_id: &str,
889 last_read_at: DateTime<Utc>,
890 ) -> Result<()> {
891 Ok(Graph::mark_chat_unread(self, chat_id, user_id, tenant_id, last_read_at).await?)
892 }
893
894 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
895 Ok(Graph::hide_chat(self, chat_id, user_id, tenant_id).await?)
896 }
897
898 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
899 Ok(Graph::unhide_chat(self, chat_id, user_id, tenant_id).await?)
900 }
901
902 845 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
903 846 Ok(ThreadMembers::new(self.session())
904 847 .remove(chat_id, user_id)
@@ -994,6 +937,9 @@ impl Remote for Graph {
994 937 .set_emotion(&conversation_ref(target), target.message_id(), &key)
995 938 .await?);
996 939 }
940 if matches!(target, MessageTarget::Chat { .. }) {
941 return Err(Error::Unsupported("this reaction in a chat"));
942 }
997 943 Ok(Graph::set_reaction(self, target, reaction_type).await?)
998 944 }
999 945
@@ -1005,6 +951,9 @@ impl Remote for Graph {
1005 951 .unset_emotions(&conversation_ref(target), target.message_id(), &keys)
1006 952 .await?);
1007 953 }
954 if matches!(target, MessageTarget::Chat { .. }) {
955 return Err(Error::Unsupported("this reaction in a chat"));
956 }
1008 957 Ok(Graph::unset_reaction(self, target, reaction_type).await?)
1009 958 }
1010 959
@@ -1022,6 +971,25 @@ impl Remote for Graph {
1022 971 .edit_message(&conversation, target.message_id(), &html)
1023 972 .await?)
1024 973 }
974 Some(conversation @ ConversationRef::Chat { .. }) => {
975 let entries = crate::teams_quote::mention_entries(mentions).ok_or(
976 Error::Unsupported("editing in a team, channel or tag mention"),
977 )?;
978 let html = format!(
979 "{}{}{}",
980 extras.kept_html(),
981 crate::teams_quote::chatsvc_mention_html(html, mentions),
982 extras.files_html()
983 );
984 Ok(Messages::new(self.session())
985 .edit_message_with_mentions(
986 &conversation,
987 target.message_id(),
988 &html,
989 Some(&serde_json::Value::Array(entries).to_string()),
990 )
991 .await?)
992 }
1025 993 Some(_) => Err(Error::Unsupported(
1026 994 "editing a channel message with mentions",
1027 995 )),
@@ -1047,8 +1015,23 @@ impl Remote for Graph {
1047 1015 }
1048 1016 }
1049 1017
1018 /// Teams names a 1:1 chat after its two members; the chat service creates it with the first message.
1050 1019 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
1051 Ok(Graph::create_one_on_one(self, my_user_id, user_id).await?)
1020 let mut pair = [my_user_id.to_owned(), user_id.to_owned()];
1021 pair.sort();
1022 let sorted_id = format!("19:{}_{}@unq.gbl.spaces", pair[0], pair[1]);
1023 let reversed_id = format!("19:{}_{}@unq.gbl.spaces", pair[1], pair[0]);
1024 let listing = chatsvc::ChatListing::new(self.session());
1025 let chat_id = if listing.conversation(&sorted_id).await.is_err()
1026 && listing.conversation(&reversed_id).await.is_ok()
1027 {
1028 reversed_id
1029 } else {
1030 sorted_id
1031 };
1032 NativeChats::new(self.session())
1033 .created_chat(&chat_id, "oneOnOne", None, &pair)
1034 .await
1052 1035 }
1053 1036
1054 1037 async fn create_group(
@@ -1057,7 +1040,19 @@ impl Remote for Graph {
1057 1040 user_ids: &[String],
1058 1041 topic: Option<&str>,
1059 1042 ) -> Result<Chat> {
1060 Ok(Graph::create_group(self, my_user_id, user_ids, topic).await?)
1043 let mut members = vec![my_user_id.to_owned()];
1044 members.extend(
1045 user_ids
1046 .iter()
1047 .filter(|user_id| *user_id != my_user_id)
1048 .cloned(),
1049 );
1050 let chat_id = ThreadMembers::new(self.session())
1051 .create_group(&members, topic)
1052 .await?;
1053 NativeChats::new(self.session())
1054 .created_chat(&chat_id, "group", topic, &members)
1055 .await
1061 1056 }
1062 1057
1063 1058 async fn search_people(&self, query: &str) -> Result<Vec<User>> {
@@ -1072,20 +1067,6 @@ impl Remote for Graph {
1072 1067 Ok(Graph::channel_description(self, team_id, channel_id).await?)
1073 1068 }
1074 1069
1075 async fn reply_with_quote(
1076 &self,
1077 chat_id: &str,
1078 quoted_message_id: &str,
1079 html: &str,
1080 mentions: &[OutgoingMention],
1081 extras: &MessageExtras,
1082 ) -> Result<Message> {
1083 Ok(
1084 Graph::reply_with_quote(self, chat_id, quoted_message_id, html, mentions, extras)
1085 .await?,
1086 )
1087 }
1088
1089 1070 async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> {
1090 1071 Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)
1091 1072 }
@@ -1182,6 +1163,8 @@ impl Remote for Graph {
1182 1163 }
1183 1164
1184 1165 async fn hosted_content(&self, url: &str) -> Result<Photo> {
1166 let ams_url = chatsvc::hosted_content_image_url(url);
1167 let url = ams_url.as_deref().unwrap_or(url);
1185 1168 if chatsvc::is_link_image_url(url) {
1186 1169 let image = Messages::new(self.session()).link_image(url).await?;
1187 1170 return Ok(Photo {
@@ -1357,11 +1340,13 @@ impl Remote for Graph {
1357 1340 chat_id: &str,
1358 1341 message_ids: &[String],
1359 1342 ) -> Result<Vec<Result<Message>>> {
1360 let messages = Graph::chat_messages_by_id(self, chat_id, message_ids).await?;
1361 Ok(messages
1362 .into_iter()
1363 .map(|message| message.map_err(Into::into))
1364 .collect())
1343 let native = NativeChats::new(self.session());
1344 Ok(futures_util::future::join_all(
1345 message_ids
1346 .iter()
1347 .map(|message_id| native.message(chat_id, message_id)),
1348 )
1349 .await)
1365 1350 }
1366 1351
1367 1352 async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
@@ -29,9 +29,10 @@ use graph::{
29};
29};
30
30
31use crate::error::{Error, Result};
31use crate::error::{Error, Result};
32use crate::native::NativeChats;
32use crate::profile::PersonProfile;
33use crate::profile::PersonProfile;
33
34
34pub const CHATSVC_CHAT_WRITES: bool = false;
35pub const CHATSVC_CHAT_WRITES: bool = true;
35const URGENT_ACK_EMOTION: &str = "acks";
36const URGENT_ACK_EMOTION: &str = "acks";
36
37
37#[derive(Debug, Clone)]
38#[derive(Debug, Clone)]
@@ -102,13 +103,6 @@ pub trait Remote {
102 channel_id: &str,
103 channel_id: &str,
103 root_ids: &[String],
104 root_ids: &[String],
104 ) -> Result<Vec<Result<Vec<Message>>>>;
105 ) -> Result<Vec<Result<Vec<Message>>>>;
105 async fn send_chat_message(
106 &self,
107 chat_id: &str,
108 html: &str,
109 mentions: &[OutgoingMention],
110 extras: &MessageExtras,
111 ) -> Result<Message>;
112 async fn send_channel_message(
106 async fn send_channel_message(
113 &self,
107 &self,
114 team_id: &str,
108 team_id: &str,
@@ -147,16 +141,6 @@ pub trait Remote {
147 message_id: &str,
141 message_id: &str,
148 cards: &str,
142 cards: &str,
149 ) -> Result<()>;
143 ) -> Result<()>;
150 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
151 async fn mark_chat_unread(
152 &self,
153 chat_id: &str,
154 user_id: &str,
155 tenant_id: &str,
156 last_read_at: DateTime<Utc>,
157 ) -> Result<()>;
158 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
159 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
160 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()>;
144 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()>;
161 async fn add_chat_members(
145 async fn add_chat_members(
162 &self,
146 &self,
@@ -213,17 +197,6 @@ pub trait Remote {
213 Err(Error::Unsupported("channel description"))
197 Err(Error::Unsupported("channel description"))
214 }
198 }
215
199
216 async fn reply_with_quote(
217 &self,
218 _chat_id: &str,
219 _quoted_message_id: &str,
220 _html: &str,
221 _mentions: &[OutgoingMention],
222 _extras: &MessageExtras,
223 ) -> Result<Message> {
224 Err(Error::Unsupported("a quoted reply"))
225 }
226
227 async fn channel_files_folder(&self, _team_id: &str, _channel_id: &str) -> Result<DriveFolder> {
200 async fn channel_files_folder(&self, _team_id: &str, _channel_id: &str) -> Result<DriveFolder> {
228 Err(Error::Unsupported("a channel files folder"))
201 Err(Error::Unsupported("a channel files folder"))
229 }
202 }
@@ -697,19 +670,19 @@ impl Remote for Graph {
697 }
670 }
698
671
699 async fn chats_page(&self, top: usize) -> Result<ChatsPage> {
672 async fn chats_page(&self, top: usize) -> Result<ChatsPage> {
700 Ok(Graph::chats_page(self, top).await?.into())
673 NativeChats::new(self.session()).first_page(top).await
701 }
674 }
702
675
703 async fn chats_at(&self, next_link: &str) -> Result<ChatsPage> {
676 async fn chats_at(&self, next_link: &str) -> Result<ChatsPage> {
704 Ok(Graph::chats_at(self, next_link).await?.into())
677 NativeChats::new(self.session()).page(next_link).await
705 }
678 }
706
679
707 async fn chat(&self, chat_id: &str) -> Result<Chat> {
680 async fn chat(&self, chat_id: &str) -> Result<Chat> {
708 Ok(Graph::chat(self, chat_id).await?)
681 NativeChats::new(self.session()).chat(chat_id).await
709 }
682 }
710
683
711 async fn chat_members(&self, chat_id: &str) -> Result<Vec<Member>> {
684 async fn chat_members(&self, chat_id: &str) -> Result<Vec<Member>> {
712 Ok(Graph::chat_members(self, chat_id).await?)
685 NativeChats::new(self.session()).members(chat_id).await
713 }
686 }
714
687
715 async fn joined_teams(&self) -> Result<Vec<Team>> {
688 async fn joined_teams(&self) -> Result<Vec<Team>> {
@@ -730,13 +703,15 @@ impl Remote for Graph {
730 before: Option<DateTime<Utc>>,
703 before: Option<DateTime<Utc>>,
731 top: usize,
704 top: usize,
732 ) -> Result<RemotePage> {
705 ) -> Result<RemotePage> {
733 Ok(Graph::chat_messages(self, chat_id, before, top)
706 NativeChats::new(self.session())
734 .await?
707 .messages(chat_id, before, top)
735 .into())
708 .await
736 }
709 }
737
710
738 async fn chat_message(&self, chat_id: &str, message_id: &str) -> Result<Message> {
711 async fn chat_message(&self, chat_id: &str, message_id: &str) -> Result<Message> {
739 Ok(Graph::chat_message(self, chat_id, message_id).await?)
712 NativeChats::new(self.session())
713 .message(chat_id, message_id)
714 .await
740 }
715 }
741
716
742 async fn channel_messages(
717 async fn channel_messages(
@@ -803,16 +778,6 @@ impl Remote for Graph {
803 .collect())
778 .collect())
804 }
779 }
805
780
806 async fn send_chat_message(
807 &self,
808 chat_id: &str,
809 html: &str,
810 mentions: &[OutgoingMention],
811 extras: &MessageExtras,
812 ) -> Result<Message> {
813 Ok(Graph::send_chat_message(self, chat_id, html, mentions, extras).await?)
814 }
815
816 async fn send_channel_message(
781 async fn send_channel_message(
817 &self,
782 &self,
818 team_id: &str,
783 team_id: &str,
@@ -877,28 +842,6 @@ impl Remote for Graph {
877 .await?)
842 .await?)
878 }
843 }
879
844
880 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
881 Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)
882 }
883
884 async fn mark_chat_unread(
885 &self,
886 chat_id: &str,
887 user_id: &str,
888 tenant_id: &str,
889 last_read_at: DateTime<Utc>,
890 ) -> Result<()> {
891 Ok(Graph::mark_chat_unread(self, chat_id, user_id, tenant_id, last_read_at).await?)
892 }
893
894 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
895 Ok(Graph::hide_chat(self, chat_id, user_id, tenant_id).await?)
896 }
897
898 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
899 Ok(Graph::unhide_chat(self, chat_id, user_id, tenant_id).await?)
900 }
901
902 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
845 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
903 Ok(ThreadMembers::new(self.session())
846 Ok(ThreadMembers::new(self.session())
904 .remove(chat_id, user_id)
847 .remove(chat_id, user_id)
@@ -994,6 +937,9 @@ impl Remote for Graph {
994 .set_emotion(&conversation_ref(target), target.message_id(), &key)
937 .set_emotion(&conversation_ref(target), target.message_id(), &key)
995 .await?);
938 .await?);
996 }
939 }
940 if matches!(target, MessageTarget::Chat { .. }) {
941 return Err(Error::Unsupported("this reaction in a chat"));
942 }
997 Ok(Graph::set_reaction(self, target, reaction_type).await?)
943 Ok(Graph::set_reaction(self, target, reaction_type).await?)
998 }
944 }
999
945
@@ -1005,6 +951,9 @@ impl Remote for Graph {
1005 .unset_emotions(&conversation_ref(target), target.message_id(), &keys)
951 .unset_emotions(&conversation_ref(target), target.message_id(), &keys)
1006 .await?);
952 .await?);
1007 }
953 }
954 if matches!(target, MessageTarget::Chat { .. }) {
955 return Err(Error::Unsupported("this reaction in a chat"));
956 }
1008 Ok(Graph::unset_reaction(self, target, reaction_type).await?)
957 Ok(Graph::unset_reaction(self, target, reaction_type).await?)
1009 }
958 }
1010
959
@@ -1022,6 +971,25 @@ impl Remote for Graph {
1022 .edit_message(&conversation, target.message_id(), &html)
971 .edit_message(&conversation, target.message_id(), &html)
1023 .await?)
972 .await?)
1024 }
973 }
974 Some(conversation @ ConversationRef::Chat { .. }) => {
975 let entries = crate::teams_quote::mention_entries(mentions).ok_or(
976 Error::Unsupported("editing in a team, channel or tag mention"),
977 )?;
978 let html = format!(
979 "{}{}{}",
980 extras.kept_html(),
981 crate::teams_quote::chatsvc_mention_html(html, mentions),
982 extras.files_html()
983 );
984 Ok(Messages::new(self.session())
985 .edit_message_with_mentions(
986 &conversation,
987 target.message_id(),
988 &html,
989 Some(&serde_json::Value::Array(entries).to_string()),
990 )
991 .await?)
992 }
1025 Some(_) => Err(Error::Unsupported(
993 Some(_) => Err(Error::Unsupported(
1026 "editing a channel message with mentions",
994 "editing a channel message with mentions",
1027 )),
995 )),
@@ -1047,8 +1015,23 @@ impl Remote for Graph {
1047 }
1015 }
1048 }
1016 }
1049
1017
1018 /// Teams names a 1:1 chat after its two members; the chat service creates it with the first message.
1050 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
1019 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
1051 Ok(Graph::create_one_on_one(self, my_user_id, user_id).await?)
1020 let mut pair = [my_user_id.to_owned(), user_id.to_owned()];
1021 pair.sort();
1022 let sorted_id = format!("19:{}_{}@unq.gbl.spaces", pair[0], pair[1]);
1023 let reversed_id = format!("19:{}_{}@unq.gbl.spaces", pair[1], pair[0]);
1024 let listing = chatsvc::ChatListing::new(self.session());
1025 let chat_id = if listing.conversation(&sorted_id).await.is_err()
1026 && listing.conversation(&reversed_id).await.is_ok()
1027 {
1028 reversed_id
1029 } else {
1030 sorted_id
1031 };
1032 NativeChats::new(self.session())
1033 .created_chat(&chat_id, "oneOnOne", None, &pair)
1034 .await
1052 }
1035 }
1053
1036
1054 async fn create_group(
1037 async fn create_group(
@@ -1057,7 +1040,19 @@ impl Remote for Graph {
1057 user_ids: &[String],
1040 user_ids: &[String],
1058 topic: Option<&str>,
1041 topic: Option<&str>,
1059 ) -> Result<Chat> {
1042 ) -> Result<Chat> {
1060 Ok(Graph::create_group(self, my_user_id, user_ids, topic).await?)
1043 let mut members = vec![my_user_id.to_owned()];
1044 members.extend(
1045 user_ids
1046 .iter()
1047 .filter(|user_id| *user_id != my_user_id)
1048 .cloned(),
1049 );
1050 let chat_id = ThreadMembers::new(self.session())
1051 .create_group(&members, topic)
1052 .await?;
1053 NativeChats::new(self.session())
1054 .created_chat(&chat_id, "group", topic, &members)
1055 .await
1061 }
1056 }
1062
1057
1063 async fn search_people(&self, query: &str) -> Result<Vec<User>> {
1058 async fn search_people(&self, query: &str) -> Result<Vec<User>> {
@@ -1072,20 +1067,6 @@ impl Remote for Graph {
1072 Ok(Graph::channel_description(self, team_id, channel_id).await?)
1067 Ok(Graph::channel_description(self, team_id, channel_id).await?)
1073 }
1068 }
1074
1069
1075 async fn reply_with_quote(
1076 &self,
1077 chat_id: &str,
1078 quoted_message_id: &str,
1079 html: &str,
1080 mentions: &[OutgoingMention],
1081 extras: &MessageExtras,
1082 ) -> Result<Message> {
1083 Ok(
1084 Graph::reply_with_quote(self, chat_id, quoted_message_id, html, mentions, extras)
1085 .await?,
1086 )
1087 }
1088
1089 async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> {
1070 async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> {
1090 Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)
1071 Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)
1091 }
1072 }
@@ -1182,6 +1163,8 @@ impl Remote for Graph {
1182 }
1163 }
1183
1164
1184 async fn hosted_content(&self, url: &str) -> Result<Photo> {
1165 async fn hosted_content(&self, url: &str) -> Result<Photo> {
1166 let ams_url = chatsvc::hosted_content_image_url(url);
1167 let url = ams_url.as_deref().unwrap_or(url);
1185 if chatsvc::is_link_image_url(url) {
1168 if chatsvc::is_link_image_url(url) {
1186 let image = Messages::new(self.session()).link_image(url).await?;
1169 let image = Messages::new(self.session()).link_image(url).await?;
1187 return Ok(Photo {
1170 return Ok(Photo {
@@ -1357,11 +1340,13 @@ impl Remote for Graph {
1357 chat_id: &str,
1340 chat_id: &str,
1358 message_ids: &[String],
1341 message_ids: &[String],
1359 ) -> Result<Vec<Result<Message>>> {
1342 ) -> Result<Vec<Result<Message>>> {
1360 let messages = Graph::chat_messages_by_id(self, chat_id, message_ids).await?;
1343 let native = NativeChats::new(self.session());
1361 Ok(messages
1344 Ok(futures_util::future::join_all(
1362 .into_iter()
1345 message_ids
1363 .map(|message| message.map_err(Into::into))
1346 .iter()
1364 .collect())
1347 .map(|message_id| native.message(chat_id, message_id)),
1348 )
1349 .await)
1365 }
1350 }
1366
1351
1367 async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
1352 async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
crates/core/src/teams_quote.rs +19 −11
@@ -45,26 +45,33 @@ pub(crate) fn teams_quote(record: &MessageRecord) -> Option<TeamsQuote> {
45 45 }
46 46
47 47 /// The `properties` Teams' `sendMessageInConv` writes; `None` when a mention has no chatsvc shape here.
48 pub(crate) fn quote_reply_properties(
49 quote: &TeamsQuote,
48 pub(crate) fn message_properties(
49 quote: Option<&TeamsQuote>,
50 50 mentions: &[OutgoingMention],
51 51 importance: Option<&str>,
52 files: &Value,
52 53 ) -> Option<Value> {
53 let mention_entries = mentions
54 .iter()
55 .map(mention_entry)
56 .collect::<Option<Vec<_>>>()?;
54 let mention_entries = mention_entries(mentions)?;
55 let quoted: Vec<Value> = quote
56 .map(|quote| quote.quoted_message.clone())
57 .into_iter()
58 .collect();
57 59 Some(json!({
58 60 "importance": importance.unwrap_or_default(),
59 61 "links": "[]",
60 62 "mentions": Value::Array(mention_entries).to_string(),
61 63 "onbehalfof": null,
62 "files": "[]",
63 "qtdMsgs": Value::Array(vec![quote.quoted_message.clone()]).to_string(),
64 "files": files.to_string(),
65 "qtdMsgs": Value::Array(quoted).to_string(),
64 66 "formatVariant": FORMAT_VARIANT,
65 67 }))
66 68 }
67 69
70 /// The chatsvc `mentions` entries; `None` when a mention is not a person.
71 pub(crate) fn mention_entries(mentions: &[OutgoingMention]) -> Option<Vec<Value>> {
72 mentions.iter().map(mention_entry).collect()
73 }
74
68 75 fn mention_entry(mention: &OutgoingMention) -> Option<Value> {
69 76 let MentionTarget::User { user_id } = &mention.target else {
70 77 return None;
@@ -132,7 +139,7 @@ mod tests {
132 139
133 140 #[test]
134 141 fn a_quote_reply_gets_the_teams_property_set() {
135 let properties = quote_reply_properties(&quote(), &[], None).unwrap();
142 let properties = message_properties(Some(&quote()), &[], None, &json!([])).unwrap();
136 143 assert_eq!(
137 144 properties,
138 145 json!({
@@ -160,7 +167,8 @@ mod tests {
160 167 html,
161 168 "hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"
162 169 );
163 let properties = quote_reply_properties(&quote(), &mentions, Some("high")).unwrap();
170 let properties =
171 message_properties(Some(&quote()), &mentions, Some("high"), &json!([])).unwrap();
164 172 assert_eq!(properties["importance"], "high");
165 173 assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");
166 174 let entries: Value =
@@ -194,7 +202,7 @@ mod tests {
194 202 },
195 203 ] {
196 204 let mentions = [mention(0, target)];
197 assert!(quote_reply_properties(&quote(), &mentions, None).is_none());
205 assert!(message_properties(Some(&quote()), &mentions, None, &json!([])).is_none());
198 206 }
199 207 }
200 208
@@ -45,26 +45,33 @@ pub(crate) fn teams_quote(record: &MessageRecord) -> Option<TeamsQuote> {
45}
45}
46
46
47/// The `properties` Teams' `sendMessageInConv` writes; `None` when a mention has no chatsvc shape here.
47/// The `properties` Teams' `sendMessageInConv` writes; `None` when a mention has no chatsvc shape here.
48pub(crate) fn quote_reply_properties(
48pub(crate) fn message_properties(
49 quote: &TeamsQuote,
49 quote: Option<&TeamsQuote>,
50 mentions: &[OutgoingMention],
50 mentions: &[OutgoingMention],
51 importance: Option<&str>,
51 importance: Option<&str>,
52 files: &Value,
52) -> Option<Value> {
53) -> Option<Value> {
53 let mention_entries = mentions
54 let mention_entries = mention_entries(mentions)?;
54 .iter()
55 let quoted: Vec<Value> = quote
55 .map(mention_entry)
56 .map(|quote| quote.quoted_message.clone())
56 .collect::<Option<Vec<_>>>()?;
57 .into_iter()
58 .collect();
57 Some(json!({
59 Some(json!({
58 "importance": importance.unwrap_or_default(),
60 "importance": importance.unwrap_or_default(),
59 "links": "[]",
61 "links": "[]",
60 "mentions": Value::Array(mention_entries).to_string(),
62 "mentions": Value::Array(mention_entries).to_string(),
61 "onbehalfof": null,
63 "onbehalfof": null,
62 "files": "[]",
64 "files": files.to_string(),
63 "qtdMsgs": Value::Array(vec![quote.quoted_message.clone()]).to_string(),
65 "qtdMsgs": Value::Array(quoted).to_string(),
64 "formatVariant": FORMAT_VARIANT,
66 "formatVariant": FORMAT_VARIANT,
65 }))
67 }))
66}
68}
67
69
70/// The chatsvc `mentions` entries; `None` when a mention is not a person.
71pub(crate) fn mention_entries(mentions: &[OutgoingMention]) -> Option<Vec<Value>> {
72 mentions.iter().map(mention_entry).collect()
73}
74
68fn mention_entry(mention: &OutgoingMention) -> Option<Value> {
75fn mention_entry(mention: &OutgoingMention) -> Option<Value> {
69 let MentionTarget::User { user_id } = &mention.target else {
76 let MentionTarget::User { user_id } = &mention.target else {
70 return None;
77 return None;
@@ -132,7 +139,7 @@ mod tests {
132
139
133 #[test]
140 #[test]
134 fn a_quote_reply_gets_the_teams_property_set() {
141 fn a_quote_reply_gets_the_teams_property_set() {
135 let properties = quote_reply_properties(&quote(), &[], None).unwrap();
142 let properties = message_properties(Some(&quote()), &[], None, &json!([])).unwrap();
136 assert_eq!(
143 assert_eq!(
137 properties,
144 properties,
138 json!({
145 json!({
@@ -160,7 +167,8 @@ mod tests {
160 html,
167 html,
161 "hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"
168 "hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"
162 );
169 );
163 let properties = quote_reply_properties(&quote(), &mentions, Some("high")).unwrap();
170 let properties =
171 message_properties(Some(&quote()), &mentions, Some("high"), &json!([])).unwrap();
164 assert_eq!(properties["importance"], "high");
172 assert_eq!(properties["importance"], "high");
165 assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");
173 assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");
166 let entries: Value =
174 let entries: Value =
@@ -194,7 +202,7 @@ mod tests {
194 },
202 },
195 ] {
203 ] {
196 let mentions = [mention(0, target)];
204 let mentions = [mention(0, target)];
197 assert!(quote_reply_properties(&quote(), &mentions, None).is_none());
205 assert!(message_properties(Some(&quote()), &mentions, None, &json!([])).is_none());
198 }
206 }
199 }
207 }
200
208
crates/core/tests/engine.rs +55 −124
@@ -93,7 +93,6 @@ struct Fake {
93 93 teams: Mutex<Vec<Team>>,
94 94 failing_team: Mutex<Option<String>>,
95 95 failing_cards: Mutex<bool>,
96 sent: Mutex<Vec<String>>,
97 96 chat_calls: Mutex<usize>,
98 97 chat_page_calls: Mutex<usize>,
99 98 team_calls: Mutex<usize>,
@@ -110,7 +109,6 @@ struct Fake {
110 109 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
111 110 extras_sent: Mutex<Vec<MessageExtras>>,
112 111 chatsvc_posts: Mutex<Vec<(String, String, String, serde_json::Value)>>,
113 send_answer_body: Mutex<Option<String>>,
114 112 folder_requests: Mutex<usize>,
115 113 directory_users: Mutex<Vec<User>>,
116 114 horizons: Mutex<Vec<chatsvc::MemberHorizon>>,
@@ -479,25 +477,6 @@ impl Remote for Handle {
479 477 .collect())
480 478 }
481 479
482 async fn send_chat_message(
483 &self,
484 _chat_id: &str,
485 html: &str,
486 mentions: &[OutgoingMention],
487 extras: &MessageExtras,
488 ) -> Result<Message> {
489 self.sent.lock().unwrap().push(html.to_owned());
490 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
491 self.extras_sent.lock().unwrap().push(extras.clone());
492 let body = self
493 .send_answer_body
494 .lock()
495 .unwrap()
496 .clone()
497 .unwrap_or_else(|| html.to_owned());
498 Ok(message(9000, 500, &body))
499 }
500
501 480 async fn send_channel_message(
502 481 &self,
503 482 _team_id: &str,
@@ -580,35 +559,6 @@ impl Remote for Handle {
580 559 Ok(())
581 560 }
582 561
583 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
584 self.record(format!("mark_read {chat_id} {user_id} {tenant_id}"));
585 Ok(())
586 }
587
588 async fn mark_chat_unread(
589 &self,
590 chat_id: &str,
591 user_id: &str,
592 tenant_id: &str,
593 last_read_at: DateTime<Utc>,
594 ) -> Result<()> {
595 self.record(format!(
596 "mark_unread {chat_id} {user_id} {tenant_id} {}",
597 last_read_at.timestamp_millis()
598 ));
599 Ok(())
600 }
601
602 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
603 self.record(format!("hide {chat_id} {user_id} {tenant_id}"));
604 Ok(())
605 }
606
607 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
608 self.record(format!("unhide {chat_id} {user_id} {tenant_id}"));
609 Ok(())
610 }
611
612 562 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
613 563 self.record(format!("remove member {chat_id} {user_id}"));
614 564 Ok(())
@@ -784,20 +734,6 @@ impl Remote for Handle {
784 734 Ok(chat("19:group@thread.v2", topic, 41, 41, ME, false))
785 735 }
786 736
787 async fn reply_with_quote(
788 &self,
789 chat_id: &str,
790 quoted_message_id: &str,
791 html: &str,
792 mentions: &[OutgoingMention],
793 extras: &MessageExtras,
794 ) -> Result<Message> {
795 self.record(format!("quote_reply {chat_id} {quoted_message_id} {html}"));
796 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
797 self.extras_sent.lock().unwrap().push(extras.clone());
798 Ok(message(9003, 503, html))
799 }
800
801 737 async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> {
802 738 *self.folder_requests.lock().unwrap() += 1;
803 739 self.record(format!("files_folder {team_id} {channel_id}"));
@@ -1560,13 +1496,10 @@ async fn chat_state_actions_call_remote_and_update_the_store() {
1560 1496
1561 1497 engine.mark_unread(CHAT).await.unwrap();
1562 1498 let last_message_millis = (base() + Duration::minutes(5)).timestamp_millis();
1563 assert_eq!(
1564 fake.calls().last().unwrap(),
1565 &format!(
1566 "mark_unread {CHAT} {ME} tenant-1 {}",
1567 last_message_millis - 1
1568 )
1569 );
1499 assert!(fake.calls().last().unwrap().starts_with(&format!(
1500 "read bookmark {CHAT} {};",
1501 last_message_millis - 1
1502 )));
1570 1503 let unread = engine.sidebar().unwrap().chats[0].clone();
1571 1504 assert!(unread.unread);
1572 1505 assert_eq!(
@@ -1592,7 +1525,7 @@ async fn hide_removes_the_chat_and_unhide_brings_it_back() {
1592 1525 engine.hide_chat(CHAT).await.unwrap();
1593 1526 assert_eq!(
1594 1527 fake.calls().last().unwrap(),
1595 &format!("hide {CHAT} {ME} tenant-1")
1528 &format!("hidden at {CHAT} now")
1596 1529 );
1597 1530 assert!(engine.sidebar().unwrap().chats.is_empty());
1598 1531 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
@@ -1600,7 +1533,7 @@ async fn hide_removes_the_chat_and_unhide_brings_it_back() {
1600 1533 engine.unhide_chat(CHAT).await.unwrap();
1601 1534 assert_eq!(
1602 1535 fake.calls().last().unwrap(),
1603 &format!("unhide {CHAT} {ME} tenant-1")
1536 &format!("hidden at {CHAT} none")
1604 1537 );
1605 1538 assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
1606 1539 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
@@ -1831,10 +1764,10 @@ async fn send_message_converts_markdown_and_caches_the_answer() {
1831 1764 .await
1832 1765 .unwrap();
1833 1766 assert_eq!(
1834 fake.sent.lock().unwrap().as_slice(),
1835 ["hi <b>there</b> &lt;x&gt;"]
1767 fake.chatsvc_posts.lock().unwrap()[0].1,
1768 "hi <b>there</b> &lt;x&gt;"
1836 1769 );
1837 assert_eq!(record.message_id, "m9000");
1770 assert_eq!(record.message_id, "1727203440000");
1838 1771 assert_eq!(engine.store().message_count(CHAT).unwrap(), 4);
1839 1772 assert_eq!(
1840 1773 events.try_recv().unwrap(),
@@ -2555,7 +2488,9 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {
2555 2488 .send_message_with_extras(NOTES_CHAT_ID, "note to self", None, &[], &extras)
2556 2489 .await
2557 2490 .unwrap();
2558 fake.set_chat_messages(vec![message(9000, 500, "<p>note to self</p>")]);
2491 let mut sent_note = message(9000, 500, "<p>note to self</p>");
2492 sent_note.id = sent.message_id.clone();
2493 fake.set_chat_messages(vec![sent_note]);
2559 2494 engine
2560 2495 .reply_to_with_extras(
2561 2496 NOTES_CHAT_ID,
@@ -2588,15 +2523,19 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {
2588 2523 .unwrap();
2589 2524
2590 2525 assert_eq!(*fake.single_chat_calls.lock().unwrap(), 0);
2591 assert_eq!(fake.sent.lock().unwrap().as_slice(), ["note to self"]);
2526 assert!(
2527 fake.chatsvc_posts.lock().unwrap()[0]
2528 .1
2529 .starts_with("note to self")
2530 );
2592 2531 let calls = fake.calls();
2593 2532 for expected in [
2594 2533 "chatsvc post 48:notes",
2595 "edit m9000 edited",
2596 "set_reaction m9000 \u{1f44d}",
2597 "unset_reaction m9000 \u{1f44d}",
2534 "edit 1727203440000 edited",
2535 "set_reaction 1727203440000 \u{1f44d}",
2536 "unset_reaction 1727203440000 \u{1f44d}",
2598 2537 "upload chat-files plan.txt 4",
2599 "soft_delete user-me m9000",
2538 "soft_delete user-me 1727203440000",
2600 2539 ] {
2601 2540 assert!(
2602 2541 calls.iter().any(|call| call == expected),
@@ -2631,9 +2570,14 @@ async fn send_with_extras_hands_images_and_files_to_the_remote() {
2631 2570 .unwrap();
2632 2571 engine.send_message(CHAT, "plain", None).await.unwrap();
2633 2572
2634 let sent = fake.extras_sent.lock().unwrap();
2635 assert_eq!(sent[0], extras);
2636 assert!(sent[1].is_empty());
2573 let calls = fake.calls();
2574 assert!(
2575 calls.contains(&format!("ams upload {CHAT} image.png 1")),
2576 "{calls:?}"
2577 );
2578 let posts = fake.chatsvc_posts.lock().unwrap();
2579 assert!(posts[0].1.contains("0-ams"));
2580 assert_eq!(posts[1].1, "plain");
2637 2581 }
2638 2582
2639 2583 #[tokio::test]
@@ -2641,7 +2585,6 @@ async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2641 2585 let directory = tempfile::tempdir().unwrap();
2642 2586 let fake = Arc::new(Fake::default());
2643 2587 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
2644 *fake.send_answer_body.lock().unwrap() = Some(format!("<p>look</p><img src=\"{HOSTED}\">"));
2645 2588 let engine = engine_with(&fake, small_pages())
2646 2589 .with_image_dir(directory.path(), 1024 * 1024)
2647 2590 .unwrap();
@@ -2662,12 +2605,11 @@ async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2662 2605 .await
2663 2606 .unwrap();
2664 2607
2665 assert_eq!(engine.image(HOSTED).unwrap().bytes, vec![9, 8, 7]);
2608 assert_eq!(engine.image(SENT_AMS_IMAGE).unwrap().bytes, vec![9, 8, 7]);
2666 2609 assert!(fake.hosted_requests.lock().unwrap().is_empty());
2667 2610 let mut seeded = false;
2668 2611 while let Ok(event) = events.try_recv() {
2669 seeded |=
2670 matches!(event, CoreEvent::ImagesChanged { keys } if keys == vec![HOSTED.to_owned()]);
2612 seeded |= matches!(event, CoreEvent::ImagesChanged { keys } if keys == vec![SENT_AMS_IMAGE.to_owned()]);
2671 2613 }
2672 2614 assert!(seeded);
2673 2615 }
@@ -2821,7 +2763,7 @@ async fn send_typing_addresses_chats_channels_and_threads() {
2821 2763 }
2822 2764
2823 2765 #[tokio::test]
2824 async fn chat_actions_call_graph_with_the_right_ids() {
2766 async fn chat_actions_call_the_remote_with_the_right_ids() {
2825 2767 let fake = Arc::new(Fake::default());
2826 2768 fake.set_chat_messages(numbered(3));
2827 2769 let engine = chat_engine(&fake, small_pages()).await;
@@ -2840,7 +2782,7 @@ async fn chat_actions_call_graph_with_the_right_ids() {
2840 2782 .await
2841 2783 .unwrap();
2842 2784 let calls = fake.calls();
2843 assert_eq!(calls[0], format!("mark_read {CHAT} {ME} tenant-1"));
2785 assert!(calls[0].starts_with(&format!("read horizon {CHAT} ")));
2844 2786 assert!(calls.contains(&"set_reaction m0001 like".to_owned()));
2845 2787 assert!(calls.contains(&"unset_reaction m0001 like".to_owned()));
2846 2788 assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned()));
@@ -4034,6 +3976,8 @@ async fn folders_without_a_source_are_unsupported() {
4034 3976 ));
4035 3977 }
4036 3978
3979 const SENT_AMS_IMAGE: &str =
3980 "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-ams/views/imgpsh_fullsize";
4037 3981 const HOSTED: &str =
4038 3982 "https://graph.microsoft.com/v1.0/chats/c/messages/m0001/hostedContents/h1/$value";
4039 3983
@@ -4274,19 +4218,13 @@ async fn chat_mentions_become_at_tags_and_a_mentions_array() {
4274 4218 )
4275 4219 .await
4276 4220 .unwrap();
4277 assert_eq!(
4278 fake.sent.lock().unwrap()[0],
4279 "hi <at id=\"0\">Ada Example</at> &amp; co"
4280 );
4281 let mentions = fake.mentions_sent.lock().unwrap()[0].clone();
4282 assert_eq!(mentions.len(), 1);
4283 assert_eq!(mentions[0].id, 0);
4284 assert_eq!(
4285 mentions[0].target,
4286 MentionTarget::User {
4287 user_id: "user-ada".to_owned()
4288 }
4289 );
4221 let posts = fake.chatsvc_posts.lock().unwrap().clone();
4222 assert!(posts[0].1.contains("Ada Example</span>"), "{}", posts[0].1);
4223 assert!(posts[0].1.ends_with(" &amp; co"), "{}", posts[0].1);
4224 let mentions: serde_json::Value =
4225 serde_json::from_str(posts[0].3["mentions"].as_str().unwrap()).unwrap();
4226 assert_eq!(mentions.as_array().unwrap().len(), 1);
4227 assert_eq!(mentions[0]["mri"], "8:orgid:user-ada");
4290 4228 assert!(
4291 4229 engine
4292 4230 .send_message_with_mentions(CHAT, "@Squad", None, &[MentionInput::team("t", "Squad")])
@@ -5228,13 +5166,10 @@ async fn mark_unread_from_a_message_backs_up_one_millisecond() {
5228 5166 let engine = chat_engine(&fake, small_pages()).await;
5229 5167 let created_at = base() + Duration::minutes(2);
5230 5168 engine.mark_unread_from(CHAT, created_at).await.unwrap();
5231 assert_eq!(
5232 fake.calls().last().unwrap(),
5233 &format!(
5234 "mark_unread {CHAT} {ME} tenant-1 {}",
5235 created_at.timestamp_millis() - 1
5236 )
5237 );
5169 assert!(fake.calls().last().unwrap().starts_with(&format!(
5170 "read bookmark {CHAT} {};",
5171 created_at.timestamp_millis() - 1
5172 )));
5238 5173 }
5239 5174
5240 5175 #[tokio::test]
@@ -5965,7 +5900,9 @@ async fn marking_the_notes_chat_read_takes_the_tenant_from_another_chat() {
5965 5900
5966 5901 let calls = fake.calls();
5967 5902 assert!(
5968 calls.contains(&format!("mark_read {NOTES_CHAT_ID} {ME} tenant-1")),
5903 calls
5904 .iter()
5905 .any(|call| call.starts_with(&format!("read horizon {NOTES_CHAT_ID} "))),
5969 5906 "{calls:?}"
5970 5907 );
5971 5908 let member_requests = fake.member_requests.lock().unwrap();
@@ -6043,7 +5980,7 @@ async fn a_quoted_chat_reply_is_written_through_chatsvc_in_the_teams_shape() {
6043 5980 }
6044 5981
6045 5982 #[tokio::test]
6046 async fn a_quoted_chat_reply_with_an_image_stays_on_graph() {
5983 async fn a_quoted_chat_reply_with_an_image_goes_through_chatsvc() {
6047 5984 let fake = Arc::new(Fake::default());
6048 5985 fake.set_chat_messages(numbered(2));
6049 5986 let engine = chat_engine(&fake, small_pages()).await;
@@ -6059,25 +5996,19 @@ async fn a_quoted_chat_reply_with_an_image_stays_on_graph() {
6059 5996 .reply_to_with_extras(CHAT, "m0001", "look", &[], &extras)
6060 5997 .await
6061 5998 .unwrap();
6062 assert!(fake.chatsvc_posts.lock().unwrap().is_empty());
6063 assert!(
6064 fake.calls()
6065 .contains(&format!("quote_reply {CHAT} m0001 look"))
6066 );
5999 let posts = fake.chatsvc_posts.lock().unwrap();
6000 assert!(posts[0].1.starts_with("<blockquote"), "{}", posts[0].1);
6001 assert!(posts[0].1.contains("0-ams"));
6067 6002 }
6068 6003
6069 6004 #[tokio::test]
6070 async fn a_quoted_reply_to_an_unknown_message_stays_on_graph() {
6005 async fn a_reply_to_an_unknown_message_is_sent_without_a_quote() {
6071 6006 let fake = Arc::new(Fake::default());
6072 6007 fake.set_chat_messages(numbered(2));
6073 6008 let engine = chat_engine(&fake, small_pages()).await;
6074 6009 engine.fetch_newer(CHAT).await.unwrap();
6075 6010 engine.reply_to(CHAT, "m7777", "hi").await.unwrap();
6076 assert!(fake.chatsvc_posts.lock().unwrap().is_empty());
6077 assert!(
6078 fake.calls()
6079 .contains(&format!("quote_reply {CHAT} m7777 hi"))
6080 );
6011 assert_eq!(fake.chatsvc_posts.lock().unwrap()[0].1, "hi");
6081 6012 }
6082 6013
6083 6014 #[tokio::test]
@@ -93,7 +93,6 @@ struct Fake {
93 teams: Mutex<Vec<Team>>,
93 teams: Mutex<Vec<Team>>,
94 failing_team: Mutex<Option<String>>,
94 failing_team: Mutex<Option<String>>,
95 failing_cards: Mutex<bool>,
95 failing_cards: Mutex<bool>,
96 sent: Mutex<Vec<String>>,
97 chat_calls: Mutex<usize>,
96 chat_calls: Mutex<usize>,
98 chat_page_calls: Mutex<usize>,
97 chat_page_calls: Mutex<usize>,
99 team_calls: Mutex<usize>,
98 team_calls: Mutex<usize>,
@@ -110,7 +109,6 @@ struct Fake {
110 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
109 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
111 extras_sent: Mutex<Vec<MessageExtras>>,
110 extras_sent: Mutex<Vec<MessageExtras>>,
112 chatsvc_posts: Mutex<Vec<(String, String, String, serde_json::Value)>>,
111 chatsvc_posts: Mutex<Vec<(String, String, String, serde_json::Value)>>,
113 send_answer_body: Mutex<Option<String>>,
114 folder_requests: Mutex<usize>,
112 folder_requests: Mutex<usize>,
115 directory_users: Mutex<Vec<User>>,
113 directory_users: Mutex<Vec<User>>,
116 horizons: Mutex<Vec<chatsvc::MemberHorizon>>,
114 horizons: Mutex<Vec<chatsvc::MemberHorizon>>,
@@ -479,25 +477,6 @@ impl Remote for Handle {
479 .collect())
477 .collect())
480 }
478 }
481
479
482 async fn send_chat_message(
483 &self,
484 _chat_id: &str,
485 html: &str,
486 mentions: &[OutgoingMention],
487 extras: &MessageExtras,
488 ) -> Result<Message> {
489 self.sent.lock().unwrap().push(html.to_owned());
490 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
491 self.extras_sent.lock().unwrap().push(extras.clone());
492 let body = self
493 .send_answer_body
494 .lock()
495 .unwrap()
496 .clone()
497 .unwrap_or_else(|| html.to_owned());
498 Ok(message(9000, 500, &body))
499 }
500
501 async fn send_channel_message(
480 async fn send_channel_message(
502 &self,
481 &self,
503 _team_id: &str,
482 _team_id: &str,
@@ -580,35 +559,6 @@ impl Remote for Handle {
580 Ok(())
559 Ok(())
581 }
560 }
582
561
583 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
584 self.record(format!("mark_read {chat_id} {user_id} {tenant_id}"));
585 Ok(())
586 }
587
588 async fn mark_chat_unread(
589 &self,
590 chat_id: &str,
591 user_id: &str,
592 tenant_id: &str,
593 last_read_at: DateTime<Utc>,
594 ) -> Result<()> {
595 self.record(format!(
596 "mark_unread {chat_id} {user_id} {tenant_id} {}",
597 last_read_at.timestamp_millis()
598 ));
599 Ok(())
600 }
601
602 async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
603 self.record(format!("hide {chat_id} {user_id} {tenant_id}"));
604 Ok(())
605 }
606
607 async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
608 self.record(format!("unhide {chat_id} {user_id} {tenant_id}"));
609 Ok(())
610 }
611
612 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
562 async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
613 self.record(format!("remove member {chat_id} {user_id}"));
563 self.record(format!("remove member {chat_id} {user_id}"));
614 Ok(())
564 Ok(())
@@ -784,20 +734,6 @@ impl Remote for Handle {
784 Ok(chat("19:group@thread.v2", topic, 41, 41, ME, false))
734 Ok(chat("19:group@thread.v2", topic, 41, 41, ME, false))
785 }
735 }
786
736
787 async fn reply_with_quote(
788 &self,
789 chat_id: &str,
790 quoted_message_id: &str,
791 html: &str,
792 mentions: &[OutgoingMention],
793 extras: &MessageExtras,
794 ) -> Result<Message> {
795 self.record(format!("quote_reply {chat_id} {quoted_message_id} {html}"));
796 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
797 self.extras_sent.lock().unwrap().push(extras.clone());
798 Ok(message(9003, 503, html))
799 }
800
801 async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> {
737 async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> {
802 *self.folder_requests.lock().unwrap() += 1;
738 *self.folder_requests.lock().unwrap() += 1;
803 self.record(format!("files_folder {team_id} {channel_id}"));
739 self.record(format!("files_folder {team_id} {channel_id}"));
@@ -1560,13 +1496,10 @@ async fn chat_state_actions_call_remote_and_update_the_store() {
1560
1496
1561 engine.mark_unread(CHAT).await.unwrap();
1497 engine.mark_unread(CHAT).await.unwrap();
1562 let last_message_millis = (base() + Duration::minutes(5)).timestamp_millis();
1498 let last_message_millis = (base() + Duration::minutes(5)).timestamp_millis();
1563 assert_eq!(
1499 assert!(fake.calls().last().unwrap().starts_with(&format!(
1564 fake.calls().last().unwrap(),
1500 "read bookmark {CHAT} {};",
1565 &format!(
1501 last_message_millis - 1
1566 "mark_unread {CHAT} {ME} tenant-1 {}",
1502 )));
1567 last_message_millis - 1
1568 )
1569 );
1570 let unread = engine.sidebar().unwrap().chats[0].clone();
1503 let unread = engine.sidebar().unwrap().chats[0].clone();
1571 assert!(unread.unread);
1504 assert!(unread.unread);
1572 assert_eq!(
1505 assert_eq!(
@@ -1592,7 +1525,7 @@ async fn hide_removes_the_chat_and_unhide_brings_it_back() {
1592 engine.hide_chat(CHAT).await.unwrap();
1525 engine.hide_chat(CHAT).await.unwrap();
1593 assert_eq!(
1526 assert_eq!(
1594 fake.calls().last().unwrap(),
1527 fake.calls().last().unwrap(),
1595 &format!("hide {CHAT} {ME} tenant-1")
1528 &format!("hidden at {CHAT} now")
1596 );
1529 );
1597 assert!(engine.sidebar().unwrap().chats.is_empty());
1530 assert!(engine.sidebar().unwrap().chats.is_empty());
1598 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
1531 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
@@ -1600,7 +1533,7 @@ async fn hide_removes_the_chat_and_unhide_brings_it_back() {
1600 engine.unhide_chat(CHAT).await.unwrap();
1533 engine.unhide_chat(CHAT).await.unwrap();
1601 assert_eq!(
1534 assert_eq!(
1602 fake.calls().last().unwrap(),
1535 fake.calls().last().unwrap(),
1603 &format!("unhide {CHAT} {ME} tenant-1")
1536 &format!("hidden at {CHAT} none")
1604 );
1537 );
1605 assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
1538 assert_eq!(engine.sidebar().unwrap().chats.len(), 1);
1606 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
1539 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
@@ -1831,10 +1764,10 @@ async fn send_message_converts_markdown_and_caches_the_answer() {
1831 .await
1764 .await
1832 .unwrap();
1765 .unwrap();
1833 assert_eq!(
1766 assert_eq!(
1834 fake.sent.lock().unwrap().as_slice(),
1767 fake.chatsvc_posts.lock().unwrap()[0].1,
1835 ["hi <b>there</b> &lt;x&gt;"]
1768 "hi <b>there</b> &lt;x&gt;"
1836 );
1769 );
1837 assert_eq!(record.message_id, "m9000");
1770 assert_eq!(record.message_id, "1727203440000");
1838 assert_eq!(engine.store().message_count(CHAT).unwrap(), 4);
1771 assert_eq!(engine.store().message_count(CHAT).unwrap(), 4);
1839 assert_eq!(
1772 assert_eq!(
1840 events.try_recv().unwrap(),
1773 events.try_recv().unwrap(),
@@ -2555,7 +2488,9 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {
2555 .send_message_with_extras(NOTES_CHAT_ID, "note to self", None, &[], &extras)
2488 .send_message_with_extras(NOTES_CHAT_ID, "note to self", None, &[], &extras)
2556 .await
2489 .await
2557 .unwrap();
2490 .unwrap();
2558 fake.set_chat_messages(vec![message(9000, 500, "<p>note to self</p>")]);
2491 let mut sent_note = message(9000, 500, "<p>note to self</p>");
2492 sent_note.id = sent.message_id.clone();
2493 fake.set_chat_messages(vec![sent_note]);
2559 engine
2494 engine
2560 .reply_to_with_extras(
2495 .reply_to_with_extras(
2561 NOTES_CHAT_ID,
2496 NOTES_CHAT_ID,
@@ -2588,15 +2523,19 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {
2588 .unwrap();
2523 .unwrap();
2589
2524
2590 assert_eq!(*fake.single_chat_calls.lock().unwrap(), 0);
2525 assert_eq!(*fake.single_chat_calls.lock().unwrap(), 0);
2591 assert_eq!(fake.sent.lock().unwrap().as_slice(), ["note to self"]);
2526 assert!(
2527 fake.chatsvc_posts.lock().unwrap()[0]
2528 .1
2529 .starts_with("note to self")
2530 );
2592 let calls = fake.calls();
2531 let calls = fake.calls();
2593 for expected in [
2532 for expected in [
2594 "chatsvc post 48:notes",
2533 "chatsvc post 48:notes",
2595 "edit m9000 edited",
2534 "edit 1727203440000 edited",
2596 "set_reaction m9000 \u{1f44d}",
2535 "set_reaction 1727203440000 \u{1f44d}",
2597 "unset_reaction m9000 \u{1f44d}",
2536 "unset_reaction 1727203440000 \u{1f44d}",
2598 "upload chat-files plan.txt 4",
2537 "upload chat-files plan.txt 4",
2599 "soft_delete user-me m9000",
2538 "soft_delete user-me 1727203440000",
2600 ] {
2539 ] {
2601 assert!(
2540 assert!(
2602 calls.iter().any(|call| call == expected),
2541 calls.iter().any(|call| call == expected),
@@ -2631,9 +2570,14 @@ async fn send_with_extras_hands_images_and_files_to_the_remote() {
2631 .unwrap();
2570 .unwrap();
2632 engine.send_message(CHAT, "plain", None).await.unwrap();
2571 engine.send_message(CHAT, "plain", None).await.unwrap();
2633
2572
2634 let sent = fake.extras_sent.lock().unwrap();
2573 let calls = fake.calls();
2635 assert_eq!(sent[0], extras);
2574 assert!(
2636 assert!(sent[1].is_empty());
2575 calls.contains(&format!("ams upload {CHAT} image.png 1")),
2576 "{calls:?}"
2577 );
2578 let posts = fake.chatsvc_posts.lock().unwrap();
2579 assert!(posts[0].1.contains("0-ams"));
2580 assert_eq!(posts[1].1, "plain");
2637}
2581}
2638
2582
2639#[tokio::test]
2583#[tokio::test]
@@ -2641,7 +2585,6 @@ async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2641 let directory = tempfile::tempdir().unwrap();
2585 let directory = tempfile::tempdir().unwrap();
2642 let fake = Arc::new(Fake::default());
2586 let fake = Arc::new(Fake::default());
2643 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
2587 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
2644 *fake.send_answer_body.lock().unwrap() = Some(format!("<p>look</p><img src=\"{HOSTED}\">"));
2645 let engine = engine_with(&fake, small_pages())
2588 let engine = engine_with(&fake, small_pages())
2646 .with_image_dir(directory.path(), 1024 * 1024)
2589 .with_image_dir(directory.path(), 1024 * 1024)
2647 .unwrap();
2590 .unwrap();
@@ -2662,12 +2605,11 @@ async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2662 .await
2605 .await
2663 .unwrap();
2606 .unwrap();
2664
2607
2665 assert_eq!(engine.image(HOSTED).unwrap().bytes, vec![9, 8, 7]);
2608 assert_eq!(engine.image(SENT_AMS_IMAGE).unwrap().bytes, vec![9, 8, 7]);
2666 assert!(fake.hosted_requests.lock().unwrap().is_empty());
2609 assert!(fake.hosted_requests.lock().unwrap().is_empty());
2667 let mut seeded = false;
2610 let mut seeded = false;
2668 while let Ok(event) = events.try_recv() {
2611 while let Ok(event) = events.try_recv() {
2669 seeded |=
2612 seeded |= matches!(event, CoreEvent::ImagesChanged { keys } if keys == vec![SENT_AMS_IMAGE.to_owned()]);
2670 matches!(event, CoreEvent::ImagesChanged { keys } if keys == vec![HOSTED.to_owned()]);
2671 }
2613 }
2672 assert!(seeded);
2614 assert!(seeded);
2673}
2615}
@@ -2821,7 +2763,7 @@ async fn send_typing_addresses_chats_channels_and_threads() {
2821}
2763}
2822
2764
2823#[tokio::test]
2765#[tokio::test]
2824async fn chat_actions_call_graph_with_the_right_ids() {
2766async fn chat_actions_call_the_remote_with_the_right_ids() {
2825 let fake = Arc::new(Fake::default());
2767 let fake = Arc::new(Fake::default());
2826 fake.set_chat_messages(numbered(3));
2768 fake.set_chat_messages(numbered(3));
2827 let engine = chat_engine(&fake, small_pages()).await;
2769 let engine = chat_engine(&fake, small_pages()).await;
@@ -2840,7 +2782,7 @@ async fn chat_actions_call_graph_with_the_right_ids() {
2840 .await
2782 .await
2841 .unwrap();
2783 .unwrap();
2842 let calls = fake.calls();
2784 let calls = fake.calls();
2843 assert_eq!(calls[0], format!("mark_read {CHAT} {ME} tenant-1"));
2785 assert!(calls[0].starts_with(&format!("read horizon {CHAT} ")));
2844 assert!(calls.contains(&"set_reaction m0001 like".to_owned()));
2786 assert!(calls.contains(&"set_reaction m0001 like".to_owned()));
2845 assert!(calls.contains(&"unset_reaction m0001 like".to_owned()));
2787 assert!(calls.contains(&"unset_reaction m0001 like".to_owned()));
2846 assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned()));
2788 assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned()));
@@ -4034,6 +3976,8 @@ async fn folders_without_a_source_are_unsupported() {
4034 ));
3976 ));
4035}
3977}
4036
3978
3979const SENT_AMS_IMAGE: &str =
3980 "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-ams/views/imgpsh_fullsize";
4037const HOSTED: &str =
3981const HOSTED: &str =
4038 "https://graph.microsoft.com/v1.0/chats/c/messages/m0001/hostedContents/h1/$value";
3982 "https://graph.microsoft.com/v1.0/chats/c/messages/m0001/hostedContents/h1/$value";
4039
3983
@@ -4274,19 +4218,13 @@ async fn chat_mentions_become_at_tags_and_a_mentions_array() {
4274 )
4218 )
4275 .await
4219 .await
4276 .unwrap();
4220 .unwrap();
4277 assert_eq!(
4221 let posts = fake.chatsvc_posts.lock().unwrap().clone();
4278 fake.sent.lock().unwrap()[0],
4222 assert!(posts[0].1.contains("Ada Example</span>"), "{}", posts[0].1);
4279 "hi <at id=\"0\">Ada Example</at> &amp; co"
4223 assert!(posts[0].1.ends_with(" &amp; co"), "{}", posts[0].1);
4280 );
4224 let mentions: serde_json::Value =
4281 let mentions = fake.mentions_sent.lock().unwrap()[0].clone();
4225 serde_json::from_str(posts[0].3["mentions"].as_str().unwrap()).unwrap();
4282 assert_eq!(mentions.len(), 1);
4226 assert_eq!(mentions.as_array().unwrap().len(), 1);
4283 assert_eq!(mentions[0].id, 0);
4227 assert_eq!(mentions[0]["mri"], "8:orgid:user-ada");
4284 assert_eq!(
4285 mentions[0].target,
4286 MentionTarget::User {
4287 user_id: "user-ada".to_owned()
4288 }
4289 );
4290 assert!(
4228 assert!(
4291 engine
4229 engine
4292 .send_message_with_mentions(CHAT, "@Squad", None, &[MentionInput::team("t", "Squad")])
4230 .send_message_with_mentions(CHAT, "@Squad", None, &[MentionInput::team("t", "Squad")])
@@ -5228,13 +5166,10 @@ async fn mark_unread_from_a_message_backs_up_one_millisecond() {
5228 let engine = chat_engine(&fake, small_pages()).await;
5166 let engine = chat_engine(&fake, small_pages()).await;
5229 let created_at = base() + Duration::minutes(2);
5167 let created_at = base() + Duration::minutes(2);
5230 engine.mark_unread_from(CHAT, created_at).await.unwrap();
5168 engine.mark_unread_from(CHAT, created_at).await.unwrap();
5231 assert_eq!(
5169 assert!(fake.calls().last().unwrap().starts_with(&format!(
5232 fake.calls().last().unwrap(),
5170 "read bookmark {CHAT} {};",
5233 &format!(
5171 created_at.timestamp_millis() - 1
5234 "mark_unread {CHAT} {ME} tenant-1 {}",
5172 )));
5235 created_at.timestamp_millis() - 1
5236 )
5237 );
5238}
5173}
5239
5174
5240#[tokio::test]
5175#[tokio::test]
@@ -5965,7 +5900,9 @@ async fn marking_the_notes_chat_read_takes_the_tenant_from_another_chat() {
5965
5900
5966 let calls = fake.calls();
5901 let calls = fake.calls();
5967 assert!(
5902 assert!(
5968 calls.contains(&format!("mark_read {NOTES_CHAT_ID} {ME} tenant-1")),
5903 calls
5904 .iter()
5905 .any(|call| call.starts_with(&format!("read horizon {NOTES_CHAT_ID} "))),
5969 "{calls:?}"
5906 "{calls:?}"
5970 );
5907 );
5971 let member_requests = fake.member_requests.lock().unwrap();
5908 let member_requests = fake.member_requests.lock().unwrap();
@@ -6043,7 +5980,7 @@ async fn a_quoted_chat_reply_is_written_through_chatsvc_in_the_teams_shape() {
6043}
5980}
6044
5981
6045#[tokio::test]
5982#[tokio::test]
6046async fn a_quoted_chat_reply_with_an_image_stays_on_graph() {
5983async fn a_quoted_chat_reply_with_an_image_goes_through_chatsvc() {
6047 let fake = Arc::new(Fake::default());
5984 let fake = Arc::new(Fake::default());
6048 fake.set_chat_messages(numbered(2));
5985 fake.set_chat_messages(numbered(2));
6049 let engine = chat_engine(&fake, small_pages()).await;
5986 let engine = chat_engine(&fake, small_pages()).await;
@@ -6059,25 +5996,19 @@ async fn a_quoted_chat_reply_with_an_image_stays_on_graph() {
6059 .reply_to_with_extras(CHAT, "m0001", "look", &[], &extras)
5996 .reply_to_with_extras(CHAT, "m0001", "look", &[], &extras)
6060 .await
5997 .await
6061 .unwrap();
5998 .unwrap();
6062 assert!(fake.chatsvc_posts.lock().unwrap().is_empty());
5999 let posts = fake.chatsvc_posts.lock().unwrap();
6063 assert!(
6000 assert!(posts[0].1.starts_with("<blockquote"), "{}", posts[0].1);
6064 fake.calls()
6001 assert!(posts[0].1.contains("0-ams"));
6065 .contains(&format!("quote_reply {CHAT} m0001 look"))
6066 );
6067}
6002}
6068
6003
6069#[tokio::test]
6004#[tokio::test]
6070async fn a_quoted_reply_to_an_unknown_message_stays_on_graph() {
6005async fn a_reply_to_an_unknown_message_is_sent_without_a_quote() {
6071 let fake = Arc::new(Fake::default());
6006 let fake = Arc::new(Fake::default());
6072 fake.set_chat_messages(numbered(2));
6007 fake.set_chat_messages(numbered(2));
6073 let engine = chat_engine(&fake, small_pages()).await;
6008 let engine = chat_engine(&fake, small_pages()).await;
6074 engine.fetch_newer(CHAT).await.unwrap();
6009 engine.fetch_newer(CHAT).await.unwrap();
6075 engine.reply_to(CHAT, "m7777", "hi").await.unwrap();
6010 engine.reply_to(CHAT, "m7777", "hi").await.unwrap();
6076 assert!(fake.chatsvc_posts.lock().unwrap().is_empty());
6011 assert_eq!(fake.chatsvc_posts.lock().unwrap()[0].1, "hi");
6077 assert!(
6078 fake.calls()
6079 .contains(&format!("quote_reply {CHAT} m7777 hi"))
6080 );
6081}
6012}
6082
6013
6083#[tokio::test]
6014#[tokio::test]
crates/graph/examples/live_data.rs deleted +0 −85
@@ -1,85 +0,0 @@
1 use std::collections::BTreeMap;
2 use std::time::Instant;
3
4 use graph::Graph;
5 use session::{DEFAULT_ENDPOINT, Session};
6
7 #[tokio::main]
8 async fn main() {
9 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
10 let graph = Graph::new(Session::connect(&endpoint).await.expect("browser"));
11 let me = graph.me().await.expect("me").id;
12 let chats = graph.chats_page(50).await.expect("chats").items;
13 let with_preview = chats
14 .iter()
15 .filter(|chat| chat.last_message_preview.is_some())
16 .count();
17 let with_body = chats
18 .iter()
19 .filter_map(|chat| {
20 chat.last_message_preview
21 .as_ref()?
22 .body
23 .as_ref()?
24 .content
25 .as_ref()
26 })
27 .filter(|content| !content.trim().is_empty())
28 .count();
29 println!(
30 "chats {} with_preview {with_preview} with_body {with_body}",
31 chats.len()
32 );
33 let mut user_ids: Vec<String> = chats
34 .iter()
35 .flat_map(|chat| chat.members.iter())
36 .filter_map(|member| member.user_id.clone())
37 .filter(|id| *id != me)
38 .collect();
39 user_ids.sort();
40 user_ids.dedup();
41 user_ids.truncate(40);
42 println!("distinct users {}", user_ids.len());
43
44 let started = Instant::now();
45 match graph.user_photos(&user_ids).await {
46 Ok(results) => {
47 let mut kinds: BTreeMap<String, usize> = BTreeMap::new();
48 let (mut hits, mut misses, mut errors, mut total_bytes) = (0, 0, 0, 0usize);
49 for result in &results {
50 match result {
51 Ok(Some(photo)) => {
52 hits += 1;
53 total_bytes += photo.bytes.len();
54 *kinds.entry(photo.content_type.clone()).or_default() += 1;
55 }
56 Ok(None) => misses += 1,
57 Err(error) => {
58 errors += 1;
59 if errors == 1 {
60 println!("first photo error status: {}", status_of(error));
61 }
62 }
63 }
64 }
65 println!(
66 "photos hits {hits} misses {misses} errors {errors} bytes {total_bytes} types {kinds:?} in {} ms",
67 started.elapsed().as_millis()
68 );
69 }
70 Err(error) => println!("photos failed: {}", status_of(&error)),
71 }
72 }
73
74 fn status_of(error: &graph::Error) -> String {
75 match error {
76 graph::Error::Session(session::Error::Api { status, .. }) => format!("HTTP {status}"),
77 graph::Error::Session(session::Error::NoFreshToken { .. }) => {
78 "no fresh token (scope not granted)".into()
79 }
80 graph::Error::Session(session::Error::LoginRequired(_)) => {
81 "login required (scope not granted)".into()
82 }
83 _ => "other error".into(),
84 }
85 }
@@ -1,85 +0,0 @@
1use std::collections::BTreeMap;
2use std::time::Instant;
3
4use graph::Graph;
5use session::{DEFAULT_ENDPOINT, Session};
6
7#[tokio::main]
8async fn main() {
9 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
10 let graph = Graph::new(Session::connect(&endpoint).await.expect("browser"));
11 let me = graph.me().await.expect("me").id;
12 let chats = graph.chats_page(50).await.expect("chats").items;
13 let with_preview = chats
14 .iter()
15 .filter(|chat| chat.last_message_preview.is_some())
16 .count();
17 let with_body = chats
18 .iter()
19 .filter_map(|chat| {
20 chat.last_message_preview
21 .as_ref()?
22 .body
23 .as_ref()?
24 .content
25 .as_ref()
26 })
27 .filter(|content| !content.trim().is_empty())
28 .count();
29 println!(
30 "chats {} with_preview {with_preview} with_body {with_body}",
31 chats.len()
32 );
33 let mut user_ids: Vec<String> = chats
34 .iter()
35 .flat_map(|chat| chat.members.iter())
36 .filter_map(|member| member.user_id.clone())
37 .filter(|id| *id != me)
38 .collect();
39 user_ids.sort();
40 user_ids.dedup();
41 user_ids.truncate(40);
42 println!("distinct users {}", user_ids.len());
43
44 let started = Instant::now();
45 match graph.user_photos(&user_ids).await {
46 Ok(results) => {
47 let mut kinds: BTreeMap<String, usize> = BTreeMap::new();
48 let (mut hits, mut misses, mut errors, mut total_bytes) = (0, 0, 0, 0usize);
49 for result in &results {
50 match result {
51 Ok(Some(photo)) => {
52 hits += 1;
53 total_bytes += photo.bytes.len();
54 *kinds.entry(photo.content_type.clone()).or_default() += 1;
55 }
56 Ok(None) => misses += 1,
57 Err(error) => {
58 errors += 1;
59 if errors == 1 {
60 println!("first photo error status: {}", status_of(error));
61 }
62 }
63 }
64 }
65 println!(
66 "photos hits {hits} misses {misses} errors {errors} bytes {total_bytes} types {kinds:?} in {} ms",
67 started.elapsed().as_millis()
68 );
69 }
70 Err(error) => println!("photos failed: {}", status_of(&error)),
71 }
72}
73
74fn status_of(error: &graph::Error) -> String {
75 match error {
76 graph::Error::Session(session::Error::Api { status, .. }) => format!("HTTP {status}"),
77 graph::Error::Session(session::Error::NoFreshToken { .. }) => {
78 "no fresh token (scope not granted)".into()
79 }
80 graph::Error::Session(session::Error::LoginRequired(_)) => {
81 "login required (scope not granted)".into()
82 }
83 _ => "other error".into(),
84 }
85}
crates/graph/src/client.rs +1 −80
@@ -4,7 +4,7 @@ use serde_json::Value;
4 4 use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
5 5
6 6 use crate::error::{Error, Result};
7 use crate::models::{Channel, Chat, Member, Message, Tag, Team, User};
7 use crate::models::{Channel, Message, Tag, Team, User};
8 8 use crate::page::Page;
9 9 use crate::urls;
10 10
@@ -33,85 +33,6 @@ impl Graph {
33 33 Ok(serde_json::from_value(body)?)
34 34 }
35 35
36 pub async fn chats_page(&self, top: usize) -> Result<Page<Chat>> {
37 self.get_page(&urls::chats(top), Scope::graph("Chat.Read"))
38 .await
39 }
40
41 pub async fn chats_at(&self, next_link: &str) -> Result<Page<Chat>> {
42 self.get_page(next_link, Scope::graph("Chat.Read")).await
43 }
44
45 pub async fn chat(&self, chat_id: &str) -> Result<Chat> {
46 let body = self
47 .get(&urls::chat(chat_id), &Scope::graph("Chat.Read"))
48 .await?;
49 Ok(serde_json::from_value(body)?)
50 }
51
52 pub async fn chat_members(&self, chat_id: &str) -> Result<Vec<Member>> {
53 self.get_all(&urls::chat_members(chat_id), Scope::graph("Chat.Read"))
54 .await
55 }
56
57 pub async fn chat_message(&self, chat_id: &str, message_id: &str) -> Result<Message> {
58 let body = self
59 .get(
60 &urls::chat_message(chat_id, message_id),
61 &Scope::graph("Chat.Read"),
62 )
63 .await?;
64 Ok(serde_json::from_value(body)?)
65 }
66
67 pub async fn chat_messages_by_id(
68 &self,
69 chat_id: &str,
70 message_ids: &[String],
71 ) -> Result<Vec<Result<Message>>> {
72 let scope = Scope::graph("Chat.Read");
73 let mut messages = Vec::with_capacity(message_ids.len());
74 for chunk in message_ids.chunks(BATCH_SIZE) {
75 let requests: Vec<Request> = chunk
76 .iter()
77 .map(|message_id| Request::get(urls::chat_message(chat_id, message_id)))
78 .collect();
79 let answers = self.session.batch(&requests, &scope).await?;
80 for (request, answer) in requests.iter().zip(answers) {
81 messages.push(if answer.is_success() {
82 serde_json::from_value(answer.body).map_err(Into::into)
83 } else {
84 Err(session::Error::api(answer.status, &request.url, answer.body).into())
85 });
86 }
87 }
88 Ok(messages)
89 }
90
91 pub async fn list_chats(&self, limit: usize) -> Result<Vec<Chat>> {
92 let mut page = self.chats_page(limit.clamp(1, CHAT_PAGE_SIZE)).await?;
93 let mut chats = std::mem::take(&mut page.items);
94 while chats.len() < limit {
95 let Some(mut next) = self.next_page(&page).await? else {
96 break;
97 };
98 chats.append(&mut std::mem::take(&mut next.items));
99 page = next;
100 }
101 chats.truncate(limit);
102 Ok(chats)
103 }
104
105 pub async fn chat_messages(
106 &self,
107 chat_id: &str,
108 before: Option<DateTime<Utc>>,
109 top: usize,
110 ) -> Result<Page<Message>> {
111 let url = urls::chat_messages(chat_id, before, top.clamp(1, MESSAGE_PAGE_SIZE));
112 self.get_page(&url, Scope::graph("Chat.Read")).await
113 }
114
115 36 pub async fn joined_teams(&self) -> Result<Vec<Team>> {
116 37 self.get_all(&urls::joined_teams(), Scope::graph("Team.ReadBasic.All"))
117 38 .await
@@ -4,7 +4,7 @@ use serde_json::Value;
4use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
4use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
5
5
6use crate::error::{Error, Result};
6use crate::error::{Error, Result};
7use crate::models::{Channel, Chat, Member, Message, Tag, Team, User};
7use crate::models::{Channel, Message, Tag, Team, User};
8use crate::page::Page;
8use crate::page::Page;
9use crate::urls;
9use crate::urls;
10
10
@@ -33,85 +33,6 @@ impl Graph {
33 Ok(serde_json::from_value(body)?)
33 Ok(serde_json::from_value(body)?)
34 }
34 }
35
35
36 pub async fn chats_page(&self, top: usize) -> Result<Page<Chat>> {
37 self.get_page(&urls::chats(top), Scope::graph("Chat.Read"))
38 .await
39 }
40
41 pub async fn chats_at(&self, next_link: &str) -> Result<Page<Chat>> {
42 self.get_page(next_link, Scope::graph("Chat.Read")).await
43 }
44
45 pub async fn chat(&self, chat_id: &str) -> Result<Chat> {
46 let body = self
47 .get(&urls::chat(chat_id), &Scope::graph("Chat.Read"))
48 .await?;
49 Ok(serde_json::from_value(body)?)
50 }
51
52 pub async fn chat_members(&self, chat_id: &str) -> Result<Vec<Member>> {
53 self.get_all(&urls::chat_members(chat_id), Scope::graph("Chat.Read"))
54 .await
55 }
56
57 pub async fn chat_message(&self, chat_id: &str, message_id: &str) -> Result<Message> {
58 let body = self
59 .get(
60 &urls::chat_message(chat_id, message_id),
61 &Scope::graph("Chat.Read"),
62 )
63 .await?;
64 Ok(serde_json::from_value(body)?)
65 }
66
67 pub async fn chat_messages_by_id(
68 &self,
69 chat_id: &str,
70 message_ids: &[String],
71 ) -> Result<Vec<Result<Message>>> {
72 let scope = Scope::graph("Chat.Read");
73 let mut messages = Vec::with_capacity(message_ids.len());
74 for chunk in message_ids.chunks(BATCH_SIZE) {
75 let requests: Vec<Request> = chunk
76 .iter()
77 .map(|message_id| Request::get(urls::chat_message(chat_id, message_id)))
78 .collect();
79 let answers = self.session.batch(&requests, &scope).await?;
80 for (request, answer) in requests.iter().zip(answers) {
81 messages.push(if answer.is_success() {
82 serde_json::from_value(answer.body).map_err(Into::into)
83 } else {
84 Err(session::Error::api(answer.status, &request.url, answer.body).into())
85 });
86 }
87 }
88 Ok(messages)
89 }
90
91 pub async fn list_chats(&self, limit: usize) -> Result<Vec<Chat>> {
92 let mut page = self.chats_page(limit.clamp(1, CHAT_PAGE_SIZE)).await?;
93 let mut chats = std::mem::take(&mut page.items);
94 while chats.len() < limit {
95 let Some(mut next) = self.next_page(&page).await? else {
96 break;
97 };
98 chats.append(&mut std::mem::take(&mut next.items));
99 page = next;
100 }
101 chats.truncate(limit);
102 Ok(chats)
103 }
104
105 pub async fn chat_messages(
106 &self,
107 chat_id: &str,
108 before: Option<DateTime<Utc>>,
109 top: usize,
110 ) -> Result<Page<Message>> {
111 let url = urls::chat_messages(chat_id, before, top.clamp(1, MESSAGE_PAGE_SIZE));
112 self.get_page(&url, Scope::graph("Chat.Read")).await
113 }
114
115 pub async fn joined_teams(&self) -> Result<Vec<Team>> {
36 pub async fn joined_teams(&self) -> Result<Vec<Team>> {
116 self.get_all(&urls::joined_teams(), Scope::graph("Team.ReadBasic.All"))
37 self.get_all(&urls::joined_teams(), Scope::graph("Team.ReadBasic.All"))
117 .await
38 .await
crates/graph/src/content.rs +3 −6
@@ -5,11 +5,10 @@ use crate::error::{Error, Result};
5 5 use crate::models::Photo;
6 6 use crate::people::decode_binary;
7 7
8 const CHAT_PATH: &str = "/v1.0/chats/";
9 8 const CHANNEL_PATH: &str = "/v1.0/teams/";
10 9 const SHARES_PATH: &str = "/v1.0/shares/";
11 10 const SHARES_SCOPE: &str = "Files.ReadWrite.All";
12 const EXTERNAL_IMAGE_SCOPE: &str = "Chat.Read";
11 const EXTERNAL_IMAGE_SCOPE: &str = "User.ReadBasic.All";
13 12
14 13 impl Graph {
15 14 /// Binary GET of a Graph hosted content URL (`.../hostedContents/{id}/$value`).
@@ -38,9 +37,7 @@ impl Graph {
38 37
39 38 pub fn hosted_content_scope(url: &str) -> Option<Scope> {
40 39 let path = url.strip_prefix(GRAPH)?;
41 if path.starts_with(CHAT_PATH) {
42 Some(Scope::graph("Chat.Read"))
43 } else if path.starts_with(CHANNEL_PATH) {
40 if path.starts_with(CHANNEL_PATH) {
44 41 Some(Scope::graph("ChannelMessage.Read.All"))
45 42 } else if path.starts_with(SHARES_PATH) {
46 43 Some(Scope::graph(SHARES_SCOPE))
@@ -58,7 +55,7 @@ mod tests {
58 55 let chat =
59 56 "https://graph.microsoft.com/v1.0/chats/19%3Aa/messages/1/hostedContents/2/$value";
60 57 let channel = "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/2/$value";
61 assert_eq!(hosted_content_scope(chat).unwrap().name, "Chat.Read");
58 assert!(hosted_content_scope(chat).is_none());
62 59 assert_eq!(
63 60 hosted_content_scope(channel).unwrap().name,
64 61 "ChannelMessage.Read.All"
@@ -5,11 +5,10 @@ use crate::error::{Error, Result};
5use crate::models::Photo;
5use crate::models::Photo;
6use crate::people::decode_binary;
6use crate::people::decode_binary;
7
7
8const CHAT_PATH: &str = "/v1.0/chats/";
9const CHANNEL_PATH: &str = "/v1.0/teams/";
8const CHANNEL_PATH: &str = "/v1.0/teams/";
10const SHARES_PATH: &str = "/v1.0/shares/";
9const SHARES_PATH: &str = "/v1.0/shares/";
11const SHARES_SCOPE: &str = "Files.ReadWrite.All";
10const SHARES_SCOPE: &str = "Files.ReadWrite.All";
12const EXTERNAL_IMAGE_SCOPE: &str = "Chat.Read";
11const EXTERNAL_IMAGE_SCOPE: &str = "User.ReadBasic.All";
13
12
14impl Graph {
13impl Graph {
15 /// Binary GET of a Graph hosted content URL (`.../hostedContents/{id}/$value`).
14 /// Binary GET of a Graph hosted content URL (`.../hostedContents/{id}/$value`).
@@ -38,9 +37,7 @@ impl Graph {
38
37
39pub fn hosted_content_scope(url: &str) -> Option<Scope> {
38pub fn hosted_content_scope(url: &str) -> Option<Scope> {
40 let path = url.strip_prefix(GRAPH)?;
39 let path = url.strip_prefix(GRAPH)?;
41 if path.starts_with(CHAT_PATH) {
40 if path.starts_with(CHANNEL_PATH) {
42 Some(Scope::graph("Chat.Read"))
43 } else if path.starts_with(CHANNEL_PATH) {
44 Some(Scope::graph("ChannelMessage.Read.All"))
41 Some(Scope::graph("ChannelMessage.Read.All"))
45 } else if path.starts_with(SHARES_PATH) {
42 } else if path.starts_with(SHARES_PATH) {
46 Some(Scope::graph(SHARES_SCOPE))
43 Some(Scope::graph(SHARES_SCOPE))
@@ -58,7 +55,7 @@ mod tests {
58 let chat =
55 let chat =
59 "https://graph.microsoft.com/v1.0/chats/19%3Aa/messages/1/hostedContents/2/$value";
56 "https://graph.microsoft.com/v1.0/chats/19%3Aa/messages/1/hostedContents/2/$value";
60 let channel = "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/2/$value";
57 let channel = "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/2/$value";
61 assert_eq!(hosted_content_scope(chat).unwrap().name, "Chat.Read");
58 assert!(hosted_content_scope(chat).is_none());
62 assert_eq!(
59 assert_eq!(
63 hosted_content_scope(channel).unwrap().name,
60 hosted_content_scope(channel).unwrap().name,
64 "ChannelMessage.Read.All"
61 "ChannelMessage.Read.All"
crates/graph/src/urls.rs +0 −136
@@ -66,24 +66,6 @@ pub fn get_schedule() -> String {
66 66 format!("{GRAPH}/v1.0/me/calendar/getSchedule")
67 67 }
68 68
69 pub fn chats(top: usize) -> String {
70 format!(
71 "{GRAPH}/v1.0/me/chats?$expand=members,lastMessagePreview\
72 &$orderby=lastMessagePreview/createdDateTime%20desc&$top={top}"
73 )
74 }
75
76 pub fn chat(chat_id: &str) -> String {
77 format!(
78 "{GRAPH}/v1.0/chats/{}?$expand=members,lastMessagePreview",
79 segment(chat_id)
80 )
81 }
82
83 pub fn chat_members(chat_id: &str) -> String {
84 format!("{GRAPH}/v1.0/chats/{}/members", segment(chat_id))
85 }
86
87 69 pub fn chat_message(chat_id: &str, message_id: &str) -> String {
88 70 format!(
89 71 "{GRAPH}/v1.0/chats/{}/messages/{}",
@@ -114,36 +96,6 @@ fn user_chat_message_action(
114 96 )
115 97 }
116 98
117 pub fn create_chat() -> String {
118 format!("{GRAPH}/v1.0/chats")
119 }
120
121 pub fn chat_messages(chat_id: &str, before: Option<DateTime<Utc>>, top: usize) -> String {
122 let mut url = format!(
123 "{GRAPH}/v1.0/chats/{}/messages?$top={top}&$orderby=createdDateTime%20desc",
124 segment(chat_id)
125 );
126 if let Some(before) = before {
127 let stamp = before.to_rfc3339_opts(SecondsFormat::Millis, true);
128 url.push_str(&format!(
129 "&$filter=createdDateTime%20lt%20{}",
130 segment(&stamp)
131 ));
132 }
133 url
134 }
135
136 pub fn chat_message_collection(chat_id: &str) -> String {
137 format!("{GRAPH}/v1.0/chats/{}/messages", segment(chat_id))
138 }
139
140 pub fn reply_with_quote(chat_id: &str) -> String {
141 format!(
142 "{GRAPH}/beta/chats/{}/messages/replyWithQuote",
143 segment(chat_id)
144 )
145 }
146
147 99 pub const CHAT_FILES_FOLDER: &str = "Microsoft Teams Chat Files";
148 100
149 101 pub fn chat_files_upload_session(file_name: &str) -> String {
@@ -274,36 +226,6 @@ pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
274 226 )
275 227 }
276 228
277 pub fn mark_chat_read(chat_id: &str) -> String {
278 format!(
279 "{GRAPH}/v1.0/chats/{}/markChatReadForUser",
280 segment(chat_id)
281 )
282 }
283
284 pub fn mark_chat_unread(chat_id: &str) -> String {
285 format!(
286 "{GRAPH}/v1.0/chats/{}/markChatUnreadForUser",
287 segment(chat_id)
288 )
289 }
290
291 pub fn hide_chat(chat_id: &str) -> String {
292 format!("{GRAPH}/v1.0/chats/{}/hideForUser", segment(chat_id))
293 }
294
295 pub fn unhide_chat(chat_id: &str) -> String {
296 format!("{GRAPH}/v1.0/chats/{}/unhideForUser", segment(chat_id))
297 }
298
299 pub fn chat_member(chat_id: &str, membership_id: &str) -> String {
300 format!(
301 "{GRAPH}/v1.0/chats/{}/members/{}",
302 segment(chat_id),
303 segment(membership_id)
304 )
305 }
306
307 229 pub fn joined_teams() -> String {
308 230 format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")
309 231 }
@@ -421,8 +343,6 @@ pub fn user_by_address(address: &str) -> String {
421 343
422 344 #[cfg(test)]
423 345 mod tests {
424 use chrono::TimeZone;
425
426 346 use super::*;
427 347
428 348 #[test]
@@ -452,14 +372,6 @@ mod tests {
452 372 assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");
453 373 }
454 374
455 #[test]
456 fn reply_with_quote_uses_the_beta_endpoint() {
457 assert_eq!(
458 reply_with_quote("19:abc@thread.v2"),
459 "https://graph.microsoft.com/beta/chats/19%3Aabc%40thread.v2/messages/replyWithQuote"
460 );
461 }
462
463 375 #[test]
464 376 fn upload_session_urls_encode_the_file_name() {
465 377 assert_eq!(
@@ -472,54 +384,6 @@ mod tests {
472 384 );
473 385 }
474 386
475 #[test]
476 fn chat_state_write_urls() {
477 assert_eq!(
478 mark_chat_unread("19:abc@thread.v2"),
479 "https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/markChatUnreadForUser"
480 );
481 assert_eq!(
482 hide_chat("19:abc@thread.v2"),
483 "https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/hideForUser"
484 );
485 assert_eq!(
486 unhide_chat("19:abc@thread.v2"),
487 "https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/unhideForUser"
488 );
489 assert_eq!(
490 chat_member("19:abc@thread.v2", "MTox"),
491 "https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/members/MTox"
492 );
493 }
494
495 #[test]
496 fn chats_url_orders_newest_first() {
497 let url = chats(50);
498 assert!(url.starts_with("https://graph.microsoft.com/v1.0/me/chats?"));
499 assert!(url.contains("$expand=members,lastMessagePreview"));
500 assert!(url.contains("$orderby=lastMessagePreview/createdDateTime%20desc"));
501 assert!(url.ends_with("$top=50"));
502 }
503
504 #[test]
505 fn messages_url_without_cursor() {
506 let url = chat_messages("19:abc@thread.v2", None, 30);
507 assert_eq!(
508 url,
509 "https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/messages?$top=30&$orderby=createdDateTime%20desc"
510 );
511 }
512
513 #[test]
514 fn messages_url_with_cursor_filters_older() {
515 let before = Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, 0).unwrap();
516 let url = chat_messages("c", Some(before), 50);
517 assert!(
518 url.ends_with("&$filter=createdDateTime%20lt%202026-10-06T09%3A00%3A00.000Z"),
519 "{url}"
520 );
521 }
522
523 387 #[test]
524 388 fn channel_messages_expand_replies() {
525 389 let url = channel_messages("team-1", "19:chan@thread.tacv2", 20);
@@ -66,24 +66,6 @@ pub fn get_schedule() -> String {
66 format!("{GRAPH}/v1.0/me/calendar/getSchedule")
66 format!("{GRAPH}/v1.0/me/calendar/getSchedule")
67}
67}
68
68
69pub fn chats(top: usize) -> String {
70 format!(
71 "{GRAPH}/v1.0/me/chats?$expand=members,lastMessagePreview\
72 &$orderby=lastMessagePreview/createdDateTime%20desc&$top={top}"
73 )
74}
75
76pub fn chat(chat_id: &str) -> String {
77 format!(
78 "{GRAPH}/v1.0/chats/{}?$expand=members,lastMessagePreview",
79 segment(chat_id)
80 )
81}
82
83pub fn chat_members(chat_id: &str) -> String {
84 format!("{GRAPH}/v1.0/chats/{}/members", segment(chat_id))
85}
86
87pub fn chat_message(chat_id: &str, message_id: &str) -> String {
69pub fn chat_message(chat_id: &str, message_id: &str) -> String {
88 format!(
70 format!(
89 "{GRAPH}/v1.0/chats/{}/messages/{}",
71 "{GRAPH}/v1.0/chats/{}/messages/{}",
@@ -114,36 +96,6 @@ fn user_chat_message_action(
114 )
96 )
115}
97}
116
98
117pub fn create_chat() -> String {
118 format!("{GRAPH}/v1.0/chats")
119}
120
121pub fn chat_messages(chat_id: &str, before: Option<DateTime<Utc>>, top: usize) -> String {
122 let mut url = format!(
123 "{GRAPH}/v1.0/chats/{}/messages?$top={top}&$orderby=createdDateTime%20desc",
124 segment(chat_id)
125 );
126 if let Some(before) = before {
127 let stamp = before.to_rfc3339_opts(SecondsFormat::Millis, true);
128 url.push_str(&format!(
129 "&$filter=createdDateTime%20lt%20{}",
130 segment(&stamp)
131 ));
132 }
133 url
134}
135
136pub fn chat_message_collection(chat_id: &str) -> String {
137 format!("{GRAPH}/v1.0/chats/{}/messages", segment(chat_id))
138}
139
140pub fn reply_with_quote(chat_id: &str) -> String {
141 format!(
142 "{GRAPH}/beta/chats/{}/messages/replyWithQuote",
143 segment(chat_id)
144 )
145}
146
147pub const CHAT_FILES_FOLDER: &str = "Microsoft Teams Chat Files";
99pub const CHAT_FILES_FOLDER: &str = "Microsoft Teams Chat Files";
148
100
149pub fn chat_files_upload_session(file_name: &str) -> String {
101pub fn chat_files_upload_session(file_name: &str) -> String {
@@ -274,36 +226,6 @@ pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
274 )
226 )
275}
227}
276
228
277pub fn mark_chat_read(chat_id: &str) -> String {
278 format!(
279 "{GRAPH}/v1.0/chats/{}/markChatReadForUser",
280 segment(chat_id)
281 )
282}
283
284pub fn mark_chat_unread(chat_id: &str) -> String {
285 format!(
286 "{GRAPH}/v1.0/chats/{}/markChatUnreadForUser",
287 segment(chat_id)
288 )
289}
290
291pub fn hide_chat(chat_id: &str) -> String {
292 format!("{GRAPH}/v1.0/chats/{}/hideForUser", segment(chat_id))
293}
294
295pub fn unhide_chat(chat_id: &str) -> String {
296 format!("{GRAPH}/v1.0/chats/{}/unhideForUser", segment(chat_id))
297}
298
299pub fn chat_member(chat_id: &str, membership_id: &str) -> String {
300 format!(
301 "{GRAPH}/v1.0/chats/{}/members/{}",
302 segment(chat_id),
303 segment(membership_id)
304 )
305}
306
307pub fn joined_teams() -> String {
229pub fn joined_teams() -> String {
308 format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")
230 format!("{GRAPH}/v1.0/me/joinedTeams?$select=id,displayName")
309}
231}
@@ -421,8 +343,6 @@ pub fn user_by_address(address: &str) -> String {
421
343
422#[cfg(test)]
344#[cfg(test)]
423mod tests {
345mod tests {
424 use chrono::TimeZone;
425
426 use super::*;
346 use super::*;
427
347
428 #[test]
348 #[test]
@@ -452,14 +372,6 @@ mod tests {
452 assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");
372 assert_eq!(segment("19:abc@thread.v2"), "19%3Aabc%40thread.v2");
453 }
373 }
454
374
455 #[test]
456 fn reply_with_quote_uses_the_beta_endpoint() {
457 assert_eq!(
458 reply_with_quote("19:abc@thread.v2"),
459 "https://graph.microsoft.com/beta/chats/19%3Aabc%40thread.v2/messages/replyWithQuote"
460 );
461 }
462
463 #[test]
375 #[test]
464 fn upload_session_urls_encode_the_file_name() {
376 fn upload_session_urls_encode_the_file_name() {
465 assert_eq!(
377 assert_eq!(
@@ -472,54 +384,6 @@ mod tests {
472 );
384 );
473 }
385 }
474
386
475 #[test]
476 fn chat_state_write_urls() {
477 assert_eq!(
478 mark_chat_unread("19:abc@thread.v2"),
479 "https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/markChatUnreadForUser"
480 );
481 assert_eq!(
482 hide_chat("19:abc@thread.v2"),
483 "https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/hideForUser"
484 );
485 assert_eq!(
486 unhide_chat("19:abc@thread.v2"),
487 "https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/unhideForUser"
488 );
489 assert_eq!(
490 chat_member("19:abc@thread.v2", "MTox"),
491 "https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/members/MTox"
492 );
493 }
494
495 #[test]
496 fn chats_url_orders_newest_first() {
497 let url = chats(50);
498 assert!(url.starts_with("https://graph.microsoft.com/v1.0/me/chats?"));
499 assert!(url.contains("$expand=members,lastMessagePreview"));
500 assert!(url.contains("$orderby=lastMessagePreview/createdDateTime%20desc"));
501 assert!(url.ends_with("$top=50"));
502 }
503
504 #[test]
505 fn messages_url_without_cursor() {
506 let url = chat_messages("19:abc@thread.v2", None, 30);
507 assert_eq!(
508 url,
509 "https://graph.microsoft.com/v1.0/chats/19%3Aabc%40thread.v2/messages?$top=30&$orderby=createdDateTime%20desc"
510 );
511 }
512
513 #[test]
514 fn messages_url_with_cursor_filters_older() {
515 let before = Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, 0).unwrap();
516 let url = chat_messages("c", Some(before), 50);
517 assert!(
518 url.ends_with("&$filter=createdDateTime%20lt%202026-10-06T09%3A00%3A00.000Z"),
519 "{url}"
520 );
521 }
522
523 #[test]
387 #[test]
524 fn channel_messages_expand_replies() {
388 fn channel_messages_expand_replies() {
525 let url = channel_messages("team-1", "19:chan@thread.tacv2", 20);
389 let url = channel_messages("team-1", "19:chan@thread.tacv2", 20);
crates/graph/src/writes.rs +3 −204
@@ -1,57 +1,14 @@
1 use chrono::{DateTime, SecondsFormat, Utc};
2 1 use serde_json::{Value, json};
3 use session::{GRAPH, Method, Scope};
2 use session::{Method, Scope};
4 3
5 4 use crate::client::Graph;
6 use crate::error::{Error, Result};
7 use crate::models::{Chat, Member, Message};
5 use crate::error::Result;
6 use crate::models::Message;
8 7 use crate::outgoing::{MessageExtras, OutgoingMention, message_body};
9 8 use crate::target::MessageTarget;
10 9 use crate::urls;
11 10
12 fn conversation_member(user_id: &str) -> Value {
13 json!({
14 "@odata.type": "#microsoft.graph.aadUserConversationMember",
15 "roles": ["owner"],
16 "user@odata.bind": format!("{GRAPH}/v1.0/users('{user_id}')"),
17 })
18 }
19
20 fn user_body(user_id: &str, tenant_id: &str) -> Value {
21 json!({"user": {"id": user_id, "tenantId": tenant_id}})
22 }
23
24 fn mark_unread_body(user_id: &str, tenant_id: &str, last_read_at: DateTime<Utc>) -> Value {
25 json!({
26 "user": {"id": user_id, "tenantId": tenant_id},
27 "lastMessageReadDateTime": last_read_at.to_rfc3339_opts(SecondsFormat::Millis, true),
28 })
29 }
30
31 fn membership_id<'a>(members: &'a [Member], user_id: &str) -> Option<&'a str> {
32 members
33 .iter()
34 .find(|member| member.user_id.as_deref() == Some(user_id))
35 .and_then(|member| member.id.as_deref())
36 }
37
38 11 impl Graph {
39 pub async fn send_chat_message(
40 &self,
41 chat_id: &str,
42 html: &str,
43 mentions: &[OutgoingMention],
44 extras: &MessageExtras,
45 ) -> Result<Message> {
46 self.write_for_message(
47 Method::Post,
48 &urls::chat_message_collection(chat_id),
49 "Chat.ReadWrite",
50 Some(message_body(html, mentions, extras)),
51 )
52 .await
53 }
54
55 12 pub async fn send_channel_message(
56 13 &self,
57 14 team_id: &str,
@@ -92,92 +49,6 @@ impl Graph {
92 49 .await
93 50 }
94 51
95 /// Beta API `chats/{id}/messages/replyWithQuote`; Teams renders the quote from the `messageReference` attachment.
96 pub async fn reply_with_quote(
97 &self,
98 chat_id: &str,
99 quoted_message_id: &str,
100 html: &str,
101 mentions: &[OutgoingMention],
102 extras: &MessageExtras,
103 ) -> Result<Message> {
104 let body = json!({
105 "messageIds": [quoted_message_id],
106 "replyMessage": message_body(html, mentions, extras),
107 });
108 self.write_for_message(
109 Method::Post,
110 &urls::reply_with_quote(chat_id),
111 "Chat.ReadWrite",
112 Some(body),
113 )
114 .await
115 }
116
117 pub async fn mark_chat_read(
118 &self,
119 chat_id: &str,
120 user_id: &str,
121 tenant_id: &str,
122 ) -> Result<()> {
123 self.write(
124 Method::Post,
125 &urls::mark_chat_read(chat_id),
126 "Chat.ReadWrite",
127 Some(user_body(user_id, tenant_id)),
128 )
129 .await
130 }
131
132 pub async fn mark_chat_unread(
133 &self,
134 chat_id: &str,
135 user_id: &str,
136 tenant_id: &str,
137 last_read_at: DateTime<Utc>,
138 ) -> Result<()> {
139 let body = mark_unread_body(user_id, tenant_id, last_read_at);
140 self.write(
141 Method::Post,
142 &urls::mark_chat_unread(chat_id),
143 "Chat.ReadWrite",
144 Some(body),
145 )
146 .await
147 }
148
149 pub async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
150 self.write(
151 Method::Post,
152 &urls::hide_chat(chat_id),
153 "Chat.ReadWrite",
154 Some(user_body(user_id, tenant_id)),
155 )
156 .await
157 }
158
159 pub async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
160 self.write(
161 Method::Post,
162 &urls::unhide_chat(chat_id),
163 "Chat.ReadWrite",
164 Some(user_body(user_id, tenant_id)),
165 )
166 .await
167 }
168
169 pub async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
170 let members = self.chat_members(chat_id).await?;
171 let membership_id = membership_id(&members, user_id).ok_or(Error::NotAMember)?;
172 self.write(
173 Method::Delete,
174 &urls::chat_member(chat_id, membership_id),
175 "Chat.ReadWrite",
176 None,
177 )
178 .await
179 }
180
181 52 pub async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
182 53 self.write(
183 54 Method::Post,
@@ -240,44 +111,6 @@ impl Graph {
240 111 .await
241 112 }
242 113
243 pub async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
244 let body = json!({
245 "chatType": "oneOnOne",
246 "members": [conversation_member(my_user_id), conversation_member(user_id)],
247 });
248 self.write_for_chat(body).await
249 }
250
251 pub async fn create_group(
252 &self,
253 my_user_id: &str,
254 user_ids: &[String],
255 topic: Option<&str>,
256 ) -> Result<Chat> {
257 let members: Vec<Value> = std::iter::once(my_user_id)
258 .chain(user_ids.iter().map(String::as_str))
259 .map(conversation_member)
260 .collect();
261 let mut body = json!({"chatType": "group", "members": members});
262 if let Some(topic) = topic.filter(|topic| !topic.is_empty()) {
263 body["topic"] = json!(topic);
264 }
265 self.write_for_chat(body).await
266 }
267
268 async fn write_for_chat(&self, body: Value) -> Result<Chat> {
269 let answer = self
270 .session()
271 .request(
272 Method::Post,
273 &urls::create_chat(),
274 &Scope::graph("Chat.ReadWrite"),
275 Some(body),
276 )
277 .await?;
278 Ok(serde_json::from_value(answer.body)?)
279 }
280
281 114 async fn write_for_message(
282 115 &self,
283 116 method: Method,
@@ -305,37 +138,3 @@ impl Graph {
305 138 Ok(())
306 139 }
307 140 }
308
309 #[cfg(test)]
310 mod tests {
311 use chrono::TimeZone;
312
313 use super::*;
314
315 fn member(id: &str, user_id: &str) -> Member {
316 Member {
317 id: Some(id.to_owned()),
318 user_id: Some(user_id.to_owned()),
319 tenant_id: None,
320 display_name: None,
321 email: None,
322 roles: Vec::new(),
323 }
324 }
325
326 #[test]
327 fn membership_is_found_by_user_id() {
328 let members = [member("m1", "u1"), member("m2", "u2")];
329 assert_eq!(membership_id(&members, "u2"), Some("m2"));
330 assert_eq!(membership_id(&members, "u3"), None);
331 }
332
333 #[test]
334 fn mark_unread_body_carries_the_read_horizon() {
335 let at = Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, 0).unwrap();
336 let body = mark_unread_body("u1", "t1", at);
337 assert_eq!(body["user"]["id"], "u1");
338 assert_eq!(body["user"]["tenantId"], "t1");
339 assert_eq!(body["lastMessageReadDateTime"], "2026-10-06T09:00:00.000Z");
340 }
341 }
@@ -1,57 +1,14 @@
1use chrono::{DateTime, SecondsFormat, Utc};
2use serde_json::{Value, json};
1use serde_json::{Value, json};
3use session::{GRAPH, Method, Scope};
2use session::{Method, Scope};
4
3
5use crate::client::Graph;
4use crate::client::Graph;
6use crate::error::{Error, Result};
5use crate::error::Result;
7use crate::models::{Chat, Member, Message};
6use crate::models::Message;
8use crate::outgoing::{MessageExtras, OutgoingMention, message_body};
7use crate::outgoing::{MessageExtras, OutgoingMention, message_body};
9use crate::target::MessageTarget;
8use crate::target::MessageTarget;
10use crate::urls;
9use crate::urls;
11
10
12fn conversation_member(user_id: &str) -> Value {
13 json!({
14 "@odata.type": "#microsoft.graph.aadUserConversationMember",
15 "roles": ["owner"],
16 "user@odata.bind": format!("{GRAPH}/v1.0/users('{user_id}')"),
17 })
18}
19
20fn user_body(user_id: &str, tenant_id: &str) -> Value {
21 json!({"user": {"id": user_id, "tenantId": tenant_id}})
22}
23
24fn mark_unread_body(user_id: &str, tenant_id: &str, last_read_at: DateTime<Utc>) -> Value {
25 json!({
26 "user": {"id": user_id, "tenantId": tenant_id},
27 "lastMessageReadDateTime": last_read_at.to_rfc3339_opts(SecondsFormat::Millis, true),
28 })
29}
30
31fn membership_id<'a>(members: &'a [Member], user_id: &str) -> Option<&'a str> {
32 members
33 .iter()
34 .find(|member| member.user_id.as_deref() == Some(user_id))
35 .and_then(|member| member.id.as_deref())
36}
37
38impl Graph {
11impl Graph {
39 pub async fn send_chat_message(
40 &self,
41 chat_id: &str,
42 html: &str,
43 mentions: &[OutgoingMention],
44 extras: &MessageExtras,
45 ) -> Result<Message> {
46 self.write_for_message(
47 Method::Post,
48 &urls::chat_message_collection(chat_id),
49 "Chat.ReadWrite",
50 Some(message_body(html, mentions, extras)),
51 )
52 .await
53 }
54
55 pub async fn send_channel_message(
12 pub async fn send_channel_message(
56 &self,
13 &self,
57 team_id: &str,
14 team_id: &str,
@@ -92,92 +49,6 @@ impl Graph {
92 .await
49 .await
93 }
50 }
94
51
95 /// Beta API `chats/{id}/messages/replyWithQuote`; Teams renders the quote from the `messageReference` attachment.
96 pub async fn reply_with_quote(
97 &self,
98 chat_id: &str,
99 quoted_message_id: &str,
100 html: &str,
101 mentions: &[OutgoingMention],
102 extras: &MessageExtras,
103 ) -> Result<Message> {
104 let body = json!({
105 "messageIds": [quoted_message_id],
106 "replyMessage": message_body(html, mentions, extras),
107 });
108 self.write_for_message(
109 Method::Post,
110 &urls::reply_with_quote(chat_id),
111 "Chat.ReadWrite",
112 Some(body),
113 )
114 .await
115 }
116
117 pub async fn mark_chat_read(
118 &self,
119 chat_id: &str,
120 user_id: &str,
121 tenant_id: &str,
122 ) -> Result<()> {
123 self.write(
124 Method::Post,
125 &urls::mark_chat_read(chat_id),
126 "Chat.ReadWrite",
127 Some(user_body(user_id, tenant_id)),
128 )
129 .await
130 }
131
132 pub async fn mark_chat_unread(
133 &self,
134 chat_id: &str,
135 user_id: &str,
136 tenant_id: &str,
137 last_read_at: DateTime<Utc>,
138 ) -> Result<()> {
139 let body = mark_unread_body(user_id, tenant_id, last_read_at);
140 self.write(
141 Method::Post,
142 &urls::mark_chat_unread(chat_id),
143 "Chat.ReadWrite",
144 Some(body),
145 )
146 .await
147 }
148
149 pub async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
150 self.write(
151 Method::Post,
152 &urls::hide_chat(chat_id),
153 "Chat.ReadWrite",
154 Some(user_body(user_id, tenant_id)),
155 )
156 .await
157 }
158
159 pub async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
160 self.write(
161 Method::Post,
162 &urls::unhide_chat(chat_id),
163 "Chat.ReadWrite",
164 Some(user_body(user_id, tenant_id)),
165 )
166 .await
167 }
168
169 pub async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
170 let members = self.chat_members(chat_id).await?;
171 let membership_id = membership_id(&members, user_id).ok_or(Error::NotAMember)?;
172 self.write(
173 Method::Delete,
174 &urls::chat_member(chat_id, membership_id),
175 "Chat.ReadWrite",
176 None,
177 )
178 .await
179 }
180
181 pub async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
52 pub async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
182 self.write(
53 self.write(
183 Method::Post,
54 Method::Post,
@@ -240,44 +111,6 @@ impl Graph {
240 .await
111 .await
241 }
112 }
242
113
243 pub async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
244 let body = json!({
245 "chatType": "oneOnOne",
246 "members": [conversation_member(my_user_id), conversation_member(user_id)],
247 });
248 self.write_for_chat(body).await
249 }
250
251 pub async fn create_group(
252 &self,
253 my_user_id: &str,
254 user_ids: &[String],
255 topic: Option<&str>,
256 ) -> Result<Chat> {
257 let members: Vec<Value> = std::iter::once(my_user_id)
258 .chain(user_ids.iter().map(String::as_str))
259 .map(conversation_member)
260 .collect();
261 let mut body = json!({"chatType": "group", "members": members});
262 if let Some(topic) = topic.filter(|topic| !topic.is_empty()) {
263 body["topic"] = json!(topic);
264 }
265 self.write_for_chat(body).await
266 }
267
268 async fn write_for_chat(&self, body: Value) -> Result<Chat> {
269 let answer = self
270 .session()
271 .request(
272 Method::Post,
273 &urls::create_chat(),
274 &Scope::graph("Chat.ReadWrite"),
275 Some(body),
276 )
277 .await?;
278 Ok(serde_json::from_value(answer.body)?)
279 }
280
281 async fn write_for_message(
114 async fn write_for_message(
282 &self,
115 &self,
283 method: Method,
116 method: Method,
@@ -305,37 +138,3 @@ impl Graph {
305 Ok(())
138 Ok(())
306 }
139 }
307}
140}
308
309#[cfg(test)]
310mod tests {
311 use chrono::TimeZone;
312
313 use super::*;
314
315 fn member(id: &str, user_id: &str) -> Member {
316 Member {
317 id: Some(id.to_owned()),
318 user_id: Some(user_id.to_owned()),
319 tenant_id: None,
320 display_name: None,
321 email: None,
322 roles: Vec::new(),
323 }
324 }
325
326 #[test]
327 fn membership_is_found_by_user_id() {
328 let members = [member("m1", "u1"), member("m2", "u2")];
329 assert_eq!(membership_id(&members, "u2"), Some("m2"));
330 assert_eq!(membership_id(&members, "u3"), None);
331 }
332
333 #[test]
334 fn mark_unread_body_carries_the_read_horizon() {
335 let at = Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, 0).unwrap();
336 let body = mark_unread_body("u1", "t1", at);
337 assert_eq!(body["user"]["id"], "u1");
338 assert_eq!(body["user"]["tenantId"], "t1");
339 assert_eq!(body["lastMessageReadDateTime"], "2026-10-06T09:00:00.000Z");
340 }
341}
crates/session/assets/fetch.js +2 −0
@@ -224,6 +224,8 @@
224 224 const text = await response.text();
225 225 let body = text;
226 226 try { body = text ? JSON.parse(text) : null; } catch (error) {}
227 const location = response.headers.get('Location');
228 if (body === null && location) body = {location};
227 229 return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};
228 230 } catch (error) {
229 231 return {status: 0, body: String(error)};
@@ -224,6 +224,8 @@
224 const text = await response.text();
224 const text = await response.text();
225 let body = text;
225 let body = text;
226 try { body = text ? JSON.parse(text) : null; } catch (error) {}
226 try { body = text ? JSON.parse(text) : null; } catch (error) {}
227 const location = response.headers.get('Location');
228 if (body === null && location) body = {location};
227 return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};
229 return {status: response.status, retryAfter: response.headers.get('Retry-After'), body};
228 } catch (error) {
230 } catch (error) {
229 return {status: 0, body: String(error)};
231 return {status: 0, body: String(error)};
crates/session/src/app.rs +1 −17
@@ -3,11 +3,10 @@ use serde::Deserialize;
3 3 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4 4 pub enum App {
5 5 Teams,
6 Outlook,
7 6 }
8 7
9 8 impl App {
10 pub const ALL: [App; 2] = [App::Teams, App::Outlook];
9 pub const ALL: [App; 1] = [App::Teams];
11 10
12 11 pub fn origins(self) -> &'static [&'static str] {
13 12 match self {
@@ -15,17 +14,12 @@ impl App {
15 14 "https://teams.cloud.microsoft",
16 15 "https://teams.microsoft.com",
17 16 ],
18 App::Outlook => &[
19 "https://outlook.office.com",
20 "https://outlook.cloud.microsoft",
21 ],
22 17 }
23 18 }
24 19
25 20 pub fn start_url(self) -> &'static str {
26 21 match self {
27 22 App::Teams => "https://teams.cloud.microsoft/",
28 App::Outlook => "https://outlook.cloud.microsoft/mail/",
29 23 }
30 24 }
31 25
@@ -33,7 +27,6 @@ impl App {
33 27 pub fn park_url(self) -> &'static str {
34 28 match self {
35 29 App::Teams => "https://teams.cloud.microsoft/robots.txt",
36 App::Outlook => "https://outlook.cloud.microsoft/owa/favicon.ico",
37 30 }
38 31 }
39 32
@@ -46,7 +39,6 @@ impl std::fmt::Display for App {
46 39 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 40 formatter.write_str(match self {
48 41 App::Teams => "teams",
49 App::Outlook => "outlook",
50 42 })
51 43 }
52 44 }
@@ -113,13 +105,6 @@ mod tests {
113 105 .as_deref(),
114 106 Some("ws://x/3")
115 107 );
116 assert_eq!(
117 find_app_tab(&targets, App::Outlook)
118 .unwrap()
119 .websocket_url
120 .as_deref(),
121 Some("ws://x/2")
122 );
123 108 }
124 109
125 110 #[test]
@@ -137,7 +122,6 @@ mod tests {
137 122 .unwrap();
138 123 let teams = find_app_tab(&parked, App::Teams).unwrap();
139 124 assert!(App::Teams.is_park_url(&teams.url));
140 assert!(App::Outlook.is_park_url(&find_app_tab(&parked, App::Outlook).unwrap().url));
141 125 assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft/v2/"));
142 126 }
143 127
@@ -3,11 +3,10 @@ use serde::Deserialize;
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4pub enum App {
4pub enum App {
5 Teams,
5 Teams,
6 Outlook,
7}
6}
8
7
9impl App {
8impl App {
10 pub const ALL: [App; 2] = [App::Teams, App::Outlook];
9 pub const ALL: [App; 1] = [App::Teams];
11
10
12 pub fn origins(self) -> &'static [&'static str] {
11 pub fn origins(self) -> &'static [&'static str] {
13 match self {
12 match self {
@@ -15,17 +14,12 @@ impl App {
15 "https://teams.cloud.microsoft",
14 "https://teams.cloud.microsoft",
16 "https://teams.microsoft.com",
15 "https://teams.microsoft.com",
17 ],
16 ],
18 App::Outlook => &[
19 "https://outlook.office.com",
20 "https://outlook.cloud.microsoft",
21 ],
22 }
17 }
23 }
18 }
24
19
25 pub fn start_url(self) -> &'static str {
20 pub fn start_url(self) -> &'static str {
26 match self {
21 match self {
27 App::Teams => "https://teams.cloud.microsoft/",
22 App::Teams => "https://teams.cloud.microsoft/",
28 App::Outlook => "https://outlook.cloud.microsoft/mail/",
29 }
23 }
30 }
24 }
31
25
@@ -33,7 +27,6 @@ impl App {
33 pub fn park_url(self) -> &'static str {
27 pub fn park_url(self) -> &'static str {
34 match self {
28 match self {
35 App::Teams => "https://teams.cloud.microsoft/robots.txt",
29 App::Teams => "https://teams.cloud.microsoft/robots.txt",
36 App::Outlook => "https://outlook.cloud.microsoft/owa/favicon.ico",
37 }
30 }
38 }
31 }
39
32
@@ -46,7 +39,6 @@ impl std::fmt::Display for App {
46 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 formatter.write_str(match self {
40 formatter.write_str(match self {
48 App::Teams => "teams",
41 App::Teams => "teams",
49 App::Outlook => "outlook",
50 })
42 })
51 }
43 }
52}
44}
@@ -113,13 +105,6 @@ mod tests {
113 .as_deref(),
105 .as_deref(),
114 Some("ws://x/3")
106 Some("ws://x/3")
115 );
107 );
116 assert_eq!(
117 find_app_tab(&targets, App::Outlook)
118 .unwrap()
119 .websocket_url
120 .as_deref(),
121 Some("ws://x/2")
122 );
123 }
108 }
124
109
125 #[test]
110 #[test]
@@ -137,7 +122,6 @@ mod tests {
137 .unwrap();
122 .unwrap();
138 let teams = find_app_tab(&parked, App::Teams).unwrap();
123 let teams = find_app_tab(&parked, App::Teams).unwrap();
139 assert!(App::Teams.is_park_url(&teams.url));
124 assert!(App::Teams.is_park_url(&teams.url));
140 assert!(App::Outlook.is_park_url(&find_app_tab(&parked, App::Outlook).unwrap().url));
141 assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft/v2/"));
125 assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft/v2/"));
142 }
126 }
143
127
crates/session/src/http.rs +0 −11
@@ -95,17 +95,6 @@ pub async fn list_targets(endpoint: &str) -> Result<Vec<Target>> {
95 95 serde_json::from_slice(&body).map_err(|error| no_browser(error.to_string()))
96 96 }
97 97
98 /// Opens a background tab; Chrome 111+ only accepts PUT here.
99 pub async fn new_tab(endpoint: &str, url: &str) -> Result<()> {
100 exchange(endpoint, "PUT", &format!("/json/new?{url}"))
101 .await
102 .map(drop)
103 .map_err(|reason| Error::NoBrowser {
104 endpoint: endpoint.to_owned(),
105 reason,
106 })
107 }
108
109 98 #[cfg(test)]
110 99 mod tests {
111 100 use super::*;
@@ -95,17 +95,6 @@ pub async fn list_targets(endpoint: &str) -> Result<Vec<Target>> {
95 serde_json::from_slice(&body).map_err(|error| no_browser(error.to_string()))
95 serde_json::from_slice(&body).map_err(|error| no_browser(error.to_string()))
96}
96}
97
97
98/// Opens a background tab; Chrome 111+ only accepts PUT here.
99pub async fn new_tab(endpoint: &str, url: &str) -> Result<()> {
100 exchange(endpoint, "PUT", &format!("/json/new?{url}"))
101 .await
102 .map(drop)
103 .map_err(|reason| Error::NoBrowser {
104 endpoint: endpoint.to_owned(),
105 reason,
106 })
107}
108
109#[cfg(test)]
98#[cfg(test)]
110mod tests {
99mod tests {
111 use super::*;
100 use super::*;
crates/session/src/lib.rs +1 −1
@@ -17,6 +17,6 @@ pub use page_script::token_acquirer_script;
17 17 pub use request::{
18 18 ApiResponse, AugloopExchange, AugloopStage, BodyToken, Method, Request, SignalrExchange,
19 19 };
20 pub use scope::{GRAPH, IC3, NestedApp, OUTLOOK, PRESENCE, SPACES, Scope};
20 pub use scope::{GRAPH, IC3, NestedApp, PRESENCE, SPACES, Scope};
21 21 pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};
22 22 pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
@@ -17,6 +17,6 @@ pub use page_script::token_acquirer_script;
17pub use request::{
17pub use request::{
18 ApiResponse, AugloopExchange, AugloopStage, BodyToken, Method, Request, SignalrExchange,
18 ApiResponse, AugloopExchange, AugloopStage, BodyToken, Method, Request, SignalrExchange,
19};
19};
20pub use scope::{GRAPH, IC3, NestedApp, OUTLOOK, PRESENCE, SPACES, Scope};
20pub use scope::{GRAPH, IC3, NestedApp, PRESENCE, SPACES, Scope};
21pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};
21pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};
22pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
22pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
crates/session/src/native.rs +7 −5
@@ -108,7 +108,7 @@ impl NativeHttp {
108 108 if !force_refresh && let Some(held) = self.held(scope) {
109 109 return Some(held);
110 110 }
111 for app in scope.tab_order() {
111 for app in App::ALL {
112 112 let Ok(Value::String(token)) = session
113 113 .run_with_token(app, scope, TOKEN_BODY, &json!({}), force_refresh)
114 114 .await
@@ -200,9 +200,14 @@ impl NativeHttp {
200 200 retry_after,
201 201 });
202 202 }
203 let location = response
204 .headers()
205 .get("Location")
206 .and_then(|value| value.to_str().ok())
207 .map(str::to_owned);
203 208 let text = response.text().await?;
204 209 let body = if text.is_empty() {
205 Value::Null
210 location.map_or(Value::Null, |location| json!({ "location": location }))
206 211 } else {
207 212 serde_json::from_str(&text).unwrap_or(Value::String(text))
208 213 };
@@ -338,9 +343,6 @@ mod tests {
338 343 assert!(!eligible(&Request::get(
339 344 "https://teams.cloud.microsoft/v2/"
340 345 )));
341 assert!(!eligible(&Request::get(
342 "https://outlook.office.com/api/v2.0/me/messages"
343 )));
344 346 assert!(!eligible(&Request::get(
345 347 "http://graph.microsoft.com/v1.0/me"
346 348 )));
@@ -108,7 +108,7 @@ impl NativeHttp {
108 if !force_refresh && let Some(held) = self.held(scope) {
108 if !force_refresh && let Some(held) = self.held(scope) {
109 return Some(held);
109 return Some(held);
110 }
110 }
111 for app in scope.tab_order() {
111 for app in App::ALL {
112 let Ok(Value::String(token)) = session
112 let Ok(Value::String(token)) = session
113 .run_with_token(app, scope, TOKEN_BODY, &json!({}), force_refresh)
113 .run_with_token(app, scope, TOKEN_BODY, &json!({}), force_refresh)
114 .await
114 .await
@@ -200,9 +200,14 @@ impl NativeHttp {
200 retry_after,
200 retry_after,
201 });
201 });
202 }
202 }
203 let location = response
204 .headers()
205 .get("Location")
206 .and_then(|value| value.to_str().ok())
207 .map(str::to_owned);
203 let text = response.text().await?;
208 let text = response.text().await?;
204 let body = if text.is_empty() {
209 let body = if text.is_empty() {
205 Value::Null
210 location.map_or(Value::Null, |location| json!({ "location": location }))
206 } else {
211 } else {
207 serde_json::from_str(&text).unwrap_or(Value::String(text))
212 serde_json::from_str(&text).unwrap_or(Value::String(text))
208 };
213 };
@@ -338,9 +343,6 @@ mod tests {
338 assert!(!eligible(&Request::get(
343 assert!(!eligible(&Request::get(
339 "https://teams.cloud.microsoft/v2/"
344 "https://teams.cloud.microsoft/v2/"
340 )));
345 )));
341 assert!(!eligible(&Request::get(
342 "https://outlook.office.com/api/v2.0/me/messages"
343 )));
344 assert!(!eligible(&Request::get(
346 assert!(!eligible(&Request::get(
345 "http://graph.microsoft.com/v1.0/me"
347 "http://graph.microsoft.com/v1.0/me"
346 )));
348 )));
crates/session/src/scope.rs +0 −40
@@ -1,11 +1,8 @@
1 1 use std::borrow::Cow;
2 2
3 use crate::app::App;
4
5 3 pub const GRAPH: &str = "https://graph.microsoft.com";
6 4 pub const IC3: &str = "https://ic3.teams.office.com";
7 5 pub const PRESENCE: &str = "https://presence.teams.microsoft.com";
8 pub const OUTLOOK: &str = "https://outlook.office.com";
9 6 pub const SPACES: &str = "https://api.spaces.skype.com";
10 7
11 8 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -51,15 +48,6 @@ impl Scope {
51 48 pub fn graph(name: impl Into<Cow<'static, str>>) -> Self {
52 49 Scope::new(GRAPH, name)
53 50 }
54
55 /// Tabs to try, best first. The other tab is the fallback, as in the Python client.
56 pub fn tab_order(&self) -> [App; 2] {
57 if self.resource == GRAPH && self.name.starts_with("Chat.") {
58 [App::Outlook, App::Teams]
59 } else {
60 [App::Teams, App::Outlook]
61 }
62 }
63 51 }
64 52
65 53 impl std::fmt::Display for Scope {
@@ -72,34 +60,6 @@ impl std::fmt::Display for Scope {
72 60 mod tests {
73 61 use super::*;
74 62
75 #[test]
76 fn chat_scopes_prefer_outlook() {
77 assert_eq!(
78 Scope::graph("Chat.Read").tab_order(),
79 [App::Outlook, App::Teams]
80 );
81 assert_eq!(
82 Scope::graph("Chat.ReadWrite").tab_order(),
83 [App::Outlook, App::Teams]
84 );
85 }
86
87 #[test]
88 fn other_scopes_prefer_teams() {
89 assert_eq!(
90 Scope::graph("ChannelMessage.Read.All").tab_order(),
91 [App::Teams, App::Outlook]
92 );
93 assert_eq!(
94 Scope::new(IC3, "Teams.AccessAsUser.All").tab_order(),
95 [App::Teams, App::Outlook]
96 );
97 assert_eq!(
98 Scope::new(PRESENCE, "Chat.Read").tab_order(),
99 [App::Teams, App::Outlook]
100 );
101 }
102
103 63 #[test]
104 64 fn displays_resource_and_name() {
105 65 assert_eq!(
@@ -1,11 +1,8 @@
1use std::borrow::Cow;
1use std::borrow::Cow;
2
2
3use crate::app::App;
4
5pub const GRAPH: &str = "https://graph.microsoft.com";
3pub const GRAPH: &str = "https://graph.microsoft.com";
6pub const IC3: &str = "https://ic3.teams.office.com";
4pub const IC3: &str = "https://ic3.teams.office.com";
7pub const PRESENCE: &str = "https://presence.teams.microsoft.com";
5pub const PRESENCE: &str = "https://presence.teams.microsoft.com";
8pub const OUTLOOK: &str = "https://outlook.office.com";
9pub const SPACES: &str = "https://api.spaces.skype.com";
6pub const SPACES: &str = "https://api.spaces.skype.com";
10
7
11#[derive(Debug, Clone, PartialEq, Eq)]
8#[derive(Debug, Clone, PartialEq, Eq)]
@@ -51,15 +48,6 @@ impl Scope {
51 pub fn graph(name: impl Into<Cow<'static, str>>) -> Self {
48 pub fn graph(name: impl Into<Cow<'static, str>>) -> Self {
52 Scope::new(GRAPH, name)
49 Scope::new(GRAPH, name)
53 }
50 }
54
55 /// Tabs to try, best first. The other tab is the fallback, as in the Python client.
56 pub fn tab_order(&self) -> [App; 2] {
57 if self.resource == GRAPH && self.name.starts_with("Chat.") {
58 [App::Outlook, App::Teams]
59 } else {
60 [App::Teams, App::Outlook]
61 }
62 }
63}
51}
64
52
65impl std::fmt::Display for Scope {
53impl std::fmt::Display for Scope {
@@ -72,34 +60,6 @@ impl std::fmt::Display for Scope {
72mod tests {
60mod tests {
73 use super::*;
61 use super::*;
74
62
75 #[test]
76 fn chat_scopes_prefer_outlook() {
77 assert_eq!(
78 Scope::graph("Chat.Read").tab_order(),
79 [App::Outlook, App::Teams]
80 );
81 assert_eq!(
82 Scope::graph("Chat.ReadWrite").tab_order(),
83 [App::Outlook, App::Teams]
84 );
85 }
86
87 #[test]
88 fn other_scopes_prefer_teams() {
89 assert_eq!(
90 Scope::graph("ChannelMessage.Read.All").tab_order(),
91 [App::Teams, App::Outlook]
92 );
93 assert_eq!(
94 Scope::new(IC3, "Teams.AccessAsUser.All").tab_order(),
95 [App::Teams, App::Outlook]
96 );
97 assert_eq!(
98 Scope::new(PRESENCE, "Chat.Read").tab_order(),
99 [App::Teams, App::Outlook]
100 );
101 }
102
103 #[test]
63 #[test]
104 fn displays_resource_and_name() {
64 fn displays_resource_and_name() {
105 assert_eq!(
65 assert_eq!(
crates/session/src/session.rs +2 −27
@@ -215,7 +215,7 @@ impl Session {
215 215 }
216 216 if search.ungranted.len() == App::ALL.len() {
217 217 return Err(Error::LoginRequired(format!(
218 "neither the Teams nor the Outlook web app is granted {scope}"
218 "the Teams web app is not granted {scope}"
219 219 )));
220 220 }
221 221 self.reload_all().await;
@@ -256,7 +256,7 @@ impl Session {
256 256 let payload = self.payload(requests, scope);
257 257 let expression = format!("({FETCH_SCRIPT})({payload})");
258 258 let has_write = requests.iter().any(|request| request.method != Method::Get);
259 for app in tab_order(requests, scope) {
259 for app in App::ALL {
260 260 let outcome = match self.evaluate_in(app, &expression).await {
261 261 Ok(Some(value)) => value,
262 262 Ok(None) => continue,
@@ -361,15 +361,6 @@ pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
361 361 .unwrap_or(default)
362 362 }
363 363
364 /// Requests without a token go to the Teams tab first: the Outlook mail page's CSP blocks cross-origin fetches.
365 fn tab_order(requests: &[&Request], scope: &Scope) -> [App; 2] {
366 if requests.iter().all(|request| request.anonymous) {
367 [App::Teams, App::Outlook]
368 } else {
369 scope.tab_order()
370 }
371 }
372
373 364 #[cfg(test)]
374 365 mod tests {
375 366 use std::sync::Mutex as StdMutex;
@@ -439,20 +430,4 @@ mod tests {
439 430 );
440 431 assert_eq!(retry_wait(Some("-3"), default), default);
441 432 }
442
443 #[test]
444 fn anonymous_requests_try_the_teams_tab_first() {
445 let chat_scope = Scope::graph("Chat.Read");
446 let image =
447 Request::anonymous_binary_get("https://media.giphy.com/media/x/giphy.gif", Vec::new());
448 let chats = Request::get("https://graph.microsoft.com/v1.0/me/chats");
449 assert_eq!(
450 tab_order(&[&image], &chat_scope),
451 [App::Teams, App::Outlook]
452 );
453 assert_eq!(
454 tab_order(&[&chats], &chat_scope),
455 [App::Outlook, App::Teams]
456 );
457 }
458 433 }
@@ -215,7 +215,7 @@ impl Session {
215 }
215 }
216 if search.ungranted.len() == App::ALL.len() {
216 if search.ungranted.len() == App::ALL.len() {
217 return Err(Error::LoginRequired(format!(
217 return Err(Error::LoginRequired(format!(
218 "neither the Teams nor the Outlook web app is granted {scope}"
218 "the Teams web app is not granted {scope}"
219 )));
219 )));
220 }
220 }
221 self.reload_all().await;
221 self.reload_all().await;
@@ -256,7 +256,7 @@ impl Session {
256 let payload = self.payload(requests, scope);
256 let payload = self.payload(requests, scope);
257 let expression = format!("({FETCH_SCRIPT})({payload})");
257 let expression = format!("({FETCH_SCRIPT})({payload})");
258 let has_write = requests.iter().any(|request| request.method != Method::Get);
258 let has_write = requests.iter().any(|request| request.method != Method::Get);
259 for app in tab_order(requests, scope) {
259 for app in App::ALL {
260 let outcome = match self.evaluate_in(app, &expression).await {
260 let outcome = match self.evaluate_in(app, &expression).await {
261 Ok(Some(value)) => value,
261 Ok(Some(value)) => value,
262 Ok(None) => continue,
262 Ok(None) => continue,
@@ -361,15 +361,6 @@ pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
361 .unwrap_or(default)
361 .unwrap_or(default)
362}
362}
363
363
364/// Requests without a token go to the Teams tab first: the Outlook mail page's CSP blocks cross-origin fetches.
365fn tab_order(requests: &[&Request], scope: &Scope) -> [App; 2] {
366 if requests.iter().all(|request| request.anonymous) {
367 [App::Teams, App::Outlook]
368 } else {
369 scope.tab_order()
370 }
371}
372
373#[cfg(test)]
364#[cfg(test)]
374mod tests {
365mod tests {
375 use std::sync::Mutex as StdMutex;
366 use std::sync::Mutex as StdMutex;
@@ -439,20 +430,4 @@ mod tests {
439 );
430 );
440 assert_eq!(retry_wait(Some("-3"), default), default);
431 assert_eq!(retry_wait(Some("-3"), default), default);
441 }
432 }
442
443 #[test]
444 fn anonymous_requests_try_the_teams_tab_first() {
445 let chat_scope = Scope::graph("Chat.Read");
446 let image =
447 Request::anonymous_binary_get("https://media.giphy.com/media/x/giphy.gif", Vec::new());
448 let chats = Request::get("https://graph.microsoft.com/v1.0/me/chats");
449 assert_eq!(
450 tab_order(&[&image], &chat_scope),
451 [App::Teams, App::Outlook]
452 );
453 assert_eq!(
454 tab_order(&[&chats], &chat_scope),
455 [App::Outlook, App::Teams]
456 );
457 }
458}
433}
crates/session/src/transport.rs +2 −39
@@ -1,13 +1,12 @@
1 1 use std::future::Future;
2 2 use std::pin::Pin;
3 use std::sync::atomic::{AtomicBool, Ordering};
4 3
5 4 use serde_json::json;
6 5
7 6 use crate::app::{App, find_app_tab, has_login_tab};
8 7 use crate::error::Result;
9 8 use crate::events::{TabControl, TabEvents, open};
10 use crate::http::{list_targets, new_tab};
9 use crate::http::list_targets;
11 10
12 11 pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
13 12 pub type OpenedTab = (TabControl, Option<TabEvents>);
@@ -18,7 +17,7 @@ pub struct Diagnosis {
18 17 pub app_tab_open: bool,
19 18 }
20 19
21 /// Where the signed-in Teams and Outlook web apps live: a debug port or an embedded webview.
20 /// Where the signed-in Teams web app lives: a debug port or an embedded webview.
22 21 pub trait Transport: Send + Sync {
23 22 fn check(&self) -> BoxFuture<'_, Result<()>>;
24 23
@@ -36,23 +35,16 @@ pub trait Transport: Send + Sync {
36 35
37 36 pub struct CdpTransport {
38 37 endpoint: String,
39 outlook_requested: AtomicBool,
40 38 }
41 39
42 40 impl CdpTransport {
43 41 pub fn new(endpoint: &str) -> Self {
44 42 CdpTransport {
45 43 endpoint: endpoint.trim_end_matches('/').to_owned(),
46 outlook_requested: AtomicBool::new(false),
47 44 }
48 45 }
49 46 }
50 47
51 /// Some tenants grant the Teams web client no Graph chat scopes; Outlook on the web has them and signs in silently next to a signed-in Teams.
52 fn wants_outlook_tab(targets: &[crate::app::Target], app: App) -> bool {
53 app == App::Outlook && find_app_tab(targets, App::Teams).is_some() && !has_login_tab(targets)
54 }
55
56 48 impl Transport for CdpTransport {
57 49 fn check(&self) -> BoxFuture<'_, Result<()>> {
58 50 Box::pin(async move { list_targets(&self.endpoint).await.map(drop) })
@@ -64,11 +56,6 @@ impl Transport for CdpTransport {
64 56 let Some(websocket_url) =
65 57 find_app_tab(&targets, app).and_then(|target| target.websocket_url.clone())
66 58 else {
67 if wants_outlook_tab(&targets, app)
68 && !self.outlook_requested.swap(true, Ordering::SeqCst)
69 {
70 new_tab(&self.endpoint, App::Outlook.start_url()).await?;
71 }
72 59 return Ok(None);
73 60 };
74 61 open(&websocket_url, with_events).await.map(Some)
@@ -109,27 +96,3 @@ impl Transport for CdpTransport {
109 96 })
110 97 }
111 98 }
112
113 #[cfg(test)]
114 mod tests {
115 use super::*;
116 use crate::app::Target;
117
118 fn page(url: &str) -> Target {
119 Target {
120 kind: "page".to_owned(),
121 url: url.to_owned(),
122 websocket_url: Some("ws://tab".to_owned()),
123 }
124 }
125
126 #[test]
127 fn outlook_opens_only_next_to_a_signed_in_teams_tab() {
128 let teams = page("https://teams.cloud.microsoft/");
129 let login = page("https://login.microsoftonline.com/common/oauth2");
130 assert!(wants_outlook_tab(&[teams.clone()], App::Outlook));
131 assert!(!wants_outlook_tab(&[teams.clone()], App::Teams));
132 assert!(!wants_outlook_tab(&[], App::Outlook));
133 assert!(!wants_outlook_tab(&[teams, login], App::Outlook));
134 }
135 }
@@ -1,13 +1,12 @@
1use std::future::Future;
1use std::future::Future;
2use std::pin::Pin;
2use std::pin::Pin;
3use std::sync::atomic::{AtomicBool, Ordering};
4
3
5use serde_json::json;
4use serde_json::json;
6
5
7use crate::app::{App, find_app_tab, has_login_tab};
6use crate::app::{App, find_app_tab, has_login_tab};
8use crate::error::Result;
7use crate::error::Result;
9use crate::events::{TabControl, TabEvents, open};
8use crate::events::{TabControl, TabEvents, open};
10use crate::http::{list_targets, new_tab};
9use crate::http::list_targets;
11
10
12pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
11pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
13pub type OpenedTab = (TabControl, Option<TabEvents>);
12pub type OpenedTab = (TabControl, Option<TabEvents>);
@@ -18,7 +17,7 @@ pub struct Diagnosis {
18 pub app_tab_open: bool,
17 pub app_tab_open: bool,
19}
18}
20
19
21/// Where the signed-in Teams and Outlook web apps live: a debug port or an embedded webview.
20/// Where the signed-in Teams web app lives: a debug port or an embedded webview.
22pub trait Transport: Send + Sync {
21pub trait Transport: Send + Sync {
23 fn check(&self) -> BoxFuture<'_, Result<()>>;
22 fn check(&self) -> BoxFuture<'_, Result<()>>;
24
23
@@ -36,23 +35,16 @@ pub trait Transport: Send + Sync {
36
35
37pub struct CdpTransport {
36pub struct CdpTransport {
38 endpoint: String,
37 endpoint: String,
39 outlook_requested: AtomicBool,
40}
38}
41
39
42impl CdpTransport {
40impl CdpTransport {
43 pub fn new(endpoint: &str) -> Self {
41 pub fn new(endpoint: &str) -> Self {
44 CdpTransport {
42 CdpTransport {
45 endpoint: endpoint.trim_end_matches('/').to_owned(),
43 endpoint: endpoint.trim_end_matches('/').to_owned(),
46 outlook_requested: AtomicBool::new(false),
47 }
44 }
48 }
45 }
49}
46}
50
47
51/// Some tenants grant the Teams web client no Graph chat scopes; Outlook on the web has them and signs in silently next to a signed-in Teams.
52fn wants_outlook_tab(targets: &[crate::app::Target], app: App) -> bool {
53 app == App::Outlook && find_app_tab(targets, App::Teams).is_some() && !has_login_tab(targets)
54}
55
56impl Transport for CdpTransport {
48impl Transport for CdpTransport {
57 fn check(&self) -> BoxFuture<'_, Result<()>> {
49 fn check(&self) -> BoxFuture<'_, Result<()>> {
58 Box::pin(async move { list_targets(&self.endpoint).await.map(drop) })
50 Box::pin(async move { list_targets(&self.endpoint).await.map(drop) })
@@ -64,11 +56,6 @@ impl Transport for CdpTransport {
64 let Some(websocket_url) =
56 let Some(websocket_url) =
65 find_app_tab(&targets, app).and_then(|target| target.websocket_url.clone())
57 find_app_tab(&targets, app).and_then(|target| target.websocket_url.clone())
66 else {
58 else {
67 if wants_outlook_tab(&targets, app)
68 && !self.outlook_requested.swap(true, Ordering::SeqCst)
69 {
70 new_tab(&self.endpoint, App::Outlook.start_url()).await?;
71 }
72 return Ok(None);
59 return Ok(None);
73 };
60 };
74 open(&websocket_url, with_events).await.map(Some)
61 open(&websocket_url, with_events).await.map(Some)
@@ -109,27 +96,3 @@ impl Transport for CdpTransport {
109 })
96 })
110 }
97 }
111}
98}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116 use crate::app::Target;
117
118 fn page(url: &str) -> Target {
119 Target {
120 kind: "page".to_owned(),
121 url: url.to_owned(),
122 websocket_url: Some("ws://tab".to_owned()),
123 }
124 }
125
126 #[test]
127 fn outlook_opens_only_next_to_a_signed_in_teams_tab() {
128 let teams = page("https://teams.cloud.microsoft/");
129 let login = page("https://login.microsoftonline.com/common/oauth2");
130 assert!(wants_outlook_tab(&[teams.clone()], App::Outlook));
131 assert!(!wants_outlook_tab(&[teams.clone()], App::Teams));
132 assert!(!wants_outlook_tab(&[], App::Outlook));
133 assert!(!wants_outlook_tab(&[teams, login], App::Outlook));
134 }
135}
crates/session/tests/mock_browser.rs +14 −16
@@ -100,16 +100,13 @@ fn fast_config() -> SessionConfig {
100 100 }
101 101 }
102 102
103 const BOTH_TABS: [&str; 2] = [
104 "https://teams.cloud.microsoft/v2/",
105 "https://outlook.cloud.microsoft/mail/",
106 ];
103 const TEAMS_TAB: [&str; 1] = ["https://teams.cloud.microsoft/v2/"];
107 104
108 105 #[tokio::test]
109 106 async fn request_returns_body() {
110 107 let browser = start_browser(
111 108 vec![json!({"results": [{"status": 200, "body": {"id": "u1"}}]})],
112 BOTH_TABS.to_vec(),
109 TEAMS_TAB.to_vec(),
113 110 )
114 111 .await;
115 112 let session = Session::connect_with(&browser.endpoint, fast_config())
@@ -137,7 +134,7 @@ async fn throttled_request_is_retried_after_retry_after() {
137 134 json!({"results": [{"status": 429, "retryAfter": "0", "body": "slow down"}]}),
138 135 json!({"results": [{"status": 200, "body": {"ok": true}}]}),
139 136 ],
140 BOTH_TABS.to_vec(),
137 TEAMS_TAB.to_vec(),
141 138 )
142 139 .await;
143 140 let session = Session::connect_with(&browser.endpoint, fast_config())
@@ -147,7 +144,7 @@ async fn throttled_request_is_retried_after_retry_after() {
147 144 .request(
148 145 Method::Get,
149 146 "https://graph.microsoft.com/v1.0/me/chats",
150 &Scope::graph("Chat.Read"),
147 &Scope::graph("ChannelMessage.Read.All"),
151 148 None,
152 149 )
153 150 .await
@@ -163,7 +160,7 @@ async fn batch_retries_only_throttled_requests() {
163 160 json!({"results": [{"status": 200, "body": "a"}, {"status": 429, "retryAfter": "0", "body": null}]}),
164 161 json!({"results": [{"status": 200, "body": "b"}]}),
165 162 ],
166 BOTH_TABS.to_vec(),
163 TEAMS_TAB.to_vec(),
167 164 )
168 165 .await;
169 166 let session = Session::connect_with(&browser.endpoint, fast_config())
@@ -174,7 +171,7 @@ async fn batch_retries_only_throttled_requests() {
174 171 Request::get("https://graph.microsoft.com/v1.0/b"),
175 172 ];
176 173 let responses = session
177 .batch(&requests, &Scope::graph("Chat.Read"))
174 .batch(&requests, &Scope::graph("ChannelMessage.Read.All"))
178 175 .await
179 176 .unwrap();
180 177 assert_eq!(responses[0].body, "a");
@@ -185,7 +182,7 @@ async fn batch_retries_only_throttled_requests() {
185 182 async fn api_error_is_typed() {
186 183 let browser = start_browser(
187 184 vec![json!({"results": [{"status": 404, "body": {"error": {"message": "gone"}}}]})],
188 BOTH_TABS.to_vec(),
185 TEAMS_TAB.to_vec(),
189 186 )
190 187 .await;
191 188 let session = Session::connect_with(&browser.endpoint, fast_config())
@@ -195,7 +192,7 @@ async fn api_error_is_typed() {
195 192 .request(
196 193 Method::Get,
197 194 "https://graph.microsoft.com/v1.0/chats/x",
198 &Scope::graph("Chat.Read"),
195 &Scope::graph("ChannelMessage.Read.All"),
199 196 None,
200 197 )
201 198 .await
@@ -204,9 +201,10 @@ async fn api_error_is_typed() {
204 201 }
205 202
206 203 #[tokio::test]
207 async fn ungranted_scope_in_both_tabs_is_login_required() {
208 let denied = json!({"noToken": true, "refreshError": "the app is not granted Chat.Read"});
209 let browser = start_browser(vec![denied.clone(), denied], BOTH_TABS.to_vec()).await;
204 async fn ungranted_scope_is_login_required() {
205 let denied =
206 json!({"noToken": true, "refreshError": "the app is not granted ChannelMessage.Read.All"});
207 let browser = start_browser(vec![denied], TEAMS_TAB.to_vec()).await;
210 208 let session = Session::connect_with(&browser.endpoint, fast_config())
211 209 .await
212 210 .unwrap();
@@ -214,7 +212,7 @@ async fn ungranted_scope_in_both_tabs_is_login_required() {
214 212 .request(
215 213 Method::Get,
216 214 "https://graph.microsoft.com/v1.0/me/chats",
217 &Scope::graph("Chat.Read"),
215 &Scope::graph("ChannelMessage.Read.All"),
218 216 None,
219 217 )
220 218 .await
@@ -225,7 +223,7 @@ async fn ungranted_scope_in_both_tabs_is_login_required() {
225 223 #[tokio::test]
226 224 async fn missing_token_without_login_tab_is_no_fresh_token() {
227 225 let missing = json!({"noToken": true, "refreshError": "invalid_grant"});
228 let browser = start_browser(vec![missing; 40], BOTH_TABS.to_vec()).await;
226 let browser = start_browser(vec![missing; 40], TEAMS_TAB.to_vec()).await;
229 227 let session = Session::connect_with(&browser.endpoint, fast_config())
230 228 .await
231 229 .unwrap();
@@ -100,16 +100,13 @@ fn fast_config() -> SessionConfig {
100 }
100 }
101}
101}
102
102
103const BOTH_TABS: [&str; 2] = [
103const TEAMS_TAB: [&str; 1] = ["https://teams.cloud.microsoft/v2/"];
104 "https://teams.cloud.microsoft/v2/",
105 "https://outlook.cloud.microsoft/mail/",
106];
107
104
108#[tokio::test]
105#[tokio::test]
109async fn request_returns_body() {
106async fn request_returns_body() {
110 let browser = start_browser(
107 let browser = start_browser(
111 vec![json!({"results": [{"status": 200, "body": {"id": "u1"}}]})],
108 vec![json!({"results": [{"status": 200, "body": {"id": "u1"}}]})],
112 BOTH_TABS.to_vec(),
109 TEAMS_TAB.to_vec(),
113 )
110 )
114 .await;
111 .await;
115 let session = Session::connect_with(&browser.endpoint, fast_config())
112 let session = Session::connect_with(&browser.endpoint, fast_config())
@@ -137,7 +134,7 @@ async fn throttled_request_is_retried_after_retry_after() {
137 json!({"results": [{"status": 429, "retryAfter": "0", "body": "slow down"}]}),
134 json!({"results": [{"status": 429, "retryAfter": "0", "body": "slow down"}]}),
138 json!({"results": [{"status": 200, "body": {"ok": true}}]}),
135 json!({"results": [{"status": 200, "body": {"ok": true}}]}),
139 ],
136 ],
140 BOTH_TABS.to_vec(),
137 TEAMS_TAB.to_vec(),
141 )
138 )
142 .await;
139 .await;
143 let session = Session::connect_with(&browser.endpoint, fast_config())
140 let session = Session::connect_with(&browser.endpoint, fast_config())
@@ -147,7 +144,7 @@ async fn throttled_request_is_retried_after_retry_after() {
147 .request(
144 .request(
148 Method::Get,
145 Method::Get,
149 "https://graph.microsoft.com/v1.0/me/chats",
146 "https://graph.microsoft.com/v1.0/me/chats",
150 &Scope::graph("Chat.Read"),
147 &Scope::graph("ChannelMessage.Read.All"),
151 None,
148 None,
152 )
149 )
153 .await
150 .await
@@ -163,7 +160,7 @@ async fn batch_retries_only_throttled_requests() {
163 json!({"results": [{"status": 200, "body": "a"}, {"status": 429, "retryAfter": "0", "body": null}]}),
160 json!({"results": [{"status": 200, "body": "a"}, {"status": 429, "retryAfter": "0", "body": null}]}),
164 json!({"results": [{"status": 200, "body": "b"}]}),
161 json!({"results": [{"status": 200, "body": "b"}]}),
165 ],
162 ],
166 BOTH_TABS.to_vec(),
163 TEAMS_TAB.to_vec(),
167 )
164 )
168 .await;
165 .await;
169 let session = Session::connect_with(&browser.endpoint, fast_config())
166 let session = Session::connect_with(&browser.endpoint, fast_config())
@@ -174,7 +171,7 @@ async fn batch_retries_only_throttled_requests() {
174 Request::get("https://graph.microsoft.com/v1.0/b"),
171 Request::get("https://graph.microsoft.com/v1.0/b"),
175 ];
172 ];
176 let responses = session
173 let responses = session
177 .batch(&requests, &Scope::graph("Chat.Read"))
174 .batch(&requests, &Scope::graph("ChannelMessage.Read.All"))
178 .await
175 .await
179 .unwrap();
176 .unwrap();
180 assert_eq!(responses[0].body, "a");
177 assert_eq!(responses[0].body, "a");
@@ -185,7 +182,7 @@ async fn batch_retries_only_throttled_requests() {
185async fn api_error_is_typed() {
182async fn api_error_is_typed() {
186 let browser = start_browser(
183 let browser = start_browser(
187 vec![json!({"results": [{"status": 404, "body": {"error": {"message": "gone"}}}]})],
184 vec![json!({"results": [{"status": 404, "body": {"error": {"message": "gone"}}}]})],
188 BOTH_TABS.to_vec(),
185 TEAMS_TAB.to_vec(),
189 )
186 )
190 .await;
187 .await;
191 let session = Session::connect_with(&browser.endpoint, fast_config())
188 let session = Session::connect_with(&browser.endpoint, fast_config())
@@ -195,7 +192,7 @@ async fn api_error_is_typed() {
195 .request(
192 .request(
196 Method::Get,
193 Method::Get,
197 "https://graph.microsoft.com/v1.0/chats/x",
194 "https://graph.microsoft.com/v1.0/chats/x",
198 &Scope::graph("Chat.Read"),
195 &Scope::graph("ChannelMessage.Read.All"),
199 None,
196 None,
200 )
197 )
201 .await
198 .await
@@ -204,9 +201,10 @@ async fn api_error_is_typed() {
204}
201}
205
202
206#[tokio::test]
203#[tokio::test]
207async fn ungranted_scope_in_both_tabs_is_login_required() {
204async fn ungranted_scope_is_login_required() {
208 let denied = json!({"noToken": true, "refreshError": "the app is not granted Chat.Read"});
205 let denied =
209 let browser = start_browser(vec![denied.clone(), denied], BOTH_TABS.to_vec()).await;
206 json!({"noToken": true, "refreshError": "the app is not granted ChannelMessage.Read.All"});
207 let browser = start_browser(vec![denied], TEAMS_TAB.to_vec()).await;
210 let session = Session::connect_with(&browser.endpoint, fast_config())
208 let session = Session::connect_with(&browser.endpoint, fast_config())
211 .await
209 .await
212 .unwrap();
210 .unwrap();
@@ -214,7 +212,7 @@ async fn ungranted_scope_in_both_tabs_is_login_required() {
214 .request(
212 .request(
215 Method::Get,
213 Method::Get,
216 "https://graph.microsoft.com/v1.0/me/chats",
214 "https://graph.microsoft.com/v1.0/me/chats",
217 &Scope::graph("Chat.Read"),
215 &Scope::graph("ChannelMessage.Read.All"),
218 None,
216 None,
219 )
217 )
220 .await
218 .await
@@ -225,7 +223,7 @@ async fn ungranted_scope_in_both_tabs_is_login_required() {
225#[tokio::test]
223#[tokio::test]
226async fn missing_token_without_login_tab_is_no_fresh_token() {
224async fn missing_token_without_login_tab_is_no_fresh_token() {
227 let missing = json!({"noToken": true, "refreshError": "invalid_grant"});
225 let missing = json!({"noToken": true, "refreshError": "invalid_grant"});
228 let browser = start_browser(vec![missing; 40], BOTH_TABS.to_vec()).await;
226 let browser = start_browser(vec![missing; 40], TEAMS_TAB.to_vec()).await;
229 let session = Session::connect_with(&browser.endpoint, fast_config())
227 let session = Session::connect_with(&browser.endpoint, fast_config())
230 .await
228 .await
231 .unwrap();
229 .unwrap();
crates/webview/src/fanout.rs +1 −4
@@ -47,18 +47,15 @@ mod tests {
47 47 }
48 48
49 49 #[test]
50 fn publishes_to_the_app_only_and_drops_closed_sinks() {
50 fn publishes_to_the_app_and_drops_closed_sinks() {
51 51 let mut subscribers = Subscribers::default();
52 52 let (teams, mut teams_events) = unbounded_channel();
53 53 let (closed, closed_events) = unbounded_channel();
54 let (outlook, mut outlook_events) = unbounded_channel();
55 54 subscribers.add(App::Teams, teams);
56 55 subscribers.add(App::Teams, closed);
57 subscribers.add(App::Outlook, outlook);
58 56 drop(closed_events);
59 57 subscribers.publish(App::Teams, &event());
60 58 assert_eq!(teams_events.try_recv().unwrap(), event());
61 assert!(outlook_events.try_recv().is_err());
62 59 assert_eq!(subscribers.sinks[&App::Teams].len(), 1);
63 60 }
64 61
@@ -47,18 +47,15 @@ mod tests {
47 }
47 }
48
48
49 #[test]
49 #[test]
50 fn publishes_to_the_app_only_and_drops_closed_sinks() {
50 fn publishes_to_the_app_and_drops_closed_sinks() {
51 let mut subscribers = Subscribers::default();
51 let mut subscribers = Subscribers::default();
52 let (teams, mut teams_events) = unbounded_channel();
52 let (teams, mut teams_events) = unbounded_channel();
53 let (closed, closed_events) = unbounded_channel();
53 let (closed, closed_events) = unbounded_channel();
54 let (outlook, mut outlook_events) = unbounded_channel();
55 subscribers.add(App::Teams, teams);
54 subscribers.add(App::Teams, teams);
56 subscribers.add(App::Teams, closed);
55 subscribers.add(App::Teams, closed);
57 subscribers.add(App::Outlook, outlook);
58 drop(closed_events);
56 drop(closed_events);
59 subscribers.publish(App::Teams, &event());
57 subscribers.publish(App::Teams, &event());
60 assert_eq!(teams_events.try_recv().unwrap(), event());
58 assert_eq!(teams_events.try_recv().unwrap(), event());
61 assert!(outlook_events.try_recv().is_err());
62 assert_eq!(subscribers.sinks[&App::Teams].len(), 1);
59 assert_eq!(subscribers.sinks[&App::Teams].len(), 1);
63 }
60 }
64
61
crates/webview/src/park.rs +3 −3
@@ -82,7 +82,6 @@ mod tests {
82 82 let mut gate = ParkGate::default();
83 83 gate.command_started(App::Teams);
84 84 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
85 assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);
86 85 gate.command_finished(App::Teams);
87 86 assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
88 87 }
@@ -120,10 +119,11 @@ mod tests {
120 119 #[test]
121 120 fn a_restart_forgets_unanswered_commands_but_keeps_holds() {
122 121 let mut gate = ParkGate::default();
123 gate.command_started(App::Outlook);
122 gate.command_started(App::Teams);
123 gate.forget_commands();
124 assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
124 125 gate.hold(App::Teams, true);
125 126 gate.forget_commands();
126 assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);
127 127 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
128 128 }
129 129 }
@@ -82,7 +82,6 @@ mod tests {
82 let mut gate = ParkGate::default();
82 let mut gate = ParkGate::default();
83 gate.command_started(App::Teams);
83 gate.command_started(App::Teams);
84 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
84 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
85 assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);
86 gate.command_finished(App::Teams);
85 gate.command_finished(App::Teams);
87 assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
86 assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
88 }
87 }
@@ -120,10 +119,11 @@ mod tests {
120 #[test]
119 #[test]
121 fn a_restart_forgets_unanswered_commands_but_keeps_holds() {
120 fn a_restart_forgets_unanswered_commands_but_keeps_holds() {
122 let mut gate = ParkGate::default();
121 let mut gate = ParkGate::default();
123 gate.command_started(App::Outlook);
122 gate.command_started(App::Teams);
123 gate.forget_commands();
124 assert_eq!(gate.decide(App::Teams), ParkDecision::Park);
124 gate.hold(App::Teams, true);
125 gate.hold(App::Teams, true);
125 gate.forget_commands();
126 gate.forget_commands();
126 assert_eq!(gate.decide(App::Outlook), ParkDecision::Park);
127 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
127 assert_eq!(gate.decide(App::Teams), ParkDecision::Wait);
128 }
128 }
129}
129}
crates/webview/src/sleep.rs +4 −2
@@ -252,11 +252,13 @@ mod tests {
252 252 assert!(!sleep.wake());
253 253 assert_eq!(sleep.admit(App::Teams, 1), None);
254 254 assert_eq!(sleep.admit(App::Teams, 2), None);
255 assert_eq!(sleep.admit(App::Outlook, 3), None);
256 255 assert!(!sleep.should_sleep(idle(), sleep.last_use + SLEEP_AFTER));
257 256 assert_eq!(sleep.loaded(App::Teams), vec![1, 2]);
258 257 assert_eq!(sleep.admit(App::Teams, 4), Some(4));
258 sleep.fall_asleep();
259 assert!(sleep.wake());
260 assert_eq!(sleep.admit(App::Teams, 3), None);
259 261 assert_eq!(sleep.reset(), vec![3]);
260 assert_eq!(sleep.admit(App::Outlook, 5), Some(5));
262 assert_eq!(sleep.admit(App::Teams, 5), Some(5));
261 263 }
262 264 }
@@ -252,11 +252,13 @@ mod tests {
252 assert!(!sleep.wake());
252 assert!(!sleep.wake());
253 assert_eq!(sleep.admit(App::Teams, 1), None);
253 assert_eq!(sleep.admit(App::Teams, 1), None);
254 assert_eq!(sleep.admit(App::Teams, 2), None);
254 assert_eq!(sleep.admit(App::Teams, 2), None);
255 assert_eq!(sleep.admit(App::Outlook, 3), None);
256 assert!(!sleep.should_sleep(idle(), sleep.last_use + SLEEP_AFTER));
255 assert!(!sleep.should_sleep(idle(), sleep.last_use + SLEEP_AFTER));
257 assert_eq!(sleep.loaded(App::Teams), vec![1, 2]);
256 assert_eq!(sleep.loaded(App::Teams), vec![1, 2]);
258 assert_eq!(sleep.admit(App::Teams, 4), Some(4));
257 assert_eq!(sleep.admit(App::Teams, 4), Some(4));
258 sleep.fall_asleep();
259 assert!(sleep.wake());
260 assert_eq!(sleep.admit(App::Teams, 3), None);
259 assert_eq!(sleep.reset(), vec![3]);
261 assert_eq!(sleep.reset(), vec![3]);
260 assert_eq!(sleep.admit(App::Outlook, 5), Some(5));
262 assert_eq!(sleep.admit(App::Teams, 5), Some(5));
261 }
263 }
262}
264}
crates/webview/src/transport.rs +6 −14
@@ -238,17 +238,12 @@ mod tests {
238 238 async fn calls_reach_the_ui_thread_and_answers_come_back() {
239 239 let ui = fake_ui();
240 240 ui.state.send_replace(ready(&[]));
241 let (control, events) = ui
242 .transport
243 .open(App::Outlook, false)
244 .await
245 .unwrap()
246 .unwrap();
241 let (control, events) = ui.transport.open(App::Teams, false).await.unwrap().unwrap();
247 242 assert!(events.is_none());
248 243 let requests = ui.requests;
249 244 let answer = tokio::task::spawn_blocking(move || match requests.recv().unwrap() {
250 245 UiRequest::Call { app, command } => {
251 assert_eq!(app, App::Outlook);
246 assert_eq!(app, App::Teams);
252 247 assert_eq!(command.method, "Page.reload");
253 248 command.respond(Ok(json!({"done": true})));
254 249 }
@@ -280,13 +275,10 @@ mod tests {
280 275 #[tokio::test]
281 276 async fn diagnose_sees_a_login_page() {
282 277 let ui = fake_ui();
283 ui.state.send_replace(ready(&[
284 (
285 App::Teams,
286 "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
287 ),
288 (App::Outlook, "https://outlook.cloud.microsoft/mail/"),
289 ]));
278 ui.state.send_replace(ready(&[(
279 App::Teams,
280 "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
281 )]));
290 282 let diagnosis = ui.transport.diagnose().await.unwrap();
291 283 assert!(diagnosis.login_pending);
292 284 assert!(diagnosis.app_tab_open);
@@ -238,17 +238,12 @@ mod tests {
238 async fn calls_reach_the_ui_thread_and_answers_come_back() {
238 async fn calls_reach_the_ui_thread_and_answers_come_back() {
239 let ui = fake_ui();
239 let ui = fake_ui();
240 ui.state.send_replace(ready(&[]));
240 ui.state.send_replace(ready(&[]));
241 let (control, events) = ui
241 let (control, events) = ui.transport.open(App::Teams, false).await.unwrap().unwrap();
242 .transport
243 .open(App::Outlook, false)
244 .await
245 .unwrap()
246 .unwrap();
247 assert!(events.is_none());
242 assert!(events.is_none());
248 let requests = ui.requests;
243 let requests = ui.requests;
249 let answer = tokio::task::spawn_blocking(move || match requests.recv().unwrap() {
244 let answer = tokio::task::spawn_blocking(move || match requests.recv().unwrap() {
250 UiRequest::Call { app, command } => {
245 UiRequest::Call { app, command } => {
251 assert_eq!(app, App::Outlook);
246 assert_eq!(app, App::Teams);
252 assert_eq!(command.method, "Page.reload");
247 assert_eq!(command.method, "Page.reload");
253 command.respond(Ok(json!({"done": true})));
248 command.respond(Ok(json!({"done": true})));
254 }
249 }
@@ -280,13 +275,10 @@ mod tests {
280 #[tokio::test]
275 #[tokio::test]
281 async fn diagnose_sees_a_login_page() {
276 async fn diagnose_sees_a_login_page() {
282 let ui = fake_ui();
277 let ui = fake_ui();
283 ui.state.send_replace(ready(&[
278 ui.state.send_replace(ready(&[(
284 (
279 App::Teams,
285 App::Teams,
280 "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
286 "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
281 )]));
287 ),
288 (App::Outlook, "https://outlook.cloud.microsoft/mail/"),
289 ]));
290 let diagnosis = ui.transport.diagnose().await.unwrap();
282 let diagnosis = ui.transport.diagnose().await.unwrap();
291 assert!(diagnosis.login_pending);
283 assert!(diagnosis.login_pending);
292 assert!(diagnosis.app_tab_open);
284 assert!(diagnosis.app_tab_open);