BlueGit

ict rusty-teams

feat(calls): 1:1 and group calls, incoming ring, meeting join with roster

| Before | After |
|---|---|
| Only the test call | Phone button in 1:1 and group chat headers; Calling and Ringing tiles; notices for declined, no answer, not available |
| No incoming calls | Rusty Teams registers as a ringable endpoint; ring toast with Decline / Accept and ring tone; missed calls in Activity; "Accept ends current call" during a call |
| No meetings | Join button on chats with a running meeting; joins muted; participant tiles with mute icons and speaking ring, "+n" past 9; lobby state; Leave, and End meeting for organizers |

- Calling engine runs always (registrar + its own Trouter instance), starts off the UI thread, logs and retries failures (1 s, 2 s, 5 s, then every 10 s), never blocks startup.
- SDP translator now also handles Teams offers (incoming calls).
- Direct-to-mixer media renegotiation when a third person joins.
- Never declines automatically: a ring timeout only stops ringing here.
- Verified live: echo test call in the app (Linux), always-on engine and echo call on Windows (console probes), a self-created Meet now meeting joined, roster of 1, ended for everyone (2 runs). Not yet verified with a second person: outgoing 1:1, incoming ring/accept, renegotiation, meetings with others, lobby.

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-10 · 7 weeks ago

Hash
f2d5d5c732cfe731fff457de08020b29bf919fca
Parent
00d18bb3
51 files changed +6085 −505
Cargo.lock +1 −0
@@ -978,6 +978,7 @@ dependencies = [
978 978 "thiserror 2.0.21",
979 979 "tokio",
980 980 "uuid",
981 "webview",
981 982 ]
982 983
983 984 [[package]]
@@ -978,6 +978,7 @@ dependencies = [
978 "thiserror 2.0.21",
978 "thiserror 2.0.21",
979 "tokio",
979 "tokio",
980 "uuid",
980 "uuid",
981 "webview",
981]
982]
982
983
983[[package]]
984[[package]]
README.md +4 −1
@@ -59,6 +59,9 @@
59 59
60 60 **Calls**
61 61 - Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats
62 - Phone button in 1:1 and group chat headers: callee tiles show Calling and Ringing, Cancel while ringing, notices like "Bea declined" or "No answer"
63 - Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity
64 - Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer
62 65
63 66 **App**
64 67 - Dark theme, opens instantly from the cache
@@ -72,7 +75,7 @@
72 75 | 🪟 Windows | Main target. Login through an embedded WebView2 |
73 76 | 🐧 Linux | Connects to a Chrome started with `--remote-debugging-port=9222`. Built-in login is planned |
74 77
75 Calls, meetings and channel tabs are planned, see [ROADMAP.md](ROADMAP.md).
78 Video, screen sharing and the remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
76 79
77 80 ## Quick start
78 81
@@ -59,6 +59,9 @@
59
59
60**Calls**
60**Calls**
61- Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats
61- Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats
62- Phone button in 1:1 and group chat headers: callee tiles show Calling and Ringing, Cancel while ringing, notices like "Bea declined" or "No answer"
63- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity
64- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer
62
65
63**App**
66**App**
64- Dark theme, opens instantly from the cache
67- Dark theme, opens instantly from the cache
@@ -72,7 +75,7 @@
72| 🪟 Windows | Main target. Login through an embedded WebView2 |
75| 🪟 Windows | Main target. Login through an embedded WebView2 |
73| 🐧 Linux | Connects to a Chrome started with `--remote-debugging-port=9222`. Built-in login is planned |
76| 🐧 Linux | Connects to a Chrome started with `--remote-debugging-port=9222`. Built-in login is planned |
74
77
75Calls, meetings and channel tabs are planned, see [ROADMAP.md](ROADMAP.md).
78Video, screen sharing and the remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
76
79
77## Quick start
80## Quick start
78
81
ROADMAP.md +5 −5
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 87 %** (76 done, 1 partial, 11 missing of 88). Partial counts half.
5 **Parity: 89 %** (76 done, 4 partial, 8 missing of 88). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18 18 | [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
19 19 | [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20 20 | [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21 | [Calls and meetings](#calls-and-meetings) | 17 % | 1 | 0 | 5 |
21 | [Calls and meetings](#calls-and-meetings) | 42 % | 1 | 3 | 2 |
22 22
23 23 ## Next
24 24
@@ -164,9 +164,9 @@ Feature parity with the Microsoft Teams desktop client.
164 164 | Feature | State | Note |
165 165 |---|---|---|
166 166 | Test call (Echo bot) | Done | Native libwebrtc audio, call view, mini window, mute, devices |
167 | Incoming call: ring, accept, decline | Missing | Native (no webview): ring toast, registrar endpoint, attach + accept |
168 | 1:1 and group calls | Missing | |
169 | Join a meeting from a chat | Missing | |
167 | Incoming call: ring, accept, decline | Partial | Ring toast, ring tone, missed call in Activity, registrar endpoint, attach + accept. Built from the Teams code, not yet rung by a second person |
168 | 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
169 | Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
170 170 | Screen sharing | Missing | |
171 171 | In a call shown in presence | Missing | |
172 172
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 87 %** (76 done, 1 partial, 11 missing of 88). Partial counts half.
5**Parity: 89 %** (76 done, 4 partial, 8 missing of 88). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
18| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
20| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21| [Calls and meetings](#calls-and-meetings) | 17 % | 1 | 0 | 5 |
21| [Calls and meetings](#calls-and-meetings) | 42 % | 1 | 3 | 2 |
22
22
23## Next
23## Next
24
24
@@ -164,9 +164,9 @@ Feature parity with the Microsoft Teams desktop client.
164| Feature | State | Note |
164| Feature | State | Note |
165|---|---|---|
165|---|---|---|
166| Test call (Echo bot) | Done | Native libwebrtc audio, call view, mini window, mute, devices |
166| Test call (Echo bot) | Done | Native libwebrtc audio, call view, mini window, mute, devices |
167| Incoming call: ring, accept, decline | Missing | Native (no webview): ring toast, registrar endpoint, attach + accept |
167| Incoming call: ring, accept, decline | Partial | Ring toast, ring tone, missed call in Activity, registrar endpoint, attach + accept. Built from the Teams code, not yet rung by a second person |
168| 1:1 and group calls | Missing | |
168| 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
169| Join a meeting from a chat | Missing | |
169| Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
170| Screen sharing | Missing | |
170| Screen sharing | Missing | |
171| In a call shown in presence | Missing | |
171| In a call shown in presence | Missing | |
172
172
crates/app/src/activity/feed.rs +60 −1
@@ -14,6 +14,7 @@ pub enum Kind {
14 14 Messages,
15 15 Mention,
16 16 Reaction,
17 MissedCall,
17 18 }
18 19
19 20 impl Kind {
@@ -22,11 +23,12 @@ impl Kind {
22 23 Kind::Messages => "messages",
23 24 Kind::Mention => "mention",
24 25 Kind::Reaction => "reaction",
26 Kind::MissedCall => "missed_call",
25 27 }
26 28 }
27 29
28 30 fn from_key(key: &str) -> Option<Kind> {
29 [Kind::Messages, Kind::Mention, Kind::Reaction]
31 [Kind::Messages, Kind::Mention, Kind::Reaction, Kind::MissedCall]
30 32 .into_iter()
31 33 .find(|kind| kind.key() == key)
32 34 }
@@ -340,6 +342,36 @@ impl Feed {
340 342 self.dirty.insert(entry.id);
341 343 }
342 344
345 pub fn record_missed_call(&mut self, conversation_id: &str, actor: Actor, at: DateTime<Utc>) {
346 let open_row = self.entries.iter().position(|entry| {
347 entry.kind == Kind::MissedCall
348 && !entry.read
349 && entry.actors.first().is_some_and(|known| known.user_id == actor.user_id && known.name == actor.name)
350 });
351 match open_row {
352 Some(index) => {
353 let entry = &mut self.entries[index];
354 entry.count += 1;
355 entry.updated_at = at;
356 self.dirty.insert(entry.id);
357 }
358 None => {
359 self.add(Entry {
360 id: 0,
361 conversation_id: conversation_id.to_owned(),
362 kind: Kind::MissedCall,
363 message_id: String::new(),
364 actors: vec![actor],
365 preview: String::new(),
366 glyphs: Vec::new(),
367 count: 1,
368 updated_at: at,
369 read: false,
370 });
371 }
372 }
373 }
374
343 375 pub fn record_chat_preview(
344 376 &mut self,
345 377 conversation_id: &str,
@@ -837,4 +869,31 @@ mod tests {
837 869 );
838 870 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
839 871 }
872 #[test]
873 fn a_missed_call_is_one_row_per_caller_until_it_is_read() {
874 let mut feed = Feed::load(Vec::new());
875 let caller = Actor { user_id: Some("u1".into()), name: "Cara".into() };
876 feed.record_missed_call("19:dm", caller.clone(), at(9, 0));
877 feed.record_missed_call("19:dm", caller.clone(), at(9, 5));
878 assert_eq!(feed.unread_count(), 1);
879 let entry = feed.get(1).unwrap();
880 assert_eq!(entry.kind, Kind::MissedCall);
881 assert_eq!(entry.count, 2);
882 assert_eq!(entry.updated_at, at(9, 5));
883 feed.mark_all_read();
884 feed.record_missed_call("19:dm", caller, at(10, 0));
885 assert_eq!(feed.unread_count(), 1);
886 feed.record_missed_call("19:other", Actor { user_id: Some("u2".into()), name: "Dan".into() }, at(10, 1));
887 assert_eq!(feed.unread_count(), 2);
888 }
889
890 #[test]
891 fn missed_calls_survive_the_store_round_trip() {
892 let mut feed = Feed::load(Vec::new());
893 feed.record_missed_call("19:dm", Actor { user_id: Some("u1".into()), name: "Cara".into() }, at(9, 0));
894 let record = feed.get(1).unwrap().to_record();
895 assert_eq!(record.kind, "missed_call");
896 let restored = Entry::from_record(record).unwrap();
897 assert_eq!(restored.kind, Kind::MissedCall);
898 }
840 899 }
@@ -14,6 +14,7 @@ pub enum Kind {
14 Messages,
14 Messages,
15 Mention,
15 Mention,
16 Reaction,
16 Reaction,
17 MissedCall,
17}
18}
18
19
19impl Kind {
20impl Kind {
@@ -22,11 +23,12 @@ impl Kind {
22 Kind::Messages => "messages",
23 Kind::Messages => "messages",
23 Kind::Mention => "mention",
24 Kind::Mention => "mention",
24 Kind::Reaction => "reaction",
25 Kind::Reaction => "reaction",
26 Kind::MissedCall => "missed_call",
25 }
27 }
26 }
28 }
27
29
28 fn from_key(key: &str) -> Option<Kind> {
30 fn from_key(key: &str) -> Option<Kind> {
29 [Kind::Messages, Kind::Mention, Kind::Reaction]
31 [Kind::Messages, Kind::Mention, Kind::Reaction, Kind::MissedCall]
30 .into_iter()
32 .into_iter()
31 .find(|kind| kind.key() == key)
33 .find(|kind| kind.key() == key)
32 }
34 }
@@ -340,6 +342,36 @@ impl Feed {
340 self.dirty.insert(entry.id);
342 self.dirty.insert(entry.id);
341 }
343 }
342
344
345 pub fn record_missed_call(&mut self, conversation_id: &str, actor: Actor, at: DateTime<Utc>) {
346 let open_row = self.entries.iter().position(|entry| {
347 entry.kind == Kind::MissedCall
348 && !entry.read
349 && entry.actors.first().is_some_and(|known| known.user_id == actor.user_id && known.name == actor.name)
350 });
351 match open_row {
352 Some(index) => {
353 let entry = &mut self.entries[index];
354 entry.count += 1;
355 entry.updated_at = at;
356 self.dirty.insert(entry.id);
357 }
358 None => {
359 self.add(Entry {
360 id: 0,
361 conversation_id: conversation_id.to_owned(),
362 kind: Kind::MissedCall,
363 message_id: String::new(),
364 actors: vec![actor],
365 preview: String::new(),
366 glyphs: Vec::new(),
367 count: 1,
368 updated_at: at,
369 read: false,
370 });
371 }
372 }
373 }
374
343 pub fn record_chat_preview(
375 pub fn record_chat_preview(
344 &mut self,
376 &mut self,
345 conversation_id: &str,
377 conversation_id: &str,
@@ -837,4 +869,31 @@ mod tests {
837 );
869 );
838 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
870 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
839 }
871 }
872 #[test]
873 fn a_missed_call_is_one_row_per_caller_until_it_is_read() {
874 let mut feed = Feed::load(Vec::new());
875 let caller = Actor { user_id: Some("u1".into()), name: "Cara".into() };
876 feed.record_missed_call("19:dm", caller.clone(), at(9, 0));
877 feed.record_missed_call("19:dm", caller.clone(), at(9, 5));
878 assert_eq!(feed.unread_count(), 1);
879 let entry = feed.get(1).unwrap();
880 assert_eq!(entry.kind, Kind::MissedCall);
881 assert_eq!(entry.count, 2);
882 assert_eq!(entry.updated_at, at(9, 5));
883 feed.mark_all_read();
884 feed.record_missed_call("19:dm", caller, at(10, 0));
885 assert_eq!(feed.unread_count(), 1);
886 feed.record_missed_call("19:other", Actor { user_id: Some("u2".into()), name: "Dan".into() }, at(10, 1));
887 assert_eq!(feed.unread_count(), 2);
888 }
889
890 #[test]
891 fn missed_calls_survive_the_store_round_trip() {
892 let mut feed = Feed::load(Vec::new());
893 feed.record_missed_call("19:dm", Actor { user_id: Some("u1".into()), name: "Cara".into() }, at(9, 0));
894 let record = feed.get(1).unwrap().to_record();
895 assert_eq!(record.kind, "missed_call");
896 let restored = Entry::from_record(record).unwrap();
897 assert_eq!(restored.kind, Kind::MissedCall);
898 }
840}
899}
crates/app/src/activity/service.rs +12 −0
@@ -7,6 +7,7 @@ use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time
7 7 use super::preview_label;
8 8 use super::reactions::reacted_messages;
9 9 use crate::app_state::{AppEvent, AppState};
10 use crate::call::MissedCall;
10 11 use crate::demo;
11 12 use crate::notify::{IncomingTracker, channel_alerts};
12 13 use crate::people::resolve_names;
@@ -72,10 +73,21 @@ impl ActivityCenter {
72 73 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
73 74 AppEvent::Selection => self.on_selection(cx),
74 75 AppEvent::Sidebar => self.on_sidebar(cx),
76 AppEvent::MissedCall(missed) => self.on_missed_call(missed, cx),
75 77 _ => {}
76 78 }
77 79 }
78 80
81 fn on_missed_call(&mut self, missed: &MissedCall, cx: &mut Context<Self>) {
82 let conversation_id = self.app.read(cx).conversation_of_missed_call(missed).unwrap_or_default();
83 let actor = Actor {
84 user_id: missed.caller_mri.strip_prefix("8:orgid:").map(str::to_owned),
85 name: missed.caller_name.clone(),
86 };
87 self.feed.record_missed_call(&conversation_id, actor, missed.at);
88 self.flush(cx);
89 }
90
79 91 fn on_selection(&mut self, cx: &mut Context<Self>) {
80 92 let selected = self
81 93 .app
@@ -7,6 +7,7 @@ use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time
7use super::preview_label;
7use super::preview_label;
8use super::reactions::reacted_messages;
8use super::reactions::reacted_messages;
9use crate::app_state::{AppEvent, AppState};
9use crate::app_state::{AppEvent, AppState};
10use crate::call::MissedCall;
10use crate::demo;
11use crate::demo;
11use crate::notify::{IncomingTracker, channel_alerts};
12use crate::notify::{IncomingTracker, channel_alerts};
12use crate::people::resolve_names;
13use crate::people::resolve_names;
@@ -72,10 +73,21 @@ impl ActivityCenter {
72 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
73 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
73 AppEvent::Selection => self.on_selection(cx),
74 AppEvent::Selection => self.on_selection(cx),
74 AppEvent::Sidebar => self.on_sidebar(cx),
75 AppEvent::Sidebar => self.on_sidebar(cx),
76 AppEvent::MissedCall(missed) => self.on_missed_call(missed, cx),
75 _ => {}
77 _ => {}
76 }
78 }
77 }
79 }
78
80
81 fn on_missed_call(&mut self, missed: &MissedCall, cx: &mut Context<Self>) {
82 let conversation_id = self.app.read(cx).conversation_of_missed_call(missed).unwrap_or_default();
83 let actor = Actor {
84 user_id: missed.caller_mri.strip_prefix("8:orgid:").map(str::to_owned),
85 name: missed.caller_name.clone(),
86 };
87 self.feed.record_missed_call(&conversation_id, actor, missed.at);
88 self.flush(cx);
89 }
90
79 fn on_selection(&mut self, cx: &mut Context<Self>) {
91 fn on_selection(&mut self, cx: &mut Context<Self>) {
80 let selected = self
92 let selected = self
81 .app
93 .app
crates/app/src/app_state.rs +15 −1
@@ -12,7 +12,8 @@ use teams_core::{
12 12 };
13 13
14 14 use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15 use crate::call::{ActiveCall, CallLauncher};
15 use crate::call::{ActiveCall, CallLauncher, MissedCall, Rings};
16 use calling::meeting::LiveMeeting;
16 17 use crate::card_state::{CardState, TaskDialogState};
17 18 use crate::data::{self, Directory};
18 19 use crate::local_previews::{LocalPreview, load_local_previews};
@@ -59,6 +60,9 @@ pub enum AppEvent {
59 60 NotificationSettings,
60 61 Profile,
61 62 Call,
63 Ring,
64 LiveMeeting,
65 MissedCall(MissedCall),
62 66 }
63 67
64 68 #[derive(Debug, Clone, Copy, Default)]
@@ -108,6 +112,9 @@ pub struct AppState {
108 112 pub call: Option<ActiveCall>,
109 113 pub call_launcher: Option<Arc<CallLauncher>>,
110 114 pub call_count: u64,
115 pub rings: Rings,
116 pub live_meetings: HashMap<String, LiveMeeting>,
117 pub live_refreshing: HashSet<String>,
111 118 }
112 119
113 120 pub struct AppHandle(pub Entity<AppState>);
@@ -194,6 +201,9 @@ impl AppState {
194 201 call: None,
195 202 call_launcher: None,
196 203 call_count: 0,
204 rings: Rings::default(),
205 live_meetings: HashMap::new(),
206 live_refreshing: HashSet::new(),
197 207 };
198 208 state.local_previews = load_local_previews(&state.store);
199 209 state.collapsed = state.load_collapsed();
@@ -576,10 +586,12 @@ impl AppState {
576 586 if !was_drafting && self.selection.as_ref() == Some(&selection) {
577 587 return;
578 588 }
589 let conversation_id = selection.conversation_id().to_owned();
579 590 self.selection = Some(selection);
580 591 self.keep_unread = None;
581 592 cx.emit(AppEvent::Selection);
582 593 cx.notify();
594 self.refresh_live_meeting(&conversation_id, cx);
583 595 }
584 596
585 597 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
@@ -687,6 +699,8 @@ impl AppState {
687 699 cx.emit(AppEvent::Status);
688 700 }
689 701 BackendEvent::Calls(launcher) => self.call_launcher = Some(launcher),
702 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
703 BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),
690 704 BackendEvent::Engine(engine) => {
691 705 self.engine = Some(engine);
692 706 self.resend_outbox(cx);
@@ -12,7 +12,8 @@ use teams_core::{
12};
12};
13
13
14use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
14use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15use crate::call::{ActiveCall, CallLauncher};
15use crate::call::{ActiveCall, CallLauncher, MissedCall, Rings};
16use calling::meeting::LiveMeeting;
16use crate::card_state::{CardState, TaskDialogState};
17use crate::card_state::{CardState, TaskDialogState};
17use crate::data::{self, Directory};
18use crate::data::{self, Directory};
18use crate::local_previews::{LocalPreview, load_local_previews};
19use crate::local_previews::{LocalPreview, load_local_previews};
@@ -59,6 +60,9 @@ pub enum AppEvent {
59 NotificationSettings,
60 NotificationSettings,
60 Profile,
61 Profile,
61 Call,
62 Call,
63 Ring,
64 LiveMeeting,
65 MissedCall(MissedCall),
62}
66}
63
67
64#[derive(Debug, Clone, Copy, Default)]
68#[derive(Debug, Clone, Copy, Default)]
@@ -108,6 +112,9 @@ pub struct AppState {
108 pub call: Option<ActiveCall>,
112 pub call: Option<ActiveCall>,
109 pub call_launcher: Option<Arc<CallLauncher>>,
113 pub call_launcher: Option<Arc<CallLauncher>>,
110 pub call_count: u64,
114 pub call_count: u64,
115 pub rings: Rings,
116 pub live_meetings: HashMap<String, LiveMeeting>,
117 pub live_refreshing: HashSet<String>,
111}
118}
112
119
113pub struct AppHandle(pub Entity<AppState>);
120pub struct AppHandle(pub Entity<AppState>);
@@ -194,6 +201,9 @@ impl AppState {
194 call: None,
201 call: None,
195 call_launcher: None,
202 call_launcher: None,
196 call_count: 0,
203 call_count: 0,
204 rings: Rings::default(),
205 live_meetings: HashMap::new(),
206 live_refreshing: HashSet::new(),
197 };
207 };
198 state.local_previews = load_local_previews(&state.store);
208 state.local_previews = load_local_previews(&state.store);
199 state.collapsed = state.load_collapsed();
209 state.collapsed = state.load_collapsed();
@@ -576,10 +586,12 @@ impl AppState {
576 if !was_drafting && self.selection.as_ref() == Some(&selection) {
586 if !was_drafting && self.selection.as_ref() == Some(&selection) {
577 return;
587 return;
578 }
588 }
589 let conversation_id = selection.conversation_id().to_owned();
579 self.selection = Some(selection);
590 self.selection = Some(selection);
580 self.keep_unread = None;
591 self.keep_unread = None;
581 cx.emit(AppEvent::Selection);
592 cx.emit(AppEvent::Selection);
582 cx.notify();
593 cx.notify();
594 self.refresh_live_meeting(&conversation_id, cx);
583 }
595 }
584
596
585 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
597 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
@@ -687,6 +699,8 @@ impl AppState {
687 cx.emit(AppEvent::Status);
699 cx.emit(AppEvent::Status);
688 }
700 }
689 BackendEvent::Calls(launcher) => self.call_launcher = Some(launcher),
701 BackendEvent::Calls(launcher) => self.call_launcher = Some(launcher),
702 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
703 BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),
690 BackendEvent::Engine(engine) => {
704 BackendEvent::Engine(engine) => {
691 self.engine = Some(engine);
705 self.engine = Some(engine);
692 self.resend_outbox(cx);
706 self.resend_outbox(cx);
crates/app/src/backend.rs +36 −3
@@ -1,6 +1,7 @@
1 1 use std::sync::Arc;
2 2 use std::time::Duration;
3 3
4 use calling::EngineEvent;
4 5 use chatsvc::{EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
5 6 use chrono::{DateTime, Utc};
6 7 use graph::Graph;
@@ -47,6 +48,8 @@ pub enum BackendEvent {
47 48 Connection(ConnectionState),
48 49 Engine(Arc<Engine>),
49 50 Calls(Arc<CallLauncher>),
51 Ring(EngineEvent),
52 ThreadChanged(String),
50 53 Core(CoreEvent),
51 54 Live(LiveState),
52 55 Typing(TypingEvent),
@@ -95,13 +98,14 @@ pub fn live_state_for(kind: StatusKind) -> LiveState {
95 98 pub fn start(
96 99 store: Arc<Store>,
97 100 transport: Arc<dyn Transport>,
101 ringable: bool,
98 102 ) -> mpsc::UnboundedReceiver<BackendEvent> {
99 103 let (sender, receiver) = mpsc::unbounded_channel();
100 crate::runtime::handle().spawn(supervise(store, transport, sender));
104 crate::runtime::handle().spawn(supervise(store, transport, ringable, sender));
101 105 receiver
102 106 }
103 107
104 async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, events: EventSender) {
108 async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: bool, events: EventSender) {
105 109 let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
106 110 let session = loop {
107 111 match Session::with_transport(transport.clone(), SessionConfig::default()).await {
@@ -125,7 +129,11 @@ async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, events: Eve
125 129 .unwrap_or_else(build);
126 130 let engine = Arc::new(engine);
127 131 let _ = events.send(BackendEvent::Engine(engine.clone()));
128 let _ = events.send(BackendEvent::Calls(Arc::new(CallLauncher::new(transport))));
132 let ring_events = events.clone();
133 let launcher = CallLauncher::start(transport, ringable, move |event| {
134 let _ = ring_events.send(BackendEvent::Ring(event));
135 });
136 let _ = events.send(BackendEvent::Calls(launcher));
129 137 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
130 138 let (nudge, nudges) = mpsc::unbounded_channel();
131 139 tokio::spawn(realtime_loop(
@@ -198,6 +206,9 @@ async fn realtime_loop(
198 206 match event {
199 207 RealtimeEvent::Message(message) => {
200 208 let _ = events.send(BackendEvent::Live(LiveState::Live));
209 if let Some(conversation_id) = thread_signal(&message) {
210 let _ = events.send(BackendEvent::ThreadChanged(conversation_id));
211 }
201 212 let receipt_engine = engine.clone();
202 213 let receipt_event = message.clone();
203 214 engine.handle_pin_event(&message);
@@ -253,6 +264,14 @@ async fn presence_resubscribe_loop(engine: Arc<Engine>) {
253 264 }
254 265 }
255 266
267 /// A thread update or a new message in a chat can start or end a meeting (the call bubble is a message).
268 pub fn thread_signal(event: &MessageEvent) -> Option<String> {
269 match event.kind {
270 EventKind::ThreadUpdate | EventKind::NewMessage => event.conversation_id.clone(),
271 _ => None,
272 }
273 }
274
256 275 pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
257 276 let conversation_id = event.conversation_id.clone()?;
258 277 match event.kind {
@@ -366,6 +385,20 @@ mod tests {
366 385 );
367 386 }
368 387
388 #[test]
389 fn thread_updates_and_new_messages_signal_a_possible_meeting_change() {
390 assert_eq!(
391 thread_signal(&event(EventKind::ThreadUpdate, Some("c"), None)).as_deref(),
392 Some("c")
393 );
394 assert_eq!(
395 thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(),
396 Some("c")
397 );
398 assert_eq!(thread_signal(&event(EventKind::Typing, Some("c"), None)), None);
399 assert_eq!(thread_signal(&event(EventKind::ThreadUpdate, None, None)), None);
400 }
401
369 402 #[test]
370 403 fn typing_and_missing_conversation_are_ignored() {
371 404 assert_eq!(
@@ -1,6 +1,7 @@
1use std::sync::Arc;
1use std::sync::Arc;
2use std::time::Duration;
2use std::time::Duration;
3
3
4use calling::EngineEvent;
4use chatsvc::{EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
5use chatsvc::{EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
5use chrono::{DateTime, Utc};
6use chrono::{DateTime, Utc};
6use graph::Graph;
7use graph::Graph;
@@ -47,6 +48,8 @@ pub enum BackendEvent {
47 Connection(ConnectionState),
48 Connection(ConnectionState),
48 Engine(Arc<Engine>),
49 Engine(Arc<Engine>),
49 Calls(Arc<CallLauncher>),
50 Calls(Arc<CallLauncher>),
51 Ring(EngineEvent),
52 ThreadChanged(String),
50 Core(CoreEvent),
53 Core(CoreEvent),
51 Live(LiveState),
54 Live(LiveState),
52 Typing(TypingEvent),
55 Typing(TypingEvent),
@@ -95,13 +98,14 @@ pub fn live_state_for(kind: StatusKind) -> LiveState {
95pub fn start(
98pub fn start(
96 store: Arc<Store>,
99 store: Arc<Store>,
97 transport: Arc<dyn Transport>,
100 transport: Arc<dyn Transport>,
101 ringable: bool,
98) -> mpsc::UnboundedReceiver<BackendEvent> {
102) -> mpsc::UnboundedReceiver<BackendEvent> {
99 let (sender, receiver) = mpsc::unbounded_channel();
103 let (sender, receiver) = mpsc::unbounded_channel();
100 crate::runtime::handle().spawn(supervise(store, transport, sender));
104 crate::runtime::handle().spawn(supervise(store, transport, ringable, sender));
101 receiver
105 receiver
102}
106}
103
107
104async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, events: EventSender) {
108async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: bool, events: EventSender) {
105 let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
109 let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
106 let session = loop {
110 let session = loop {
107 match Session::with_transport(transport.clone(), SessionConfig::default()).await {
111 match Session::with_transport(transport.clone(), SessionConfig::default()).await {
@@ -125,7 +129,11 @@ async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, events: Eve
125 .unwrap_or_else(build);
129 .unwrap_or_else(build);
126 let engine = Arc::new(engine);
130 let engine = Arc::new(engine);
127 let _ = events.send(BackendEvent::Engine(engine.clone()));
131 let _ = events.send(BackendEvent::Engine(engine.clone()));
128 let _ = events.send(BackendEvent::Calls(Arc::new(CallLauncher::new(transport))));
132 let ring_events = events.clone();
133 let launcher = CallLauncher::start(transport, ringable, move |event| {
134 let _ = ring_events.send(BackendEvent::Ring(event));
135 });
136 let _ = events.send(BackendEvent::Calls(launcher));
129 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
137 tokio::spawn(forward_core_events(engine.clone(), events.clone()));
130 let (nudge, nudges) = mpsc::unbounded_channel();
138 let (nudge, nudges) = mpsc::unbounded_channel();
131 tokio::spawn(realtime_loop(
139 tokio::spawn(realtime_loop(
@@ -198,6 +206,9 @@ async fn realtime_loop(
198 match event {
206 match event {
199 RealtimeEvent::Message(message) => {
207 RealtimeEvent::Message(message) => {
200 let _ = events.send(BackendEvent::Live(LiveState::Live));
208 let _ = events.send(BackendEvent::Live(LiveState::Live));
209 if let Some(conversation_id) = thread_signal(&message) {
210 let _ = events.send(BackendEvent::ThreadChanged(conversation_id));
211 }
201 let receipt_engine = engine.clone();
212 let receipt_engine = engine.clone();
202 let receipt_event = message.clone();
213 let receipt_event = message.clone();
203 engine.handle_pin_event(&message);
214 engine.handle_pin_event(&message);
@@ -253,6 +264,14 @@ async fn presence_resubscribe_loop(engine: Arc<Engine>) {
253 }
264 }
254}
265}
255
266
267/// A thread update or a new message in a chat can start or end a meeting (the call bubble is a message).
268pub fn thread_signal(event: &MessageEvent) -> Option<String> {
269 match event.kind {
270 EventKind::ThreadUpdate | EventKind::NewMessage => event.conversation_id.clone(),
271 _ => None,
272 }
273}
274
256pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
275pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
257 let conversation_id = event.conversation_id.clone()?;
276 let conversation_id = event.conversation_id.clone()?;
258 match event.kind {
277 match event.kind {
@@ -366,6 +385,20 @@ mod tests {
366 );
385 );
367 }
386 }
368
387
388 #[test]
389 fn thread_updates_and_new_messages_signal_a_possible_meeting_change() {
390 assert_eq!(
391 thread_signal(&event(EventKind::ThreadUpdate, Some("c"), None)).as_deref(),
392 Some("c")
393 );
394 assert_eq!(
395 thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(),
396 Some("c")
397 );
398 assert_eq!(thread_signal(&event(EventKind::Typing, Some("c"), None)), None);
399 assert_eq!(thread_signal(&event(EventKind::ThreadUpdate, None, None)), None);
400 }
401
369 #[test]
402 #[test]
370 fn typing_and_missing_conversation_are_ignored() {
403 fn typing_and_missing_conversation_are_ignored() {
371 assert_eq!(
404 assert_eq!(
crates/app/src/call/actions.rs +469 −19
@@ -1,15 +1,32 @@
1 1 use std::time::{Duration, Instant};
2 2
3 use calling::{CallCommand, CallHandle, CallUpdate, DeviceChoice, MuteCommand};
3 use calling::meeting::LiveMeeting;
4 use calling::{CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, RingSignal};
4 5 use gpui_kit::*;
5 6
6 use super::demo::start_demo_call;
7 use super::model::{ActiveCall, CallModel, TEST_CALL_TITLE, ended_notice};
8 use crate::app_state::{AppEvent, AppState};
7 use super::demo::{DemoCall, demo_caller, demo_guests, demo_ring, start_demo_call};
8 use super::model::{ActiveCall, CallModel, ended_notice};
9 use super::ring::{MissedCall, RingOutcome};
10 use super::target::{is_organizer, plan_for_chat};
11 use crate::app_state::{AppEvent, AppState, Selection, chat_title};
12 use crate::notify::selection_for;
9 13
10 14 const TIMER_REFRESH: Duration = Duration::from_millis(500);
11 15 const NOT_CONNECTED_NOTICE: &str = "Not connected to Teams yet";
12 16 const READ_ONLY_NOTICE: &str = "Calls are off in read-only mode";
17 const NOT_CALLABLE_NOTICE: &str = "This chat cannot be called";
18 const MEETING_UNAVAILABLE_NOTICE: &str = "This meeting cannot be joined";
19 const ANSWER_FAILED_NOTICE: &str = "Could not answer the call";
20 const MEETING_KIND: &str = "meeting";
21 const DEMO_LOBBY_MEETING: &str = "demo-chat-meeting-retro";
22 const DEMO_CROWD: usize = 11;
23 const DEMO_SMALL_MEETING: usize = 4;
24 const DEMO_LIVE_MINUTES: i64 = 60;
25 const ORGID_PREFIX: &str = "8:orgid:";
26
27 fn now_unix() -> i64 {
28 chrono::Utc::now().timestamp()
29 }
13 30
14 31 impl AppState {
15 32 pub fn start_test_call(&mut self, cx: &mut Context<Self>) {
@@ -17,26 +34,114 @@ impl AppState {
17 34 self.show_call(true, cx);
18 35 return;
19 36 }
20 let handle = if self.mode.demo {
21 start_demo_call()
22 } else if self.mode.read_only {
23 self.raise_notice(READ_ONLY_NOTICE.to_owned(), None, cx);
37 let Some(handle) = self.place_call(CallSpec::Echo, DemoCall::Test, cx) else {
38 return;
39 };
40 self.begin_call(handle, CallModel::test(), None, cx);
41 }
42
43 pub fn start_chat_call(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
44 if self.call.is_some() {
45 self.show_call(true, cx);
46 return;
47 }
48 let plan = self
49 .sidebar
50 .chats
51 .iter()
52 .find(|chat| chat.id == conversation_id)
53 .and_then(|chat| plan_for_chat(chat, self.directory.me.as_ref()));
54 let Some(plan) = plan else {
55 self.raise_notice(NOT_CALLABLE_NOTICE.to_owned(), None, cx);
56 return;
57 };
58 let spec = CallSpec::People {
59 callees: plan
60 .callees
61 .iter()
62 .map(|(mri, name)| Callee {
63 mri: mri.clone(),
64 display_name: name.clone(),
65 })
66 .collect(),
67 thread_id: conversation_id.to_owned(),
68 };
69 let Some(handle) = self.place_call(spec, DemoCall::People(plan.callees.clone()), cx) else {
70 return;
71 };
72 let user_ids = plan
73 .callees
74 .iter()
75 .filter_map(|(mri, _)| mri.strip_prefix(ORGID_PREFIX).map(str::to_owned))
76 .collect();
77 self.request_avatars(user_ids, cx);
78 let model = CallModel::people(&plan.title, &plan.callees);
79 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
80 }
81
82 pub fn join_meeting_call(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
83 if self.call.is_some() {
84 self.show_call(true, cx);
85 return;
86 }
87 let Some(meeting) = self.running_meeting(conversation_id).cloned() else {
88 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
89 return;
90 };
91 let Some(target) = meeting.target() else {
92 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
24 93 return;
25 } else if let Some(launcher) = self.call_launcher.clone() {
26 launcher.start_test_call()
27 } else {
28 self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);
94 };
95 let guests = if conversation_id == DEMO_LOBBY_MEETING { DEMO_SMALL_MEETING } else { DEMO_CROWD };
96 let demo = DemoCall::Meeting {
97 guests: demo_guests(guests),
98 lobby: conversation_id == DEMO_LOBBY_MEETING,
99 };
100 let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, cx) else {
29 101 return;
30 102 };
103 let title = selection_for(&self.sidebar, conversation_id)
104 .map(|selection| crate::app_state::selection_title(&self.sidebar, &selection))
105 .unwrap_or_else(|| "Meeting".to_owned());
106 let model = CallModel::meeting(&title, is_organizer(&meeting, self.directory.me.as_ref()));
107 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
108 }
109
110 fn place_call(&mut self, spec: CallSpec, demo: DemoCall, cx: &mut Context<Self>) -> Option<CallHandle> {
111 if self.mode.demo {
112 return Some(start_demo_call(demo));
113 }
114 if self.mode.read_only {
115 self.raise_notice(READ_ONLY_NOTICE.to_owned(), None, cx);
116 return None;
117 }
118 match self.call_launcher.clone() {
119 Some(launcher) => Some(launcher.start_call(spec)),
120 None => {
121 self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);
122 None
123 }
124 }
125 }
126
127 fn begin_call(
128 &mut self,
129 handle: CallHandle,
130 model: CallModel,
131 conversation_id: Option<String>,
132 cx: &mut Context<Self>,
133 ) {
31 134 self.call_count += 1;
32 135 let call_id = self.call_count;
33 136 let CallHandle { commands, updates } = handle;
34 137 self.call = Some(ActiveCall {
35 138 id: call_id,
36 model: CallModel::new(TEST_CALL_TITLE),
139 model,
37 140 commands,
38 141 viewing: true,
142 conversation_id,
39 143 });
144 self.new_chat = false;
40 145 self.follow_call(call_id, updates, cx);
41 146 cx.emit(AppEvent::Call);
42 147 cx.notify();
@@ -75,7 +180,7 @@ impl AppState {
75 180 .detach();
76 181 }
77 182
78 fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {
183 pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {
79 184 let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
80 185 return;
81 186 };
@@ -86,8 +191,9 @@ impl AppState {
86 191 return;
87 192 };
88 193 let elapsed = call.model.elapsed(Instant::now());
194 let notice = ended_notice(&reason, elapsed, &call.model.peer_name);
89 195 self.call = None;
90 self.raise_notice(ended_notice(&reason, elapsed), None, cx);
196 self.raise_notice(notice, None, cx);
91 197 cx.emit(AppEvent::Call);
92 198 cx.notify();
93 199 }
@@ -109,6 +215,13 @@ impl AppState {
109 215 self.send_call_command(CallCommand::Hangup);
110 216 }
111 217
218 pub fn end_meeting_for_all(&mut self, _cx: &mut Context<Self>) {
219 let allowed = self.call.as_ref().is_some_and(|call| call.model.can_end_meeting);
220 if allowed {
221 self.send_call_command(CallCommand::EndMeeting);
222 }
223 }
224
112 225 pub fn select_call_input(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
113 226 self.send_call_command(CallCommand::SelectInput(choice));
114 227 }
@@ -129,22 +242,217 @@ impl AppState {
129 242 cx.notify();
130 243 }
131 244
245 pub fn open_call_chat(&mut self, cx: &mut Context<Self>) {
246 let Some(conversation_id) = self.call.as_ref().and_then(|call| call.conversation_id.clone()) else {
247 return;
248 };
249 if let Some(selection) = selection_for(&self.sidebar, &conversation_id) {
250 self.select(selection, cx);
251 }
252 }
253
132 254 pub fn viewing_call(&self) -> bool {
133 255 self.call.as_ref().is_some_and(|call| call.viewing)
134 256 }
135 257 }
136 258
259 impl AppState {
260 pub fn on_engine_event(&mut self, event: EngineEvent, cx: &mut Context<Self>) {
261 match event {
262 EngineEvent::Incoming(ring) => self.push_ring(ring, false, cx),
263 EngineEvent::RingEnded { ring_id, kind, .. } => {
264 self.signal_ring(ring_id, RingSignal::Remote(kind), cx);
265 }
266 }
267 }
268
269 fn push_ring(&mut self, ring: calling::IncomingRing, demo: bool, cx: &mut Context<Self>) {
270 let caller_user_id = ring.caller.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
271 self.rings.push(ring, demo, Instant::now());
272 if let Some(user_id) = caller_user_id {
273 self.request_avatars(vec![user_id], cx);
274 }
275 cx.emit(AppEvent::Ring);
276 cx.notify();
277 }
278
279 pub fn demo_incoming_ring(&mut self, cx: &mut Context<Self>) {
280 self.push_ring(demo_ring(), true, cx);
281 }
282
283 fn signal_ring(&mut self, ring_id: u64, signal: RingSignal, cx: &mut Context<Self>) {
284 if let Some(outcome) = self.rings.signal(ring_id, signal, Instant::now()) {
285 self.finish_ring(ring_id, outcome, cx);
286 }
287 }
288
289 fn finish_ring(&mut self, ring_id: u64, outcome: RingOutcome, cx: &mut Context<Self>) {
290 if let RingOutcome::Missed(missed) = outcome {
291 if let Some(launcher) = &self.call_launcher {
292 launcher.drop_ring(ring_id);
293 }
294 cx.emit(AppEvent::MissedCall(missed));
295 }
296 cx.emit(AppEvent::Ring);
297 cx.notify();
298 }
299
300 pub fn tick_rings(&mut self, cx: &mut Context<Self>) {
301 if self.rings.is_empty() {
302 return;
303 }
304 for (ring_id, outcome) in self.rings.tick(Instant::now()) {
305 self.finish_ring(ring_id, outcome, cx);
306 }
307 }
308
309 pub fn accept_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {
310 let Some(entry) = self.rings.get(ring_id).cloned() else {
311 return;
312 };
313 if self.call.is_some() {
314 self.leave_call(cx);
315 }
316 self.signal_ring(ring_id, RingSignal::Accept, cx);
317 let conversation_id = entry.ring.thread_id.clone();
318 let title = conversation_id
319 .as_deref()
320 .and_then(|id| self.sidebar.chats.iter().find(|chat| chat.id == id))
321 .filter(|_| entry.ring.is_group)
322 .map(chat_title)
323 .unwrap_or_else(|| entry.caller_name().to_owned());
324 let model = CallModel::incoming(&title, &entry.ring.caller.mri, entry.caller_name());
325 if entry.demo {
326 let handle = start_demo_call(DemoCall::Incoming(demo_caller()));
327 self.begin_call(handle, model, conversation_id, cx);
328 return;
329 }
330 let Some(launcher) = self.call_launcher.clone() else {
331 self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);
332 return;
333 };
334 let receiver = crate::runtime::spawn(async move { launcher.accept_ring(ring_id).await });
335 cx.spawn(async move |this, cx| {
336 let handle = receiver.await.ok().flatten();
337 this.update(cx, |state, cx| match handle {
338 Some(handle) => state.begin_call(handle, model, conversation_id, cx),
339 None => state.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx),
340 })
341 .ok();
342 })
343 .detach();
344 }
345
346 pub fn decline_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {
347 let Some(entry) = self.rings.get(ring_id) else {
348 return;
349 };
350 let demo = entry.demo;
351 if !demo && let Some(launcher) = &self.call_launcher {
352 launcher.decline_ring(ring_id);
353 }
354 self.signal_ring(ring_id, RingSignal::Decline, cx);
355 }
356
357 pub fn conversation_of_missed_call(&self, missed: &MissedCall) -> Option<String> {
358 if let Some(thread_id) = missed.thread_id.as_ref().filter(|id| self.sidebar.chats.iter().any(|chat| &chat.id == *id)) {
359 return Some(thread_id.clone());
360 }
361 let user_id = missed.caller_mri.strip_prefix(ORGID_PREFIX)?;
362 self.sidebar
363 .chats
364 .iter()
365 .find(|chat| {
366 crate::data::is_one_on_one(chat)
367 && chat.members.iter().any(|member| member.user_id.as_deref() == Some(user_id))
368 })
369 .map(|chat| chat.id.clone())
370 }
371 }
372
373 impl AppState {
374 pub fn running_meeting(&self, conversation_id: &str) -> Option<&LiveMeeting> {
375 self.live_meetings
376 .get(conversation_id)
377 .filter(|meeting| meeting.is_running(now_unix()) && meeting.target().is_some())
378 }
379
380 pub fn demo_live_meetings(&mut self) {
381 for conversation_id in ["demo-chat-meeting-standup", DEMO_LOBBY_MEETING] {
382 self.live_meetings.insert(
383 conversation_id.to_owned(),
384 LiveMeeting {
385 thread_id: conversation_id.to_owned(),
386 conversation_url: None,
387 expiration: Some(now_unix() + DEMO_LIVE_MINUTES * 60),
388 organizer_id: Some("demo-jonas".to_owned()),
389 tenant_id: Some("demo-tenant".to_owned()),
390 meeting_code: None,
391 passcode: None,
392 },
393 );
394 }
395 }
396
397 pub fn watches_live_meeting(&self, conversation_id: &str) -> bool {
398 let meeting_chat = self
399 .sidebar
400 .chats
401 .iter()
402 .any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case(MEETING_KIND));
403 meeting_chat || matches!(selection_for(&self.sidebar, conversation_id), Some(Selection::Channel(_)))
404 }
405
406 pub fn refresh_live_meeting(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
407 if self.mode.demo || !self.watches_live_meeting(conversation_id) {
408 return;
409 }
410 let Some(launcher) = self.call_launcher.clone() else {
411 return;
412 };
413 if !self.live_refreshing.insert(conversation_id.to_owned()) {
414 return;
415 }
416 let thread_id = conversation_id.to_owned();
417 let receiver = crate::runtime::spawn(async move { launcher.live_meeting(&thread_id).await });
418 let conversation_id = conversation_id.to_owned();
419 cx.spawn(async move |this, cx| {
420 let meeting = receiver.await.ok().flatten();
421 this.update(cx, |state, cx| state.apply_live_meeting(conversation_id, meeting, cx)).ok();
422 })
423 .detach();
424 }
425
426 pub fn apply_live_meeting(&mut self, conversation_id: String, meeting: Option<LiveMeeting>, cx: &mut Context<Self>) {
427 self.live_refreshing.remove(&conversation_id);
428 let changed = match meeting {
429 Some(meeting) => self.live_meetings.insert(conversation_id.clone(), meeting.clone()) != Some(meeting),
430 None => self.live_meetings.remove(&conversation_id).is_some(),
431 };
432 if changed {
433 cx.emit(AppEvent::LiveMeeting);
434 cx.notify();
435 }
436 }
437
438 pub fn on_thread_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
439 self.refresh_live_meeting(conversation_id, cx);
440 }
441 }
442
137 443 #[cfg(test)]
138 444 mod tests {
139 445 use std::sync::Arc;
140 446 use std::time::{Duration, Instant};
141 447
142 use calling::{CallState, CallUpdate, EndReason, call_channel};
448 use calling::{CallState, CallUpdate, EndKind, EndReason, EngineEvent, call_channel};
143 449 use gpui_kit::{AppContext as _, Entity, TestAppContext};
144 use store::Store;
450 use store::{ChatRecord, MemberRecord, Store};
145 451
146 use super::{ActiveCall, CallModel, TEST_CALL_TITLE};
452 use super::{ActiveCall, CallModel};
147 453 use crate::app_state::{AppState, Mode, Selection};
454 use crate::call::demo::demo_ring;
455 use crate::data::Person;
148 456
149 457 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
150 458 cx.update(gpui_kit::init);
@@ -155,15 +463,48 @@ mod tests {
155 463 app.update(cx, |state, _| {
156 464 state.call = Some(ActiveCall {
157 465 id: 7,
158 model: CallModel::new(TEST_CALL_TITLE),
466 model: CallModel::test(),
159 467 commands: handle.commands,
160 468 viewing: true,
469 conversation_id: None,
161 470 });
162 471 })
163 472 });
164 473 app
165 474 }
166 475
476 fn app_with_chats(cx: &mut TestAppContext) -> Entity<AppState> {
477 cx.update(gpui_kit::init);
478 let store = Arc::new(Store::open_in_memory().unwrap());
479 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
480 cx.update(|cx| {
481 app.update(cx, |state, _| {
482 state.directory.me = Some(Person {
483 user_id: "me-id".into(),
484 display_name: "Me".into(),
485 });
486 state.sidebar.chats = vec![
487 ChatRecord {
488 id: "19:meeting@thread.v2".into(),
489 kind: "meeting".into(),
490 members: vec![MemberRecord { user_id: Some("bea-id".into()), display_name: "Bea".into() }],
491 ..Default::default()
492 },
493 ChatRecord {
494 id: "19:dm@unq.gbl.spaces".into(),
495 kind: "oneOnOne".into(),
496 members: vec![
497 MemberRecord { user_id: Some("me-id".into()), display_name: "Me".into() },
498 MemberRecord { user_id: Some("bea-id".into()), display_name: "Bea".into() },
499 ],
500 ..Default::default()
501 },
502 ];
503 })
504 });
505 app
506 }
507
167 508 #[gpui_kit::test]
168 509 fn picking_another_chat_moves_the_call_to_the_mini_window(cx: &mut TestAppContext) {
169 510 let app = app_with_call(cx);
@@ -200,6 +541,24 @@ mod tests {
200 541 });
201 542 }
202 543
544 #[gpui_kit::test]
545 fn a_declined_call_names_who_declined(cx: &mut TestAppContext) {
546 let app = app_with_call(cx);
547 cx.update(|cx| {
548 app.update(cx, |state, cx| {
549 state.call.as_mut().unwrap().model.peer_name = "Bea".into();
550 state.apply_call_update(
551 7,
552 CallUpdate::State(CallState::Ended {
553 reason: EndReason::Remote(EndKind::Declined),
554 }),
555 cx,
556 );
557 assert_eq!(state.notice.as_ref().unwrap().text, "Bea declined");
558 })
559 });
560 }
561
203 562 #[gpui_kit::test]
204 563 fn updates_of_an_older_call_are_ignored(cx: &mut TestAppContext) {
205 564 let app = app_with_call(cx);
@@ -217,4 +576,95 @@ mod tests {
217 576 })
218 577 });
219 578 }
579
580 #[gpui_kit::test]
581 fn a_ring_that_times_out_becomes_a_missed_call_event(cx: &mut TestAppContext) {
582 cx.update(gpui_kit::init);
583 let store = Arc::new(Store::open_in_memory().unwrap());
584 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
585 cx.update(|cx| {
586 app.update(cx, |state, cx| {
587 state.on_engine_event(EngineEvent::Incoming(demo_ring()), cx);
588 assert!(state.rings.is_ringing());
589 state.tick_rings(cx);
590 assert!(state.rings.is_ringing());
591 state.on_engine_event(
592 EngineEvent::RingEnded {
593 ring_id: demo_ring().ring_id,
594 kind: EndKind::Cancelled,
595 answered_by: None,
596 },
597 cx,
598 );
599 assert!(!state.rings.is_ringing());
600 })
601 });
602 }
603
604 #[gpui_kit::test]
605 fn calls_are_refused_for_meeting_chats_and_missing_chats(cx: &mut TestAppContext) {
606 let app = app_with_chats(cx);
607 cx.update(|cx| {
608 app.update(cx, |state, cx| {
609 state.start_chat_call("19:meeting@thread.v2", cx);
610 assert!(state.call.is_none());
611 assert_eq!(state.notice.as_ref().unwrap().text, "This chat cannot be called");
612 state.start_chat_call("19:unknown", cx);
613 assert!(state.call.is_none());
614 })
615 });
616 }
617
618 #[gpui_kit::test]
619 fn a_missed_call_finds_the_one_on_one_chat_of_the_caller(cx: &mut TestAppContext) {
620 let app = app_with_chats(cx);
621 cx.update(|cx| {
622 app.update(cx, |state, _| {
623 let missed = super::MissedCall {
624 caller_mri: "8:orgid:bea-id".into(),
625 caller_name: "Bea".into(),
626 thread_id: None,
627 at: chrono::Utc::now(),
628 };
629 assert_eq!(state.conversation_of_missed_call(&missed).as_deref(), Some("19:dm@unq.gbl.spaces"));
630 let direct = super::MissedCall { thread_id: Some("19:dm@unq.gbl.spaces".into()), ..missed.clone() };
631 assert_eq!(state.conversation_of_missed_call(&direct).as_deref(), Some("19:dm@unq.gbl.spaces"));
632 })
633 });
634 }
635
636 #[gpui_kit::test]
637 fn only_meeting_chats_and_channels_watch_for_a_running_meeting(cx: &mut TestAppContext) {
638 let app = app_with_chats(cx);
639 cx.update(|cx| {
640 app.update(cx, |state, _| {
641 assert!(state.watches_live_meeting("19:meeting@thread.v2"));
642 assert!(!state.watches_live_meeting("19:dm@unq.gbl.spaces"));
643 assert!(!state.watches_live_meeting("19:unknown"));
644 })
645 });
646 }
647
648 #[gpui_kit::test]
649 fn a_live_meeting_shows_until_it_ends(cx: &mut TestAppContext) {
650 let app = app_with_chats(cx);
651 let meeting = calling::meeting::LiveMeeting {
652 thread_id: "19:meeting@thread.v2".into(),
653 conversation_url: None,
654 expiration: Some(chrono::Utc::now().timestamp() + 600),
655 organizer_id: Some("org".into()),
656 tenant_id: Some("tenant".into()),
657 meeting_code: None,
658 passcode: None,
659 };
660 cx.update(|cx| {
661 app.update(cx, |state, cx| {
662 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
663 state.apply_live_meeting("19:meeting@thread.v2".into(), Some(meeting), cx);
664 assert!(state.running_meeting("19:meeting@thread.v2").is_some());
665 state.apply_live_meeting("19:meeting@thread.v2".into(), None, cx);
666 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
667 })
668 });
669 }
220 670 }
@@ -1,15 +1,32 @@
1use std::time::{Duration, Instant};
1use std::time::{Duration, Instant};
2
2
3use calling::{CallCommand, CallHandle, CallUpdate, DeviceChoice, MuteCommand};
3use calling::meeting::LiveMeeting;
4use calling::{CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, RingSignal};
4use gpui_kit::*;
5use gpui_kit::*;
5
6
6use super::demo::start_demo_call;
7use super::demo::{DemoCall, demo_caller, demo_guests, demo_ring, start_demo_call};
7use super::model::{ActiveCall, CallModel, TEST_CALL_TITLE, ended_notice};
8use super::model::{ActiveCall, CallModel, ended_notice};
8use crate::app_state::{AppEvent, AppState};
9use super::ring::{MissedCall, RingOutcome};
10use super::target::{is_organizer, plan_for_chat};
11use crate::app_state::{AppEvent, AppState, Selection, chat_title};
12use crate::notify::selection_for;
9
13
10const TIMER_REFRESH: Duration = Duration::from_millis(500);
14const TIMER_REFRESH: Duration = Duration::from_millis(500);
11const NOT_CONNECTED_NOTICE: &str = "Not connected to Teams yet";
15const NOT_CONNECTED_NOTICE: &str = "Not connected to Teams yet";
12const READ_ONLY_NOTICE: &str = "Calls are off in read-only mode";
16const READ_ONLY_NOTICE: &str = "Calls are off in read-only mode";
17const NOT_CALLABLE_NOTICE: &str = "This chat cannot be called";
18const MEETING_UNAVAILABLE_NOTICE: &str = "This meeting cannot be joined";
19const ANSWER_FAILED_NOTICE: &str = "Could not answer the call";
20const MEETING_KIND: &str = "meeting";
21const DEMO_LOBBY_MEETING: &str = "demo-chat-meeting-retro";
22const DEMO_CROWD: usize = 11;
23const DEMO_SMALL_MEETING: usize = 4;
24const DEMO_LIVE_MINUTES: i64 = 60;
25const ORGID_PREFIX: &str = "8:orgid:";
26
27fn now_unix() -> i64 {
28 chrono::Utc::now().timestamp()
29}
13
30
14impl AppState {
31impl AppState {
15 pub fn start_test_call(&mut self, cx: &mut Context<Self>) {
32 pub fn start_test_call(&mut self, cx: &mut Context<Self>) {
@@ -17,26 +34,114 @@ impl AppState {
17 self.show_call(true, cx);
34 self.show_call(true, cx);
18 return;
35 return;
19 }
36 }
20 let handle = if self.mode.demo {
37 let Some(handle) = self.place_call(CallSpec::Echo, DemoCall::Test, cx) else {
21 start_demo_call()
38 return;
22 } else if self.mode.read_only {
39 };
23 self.raise_notice(READ_ONLY_NOTICE.to_owned(), None, cx);
40 self.begin_call(handle, CallModel::test(), None, cx);
41 }
42
43 pub fn start_chat_call(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
44 if self.call.is_some() {
45 self.show_call(true, cx);
46 return;
47 }
48 let plan = self
49 .sidebar
50 .chats
51 .iter()
52 .find(|chat| chat.id == conversation_id)
53 .and_then(|chat| plan_for_chat(chat, self.directory.me.as_ref()));
54 let Some(plan) = plan else {
55 self.raise_notice(NOT_CALLABLE_NOTICE.to_owned(), None, cx);
56 return;
57 };
58 let spec = CallSpec::People {
59 callees: plan
60 .callees
61 .iter()
62 .map(|(mri, name)| Callee {
63 mri: mri.clone(),
64 display_name: name.clone(),
65 })
66 .collect(),
67 thread_id: conversation_id.to_owned(),
68 };
69 let Some(handle) = self.place_call(spec, DemoCall::People(plan.callees.clone()), cx) else {
70 return;
71 };
72 let user_ids = plan
73 .callees
74 .iter()
75 .filter_map(|(mri, _)| mri.strip_prefix(ORGID_PREFIX).map(str::to_owned))
76 .collect();
77 self.request_avatars(user_ids, cx);
78 let model = CallModel::people(&plan.title, &plan.callees);
79 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
80 }
81
82 pub fn join_meeting_call(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
83 if self.call.is_some() {
84 self.show_call(true, cx);
85 return;
86 }
87 let Some(meeting) = self.running_meeting(conversation_id).cloned() else {
88 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
89 return;
90 };
91 let Some(target) = meeting.target() else {
92 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
24 return;
93 return;
25 } else if let Some(launcher) = self.call_launcher.clone() {
94 };
26 launcher.start_test_call()
95 let guests = if conversation_id == DEMO_LOBBY_MEETING { DEMO_SMALL_MEETING } else { DEMO_CROWD };
27 } else {
96 let demo = DemoCall::Meeting {
28 self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);
97 guests: demo_guests(guests),
98 lobby: conversation_id == DEMO_LOBBY_MEETING,
99 };
100 let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, cx) else {
29 return;
101 return;
30 };
102 };
103 let title = selection_for(&self.sidebar, conversation_id)
104 .map(|selection| crate::app_state::selection_title(&self.sidebar, &selection))
105 .unwrap_or_else(|| "Meeting".to_owned());
106 let model = CallModel::meeting(&title, is_organizer(&meeting, self.directory.me.as_ref()));
107 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
108 }
109
110 fn place_call(&mut self, spec: CallSpec, demo: DemoCall, cx: &mut Context<Self>) -> Option<CallHandle> {
111 if self.mode.demo {
112 return Some(start_demo_call(demo));
113 }
114 if self.mode.read_only {
115 self.raise_notice(READ_ONLY_NOTICE.to_owned(), None, cx);
116 return None;
117 }
118 match self.call_launcher.clone() {
119 Some(launcher) => Some(launcher.start_call(spec)),
120 None => {
121 self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);
122 None
123 }
124 }
125 }
126
127 fn begin_call(
128 &mut self,
129 handle: CallHandle,
130 model: CallModel,
131 conversation_id: Option<String>,
132 cx: &mut Context<Self>,
133 ) {
31 self.call_count += 1;
134 self.call_count += 1;
32 let call_id = self.call_count;
135 let call_id = self.call_count;
33 let CallHandle { commands, updates } = handle;
136 let CallHandle { commands, updates } = handle;
34 self.call = Some(ActiveCall {
137 self.call = Some(ActiveCall {
35 id: call_id,
138 id: call_id,
36 model: CallModel::new(TEST_CALL_TITLE),
139 model,
37 commands,
140 commands,
38 viewing: true,
141 viewing: true,
142 conversation_id,
39 });
143 });
144 self.new_chat = false;
40 self.follow_call(call_id, updates, cx);
145 self.follow_call(call_id, updates, cx);
41 cx.emit(AppEvent::Call);
146 cx.emit(AppEvent::Call);
42 cx.notify();
147 cx.notify();
@@ -75,7 +180,7 @@ impl AppState {
75 .detach();
180 .detach();
76 }
181 }
77
182
78 fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {
183 pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {
79 let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
184 let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
80 return;
185 return;
81 };
186 };
@@ -86,8 +191,9 @@ impl AppState {
86 return;
191 return;
87 };
192 };
88 let elapsed = call.model.elapsed(Instant::now());
193 let elapsed = call.model.elapsed(Instant::now());
194 let notice = ended_notice(&reason, elapsed, &call.model.peer_name);
89 self.call = None;
195 self.call = None;
90 self.raise_notice(ended_notice(&reason, elapsed), None, cx);
196 self.raise_notice(notice, None, cx);
91 cx.emit(AppEvent::Call);
197 cx.emit(AppEvent::Call);
92 cx.notify();
198 cx.notify();
93 }
199 }
@@ -109,6 +215,13 @@ impl AppState {
109 self.send_call_command(CallCommand::Hangup);
215 self.send_call_command(CallCommand::Hangup);
110 }
216 }
111
217
218 pub fn end_meeting_for_all(&mut self, _cx: &mut Context<Self>) {
219 let allowed = self.call.as_ref().is_some_and(|call| call.model.can_end_meeting);
220 if allowed {
221 self.send_call_command(CallCommand::EndMeeting);
222 }
223 }
224
112 pub fn select_call_input(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
225 pub fn select_call_input(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
113 self.send_call_command(CallCommand::SelectInput(choice));
226 self.send_call_command(CallCommand::SelectInput(choice));
114 }
227 }
@@ -129,22 +242,217 @@ impl AppState {
129 cx.notify();
242 cx.notify();
130 }
243 }
131
244
245 pub fn open_call_chat(&mut self, cx: &mut Context<Self>) {
246 let Some(conversation_id) = self.call.as_ref().and_then(|call| call.conversation_id.clone()) else {
247 return;
248 };
249 if let Some(selection) = selection_for(&self.sidebar, &conversation_id) {
250 self.select(selection, cx);
251 }
252 }
253
132 pub fn viewing_call(&self) -> bool {
254 pub fn viewing_call(&self) -> bool {
133 self.call.as_ref().is_some_and(|call| call.viewing)
255 self.call.as_ref().is_some_and(|call| call.viewing)
134 }
256 }
135}
257}
136
258
259impl AppState {
260 pub fn on_engine_event(&mut self, event: EngineEvent, cx: &mut Context<Self>) {
261 match event {
262 EngineEvent::Incoming(ring) => self.push_ring(ring, false, cx),
263 EngineEvent::RingEnded { ring_id, kind, .. } => {
264 self.signal_ring(ring_id, RingSignal::Remote(kind), cx);
265 }
266 }
267 }
268
269 fn push_ring(&mut self, ring: calling::IncomingRing, demo: bool, cx: &mut Context<Self>) {
270 let caller_user_id = ring.caller.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
271 self.rings.push(ring, demo, Instant::now());
272 if let Some(user_id) = caller_user_id {
273 self.request_avatars(vec![user_id], cx);
274 }
275 cx.emit(AppEvent::Ring);
276 cx.notify();
277 }
278
279 pub fn demo_incoming_ring(&mut self, cx: &mut Context<Self>) {
280 self.push_ring(demo_ring(), true, cx);
281 }
282
283 fn signal_ring(&mut self, ring_id: u64, signal: RingSignal, cx: &mut Context<Self>) {
284 if let Some(outcome) = self.rings.signal(ring_id, signal, Instant::now()) {
285 self.finish_ring(ring_id, outcome, cx);
286 }
287 }
288
289 fn finish_ring(&mut self, ring_id: u64, outcome: RingOutcome, cx: &mut Context<Self>) {
290 if let RingOutcome::Missed(missed) = outcome {
291 if let Some(launcher) = &self.call_launcher {
292 launcher.drop_ring(ring_id);
293 }
294 cx.emit(AppEvent::MissedCall(missed));
295 }
296 cx.emit(AppEvent::Ring);
297 cx.notify();
298 }
299
300 pub fn tick_rings(&mut self, cx: &mut Context<Self>) {
301 if self.rings.is_empty() {
302 return;
303 }
304 for (ring_id, outcome) in self.rings.tick(Instant::now()) {
305 self.finish_ring(ring_id, outcome, cx);
306 }
307 }
308
309 pub fn accept_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {
310 let Some(entry) = self.rings.get(ring_id).cloned() else {
311 return;
312 };
313 if self.call.is_some() {
314 self.leave_call(cx);
315 }
316 self.signal_ring(ring_id, RingSignal::Accept, cx);
317 let conversation_id = entry.ring.thread_id.clone();
318 let title = conversation_id
319 .as_deref()
320 .and_then(|id| self.sidebar.chats.iter().find(|chat| chat.id == id))
321 .filter(|_| entry.ring.is_group)
322 .map(chat_title)
323 .unwrap_or_else(|| entry.caller_name().to_owned());
324 let model = CallModel::incoming(&title, &entry.ring.caller.mri, entry.caller_name());
325 if entry.demo {
326 let handle = start_demo_call(DemoCall::Incoming(demo_caller()));
327 self.begin_call(handle, model, conversation_id, cx);
328 return;
329 }
330 let Some(launcher) = self.call_launcher.clone() else {
331 self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);
332 return;
333 };
334 let receiver = crate::runtime::spawn(async move { launcher.accept_ring(ring_id).await });
335 cx.spawn(async move |this, cx| {
336 let handle = receiver.await.ok().flatten();
337 this.update(cx, |state, cx| match handle {
338 Some(handle) => state.begin_call(handle, model, conversation_id, cx),
339 None => state.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx),
340 })
341 .ok();
342 })
343 .detach();
344 }
345
346 pub fn decline_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {
347 let Some(entry) = self.rings.get(ring_id) else {
348 return;
349 };
350 let demo = entry.demo;
351 if !demo && let Some(launcher) = &self.call_launcher {
352 launcher.decline_ring(ring_id);
353 }
354 self.signal_ring(ring_id, RingSignal::Decline, cx);
355 }
356
357 pub fn conversation_of_missed_call(&self, missed: &MissedCall) -> Option<String> {
358 if let Some(thread_id) = missed.thread_id.as_ref().filter(|id| self.sidebar.chats.iter().any(|chat| &chat.id == *id)) {
359 return Some(thread_id.clone());
360 }
361 let user_id = missed.caller_mri.strip_prefix(ORGID_PREFIX)?;
362 self.sidebar
363 .chats
364 .iter()
365 .find(|chat| {
366 crate::data::is_one_on_one(chat)
367 && chat.members.iter().any(|member| member.user_id.as_deref() == Some(user_id))
368 })
369 .map(|chat| chat.id.clone())
370 }
371}
372
373impl AppState {
374 pub fn running_meeting(&self, conversation_id: &str) -> Option<&LiveMeeting> {
375 self.live_meetings
376 .get(conversation_id)
377 .filter(|meeting| meeting.is_running(now_unix()) && meeting.target().is_some())
378 }
379
380 pub fn demo_live_meetings(&mut self) {
381 for conversation_id in ["demo-chat-meeting-standup", DEMO_LOBBY_MEETING] {
382 self.live_meetings.insert(
383 conversation_id.to_owned(),
384 LiveMeeting {
385 thread_id: conversation_id.to_owned(),
386 conversation_url: None,
387 expiration: Some(now_unix() + DEMO_LIVE_MINUTES * 60),
388 organizer_id: Some("demo-jonas".to_owned()),
389 tenant_id: Some("demo-tenant".to_owned()),
390 meeting_code: None,
391 passcode: None,
392 },
393 );
394 }
395 }
396
397 pub fn watches_live_meeting(&self, conversation_id: &str) -> bool {
398 let meeting_chat = self
399 .sidebar
400 .chats
401 .iter()
402 .any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case(MEETING_KIND));
403 meeting_chat || matches!(selection_for(&self.sidebar, conversation_id), Some(Selection::Channel(_)))
404 }
405
406 pub fn refresh_live_meeting(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
407 if self.mode.demo || !self.watches_live_meeting(conversation_id) {
408 return;
409 }
410 let Some(launcher) = self.call_launcher.clone() else {
411 return;
412 };
413 if !self.live_refreshing.insert(conversation_id.to_owned()) {
414 return;
415 }
416 let thread_id = conversation_id.to_owned();
417 let receiver = crate::runtime::spawn(async move { launcher.live_meeting(&thread_id).await });
418 let conversation_id = conversation_id.to_owned();
419 cx.spawn(async move |this, cx| {
420 let meeting = receiver.await.ok().flatten();
421 this.update(cx, |state, cx| state.apply_live_meeting(conversation_id, meeting, cx)).ok();
422 })
423 .detach();
424 }
425
426 pub fn apply_live_meeting(&mut self, conversation_id: String, meeting: Option<LiveMeeting>, cx: &mut Context<Self>) {
427 self.live_refreshing.remove(&conversation_id);
428 let changed = match meeting {
429 Some(meeting) => self.live_meetings.insert(conversation_id.clone(), meeting.clone()) != Some(meeting),
430 None => self.live_meetings.remove(&conversation_id).is_some(),
431 };
432 if changed {
433 cx.emit(AppEvent::LiveMeeting);
434 cx.notify();
435 }
436 }
437
438 pub fn on_thread_changed(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
439 self.refresh_live_meeting(conversation_id, cx);
440 }
441}
442
137#[cfg(test)]
443#[cfg(test)]
138mod tests {
444mod tests {
139 use std::sync::Arc;
445 use std::sync::Arc;
140 use std::time::{Duration, Instant};
446 use std::time::{Duration, Instant};
141
447
142 use calling::{CallState, CallUpdate, EndReason, call_channel};
448 use calling::{CallState, CallUpdate, EndKind, EndReason, EngineEvent, call_channel};
143 use gpui_kit::{AppContext as _, Entity, TestAppContext};
449 use gpui_kit::{AppContext as _, Entity, TestAppContext};
144 use store::Store;
450 use store::{ChatRecord, MemberRecord, Store};
145
451
146 use super::{ActiveCall, CallModel, TEST_CALL_TITLE};
452 use super::{ActiveCall, CallModel};
147 use crate::app_state::{AppState, Mode, Selection};
453 use crate::app_state::{AppState, Mode, Selection};
454 use crate::call::demo::demo_ring;
455 use crate::data::Person;
148
456
149 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
457 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
150 cx.update(gpui_kit::init);
458 cx.update(gpui_kit::init);
@@ -155,15 +463,48 @@ mod tests {
155 app.update(cx, |state, _| {
463 app.update(cx, |state, _| {
156 state.call = Some(ActiveCall {
464 state.call = Some(ActiveCall {
157 id: 7,
465 id: 7,
158 model: CallModel::new(TEST_CALL_TITLE),
466 model: CallModel::test(),
159 commands: handle.commands,
467 commands: handle.commands,
160 viewing: true,
468 viewing: true,
469 conversation_id: None,
161 });
470 });
162 })
471 })
163 });
472 });
164 app
473 app
165 }
474 }
166
475
476 fn app_with_chats(cx: &mut TestAppContext) -> Entity<AppState> {
477 cx.update(gpui_kit::init);
478 let store = Arc::new(Store::open_in_memory().unwrap());
479 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
480 cx.update(|cx| {
481 app.update(cx, |state, _| {
482 state.directory.me = Some(Person {
483 user_id: "me-id".into(),
484 display_name: "Me".into(),
485 });
486 state.sidebar.chats = vec![
487 ChatRecord {
488 id: "19:meeting@thread.v2".into(),
489 kind: "meeting".into(),
490 members: vec![MemberRecord { user_id: Some("bea-id".into()), display_name: "Bea".into() }],
491 ..Default::default()
492 },
493 ChatRecord {
494 id: "19:dm@unq.gbl.spaces".into(),
495 kind: "oneOnOne".into(),
496 members: vec![
497 MemberRecord { user_id: Some("me-id".into()), display_name: "Me".into() },
498 MemberRecord { user_id: Some("bea-id".into()), display_name: "Bea".into() },
499 ],
500 ..Default::default()
501 },
502 ];
503 })
504 });
505 app
506 }
507
167 #[gpui_kit::test]
508 #[gpui_kit::test]
168 fn picking_another_chat_moves_the_call_to_the_mini_window(cx: &mut TestAppContext) {
509 fn picking_another_chat_moves_the_call_to_the_mini_window(cx: &mut TestAppContext) {
169 let app = app_with_call(cx);
510 let app = app_with_call(cx);
@@ -200,6 +541,24 @@ mod tests {
200 });
541 });
201 }
542 }
202
543
544 #[gpui_kit::test]
545 fn a_declined_call_names_who_declined(cx: &mut TestAppContext) {
546 let app = app_with_call(cx);
547 cx.update(|cx| {
548 app.update(cx, |state, cx| {
549 state.call.as_mut().unwrap().model.peer_name = "Bea".into();
550 state.apply_call_update(
551 7,
552 CallUpdate::State(CallState::Ended {
553 reason: EndReason::Remote(EndKind::Declined),
554 }),
555 cx,
556 );
557 assert_eq!(state.notice.as_ref().unwrap().text, "Bea declined");
558 })
559 });
560 }
561
203 #[gpui_kit::test]
562 #[gpui_kit::test]
204 fn updates_of_an_older_call_are_ignored(cx: &mut TestAppContext) {
563 fn updates_of_an_older_call_are_ignored(cx: &mut TestAppContext) {
205 let app = app_with_call(cx);
564 let app = app_with_call(cx);
@@ -217,4 +576,95 @@ mod tests {
217 })
576 })
218 });
577 });
219 }
578 }
579
580 #[gpui_kit::test]
581 fn a_ring_that_times_out_becomes_a_missed_call_event(cx: &mut TestAppContext) {
582 cx.update(gpui_kit::init);
583 let store = Arc::new(Store::open_in_memory().unwrap());
584 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
585 cx.update(|cx| {
586 app.update(cx, |state, cx| {
587 state.on_engine_event(EngineEvent::Incoming(demo_ring()), cx);
588 assert!(state.rings.is_ringing());
589 state.tick_rings(cx);
590 assert!(state.rings.is_ringing());
591 state.on_engine_event(
592 EngineEvent::RingEnded {
593 ring_id: demo_ring().ring_id,
594 kind: EndKind::Cancelled,
595 answered_by: None,
596 },
597 cx,
598 );
599 assert!(!state.rings.is_ringing());
600 })
601 });
602 }
603
604 #[gpui_kit::test]
605 fn calls_are_refused_for_meeting_chats_and_missing_chats(cx: &mut TestAppContext) {
606 let app = app_with_chats(cx);
607 cx.update(|cx| {
608 app.update(cx, |state, cx| {
609 state.start_chat_call("19:meeting@thread.v2", cx);
610 assert!(state.call.is_none());
611 assert_eq!(state.notice.as_ref().unwrap().text, "This chat cannot be called");
612 state.start_chat_call("19:unknown", cx);
613 assert!(state.call.is_none());
614 })
615 });
616 }
617
618 #[gpui_kit::test]
619 fn a_missed_call_finds_the_one_on_one_chat_of_the_caller(cx: &mut TestAppContext) {
620 let app = app_with_chats(cx);
621 cx.update(|cx| {
622 app.update(cx, |state, _| {
623 let missed = super::MissedCall {
624 caller_mri: "8:orgid:bea-id".into(),
625 caller_name: "Bea".into(),
626 thread_id: None,
627 at: chrono::Utc::now(),
628 };
629 assert_eq!(state.conversation_of_missed_call(&missed).as_deref(), Some("19:dm@unq.gbl.spaces"));
630 let direct = super::MissedCall { thread_id: Some("19:dm@unq.gbl.spaces".into()), ..missed.clone() };
631 assert_eq!(state.conversation_of_missed_call(&direct).as_deref(), Some("19:dm@unq.gbl.spaces"));
632 })
633 });
634 }
635
636 #[gpui_kit::test]
637 fn only_meeting_chats_and_channels_watch_for_a_running_meeting(cx: &mut TestAppContext) {
638 let app = app_with_chats(cx);
639 cx.update(|cx| {
640 app.update(cx, |state, _| {
641 assert!(state.watches_live_meeting("19:meeting@thread.v2"));
642 assert!(!state.watches_live_meeting("19:dm@unq.gbl.spaces"));
643 assert!(!state.watches_live_meeting("19:unknown"));
644 })
645 });
646 }
647
648 #[gpui_kit::test]
649 fn a_live_meeting_shows_until_it_ends(cx: &mut TestAppContext) {
650 let app = app_with_chats(cx);
651 let meeting = calling::meeting::LiveMeeting {
652 thread_id: "19:meeting@thread.v2".into(),
653 conversation_url: None,
654 expiration: Some(chrono::Utc::now().timestamp() + 600),
655 organizer_id: Some("org".into()),
656 tenant_id: Some("tenant".into()),
657 meeting_code: None,
658 passcode: None,
659 };
660 cx.update(|cx| {
661 app.update(cx, |state, cx| {
662 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
663 state.apply_live_meeting("19:meeting@thread.v2".into(), Some(meeting), cx);
664 assert!(state.running_meeting("19:meeting@thread.v2").is_some());
665 state.apply_live_meeting("19:meeting@thread.v2".into(), None, cx);
666 assert!(state.running_meeting("19:meeting@thread.v2").is_none());
667 })
668 });
669 }
220}
670}
crates/app/src/call/demo.rs +151 −10
@@ -1,17 +1,74 @@
1 1 use std::time::{Duration, Instant};
2 2
3 3 use calling::{
4 AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, DeviceChoice,
5 DeviceLists, EndReason, call_channel,
4 AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, DeviceChoice, DeviceLists, EndReason,
5 IncomingRing, Progress, RosterEntry, call_channel,
6 6 };
7 7 use tokio::time::{interval, sleep};
8 8
9 use super::model::{ECHO_MRI, ECHO_NAME};
10
9 11 const CONNECT_DELAY: Duration = Duration::from_millis(2200);
12 const RING_START: Duration = Duration::from_millis(1400);
13 const ANSWER_DELAY: Duration = Duration::from_millis(3200);
14 const INCOMING_CONNECT_DELAY: Duration = Duration::from_millis(600);
15 const LOBBY_WAIT: Duration = Duration::from_secs(6);
10 16 const LEVEL_PERIOD: Duration = Duration::from_millis(200);
11 17 const CYCLE_TICKS: u32 = 40;
12 18 const REMOTE_SPEAKS: std::ops::Range<u32> = 0..18;
13 19 const LOCAL_SPEAKS: std::ops::Range<u32> = 24..32;
14 20 const SPEAKING_LEVEL: f32 = 0.3;
21 const SPEAKER_TICKS: u32 = 10;
22 pub const DEMO_OWN_MRI: &str = "8:orgid:demo-me";
23 pub const DEMO_RING_ID: u64 = 9001;
24 const DEMO_CALLER: (&str, &str) = ("8:orgid:demo-mara", "Mara Lindqvist");
25 const DEMO_GUESTS: [&str; 11] = [
26 "Mara Lindqvist",
27 "Jonas Ortega",
28 "Priya Nair",
29 "Lea Schneider",
30 "Tobias Klein",
31 "Ines Duarte",
32 "Noor Haddad",
33 "Felix Brandt",
34 "Yuki Tanaka",
35 "Carlos Mendez",
36 "Sofia Rossi",
37 ];
38
39 pub type Person = (String, String);
40
41 pub enum DemoCall {
42 Test,
43 People(Vec<Person>),
44 Meeting { guests: Vec<Person>, lobby: bool },
45 Incoming(Person),
46 }
47
48 pub fn demo_guests(count: usize) -> Vec<Person> {
49 DEMO_GUESTS
50 .iter()
51 .take(count)
52 .enumerate()
53 .map(|(index, name)| (format!("8:orgid:demo-guest-{index}"), (*name).to_owned()))
54 .collect()
55 }
56
57 pub fn demo_caller() -> Person {
58 (DEMO_CALLER.0.to_owned(), DEMO_CALLER.1.to_owned())
59 }
60
61 pub fn demo_ring() -> IncomingRing {
62 let (mri, display_name) = demo_caller();
63 IncomingRing {
64 ring_id: DEMO_RING_ID,
65 caller: Caller { mri, display_name },
66 thread_id: Some("demo-chat-mara".to_owned()),
67 video: false,
68 is_group: false,
69 subject: None,
70 }
71 }
15 72
16 73 fn device(index: u16, name: &str) -> AudioDevice {
17 74 AudioDevice {
@@ -28,15 +85,39 @@ fn demo_devices() -> DeviceLists {
28 85 }
29 86 }
30 87
31 pub fn start_demo_call() -> CallHandle {
88 pub fn start_demo_call(script: DemoCall) -> CallHandle {
32 89 let (handle, control) = call_channel();
33 crate::runtime::handle().spawn(run_demo_call(control));
90 crate::runtime::handle().spawn(run_demo_call(control, script));
34 91 handle
35 92 }
36 93
37 async fn run_demo_call(mut control: CallControl) {
38 if control.until_hangup(sleep(CONNECT_DELAY)).await.is_err() {
39 end(&control, EndReason::Cancelled);
94 fn roster_of(people: &[Person]) -> Vec<RosterEntry> {
95 people
96 .iter()
97 .enumerate()
98 .map(|(index, (mri, name))| RosterEntry {
99 mri: mri.clone(),
100 display_name: name.clone(),
101 muted: index % 3 == 1,
102 in_lobby: false,
103 })
104 .collect()
105 }
106
107 async fn run_demo_call(mut control: CallControl, script: DemoCall) {
108 control.send(CallUpdate::OwnIdentity {
109 mri: DEMO_OWN_MRI.to_owned(),
110 });
111 let (people, lobby) = match &script {
112 DemoCall::Test => (vec![(ECHO_MRI.to_owned(), ECHO_NAME.to_owned())], false),
113 DemoCall::People(callees) => (callees.clone(), false),
114 DemoCall::Meeting { guests, lobby } => (guests.clone(), *lobby),
115 DemoCall::Incoming(caller) => (vec![caller.clone()], false),
116 };
117 if !ring_until_answered(&mut control, &script).await {
118 control.send(CallUpdate::State(CallState::Ended {
119 reason: EndReason::Cancelled,
120 }));
40 121 return;
41 122 }
42 123 control.send(CallUpdate::ListenOnly(false));
@@ -48,6 +129,39 @@ async fn run_demo_call(mut control: CallControl) {
48 129 control.send(CallUpdate::State(CallState::Connected {
49 130 since: Instant::now(),
50 131 }));
132 if lobby {
133 control.send(CallUpdate::Lobby(true));
134 if control.until_hangup(sleep(LOBBY_WAIT)).await.is_err() {
135 end(&control, EndReason::LocalHangup);
136 return;
137 }
138 control.send(CallUpdate::Lobby(false));
139 }
140 control.send(CallUpdate::Roster(roster_of(&people)));
141 speak_until_hangup(control, people).await;
142 }
143
144 async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bool {
145 let steps: Vec<(Option<Progress>, Duration)> = match script {
146 DemoCall::People(_) => vec![
147 (Some(Progress::Calling), RING_START),
148 (Some(Progress::Ringing), ANSWER_DELAY - RING_START),
149 ],
150 DemoCall::Incoming(_) => vec![(None, INCOMING_CONNECT_DELAY)],
151 DemoCall::Test | DemoCall::Meeting { .. } => vec![(None, CONNECT_DELAY)],
152 };
153 for (progress, wait) in steps {
154 if let Some(progress) = progress {
155 control.send(CallUpdate::Progress(progress));
156 }
157 if control.until_hangup(sleep(wait)).await.is_err() {
158 return false;
159 }
160 }
161 true
162 }
163
164 async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>) {
51 165 let mut muted = false;
52 166 let mut input = DeviceChoice::SystemDefault;
53 167 let mut output = DeviceChoice::SystemDefault;
@@ -57,11 +171,16 @@ async fn run_demo_call(mut control: CallControl) {
57 171 tokio::select! {
58 172 _ = tick.tick() => {
59 173 let phase = ticks % CYCLE_TICKS;
60 ticks += 1;
174 let remote_speaks = REMOTE_SPEAKS.contains(&phase);
61 175 control.send(CallUpdate::Levels {
62 176 local: if LOCAL_SPEAKS.contains(&phase) && !muted { SPEAKING_LEVEL } else { 0.0 },
63 remote: if REMOTE_SPEAKS.contains(&phase) { SPEAKING_LEVEL } else { 0.0 },
177 remote: if remote_speaks { SPEAKING_LEVEL } else { 0.0 },
64 178 });
179 if people.len() > 1 && ticks.is_multiple_of(SPEAKER_TICKS) {
180 let speaker = &people[(ticks / SPEAKER_TICKS) as usize % people.len()];
181 control.send(CallUpdate::Speakers(vec![speaker.0.clone()]));
182 }
183 ticks += 1;
65 184 }
66 185 command = control.recv() => match command {
67 186 Some(CallCommand::Mute(command)) => {
@@ -77,7 +196,7 @@ async fn run_demo_call(mut control: CallControl) {
77 196 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
78 197 }
79 198 Some(CallCommand::RefreshDevices) => control.send(CallUpdate::Devices(demo_devices())),
80 Some(CallCommand::Hangup) | None => {
199 Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {
81 200 end(&control, EndReason::LocalHangup);
82 201 return;
83 202 }
@@ -89,3 +208,25 @@ async fn run_demo_call(mut control: CallControl) {
89 208 fn end(control: &CallControl, reason: EndReason) {
90 209 control.send(CallUpdate::State(CallState::Ended { reason }));
91 210 }
211
212 #[cfg(test)]
213 mod tests {
214 use super::*;
215
216 #[test]
217 fn demo_guests_have_distinct_mris_and_names() {
218 let guests = demo_guests(11);
219 assert_eq!(guests.len(), 11);
220 let mut mris: Vec<&String> = guests.iter().map(|guest| &guest.0).collect();
221 mris.sort();
222 mris.dedup();
223 assert_eq!(mris.len(), 11);
224 }
225
226 #[test]
227 fn the_demo_ring_names_a_caller_and_a_chat() {
228 let ring = demo_ring();
229 assert_eq!(ring.caller.display_name, "Mara Lindqvist");
230 assert_eq!(ring.thread_id.as_deref(), Some("demo-chat-mara"));
231 }
232 }
@@ -1,17 +1,74 @@
1use std::time::{Duration, Instant};
1use std::time::{Duration, Instant};
2
2
3use calling::{
3use calling::{
4 AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, DeviceChoice,
4 AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, DeviceChoice, DeviceLists, EndReason,
5 DeviceLists, EndReason, call_channel,
5 IncomingRing, Progress, RosterEntry, call_channel,
6};
6};
7use tokio::time::{interval, sleep};
7use tokio::time::{interval, sleep};
8
8
9use super::model::{ECHO_MRI, ECHO_NAME};
10
9const CONNECT_DELAY: Duration = Duration::from_millis(2200);
11const CONNECT_DELAY: Duration = Duration::from_millis(2200);
12const RING_START: Duration = Duration::from_millis(1400);
13const ANSWER_DELAY: Duration = Duration::from_millis(3200);
14const INCOMING_CONNECT_DELAY: Duration = Duration::from_millis(600);
15const LOBBY_WAIT: Duration = Duration::from_secs(6);
10const LEVEL_PERIOD: Duration = Duration::from_millis(200);
16const LEVEL_PERIOD: Duration = Duration::from_millis(200);
11const CYCLE_TICKS: u32 = 40;
17const CYCLE_TICKS: u32 = 40;
12const REMOTE_SPEAKS: std::ops::Range<u32> = 0..18;
18const REMOTE_SPEAKS: std::ops::Range<u32> = 0..18;
13const LOCAL_SPEAKS: std::ops::Range<u32> = 24..32;
19const LOCAL_SPEAKS: std::ops::Range<u32> = 24..32;
14const SPEAKING_LEVEL: f32 = 0.3;
20const SPEAKING_LEVEL: f32 = 0.3;
21const SPEAKER_TICKS: u32 = 10;
22pub const DEMO_OWN_MRI: &str = "8:orgid:demo-me";
23pub const DEMO_RING_ID: u64 = 9001;
24const DEMO_CALLER: (&str, &str) = ("8:orgid:demo-mara", "Mara Lindqvist");
25const DEMO_GUESTS: [&str; 11] = [
26 "Mara Lindqvist",
27 "Jonas Ortega",
28 "Priya Nair",
29 "Lea Schneider",
30 "Tobias Klein",
31 "Ines Duarte",
32 "Noor Haddad",
33 "Felix Brandt",
34 "Yuki Tanaka",
35 "Carlos Mendez",
36 "Sofia Rossi",
37];
38
39pub type Person = (String, String);
40
41pub enum DemoCall {
42 Test,
43 People(Vec<Person>),
44 Meeting { guests: Vec<Person>, lobby: bool },
45 Incoming(Person),
46}
47
48pub fn demo_guests(count: usize) -> Vec<Person> {
49 DEMO_GUESTS
50 .iter()
51 .take(count)
52 .enumerate()
53 .map(|(index, name)| (format!("8:orgid:demo-guest-{index}"), (*name).to_owned()))
54 .collect()
55}
56
57pub fn demo_caller() -> Person {
58 (DEMO_CALLER.0.to_owned(), DEMO_CALLER.1.to_owned())
59}
60
61pub fn demo_ring() -> IncomingRing {
62 let (mri, display_name) = demo_caller();
63 IncomingRing {
64 ring_id: DEMO_RING_ID,
65 caller: Caller { mri, display_name },
66 thread_id: Some("demo-chat-mara".to_owned()),
67 video: false,
68 is_group: false,
69 subject: None,
70 }
71}
15
72
16fn device(index: u16, name: &str) -> AudioDevice {
73fn device(index: u16, name: &str) -> AudioDevice {
17 AudioDevice {
74 AudioDevice {
@@ -28,15 +85,39 @@ fn demo_devices() -> DeviceLists {
28 }
85 }
29}
86}
30
87
31pub fn start_demo_call() -> CallHandle {
88pub fn start_demo_call(script: DemoCall) -> CallHandle {
32 let (handle, control) = call_channel();
89 let (handle, control) = call_channel();
33 crate::runtime::handle().spawn(run_demo_call(control));
90 crate::runtime::handle().spawn(run_demo_call(control, script));
34 handle
91 handle
35}
92}
36
93
37async fn run_demo_call(mut control: CallControl) {
94fn roster_of(people: &[Person]) -> Vec<RosterEntry> {
38 if control.until_hangup(sleep(CONNECT_DELAY)).await.is_err() {
95 people
39 end(&control, EndReason::Cancelled);
96 .iter()
97 .enumerate()
98 .map(|(index, (mri, name))| RosterEntry {
99 mri: mri.clone(),
100 display_name: name.clone(),
101 muted: index % 3 == 1,
102 in_lobby: false,
103 })
104 .collect()
105}
106
107async fn run_demo_call(mut control: CallControl, script: DemoCall) {
108 control.send(CallUpdate::OwnIdentity {
109 mri: DEMO_OWN_MRI.to_owned(),
110 });
111 let (people, lobby) = match &script {
112 DemoCall::Test => (vec![(ECHO_MRI.to_owned(), ECHO_NAME.to_owned())], false),
113 DemoCall::People(callees) => (callees.clone(), false),
114 DemoCall::Meeting { guests, lobby } => (guests.clone(), *lobby),
115 DemoCall::Incoming(caller) => (vec![caller.clone()], false),
116 };
117 if !ring_until_answered(&mut control, &script).await {
118 control.send(CallUpdate::State(CallState::Ended {
119 reason: EndReason::Cancelled,
120 }));
40 return;
121 return;
41 }
122 }
42 control.send(CallUpdate::ListenOnly(false));
123 control.send(CallUpdate::ListenOnly(false));
@@ -48,6 +129,39 @@ async fn run_demo_call(mut control: CallControl) {
48 control.send(CallUpdate::State(CallState::Connected {
129 control.send(CallUpdate::State(CallState::Connected {
49 since: Instant::now(),
130 since: Instant::now(),
50 }));
131 }));
132 if lobby {
133 control.send(CallUpdate::Lobby(true));
134 if control.until_hangup(sleep(LOBBY_WAIT)).await.is_err() {
135 end(&control, EndReason::LocalHangup);
136 return;
137 }
138 control.send(CallUpdate::Lobby(false));
139 }
140 control.send(CallUpdate::Roster(roster_of(&people)));
141 speak_until_hangup(control, people).await;
142}
143
144async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bool {
145 let steps: Vec<(Option<Progress>, Duration)> = match script {
146 DemoCall::People(_) => vec![
147 (Some(Progress::Calling), RING_START),
148 (Some(Progress::Ringing), ANSWER_DELAY - RING_START),
149 ],
150 DemoCall::Incoming(_) => vec![(None, INCOMING_CONNECT_DELAY)],
151 DemoCall::Test | DemoCall::Meeting { .. } => vec![(None, CONNECT_DELAY)],
152 };
153 for (progress, wait) in steps {
154 if let Some(progress) = progress {
155 control.send(CallUpdate::Progress(progress));
156 }
157 if control.until_hangup(sleep(wait)).await.is_err() {
158 return false;
159 }
160 }
161 true
162}
163
164async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>) {
51 let mut muted = false;
165 let mut muted = false;
52 let mut input = DeviceChoice::SystemDefault;
166 let mut input = DeviceChoice::SystemDefault;
53 let mut output = DeviceChoice::SystemDefault;
167 let mut output = DeviceChoice::SystemDefault;
@@ -57,11 +171,16 @@ async fn run_demo_call(mut control: CallControl) {
57 tokio::select! {
171 tokio::select! {
58 _ = tick.tick() => {
172 _ = tick.tick() => {
59 let phase = ticks % CYCLE_TICKS;
173 let phase = ticks % CYCLE_TICKS;
60 ticks += 1;
174 let remote_speaks = REMOTE_SPEAKS.contains(&phase);
61 control.send(CallUpdate::Levels {
175 control.send(CallUpdate::Levels {
62 local: if LOCAL_SPEAKS.contains(&phase) && !muted { SPEAKING_LEVEL } else { 0.0 },
176 local: if LOCAL_SPEAKS.contains(&phase) && !muted { SPEAKING_LEVEL } else { 0.0 },
63 remote: if REMOTE_SPEAKS.contains(&phase) { SPEAKING_LEVEL } else { 0.0 },
177 remote: if remote_speaks { SPEAKING_LEVEL } else { 0.0 },
64 });
178 });
179 if people.len() > 1 && ticks.is_multiple_of(SPEAKER_TICKS) {
180 let speaker = &people[(ticks / SPEAKER_TICKS) as usize % people.len()];
181 control.send(CallUpdate::Speakers(vec![speaker.0.clone()]));
182 }
183 ticks += 1;
65 }
184 }
66 command = control.recv() => match command {
185 command = control.recv() => match command {
67 Some(CallCommand::Mute(command)) => {
186 Some(CallCommand::Mute(command)) => {
@@ -77,7 +196,7 @@ async fn run_demo_call(mut control: CallControl) {
77 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
196 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
78 }
197 }
79 Some(CallCommand::RefreshDevices) => control.send(CallUpdate::Devices(demo_devices())),
198 Some(CallCommand::RefreshDevices) => control.send(CallUpdate::Devices(demo_devices())),
80 Some(CallCommand::Hangup) | None => {
199 Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {
81 end(&control, EndReason::LocalHangup);
200 end(&control, EndReason::LocalHangup);
82 return;
201 return;
83 }
202 }
@@ -89,3 +208,25 @@ async fn run_demo_call(mut control: CallControl) {
89fn end(control: &CallControl, reason: EndReason) {
208fn end(control: &CallControl, reason: EndReason) {
90 control.send(CallUpdate::State(CallState::Ended { reason }));
209 control.send(CallUpdate::State(CallState::Ended { reason }));
91}
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 #[test]
217 fn demo_guests_have_distinct_mris_and_names() {
218 let guests = demo_guests(11);
219 assert_eq!(guests.len(), 11);
220 let mut mris: Vec<&String> = guests.iter().map(|guest| &guest.0).collect();
221 mris.sort();
222 mris.dedup();
223 assert_eq!(mris.len(), 11);
224 }
225
226 #[test]
227 fn the_demo_ring_names_a_caller_and_a_chat() {
228 let ring = demo_ring();
229 assert_eq!(ring.caller.display_name, "Mara Lindqvist");
230 assert_eq!(ring.thread_id.as_deref(), Some("demo-chat-mara"));
231 }
232}
crates/app/src/call/launcher.rs +133 −29
@@ -1,44 +1,148 @@
1 use std::sync::Arc;
1 use std::future::Future;
2 use std::sync::{Arc, Mutex};
3 use std::time::Duration;
2 4
5 use calling::meeting::{LiveMeeting, fetch_live_meeting};
3 6 use calling::{
4 CallHandle, CallState, CallUpdate, EndReason, TestCallOptions, call_channel, run_test_call,
7 CallEngine, CallHandle, CallSpec, CallState, CallUpdate, EndReason, EngineConfig, EngineEvent, call_channel,
5 8 };
6 9 use session::{Session, SessionConfig, Transport};
7 use tokio::sync::Mutex;
10
11 const START_RETRY_STEPS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(5)];
12 const START_RETRY_STEADY: Duration = Duration::from_secs(10);
13 const NOT_READY: &str = "Calls are not ready yet";
8 14
9 15 pub struct CallLauncher {
10 transport: Arc<dyn Transport>,
11 one_call_at_a_time: Arc<Mutex<()>>,
16 engine: Mutex<Option<CallEngine>>,
12 17 }
13 18
14 19 impl CallLauncher {
15 pub fn new(transport: Arc<dyn Transport>) -> Self {
16 CallLauncher {
17 transport,
18 one_call_at_a_time: Arc::new(Mutex::new(())),
20 pub fn start(
21 transport: Arc<dyn Transport>,
22 ringable: bool,
23 on_event: impl Fn(EngineEvent) + Send + 'static,
24 ) -> Arc<CallLauncher> {
25 let launcher = Arc::new(CallLauncher {
26 engine: Mutex::new(None),
27 });
28 let running = launcher.clone();
29 crate::runtime::handle().spawn(async move {
30 let (engine, mut events) =
31 start_with_retry(|| start_engine(transport.clone(), ringable), &START_RETRY_STEPS, START_RETRY_STEADY).await;
32 eprintln!("calls: engine ready, registered with the registrar");
33 *running.engine.lock().expect("engine lock") = Some(engine);
34 while let Some(event) = events.recv().await {
35 on_event(event);
36 }
37 });
38 launcher
39 }
40
41 fn engine(&self) -> Option<CallEngine> {
42 self.engine.lock().expect("engine lock").clone()
43 }
44
45 pub fn start_call(&self, spec: CallSpec) -> CallHandle {
46 match self.engine() {
47 Some(engine) => engine.start_call(spec),
48 None => failed_handle(NOT_READY),
19 49 }
20 50 }
21 51
22 pub fn start_test_call(&self) -> CallHandle {
23 let (handle, control) = call_channel();
24 let transport = self.transport.clone();
25 let gate = self.one_call_at_a_time.clone();
26 crate::runtime::handle().spawn(async move {
27 let _previous_call_finished = gate.lock().await;
28 let sessions = async {
29 let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;
30 let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;
31 Ok::<_, session::Error>((session, poll_session))
32 };
33 match sessions.await {
34 Ok((session, poll_session)) => {
35 let _ = run_test_call(&session, &poll_session, TestCallOptions::default(), control).await;
52 pub async fn accept_ring(&self, ring_id: u64) -> Option<CallHandle> {
53 self.engine()?.accept_ring(ring_id).await
54 }
55
56 pub fn decline_ring(&self, ring_id: u64) {
57 if let Some(engine) = self.engine() {
58 engine.decline_ring(ring_id);
59 }
60 }
61
62 pub fn drop_ring(&self, ring_id: u64) {
63 if let Some(engine) = self.engine() {
64 engine.drop_ring(ring_id);
65 }
66 }
67
68 pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {
69 let session = self.engine()?.session();
70 fetch_live_meeting(&session, thread_id).await.ok().flatten()
71 }
72 }
73
74 async fn start_with_retry<T, E, F, S>(mut start: S, steps: &[Duration], steady: Duration) -> T
75 where
76 T: Send + 'static,
77 E: std::fmt::Display + Send + 'static,
78 F: Future<Output = Result<T, E>> + Send + 'static,
79 S: FnMut() -> F,
80 {
81 let mut last_failure = String::new();
82 let mut failures = 0usize;
83 loop {
84 let failure = match tokio::spawn(start()).await {
85 Ok(Ok(started)) => return started,
86 Ok(Err(error)) => error.to_string(),
87 Err(join_error) => format!("start task panicked: {join_error}"),
88 };
89 let delay = steps.get(failures).copied().unwrap_or(steady);
90 failures += 1;
91 if failure != last_failure {
92 eprintln!("calls: engine start failed, retrying in {}s: {failure}", delay.as_secs());
93 last_failure = failure;
94 }
95 tokio::time::sleep(delay).await;
96 }
97 }
98
99 async fn start_engine(
100 transport: Arc<dyn Transport>,
101 ringable: bool,
102 ) -> calling::Result<(CallEngine, tokio::sync::mpsc::UnboundedReceiver<EngineEvent>)> {
103 let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;
104 let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;
105 let config = EngineConfig {
106 ringable,
107 ..EngineConfig::default()
108 };
109 CallEngine::start(session, poll_session, config).await
110 }
111
112 fn failed_handle(message: &str) -> CallHandle {
113 let (handle, control) = call_channel();
114 control.send(CallUpdate::State(CallState::Ended {
115 reason: EndReason::Failed(message.to_owned()),
116 }));
117 handle
118 }
119
120 #[cfg(test)]
121 mod tests {
122 use std::sync::atomic::{AtomicU32, Ordering};
123
124 use super::*;
125
126 #[test]
127 fn engine_start_survives_errors_and_panics() {
128 let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
129 let attempts = Arc::new(AtomicU32::new(0));
130 let counter = attempts.clone();
131 let started = runtime.block_on(start_with_retry(
132 move || {
133 let attempt = counter.fetch_add(1, Ordering::SeqCst);
134 async move {
135 match attempt {
136 0 => panic!("boom"),
137 1 => Err("registrar_http_500".to_owned()),
138 _ => Ok(attempt),
139 }
36 140 }
37 Err(error) => control.send(CallUpdate::State(CallState::Ended {
38 reason: EndReason::Failed(crate::notice::short_error(&error)),
39 })),
40 }
41 });
42 handle
141 },
142 &[Duration::ZERO],
143 Duration::ZERO,
144 ));
145 assert_eq!(started, 2);
146 assert_eq!(attempts.load(Ordering::SeqCst), 3);
43 147 }
44 148 }
@@ -1,44 +1,148 @@
1use std::sync::Arc;
1use std::future::Future;
2use std::sync::{Arc, Mutex};
3use std::time::Duration;
2
4
5use calling::meeting::{LiveMeeting, fetch_live_meeting};
3use calling::{
6use calling::{
4 CallHandle, CallState, CallUpdate, EndReason, TestCallOptions, call_channel, run_test_call,
7 CallEngine, CallHandle, CallSpec, CallState, CallUpdate, EndReason, EngineConfig, EngineEvent, call_channel,
5};
8};
6use session::{Session, SessionConfig, Transport};
9use session::{Session, SessionConfig, Transport};
7use tokio::sync::Mutex;
10
11const START_RETRY_STEPS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(5)];
12const START_RETRY_STEADY: Duration = Duration::from_secs(10);
13const NOT_READY: &str = "Calls are not ready yet";
8
14
9pub struct CallLauncher {
15pub struct CallLauncher {
10 transport: Arc<dyn Transport>,
16 engine: Mutex<Option<CallEngine>>,
11 one_call_at_a_time: Arc<Mutex<()>>,
12}
17}
13
18
14impl CallLauncher {
19impl CallLauncher {
15 pub fn new(transport: Arc<dyn Transport>) -> Self {
20 pub fn start(
16 CallLauncher {
21 transport: Arc<dyn Transport>,
17 transport,
22 ringable: bool,
18 one_call_at_a_time: Arc::new(Mutex::new(())),
23 on_event: impl Fn(EngineEvent) + Send + 'static,
24 ) -> Arc<CallLauncher> {
25 let launcher = Arc::new(CallLauncher {
26 engine: Mutex::new(None),
27 });
28 let running = launcher.clone();
29 crate::runtime::handle().spawn(async move {
30 let (engine, mut events) =
31 start_with_retry(|| start_engine(transport.clone(), ringable), &START_RETRY_STEPS, START_RETRY_STEADY).await;
32 eprintln!("calls: engine ready, registered with the registrar");
33 *running.engine.lock().expect("engine lock") = Some(engine);
34 while let Some(event) = events.recv().await {
35 on_event(event);
36 }
37 });
38 launcher
39 }
40
41 fn engine(&self) -> Option<CallEngine> {
42 self.engine.lock().expect("engine lock").clone()
43 }
44
45 pub fn start_call(&self, spec: CallSpec) -> CallHandle {
46 match self.engine() {
47 Some(engine) => engine.start_call(spec),
48 None => failed_handle(NOT_READY),
19 }
49 }
20 }
50 }
21
51
22 pub fn start_test_call(&self) -> CallHandle {
52 pub async fn accept_ring(&self, ring_id: u64) -> Option<CallHandle> {
23 let (handle, control) = call_channel();
53 self.engine()?.accept_ring(ring_id).await
24 let transport = self.transport.clone();
54 }
25 let gate = self.one_call_at_a_time.clone();
55
26 crate::runtime::handle().spawn(async move {
56 pub fn decline_ring(&self, ring_id: u64) {
27 let _previous_call_finished = gate.lock().await;
57 if let Some(engine) = self.engine() {
28 let sessions = async {
58 engine.decline_ring(ring_id);
29 let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;
59 }
30 let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;
60 }
31 Ok::<_, session::Error>((session, poll_session))
61
32 };
62 pub fn drop_ring(&self, ring_id: u64) {
33 match sessions.await {
63 if let Some(engine) = self.engine() {
34 Ok((session, poll_session)) => {
64 engine.drop_ring(ring_id);
35 let _ = run_test_call(&session, &poll_session, TestCallOptions::default(), control).await;
65 }
66 }
67
68 pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {
69 let session = self.engine()?.session();
70 fetch_live_meeting(&session, thread_id).await.ok().flatten()
71 }
72}
73
74async fn start_with_retry<T, E, F, S>(mut start: S, steps: &[Duration], steady: Duration) -> T
75where
76 T: Send + 'static,
77 E: std::fmt::Display + Send + 'static,
78 F: Future<Output = Result<T, E>> + Send + 'static,
79 S: FnMut() -> F,
80{
81 let mut last_failure = String::new();
82 let mut failures = 0usize;
83 loop {
84 let failure = match tokio::spawn(start()).await {
85 Ok(Ok(started)) => return started,
86 Ok(Err(error)) => error.to_string(),
87 Err(join_error) => format!("start task panicked: {join_error}"),
88 };
89 let delay = steps.get(failures).copied().unwrap_or(steady);
90 failures += 1;
91 if failure != last_failure {
92 eprintln!("calls: engine start failed, retrying in {}s: {failure}", delay.as_secs());
93 last_failure = failure;
94 }
95 tokio::time::sleep(delay).await;
96 }
97}
98
99async fn start_engine(
100 transport: Arc<dyn Transport>,
101 ringable: bool,
102) -> calling::Result<(CallEngine, tokio::sync::mpsc::UnboundedReceiver<EngineEvent>)> {
103 let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;
104 let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;
105 let config = EngineConfig {
106 ringable,
107 ..EngineConfig::default()
108 };
109 CallEngine::start(session, poll_session, config).await
110}
111
112fn failed_handle(message: &str) -> CallHandle {
113 let (handle, control) = call_channel();
114 control.send(CallUpdate::State(CallState::Ended {
115 reason: EndReason::Failed(message.to_owned()),
116 }));
117 handle
118}
119
120#[cfg(test)]
121mod tests {
122 use std::sync::atomic::{AtomicU32, Ordering};
123
124 use super::*;
125
126 #[test]
127 fn engine_start_survives_errors_and_panics() {
128 let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
129 let attempts = Arc::new(AtomicU32::new(0));
130 let counter = attempts.clone();
131 let started = runtime.block_on(start_with_retry(
132 move || {
133 let attempt = counter.fetch_add(1, Ordering::SeqCst);
134 async move {
135 match attempt {
136 0 => panic!("boom"),
137 1 => Err("registrar_http_500".to_owned()),
138 _ => Ok(attempt),
139 }
36 }
140 }
37 Err(error) => control.send(CallUpdate::State(CallState::Ended {
141 },
38 reason: EndReason::Failed(crate::notice::short_error(&error)),
142 &[Duration::ZERO],
39 })),
143 Duration::ZERO,
40 }
144 ));
41 });
145 assert_eq!(started, 2);
42 handle
146 assert_eq!(attempts.load(Ordering::SeqCst), 3);
43 }
147 }
44}
148}
crates/app/src/call/mod.rs +5 −1
@@ -2,6 +2,10 @@ mod actions;
2 2 mod demo;
3 3 mod launcher;
4 4 mod model;
5 mod ring;
6 mod target;
5 7
6 8 pub use launcher::CallLauncher;
7 pub use model::{ActiveCall, CallModel};
9 pub use model::{ActiveCall, CallKind, CallModel, GridLayout, TileSize, TileState, grid_layout, tile_size};
10 pub use ring::{MissedCall, RingEntry, Rings};
11 pub use target::plan_for_chat;
@@ -2,6 +2,10 @@ mod actions;
2mod demo;
2mod demo;
3mod launcher;
3mod launcher;
4mod model;
4mod model;
5mod ring;
6mod target;
5
7
6pub use launcher::CallLauncher;
8pub use launcher::CallLauncher;
7pub use model::{ActiveCall, CallModel};
9pub use model::{ActiveCall, CallKind, CallModel, GridLayout, TileSize, TileState, grid_layout, tile_size};
10pub use ring::{MissedCall, RingEntry, Rings};
11pub use target::plan_for_chat;
crates/app/src/call/model.rs +404 −20
@@ -1,53 +1,207 @@
1 1 use std::time::{Duration, Instant};
2 2
3 3 use calling::{
4 CallCommand, CallState, CallUpdate, DeviceChoice, DeviceLists, EndReason, SpeakingDetector,
4 CallCommand, CallState, CallUpdate, DeviceChoice, DeviceLists, EndKind, EndReason, Progress, RosterEntry,
5 SpeakingDetector,
5 6 };
6 7 use tokio::sync::mpsc::UnboundedSender;
7 8
8 9 pub const TEST_CALL_TITLE: &str = "Test call";
10 pub const ECHO_NAME: &str = "Teams echo";
11 pub const ECHO_MRI: &str = calling::signaling::ECHO_BOT_MRI;
12 pub const MAX_TILES: usize = 9;
13 const ORGID_PREFIX: &str = "8:orgid:";
14 const WIDE_TILES: usize = 2;
15 const MEDIUM_TILES: usize = 4;
9 16
10 17 pub struct ActiveCall {
11 18 pub id: u64,
12 19 pub model: CallModel,
13 20 pub commands: UnboundedSender<CallCommand>,
14 21 pub viewing: bool,
22 pub conversation_id: Option<String>,
23 }
24
25 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
26 pub enum CallKind {
27 Test,
28 Direct,
29 Group,
30 Meeting,
31 }
32
33 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
34 pub enum TileState {
35 Invited,
36 Present,
37 InLobby,
38 Left,
39 }
40
41 #[derive(Debug, Clone, PartialEq, Eq)]
42 pub struct Tile {
43 pub mri: String,
44 pub user_id: Option<String>,
45 pub name: String,
46 pub muted: bool,
47 pub state: TileState,
48 pub invited: bool,
49 }
50
51 impl Tile {
52 pub fn invited(mri: &str, name: &str) -> Tile {
53 Tile {
54 mri: mri.to_owned(),
55 user_id: mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
56 name: name.to_owned(),
57 muted: false,
58 state: TileState::Invited,
59 invited: true,
60 }
61 }
62 }
63
64 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
65 pub struct GridLayout {
66 pub shown_others: usize,
67 pub hidden: usize,
68 }
69
70 pub fn grid_layout(others: usize) -> GridLayout {
71 let total = others + 1;
72 if total <= MAX_TILES {
73 return GridLayout {
74 shown_others: others,
75 hidden: 0,
76 };
77 }
78 let shown_others = MAX_TILES - 2;
79 GridLayout {
80 shown_others,
81 hidden: others - shown_others,
82 }
83 }
84
85 #[derive(Debug, Clone, Copy, PartialEq)]
86 pub struct TileSize {
87 pub width: f32,
88 pub height: f32,
89 pub avatar: f32,
90 }
91
92 pub fn tile_size(cells: usize) -> TileSize {
93 if cells <= WIDE_TILES {
94 TileSize {
95 width: 260.,
96 height: 210.,
97 avatar: 96.,
98 }
99 } else if cells <= MEDIUM_TILES {
100 TileSize {
101 width: 220.,
102 height: 180.,
103 avatar: 72.,
104 }
105 } else {
106 TileSize {
107 width: 190.,
108 height: 150.,
109 avatar: 56.,
110 }
111 }
15 112 }
16 113
17 114 #[derive(Debug, Clone)]
18 115 pub struct CallModel {
19 116 pub title: String,
117 pub kind: CallKind,
118 pub peer_name: String,
20 119 pub state: CallState,
120 pub progress: Option<Progress>,
21 121 pub muted: bool,
22 122 pub listen_only: bool,
123 pub lobby: bool,
124 pub can_end_meeting: bool,
125 pub incoming: bool,
23 126 pub input: DeviceChoice,
24 127 pub output: DeviceChoice,
25 128 pub devices: DeviceLists,
26 129 pub local_speaking: bool,
27 130 pub remote_speaking: bool,
131 pub speaking_mris: Vec<String>,
28 132 pub connected_since: Option<Instant>,
133 pub own_mri: Option<String>,
134 pub tiles: Vec<Tile>,
29 135 local_detector: SpeakingDetector,
30 136 remote_detector: SpeakingDetector,
31 137 }
32 138
33 139 impl CallModel {
34 pub fn new(title: &str) -> Self {
140 fn base(kind: CallKind, title: &str, peer_name: &str, tiles: Vec<Tile>) -> Self {
35 141 CallModel {
36 142 title: title.to_owned(),
143 kind,
144 peer_name: peer_name.to_owned(),
37 145 state: CallState::Connecting,
146 progress: None,
38 147 muted: false,
39 148 listen_only: false,
149 lobby: false,
150 can_end_meeting: false,
151 incoming: false,
40 152 input: DeviceChoice::SystemDefault,
41 153 output: DeviceChoice::SystemDefault,
42 154 devices: DeviceLists::default(),
43 155 local_speaking: false,
44 156 remote_speaking: false,
157 speaking_mris: Vec::new(),
45 158 connected_since: None,
159 own_mri: None,
160 tiles,
46 161 local_detector: SpeakingDetector::default(),
47 162 remote_detector: SpeakingDetector::default(),
48 163 }
49 164 }
50 165
166 pub fn test() -> Self {
167 Self::base(
168 CallKind::Test,
169 TEST_CALL_TITLE,
170 ECHO_NAME,
171 vec![Tile::invited(ECHO_MRI, ECHO_NAME)],
172 )
173 }
174
175 pub fn people(title: &str, callees: &[(String, String)]) -> Self {
176 let kind = if callees.len() == 1 { CallKind::Direct } else { CallKind::Group };
177 let peer_name = match callees {
178 [(_, name)] => name.clone(),
179 _ => title.to_owned(),
180 };
181 let tiles = callees.iter().map(|(mri, name)| Tile::invited(mri, name)).collect();
182 Self::base(kind, title, &peer_name, tiles)
183 }
184
185 pub fn meeting(title: &str, can_end_meeting: bool) -> Self {
186 let mut model = Self::base(CallKind::Meeting, title, title, Vec::new());
187 model.can_end_meeting = can_end_meeting;
188 model
189 }
190
191 pub fn incoming(title: &str, caller_mri: &str, caller_name: &str) -> Self {
192 let mut model = Self::base(
193 CallKind::Direct,
194 title,
195 caller_name,
196 vec![Tile {
197 state: TileState::Present,
198 ..Tile::invited(caller_mri, caller_name)
199 }],
200 );
201 model.incoming = true;
202 model
203 }
204
51 205 pub fn apply(&mut self, update: CallUpdate) {
52 206 match update {
53 207 CallUpdate::State(state) => {
@@ -77,21 +231,103 @@ impl CallModel {
77 231 }
78 232 CallUpdate::ListenOnly(listen_only) => self.listen_only = listen_only,
79 233 CallUpdate::Stats { .. } => {}
234 CallUpdate::Progress(progress) => self.progress = Some(progress),
235 CallUpdate::Roster(entries) => self.apply_roster(&entries),
236 CallUpdate::Speakers(mris) => self.speaking_mris = mris,
237 CallUpdate::Lobby(lobby) => self.lobby = lobby,
238 CallUpdate::OwnIdentity { mri } => self.own_mri = Some(mri),
80 239 }
81 240 }
82 241
83 242 fn silence(&mut self) {
84 243 self.local_speaking = false;
85 244 self.remote_speaking = false;
245 self.speaking_mris.clear();
86 246 self.local_detector.reset();
87 247 self.remote_detector.reset();
88 248 }
89 249
250 fn apply_roster(&mut self, entries: &[RosterEntry]) {
251 for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {
252 let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };
253 match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
254 Some(tile) => {
255 tile.state = state;
256 tile.muted = entry.muted;
257 if tile.name.is_empty() {
258 tile.name = entry.display_name.clone();
259 }
260 }
261 None => self.tiles.push(Tile {
262 mri: entry.mri.clone(),
263 user_id: entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
264 name: entry.display_name.clone(),
265 muted: entry.muted,
266 state,
267 invited: false,
268 }),
269 }
270 }
271 let own_mri = self.own_mri.clone();
272 let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
273 self.tiles.retain_mut(|tile| {
274 if listed(&tile.mri) || Some(&tile.mri) == own_mri.as_ref() {
275 return true;
276 }
277 match (tile.invited, tile.state) {
278 (true, TileState::Invited) => true,
279 (true, _) => {
280 tile.state = TileState::Left;
281 true
282 }
283 (false, _) => false,
284 }
285 });
286 }
287
288 pub fn visible_tiles(&self) -> Vec<&Tile> {
289 let mut tiles: Vec<&Tile> = self.tiles.iter().filter(|tile| tile.state != TileState::InLobby).collect();
290 tiles.sort_by_key(|tile| match tile.state {
291 TileState::Present => 0,
292 TileState::Invited => 1,
293 _ => 2,
294 });
295 tiles
296 }
297
298 pub fn tile_speaking(&self, tile: &Tile) -> bool {
299 if self.speaking_mris.contains(&tile.mri) {
300 return true;
301 }
302 let only_remote = self.tiles.len() == 1;
303 only_remote && tile.state != TileState::Left && self.remote_speaking
304 }
305
306 pub fn tile_caption(&self, tile: &Tile) -> Option<&'static str> {
307 match tile.state {
308 TileState::Invited => Some(match self.progress {
309 Some(Progress::Ringing) => "Ringing",
310 _ => "Calling...",
311 }),
312 TileState::Left => Some("Left"),
313 TileState::Present | TileState::InLobby => None,
314 }
315 }
316
90 317 pub fn elapsed(&self, now: Instant) -> Option<Duration> {
91 318 self.connected_since
92 319 .map(|since| now.saturating_duration_since(since))
93 320 }
94 321
322 pub fn connecting_text(&self) -> &'static str {
323 match (self.kind, self.progress) {
324 (CallKind::Meeting, _) => "Joining...",
325 (_, _) if self.incoming => "Connecting...",
326 (_, Some(Progress::Ringing)) => "Ringing",
327 _ => "Calling...",
328 }
329 }
330
95 331 pub fn is_connecting(&self) -> bool {
96 332 matches!(self.state, CallState::Connecting)
97 333 }
@@ -126,15 +362,20 @@ pub fn format_elapsed(elapsed: Duration) -> String {
126 362 }
127 363 }
128 364
129 pub fn ended_notice(reason: &EndReason, elapsed: Option<Duration>) -> String {
130 match (reason, elapsed) {
131 (EndReason::Cancelled, _) => "Call cancelled".to_owned(),
132 (EndReason::Dropped, _) => "Call dropped".to_owned(),
133 (EndReason::Failed(message), _) => format!("Test call failed: {message}"),
134 (EndReason::LocalHangup | EndReason::RemoteEnded, Some(elapsed)) => {
135 format!("Call ended {}", format_elapsed(elapsed))
136 }
137 (EndReason::LocalHangup | EndReason::RemoteEnded, None) => "Call ended".to_owned(),
365 pub fn ended_notice(reason: &EndReason, elapsed: Option<Duration>, peer_name: &str) -> String {
366 let ended = || match elapsed {
367 Some(elapsed) => format!("Call ended {}", format_elapsed(elapsed)),
368 None => "Call ended".to_owned(),
369 };
370 match reason {
371 EndReason::Cancelled => "Call cancelled".to_owned(),
372 EndReason::Dropped => "Call dropped".to_owned(),
373 EndReason::Failed(message) => format!("Call failed: {message}"),
374 EndReason::LocalHangup => ended(),
375 EndReason::Remote(EndKind::Declined) => format!("{peer_name} declined"),
376 EndReason::Remote(EndKind::NoAnswer) => "No answer".to_owned(),
377 EndReason::Remote(EndKind::Unavailable) => format!("{peer_name} is not available"),
378 EndReason::Remote(_) => ended(),
138 379 }
139 380 }
140 381
@@ -143,13 +384,28 @@ mod tests {
143 384 use super::*;
144 385
145 386 fn connected_model() -> CallModel {
146 let mut model = CallModel::new(TEST_CALL_TITLE);
387 let mut model = CallModel::test();
147 388 model.apply(CallUpdate::State(CallState::Connected {
148 389 since: Instant::now(),
149 390 }));
150 391 model
151 392 }
152 393
394 fn entry(mri: &str, name: &str, muted: bool, in_lobby: bool) -> RosterEntry {
395 RosterEntry {
396 mri: mri.into(),
397 display_name: name.into(),
398 muted,
399 in_lobby,
400 }
401 }
402
403 fn meeting_with_me() -> CallModel {
404 let mut model = CallModel::meeting("Standup", false);
405 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
406 model
407 }
408
153 409 #[test]
154 410 fn elapsed_text_is_minutes_and_seconds() {
155 411 assert_eq!(format_elapsed(Duration::from_secs(42)), "00:42");
@@ -207,14 +463,30 @@ mod tests {
207 463 #[test]
208 464 fn notices_for_every_end_reason() {
209 465 let elapsed = Some(Duration::from_secs(42));
210 assert_eq!(ended_notice(&EndReason::LocalHangup, elapsed), "Call ended 00:42");
211 assert_eq!(ended_notice(&EndReason::RemoteEnded, elapsed), "Call ended 00:42");
212 assert_eq!(ended_notice(&EndReason::Cancelled, None), "Call cancelled");
213 assert_eq!(ended_notice(&EndReason::Dropped, elapsed), "Call dropped");
214 assert_eq!(
215 ended_notice(&EndReason::Failed("no route".into()), None),
216 "Test call failed: no route"
217 );
466 let notice = |reason: EndReason, elapsed| ended_notice(&reason, elapsed, "Bea");
467 assert_eq!(notice(EndReason::LocalHangup, elapsed), "Call ended 00:42");
468 assert_eq!(notice(EndReason::Remote(EndKind::Normal), elapsed), "Call ended 00:42");
469 assert_eq!(notice(EndReason::Remote(EndKind::Normal), None), "Call ended");
470 assert_eq!(notice(EndReason::Cancelled, None), "Call cancelled");
471 assert_eq!(notice(EndReason::Dropped, elapsed), "Call dropped");
472 assert_eq!(notice(EndReason::Failed("no route".into()), None), "Call failed: no route");
473 assert_eq!(notice(EndReason::Remote(EndKind::Declined), None), "Bea declined");
474 assert_eq!(notice(EndReason::Remote(EndKind::NoAnswer), None), "No answer");
475 assert_eq!(notice(EndReason::Remote(EndKind::Unavailable), None), "Bea is not available");
476 assert_eq!(notice(EndReason::Remote(EndKind::Cancelled), None), "Call ended");
477 assert_eq!(notice(EndReason::Remote(EndKind::Other), None), "Call ended");
478 assert_eq!(notice(EndReason::Remote(EndKind::AnsweredElsewhere), None), "Call ended");
479 }
480
481 #[test]
482 fn the_connecting_text_follows_the_kind_of_call() {
483 let mut direct = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
484 assert_eq!(direct.connecting_text(), "Calling...");
485 direct.apply(CallUpdate::Progress(Progress::Ringing));
486 assert_eq!(direct.connecting_text(), "Ringing");
487 assert_eq!(CallModel::meeting("Standup", false).connecting_text(), "Joining...");
488 assert_eq!(CallModel::incoming("Bea", "8:orgid:b", "Bea").connecting_text(), "Connecting...");
489 assert_eq!(CallModel::test().connecting_text(), "Calling...");
218 490 }
219 491
220 492 #[test]
@@ -224,4 +496,116 @@ mod tests {
224 496 model.apply(CallUpdate::ListenOnly(true));
225 497 assert!(!model.can_unmute());
226 498 }
499
500 #[test]
501 fn callees_start_invited_and_follow_the_progress() {
502 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
503 assert_eq!(model.kind, CallKind::Direct);
504 assert_eq!(model.peer_name, "Bea");
505 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Calling..."));
506 model.apply(CallUpdate::Progress(Progress::Ringing));
507 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Ringing"));
508 model.apply(CallUpdate::Roster(vec![entry("8:orgid:b", "Bea", false, false)]));
509 assert_eq!(model.tiles[0].state, TileState::Present);
510 assert_eq!(model.tile_caption(&model.tiles[0]), None);
511 }
512
513 #[test]
514 fn several_callees_make_a_group_call_named_after_the_chat() {
515 let model = CallModel::people(
516 "Retro team",
517 &[("8:orgid:b".into(), "Bea".into()), ("8:orgid:c".into(), "Cy".into())],
518 );
519 assert_eq!(model.kind, CallKind::Group);
520 assert_eq!(model.peer_name, "Retro team");
521 assert_eq!(model.tiles.len(), 2);
522 }
523
524 #[test]
525 fn roster_adds_guests_updates_mute_and_drops_leavers() {
526 let mut model = meeting_with_me();
527 model.apply(CallUpdate::Roster(vec![
528 entry("8:orgid:me", "Me", false, false),
529 entry("8:orgid:a", "Ana", true, false),
530 entry("8:orgid:b", "Bo", false, false),
531 ]));
532 assert_eq!(model.tiles.len(), 2);
533 assert!(model.tiles.iter().find(|tile| tile.name == "Ana").unwrap().muted);
534 model.apply(CallUpdate::Roster(vec![entry("8:orgid:me", "Me", false, false), entry("8:orgid:b", "Bo", false, false)]));
535 assert_eq!(model.tiles.len(), 1);
536 assert_eq!(model.tiles[0].name, "Bo");
537 }
538
539 #[test]
540 fn an_invited_callee_who_leaves_stays_as_left() {
541 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
542 model.apply(CallUpdate::Roster(vec![entry("8:orgid:b", "Bea", false, false)]));
543 model.apply(CallUpdate::Roster(Vec::new()));
544 assert_eq!(model.tiles[0].state, TileState::Left);
545 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Left"));
546 }
547
548 #[test]
549 fn lobby_guests_get_no_tile() {
550 let mut model = meeting_with_me();
551 model.apply(CallUpdate::Roster(vec![
552 entry("8:orgid:a", "Ana", false, false),
553 entry("8:orgid:g", "Guest", false, true),
554 ]));
555 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
556 assert_eq!(names, vec!["Ana"]);
557 }
558
559 #[test]
560 fn the_lobby_flag_follows_the_call() {
561 let mut model = meeting_with_me();
562 model.apply(CallUpdate::Lobby(true));
563 assert!(model.lobby);
564 model.apply(CallUpdate::Lobby(false));
565 assert!(!model.lobby);
566 }
567
568 #[test]
569 fn speakers_light_their_own_tile_and_a_lone_remote_follows_the_level() {
570 let mut model = meeting_with_me();
571 model.apply(CallUpdate::Roster(vec![
572 entry("8:orgid:a", "Ana", false, false),
573 entry("8:orgid:b", "Bo", false, false),
574 ]));
575 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
576 model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
577 let tiles: Vec<Tile> = model.tiles.clone();
578 assert!(!model.tile_speaking(&tiles[0]));
579 assert!(model.tile_speaking(&tiles[1]));
580 let mut lone = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
581 lone.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
582 lone.apply(CallUpdate::Levels { local: 0.0, remote: 0.5 });
583 assert!(lone.tile_speaking(&lone.tiles[0].clone()));
584 }
585
586 #[test]
587 fn more_than_nine_cells_collapse_into_a_plus_n_tile() {
588 assert_eq!(grid_layout(0), GridLayout { shown_others: 0, hidden: 0 });
589 assert_eq!(grid_layout(8), GridLayout { shown_others: 8, hidden: 0 });
590 assert_eq!(grid_layout(9), GridLayout { shown_others: 7, hidden: 2 });
591 assert_eq!(grid_layout(30), GridLayout { shown_others: 7, hidden: 23 });
592 }
593
594 #[test]
595 fn crowded_calls_get_smaller_tiles() {
596 assert_eq!(tile_size(2).avatar, 96.);
597 assert_eq!(tile_size(4).avatar, 72.);
598 assert_eq!(tile_size(9).avatar, 56.);
599 }
600
601 #[test]
602 fn present_guests_sort_before_waiting_ones() {
603 let mut model = CallModel::people(
604 "Group",
605 &[("8:orgid:b".into(), "Bea".into()), ("8:orgid:c".into(), "Cy".into())],
606 );
607 model.apply(CallUpdate::Roster(vec![entry("8:orgid:c", "Cy", false, false)]));
608 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
609 assert_eq!(names, vec!["Cy", "Bea"]);
610 }
227 611 }
@@ -1,53 +1,207 @@
1use std::time::{Duration, Instant};
1use std::time::{Duration, Instant};
2
2
3use calling::{
3use calling::{
4 CallCommand, CallState, CallUpdate, DeviceChoice, DeviceLists, EndReason, SpeakingDetector,
4 CallCommand, CallState, CallUpdate, DeviceChoice, DeviceLists, EndKind, EndReason, Progress, RosterEntry,
5 SpeakingDetector,
5};
6};
6use tokio::sync::mpsc::UnboundedSender;
7use tokio::sync::mpsc::UnboundedSender;
7
8
8pub const TEST_CALL_TITLE: &str = "Test call";
9pub const TEST_CALL_TITLE: &str = "Test call";
10pub const ECHO_NAME: &str = "Teams echo";
11pub const ECHO_MRI: &str = calling::signaling::ECHO_BOT_MRI;
12pub const MAX_TILES: usize = 9;
13const ORGID_PREFIX: &str = "8:orgid:";
14const WIDE_TILES: usize = 2;
15const MEDIUM_TILES: usize = 4;
9
16
10pub struct ActiveCall {
17pub struct ActiveCall {
11 pub id: u64,
18 pub id: u64,
12 pub model: CallModel,
19 pub model: CallModel,
13 pub commands: UnboundedSender<CallCommand>,
20 pub commands: UnboundedSender<CallCommand>,
14 pub viewing: bool,
21 pub viewing: bool,
22 pub conversation_id: Option<String>,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum CallKind {
27 Test,
28 Direct,
29 Group,
30 Meeting,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum TileState {
35 Invited,
36 Present,
37 InLobby,
38 Left,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Tile {
43 pub mri: String,
44 pub user_id: Option<String>,
45 pub name: String,
46 pub muted: bool,
47 pub state: TileState,
48 pub invited: bool,
49}
50
51impl Tile {
52 pub fn invited(mri: &str, name: &str) -> Tile {
53 Tile {
54 mri: mri.to_owned(),
55 user_id: mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
56 name: name.to_owned(),
57 muted: false,
58 state: TileState::Invited,
59 invited: true,
60 }
61 }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct GridLayout {
66 pub shown_others: usize,
67 pub hidden: usize,
68}
69
70pub fn grid_layout(others: usize) -> GridLayout {
71 let total = others + 1;
72 if total <= MAX_TILES {
73 return GridLayout {
74 shown_others: others,
75 hidden: 0,
76 };
77 }
78 let shown_others = MAX_TILES - 2;
79 GridLayout {
80 shown_others,
81 hidden: others - shown_others,
82 }
83}
84
85#[derive(Debug, Clone, Copy, PartialEq)]
86pub struct TileSize {
87 pub width: f32,
88 pub height: f32,
89 pub avatar: f32,
90}
91
92pub fn tile_size(cells: usize) -> TileSize {
93 if cells <= WIDE_TILES {
94 TileSize {
95 width: 260.,
96 height: 210.,
97 avatar: 96.,
98 }
99 } else if cells <= MEDIUM_TILES {
100 TileSize {
101 width: 220.,
102 height: 180.,
103 avatar: 72.,
104 }
105 } else {
106 TileSize {
107 width: 190.,
108 height: 150.,
109 avatar: 56.,
110 }
111 }
15}
112}
16
113
17#[derive(Debug, Clone)]
114#[derive(Debug, Clone)]
18pub struct CallModel {
115pub struct CallModel {
19 pub title: String,
116 pub title: String,
117 pub kind: CallKind,
118 pub peer_name: String,
20 pub state: CallState,
119 pub state: CallState,
120 pub progress: Option<Progress>,
21 pub muted: bool,
121 pub muted: bool,
22 pub listen_only: bool,
122 pub listen_only: bool,
123 pub lobby: bool,
124 pub can_end_meeting: bool,
125 pub incoming: bool,
23 pub input: DeviceChoice,
126 pub input: DeviceChoice,
24 pub output: DeviceChoice,
127 pub output: DeviceChoice,
25 pub devices: DeviceLists,
128 pub devices: DeviceLists,
26 pub local_speaking: bool,
129 pub local_speaking: bool,
27 pub remote_speaking: bool,
130 pub remote_speaking: bool,
131 pub speaking_mris: Vec<String>,
28 pub connected_since: Option<Instant>,
132 pub connected_since: Option<Instant>,
133 pub own_mri: Option<String>,
134 pub tiles: Vec<Tile>,
29 local_detector: SpeakingDetector,
135 local_detector: SpeakingDetector,
30 remote_detector: SpeakingDetector,
136 remote_detector: SpeakingDetector,
31}
137}
32
138
33impl CallModel {
139impl CallModel {
34 pub fn new(title: &str) -> Self {
140 fn base(kind: CallKind, title: &str, peer_name: &str, tiles: Vec<Tile>) -> Self {
35 CallModel {
141 CallModel {
36 title: title.to_owned(),
142 title: title.to_owned(),
143 kind,
144 peer_name: peer_name.to_owned(),
37 state: CallState::Connecting,
145 state: CallState::Connecting,
146 progress: None,
38 muted: false,
147 muted: false,
39 listen_only: false,
148 listen_only: false,
149 lobby: false,
150 can_end_meeting: false,
151 incoming: false,
40 input: DeviceChoice::SystemDefault,
152 input: DeviceChoice::SystemDefault,
41 output: DeviceChoice::SystemDefault,
153 output: DeviceChoice::SystemDefault,
42 devices: DeviceLists::default(),
154 devices: DeviceLists::default(),
43 local_speaking: false,
155 local_speaking: false,
44 remote_speaking: false,
156 remote_speaking: false,
157 speaking_mris: Vec::new(),
45 connected_since: None,
158 connected_since: None,
159 own_mri: None,
160 tiles,
46 local_detector: SpeakingDetector::default(),
161 local_detector: SpeakingDetector::default(),
47 remote_detector: SpeakingDetector::default(),
162 remote_detector: SpeakingDetector::default(),
48 }
163 }
49 }
164 }
50
165
166 pub fn test() -> Self {
167 Self::base(
168 CallKind::Test,
169 TEST_CALL_TITLE,
170 ECHO_NAME,
171 vec![Tile::invited(ECHO_MRI, ECHO_NAME)],
172 )
173 }
174
175 pub fn people(title: &str, callees: &[(String, String)]) -> Self {
176 let kind = if callees.len() == 1 { CallKind::Direct } else { CallKind::Group };
177 let peer_name = match callees {
178 [(_, name)] => name.clone(),
179 _ => title.to_owned(),
180 };
181 let tiles = callees.iter().map(|(mri, name)| Tile::invited(mri, name)).collect();
182 Self::base(kind, title, &peer_name, tiles)
183 }
184
185 pub fn meeting(title: &str, can_end_meeting: bool) -> Self {
186 let mut model = Self::base(CallKind::Meeting, title, title, Vec::new());
187 model.can_end_meeting = can_end_meeting;
188 model
189 }
190
191 pub fn incoming(title: &str, caller_mri: &str, caller_name: &str) -> Self {
192 let mut model = Self::base(
193 CallKind::Direct,
194 title,
195 caller_name,
196 vec![Tile {
197 state: TileState::Present,
198 ..Tile::invited(caller_mri, caller_name)
199 }],
200 );
201 model.incoming = true;
202 model
203 }
204
51 pub fn apply(&mut self, update: CallUpdate) {
205 pub fn apply(&mut self, update: CallUpdate) {
52 match update {
206 match update {
53 CallUpdate::State(state) => {
207 CallUpdate::State(state) => {
@@ -77,21 +231,103 @@ impl CallModel {
77 }
231 }
78 CallUpdate::ListenOnly(listen_only) => self.listen_only = listen_only,
232 CallUpdate::ListenOnly(listen_only) => self.listen_only = listen_only,
79 CallUpdate::Stats { .. } => {}
233 CallUpdate::Stats { .. } => {}
234 CallUpdate::Progress(progress) => self.progress = Some(progress),
235 CallUpdate::Roster(entries) => self.apply_roster(&entries),
236 CallUpdate::Speakers(mris) => self.speaking_mris = mris,
237 CallUpdate::Lobby(lobby) => self.lobby = lobby,
238 CallUpdate::OwnIdentity { mri } => self.own_mri = Some(mri),
80 }
239 }
81 }
240 }
82
241
83 fn silence(&mut self) {
242 fn silence(&mut self) {
84 self.local_speaking = false;
243 self.local_speaking = false;
85 self.remote_speaking = false;
244 self.remote_speaking = false;
245 self.speaking_mris.clear();
86 self.local_detector.reset();
246 self.local_detector.reset();
87 self.remote_detector.reset();
247 self.remote_detector.reset();
88 }
248 }
89
249
250 fn apply_roster(&mut self, entries: &[RosterEntry]) {
251 for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {
252 let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };
253 match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
254 Some(tile) => {
255 tile.state = state;
256 tile.muted = entry.muted;
257 if tile.name.is_empty() {
258 tile.name = entry.display_name.clone();
259 }
260 }
261 None => self.tiles.push(Tile {
262 mri: entry.mri.clone(),
263 user_id: entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
264 name: entry.display_name.clone(),
265 muted: entry.muted,
266 state,
267 invited: false,
268 }),
269 }
270 }
271 let own_mri = self.own_mri.clone();
272 let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
273 self.tiles.retain_mut(|tile| {
274 if listed(&tile.mri) || Some(&tile.mri) == own_mri.as_ref() {
275 return true;
276 }
277 match (tile.invited, tile.state) {
278 (true, TileState::Invited) => true,
279 (true, _) => {
280 tile.state = TileState::Left;
281 true
282 }
283 (false, _) => false,
284 }
285 });
286 }
287
288 pub fn visible_tiles(&self) -> Vec<&Tile> {
289 let mut tiles: Vec<&Tile> = self.tiles.iter().filter(|tile| tile.state != TileState::InLobby).collect();
290 tiles.sort_by_key(|tile| match tile.state {
291 TileState::Present => 0,
292 TileState::Invited => 1,
293 _ => 2,
294 });
295 tiles
296 }
297
298 pub fn tile_speaking(&self, tile: &Tile) -> bool {
299 if self.speaking_mris.contains(&tile.mri) {
300 return true;
301 }
302 let only_remote = self.tiles.len() == 1;
303 only_remote && tile.state != TileState::Left && self.remote_speaking
304 }
305
306 pub fn tile_caption(&self, tile: &Tile) -> Option<&'static str> {
307 match tile.state {
308 TileState::Invited => Some(match self.progress {
309 Some(Progress::Ringing) => "Ringing",
310 _ => "Calling...",
311 }),
312 TileState::Left => Some("Left"),
313 TileState::Present | TileState::InLobby => None,
314 }
315 }
316
90 pub fn elapsed(&self, now: Instant) -> Option<Duration> {
317 pub fn elapsed(&self, now: Instant) -> Option<Duration> {
91 self.connected_since
318 self.connected_since
92 .map(|since| now.saturating_duration_since(since))
319 .map(|since| now.saturating_duration_since(since))
93 }
320 }
94
321
322 pub fn connecting_text(&self) -> &'static str {
323 match (self.kind, self.progress) {
324 (CallKind::Meeting, _) => "Joining...",
325 (_, _) if self.incoming => "Connecting...",
326 (_, Some(Progress::Ringing)) => "Ringing",
327 _ => "Calling...",
328 }
329 }
330
95 pub fn is_connecting(&self) -> bool {
331 pub fn is_connecting(&self) -> bool {
96 matches!(self.state, CallState::Connecting)
332 matches!(self.state, CallState::Connecting)
97 }
333 }
@@ -126,15 +362,20 @@ pub fn format_elapsed(elapsed: Duration) -> String {
126 }
362 }
127}
363}
128
364
129pub fn ended_notice(reason: &EndReason, elapsed: Option<Duration>) -> String {
365pub fn ended_notice(reason: &EndReason, elapsed: Option<Duration>, peer_name: &str) -> String {
130 match (reason, elapsed) {
366 let ended = || match elapsed {
131 (EndReason::Cancelled, _) => "Call cancelled".to_owned(),
367 Some(elapsed) => format!("Call ended {}", format_elapsed(elapsed)),
132 (EndReason::Dropped, _) => "Call dropped".to_owned(),
368 None => "Call ended".to_owned(),
133 (EndReason::Failed(message), _) => format!("Test call failed: {message}"),
369 };
134 (EndReason::LocalHangup | EndReason::RemoteEnded, Some(elapsed)) => {
370 match reason {
135 format!("Call ended {}", format_elapsed(elapsed))
371 EndReason::Cancelled => "Call cancelled".to_owned(),
136 }
372 EndReason::Dropped => "Call dropped".to_owned(),
137 (EndReason::LocalHangup | EndReason::RemoteEnded, None) => "Call ended".to_owned(),
373 EndReason::Failed(message) => format!("Call failed: {message}"),
374 EndReason::LocalHangup => ended(),
375 EndReason::Remote(EndKind::Declined) => format!("{peer_name} declined"),
376 EndReason::Remote(EndKind::NoAnswer) => "No answer".to_owned(),
377 EndReason::Remote(EndKind::Unavailable) => format!("{peer_name} is not available"),
378 EndReason::Remote(_) => ended(),
138 }
379 }
139}
380}
140
381
@@ -143,13 +384,28 @@ mod tests {
143 use super::*;
384 use super::*;
144
385
145 fn connected_model() -> CallModel {
386 fn connected_model() -> CallModel {
146 let mut model = CallModel::new(TEST_CALL_TITLE);
387 let mut model = CallModel::test();
147 model.apply(CallUpdate::State(CallState::Connected {
388 model.apply(CallUpdate::State(CallState::Connected {
148 since: Instant::now(),
389 since: Instant::now(),
149 }));
390 }));
150 model
391 model
151 }
392 }
152
393
394 fn entry(mri: &str, name: &str, muted: bool, in_lobby: bool) -> RosterEntry {
395 RosterEntry {
396 mri: mri.into(),
397 display_name: name.into(),
398 muted,
399 in_lobby,
400 }
401 }
402
403 fn meeting_with_me() -> CallModel {
404 let mut model = CallModel::meeting("Standup", false);
405 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
406 model
407 }
408
153 #[test]
409 #[test]
154 fn elapsed_text_is_minutes_and_seconds() {
410 fn elapsed_text_is_minutes_and_seconds() {
155 assert_eq!(format_elapsed(Duration::from_secs(42)), "00:42");
411 assert_eq!(format_elapsed(Duration::from_secs(42)), "00:42");
@@ -207,14 +463,30 @@ mod tests {
207 #[test]
463 #[test]
208 fn notices_for_every_end_reason() {
464 fn notices_for_every_end_reason() {
209 let elapsed = Some(Duration::from_secs(42));
465 let elapsed = Some(Duration::from_secs(42));
210 assert_eq!(ended_notice(&EndReason::LocalHangup, elapsed), "Call ended 00:42");
466 let notice = |reason: EndReason, elapsed| ended_notice(&reason, elapsed, "Bea");
211 assert_eq!(ended_notice(&EndReason::RemoteEnded, elapsed), "Call ended 00:42");
467 assert_eq!(notice(EndReason::LocalHangup, elapsed), "Call ended 00:42");
212 assert_eq!(ended_notice(&EndReason::Cancelled, None), "Call cancelled");
468 assert_eq!(notice(EndReason::Remote(EndKind::Normal), elapsed), "Call ended 00:42");
213 assert_eq!(ended_notice(&EndReason::Dropped, elapsed), "Call dropped");
469 assert_eq!(notice(EndReason::Remote(EndKind::Normal), None), "Call ended");
214 assert_eq!(
470 assert_eq!(notice(EndReason::Cancelled, None), "Call cancelled");
215 ended_notice(&EndReason::Failed("no route".into()), None),
471 assert_eq!(notice(EndReason::Dropped, elapsed), "Call dropped");
216 "Test call failed: no route"
472 assert_eq!(notice(EndReason::Failed("no route".into()), None), "Call failed: no route");
217 );
473 assert_eq!(notice(EndReason::Remote(EndKind::Declined), None), "Bea declined");
474 assert_eq!(notice(EndReason::Remote(EndKind::NoAnswer), None), "No answer");
475 assert_eq!(notice(EndReason::Remote(EndKind::Unavailable), None), "Bea is not available");
476 assert_eq!(notice(EndReason::Remote(EndKind::Cancelled), None), "Call ended");
477 assert_eq!(notice(EndReason::Remote(EndKind::Other), None), "Call ended");
478 assert_eq!(notice(EndReason::Remote(EndKind::AnsweredElsewhere), None), "Call ended");
479 }
480
481 #[test]
482 fn the_connecting_text_follows_the_kind_of_call() {
483 let mut direct = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
484 assert_eq!(direct.connecting_text(), "Calling...");
485 direct.apply(CallUpdate::Progress(Progress::Ringing));
486 assert_eq!(direct.connecting_text(), "Ringing");
487 assert_eq!(CallModel::meeting("Standup", false).connecting_text(), "Joining...");
488 assert_eq!(CallModel::incoming("Bea", "8:orgid:b", "Bea").connecting_text(), "Connecting...");
489 assert_eq!(CallModel::test().connecting_text(), "Calling...");
218 }
490 }
219
491
220 #[test]
492 #[test]
@@ -224,4 +496,116 @@ mod tests {
224 model.apply(CallUpdate::ListenOnly(true));
496 model.apply(CallUpdate::ListenOnly(true));
225 assert!(!model.can_unmute());
497 assert!(!model.can_unmute());
226 }
498 }
499
500 #[test]
501 fn callees_start_invited_and_follow_the_progress() {
502 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
503 assert_eq!(model.kind, CallKind::Direct);
504 assert_eq!(model.peer_name, "Bea");
505 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Calling..."));
506 model.apply(CallUpdate::Progress(Progress::Ringing));
507 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Ringing"));
508 model.apply(CallUpdate::Roster(vec![entry("8:orgid:b", "Bea", false, false)]));
509 assert_eq!(model.tiles[0].state, TileState::Present);
510 assert_eq!(model.tile_caption(&model.tiles[0]), None);
511 }
512
513 #[test]
514 fn several_callees_make_a_group_call_named_after_the_chat() {
515 let model = CallModel::people(
516 "Retro team",
517 &[("8:orgid:b".into(), "Bea".into()), ("8:orgid:c".into(), "Cy".into())],
518 );
519 assert_eq!(model.kind, CallKind::Group);
520 assert_eq!(model.peer_name, "Retro team");
521 assert_eq!(model.tiles.len(), 2);
522 }
523
524 #[test]
525 fn roster_adds_guests_updates_mute_and_drops_leavers() {
526 let mut model = meeting_with_me();
527 model.apply(CallUpdate::Roster(vec![
528 entry("8:orgid:me", "Me", false, false),
529 entry("8:orgid:a", "Ana", true, false),
530 entry("8:orgid:b", "Bo", false, false),
531 ]));
532 assert_eq!(model.tiles.len(), 2);
533 assert!(model.tiles.iter().find(|tile| tile.name == "Ana").unwrap().muted);
534 model.apply(CallUpdate::Roster(vec![entry("8:orgid:me", "Me", false, false), entry("8:orgid:b", "Bo", false, false)]));
535 assert_eq!(model.tiles.len(), 1);
536 assert_eq!(model.tiles[0].name, "Bo");
537 }
538
539 #[test]
540 fn an_invited_callee_who_leaves_stays_as_left() {
541 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
542 model.apply(CallUpdate::Roster(vec![entry("8:orgid:b", "Bea", false, false)]));
543 model.apply(CallUpdate::Roster(Vec::new()));
544 assert_eq!(model.tiles[0].state, TileState::Left);
545 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Left"));
546 }
547
548 #[test]
549 fn lobby_guests_get_no_tile() {
550 let mut model = meeting_with_me();
551 model.apply(CallUpdate::Roster(vec![
552 entry("8:orgid:a", "Ana", false, false),
553 entry("8:orgid:g", "Guest", false, true),
554 ]));
555 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
556 assert_eq!(names, vec!["Ana"]);
557 }
558
559 #[test]
560 fn the_lobby_flag_follows_the_call() {
561 let mut model = meeting_with_me();
562 model.apply(CallUpdate::Lobby(true));
563 assert!(model.lobby);
564 model.apply(CallUpdate::Lobby(false));
565 assert!(!model.lobby);
566 }
567
568 #[test]
569 fn speakers_light_their_own_tile_and_a_lone_remote_follows_the_level() {
570 let mut model = meeting_with_me();
571 model.apply(CallUpdate::Roster(vec![
572 entry("8:orgid:a", "Ana", false, false),
573 entry("8:orgid:b", "Bo", false, false),
574 ]));
575 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
576 model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
577 let tiles: Vec<Tile> = model.tiles.clone();
578 assert!(!model.tile_speaking(&tiles[0]));
579 assert!(model.tile_speaking(&tiles[1]));
580 let mut lone = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
581 lone.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
582 lone.apply(CallUpdate::Levels { local: 0.0, remote: 0.5 });
583 assert!(lone.tile_speaking(&lone.tiles[0].clone()));
584 }
585
586 #[test]
587 fn more_than_nine_cells_collapse_into_a_plus_n_tile() {
588 assert_eq!(grid_layout(0), GridLayout { shown_others: 0, hidden: 0 });
589 assert_eq!(grid_layout(8), GridLayout { shown_others: 8, hidden: 0 });
590 assert_eq!(grid_layout(9), GridLayout { shown_others: 7, hidden: 2 });
591 assert_eq!(grid_layout(30), GridLayout { shown_others: 7, hidden: 23 });
592 }
593
594 #[test]
595 fn crowded_calls_get_smaller_tiles() {
596 assert_eq!(tile_size(2).avatar, 96.);
597 assert_eq!(tile_size(4).avatar, 72.);
598 assert_eq!(tile_size(9).avatar, 56.);
599 }
600
601 #[test]
602 fn present_guests_sort_before_waiting_ones() {
603 let mut model = CallModel::people(
604 "Group",
605 &[("8:orgid:b".into(), "Bea".into()), ("8:orgid:c".into(), "Cy".into())],
606 );
607 model.apply(CallUpdate::Roster(vec![entry("8:orgid:c", "Cy", false, false)]));
608 let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
609 assert_eq!(names, vec!["Cy", "Bea"]);
610 }
227}
611}
crates/app/src/call/ring.rs added +219 −0
@@ -0,0 +1,219 @@
1 use std::time::Instant;
2
3 use calling::{IncomingRing, RingSignal, RingState};
4 use chrono::{DateTime, Utc};
5
6 const ORGID_PREFIX: &str = "8:orgid:";
7
8 #[derive(Debug, Clone)]
9 pub struct RingEntry {
10 pub ring: IncomingRing,
11 pub state: RingState,
12 pub demo: bool,
13 }
14
15 impl RingEntry {
16 pub fn caller_user_id(&self) -> Option<String> {
17 self.ring.caller.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned)
18 }
19
20 pub fn caller_name(&self) -> &str {
21 &self.ring.caller.display_name
22 }
23
24 pub fn subtitle(&self) -> &'static str {
25 match (self.ring.video, self.ring.is_group) {
26 (true, _) => "Incoming call",
27 (false, true) => "Incoming group audio call",
28 (false, false) => "Incoming audio call",
29 }
30 }
31
32 pub fn accept_label(&self) -> &'static str {
33 if self.ring.video { "Accept with audio" } else { "Accept" }
34 }
35 }
36
37 #[derive(Debug, Clone, PartialEq, Eq)]
38 pub struct MissedCall {
39 pub caller_mri: String,
40 pub caller_name: String,
41 pub thread_id: Option<String>,
42 pub at: DateTime<Utc>,
43 }
44
45 #[derive(Debug, Clone, PartialEq, Eq)]
46 pub enum RingOutcome {
47 Missed(MissedCall),
48 Gone,
49 }
50
51 #[derive(Default)]
52 pub struct Rings {
53 entries: Vec<RingEntry>,
54 }
55
56 impl Rings {
57 pub fn push(&mut self, ring: IncomingRing, demo: bool, now: Instant) {
58 if self.entries.iter().any(|entry| entry.ring.ring_id == ring.ring_id) {
59 return;
60 }
61 self.entries.push(RingEntry {
62 ring,
63 state: RingState::start(now),
64 demo,
65 });
66 }
67
68 pub fn get(&self, ring_id: u64) -> Option<&RingEntry> {
69 self.entries.iter().find(|entry| entry.ring.ring_id == ring_id)
70 }
71
72 pub fn ringing(&self) -> impl Iterator<Item = &RingEntry> {
73 self.entries.iter().filter(|entry| entry.state.is_ringing())
74 }
75
76 pub fn is_ringing(&self) -> bool {
77 self.ringing().next().is_some()
78 }
79
80 pub fn is_empty(&self) -> bool {
81 self.entries.is_empty()
82 }
83
84 pub fn signal(&mut self, ring_id: u64, signal: RingSignal, now: Instant) -> Option<RingOutcome> {
85 let index = self.entries.iter().position(|entry| entry.ring.ring_id == ring_id)?;
86 let next = self.entries[index].state.next(signal, now);
87 self.entries[index].state = next;
88 self.settle(index)
89 }
90
91 pub fn tick(&mut self, now: Instant) -> Vec<(u64, RingOutcome)> {
92 let mut outcomes = Vec::new();
93 let ids: Vec<u64> = self.entries.iter().map(|entry| entry.ring.ring_id).collect();
94 for ring_id in ids {
95 if let Some(outcome) = self.signal(ring_id, RingSignal::Tick, now) {
96 outcomes.push((ring_id, outcome));
97 }
98 }
99 outcomes
100 }
101
102 fn settle(&mut self, index: usize) -> Option<RingOutcome> {
103 let entry = &self.entries[index];
104 if entry.state.is_ringing() {
105 return None;
106 }
107 let outcome = if entry.state.is_missed() {
108 RingOutcome::Missed(MissedCall {
109 caller_mri: entry.ring.caller.mri.clone(),
110 caller_name: entry.ring.caller.display_name.clone(),
111 thread_id: entry.ring.thread_id.clone(),
112 at: Utc::now(),
113 })
114 } else {
115 RingOutcome::Gone
116 };
117 self.entries.remove(index);
118 Some(outcome)
119 }
120 }
121
122 #[cfg(test)]
123 mod tests {
124 use std::time::Duration;
125
126 use calling::{Caller, EndKind};
127
128 use super::*;
129
130 fn ring(ring_id: u64, video: bool) -> IncomingRing {
131 IncomingRing {
132 ring_id,
133 caller: Caller {
134 mri: "8:orgid:caller".into(),
135 display_name: "Cara".into(),
136 },
137 thread_id: Some("19:a_b@unq.gbl.spaces".into()),
138 video,
139 is_group: false,
140 subject: None,
141 }
142 }
143
144 #[test]
145 fn a_ring_stays_until_it_is_settled() {
146 let start = Instant::now();
147 let mut rings = Rings::default();
148 rings.push(ring(1, false), false, start);
149 assert!(rings.is_ringing());
150 assert!(rings.tick(start + Duration::from_secs(5)).is_empty());
151 assert!(rings.get(1).is_some());
152 }
153
154 #[test]
155 fn thirty_seconds_without_an_answer_make_a_missed_call() {
156 let start = Instant::now();
157 let mut rings = Rings::default();
158 rings.push(ring(1, false), false, start);
159 let outcomes = rings.tick(start + Duration::from_secs(30));
160 assert_eq!(outcomes.len(), 1);
161 let (ring_id, RingOutcome::Missed(missed)) = &outcomes[0] else { panic!("not missed") };
162 assert_eq!(*ring_id, 1);
163 assert_eq!(missed.caller_name, "Cara");
164 assert_eq!(missed.thread_id.as_deref(), Some("19:a_b@unq.gbl.spaces"));
165 assert!(rings.is_empty() && !rings.is_ringing());
166 }
167
168 #[test]
169 fn the_caller_hanging_up_is_missed_but_answering_elsewhere_is_not() {
170 let start = Instant::now();
171 let mut rings = Rings::default();
172 rings.push(ring(1, false), false, start);
173 rings.push(ring(2, false), false, start);
174 let cancelled = rings.signal(1, RingSignal::Remote(EndKind::Cancelled), start);
175 assert!(matches!(cancelled, Some(RingOutcome::Missed(_))));
176 let elsewhere = rings.signal(2, RingSignal::Remote(EndKind::AnsweredElsewhere), start);
177 assert_eq!(elsewhere, Some(RingOutcome::Gone));
178 }
179
180 #[test]
181 fn accept_and_decline_leave_no_missed_call() {
182 let start = Instant::now();
183 let mut rings = Rings::default();
184 rings.push(ring(1, false), false, start);
185 rings.push(ring(2, false), false, start);
186 assert_eq!(rings.signal(1, RingSignal::Accept, start), Some(RingOutcome::Gone));
187 assert_eq!(rings.signal(2, RingSignal::Decline, start), Some(RingOutcome::Gone));
188 assert!(rings.is_empty());
189 assert_eq!(rings.signal(1, RingSignal::Accept, start), None);
190 }
191
192 #[test]
193 fn a_ring_id_rings_only_once() {
194 let start = Instant::now();
195 let mut rings = Rings::default();
196 rings.push(ring(1, false), false, start);
197 rings.push(ring(1, false), false, start);
198 assert_eq!(rings.ringing().count(), 1);
199 }
200
201 #[test]
202 fn video_calls_offer_accept_with_audio() {
203 let audio = RingEntry { ring: ring(1, false), state: RingState::start(Instant::now()), demo: false };
204 let video = RingEntry { ring: ring(2, true), ..audio.clone() };
205 assert_eq!(audio.subtitle(), "Incoming audio call");
206 assert_eq!(audio.accept_label(), "Accept");
207 assert_eq!(video.subtitle(), "Incoming call");
208 assert_eq!(video.accept_label(), "Accept with audio");
209 assert_eq!(audio.caller_user_id().as_deref(), Some("caller"));
210 }
211
212 #[test]
213 fn group_rings_say_so() {
214 let mut group = ring(3, false);
215 group.is_group = true;
216 let entry = RingEntry { ring: group, state: RingState::start(Instant::now()), demo: false };
217 assert_eq!(entry.subtitle(), "Incoming group audio call");
218 }
219 }
@@ -0,0 +1,219 @@
1use std::time::Instant;
2
3use calling::{IncomingRing, RingSignal, RingState};
4use chrono::{DateTime, Utc};
5
6const ORGID_PREFIX: &str = "8:orgid:";
7
8#[derive(Debug, Clone)]
9pub struct RingEntry {
10 pub ring: IncomingRing,
11 pub state: RingState,
12 pub demo: bool,
13}
14
15impl RingEntry {
16 pub fn caller_user_id(&self) -> Option<String> {
17 self.ring.caller.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned)
18 }
19
20 pub fn caller_name(&self) -> &str {
21 &self.ring.caller.display_name
22 }
23
24 pub fn subtitle(&self) -> &'static str {
25 match (self.ring.video, self.ring.is_group) {
26 (true, _) => "Incoming call",
27 (false, true) => "Incoming group audio call",
28 (false, false) => "Incoming audio call",
29 }
30 }
31
32 pub fn accept_label(&self) -> &'static str {
33 if self.ring.video { "Accept with audio" } else { "Accept" }
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct MissedCall {
39 pub caller_mri: String,
40 pub caller_name: String,
41 pub thread_id: Option<String>,
42 pub at: DateTime<Utc>,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum RingOutcome {
47 Missed(MissedCall),
48 Gone,
49}
50
51#[derive(Default)]
52pub struct Rings {
53 entries: Vec<RingEntry>,
54}
55
56impl Rings {
57 pub fn push(&mut self, ring: IncomingRing, demo: bool, now: Instant) {
58 if self.entries.iter().any(|entry| entry.ring.ring_id == ring.ring_id) {
59 return;
60 }
61 self.entries.push(RingEntry {
62 ring,
63 state: RingState::start(now),
64 demo,
65 });
66 }
67
68 pub fn get(&self, ring_id: u64) -> Option<&RingEntry> {
69 self.entries.iter().find(|entry| entry.ring.ring_id == ring_id)
70 }
71
72 pub fn ringing(&self) -> impl Iterator<Item = &RingEntry> {
73 self.entries.iter().filter(|entry| entry.state.is_ringing())
74 }
75
76 pub fn is_ringing(&self) -> bool {
77 self.ringing().next().is_some()
78 }
79
80 pub fn is_empty(&self) -> bool {
81 self.entries.is_empty()
82 }
83
84 pub fn signal(&mut self, ring_id: u64, signal: RingSignal, now: Instant) -> Option<RingOutcome> {
85 let index = self.entries.iter().position(|entry| entry.ring.ring_id == ring_id)?;
86 let next = self.entries[index].state.next(signal, now);
87 self.entries[index].state = next;
88 self.settle(index)
89 }
90
91 pub fn tick(&mut self, now: Instant) -> Vec<(u64, RingOutcome)> {
92 let mut outcomes = Vec::new();
93 let ids: Vec<u64> = self.entries.iter().map(|entry| entry.ring.ring_id).collect();
94 for ring_id in ids {
95 if let Some(outcome) = self.signal(ring_id, RingSignal::Tick, now) {
96 outcomes.push((ring_id, outcome));
97 }
98 }
99 outcomes
100 }
101
102 fn settle(&mut self, index: usize) -> Option<RingOutcome> {
103 let entry = &self.entries[index];
104 if entry.state.is_ringing() {
105 return None;
106 }
107 let outcome = if entry.state.is_missed() {
108 RingOutcome::Missed(MissedCall {
109 caller_mri: entry.ring.caller.mri.clone(),
110 caller_name: entry.ring.caller.display_name.clone(),
111 thread_id: entry.ring.thread_id.clone(),
112 at: Utc::now(),
113 })
114 } else {
115 RingOutcome::Gone
116 };
117 self.entries.remove(index);
118 Some(outcome)
119 }
120}
121
122#[cfg(test)]
123mod tests {
124 use std::time::Duration;
125
126 use calling::{Caller, EndKind};
127
128 use super::*;
129
130 fn ring(ring_id: u64, video: bool) -> IncomingRing {
131 IncomingRing {
132 ring_id,
133 caller: Caller {
134 mri: "8:orgid:caller".into(),
135 display_name: "Cara".into(),
136 },
137 thread_id: Some("19:a_b@unq.gbl.spaces".into()),
138 video,
139 is_group: false,
140 subject: None,
141 }
142 }
143
144 #[test]
145 fn a_ring_stays_until_it_is_settled() {
146 let start = Instant::now();
147 let mut rings = Rings::default();
148 rings.push(ring(1, false), false, start);
149 assert!(rings.is_ringing());
150 assert!(rings.tick(start + Duration::from_secs(5)).is_empty());
151 assert!(rings.get(1).is_some());
152 }
153
154 #[test]
155 fn thirty_seconds_without_an_answer_make_a_missed_call() {
156 let start = Instant::now();
157 let mut rings = Rings::default();
158 rings.push(ring(1, false), false, start);
159 let outcomes = rings.tick(start + Duration::from_secs(30));
160 assert_eq!(outcomes.len(), 1);
161 let (ring_id, RingOutcome::Missed(missed)) = &outcomes[0] else { panic!("not missed") };
162 assert_eq!(*ring_id, 1);
163 assert_eq!(missed.caller_name, "Cara");
164 assert_eq!(missed.thread_id.as_deref(), Some("19:a_b@unq.gbl.spaces"));
165 assert!(rings.is_empty() && !rings.is_ringing());
166 }
167
168 #[test]
169 fn the_caller_hanging_up_is_missed_but_answering_elsewhere_is_not() {
170 let start = Instant::now();
171 let mut rings = Rings::default();
172 rings.push(ring(1, false), false, start);
173 rings.push(ring(2, false), false, start);
174 let cancelled = rings.signal(1, RingSignal::Remote(EndKind::Cancelled), start);
175 assert!(matches!(cancelled, Some(RingOutcome::Missed(_))));
176 let elsewhere = rings.signal(2, RingSignal::Remote(EndKind::AnsweredElsewhere), start);
177 assert_eq!(elsewhere, Some(RingOutcome::Gone));
178 }
179
180 #[test]
181 fn accept_and_decline_leave_no_missed_call() {
182 let start = Instant::now();
183 let mut rings = Rings::default();
184 rings.push(ring(1, false), false, start);
185 rings.push(ring(2, false), false, start);
186 assert_eq!(rings.signal(1, RingSignal::Accept, start), Some(RingOutcome::Gone));
187 assert_eq!(rings.signal(2, RingSignal::Decline, start), Some(RingOutcome::Gone));
188 assert!(rings.is_empty());
189 assert_eq!(rings.signal(1, RingSignal::Accept, start), None);
190 }
191
192 #[test]
193 fn a_ring_id_rings_only_once() {
194 let start = Instant::now();
195 let mut rings = Rings::default();
196 rings.push(ring(1, false), false, start);
197 rings.push(ring(1, false), false, start);
198 assert_eq!(rings.ringing().count(), 1);
199 }
200
201 #[test]
202 fn video_calls_offer_accept_with_audio() {
203 let audio = RingEntry { ring: ring(1, false), state: RingState::start(Instant::now()), demo: false };
204 let video = RingEntry { ring: ring(2, true), ..audio.clone() };
205 assert_eq!(audio.subtitle(), "Incoming audio call");
206 assert_eq!(audio.accept_label(), "Accept");
207 assert_eq!(video.subtitle(), "Incoming call");
208 assert_eq!(video.accept_label(), "Accept with audio");
209 assert_eq!(audio.caller_user_id().as_deref(), Some("caller"));
210 }
211
212 #[test]
213 fn group_rings_say_so() {
214 let mut group = ring(3, false);
215 group.is_group = true;
216 let entry = RingEntry { ring: group, state: RingState::start(Instant::now()), demo: false };
217 assert_eq!(entry.subtitle(), "Incoming group audio call");
218 }
219}
crates/app/src/call/target.rs added +115 −0
@@ -0,0 +1,115 @@
1 use calling::meeting::LiveMeeting;
2 use store::ChatRecord;
3
4 use crate::data::{Person, is_one_on_one, others};
5
6 const ORGID_PREFIX: &str = "8:orgid:";
7 const GROUP_KIND: &str = "group";
8
9 pub struct CallPlan {
10 pub title: String,
11 pub callees: Vec<(String, String)>,
12 }
13
14 pub fn plan_for_chat(chat: &ChatRecord, me: Option<&Person>) -> Option<CallPlan> {
15 if !is_one_on_one(chat) && !chat.kind.eq_ignore_ascii_case(GROUP_KIND) {
16 return None;
17 }
18 let callees: Vec<(String, String)> = others(chat, me)
19 .into_iter()
20 .filter_map(|(user_id, name)| Some((format!("{ORGID_PREFIX}{}", user_id?), name)))
21 .collect();
22 let title = match callees.as_slice() {
23 [] => return None,
24 [(_, name)] if is_one_on_one(chat) => name.clone(),
25 _ => crate::app_state::chat_title(chat),
26 };
27 Some(CallPlan { title, callees })
28 }
29
30 pub fn is_organizer(meeting: &LiveMeeting, me: Option<&Person>) -> bool {
31 match (meeting.organizer_id.as_deref(), me) {
32 (Some(organizer), Some(me)) => organizer.eq_ignore_ascii_case(&me.user_id),
33 _ => false,
34 }
35 }
36
37 #[cfg(test)]
38 mod tests {
39 use store::MemberRecord;
40
41 use super::*;
42
43 fn chat(kind: &str, title: &str, members: &[(Option<&str>, &str)]) -> ChatRecord {
44 ChatRecord {
45 id: "19:chat".into(),
46 kind: kind.into(),
47 title: title.into(),
48 members: members
49 .iter()
50 .map(|(user_id, name)| MemberRecord {
51 user_id: user_id.map(str::to_owned),
52 display_name: (*name).to_owned(),
53 })
54 .collect(),
55 ..Default::default()
56 }
57 }
58
59 fn me() -> Person {
60 Person {
61 user_id: "me-id".into(),
62 display_name: "Me".into(),
63 }
64 }
65
66 #[test]
67 fn a_one_on_one_chat_calls_the_other_person_by_name() {
68 let chat = chat("oneOnOne", "", &[(Some("me-id"), "Me"), (Some("bea-id"), "Bea")]);
69 let plan = plan_for_chat(&chat, Some(&me())).unwrap();
70 assert_eq!(plan.title, "Bea");
71 assert_eq!(plan.callees, vec![("8:orgid:bea-id".to_owned(), "Bea".to_owned())]);
72 }
73
74 #[test]
75 fn a_group_chat_calls_everybody_else_under_the_chat_title() {
76 let chat = chat(
77 "group",
78 "Retro team",
79 &[(Some("me-id"), "Me"), (Some("bea-id"), "Bea"), (Some("cy-id"), "Cy")],
80 );
81 let plan = plan_for_chat(&chat, Some(&me())).unwrap();
82 assert_eq!(plan.title, "Retro team");
83 assert_eq!(plan.callees.len(), 2);
84 }
85
86 #[test]
87 fn meeting_chats_and_chats_without_callable_members_have_no_call_button() {
88 let meeting = chat("meeting", "Standup", &[(Some("bea-id"), "Bea")]);
89 assert!(plan_for_chat(&meeting, Some(&me())).is_none());
90 let alone = chat("oneOnOne", "Notes", &[(Some("me-id"), "Me")]);
91 assert!(plan_for_chat(&alone, Some(&me())).is_none());
92 let unknown_ids = chat("group", "Guests", &[(None, "Guest")]);
93 assert!(plan_for_chat(&unknown_ids, Some(&me())).is_none());
94 }
95
96 #[test]
97 fn the_organizer_may_end_the_meeting() {
98 let meeting = LiveMeeting {
99 thread_id: "t".into(),
100 conversation_url: None,
101 expiration: None,
102 organizer_id: Some("ME-ID".into()),
103 tenant_id: None,
104 meeting_code: None,
105 passcode: None,
106 };
107 assert!(is_organizer(&meeting, Some(&me())));
108 let other = LiveMeeting {
109 organizer_id: Some("someone".into()),
110 ..meeting.clone()
111 };
112 assert!(!is_organizer(&other, Some(&me())));
113 assert!(!is_organizer(&meeting, None));
114 }
115 }
@@ -0,0 +1,115 @@
1use calling::meeting::LiveMeeting;
2use store::ChatRecord;
3
4use crate::data::{Person, is_one_on_one, others};
5
6const ORGID_PREFIX: &str = "8:orgid:";
7const GROUP_KIND: &str = "group";
8
9pub struct CallPlan {
10 pub title: String,
11 pub callees: Vec<(String, String)>,
12}
13
14pub fn plan_for_chat(chat: &ChatRecord, me: Option<&Person>) -> Option<CallPlan> {
15 if !is_one_on_one(chat) && !chat.kind.eq_ignore_ascii_case(GROUP_KIND) {
16 return None;
17 }
18 let callees: Vec<(String, String)> = others(chat, me)
19 .into_iter()
20 .filter_map(|(user_id, name)| Some((format!("{ORGID_PREFIX}{}", user_id?), name)))
21 .collect();
22 let title = match callees.as_slice() {
23 [] => return None,
24 [(_, name)] if is_one_on_one(chat) => name.clone(),
25 _ => crate::app_state::chat_title(chat),
26 };
27 Some(CallPlan { title, callees })
28}
29
30pub fn is_organizer(meeting: &LiveMeeting, me: Option<&Person>) -> bool {
31 match (meeting.organizer_id.as_deref(), me) {
32 (Some(organizer), Some(me)) => organizer.eq_ignore_ascii_case(&me.user_id),
33 _ => false,
34 }
35}
36
37#[cfg(test)]
38mod tests {
39 use store::MemberRecord;
40
41 use super::*;
42
43 fn chat(kind: &str, title: &str, members: &[(Option<&str>, &str)]) -> ChatRecord {
44 ChatRecord {
45 id: "19:chat".into(),
46 kind: kind.into(),
47 title: title.into(),
48 members: members
49 .iter()
50 .map(|(user_id, name)| MemberRecord {
51 user_id: user_id.map(str::to_owned),
52 display_name: (*name).to_owned(),
53 })
54 .collect(),
55 ..Default::default()
56 }
57 }
58
59 fn me() -> Person {
60 Person {
61 user_id: "me-id".into(),
62 display_name: "Me".into(),
63 }
64 }
65
66 #[test]
67 fn a_one_on_one_chat_calls_the_other_person_by_name() {
68 let chat = chat("oneOnOne", "", &[(Some("me-id"), "Me"), (Some("bea-id"), "Bea")]);
69 let plan = plan_for_chat(&chat, Some(&me())).unwrap();
70 assert_eq!(plan.title, "Bea");
71 assert_eq!(plan.callees, vec![("8:orgid:bea-id".to_owned(), "Bea".to_owned())]);
72 }
73
74 #[test]
75 fn a_group_chat_calls_everybody_else_under_the_chat_title() {
76 let chat = chat(
77 "group",
78 "Retro team",
79 &[(Some("me-id"), "Me"), (Some("bea-id"), "Bea"), (Some("cy-id"), "Cy")],
80 );
81 let plan = plan_for_chat(&chat, Some(&me())).unwrap();
82 assert_eq!(plan.title, "Retro team");
83 assert_eq!(plan.callees.len(), 2);
84 }
85
86 #[test]
87 fn meeting_chats_and_chats_without_callable_members_have_no_call_button() {
88 let meeting = chat("meeting", "Standup", &[(Some("bea-id"), "Bea")]);
89 assert!(plan_for_chat(&meeting, Some(&me())).is_none());
90 let alone = chat("oneOnOne", "Notes", &[(Some("me-id"), "Me")]);
91 assert!(plan_for_chat(&alone, Some(&me())).is_none());
92 let unknown_ids = chat("group", "Guests", &[(None, "Guest")]);
93 assert!(plan_for_chat(&unknown_ids, Some(&me())).is_none());
94 }
95
96 #[test]
97 fn the_organizer_may_end_the_meeting() {
98 let meeting = LiveMeeting {
99 thread_id: "t".into(),
100 conversation_url: None,
101 expiration: None,
102 organizer_id: Some("ME-ID".into()),
103 tenant_id: None,
104 meeting_code: None,
105 passcode: None,
106 };
107 assert!(is_organizer(&meeting, Some(&me())));
108 let other = LiveMeeting {
109 organizer_id: Some("someone".into()),
110 ..meeting.clone()
111 };
112 assert!(!is_organizer(&other, Some(&me())));
113 assert!(!is_organizer(&meeting, None));
114 }
115}
crates/app/src/main.rs +5 −1
@@ -196,7 +196,10 @@ fn main() {
196 196 };
197 197 let store = Arc::new(store);
198 198 let receiver = (!arguments.demo)
199 .then(|| backend::start(store.clone(), transport(arguments.endpoint.as_deref(), arguments.database.as_deref())));
199 .then(|| {
200 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
201 backend::start(store.clone(), transport, !arguments.read_only)
202 });
200 203
201 204 let mut application = gpui_kit::application();
202 205 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
@@ -219,6 +222,7 @@ fn main() {
219 222 if arguments.demo {
220 223 state.update(cx, |state, cx| {
221 224 demo::seed_directory(state);
225 state.demo_live_meetings();
222 226 state.select(demo::first_selection(), cx);
223 227 });
224 228 }
@@ -196,7 +196,10 @@ fn main() {
196 };
196 };
197 let store = Arc::new(store);
197 let store = Arc::new(store);
198 let receiver = (!arguments.demo)
198 let receiver = (!arguments.demo)
199 .then(|| backend::start(store.clone(), transport(arguments.endpoint.as_deref(), arguments.database.as_deref())));
199 .then(|| {
200 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
201 backend::start(store.clone(), transport, !arguments.read_only)
202 });
200
203
201 let mut application = gpui_kit::application();
204 let mut application = gpui_kit::application();
202 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
205 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
@@ -219,6 +222,7 @@ fn main() {
219 if arguments.demo {
222 if arguments.demo {
220 state.update(cx, |state, cx| {
223 state.update(cx, |state, cx| {
221 demo::seed_directory(state);
224 demo::seed_directory(state);
225 state.demo_live_meetings();
222 state.select(demo::first_selection(), cx);
226 state.select(demo::first_selection(), cx);
223 });
227 });
224 }
228 }
crates/app/src/notify/center.rs +118 −3
@@ -7,7 +7,7 @@ use store::Sidebar;
7 7
8 8 use super::badge::{Badge, badge_for};
9 9 use super::incoming::IncomingTracker;
10 use super::layout::{self, Slot};
10 use super::layout::{self, Slot, ring_height};
11 11 use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
12 12 use super::rules::{
13 13 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,
@@ -19,6 +19,7 @@ use super::stack::{
19 19 FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
20 20 };
21 21 use super::text::describe;
22 use super::ring_view::RingView;
22 23 use super::toast::{PillView, ToastView};
23 24 use crate::app_state::{AppEvent, AppState, Selection};
24 25 use crate::data::{self, Directory, PresenceKind};
@@ -29,6 +30,7 @@ const TICK: Duration = Duration::from_millis(33);
29 30 const SLIDE_DURATION: Duration = Duration::from_millis(180);
30 31 const SLIDE_DISTANCE: f32 = 48.;
31 32 const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);
33 const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING";
32 34
33 35 struct OpenWindow {
34 36 handle: AnyWindowHandle,
@@ -56,6 +58,10 @@ pub struct NotificationCenter {
56 58 throttle: SoundThrottle,
57 59 windows: HashMap<u64, OpenWindow>,
58 60 opening: HashSet<u64>,
61 ring_windows: HashMap<u64, OpenWindow>,
62 ring_opening: HashSet<u64>,
63 ring_tone: Option<platform::RingTone>,
64 demo_mode: bool,
59 65 pill: Option<OpenWindow>,
60 66 pill_opening: bool,
61 67 hover_hold: bool,
@@ -88,6 +94,10 @@ impl NotificationCenter {
88 94 throttle: SoundThrottle::default(),
89 95 windows: HashMap::new(),
90 96 opening: HashSet::new(),
97 ring_windows: HashMap::new(),
98 ring_opening: HashSet::new(),
99 ring_tone: None,
100 demo_mode: app.read(cx).mode.demo,
91 101 pill: None,
92 102 pill_opening: false,
93 103 hover_hold: false,
@@ -116,10 +126,22 @@ impl NotificationCenter {
116 126 .ok();
117 127 })
118 128 .detach();
129 if let Some(delay) = demo_ring_delay() {
130 let app = center.app.clone();
131 cx.spawn(async move |_, cx| {
132 cx.background_executor().timer(delay).await;
133 app.update(cx, |state, cx| state.demo_incoming_ring(cx));
134 })
135 .detach();
136 }
119 137 }
120 138 center
121 139 }
122 140
141 pub fn app(&self) -> &Entity<AppState> {
142 &self.app
143 }
144
123 145 pub fn settings(&self) -> &Settings {
124 146 &self.settings
125 147 }
@@ -175,6 +197,7 @@ impl NotificationCenter {
175 197 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
176 198 AppEvent::Selection => self.on_selection(cx),
177 199 AppEvent::Sidebar => self.refresh_badge(cx),
200 AppEvent::Ring => self.on_rings_changed(cx),
178 201 _ => {}
179 202 }
180 203 }
@@ -294,6 +317,16 @@ impl NotificationCenter {
294 317 }
295 318 }
296 319
320 fn ringing_ids(&self, cx: &App) -> Vec<(u64, bool)> {
321 let state = self.app.read(cx);
322 let in_call = state.call.is_some();
323 state
324 .rings
325 .ringing()
326 .map(|entry| (entry.ring.ring_id, in_call))
327 .collect()
328 }
329
297 330 fn sync_windows(&mut self, cx: &mut Context<Self>) {
298 331 let visible = self.visible_ids();
299 332 let stale: Vec<u64> = self
@@ -305,8 +338,18 @@ impl NotificationCenter {
305 338 for id in stale {
306 339 self.close_window(id, cx);
307 340 }
341 let rings = self.ringing_ids(cx);
342 let stale_rings: Vec<u64> = self
343 .ring_windows
344 .keys()
345 .filter(|id| !rings.iter().any(|(ring_id, _)| ring_id == *id))
346 .copied()
347 .collect();
348 for id in stale_rings {
349 self.close_ring_window(id, cx);
350 }
308 351 let area = self.work_area(cx);
309 let heights: Vec<f32> = self
352 let mut heights: Vec<f32> = self
310 353 .stack
311 354 .visible()
312 355 .iter()
@@ -315,14 +358,77 @@ impl NotificationCenter {
315 358 layout::toast_height(toast, lines)
316 359 })
317 360 .collect();
361 heights.extend(rings.iter().map(|(_, in_call)| ring_height(*in_call)));
318 362 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
319 363 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
320 364 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
321 365 self.place_toast(*id, *slot, area, cx);
322 366 }
367 for ((ring_id, _), slot) in rings.iter().zip(slots.toasts.iter().skip(visible.len())) {
368 self.place_ring(*ring_id, *slot, area, cx);
369 }
323 370 self.sync_pill(slots.pill, area, cx);
324 371 }
325 372
373 fn place_ring(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
374 let Some(window) = self.ring_windows.get(&ring_id) else {
375 self.open_ring_window(ring_id, slot, area, cx);
376 return;
377 };
378 if let Some(native) = window.native {
379 let offset = self.slide_offset(window.opened, area);
380 window.place(native, slot, slot.x + offset, cx);
381 }
382 }
383
384 fn open_ring_window(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
385 if !self.ring_opening.insert(ring_id) {
386 return;
387 }
388 open_popup(
389 popup_options(slot, area),
390 cx,
391 move |center, _, cx| cx.new(|cx| RingView::new(center, ring_id, cx)),
392 move |this, window| {
393 this.ring_opening.remove(&ring_id);
394 if let Some(window) = window {
395 this.ring_windows.insert(ring_id, window);
396 }
397 },
398 );
399 }
400
401 fn close_ring_window(&mut self, ring_id: u64, cx: &mut Context<Self>) {
402 let closed = self.ring_windows.get(&ring_id).is_some_and(|window| {
403 window
404 .handle
405 .update(cx, |_, window, _| window.remove_window())
406 .is_ok()
407 });
408 if closed {
409 self.ring_windows.remove(&ring_id);
410 }
411 }
412
413 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
414 let ringing = self.app.read(cx).rings.is_ringing();
415 if ringing && !self.main_window_active(cx) && let Some(native) = self.main_native {
416 platform::flash(native);
417 }
418 self.sync_windows(cx);
419 self.sync_ring_tone(ringing);
420 cx.notify();
421 }
422
423 fn sync_ring_tone(&mut self, ringing: bool) {
424 let audible = ringing && self.settings.sound && !self.demo_mode;
425 match (audible, self.ring_tone.is_some()) {
426 (true, false) => self.ring_tone = platform::start_ring(),
427 (false, true) => self.ring_tone = None,
428 _ => {}
429 }
430 }
431
326 432 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
327 433 if !self.animations {
328 434 return 0;
@@ -466,7 +572,10 @@ impl NotificationCenter {
466 572 }
467 573 self.stack.promote(now, fade_in);
468 574 self.sync_hover_hold(now);
469 if !self.stack.is_empty() || !self.windows.is_empty() || self.pill.is_some() {
575 if !self.app.read(cx).rings.is_empty() {
576 self.app.update(cx, |state, cx| state.tick_rings(cx));
577 }
578 if !self.stack.is_empty() || !self.windows.is_empty() || self.pill.is_some() || !self.ring_windows.is_empty() {
470 579 self.sync_windows(cx);
471 580 cx.notify();
472 581 }
@@ -792,6 +901,12 @@ fn open_popup<V: Render>(
792 901 });
793 902 }
794 903
904 /// `TEAMS_DEMO_RING=<seconds>` rings a fake incoming call that long after the demo starts.
905 fn demo_ring_delay() -> Option<Duration> {
906 let seconds: f32 = std::env::var(DEMO_RING_ENV).ok()?.trim().parse().ok()?;
907 (seconds >= 0.).then(|| Duration::from_secs_f32(seconds))
908 }
909
795 910 fn preview_lines(text: &str, cx: &App) -> usize {
796 911 let mut wrapper = cx
797 912 .text_system()
@@ -7,7 +7,7 @@ use store::Sidebar;
7
7
8use super::badge::{Badge, badge_for};
8use super::badge::{Badge, badge_for};
9use super::incoming::IncomingTracker;
9use super::incoming::IncomingTracker;
10use super::layout::{self, Slot};
10use super::layout::{self, Slot, ring_height};
11use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
11use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
12use super::rules::{
12use super::rules::{
13 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,
13 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,
@@ -19,6 +19,7 @@ use super::stack::{
19 FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
19 FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
20};
20};
21use super::text::describe;
21use super::text::describe;
22use super::ring_view::RingView;
22use super::toast::{PillView, ToastView};
23use super::toast::{PillView, ToastView};
23use crate::app_state::{AppEvent, AppState, Selection};
24use crate::app_state::{AppEvent, AppState, Selection};
24use crate::data::{self, Directory, PresenceKind};
25use crate::data::{self, Directory, PresenceKind};
@@ -29,6 +30,7 @@ const TICK: Duration = Duration::from_millis(33);
29const SLIDE_DURATION: Duration = Duration::from_millis(180);
30const SLIDE_DURATION: Duration = Duration::from_millis(180);
30const SLIDE_DISTANCE: f32 = 48.;
31const SLIDE_DISTANCE: f32 = 48.;
31const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);
32const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);
33const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING";
32
34
33struct OpenWindow {
35struct OpenWindow {
34 handle: AnyWindowHandle,
36 handle: AnyWindowHandle,
@@ -56,6 +58,10 @@ pub struct NotificationCenter {
56 throttle: SoundThrottle,
58 throttle: SoundThrottle,
57 windows: HashMap<u64, OpenWindow>,
59 windows: HashMap<u64, OpenWindow>,
58 opening: HashSet<u64>,
60 opening: HashSet<u64>,
61 ring_windows: HashMap<u64, OpenWindow>,
62 ring_opening: HashSet<u64>,
63 ring_tone: Option<platform::RingTone>,
64 demo_mode: bool,
59 pill: Option<OpenWindow>,
65 pill: Option<OpenWindow>,
60 pill_opening: bool,
66 pill_opening: bool,
61 hover_hold: bool,
67 hover_hold: bool,
@@ -88,6 +94,10 @@ impl NotificationCenter {
88 throttle: SoundThrottle::default(),
94 throttle: SoundThrottle::default(),
89 windows: HashMap::new(),
95 windows: HashMap::new(),
90 opening: HashSet::new(),
96 opening: HashSet::new(),
97 ring_windows: HashMap::new(),
98 ring_opening: HashSet::new(),
99 ring_tone: None,
100 demo_mode: app.read(cx).mode.demo,
91 pill: None,
101 pill: None,
92 pill_opening: false,
102 pill_opening: false,
93 hover_hold: false,
103 hover_hold: false,
@@ -116,10 +126,22 @@ impl NotificationCenter {
116 .ok();
126 .ok();
117 })
127 })
118 .detach();
128 .detach();
129 if let Some(delay) = demo_ring_delay() {
130 let app = center.app.clone();
131 cx.spawn(async move |_, cx| {
132 cx.background_executor().timer(delay).await;
133 app.update(cx, |state, cx| state.demo_incoming_ring(cx));
134 })
135 .detach();
136 }
119 }
137 }
120 center
138 center
121 }
139 }
122
140
141 pub fn app(&self) -> &Entity<AppState> {
142 &self.app
143 }
144
123 pub fn settings(&self) -> &Settings {
145 pub fn settings(&self) -> &Settings {
124 &self.settings
146 &self.settings
125 }
147 }
@@ -175,6 +197,7 @@ impl NotificationCenter {
175 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
197 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
176 AppEvent::Selection => self.on_selection(cx),
198 AppEvent::Selection => self.on_selection(cx),
177 AppEvent::Sidebar => self.refresh_badge(cx),
199 AppEvent::Sidebar => self.refresh_badge(cx),
200 AppEvent::Ring => self.on_rings_changed(cx),
178 _ => {}
201 _ => {}
179 }
202 }
180 }
203 }
@@ -294,6 +317,16 @@ impl NotificationCenter {
294 }
317 }
295 }
318 }
296
319
320 fn ringing_ids(&self, cx: &App) -> Vec<(u64, bool)> {
321 let state = self.app.read(cx);
322 let in_call = state.call.is_some();
323 state
324 .rings
325 .ringing()
326 .map(|entry| (entry.ring.ring_id, in_call))
327 .collect()
328 }
329
297 fn sync_windows(&mut self, cx: &mut Context<Self>) {
330 fn sync_windows(&mut self, cx: &mut Context<Self>) {
298 let visible = self.visible_ids();
331 let visible = self.visible_ids();
299 let stale: Vec<u64> = self
332 let stale: Vec<u64> = self
@@ -305,8 +338,18 @@ impl NotificationCenter {
305 for id in stale {
338 for id in stale {
306 self.close_window(id, cx);
339 self.close_window(id, cx);
307 }
340 }
341 let rings = self.ringing_ids(cx);
342 let stale_rings: Vec<u64> = self
343 .ring_windows
344 .keys()
345 .filter(|id| !rings.iter().any(|(ring_id, _)| ring_id == *id))
346 .copied()
347 .collect();
348 for id in stale_rings {
349 self.close_ring_window(id, cx);
350 }
308 let area = self.work_area(cx);
351 let area = self.work_area(cx);
309 let heights: Vec<f32> = self
352 let mut heights: Vec<f32> = self
310 .stack
353 .stack
311 .visible()
354 .visible()
312 .iter()
355 .iter()
@@ -315,14 +358,77 @@ impl NotificationCenter {
315 layout::toast_height(toast, lines)
358 layout::toast_height(toast, lines)
316 })
359 })
317 .collect();
360 .collect();
361 heights.extend(rings.iter().map(|(_, in_call)| ring_height(*in_call)));
318 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
362 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
319 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
363 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
320 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
364 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
321 self.place_toast(*id, *slot, area, cx);
365 self.place_toast(*id, *slot, area, cx);
322 }
366 }
367 for ((ring_id, _), slot) in rings.iter().zip(slots.toasts.iter().skip(visible.len())) {
368 self.place_ring(*ring_id, *slot, area, cx);
369 }
323 self.sync_pill(slots.pill, area, cx);
370 self.sync_pill(slots.pill, area, cx);
324 }
371 }
325
372
373 fn place_ring(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
374 let Some(window) = self.ring_windows.get(&ring_id) else {
375 self.open_ring_window(ring_id, slot, area, cx);
376 return;
377 };
378 if let Some(native) = window.native {
379 let offset = self.slide_offset(window.opened, area);
380 window.place(native, slot, slot.x + offset, cx);
381 }
382 }
383
384 fn open_ring_window(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
385 if !self.ring_opening.insert(ring_id) {
386 return;
387 }
388 open_popup(
389 popup_options(slot, area),
390 cx,
391 move |center, _, cx| cx.new(|cx| RingView::new(center, ring_id, cx)),
392 move |this, window| {
393 this.ring_opening.remove(&ring_id);
394 if let Some(window) = window {
395 this.ring_windows.insert(ring_id, window);
396 }
397 },
398 );
399 }
400
401 fn close_ring_window(&mut self, ring_id: u64, cx: &mut Context<Self>) {
402 let closed = self.ring_windows.get(&ring_id).is_some_and(|window| {
403 window
404 .handle
405 .update(cx, |_, window, _| window.remove_window())
406 .is_ok()
407 });
408 if closed {
409 self.ring_windows.remove(&ring_id);
410 }
411 }
412
413 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
414 let ringing = self.app.read(cx).rings.is_ringing();
415 if ringing && !self.main_window_active(cx) && let Some(native) = self.main_native {
416 platform::flash(native);
417 }
418 self.sync_windows(cx);
419 self.sync_ring_tone(ringing);
420 cx.notify();
421 }
422
423 fn sync_ring_tone(&mut self, ringing: bool) {
424 let audible = ringing && self.settings.sound && !self.demo_mode;
425 match (audible, self.ring_tone.is_some()) {
426 (true, false) => self.ring_tone = platform::start_ring(),
427 (false, true) => self.ring_tone = None,
428 _ => {}
429 }
430 }
431
326 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
432 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
327 if !self.animations {
433 if !self.animations {
328 return 0;
434 return 0;
@@ -466,7 +572,10 @@ impl NotificationCenter {
466 }
572 }
467 self.stack.promote(now, fade_in);
573 self.stack.promote(now, fade_in);
468 self.sync_hover_hold(now);
574 self.sync_hover_hold(now);
469 if !self.stack.is_empty() || !self.windows.is_empty() || self.pill.is_some() {
575 if !self.app.read(cx).rings.is_empty() {
576 self.app.update(cx, |state, cx| state.tick_rings(cx));
577 }
578 if !self.stack.is_empty() || !self.windows.is_empty() || self.pill.is_some() || !self.ring_windows.is_empty() {
470 self.sync_windows(cx);
579 self.sync_windows(cx);
471 cx.notify();
580 cx.notify();
472 }
581 }
@@ -792,6 +901,12 @@ fn open_popup<V: Render>(
792 });
901 });
793}
902}
794
903
904/// `TEAMS_DEMO_RING=<seconds>` rings a fake incoming call that long after the demo starts.
905fn demo_ring_delay() -> Option<Duration> {
906 let seconds: f32 = std::env::var(DEMO_RING_ENV).ok()?.trim().parse().ok()?;
907 (seconds >= 0.).then(|| Duration::from_secs_f32(seconds))
908}
909
795fn preview_lines(text: &str, cx: &App) -> usize {
910fn preview_lines(text: &str, cx: &App) -> usize {
796 let mut wrapper = cx
911 let mut wrapper = cx
797 .text_system()
912 .text_system()
crates/app/src/notify/layout.rs +20 −0
@@ -24,6 +24,8 @@ const REPLY_FIELD_FRAME: f32 = 14.;
24 24 const REPLY_HINT_ROW: f32 = 20.;
25 25 const REPLY_SPACING: f32 = 8.;
26 26 const CONFIRM_HEIGHT: f32 = 56.;
27 const RING_BASE_HEIGHT: f32 = 120.;
28 const RING_NOTE_HEIGHT: f32 = 18.;
27 29
28 30 #[derive(Debug, Clone, Copy, PartialEq)]
29 31 pub struct Slot {
@@ -44,6 +46,10 @@ pub fn toast_height(model: &ToastModel, preview_lines: usize) -> f32 {
44 46 }
45 47 }
46 48
49 pub fn ring_height(ends_current_call: bool) -> f32 {
50 if ends_current_call { RING_BASE_HEIGHT + RING_NOTE_HEIGHT } else { RING_BASE_HEIGHT }
51 }
52
47 53 pub struct StackSlots {
48 54 pub toasts: Vec<Slot>,
49 55 pub pill: Option<Slot>,
@@ -151,6 +157,20 @@ mod tests {
151 157 assert_eq!(toast.y + toast.height, 1032 - 18);
152 158 }
153 159
160 #[test]
161 fn ring_toasts_sit_below_the_message_toasts_next_to_the_corner() {
162 let heights = [80., ring_height(false)];
163 let slots = stack_slots(area(1.), Corner::BottomRight, &heights, false);
164 assert_eq!(slots.toasts[1].y + slots.toasts[1].height, 1032 - 12);
165 assert_eq!(slots.toasts[1].height, 120);
166 assert!(slots.toasts[0].y + slots.toasts[0].height < slots.toasts[1].y);
167 }
168
169 #[test]
170 fn the_second_call_note_makes_the_ring_toast_taller() {
171 assert!(ring_height(true) > ring_height(false));
172 }
173
154 174 #[test]
155 175 fn heights_stay_in_board_range() {
156 176 use super::super::rules::{ChatKind, Preview};
@@ -24,6 +24,8 @@ const REPLY_FIELD_FRAME: f32 = 14.;
24const REPLY_HINT_ROW: f32 = 20.;
24const REPLY_HINT_ROW: f32 = 20.;
25const REPLY_SPACING: f32 = 8.;
25const REPLY_SPACING: f32 = 8.;
26const CONFIRM_HEIGHT: f32 = 56.;
26const CONFIRM_HEIGHT: f32 = 56.;
27const RING_BASE_HEIGHT: f32 = 120.;
28const RING_NOTE_HEIGHT: f32 = 18.;
27
29
28#[derive(Debug, Clone, Copy, PartialEq)]
30#[derive(Debug, Clone, Copy, PartialEq)]
29pub struct Slot {
31pub struct Slot {
@@ -44,6 +46,10 @@ pub fn toast_height(model: &ToastModel, preview_lines: usize) -> f32 {
44 }
46 }
45}
47}
46
48
49pub fn ring_height(ends_current_call: bool) -> f32 {
50 if ends_current_call { RING_BASE_HEIGHT + RING_NOTE_HEIGHT } else { RING_BASE_HEIGHT }
51}
52
47pub struct StackSlots {
53pub struct StackSlots {
48 pub toasts: Vec<Slot>,
54 pub toasts: Vec<Slot>,
49 pub pill: Option<Slot>,
55 pub pill: Option<Slot>,
@@ -151,6 +157,20 @@ mod tests {
151 assert_eq!(toast.y + toast.height, 1032 - 18);
157 assert_eq!(toast.y + toast.height, 1032 - 18);
152 }
158 }
153
159
160 #[test]
161 fn ring_toasts_sit_below_the_message_toasts_next_to_the_corner() {
162 let heights = [80., ring_height(false)];
163 let slots = stack_slots(area(1.), Corner::BottomRight, &heights, false);
164 assert_eq!(slots.toasts[1].y + slots.toasts[1].height, 1032 - 12);
165 assert_eq!(slots.toasts[1].height, 120);
166 assert!(slots.toasts[0].y + slots.toasts[0].height < slots.toasts[1].y);
167 }
168
169 #[test]
170 fn the_second_call_note_makes_the_ring_toast_taller() {
171 assert!(ring_height(true) > ring_height(false));
172 }
173
154 #[test]
174 #[test]
155 fn heights_stay_in_board_range() {
175 fn heights_stay_in_board_range() {
156 use super::super::rules::{ChatKind, Preview};
176 use super::super::rules::{ChatKind, Preview};
crates/app/src/notify/mod.rs +3 −0
@@ -5,6 +5,9 @@ mod incoming;
5 5 mod layout;
6 6 #[cfg_attr(not(windows), allow(dead_code))]
7 7 mod platform;
8 #[cfg_attr(not(windows), allow(dead_code))]
9 mod ring_tone;
10 mod ring_view;
8 11 mod rules;
9 12 mod settings;
10 13 mod settings_view;
@@ -5,6 +5,9 @@ mod incoming;
5mod layout;
5mod layout;
6#[cfg_attr(not(windows), allow(dead_code))]
6#[cfg_attr(not(windows), allow(dead_code))]
7mod platform;
7mod platform;
8#[cfg_attr(not(windows), allow(dead_code))]
9mod ring_tone;
10mod ring_view;
8mod rules;
11mod rules;
9mod settings;
12mod settings;
10mod settings_view;
13mod settings_view;
crates/app/src/notify/platform/stub.rs +6 −0
@@ -33,6 +33,12 @@ pub fn set_badge(_handle: NativeHandle, _badge: Option<&Badge>) {}
33 33
34 34 pub fn play_sound() {}
35 35
36 pub struct RingTone;
37
38 pub fn start_ring() -> Option<RingTone> {
39 None
40 }
41
36 42 pub struct Tray;
37 43
38 44 impl Tray {
@@ -33,6 +33,12 @@ pub fn set_badge(_handle: NativeHandle, _badge: Option<&Badge>) {}
33
33
34pub fn play_sound() {}
34pub fn play_sound() {}
35
35
36pub struct RingTone;
37
38pub fn start_ring() -> Option<RingTone> {
39 None
40}
41
36pub struct Tray;
42pub struct Tray;
37
43
38impl Tray {
44impl Tray {
crates/app/src/notify/platform/windows_impl.rs +43 −0
@@ -1,5 +1,9 @@
1 1 use std::ffi::c_void;
2 2 use std::io::Cursor;
3 use std::num::NonZero;
4 use std::sync::Arc;
5 use std::sync::atomic::{AtomicBool, Ordering};
6 use std::time::Duration;
3 7
4 8 use gpui_kit::Window;
5 9 use raw_window_handle::{HasWindowHandle, RawWindowHandle};
@@ -32,12 +36,14 @@ use windows::core::{BOOL, w};
32 36
33 37 use super::{NativeHandle, TrayCommand, WorkArea};
34 38 use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};
39 use crate::notify::ring_tone::{SAMPLE_RATE, ring_cycle};
35 40
36 41 const SOUND_BYTES: &[u8] = include_bytes!("../../../assets/sounds/notification.mp3");
37 42 const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../assets/icon/teams-fast-256.png");
38 43 const TRAY_ICON_SIZE: u32 = 32;
39 44 const TRAY_DOT_RADIUS: f32 = 6.;
40 45 const BASE_DPI: f32 = 96.;
46 const RING_POLL: Duration = Duration::from_millis(20);
41 47
42 48 fn hwnd(handle: NativeHandle) -> HWND {
43 49 HWND(handle as *mut c_void)
@@ -246,6 +252,43 @@ unsafe fn icon_from_badge(badge: &Badge) -> Option<HICON> {
246 252 }
247 253 }
248 254
255 pub struct RingTone {
256 stop: Arc<AtomicBool>,
257 }
258
259 impl Drop for RingTone {
260 fn drop(&mut self) {
261 self.stop.store(true, Ordering::SeqCst);
262 }
263 }
264
265 pub fn start_ring() -> Option<RingTone> {
266 let stop = Arc::new(AtomicBool::new(false));
267 let flag = stop.clone();
268 std::thread::spawn(move || {
269 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
270 return;
271 };
272 sink.log_on_drop(false);
273 let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
274 return;
275 };
276 let cycle = ring_cycle(SAMPLE_RATE);
277 while !flag.load(Ordering::SeqCst) {
278 let player = rodio::Player::connect_new(sink.mixer());
279 player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle.clone()));
280 while !player.empty() {
281 if flag.load(Ordering::SeqCst) {
282 player.stop();
283 return;
284 }
285 std::thread::sleep(RING_POLL);
286 }
287 }
288 });
289 Some(RingTone { stop })
290 }
291
249 292 pub fn play_sound() {
250 293 std::thread::spawn(|| {
251 294 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
@@ -1,5 +1,9 @@
1use std::ffi::c_void;
1use std::ffi::c_void;
2use std::io::Cursor;
2use std::io::Cursor;
3use std::num::NonZero;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::time::Duration;
3
7
4use gpui_kit::Window;
8use gpui_kit::Window;
5use raw_window_handle::{HasWindowHandle, RawWindowHandle};
9use raw_window_handle::{HasWindowHandle, RawWindowHandle};
@@ -32,12 +36,14 @@ use windows::core::{BOOL, w};
32
36
33use super::{NativeHandle, TrayCommand, WorkArea};
37use super::{NativeHandle, TrayCommand, WorkArea};
34use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};
38use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};
39use crate::notify::ring_tone::{SAMPLE_RATE, ring_cycle};
35
40
36const SOUND_BYTES: &[u8] = include_bytes!("../../../assets/sounds/notification.mp3");
41const SOUND_BYTES: &[u8] = include_bytes!("../../../assets/sounds/notification.mp3");
37const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../assets/icon/teams-fast-256.png");
42const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../assets/icon/teams-fast-256.png");
38const TRAY_ICON_SIZE: u32 = 32;
43const TRAY_ICON_SIZE: u32 = 32;
39const TRAY_DOT_RADIUS: f32 = 6.;
44const TRAY_DOT_RADIUS: f32 = 6.;
40const BASE_DPI: f32 = 96.;
45const BASE_DPI: f32 = 96.;
46const RING_POLL: Duration = Duration::from_millis(20);
41
47
42fn hwnd(handle: NativeHandle) -> HWND {
48fn hwnd(handle: NativeHandle) -> HWND {
43 HWND(handle as *mut c_void)
49 HWND(handle as *mut c_void)
@@ -246,6 +252,43 @@ unsafe fn icon_from_badge(badge: &Badge) -> Option<HICON> {
246 }
252 }
247}
253}
248
254
255pub struct RingTone {
256 stop: Arc<AtomicBool>,
257}
258
259impl Drop for RingTone {
260 fn drop(&mut self) {
261 self.stop.store(true, Ordering::SeqCst);
262 }
263}
264
265pub fn start_ring() -> Option<RingTone> {
266 let stop = Arc::new(AtomicBool::new(false));
267 let flag = stop.clone();
268 std::thread::spawn(move || {
269 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
270 return;
271 };
272 sink.log_on_drop(false);
273 let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
274 return;
275 };
276 let cycle = ring_cycle(SAMPLE_RATE);
277 while !flag.load(Ordering::SeqCst) {
278 let player = rodio::Player::connect_new(sink.mixer());
279 player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle.clone()));
280 while !player.empty() {
281 if flag.load(Ordering::SeqCst) {
282 player.stop();
283 return;
284 }
285 std::thread::sleep(RING_POLL);
286 }
287 }
288 });
289 Some(RingTone { stop })
290}
291
249pub fn play_sound() {
292pub fn play_sound() {
250 std::thread::spawn(|| {
293 std::thread::spawn(|| {
251 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
294 let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
crates/app/src/notify/ring_tone.rs added +61 −0
@@ -0,0 +1,61 @@
1 use std::f32::consts::PI;
2
3 pub const SAMPLE_RATE: u32 = 44_100;
4 const LOW_HZ: f32 = 784.;
5 const HIGH_HZ: f32 = 988.;
6 const BEEP_SECONDS: f32 = 0.18;
7 const FADE_SECONDS: f32 = 0.015;
8 const AMPLITUDE: f32 = 0.3;
9 const BEEPS: [f32; 4] = [LOW_HZ, HIGH_HZ, LOW_HZ, HIGH_HZ];
10 const CYCLE_SECONDS: f32 = 2.4;
11
12 pub fn ring_cycle(sample_rate: u32) -> Vec<f32> {
13 let total = (CYCLE_SECONDS * sample_rate as f32) as usize;
14 let beep = (BEEP_SECONDS * sample_rate as f32) as usize;
15 let fade = (FADE_SECONDS * sample_rate as f32) as usize;
16 let mut samples = vec![0.; total];
17 for (index, frequency) in BEEPS.iter().enumerate() {
18 let start = index * beep;
19 for position in 0..beep {
20 let envelope = (position.min(beep - 1 - position) as f32 / fade as f32).min(1.);
21 let phase = 2. * PI * frequency * position as f32 / sample_rate as f32;
22 samples[start + position] = AMPLITUDE * envelope * phase.sin();
23 }
24 }
25 samples
26 }
27
28 #[cfg(test)]
29 mod tests {
30 use super::*;
31
32 #[test]
33 fn a_cycle_lasts_two_and_a_half_seconds_at_most_and_stays_quiet() {
34 let samples = ring_cycle(SAMPLE_RATE);
35 assert_eq!(samples.len(), (CYCLE_SECONDS * SAMPLE_RATE as f32) as usize);
36 assert!(samples.iter().all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON));
37 assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));
38 }
39
40 #[test]
41 fn beeps_fade_in_and_out_without_clicks() {
42 let samples = ring_cycle(SAMPLE_RATE);
43 assert_eq!(samples[0], 0.);
44 let beep = (BEEP_SECONDS * SAMPLE_RATE as f32) as usize;
45 assert!(samples[1].abs() < 0.05);
46 assert!(samples[beep - 1].abs() < 0.05);
47 }
48
49 #[test]
50 fn the_cycle_ends_in_silence_so_it_can_repeat() {
51 let samples = ring_cycle(SAMPLE_RATE);
52 let beeps_end = (BEEP_SECONDS * BEEPS.len() as f32 * SAMPLE_RATE as f32) as usize;
53 assert!(samples[beeps_end..].iter().all(|sample| *sample == 0.));
54 assert!(beeps_end < samples.len());
55 }
56
57 #[test]
58 fn the_cycle_is_the_same_every_time() {
59 assert_eq!(ring_cycle(SAMPLE_RATE), ring_cycle(SAMPLE_RATE));
60 }
61 }
@@ -0,0 +1,61 @@
1use std::f32::consts::PI;
2
3pub const SAMPLE_RATE: u32 = 44_100;
4const LOW_HZ: f32 = 784.;
5const HIGH_HZ: f32 = 988.;
6const BEEP_SECONDS: f32 = 0.18;
7const FADE_SECONDS: f32 = 0.015;
8const AMPLITUDE: f32 = 0.3;
9const BEEPS: [f32; 4] = [LOW_HZ, HIGH_HZ, LOW_HZ, HIGH_HZ];
10const CYCLE_SECONDS: f32 = 2.4;
11
12pub fn ring_cycle(sample_rate: u32) -> Vec<f32> {
13 let total = (CYCLE_SECONDS * sample_rate as f32) as usize;
14 let beep = (BEEP_SECONDS * sample_rate as f32) as usize;
15 let fade = (FADE_SECONDS * sample_rate as f32) as usize;
16 let mut samples = vec![0.; total];
17 for (index, frequency) in BEEPS.iter().enumerate() {
18 let start = index * beep;
19 for position in 0..beep {
20 let envelope = (position.min(beep - 1 - position) as f32 / fade as f32).min(1.);
21 let phase = 2. * PI * frequency * position as f32 / sample_rate as f32;
22 samples[start + position] = AMPLITUDE * envelope * phase.sin();
23 }
24 }
25 samples
26}
27
28#[cfg(test)]
29mod tests {
30 use super::*;
31
32 #[test]
33 fn a_cycle_lasts_two_and_a_half_seconds_at_most_and_stays_quiet() {
34 let samples = ring_cycle(SAMPLE_RATE);
35 assert_eq!(samples.len(), (CYCLE_SECONDS * SAMPLE_RATE as f32) as usize);
36 assert!(samples.iter().all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON));
37 assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));
38 }
39
40 #[test]
41 fn beeps_fade_in_and_out_without_clicks() {
42 let samples = ring_cycle(SAMPLE_RATE);
43 assert_eq!(samples[0], 0.);
44 let beep = (BEEP_SECONDS * SAMPLE_RATE as f32) as usize;
45 assert!(samples[1].abs() < 0.05);
46 assert!(samples[beep - 1].abs() < 0.05);
47 }
48
49 #[test]
50 fn the_cycle_ends_in_silence_so_it_can_repeat() {
51 let samples = ring_cycle(SAMPLE_RATE);
52 let beeps_end = (BEEP_SECONDS * BEEPS.len() as f32 * SAMPLE_RATE as f32) as usize;
53 assert!(samples[beeps_end..].iter().all(|sample| *sample == 0.));
54 assert!(beeps_end < samples.len());
55 }
56
57 #[test]
58 fn the_cycle_is_the_same_every_time() {
59 assert_eq!(ring_cycle(SAMPLE_RATE), ring_cycle(SAMPLE_RATE));
60 }
61}
crates/app/src/notify/ring_view.rs added +149 −0
@@ -0,0 +1,149 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::{h_flex, v_flex};
3 use gpui_kit::prelude::FluentBuilder as _;
4 use gpui_kit::*;
5
6 use super::center::NotificationCenter;
7 use super::layout::{AVATAR_GAP, TOAST_PADDING};
8 use crate::app_state::AppState;
9 use crate::call::RingEntry;
10 use crate::theme;
11 use crate::views::avatar::person_avatar;
12 use crate::views::call_view::pulsing;
13 use crate::views::widgets::icon;
14
15 pub const RING_AVATAR: f32 = 56.;
16 const RING_BORDER: f32 = 2.;
17 const RING_WIDTH: f32 = 3.;
18 const RING_GAP: f32 = 3.;
19 const TOAST_RADIUS: f32 = 12.;
20 const BUTTON_HEIGHT: f32 = 32.;
21 pub const ENDS_CURRENT_CALL: &str = "Accept ends current call";
22
23 pub struct RingView {
24 app: Entity<AppState>,
25 ring_id: u64,
26 _subscription: Subscription,
27 }
28
29 impl RingView {
30 pub fn new(center: Entity<NotificationCenter>, ring_id: u64, cx: &mut Context<Self>) -> Self {
31 let app = center.read(cx).app().clone();
32 let subscription = cx.observe(&app, |_, _, cx| cx.notify());
33 RingView {
34 app,
35 ring_id,
36 _subscription: subscription,
37 }
38 }
39 }
40
41 fn answer_button(id: &'static str, label: &str, glyph: IconName, fill: Hsla) -> Stateful<gpui_kit::Div> {
42 h_flex()
43 .id(id)
44 .h(px(BUTTON_HEIGHT))
45 .px(px(14.))
46 .gap(px(6.))
47 .flex_none()
48 .items_center()
49 .justify_center()
50 .rounded_full()
51 .bg(fill)
52 .text_color(theme::white())
53 .text_size(px(13.))
54 .font_weight(FontWeight::SEMIBOLD)
55 .cursor_pointer()
56 .hover(|button| button.opacity(0.85))
57 .child(icon(glyph, 16., theme::white()))
58 .child(label.to_owned())
59 }
60
61 fn caller_avatar(state: &AppState, entry: &RingEntry) -> AnyElement {
62 let avatar = person_avatar(
63 &state.directory,
64 entry.caller_user_id().as_deref(),
65 entry.caller_name(),
66 RING_AVATAR,
67 );
68 let ringed = div()
69 .p(px(RING_GAP))
70 .rounded_full()
71 .border(px(RING_WIDTH))
72 .border_color(theme::green())
73 .child(avatar);
74 pulsing(ringed, "ring-avatar-pulse")
75 }
76
77 impl Render for RingView {
78 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
79 let state = self.app.read(cx);
80 let Some(entry) = state.rings.get(self.ring_id).cloned() else {
81 return div().size_full().bg(theme::surface_raised()).into_any_element();
82 };
83 window.set_window_title(&format!("{}: {}", entry.caller_name(), entry.subtitle()));
84 let ends_current = state.call.is_some();
85 let avatar = caller_avatar(state, &entry);
86 let ring_id = self.ring_id;
87 let decline_app = self.app.clone();
88 let accept_app = self.app.clone();
89 let decline = answer_button("ring-decline", "Decline", IconName::PhoneOff, theme::red()).on_click(
90 move |_, _, cx| {
91 cx.stop_propagation();
92 decline_app.update(cx, |state, cx| state.decline_ring(ring_id, cx));
93 },
94 );
95 let accept = answer_button("ring-accept", entry.accept_label(), IconName::Phone, theme::green()).on_click(
96 move |_, _, cx| {
97 cx.stop_propagation();
98 accept_app.update(cx, |state, cx| state.accept_ring(ring_id, cx));
99 },
100 );
101 div()
102 .id(("ring", ring_id))
103 .size_full()
104 .rounded(px(TOAST_RADIUS))
105 .bg(theme::surface_raised())
106 .border(px(RING_BORDER))
107 .border_color(theme::green())
108 .overflow_hidden()
109 .child(
110 div().size_full().p(px(TOAST_PADDING)).child(
111 h_flex()
112 .size_full()
113 .gap(px(AVATAR_GAP))
114 .items_start()
115 .child(avatar)
116 .child(
117 v_flex()
118 .flex_1()
119 .min_w_0()
120 .gap(px(2.))
121 .child(
122 div()
123 .truncate()
124 .text_size(px(15.))
125 .font_weight(FontWeight::SEMIBOLD)
126 .text_color(theme::text())
127 .child(entry.caller_name().to_owned()),
128 )
129 .child(
130 div()
131 .text_size(px(12.5))
132 .text_color(theme::text_muted())
133 .child(entry.subtitle()),
134 )
135 .when(ends_current, |column| {
136 column.child(
137 div()
138 .text_size(px(12.))
139 .text_color(theme::amber())
140 .child(ENDS_CURRENT_CALL),
141 )
142 })
143 .child(h_flex().mt(px(8.)).gap(px(8.)).child(decline).child(accept)),
144 ),
145 ),
146 )
147 .into_any_element()
148 }
149 }
@@ -0,0 +1,149 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
5
6use super::center::NotificationCenter;
7use super::layout::{AVATAR_GAP, TOAST_PADDING};
8use crate::app_state::AppState;
9use crate::call::RingEntry;
10use crate::theme;
11use crate::views::avatar::person_avatar;
12use crate::views::call_view::pulsing;
13use crate::views::widgets::icon;
14
15pub const RING_AVATAR: f32 = 56.;
16const RING_BORDER: f32 = 2.;
17const RING_WIDTH: f32 = 3.;
18const RING_GAP: f32 = 3.;
19const TOAST_RADIUS: f32 = 12.;
20const BUTTON_HEIGHT: f32 = 32.;
21pub const ENDS_CURRENT_CALL: &str = "Accept ends current call";
22
23pub struct RingView {
24 app: Entity<AppState>,
25 ring_id: u64,
26 _subscription: Subscription,
27}
28
29impl RingView {
30 pub fn new(center: Entity<NotificationCenter>, ring_id: u64, cx: &mut Context<Self>) -> Self {
31 let app = center.read(cx).app().clone();
32 let subscription = cx.observe(&app, |_, _, cx| cx.notify());
33 RingView {
34 app,
35 ring_id,
36 _subscription: subscription,
37 }
38 }
39}
40
41fn answer_button(id: &'static str, label: &str, glyph: IconName, fill: Hsla) -> Stateful<gpui_kit::Div> {
42 h_flex()
43 .id(id)
44 .h(px(BUTTON_HEIGHT))
45 .px(px(14.))
46 .gap(px(6.))
47 .flex_none()
48 .items_center()
49 .justify_center()
50 .rounded_full()
51 .bg(fill)
52 .text_color(theme::white())
53 .text_size(px(13.))
54 .font_weight(FontWeight::SEMIBOLD)
55 .cursor_pointer()
56 .hover(|button| button.opacity(0.85))
57 .child(icon(glyph, 16., theme::white()))
58 .child(label.to_owned())
59}
60
61fn caller_avatar(state: &AppState, entry: &RingEntry) -> AnyElement {
62 let avatar = person_avatar(
63 &state.directory,
64 entry.caller_user_id().as_deref(),
65 entry.caller_name(),
66 RING_AVATAR,
67 );
68 let ringed = div()
69 .p(px(RING_GAP))
70 .rounded_full()
71 .border(px(RING_WIDTH))
72 .border_color(theme::green())
73 .child(avatar);
74 pulsing(ringed, "ring-avatar-pulse")
75}
76
77impl Render for RingView {
78 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
79 let state = self.app.read(cx);
80 let Some(entry) = state.rings.get(self.ring_id).cloned() else {
81 return div().size_full().bg(theme::surface_raised()).into_any_element();
82 };
83 window.set_window_title(&format!("{}: {}", entry.caller_name(), entry.subtitle()));
84 let ends_current = state.call.is_some();
85 let avatar = caller_avatar(state, &entry);
86 let ring_id = self.ring_id;
87 let decline_app = self.app.clone();
88 let accept_app = self.app.clone();
89 let decline = answer_button("ring-decline", "Decline", IconName::PhoneOff, theme::red()).on_click(
90 move |_, _, cx| {
91 cx.stop_propagation();
92 decline_app.update(cx, |state, cx| state.decline_ring(ring_id, cx));
93 },
94 );
95 let accept = answer_button("ring-accept", entry.accept_label(), IconName::Phone, theme::green()).on_click(
96 move |_, _, cx| {
97 cx.stop_propagation();
98 accept_app.update(cx, |state, cx| state.accept_ring(ring_id, cx));
99 },
100 );
101 div()
102 .id(("ring", ring_id))
103 .size_full()
104 .rounded(px(TOAST_RADIUS))
105 .bg(theme::surface_raised())
106 .border(px(RING_BORDER))
107 .border_color(theme::green())
108 .overflow_hidden()
109 .child(
110 div().size_full().p(px(TOAST_PADDING)).child(
111 h_flex()
112 .size_full()
113 .gap(px(AVATAR_GAP))
114 .items_start()
115 .child(avatar)
116 .child(
117 v_flex()
118 .flex_1()
119 .min_w_0()
120 .gap(px(2.))
121 .child(
122 div()
123 .truncate()
124 .text_size(px(15.))
125 .font_weight(FontWeight::SEMIBOLD)
126 .text_color(theme::text())
127 .child(entry.caller_name().to_owned()),
128 )
129 .child(
130 div()
131 .text_size(px(12.5))
132 .text_color(theme::text_muted())
133 .child(entry.subtitle()),
134 )
135 .when(ends_current, |column| {
136 column.child(
137 div()
138 .text_size(px(12.))
139 .text_color(theme::amber())
140 .child(ENDS_CURRENT_CALL),
141 )
142 })
143 .child(h_flex().mt(px(8.)).gap(px(8.)).child(decline).child(accept)),
144 ),
145 ),
146 )
147 .into_any_element()
148 }
149}
crates/app/src/views/activity_panel.rs +8 −0
@@ -344,6 +344,7 @@ fn kind_marker(entry: &Entry) -> Div {
344 344 .font_weight(FontWeight::BOLD)
345 345 .child("@"),
346 346 Kind::Reaction => marker.child(entry.glyphs.first().cloned().unwrap_or_default()),
347 Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),
347 348 }
348 349 }
349 350
@@ -353,6 +354,7 @@ fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, S
353 354 Kind::Messages => names,
354 355 Kind::Mention => format!("{names} mentioned you"),
355 356 Kind::Reaction => format!("{names} reacted"),
357 Kind::MissedCall => format!("Missed call from {names}"),
356 358 };
357 359 match conversation_label(sidebar, &entry.conversation_id) {
358 360 Some(label) => format!("{verb} in {label}"),
@@ -366,6 +368,7 @@ fn detail(entry: &Entry) -> String {
366 368 format!("{} new messages: {}", entry.count, entry.preview)
367 369 }
368 370 Kind::Reaction => format!("{} to: {}", entry.glyphs.join(" "), entry.preview),
371 Kind::MissedCall if entry.count > 1 => format!("{} missed calls", entry.count),
369 372 _ => entry.preview.clone(),
370 373 }
371 374 }
@@ -522,6 +525,7 @@ mod tests {
522 525 assert_eq!(detail(&entry(Kind::Messages, 3)), "3 new messages: hello");
523 526 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
524 527 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
528 assert_eq!(detail(&entry(Kind::MissedCall, 3)), "3 missed calls");
525 529 }
526 530
527 531 #[test]
@@ -546,6 +550,10 @@ mod tests {
546 550 headline(&entry(Kind::Mention, 1), &sidebar, &HashMap::new()),
547 551 "Anna mentioned you"
548 552 );
553 assert_eq!(
554 headline(&entry(Kind::MissedCall, 1), &sidebar, &HashMap::new()),
555 "Missed call from Anna"
556 );
549 557 }
550 558
551 559 #[test]
@@ -344,6 +344,7 @@ fn kind_marker(entry: &Entry) -> Div {
344 .font_weight(FontWeight::BOLD)
344 .font_weight(FontWeight::BOLD)
345 .child("@"),
345 .child("@"),
346 Kind::Reaction => marker.child(entry.glyphs.first().cloned().unwrap_or_default()),
346 Kind::Reaction => marker.child(entry.glyphs.first().cloned().unwrap_or_default()),
347 Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),
347 }
348 }
348}
349}
349
350
@@ -353,6 +354,7 @@ fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, S
353 Kind::Messages => names,
354 Kind::Messages => names,
354 Kind::Mention => format!("{names} mentioned you"),
355 Kind::Mention => format!("{names} mentioned you"),
355 Kind::Reaction => format!("{names} reacted"),
356 Kind::Reaction => format!("{names} reacted"),
357 Kind::MissedCall => format!("Missed call from {names}"),
356 };
358 };
357 match conversation_label(sidebar, &entry.conversation_id) {
359 match conversation_label(sidebar, &entry.conversation_id) {
358 Some(label) => format!("{verb} in {label}"),
360 Some(label) => format!("{verb} in {label}"),
@@ -366,6 +368,7 @@ fn detail(entry: &Entry) -> String {
366 format!("{} new messages: {}", entry.count, entry.preview)
368 format!("{} new messages: {}", entry.count, entry.preview)
367 }
369 }
368 Kind::Reaction => format!("{} to: {}", entry.glyphs.join(" "), entry.preview),
370 Kind::Reaction => format!("{} to: {}", entry.glyphs.join(" "), entry.preview),
371 Kind::MissedCall if entry.count > 1 => format!("{} missed calls", entry.count),
369 _ => entry.preview.clone(),
372 _ => entry.preview.clone(),
370 }
373 }
371}
374}
@@ -522,6 +525,7 @@ mod tests {
522 assert_eq!(detail(&entry(Kind::Messages, 3)), "3 new messages: hello");
525 assert_eq!(detail(&entry(Kind::Messages, 3)), "3 new messages: hello");
523 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
526 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
524 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
527 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
528 assert_eq!(detail(&entry(Kind::MissedCall, 3)), "3 missed calls");
525 }
529 }
526
530
527 #[test]
531 #[test]
@@ -546,6 +550,10 @@ mod tests {
546 headline(&entry(Kind::Mention, 1), &sidebar, &HashMap::new()),
550 headline(&entry(Kind::Mention, 1), &sidebar, &HashMap::new()),
547 "Anna mentioned you"
551 "Anna mentioned you"
548 );
552 );
553 assert_eq!(
554 headline(&entry(Kind::MissedCall, 1), &sidebar, &HashMap::new()),
555 "Missed call from Anna"
556 );
549 }
557 }
550
558
551 #[test]
559 #[test]
crates/app/src/views/call_controls.rs added +73 −0
@@ -0,0 +1,73 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::{
3 button::{Button, ButtonVariants as _},
4 h_flex,
5 };
6 use gpui_kit::*;
7
8 use super::widgets::icon;
9 use crate::app_state::{AppState, Selection};
10 use crate::call::plan_for_chat;
11 use crate::theme;
12
13 const BUTTON_SIZE: f32 = 30.;
14 const GLYPH_SIZE: f32 = 16.;
15 const JOIN_HEIGHT: f32 = 30.;
16
17 pub fn header_call_controls(app: &Entity<AppState>, state: &AppState, selection: &Selection) -> Vec<AnyElement> {
18 let conversation_id = selection.conversation_id().to_owned();
19 let mut controls = Vec::new();
20 if state.running_meeting(&conversation_id).is_some() {
21 let join_app = app.clone();
22 let join_id = conversation_id.clone();
23 controls.push(
24 h_flex()
25 .id("header-join")
26 .h(px(JOIN_HEIGHT))
27 .px(px(14.))
28 .gap(px(6.))
29 .flex_none()
30 .items_center()
31 .rounded_full()
32 .bg(theme::green())
33 .text_color(theme::white())
34 .text_size(px(13.))
35 .font_weight(FontWeight::SEMIBOLD)
36 .cursor_pointer()
37 .hover(|button| button.opacity(0.85))
38 .child(icon(IconName::Phone, 14., theme::white()))
39 .child("Join")
40 .on_click(move |_, _, cx| {
41 join_app.update(cx, |state, cx| state.join_meeting_call(&join_id, cx));
42 })
43 .into_any_element(),
44 );
45 }
46 let callable = matches!(selection, Selection::Chat(chat_id)
47 if state
48 .sidebar
49 .chats
50 .iter()
51 .find(|chat| &chat.id == chat_id)
52 .is_some_and(|chat| plan_for_chat(chat, state.directory.me.as_ref()).is_some()));
53 if callable {
54 let call_app = app.clone();
55 controls.push(
56 Button::new("header-call")
57 .ghost()
58 .p_0()
59 .size(px(BUTTON_SIZE))
60 .tooltip("Call")
61 .child(icon(IconName::Phone, GLYPH_SIZE, theme::text_soft()))
62 .on_click(move |_, _, cx| {
63 call_app.update(cx, |state, cx| {
64 if let Some(Selection::Chat(chat_id)) = state.selection.clone() {
65 state.start_chat_call(&chat_id, cx);
66 }
67 });
68 })
69 .into_any_element(),
70 );
71 }
72 controls
73 }
@@ -0,0 +1,73 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::component::{
3 button::{Button, ButtonVariants as _},
4 h_flex,
5};
6use gpui_kit::*;
7
8use super::widgets::icon;
9use crate::app_state::{AppState, Selection};
10use crate::call::plan_for_chat;
11use crate::theme;
12
13const BUTTON_SIZE: f32 = 30.;
14const GLYPH_SIZE: f32 = 16.;
15const JOIN_HEIGHT: f32 = 30.;
16
17pub fn header_call_controls(app: &Entity<AppState>, state: &AppState, selection: &Selection) -> Vec<AnyElement> {
18 let conversation_id = selection.conversation_id().to_owned();
19 let mut controls = Vec::new();
20 if state.running_meeting(&conversation_id).is_some() {
21 let join_app = app.clone();
22 let join_id = conversation_id.clone();
23 controls.push(
24 h_flex()
25 .id("header-join")
26 .h(px(JOIN_HEIGHT))
27 .px(px(14.))
28 .gap(px(6.))
29 .flex_none()
30 .items_center()
31 .rounded_full()
32 .bg(theme::green())
33 .text_color(theme::white())
34 .text_size(px(13.))
35 .font_weight(FontWeight::SEMIBOLD)
36 .cursor_pointer()
37 .hover(|button| button.opacity(0.85))
38 .child(icon(IconName::Phone, 14., theme::white()))
39 .child("Join")
40 .on_click(move |_, _, cx| {
41 join_app.update(cx, |state, cx| state.join_meeting_call(&join_id, cx));
42 })
43 .into_any_element(),
44 );
45 }
46 let callable = matches!(selection, Selection::Chat(chat_id)
47 if state
48 .sidebar
49 .chats
50 .iter()
51 .find(|chat| &chat.id == chat_id)
52 .is_some_and(|chat| plan_for_chat(chat, state.directory.me.as_ref()).is_some()));
53 if callable {
54 let call_app = app.clone();
55 controls.push(
56 Button::new("header-call")
57 .ghost()
58 .p_0()
59 .size(px(BUTTON_SIZE))
60 .tooltip("Call")
61 .child(icon(IconName::Phone, GLYPH_SIZE, theme::text_soft()))
62 .on_click(move |_, _, cx| {
63 call_app.update(cx, |state, cx| {
64 if let Some(Selection::Chat(chat_id)) = state.selection.clone() {
65 state.start_chat_call(&chat_id, cx);
66 }
67 });
68 })
69 .into_any_element(),
70 );
71 }
72 controls
73}
crates/app/src/views/call_view.rs +122 −33
@@ -15,13 +15,11 @@ use gpui_kit::*;
15 15 use super::avatar::person_avatar;
16 16 use super::widgets::icon;
17 17 use crate::app_state::AppState;
18 use crate::call::CallModel;
18 use crate::call::{CallKind, CallModel, GridLayout, TileState, grid_layout, tile_size};
19 use crate::call::TileSize;
19 20 use crate::theme;
20 21
21 22 const HEADER_HEIGHT: f32 = 60.;
22 const TILE_WIDTH: f32 = 260.;
23 const TILE_HEIGHT: f32 = 210.;
24 const AVATAR_SIZE: f32 = 96.;
25 23 const RING_WIDTH: f32 = 3.;
26 24 const RING_GAP: f32 = 4.;
27 25 const CONTROL_SIZE: f32 = 44.;
@@ -29,12 +27,16 @@ const CONTROL_ICON: f32 = 20.;
29 27 const MENU_WIDTH: f32 = 280.;
30 28 const PULSE_PERIOD: Duration = Duration::from_millis(1400);
31 29 const DISABLED_OPACITY: f32 = 0.4;
32 pub const ECHO_NAME: &str = "Teams echo";
30 const TILE_GAP: f32 = 20.;
31 const GRID_PADDING: f32 = 24.;
33 32 pub const NO_MICROPHONE_HINT: &str = "No microphone found";
33 pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
34 34
35 35 pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {
36 if model.is_connecting() {
37 ("Calling...".to_owned(), theme::text_muted())
36 if model.lobby {
37 (LOBBY_TEXT.to_owned(), theme::amber())
38 } else if model.is_connecting() {
39 (model.connecting_text().to_owned(), theme::text_muted())
38 40 } else if model.is_reconnecting() {
39 41 ("Reconnecting...".to_owned(), theme::amber())
40 42 } else {
@@ -69,7 +71,14 @@ fn speaking_ring(avatar: AnyElement, speaking: bool) -> Div {
69 71 .child(avatar)
70 72 }
71 73
72 fn tile(avatar: AnyElement, name: &str, speaking: bool, muted: bool, caption: Option<AnyElement>) -> Div {
74 fn tile(
75 size: TileSize,
76 avatar: AnyElement,
77 name: &str,
78 speaking: bool,
79 muted: bool,
80 caption: Option<AnyElement>,
81 ) -> Div {
73 82 let badge = div()
74 83 .absolute()
75 84 .top(px(10.))
@@ -83,8 +92,8 @@ fn tile(avatar: AnyElement, name: &str, speaking: bool, muted: bool, caption: Op
83 92 .child(icon(IconName::MicOff, 13., theme::white()));
84 93 v_flex()
85 94 .relative()
86 .w(px(TILE_WIDTH))
87 .h(px(TILE_HEIGHT))
95 .w(px(size.width))
96 .h(px(size.height))
88 97 .items_center()
89 98 .justify_center()
90 99 .gap(px(12.))
@@ -97,8 +106,11 @@ fn tile(avatar: AnyElement, name: &str, speaking: bool, muted: bool, caption: Op
97 106 v_flex()
98 107 .items_center()
99 108 .gap(px(2.))
109 .max_w(px(size.width - 16.))
100 110 .child(
101 111 div()
112 .max_w_full()
113 .truncate()
102 114 .text_size(px(14.))
103 115 .font_weight(FontWeight::SEMIBOLD)
104 116 .child(name.to_owned()),
@@ -108,6 +120,25 @@ fn tile(avatar: AnyElement, name: &str, speaking: bool, muted: bool, caption: Op
108 120 .when(muted, |tile| tile.child(badge))
109 121 }
110 122
123 fn overflow_tile(size: TileSize, hidden: usize) -> Div {
124 v_flex()
125 .w(px(size.width))
126 .h(px(size.height))
127 .items_center()
128 .justify_center()
129 .rounded(px(12.))
130 .bg(theme::surface())
131 .border_1()
132 .border_color(theme::border())
133 .child(
134 div()
135 .text_size(px(size.avatar * 0.5))
136 .font_weight(FontWeight::SEMIBOLD)
137 .text_color(theme::text_muted())
138 .child(format!("+{hidden}")),
139 )
140 }
141
111 142 fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {
112 143 div()
113 144 .id(id)
@@ -169,6 +200,48 @@ pub fn leave_button(app: &Entity<AppState>, model: &CallModel, id: &'static str,
169 200 })
170 201 }
171 202
203 fn chat_button(app: &Entity<AppState>) -> Stateful<Div> {
204 let app = app.clone();
205 round_control("call-chat", IconName::MessageCircle, theme::surface_raised(), theme::text())
206 .tooltip(|window, cx| Tooltip::new("Open the chat").build(window, cx))
207 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.open_call_chat(cx)))
208 }
209
210 fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
211 let leave_app = app.clone();
212 let end_app = app.clone();
213 let can_end = model.can_end_meeting;
214 Button::new("call-leave-menu")
215 .ghost()
216 .p_0()
217 .size(px(CONTROL_SIZE))
218 .rounded_full()
219 .child(round_control(
220 "call-leave-menu-face",
221 IconName::ChevronUp,
222 theme::surface_raised(),
223 theme::text(),
224 ))
225 .dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
226 let leave_app = leave_app.clone();
227 let end_app = end_app.clone();
228 let popup = popup.min_w(px(MENU_WIDTH)).item(
229 PopupMenuItem::new("Leave")
230 .icon(IconName::PhoneOff)
231 .on_click(move |_, _, cx| leave_app.update(cx, |state, cx| state.leave_call(cx))),
232 );
233 if can_end {
234 popup.item(
235 PopupMenuItem::new("End meeting for everyone")
236 .icon(IconName::PhoneOff)
237 .on_click(move |_, _, cx| end_app.update(cx, |state, cx| state.end_meeting_for_all(cx))),
238 )
239 } else {
240 popup
241 }
242 })
243 }
244
172 245 fn device_items(
173 246 entries: Vec<DeviceEntry>,
174 247 selected: &calling::DeviceChoice,
@@ -231,6 +304,28 @@ fn devices_button(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement
231 304 })
232 305 }
233 306
307 fn remote_tiles(state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout) -> Vec<AnyElement> {
308 let visible = model.visible_tiles();
309 let mut cells: Vec<AnyElement> = visible
310 .iter()
311 .take(hidden_cap.shown_others)
312 .map(|remote| {
313 let waiting = remote.state == TileState::Invited;
314 let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);
315 let avatar = if waiting { pulsing(avatar, "call-invited-pulse") } else { avatar };
316 let caption = model.tile_caption(remote).map(|text| {
317 let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);
318 if waiting { pulsing(label, "call-invited-caption") } else { label.into_any_element() }
319 });
320 tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption).into_any_element()
321 })
322 .collect();
323 if hidden_cap.hidden > 0 {
324 cells.push(overflow_tile(size, hidden_cap.hidden).into_any_element());
325 }
326 cells
327 }
328
234 329 pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
235 330 let call = state.call.as_ref()?;
236 331 let model = &call.model;
@@ -249,35 +344,25 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
249 344 .child(icon(IconName::Phone, 18., theme::accent_text()))
250 345 .child(
251 346 div()
347 .min_w_0()
348 .truncate()
252 349 .text_size(px(16.))
253 350 .font_weight(FontWeight::SEMIBOLD)
254 351 .child(model.title.clone()),
255 352 )
256 .child(div().text_size(px(13.)).text_color(status_color).child(status));
353 .child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status));
257 354
258 let echo_avatar = person_avatar(&state.directory, None, ECHO_NAME, AVATAR_SIZE);
259 let calling_caption = model.is_connecting().then(|| {
260 pulsing(
261 div()
262 .text_size(px(12.))
263 .text_color(theme::text_muted())
264 .child("Calling..."),
265 "call-calling",
266 )
267 });
268 let echo_avatar = if model.is_connecting() {
269 pulsing(echo_avatar, "call-echo-pulse")
270 } else {
271 echo_avatar
272 };
273 let echo_tile = tile(echo_avatar, ECHO_NAME, model.remote_speaking, false, calling_caption);
355 let layout = grid_layout(model.visible_tiles().len());
356 let size = tile_size(layout.shown_others + usize::from(layout.hidden > 0) + 1);
274 357 let own_avatar = person_avatar(
275 358 &state.directory,
276 359 me.map(|person| person.user_id.as_str()),
277 360 me.map_or("You", |person| person.display_name.as_str()),
278 AVATAR_SIZE,
361 size.avatar,
279 362 );
280 let own_tile = tile(own_avatar, "You", model.local_speaking, model.muted, None);
363 let own_tile = tile(size, own_avatar, "You", model.local_speaking, model.muted, None);
364 let mut cells = remote_tiles(state, model, size, layout);
365 cells.push(own_tile.into_any_element());
281 366
282 367 let controls = h_flex()
283 368 .w_full()
@@ -290,7 +375,9 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
290 375 .border_color(theme::border())
291 376 .child(mute_button(app, model, "call-mute", CONTROL_SIZE))
292 377 .child(devices_button(app, model))
293 .child(leave_button(app, model, "call-leave", false));
378 .when(call.conversation_id.is_some(), |row| row.child(chat_button(app)))
379 .child(leave_button(app, model, "call-leave", false))
380 .when(model.kind == CallKind::Meeting, |row| row.child(leave_menu(app, model)));
294 381
295 382 Some(
296 383 v_flex()
@@ -303,11 +390,13 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
303 390 h_flex()
304 391 .flex_1()
305 392 .min_h_0()
306 .gap(px(20.))
393 .flex_wrap()
394 .content_center()
395 .p(px(GRID_PADDING))
396 .gap(px(TILE_GAP))
307 397 .items_center()
308 398 .justify_center()
309 .child(echo_tile)
310 .child(own_tile),
399 .children(cells),
311 400 )
312 401 .child(controls)
313 402 .into_any_element(),
@@ -15,13 +15,11 @@ use gpui_kit::*;
15use super::avatar::person_avatar;
15use super::avatar::person_avatar;
16use super::widgets::icon;
16use super::widgets::icon;
17use crate::app_state::AppState;
17use crate::app_state::AppState;
18use crate::call::CallModel;
18use crate::call::{CallKind, CallModel, GridLayout, TileState, grid_layout, tile_size};
19use crate::call::TileSize;
19use crate::theme;
20use crate::theme;
20
21
21const HEADER_HEIGHT: f32 = 60.;
22const HEADER_HEIGHT: f32 = 60.;
22const TILE_WIDTH: f32 = 260.;
23const TILE_HEIGHT: f32 = 210.;
24const AVATAR_SIZE: f32 = 96.;
25const RING_WIDTH: f32 = 3.;
23const RING_WIDTH: f32 = 3.;
26const RING_GAP: f32 = 4.;
24const RING_GAP: f32 = 4.;
27const CONTROL_SIZE: f32 = 44.;
25const CONTROL_SIZE: f32 = 44.;
@@ -29,12 +27,16 @@ const CONTROL_ICON: f32 = 20.;
29const MENU_WIDTH: f32 = 280.;
27const MENU_WIDTH: f32 = 280.;
30const PULSE_PERIOD: Duration = Duration::from_millis(1400);
28const PULSE_PERIOD: Duration = Duration::from_millis(1400);
31const DISABLED_OPACITY: f32 = 0.4;
29const DISABLED_OPACITY: f32 = 0.4;
32pub const ECHO_NAME: &str = "Teams echo";
30const TILE_GAP: f32 = 20.;
31const GRID_PADDING: f32 = 24.;
33pub const NO_MICROPHONE_HINT: &str = "No microphone found";
32pub const NO_MICROPHONE_HINT: &str = "No microphone found";
33pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
34
34
35pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {
35pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {
36 if model.is_connecting() {
36 if model.lobby {
37 ("Calling...".to_owned(), theme::text_muted())
37 (LOBBY_TEXT.to_owned(), theme::amber())
38 } else if model.is_connecting() {
39 (model.connecting_text().to_owned(), theme::text_muted())
38 } else if model.is_reconnecting() {
40 } else if model.is_reconnecting() {
39 ("Reconnecting...".to_owned(), theme::amber())
41 ("Reconnecting...".to_owned(), theme::amber())
40 } else {
42 } else {
@@ -69,7 +71,14 @@ fn speaking_ring(avatar: AnyElement, speaking: bool) -> Div {
69 .child(avatar)
71 .child(avatar)
70}
72}
71
73
72fn tile(avatar: AnyElement, name: &str, speaking: bool, muted: bool, caption: Option<AnyElement>) -> Div {
74fn tile(
75 size: TileSize,
76 avatar: AnyElement,
77 name: &str,
78 speaking: bool,
79 muted: bool,
80 caption: Option<AnyElement>,
81) -> Div {
73 let badge = div()
82 let badge = div()
74 .absolute()
83 .absolute()
75 .top(px(10.))
84 .top(px(10.))
@@ -83,8 +92,8 @@ fn tile(avatar: AnyElement, name: &str, speaking: bool, muted: bool, caption: Op
83 .child(icon(IconName::MicOff, 13., theme::white()));
92 .child(icon(IconName::MicOff, 13., theme::white()));
84 v_flex()
93 v_flex()
85 .relative()
94 .relative()
86 .w(px(TILE_WIDTH))
95 .w(px(size.width))
87 .h(px(TILE_HEIGHT))
96 .h(px(size.height))
88 .items_center()
97 .items_center()
89 .justify_center()
98 .justify_center()
90 .gap(px(12.))
99 .gap(px(12.))
@@ -97,8 +106,11 @@ fn tile(avatar: AnyElement, name: &str, speaking: bool, muted: bool, caption: Op
97 v_flex()
106 v_flex()
98 .items_center()
107 .items_center()
99 .gap(px(2.))
108 .gap(px(2.))
109 .max_w(px(size.width - 16.))
100 .child(
110 .child(
101 div()
111 div()
112 .max_w_full()
113 .truncate()
102 .text_size(px(14.))
114 .text_size(px(14.))
103 .font_weight(FontWeight::SEMIBOLD)
115 .font_weight(FontWeight::SEMIBOLD)
104 .child(name.to_owned()),
116 .child(name.to_owned()),
@@ -108,6 +120,25 @@ fn tile(avatar: AnyElement, name: &str, speaking: bool, muted: bool, caption: Op
108 .when(muted, |tile| tile.child(badge))
120 .when(muted, |tile| tile.child(badge))
109}
121}
110
122
123fn overflow_tile(size: TileSize, hidden: usize) -> Div {
124 v_flex()
125 .w(px(size.width))
126 .h(px(size.height))
127 .items_center()
128 .justify_center()
129 .rounded(px(12.))
130 .bg(theme::surface())
131 .border_1()
132 .border_color(theme::border())
133 .child(
134 div()
135 .text_size(px(size.avatar * 0.5))
136 .font_weight(FontWeight::SEMIBOLD)
137 .text_color(theme::text_muted())
138 .child(format!("+{hidden}")),
139 )
140}
141
111fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {
142fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {
112 div()
143 div()
113 .id(id)
144 .id(id)
@@ -169,6 +200,48 @@ pub fn leave_button(app: &Entity<AppState>, model: &CallModel, id: &'static str,
169 })
200 })
170}
201}
171
202
203fn chat_button(app: &Entity<AppState>) -> Stateful<Div> {
204 let app = app.clone();
205 round_control("call-chat", IconName::MessageCircle, theme::surface_raised(), theme::text())
206 .tooltip(|window, cx| Tooltip::new("Open the chat").build(window, cx))
207 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.open_call_chat(cx)))
208}
209
210fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
211 let leave_app = app.clone();
212 let end_app = app.clone();
213 let can_end = model.can_end_meeting;
214 Button::new("call-leave-menu")
215 .ghost()
216 .p_0()
217 .size(px(CONTROL_SIZE))
218 .rounded_full()
219 .child(round_control(
220 "call-leave-menu-face",
221 IconName::ChevronUp,
222 theme::surface_raised(),
223 theme::text(),
224 ))
225 .dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
226 let leave_app = leave_app.clone();
227 let end_app = end_app.clone();
228 let popup = popup.min_w(px(MENU_WIDTH)).item(
229 PopupMenuItem::new("Leave")
230 .icon(IconName::PhoneOff)
231 .on_click(move |_, _, cx| leave_app.update(cx, |state, cx| state.leave_call(cx))),
232 );
233 if can_end {
234 popup.item(
235 PopupMenuItem::new("End meeting for everyone")
236 .icon(IconName::PhoneOff)
237 .on_click(move |_, _, cx| end_app.update(cx, |state, cx| state.end_meeting_for_all(cx))),
238 )
239 } else {
240 popup
241 }
242 })
243}
244
172fn device_items(
245fn device_items(
173 entries: Vec<DeviceEntry>,
246 entries: Vec<DeviceEntry>,
174 selected: &calling::DeviceChoice,
247 selected: &calling::DeviceChoice,
@@ -231,6 +304,28 @@ fn devices_button(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement
231 })
304 })
232}
305}
233
306
307fn remote_tiles(state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout) -> Vec<AnyElement> {
308 let visible = model.visible_tiles();
309 let mut cells: Vec<AnyElement> = visible
310 .iter()
311 .take(hidden_cap.shown_others)
312 .map(|remote| {
313 let waiting = remote.state == TileState::Invited;
314 let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);
315 let avatar = if waiting { pulsing(avatar, "call-invited-pulse") } else { avatar };
316 let caption = model.tile_caption(remote).map(|text| {
317 let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);
318 if waiting { pulsing(label, "call-invited-caption") } else { label.into_any_element() }
319 });
320 tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption).into_any_element()
321 })
322 .collect();
323 if hidden_cap.hidden > 0 {
324 cells.push(overflow_tile(size, hidden_cap.hidden).into_any_element());
325 }
326 cells
327}
328
234pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
329pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
235 let call = state.call.as_ref()?;
330 let call = state.call.as_ref()?;
236 let model = &call.model;
331 let model = &call.model;
@@ -249,35 +344,25 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
249 .child(icon(IconName::Phone, 18., theme::accent_text()))
344 .child(icon(IconName::Phone, 18., theme::accent_text()))
250 .child(
345 .child(
251 div()
346 div()
347 .min_w_0()
348 .truncate()
252 .text_size(px(16.))
349 .text_size(px(16.))
253 .font_weight(FontWeight::SEMIBOLD)
350 .font_weight(FontWeight::SEMIBOLD)
254 .child(model.title.clone()),
351 .child(model.title.clone()),
255 )
352 )
256 .child(div().text_size(px(13.)).text_color(status_color).child(status));
353 .child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status));
257
354
258 let echo_avatar = person_avatar(&state.directory, None, ECHO_NAME, AVATAR_SIZE);
355 let layout = grid_layout(model.visible_tiles().len());
259 let calling_caption = model.is_connecting().then(|| {
356 let size = tile_size(layout.shown_others + usize::from(layout.hidden > 0) + 1);
260 pulsing(
261 div()
262 .text_size(px(12.))
263 .text_color(theme::text_muted())
264 .child("Calling..."),
265 "call-calling",
266 )
267 });
268 let echo_avatar = if model.is_connecting() {
269 pulsing(echo_avatar, "call-echo-pulse")
270 } else {
271 echo_avatar
272 };
273 let echo_tile = tile(echo_avatar, ECHO_NAME, model.remote_speaking, false, calling_caption);
274 let own_avatar = person_avatar(
357 let own_avatar = person_avatar(
275 &state.directory,
358 &state.directory,
276 me.map(|person| person.user_id.as_str()),
359 me.map(|person| person.user_id.as_str()),
277 me.map_or("You", |person| person.display_name.as_str()),
360 me.map_or("You", |person| person.display_name.as_str()),
278 AVATAR_SIZE,
361 size.avatar,
279 );
362 );
280 let own_tile = tile(own_avatar, "You", model.local_speaking, model.muted, None);
363 let own_tile = tile(size, own_avatar, "You", model.local_speaking, model.muted, None);
364 let mut cells = remote_tiles(state, model, size, layout);
365 cells.push(own_tile.into_any_element());
281
366
282 let controls = h_flex()
367 let controls = h_flex()
283 .w_full()
368 .w_full()
@@ -290,7 +375,9 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
290 .border_color(theme::border())
375 .border_color(theme::border())
291 .child(mute_button(app, model, "call-mute", CONTROL_SIZE))
376 .child(mute_button(app, model, "call-mute", CONTROL_SIZE))
292 .child(devices_button(app, model))
377 .child(devices_button(app, model))
293 .child(leave_button(app, model, "call-leave", false));
378 .when(call.conversation_id.is_some(), |row| row.child(chat_button(app)))
379 .child(leave_button(app, model, "call-leave", false))
380 .when(model.kind == CallKind::Meeting, |row| row.child(leave_menu(app, model)));
294
381
295 Some(
382 Some(
296 v_flex()
383 v_flex()
@@ -303,11 +390,13 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
303 h_flex()
390 h_flex()
304 .flex_1()
391 .flex_1()
305 .min_h_0()
392 .min_h_0()
306 .gap(px(20.))
393 .flex_wrap()
394 .content_center()
395 .p(px(GRID_PADDING))
396 .gap(px(TILE_GAP))
307 .items_center()
397 .items_center()
308 .justify_center()
398 .justify_center()
309 .child(echo_tile)
399 .children(cells),
310 .child(own_tile),
311 )
400 )
312 .child(controls)
401 .child(controls)
313 .into_any_element(),
402 .into_any_element(),
crates/app/src/views/conversation.rs +6 −0
@@ -27,6 +27,7 @@ mod shared;
27 27
28 28 use super::attachments::FileActions;
29 29 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
30 use super::call_controls::header_call_controls;
30 31 use super::channel_tabs::ChannelPane;
31 32 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
32 33 use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
@@ -553,7 +554,10 @@ impl ConversationView {
553 554 | AppEvent::StatusMessage
554 555 | AppEvent::NotificationSettings
555 556 | AppEvent::Profile
557 | AppEvent::Ring
558 | AppEvent::MissedCall(_)
556 559 | AppEvent::Call => {}
560 AppEvent::LiveMeeting => cx.notify(),
557 561 AppEvent::Saved => cx.notify(),
558 562 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
559 563 AppEvent::Typing => cx.notify(),
@@ -2934,6 +2938,7 @@ impl ConversationView {
2934 2938 if let Some(note) = channel_note {
2935 2939 subline = note.to_owned();
2936 2940 }
2941 let call_controls = header_call_controls(&self.app, app, &current.selection);
2937 2942 let sync = &current.sync;
2938 2943 if sync.failed {
2939 2944 subline = "Not up to date".to_owned();
@@ -2977,6 +2982,7 @@ impl ConversationView {
2977 2982 }),
2978 2983 )
2979 2984 .children(stack)
2985 .children(call_controls)
2980 2986 }
2981 2987 }
2982 2988
@@ -27,6 +27,7 @@ mod shared;
27
27
28use super::attachments::FileActions;
28use super::attachments::FileActions;
29use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
29use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
30use super::call_controls::header_call_controls;
30use super::channel_tabs::ChannelPane;
31use super::channel_tabs::ChannelPane;
31use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
32use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
32use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
33use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
@@ -553,7 +554,10 @@ impl ConversationView {
553 | AppEvent::StatusMessage
554 | AppEvent::StatusMessage
554 | AppEvent::NotificationSettings
555 | AppEvent::NotificationSettings
555 | AppEvent::Profile
556 | AppEvent::Profile
557 | AppEvent::Ring
558 | AppEvent::MissedCall(_)
556 | AppEvent::Call => {}
559 | AppEvent::Call => {}
560 AppEvent::LiveMeeting => cx.notify(),
557 AppEvent::Saved => cx.notify(),
561 AppEvent::Saved => cx.notify(),
558 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
562 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
559 AppEvent::Typing => cx.notify(),
563 AppEvent::Typing => cx.notify(),
@@ -2934,6 +2938,7 @@ impl ConversationView {
2934 if let Some(note) = channel_note {
2938 if let Some(note) = channel_note {
2935 subline = note.to_owned();
2939 subline = note.to_owned();
2936 }
2940 }
2941 let call_controls = header_call_controls(&self.app, app, &current.selection);
2937 let sync = &current.sync;
2942 let sync = &current.sync;
2938 if sync.failed {
2943 if sync.failed {
2939 subline = "Not up to date".to_owned();
2944 subline = "Not up to date".to_owned();
@@ -2977,6 +2982,7 @@ impl ConversationView {
2977 }),
2982 }),
2978 )
2983 )
2979 .children(stack)
2984 .children(stack)
2985 .children(call_controls)
2980 }
2986 }
2981}
2987}
2982
2988
crates/app/src/views/mod.rs +1 −0
@@ -3,6 +3,7 @@ pub mod adaptive_card;
3 3 pub mod attachment_tray;
4 4 pub mod attachments;
5 5 pub mod avatar;
6 pub mod call_controls;
6 7 pub mod call_mini;
7 8 pub mod call_view;
8 9 pub mod card_carousel;
@@ -3,6 +3,7 @@ pub mod adaptive_card;
3pub mod attachment_tray;
3pub mod attachment_tray;
4pub mod attachments;
4pub mod attachments;
5pub mod avatar;
5pub mod avatar;
6pub mod call_controls;
6pub mod call_mini;
7pub mod call_mini;
7pub mod call_view;
8pub mod call_view;
8pub mod card_carousel;
9pub mod card_carousel;
crates/app/src/views/status_menu.rs +14 −2
@@ -179,7 +179,9 @@ fn status_menu(
179 179 None => context.summary.label.to_owned(),
180 180 };
181 181 let submenu_context = context.clone();
182 popup
182 let ring_app = context.app.clone();
183 let demo = context.app.read(cx).mode.demo;
184 let popup = popup
183 185 .min_w(px(MENU_WIDTH))
184 186 .item(PopupMenuItem::element(move |_, cx| {
185 187 header(&header_context, cx)
@@ -215,7 +217,17 @@ fn status_menu(
215 217 .on_click(move |_, _, cx| {
216 218 settings_app.update(cx, |state, cx| state.open_notification_settings(cx));
217 219 }),
218 )
220 );
221 if !demo {
222 return popup;
223 }
224 popup.item(
225 PopupMenuItem::new("Simulate incoming call")
226 .icon(menu_icon(IconName::Phone))
227 .on_click(move |_, _, cx| {
228 ring_app.update(cx, |state, cx| state.demo_incoming_ring(cx));
229 }),
230 )
219 231 }
220 232
221 233 fn chat_list_item(
@@ -179,7 +179,9 @@ fn status_menu(
179 None => context.summary.label.to_owned(),
179 None => context.summary.label.to_owned(),
180 };
180 };
181 let submenu_context = context.clone();
181 let submenu_context = context.clone();
182 popup
182 let ring_app = context.app.clone();
183 let demo = context.app.read(cx).mode.demo;
184 let popup = popup
183 .min_w(px(MENU_WIDTH))
185 .min_w(px(MENU_WIDTH))
184 .item(PopupMenuItem::element(move |_, cx| {
186 .item(PopupMenuItem::element(move |_, cx| {
185 header(&header_context, cx)
187 header(&header_context, cx)
@@ -215,7 +217,17 @@ fn status_menu(
215 .on_click(move |_, _, cx| {
217 .on_click(move |_, _, cx| {
216 settings_app.update(cx, |state, cx| state.open_notification_settings(cx));
218 settings_app.update(cx, |state, cx| state.open_notification_settings(cx));
217 }),
219 }),
218 )
220 );
221 if !demo {
222 return popup;
223 }
224 popup.item(
225 PopupMenuItem::new("Simulate incoming call")
226 .icon(menu_icon(IconName::Phone))
227 .on_click(move |_, _, cx| {
228 ring_app.update(cx, |state, cx| state.demo_incoming_ring(cx));
229 }),
230 )
219}
231}
220
232
221fn chat_list_item(
233fn chat_list_item(
crates/calling/Cargo.toml +3 −0
@@ -17,3 +17,6 @@ session.workspace = true
17 17 thiserror.workspace = true
18 18 tokio.workspace = true
19 19 uuid.workspace = true
20
21 [target.'cfg(windows)'.dev-dependencies]
22 webview.workspace = true
@@ -17,3 +17,6 @@ session.workspace = true
17thiserror.workspace = true
17thiserror.workspace = true
18tokio.workspace = true
18tokio.workspace = true
19uuid.workspace = true
19uuid.workspace = true
20
21[target.'cfg(windows)'.dev-dependencies]
22webview.workspace = true
crates/calling/examples/echo_call.rs +4 −4
@@ -2,13 +2,13 @@ use std::path::PathBuf;
2 2 use std::time::Duration;
3 3
4 4 use calling::audio_io::AUDIO_MODE_ENV;
5 use calling::{AudioMode, TestCallOptions, TestCallReport, call_channel, run_test_call};
5 use calling::{AudioMode, CallOptions, CallReport, call_channel, run_test_call};
6 6 use session::{DEFAULT_ENDPOINT, Session};
7 7
8 8 const HOLD_AFTER_CONNECTED: Duration = Duration::from_secs(12);
9 9 const HARD_LIMIT: Duration = Duration::from_secs(20);
10 10
11 fn print_report(report: &TestCallReport) {
11 fn print_report(report: &CallReport) {
12 12 println!("# ice connected at {:?} ms, peer connected at {:?} ms", report.ice_connected_ms, report.peer_connected_ms);
13 13 println!("# selected pair: {}", report.selected_pair.as_deref().unwrap_or("-"));
14 14 println!("# dtls {} {} srtp {}", report.tls_version, report.dtls_cipher, report.srtp_cipher);
@@ -36,7 +36,7 @@ async fn main() {
36 36 let session = Session::connect(&endpoint).await.expect("browser");
37 37 let poll_session = Session::connect(&endpoint).await.expect("browser");
38 38 let audio = AudioMode::parse(Some(&std::env::var(AUDIO_MODE_ENV).unwrap_or_else(|_| "tone".to_owned())));
39 let options = TestCallOptions {
39 let options = CallOptions {
40 40 audio,
41 41 hold_after_connected: Some(HOLD_AFTER_CONNECTED),
42 42 hard_limit: Some(HARD_LIMIT),
@@ -44,7 +44,7 @@ async fn main() {
44 44 wav_path: wav_path.clone(),
45 45 sdp_dump_dir: std::env::var("CALLING_SDP_DUMP").ok().map(PathBuf::from),
46 46 trace: true,
47 ..TestCallOptions::default()
47 ..CallOptions::default()
48 48 };
49 49 println!(
50 50 "# Test call, audio {:?}, hang up after {:?} connected (hard limit {:?})",
@@ -2,13 +2,13 @@ use std::path::PathBuf;
2use std::time::Duration;
2use std::time::Duration;
3
3
4use calling::audio_io::AUDIO_MODE_ENV;
4use calling::audio_io::AUDIO_MODE_ENV;
5use calling::{AudioMode, TestCallOptions, TestCallReport, call_channel, run_test_call};
5use calling::{AudioMode, CallOptions, CallReport, call_channel, run_test_call};
6use session::{DEFAULT_ENDPOINT, Session};
6use session::{DEFAULT_ENDPOINT, Session};
7
7
8const HOLD_AFTER_CONNECTED: Duration = Duration::from_secs(12);
8const HOLD_AFTER_CONNECTED: Duration = Duration::from_secs(12);
9const HARD_LIMIT: Duration = Duration::from_secs(20);
9const HARD_LIMIT: Duration = Duration::from_secs(20);
10
10
11fn print_report(report: &TestCallReport) {
11fn print_report(report: &CallReport) {
12 println!("# ice connected at {:?} ms, peer connected at {:?} ms", report.ice_connected_ms, report.peer_connected_ms);
12 println!("# ice connected at {:?} ms, peer connected at {:?} ms", report.ice_connected_ms, report.peer_connected_ms);
13 println!("# selected pair: {}", report.selected_pair.as_deref().unwrap_or("-"));
13 println!("# selected pair: {}", report.selected_pair.as_deref().unwrap_or("-"));
14 println!("# dtls {} {} srtp {}", report.tls_version, report.dtls_cipher, report.srtp_cipher);
14 println!("# dtls {} {} srtp {}", report.tls_version, report.dtls_cipher, report.srtp_cipher);
@@ -36,7 +36,7 @@ async fn main() {
36 let session = Session::connect(&endpoint).await.expect("browser");
36 let session = Session::connect(&endpoint).await.expect("browser");
37 let poll_session = Session::connect(&endpoint).await.expect("browser");
37 let poll_session = Session::connect(&endpoint).await.expect("browser");
38 let audio = AudioMode::parse(Some(&std::env::var(AUDIO_MODE_ENV).unwrap_or_else(|_| "tone".to_owned())));
38 let audio = AudioMode::parse(Some(&std::env::var(AUDIO_MODE_ENV).unwrap_or_else(|_| "tone".to_owned())));
39 let options = TestCallOptions {
39 let options = CallOptions {
40 audio,
40 audio,
41 hold_after_connected: Some(HOLD_AFTER_CONNECTED),
41 hold_after_connected: Some(HOLD_AFTER_CONNECTED),
42 hard_limit: Some(HARD_LIMIT),
42 hard_limit: Some(HARD_LIMIT),
@@ -44,7 +44,7 @@ async fn main() {
44 wav_path: wav_path.clone(),
44 wav_path: wav_path.clone(),
45 sdp_dump_dir: std::env::var("CALLING_SDP_DUMP").ok().map(PathBuf::from),
45 sdp_dump_dir: std::env::var("CALLING_SDP_DUMP").ok().map(PathBuf::from),
46 trace: true,
46 trace: true,
47 ..TestCallOptions::default()
47 ..CallOptions::default()
48 };
48 };
49 println!(
49 println!(
50 "# Test call, audio {:?}, hang up after {:?} connected (hard limit {:?})",
50 "# Test call, audio {:?}, hang up after {:?} connected (hard limit {:?})",
crates/calling/examples/engine_probe.rs added +76 −0
@@ -0,0 +1,76 @@
1 #[cfg(not(windows))]
2 fn main() {
3 eprintln!("engine_probe runs on Windows only; it uses the app's WebView2 host");
4 std::process::exit(2);
5 }
6
7 #[cfg(windows)]
8 #[tokio::main]
9 async fn main() {
10 use std::path::PathBuf;
11 use std::time::{Duration, Instant};
12
13 use calling::{CallEngine, EngineConfig, EngineEvent};
14 use session::{Session, SessionConfig};
15
16 const START_LIMIT: Duration = Duration::from_secs(90);
17
18 let folder = std::env::args().nth(1).map(PathBuf::from).expect("usage: engine_probe <user-data-folder> [hold-seconds]");
19 let hold = Duration::from_secs(std::env::args().nth(2).and_then(|value| value.parse().ok()).unwrap_or(15));
20 let started = Instant::now();
21 let transport = webview::start(webview::HostConfig {
22 user_data_folder: folder,
23 window_title: "Rusty Teams engine probe - Sign in".into(),
24 });
25 let sessions = async {
26 let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;
27 let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;
28 Ok::<_, session::Error>((session, poll_session))
29 };
30 let (session, poll_session) = match sessions.await {
31 Ok(sessions) => sessions,
32 Err(error) => return println!("# session failed after {:?}: {error}", started.elapsed()),
33 };
34 println!("# webview session ready after {:?}", started.elapsed());
35 let page_ready = async {
36 let (control, _events) = session.subscribe(session::App::Teams).await.ok()?;
37 loop {
38 let host = control.evaluate("location.host").await.ok()?.as_str().unwrap_or_default().to_owned();
39 if host.starts_with("teams.") {
40 return Some(true);
41 }
42 if host.starts_with("login.") {
43 return Some(false);
44 }
45 tokio::time::sleep(Duration::from_millis(250)).await;
46 }
47 };
48 match tokio::time::timeout(Duration::from_secs(60), page_ready).await {
49 Ok(Some(true)) => println!("# teams page on its origin after {:?}", started.elapsed()),
50 Ok(Some(false)) => return println!("# teams page is on the sign-in page, profile not signed in; stopping"),
51 _ => return println!("# teams page did not reach its origin"),
52 }
53 let engine_started = Instant::now();
54 let outcome = tokio::time::timeout(START_LIMIT, CallEngine::start(session, poll_session, EngineConfig::default())).await;
55 let (engine, mut events) = match outcome {
56 Ok(Ok(started_engine)) => started_engine,
57 Ok(Err(error)) => return println!("# engine start failed after {:?}: {error}", engine_started.elapsed()),
58 Err(_) => return println!("# engine start timed out after {START_LIMIT:?}"),
59 };
60 println!("# engine ready (registrar registration ok) after {:?}", engine_started.elapsed());
61 let mut incoming = 0;
62 let _ = tokio::time::timeout(hold, async {
63 while let Some(event) = events.recv().await {
64 incoming += 1;
65 match event {
66 EngineEvent::Incoming(ring) => println!("# evt: incoming ring id {} group {}", ring.ring_id, ring.is_group),
67 EngineEvent::RingEnded { ring_id, kind, .. } => println!("# evt: ring {ring_id} ended {kind:?}"),
68 }
69 }
70 })
71 .await;
72 println!("# held {hold:?}, engine events: {incoming}");
73 let stop_started = Instant::now();
74 engine.stop().await;
75 println!("# engine stopped after {:?}, total {:?}", stop_started.elapsed(), started.elapsed());
76 }
@@ -0,0 +1,76 @@
1#[cfg(not(windows))]
2fn main() {
3 eprintln!("engine_probe runs on Windows only; it uses the app's WebView2 host");
4 std::process::exit(2);
5}
6
7#[cfg(windows)]
8#[tokio::main]
9async fn main() {
10 use std::path::PathBuf;
11 use std::time::{Duration, Instant};
12
13 use calling::{CallEngine, EngineConfig, EngineEvent};
14 use session::{Session, SessionConfig};
15
16 const START_LIMIT: Duration = Duration::from_secs(90);
17
18 let folder = std::env::args().nth(1).map(PathBuf::from).expect("usage: engine_probe <user-data-folder> [hold-seconds]");
19 let hold = Duration::from_secs(std::env::args().nth(2).and_then(|value| value.parse().ok()).unwrap_or(15));
20 let started = Instant::now();
21 let transport = webview::start(webview::HostConfig {
22 user_data_folder: folder,
23 window_title: "Rusty Teams engine probe - Sign in".into(),
24 });
25 let sessions = async {
26 let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;
27 let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;
28 Ok::<_, session::Error>((session, poll_session))
29 };
30 let (session, poll_session) = match sessions.await {
31 Ok(sessions) => sessions,
32 Err(error) => return println!("# session failed after {:?}: {error}", started.elapsed()),
33 };
34 println!("# webview session ready after {:?}", started.elapsed());
35 let page_ready = async {
36 let (control, _events) = session.subscribe(session::App::Teams).await.ok()?;
37 loop {
38 let host = control.evaluate("location.host").await.ok()?.as_str().unwrap_or_default().to_owned();
39 if host.starts_with("teams.") {
40 return Some(true);
41 }
42 if host.starts_with("login.") {
43 return Some(false);
44 }
45 tokio::time::sleep(Duration::from_millis(250)).await;
46 }
47 };
48 match tokio::time::timeout(Duration::from_secs(60), page_ready).await {
49 Ok(Some(true)) => println!("# teams page on its origin after {:?}", started.elapsed()),
50 Ok(Some(false)) => return println!("# teams page is on the sign-in page, profile not signed in; stopping"),
51 _ => return println!("# teams page did not reach its origin"),
52 }
53 let engine_started = Instant::now();
54 let outcome = tokio::time::timeout(START_LIMIT, CallEngine::start(session, poll_session, EngineConfig::default())).await;
55 let (engine, mut events) = match outcome {
56 Ok(Ok(started_engine)) => started_engine,
57 Ok(Err(error)) => return println!("# engine start failed after {:?}: {error}", engine_started.elapsed()),
58 Err(_) => return println!("# engine start timed out after {START_LIMIT:?}"),
59 };
60 println!("# engine ready (registrar registration ok) after {:?}", engine_started.elapsed());
61 let mut incoming = 0;
62 let _ = tokio::time::timeout(hold, async {
63 while let Some(event) = events.recv().await {
64 incoming += 1;
65 match event {
66 EngineEvent::Incoming(ring) => println!("# evt: incoming ring id {} group {}", ring.ring_id, ring.is_group),
67 EngineEvent::RingEnded { ring_id, kind, .. } => println!("# evt: ring {ring_id} ended {kind:?}"),
68 }
69 }
70 })
71 .await;
72 println!("# held {hold:?}, engine events: {incoming}");
73 let stop_started = Instant::now();
74 engine.stop().await;
75 println!("# engine stopped after {:?}, total {:?}", stop_started.elapsed(), started.elapsed());
76}
crates/calling/examples/meet_now.rs added +192 −0
@@ -0,0 +1,192 @@
1 use std::path::PathBuf;
2 use std::time::{Duration, Instant};
3
4 use calling::meeting::fetch_live_meeting;
5 use calling::relay::ic3_scope;
6 use calling::signaling::{CHATSVC_REGION, fetch_self};
7 use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, EngineConfig, MeetingTarget};
8 use chatsvc::InstanceNames;
9 use serde_json::{Value, json};
10 use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};
11
12 const CREATE_URL: &str =
13 "https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create";
14 const SUBJECT: &str = "Native client test";
15 const CONNECT_LIMIT: Duration = Duration::from_secs(45);
16 const LIVE_STATE_LIMIT: Duration = Duration::from_secs(30);
17 const WAIT_FILE_LIMIT: Duration = Duration::from_secs(300);
18 const END_LIMIT: Duration = Duration::from_secs(20);
19 const GONE_LIMIT: Duration = Duration::from_secs(90);
20 const POLL: Duration = Duration::from_secs(2);
21
22 struct Arguments {
23 hold: Duration,
24 thread_out: Option<PathBuf>,
25 wait_file: Option<PathBuf>,
26 }
27
28 fn arguments() -> Arguments {
29 let mut parsed = Arguments {
30 hold: Duration::from_secs(10),
31 thread_out: None,
32 wait_file: None,
33 };
34 let mut input = std::env::args().skip(1);
35 while let Some(flag) = input.next() {
36 match flag.as_str() {
37 "--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),
38 "--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
39 "--wait-file" => parsed.wait_file = input.next().map(PathBuf::from),
40 _ => {}
41 }
42 }
43 parsed
44 }
45
46 fn as_object(value: &Value) -> Option<Value> {
47 match value {
48 Value::String(text) => serde_json::from_str(text).ok(),
49 Value::Object(_) => Some(value.clone()),
50 _ => None,
51 }
52 }
53
54 async fn tenant_and_organizer(session: &Session, thread_id: &str) -> (Option<String>, Option<String>) {
55 let url = format!(
56 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
57 thread_id.replace(':', "%3A").replace('@', "%40")
58 );
59 let Ok(response) = session.send(Request::get(url), &ic3_scope()).await else {
60 return (None, None);
61 };
62 let properties = &response.body["properties"];
63 let meeting = as_object(&properties["meeting"]);
64 let text = |value: &Value| value.as_str().filter(|text| !text.is_empty()).map(str::to_owned);
65 let tenant = meeting
66 .as_ref()
67 .and_then(|meeting| text(&meeting["tenantId"]))
68 .or_else(|| text(&properties["addedByTenantId"]));
69 (tenant, meeting.as_ref().and_then(|meeting| text(&meeting["organizerId"])))
70 }
71
72 #[tokio::main]
73 async fn main() {
74 let arguments = arguments();
75 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
76 let session = Session::connect(&endpoint).await.expect("browser");
77 let poll_session = Session::connect(&endpoint).await.expect("browser");
78 let me = fetch_self(&session).await.expect("own identity");
79
80 let started = Instant::now();
81 let reused = std::env::args().skip_while(|argument| argument != "--thread").nth(1);
82 let thread_id = match reused {
83 Some(thread_id) => thread_id,
84 None => {
85 let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});
86 let created = session
87 .request(Method::Post, CREATE_URL, &Scope::new(SPACES, "user_impersonation"), Some(body))
88 .await
89 .expect("create meeting");
90 println!("# create MeetNow: HTTP {} after {:?}", created.status, started.elapsed());
91 created.body.pointer("/value/groupContext/threadId").and_then(Value::as_str).expect("meeting thread").to_owned()
92 }
93 };
94 if let Some(path) = &arguments.thread_out {
95 std::fs::write(path, &thread_id).expect("thread file");
96 }
97
98 let (tenant_id, organizer_id) = tenant_and_organizer(&session, &thread_id).await;
99 let organizer_id = organizer_id.unwrap_or_else(|| me.object_id.clone());
100 println!(
101 "# thread: tenant found {}, organizer is me {}",
102 tenant_id.is_some(),
103 organizer_id.eq_ignore_ascii_case(&me.object_id)
104 );
105 let target = MeetingTarget {
106 thread_id: thread_id.clone(),
107 tenant_id: tenant_id.expect("tenant id"),
108 organizer_id,
109 meeting_data: None,
110 };
111
112 let config = EngineConfig {
113 ringable: false,
114 trace: true,
115 instance: InstanceNames {
116 global: "__meetNowTrouter".into(),
117 binding: "__meetNowRealtime".into(),
118 endpoint_storage_key: "__meetNowEpid".into(),
119 },
120 ..EngineConfig::default()
121 };
122 let (engine, _events) = CallEngine::start(session.clone(), poll_session, config).await.expect("engine");
123 println!("# engine ready after {:?}", started.elapsed());
124 let join_started = Instant::now();
125 let mut handle = engine.start_call(CallSpec::Meeting(target));
126
127 let mut connected_after = None;
128 let mut roster_count = None;
129 let mut inbound = 0;
130 let mut ended = None;
131 let mut live_detected_after = None;
132 let mut released_at = None;
133 let mut end_sent_at = None;
134 let deadline = Instant::now() + CONNECT_LIMIT + LIVE_STATE_LIMIT + WAIT_FILE_LIMIT + arguments.hold + END_LIMIT;
135 let mut tick = tokio::time::interval(POLL);
136 while ended.is_none() && Instant::now() < deadline {
137 tokio::select! {
138 update = handle.updates.recv() => match update {
139 Some(CallUpdate::State(CallState::Connected { .. })) => {
140 connected_after.get_or_insert(join_started.elapsed());
141 }
142 Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),
143 Some(CallUpdate::Roster(entries)) => roster_count = Some(entries.len()),
144 Some(CallUpdate::Stats { inbound_packets, .. }) => inbound = inbound_packets,
145 Some(_) => {}
146 None => break,
147 },
148 _ = tick.tick() => {
149 if connected_after.is_none() {
150 if join_started.elapsed() > CONNECT_LIMIT {
151 println!("# not connected within {CONNECT_LIMIT:?}, hanging up");
152 let _ = handle.commands.send(CallCommand::Hangup);
153 }
154 continue;
155 }
156 if live_detected_after.is_none() && end_sent_at.is_none() {
157 if let Ok(Some(meeting)) = fetch_live_meeting(&session, &thread_id).await {
158 live_detected_after = Some(join_started.elapsed());
159 println!("# live state detected, join target complete: {}", meeting.target().is_some());
160 released_at = Some(Instant::now() + arguments.hold);
161 } else if join_started.elapsed() > CONNECT_LIMIT + LIVE_STATE_LIMIT {
162 println!("# live state not seen within {LIVE_STATE_LIMIT:?}");
163 released_at = Some(Instant::now());
164 }
165 }
166 let waiting_for_file = arguments.wait_file.as_ref().is_some_and(|path| !path.exists())
167 && join_started.elapsed() < CONNECT_LIMIT + WAIT_FILE_LIMIT;
168 if end_sent_at.is_none() && released_at.is_some_and(|at| Instant::now() >= at) && !waiting_for_file {
169 println!("# roster before end: {roster_count:?} participant(s), inbound packets {inbound}");
170 let _ = handle.commands.send(CallCommand::EndMeeting);
171 end_sent_at = Some(Instant::now());
172 }
173 }
174 }
175 }
176 println!(
177 "# connected after {connected_after:?}, live state after {live_detected_after:?}, roster {roster_count:?}, inbound packets {inbound}"
178 );
179 println!("# ended: {ended:?}");
180 let gone_started = Instant::now();
181 let mut gone_after = None;
182 while gone_started.elapsed() < GONE_LIMIT {
183 if matches!(fetch_live_meeting(&session, &thread_id).await, Ok(None)) {
184 gone_after = Some(gone_started.elapsed());
185 break;
186 }
187 tokio::time::sleep(POLL).await;
188 }
189 println!("# live state gone after end: {gone_after:?}");
190 engine.stop().await;
191 println!("# engine stopped, total {:?}", started.elapsed());
192 }
@@ -0,0 +1,192 @@
1use std::path::PathBuf;
2use std::time::{Duration, Instant};
3
4use calling::meeting::fetch_live_meeting;
5use calling::relay::ic3_scope;
6use calling::signaling::{CHATSVC_REGION, fetch_self};
7use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, EngineConfig, MeetingTarget};
8use chatsvc::InstanceNames;
9use serde_json::{Value, json};
10use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};
11
12const CREATE_URL: &str =
13 "https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create";
14const SUBJECT: &str = "Native client test";
15const CONNECT_LIMIT: Duration = Duration::from_secs(45);
16const LIVE_STATE_LIMIT: Duration = Duration::from_secs(30);
17const WAIT_FILE_LIMIT: Duration = Duration::from_secs(300);
18const END_LIMIT: Duration = Duration::from_secs(20);
19const GONE_LIMIT: Duration = Duration::from_secs(90);
20const POLL: Duration = Duration::from_secs(2);
21
22struct Arguments {
23 hold: Duration,
24 thread_out: Option<PathBuf>,
25 wait_file: Option<PathBuf>,
26}
27
28fn arguments() -> Arguments {
29 let mut parsed = Arguments {
30 hold: Duration::from_secs(10),
31 thread_out: None,
32 wait_file: None,
33 };
34 let mut input = std::env::args().skip(1);
35 while let Some(flag) = input.next() {
36 match flag.as_str() {
37 "--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),
38 "--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
39 "--wait-file" => parsed.wait_file = input.next().map(PathBuf::from),
40 _ => {}
41 }
42 }
43 parsed
44}
45
46fn as_object(value: &Value) -> Option<Value> {
47 match value {
48 Value::String(text) => serde_json::from_str(text).ok(),
49 Value::Object(_) => Some(value.clone()),
50 _ => None,
51 }
52}
53
54async fn tenant_and_organizer(session: &Session, thread_id: &str) -> (Option<String>, Option<String>) {
55 let url = format!(
56 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
57 thread_id.replace(':', "%3A").replace('@', "%40")
58 );
59 let Ok(response) = session.send(Request::get(url), &ic3_scope()).await else {
60 return (None, None);
61 };
62 let properties = &response.body["properties"];
63 let meeting = as_object(&properties["meeting"]);
64 let text = |value: &Value| value.as_str().filter(|text| !text.is_empty()).map(str::to_owned);
65 let tenant = meeting
66 .as_ref()
67 .and_then(|meeting| text(&meeting["tenantId"]))
68 .or_else(|| text(&properties["addedByTenantId"]));
69 (tenant, meeting.as_ref().and_then(|meeting| text(&meeting["organizerId"])))
70}
71
72#[tokio::main]
73async fn main() {
74 let arguments = arguments();
75 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
76 let session = Session::connect(&endpoint).await.expect("browser");
77 let poll_session = Session::connect(&endpoint).await.expect("browser");
78 let me = fetch_self(&session).await.expect("own identity");
79
80 let started = Instant::now();
81 let reused = std::env::args().skip_while(|argument| argument != "--thread").nth(1);
82 let thread_id = match reused {
83 Some(thread_id) => thread_id,
84 None => {
85 let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});
86 let created = session
87 .request(Method::Post, CREATE_URL, &Scope::new(SPACES, "user_impersonation"), Some(body))
88 .await
89 .expect("create meeting");
90 println!("# create MeetNow: HTTP {} after {:?}", created.status, started.elapsed());
91 created.body.pointer("/value/groupContext/threadId").and_then(Value::as_str).expect("meeting thread").to_owned()
92 }
93 };
94 if let Some(path) = &arguments.thread_out {
95 std::fs::write(path, &thread_id).expect("thread file");
96 }
97
98 let (tenant_id, organizer_id) = tenant_and_organizer(&session, &thread_id).await;
99 let organizer_id = organizer_id.unwrap_or_else(|| me.object_id.clone());
100 println!(
101 "# thread: tenant found {}, organizer is me {}",
102 tenant_id.is_some(),
103 organizer_id.eq_ignore_ascii_case(&me.object_id)
104 );
105 let target = MeetingTarget {
106 thread_id: thread_id.clone(),
107 tenant_id: tenant_id.expect("tenant id"),
108 organizer_id,
109 meeting_data: None,
110 };
111
112 let config = EngineConfig {
113 ringable: false,
114 trace: true,
115 instance: InstanceNames {
116 global: "__meetNowTrouter".into(),
117 binding: "__meetNowRealtime".into(),
118 endpoint_storage_key: "__meetNowEpid".into(),
119 },
120 ..EngineConfig::default()
121 };
122 let (engine, _events) = CallEngine::start(session.clone(), poll_session, config).await.expect("engine");
123 println!("# engine ready after {:?}", started.elapsed());
124 let join_started = Instant::now();
125 let mut handle = engine.start_call(CallSpec::Meeting(target));
126
127 let mut connected_after = None;
128 let mut roster_count = None;
129 let mut inbound = 0;
130 let mut ended = None;
131 let mut live_detected_after = None;
132 let mut released_at = None;
133 let mut end_sent_at = None;
134 let deadline = Instant::now() + CONNECT_LIMIT + LIVE_STATE_LIMIT + WAIT_FILE_LIMIT + arguments.hold + END_LIMIT;
135 let mut tick = tokio::time::interval(POLL);
136 while ended.is_none() && Instant::now() < deadline {
137 tokio::select! {
138 update = handle.updates.recv() => match update {
139 Some(CallUpdate::State(CallState::Connected { .. })) => {
140 connected_after.get_or_insert(join_started.elapsed());
141 }
142 Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),
143 Some(CallUpdate::Roster(entries)) => roster_count = Some(entries.len()),
144 Some(CallUpdate::Stats { inbound_packets, .. }) => inbound = inbound_packets,
145 Some(_) => {}
146 None => break,
147 },
148 _ = tick.tick() => {
149 if connected_after.is_none() {
150 if join_started.elapsed() > CONNECT_LIMIT {
151 println!("# not connected within {CONNECT_LIMIT:?}, hanging up");
152 let _ = handle.commands.send(CallCommand::Hangup);
153 }
154 continue;
155 }
156 if live_detected_after.is_none() && end_sent_at.is_none() {
157 if let Ok(Some(meeting)) = fetch_live_meeting(&session, &thread_id).await {
158 live_detected_after = Some(join_started.elapsed());
159 println!("# live state detected, join target complete: {}", meeting.target().is_some());
160 released_at = Some(Instant::now() + arguments.hold);
161 } else if join_started.elapsed() > CONNECT_LIMIT + LIVE_STATE_LIMIT {
162 println!("# live state not seen within {LIVE_STATE_LIMIT:?}");
163 released_at = Some(Instant::now());
164 }
165 }
166 let waiting_for_file = arguments.wait_file.as_ref().is_some_and(|path| !path.exists())
167 && join_started.elapsed() < CONNECT_LIMIT + WAIT_FILE_LIMIT;
168 if end_sent_at.is_none() && released_at.is_some_and(|at| Instant::now() >= at) && !waiting_for_file {
169 println!("# roster before end: {roster_count:?} participant(s), inbound packets {inbound}");
170 let _ = handle.commands.send(CallCommand::EndMeeting);
171 end_sent_at = Some(Instant::now());
172 }
173 }
174 }
175 }
176 println!(
177 "# connected after {connected_after:?}, live state after {live_detected_after:?}, roster {roster_count:?}, inbound packets {inbound}"
178 );
179 println!("# ended: {ended:?}");
180 let gone_started = Instant::now();
181 let mut gone_after = None;
182 while gone_started.elapsed() < GONE_LIMIT {
183 if matches!(fetch_live_meeting(&session, &thread_id).await, Ok(None)) {
184 gone_after = Some(gone_started.elapsed());
185 break;
186 }
187 tokio::time::sleep(POLL).await;
188 }
189 println!("# live state gone after end: {gone_after:?}");
190 engine.stop().await;
191 println!("# engine stopped, total {:?}", started.elapsed());
192}
crates/calling/src/call.rs +660 −235
@@ -1,9 +1,10 @@
1 use std::collections::BTreeMap;
1 2 use std::path::PathBuf;
2 3 use std::sync::Arc;
3 4 use std::sync::atomic::{AtomicBool, Ordering};
4 5 use std::time::Duration;
5 6
6 use chatsvc::{CallbackReplier, InstanceNames, Realtime, RealtimeConfig, RealtimeEvent, TrouterCallback};
7 use chatsvc::TrouterCallback;
7 8 use futures_util::StreamExt;
8 9 use libwebrtc::audio_stream::native::NativeAudioStream;
9 10 use libwebrtc::prelude::*;
@@ -17,30 +18,40 @@ use tokio::time::{Instant, interval, sleep_until, timeout};
17 18
18 19 use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};
19 20 use crate::audio_io::{AudioMode, AudioSetup};
20 use crate::control::{CallCommand, CallControl, CallUpdate};
21 use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
21 22 use crate::devices::{self, DeviceChoice};
23 use crate::end::EndKind;
24 use crate::engine::{CallEngine, EngineConfig, Inner};
22 25 use crate::error::{Error, Result};
23 26 use crate::mute::{MuteCommand, MuteEffect};
24 use crate::relay::{DEFAULT_RELAY_HOST, fetch_relay_grant};
25 use crate::sdp::{OfferPlan, SignaledOffer, to_browser_answer, to_teams_offer};
27 use crate::push::CallNotification;
28 use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
29 use crate::renegotiation::{MediaAction, MediaNegotiator};
30 use crate::roster::Roster;
31 use crate::sdp::{OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, to_browser_answer, to_teams_answer, to_teams_offer};
26 32 use crate::signaling::{
27 Conversation, EchoInvitation, Participant, Signaling, TenantRouting, fetch_self, find_echo_bot_thread,
33 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling,
34 TenantRouting, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
28 35 };
29 36 use crate::state::{CallSignal, CallState};
30 37 use crate::timeline::{Timeline, TimelineEntry};
31 use crate::trouter_events::{CallEnd, CallEvent, CallbackLinks, acceptance_acknowledgement, classify, decode_body};
38 use crate::trouter_events::{
39 CallEnd, CallEvent, CallbackLinks, ProgressStatus, acceptance_acknowledgement, classify, decode_body,
40 };
32 41
33 const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
34 42 const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
35 43 const STATS_PERIOD: Duration = Duration::from_millis(200);
36 44 const TICKS_PER_SECOND: u32 = 5;
37 45 const RECONNECT_WINDOW: Duration = Duration::from_secs(30);
46 const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90);
38 47 const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365);
39 const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
40 pub const TRACE_ENV: &str = "CALLING_TRACE";
48 const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700;
49 const MIN_KEEP_ALIVE_SECONDS: u64 = 60;
50 const KEEP_ALIVE_FRACTION: f64 = 0.9;
51 const MIC_STREAM: &str = "microphone";
41 52
42 53 #[derive(Debug, Clone)]
43 pub struct TestCallOptions {
54 pub struct CallOptions {
44 55 pub hold_after_connected: Option<Duration>,
45 56 pub hard_limit: Option<Duration>,
46 57 pub reconnect_window: Duration,
@@ -56,9 +67,9 @@ pub struct TestCallOptions {
56 67 pub trace: bool,
57 68 }
58 69
59 impl Default for TestCallOptions {
70 impl Default for CallOptions {
60 71 fn default() -> Self {
61 TestCallOptions {
72 CallOptions {
62 73 hold_after_connected: None,
63 74 hard_limit: None,
64 75 reconnect_window: RECONNECT_WINDOW,
@@ -71,7 +82,7 @@ impl Default for TestCallOptions {
71 82 record_remote: false,
72 83 wav_path: None,
73 84 sdp_dump_dir: None,
74 trace: std::env::var_os(TRACE_ENV).is_some(),
85 trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(),
75 86 }
76 87 }
77 88 }
@@ -87,7 +98,7 @@ pub struct AudioSecond {
87 98 }
88 99
89 100 #[derive(Debug, Clone, Default)]
90 pub struct TestCallReport {
101 pub struct CallReport {
91 102 pub timeline: Vec<TimelineEntry>,
92 103 pub ice_connected_ms: Option<u128>,
93 104 pub peer_connected_ms: Option<u128>,
@@ -105,28 +116,57 @@ pub struct TestCallReport {
105 116 pub recorded_samples: usize,
106 117 }
107 118
108 pub fn calling_realtime_config() -> RealtimeConfig {
109 RealtimeConfig {
110 instance: InstanceNames {
111 global: "__callingTrouter".into(),
112 binding: "__callingRealtime".into(),
113 endpoint_storage_key: "__callingEpid".into(),
114 },
115 forward_callbacks: true,
116 ..RealtimeConfig::default()
119 #[derive(Debug, Clone)]
120 pub enum CallSpec {
121 Echo,
122 People { callees: Vec<Callee>, thread_id: String },
123 Meeting(MeetingTarget),
124 }
125
126 impl CallSpec {
127 fn target(&self) -> InviteTarget {
128 match self {
129 CallSpec::Echo => InviteTarget::Echo,
130 CallSpec::People { callees, thread_id } => InviteTarget::People {
131 callees: callees.clone(),
132 thread_id: thread_id.clone(),
133 },
134 CallSpec::Meeting(meeting) => InviteTarget::Meeting(meeting.clone()),
135 }
136 }
137
138 fn is_meeting(&self) -> bool {
139 matches!(self, CallSpec::Meeting(_))
140 }
141
142 fn is_people(&self) -> bool {
143 matches!(self, CallSpec::People { .. })
117 144 }
118 145 }
119 146
147 pub(crate) struct IncomingCall {
148 pub notification: CallNotification,
149 pub attached: Attached,
150 pub links: CallbackLinks,
151 pub participant: Participant,
152 pub callbacks: mpsc::UnboundedReceiver<TrouterCallback>,
153 }
154
155 pub(crate) enum Plan {
156 Outgoing(CallSpec),
157 Incoming(Box<IncomingCall>),
158 }
159
160 pub fn keep_alive_period(seconds: Option<u64>) -> Duration {
161 let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS);
162 Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)
163 }
164
120 165 fn random_u32() -> u32 {
121 166 let bytes = uuid::Uuid::new_v4().into_bytes();
122 167 u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff
123 168 }
124 169
125 fn callback_base(trouter_uri: &str) -> String {
126 let trimmed = trouter_uri.strip_suffix(PRESENCE_SUFFIX).unwrap_or(trouter_uri).trim_end_matches('/');
127 format!("{trimmed}/")
128 }
129
130 170 #[derive(Default)]
131 171 struct Recording {
132 172 samples: Vec<i16>,
@@ -140,6 +180,26 @@ enum PeerEvent {
140 180 Track(RtcAudioTrack),
141 181 }
142 182
183 struct PeerSession {
184 peer: PeerConnection,
185 events: mpsc::UnboundedReceiver<PeerEvent>,
186 }
187
188 struct OfferedMedia {
189 browser_offer: String,
190 signaled: SignaledOffer,
191 }
192
193 struct NextPeer {
194 session: PeerSession,
195 offered: Option<OfferedMedia>,
196 }
197
198 struct AnsweredMedia {
199 remote: RemoteOffer,
200 answer_sdp: String,
201 }
202
143 203 #[derive(Clone)]
144 204 struct RemoteCall {
145 205 signaling: Arc<Signaling>,
@@ -149,14 +209,15 @@ struct RemoteCall {
149 209
150 210 #[derive(Default)]
151 211 struct Live {
152 realtime: Option<Realtime>,
153 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
154 replier: Option<CallbackReplier>,
155 peer: Option<PeerConnection>,
212 peers: Vec<PeerConnection>,
156 213 audio: Option<AudioSetup>,
157 214 remote: Option<RemoteCall>,
158 215 broker: Option<JoinHandle<()>>,
159 216 broker_running: Arc<AtomicBool>,
217 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
218 route_id: Option<String>,
219 skip_leave: bool,
220 cancel_leave: bool,
160 221 }
161 222
162 223 fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool {
@@ -169,147 +230,109 @@ fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) ->
169 230 true
170 231 }
171 232
233 /// Places the Echo test call on its own non-ringable Trouter instance; the app uses a shared engine instead.
172 234 pub async fn run_test_call(
173 235 session: &Session,
174 236 poll_session: &Session,
175 options: TestCallOptions,
176 mut control: CallControl,
177 ) -> Result<TestCallReport> {
178 let timeline = Timeline::new(options.trace);
179 let mut report = TestCallReport::default();
180 let mut state = CallState::Idle;
181 advance(&mut state, CallSignal::Dial, &control);
182 let mut live = Live::default();
183 let recording = Arc::new(Mutex::new(Recording::default()));
184 let setup = CallSetup {
185 session,
186 poll_session,
187 options: &options,
188 timeline: &timeline,
189 recording: &recording,
237 options: CallOptions,
238 control: CallControl,
239 ) -> Result<CallReport> {
240 let config = EngineConfig {
241 ringable: false,
242 routing: options.routing.clone(),
243 relay_host: options.relay_host.clone(),
244 trace: options.trace,
245 instance: chatsvc::InstanceNames {
246 global: "__testCallTrouter".into(),
247 binding: "__testCallRealtime".into(),
248 endpoint_storage_key: "__testCallEpid".into(),
249 },
190 250 };
191 let outcome = drive(&mut live, &setup, &mut control, &mut state, &mut report).await;
192 let failure = match outcome {
193 Ok(()) => None,
194 Err(Error::Cancelled) => {
195 advance(&mut state, CallSignal::LocalLeave, &control);
196 None
251 let (engine, _events) = CallEngine::start(session.clone(), poll_session.clone(), config).await?;
252 let report = engine.run(Plan::Outgoing(CallSpec::Echo), options, control).await;
253 engine.stop().await;
254 report
255 }
256
257 impl CallEngine {
258 pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
259 let inner = self.inner.as_ref();
260 let _one_call_at_a_time = inner.gate.lock().await;
261 let timeline = Timeline::new(options.trace);
262 let mut report = CallReport::default();
263 let mut state = CallState::Idle;
264 advance(&mut state, CallSignal::Dial, &control);
265 let mut live = Live::default();
266 let recording = Arc::new(Mutex::new(Recording::default()));
267 let outcome = drive(
268 inner,
269 &options,
270 &timeline,
271 &recording,
272 plan,
273 &mut live,
274 &mut control,
275 &mut state,
276 &mut report,
277 )
278 .await;
279 let failure = match outcome {
280 Ok(()) => None,
281 Err(Error::Cancelled) => {
282 advance(&mut state, CallSignal::LocalLeave, &control);
283 None
284 }
285 Err(error) => {
286 advance(&mut state, CallSignal::Error(error.to_string()), &control);
287 Some(error)
288 }
289 };
290 let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled });
291 tear_down(live, inner, &timeline, &mut report, cancelled).await;
292 let recording = recording.lock().await;
293 report.recorded_samples = recording.samples.len();
294 if let Some(path) = &options.wav_path {
295 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
197 296 }
198 Err(error) => {
199 advance(&mut state, CallSignal::Error(error.to_string()), &control);
200 Some(error)
297 report.timeline = timeline.entries();
298 match failure {
299 Some(error) => Err(error),
300 None => Ok(report),
201 301 }
202 };
203 tear_down(live, &timeline, &mut report).await;
204 let recording = recording.lock().await;
205 report.recorded_samples = recording.samples.len();
206 if let Some(path) = &options.wav_path {
207 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
208 }
209 report.timeline = timeline.entries();
210 match failure {
211 Some(error) => Err(error),
212 None => Ok(report),
213 302 }
214 303 }
215 304
216 struct CallSetup<'a> {
217 session: &'a Session,
218 poll_session: &'a Session,
219 options: &'a TestCallOptions,
220 timeline: &'a Timeline,
221 recording: &'a Arc<Mutex<Recording>>,
222 }
223
224 async fn drive(
225 live: &mut Live,
226 setup: &CallSetup<'_>,
227 control: &mut CallControl,
228 state: &mut CallState,
229 report: &mut TestCallReport,
230 ) -> Result<()> {
231 let CallSetup {
232 session,
233 poll_session,
234 options,
235 timeline,
236 recording,
237 } = *setup;
238 let mut realtime = Realtime::start_with(session, calling_realtime_config()).await?;
239 live.callbacks = Some(
240 realtime
241 .take_callbacks()
242 .ok_or_else(|| Error::Callback("callback stream already taken".into()))?,
243 );
244 live.replier = Some(realtime.callback_replier());
245 let endpoint = control
246 .until_hangup(timeout(ENDPOINT_WAIT, async {
247 while let Some(event) = realtime.recv().await {
248 if let RealtimeEvent::Endpoint(endpoint) = event {
249 return Some(endpoint);
250 }
251 }
252 None
253 }))
254 .await;
255 live.realtime = Some(realtime);
256 let endpoint = endpoint?
257 .ok()
258 .flatten()
259 .ok_or_else(|| Error::Callback("Trouter socket never announced its endpoint".into()))?;
260 timeline.record("Trouter connected", "callback socket ready");
261
262 let identity = control.until_hangup(fetch_self(session)).await??;
263 let thread_id = control
264 .until_hangup(find_echo_bot_thread(session, &identity.object_id))
265 .await??;
266 timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" });
267 let grant = control.until_hangup(fetch_relay_grant(session)).await??;
268 timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds));
269
270 let factory = devices::shared_factory();
271 let mut input = options.input.clone();
272 let mut output = options.output.clone();
273 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
274 control.send(CallUpdate::ListenOnly(audio.listen_only));
275 control.send(CallUpdate::Devices(devices::list_devices(&factory)));
276 control.send(CallUpdate::Selected {
277 input: input.clone(),
278 output: output.clone(),
279 });
280 let track = audio.track.clone();
281 live.audio = Some(audio);
282
305 fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str) -> Result<PeerSession> {
283 306 let mut configuration = RtcConfiguration::default();
284 configuration.ice_servers = vec![grant.ice_server(&options.relay_host)];
307 configuration.ice_servers = vec![grant.ice_server(relay_host)];
285 308 let peer = factory
286 309 .create_peer_connection(configuration)
287 310 .map_err(|error| Error::Webrtc(error.to_string()))?;
288 live.peer = Some(peer.clone());
289 let (peer_events, mut peer_receiver) = mpsc::unbounded_channel();
290 let ice_sender = peer_events.clone();
311 let (sender, events) = mpsc::unbounded_channel();
312 let ice_sender = sender.clone();
291 313 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
292 314 let _ = ice_sender.send(PeerEvent::Ice(state));
293 315 })));
294 let connection_sender = peer_events.clone();
316 let connection_sender = sender.clone();
295 317 peer.on_connection_state_change(Some(Box::new(move |state| {
296 318 let _ = connection_sender.send(PeerEvent::Connection(state));
297 319 })));
298 let track_sender = peer_events;
299 320 peer.on_track(Some(Box::new(move |event| {
300 321 if let MediaStreamTrack::Audio(track) = event.track {
301 let _ = track_sender.send(PeerEvent::Track(track));
322 let _ = sender.send(PeerEvent::Track(track));
302 323 }
303 324 })));
325 Ok(PeerSession { peer, events })
326 }
304 327
328 async fn create_offer(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<OfferedMedia> {
305 329 let transceiver_init = RtpTransceiverInit {
306 330 direction: RtpTransceiverDirection::SendRecv,
307 stream_ids: vec!["microphone".into()],
331 stream_ids: vec![MIC_STREAM.into()],
308 332 send_encodings: Vec::new(),
309 333 };
310 peer.add_transceiver(MediaStreamTrack::Audio(track), transceiver_init)
334 peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init)
311 335 .map_err(|error| Error::Webrtc(error.to_string()))?;
312
313 336 let offer = peer
314 337 .create_offer(OfferOptions {
315 338 offer_to_receive_audio: true,
@@ -323,40 +346,212 @@ async fn drive(
323 346 let browser_offer = offer.to_string();
324 347 let mut numbers = random_u32;
325 348 let signaled = to_teams_offer(&browser_offer, &OfferPlan::default(), &mut numbers)?;
326 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", signaled.lines.len()));
327 dump_sdp(options, "1-browser-offer.sdp", &browser_offer);
328 dump_sdp(options, "2-teams-offer.sdp", &signaled.sdp);
329
330 let participant = Participant {
331 mri: format!("8:orgid:{}", identity.object_id),
332 display_name: identity.display_name.clone(),
333 endpoint_id: endpoint.endpoint_id.clone(),
334 participant_id: uuid::Uuid::new_v4().to_string(),
335 language_id: "en-gb".into(),
349 Ok(OfferedMedia { browser_offer, signaled })
350 }
351
352 /// Video lines of a Teams offer are stopped so the answer rejects them; audio is all this client does.
353 async fn answer_offer(
354 peer: &PeerConnection,
355 track: Option<&RtcAudioTrack>,
356 teams_offer: &str,
357 ) -> Result<AnsweredMedia> {
358 let remote = from_teams_offer(teams_offer)?;
359 let description =
360 SessionDescription::parse(&remote.browser_sdp, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;
361 peer.set_remote_description(description)
362 .await
363 .map_err(|error| Error::Webrtc(error.to_string()))?;
364 for transceiver in peer.transceivers() {
365 if matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_))) {
366 let _ = transceiver.stop();
367 }
368 }
369 if let Some(track) = track {
370 peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
371 .map_err(|error| Error::Webrtc(error.to_string()))?;
372 }
373 let answer = peer
374 .create_answer(AnswerOptions::default())
375 .await
376 .map_err(|error| Error::Webrtc(error.to_string()))?;
377 peer.set_local_description(answer.clone())
378 .await
379 .map_err(|error| Error::Webrtc(error.to_string()))?;
380 let mut numbers = random_u32;
381 let signaled = to_teams_answer(&answer.to_string(), &remote, &mut numbers)?;
382 Ok(AnsweredMedia {
383 remote,
384 answer_sdp: signaled.sdp,
385 })
386 }
387
388 fn new_media_leg_id() -> String {
389 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
390 }
391
392 async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> {
393 match next {
394 Some(next) => next.session.events.recv().await,
395 None => std::future::pending().await,
396 }
397 }
398
399 #[allow(clippy::too_many_arguments)]
400 async fn drive(
401 inner: &Inner,
402 options: &CallOptions,
403 timeline: &Timeline,
404 recording: &Arc<Mutex<Recording>>,
405 plan: Plan,
406 live: &mut Live,
407 control: &mut CallControl,
408 state: &mut CallState,
409 report: &mut CallReport,
410 ) -> Result<()> {
411 let own_mri = format!("8:orgid:{}", inner.identity.object_id);
412 control.send(CallUpdate::OwnIdentity { mri: own_mri.clone() });
413 let (spec, incoming) = match plan {
414 Plan::Outgoing(spec) => (Some(spec), None),
415 Plan::Incoming(incoming) => (None, Some(*incoming)),
336 416 };
337 let links = CallbackLinks::new(&callback_base(&endpoint.trouter_uri), &uuid::Uuid::new_v4().to_string());
338 let media_leg_id = uuid::Uuid::new_v4().simple().to_string().to_uppercase();
339 let signaling = Arc::new(Signaling::new(
340 session.clone(),
341 poll_session.clone(),
342 options.routing.clone(),
343 timeline.clone(),
344 ));
417 let (links, participant, mut callbacks, incoming_media) = match incoming {
418 Some(IncomingCall {
419 notification,
420 attached,
421 links,
422 participant,
423 callbacks,
424 }) => (links, participant, callbacks, Some((notification, attached))),
425 None => {
426 let links = inner.callback_links();
427 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
428 let callbacks = inner.register_route(links.call_id());
429 (links, participant, callbacks, None)
430 }
431 };
432 live.route_id = Some(links.call_id().to_owned());
433 timeline.record("Trouter connected", "callback socket ready");
434
435 let thread_id = if matches!(spec, Some(CallSpec::Echo)) {
436 let thread_id = control
437 .until_hangup(find_echo_bot_thread(&inner.session, &inner.identity.object_id))
438 .await??;
439 timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" });
440 thread_id
441 } else {
442 None
443 };
444 let grant = control.until_hangup(fetch_relay_grant(&inner.session)).await??;
445 timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds));
446
447 let factory = devices::shared_factory();
448 let mut input = options.input.clone();
449 let mut output = options.output.clone();
450 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
451 control.send(CallUpdate::ListenOnly(audio.listen_only));
452 control.send(CallUpdate::Devices(devices::list_devices(&factory)));
453 control.send(CallUpdate::Selected {
454 input: input.clone(),
455 output: output.clone(),
456 });
457 let track = audio.track.clone();
458 live.audio = Some(audio);
459
460 let mut current = open_peer(&factory, &grant, &options.relay_host)?;
461 live.peers.push(current.peer.clone());
462
463 let signaling = Arc::new(inner.signaling(timeline.clone()));
464 let media_leg_id = new_media_leg_id();
345 465 let call_started = Instant::now();
346 let conversation = control
347 .until_hangup(signaling.create_conversation(&EchoInvitation {
348 from: &participant,
349 offer_sdp: &signaled.sdp,
350 media_leg_id: &media_leg_id,
351 callbacks: &links,
352 }))
353 .await??;
354 let remote = RemoteCall {
355 signaling: signaling.clone(),
356 conversation: conversation.clone(),
357 participant: participant.clone(),
466 let mut offered: Option<OfferedMedia> = None;
467 let mut negotiator = MediaNegotiator::default();
468 let mut remote_set = false;
469 let mut keep_alive_link: Option<String> = None;
470 let mut keep_alive_seconds: Option<u64> = None;
471 let mut keep_alive_at: Option<Instant> = None;
472 let mut outgoing_deadline: Option<Instant> = None;
473 let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
474 let is_echo = matches!(spec, Some(CallSpec::Echo));
475
476 let conversation = match (spec, incoming_media) {
477 (Some(spec), None) => {
478 let media = create_offer(&current.peer, &track).await?;
479 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
480 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
481 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
482 let target = spec.target();
483 let invitation = Invitation {
484 from: &participant,
485 offer_sdp: &media.signaled.sdp,
486 media_leg_id: &media_leg_id,
487 callbacks: &links,
488 target: &target,
489 };
490 let conversation = match &target {
491 InviteTarget::Meeting(meeting) => {
492 let subscribed = control
493 .until_hangup(signaling.subscribe_meeting(&participant, &links, meeting))
494 .await??;
495 signaling.join_meeting(&subscribed, &invitation).await?
496 }
497 _ => signaling.create_conversation(&invitation).await?,
498 };
499 if spec.is_people() {
500 control.send(CallUpdate::Progress(Progress::Calling));
501 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
502 }
503 offered = Some(media);
504 live.remote = Some(RemoteCall {
505 signaling: signaling.clone(),
506 conversation: conversation.clone(),
507 participant: participant.clone(),
508 });
509 conversation
510 }
511 (None, Some((_notification, attached))) => {
512 let teams_offer = attached
513 .offer_sdp
514 .clone()
515 .ok_or_else(|| Error::Signaling("attach answer without an offer".into()))?;
516 let conversation = attached
517 .conversation
518 .clone()
519 .ok_or_else(|| Error::Signaling("attach answer without a conversation".into()))?;
520 live.remote = Some(RemoteCall {
521 signaling: signaling.clone(),
522 conversation: conversation.clone(),
523 participant: participant.clone(),
524 });
525 let answered = answer_offer(&current.peer, Some(&track), &teams_offer).await?;
526 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
527 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
528 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
529 let acceptance_url = attached
530 .links
531 .get("acceptance")
532 .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
533 let modalities = vec!["Audio".to_owned()];
534 signaling
535 .accept(
536 acceptance_url,
537 &Answer {
538 from: &participant,
539 answer_sdp: &answered.answer_sdp,
540 media_leg_id: &media_leg_id,
541 callbacks: &links,
542 modalities: &modalities,
543 },
544 )
545 .await?;
546 negotiator.answered_incoming(attached.from_mixer);
547 remote_set = true;
548 keep_alive_link = attached.links.get("callLeg").cloned();
549 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
550 conversation
551 }
552 _ => return Err(Error::Callback("call plan without an offer or an invitation".into())),
358 553 };
359 live.remote = Some(remote.clone());
554 let remote = live.remote.clone().expect("remote call set above");
360 555 live.broker_running.store(true, Ordering::SeqCst);
361 556 live.broker = Some(tokio::spawn(poll_broker(
362 557 signaling.clone(),
@@ -364,21 +559,28 @@ async fn drive(
364 559 live.broker_running.clone(),
365 560 )));
366 561
367 let mut muted = false;
368 if let Err(error) = signaling.update_endpoint_state(&conversation, &participant, muted).await {
562 let initial = MuteEffect::initial(is_meeting);
563 let mut muted = initial.muted;
564 live.audio.as_ref().expect("audio set above").track.set_enabled(initial.track_enabled);
565 if muted {
566 control.send(CallUpdate::Muted(true));
567 }
568 if let Err(error) = signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted).await {
369 569 timeline.record("updateEndpointState failed", error.to_string());
370 570 }
371 571
372 let callbacks = live.callbacks.as_mut().expect("callbacks set above");
373 let replier = live.replier.clone().expect("replier set above");
572 let replier = inner.replier.clone();
374 573 let mut stats_tick = interval(STATS_PERIOD);
375 574 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
376 575 let mut leave_at = hard_deadline;
377 576 let mut reconnect_deadline: Option<Instant> = None;
378 let mut remote_set = false;
577 let mut next: Option<NextPeer> = None;
578 let mut roster = Roster::default();
579 let mut lobby = false;
379 580 let mut previous_packets = 0u64;
380 581 let mut ticks = 0u32;
381 582 let mut second = 0u32;
583 let echo_thread = thread_id;
382 584 loop {
383 585 tokio::select! {
384 586 Some(callback) = callbacks.recv() => {
@@ -386,34 +588,135 @@ async fn drive(
386 588 match handle_callback(&callback, timeline) {
387 589 Ok(CallEvent::Acceptance(acceptance)) => {
388 590 replier.reply(request_id, 200, acceptance_acknowledgement(&links).to_string());
389 dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp);
390 if let Ok(answer) = to_browser_answer(&acceptance.sdp, &signaled, &browser_offer) {
391 dump_sdp(options, "4-browser-answer.sdp", &answer);
591 match negotiator.on_acceptance(acceptance.from_mixer) {
592 MediaAction::ApplyAnswer => {
593 let Some(media) = offered.as_ref() else { continue };
594 dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp);
595 if let Ok(answer) = to_browser_answer(&acceptance.sdp, &media.signaled, &media.browser_offer) {
596 dump_sdp(options, "4-browser-answer.sdp", &answer);
597 }
598 apply_answer(&current.peer, &acceptance.sdp, &media.signaled, &media.browser_offer)
599 .await
600 .inspect_err(|error| timeline.record("answer rejected", error.to_string()))?;
601 remote_set = true;
602 outgoing_deadline = None;
603 let directions: Vec<String> = current
604 .peer
605 .transceivers()
606 .iter()
607 .map(|transceiver| format!("{:?}", transceiver.current_direction()))
608 .collect();
609 timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(",")));
610 if acceptance.in_lobby() {
611 lobby = true;
612 control.send(CallUpdate::Lobby(true));
613 }
614 keep_alive_link = acceptance.links.get("callLeg").cloned();
615 keep_alive_seconds = acceptance.keep_alive_seconds;
616 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
617 let remote = remote.clone();
618 let links = links.clone();
619 let thread_id = echo_thread.clone();
620 tokio::spawn(async move {
621 if is_echo {
622 let _ = remote.signaling.add_echo_bot(&remote.conversation, &remote.participant, thread_id.as_deref(), &links).await;
623 }
624 let _ = remote.signaling.update_endpoint_metadata(&remote.conversation, &remote.participant).await;
625 });
626 }
627 MediaAction::Escalate => {
628 match start_escalation(&factory, &grant, options, &track, &remote, &links, &media_leg_id, &acceptance.links).await {
629 Ok(pending) => {
630 timeline.record("escalation", "new peer connection, new offer sent");
631 live.peers.push(pending.session.peer.clone());
632 next = Some(pending);
633 }
634 Err(error) => {
635 negotiator.escalation_failed();
636 timeline.record("escalation failed", error.to_string());
637 }
638 }
639 }
640 _ => {}
641 }
642 }
643 Ok(CallEvent::MediaAnswer(answer)) => {
644 replier.reply(request_id, 200, "");
645 if negotiator.on_media_answer() == MediaAction::ApplyOnNewPeer {
646 let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) {
647 Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await,
648 None => Err(Error::Webrtc("no pending peer connection for the answer".into())),
649 };
650 match applied {
651 Ok(()) => {
652 if let Some(url) = answer.links.get("mediaAcknowledgement") {
653 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
654 }
655 }
656 Err(error) => {
657 negotiator.escalation_failed();
658 next = None;
659 timeline.record("escalation answer rejected", error.to_string());
660 }
661 }
662 }
663 }
664 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
665 replier.reply(request_id, 200, "");
666 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
667 let result = match action {
668 MediaAction::AnswerOnNewPeer => {
669 match answer_on_new_peer(&factory, &grant, options, &track, &renegotiation.sdp).await {
670 Ok((session, answered)) => {
671 live.peers.push(session.peer.clone());
672 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
673 next = Some(NextPeer { session, offered: None });
674 sent
675 }
676 Err(error) => Err(error),
677 }
678 }
679 MediaAction::AnswerOnSamePeer => {
680 match answer_offer(&current.peer, None, &renegotiation.sdp).await {
681 Ok(answered) => send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await,
682 Err(error) => Err(error),
683 }
684 }
685 _ => Ok(()),
686 };
687 if let Err(error) = result {
688 timeline.record("renegotiation failed", error.to_string());
392 689 }
393 apply_answer(&peer, &acceptance.sdp, &signaled, &browser_offer).await.inspect_err(|error| {
394 timeline.record("answer rejected", error.to_string());
395 })?;
396 remote_set = true;
397 let directions: Vec<String> = peer
398 .transceivers()
399 .iter()
400 .map(|transceiver| format!("{:?}", transceiver.current_direction()))
401 .collect();
402 timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(",")));
403 let signaling = signaling.clone();
404 let conversation = conversation.clone();
405 let participant = participant.clone();
406 let links = links.clone();
407 let thread_id = thread_id.clone();
408 tokio::spawn(async move {
409 let _ = signaling.add_echo_bot(&conversation, &participant, thread_id.as_deref(), &links).await;
410 let _ = signaling.update_endpoint_metadata(&conversation, &participant).await;
411 });
690 }
691 Ok(CallEvent::RosterUpdate(body)) => {
692 replier.reply(request_id, 200, "");
693 if roster.apply(&body) {
694 let entries = roster.entries();
695 timeline.record("roster", format!("{} participant(s)", entries.len()));
696 control.send(CallUpdate::Roster(entries));
697 if let Some(in_lobby) = roster.is_in_lobby(&own_mri)
698 && in_lobby != lobby
699 {
700 lobby = in_lobby;
701 control.send(CallUpdate::Lobby(lobby));
702 }
703 }
704 }
705 Ok(CallEvent::Progress(status)) => {
706 replier.reply(request_id, 200, "");
707 if status == ProgressStatus::Ringing {
708 control.send(CallUpdate::Progress(Progress::Ringing));
709 }
710 }
711 Ok(CallEvent::Speakers(sources)) => {
712 replier.reply(request_id, 200, "");
713 control.send(CallUpdate::Speakers(roster.mris_for_sources(&sources)));
412 714 }
413 715 Ok(CallEvent::End(end)) => {
414 716 replier.reply(request_id, 200, "");
717 let kind = end.kind();
415 718 report.end = Some(end);
416 advance(state, CallSignal::RemoteEnd, control);
719 advance(state, CallSignal::RemoteEnd(kind), control);
417 720 break;
418 721 }
419 722 Ok(_) => replier.reply(request_id, 200, ""),
@@ -423,7 +726,7 @@ async fn drive(
423 726 }
424 727 }
425 728 }
426 Some(event) = peer_receiver.recv() => match event {
729 Some(event) = current.events.recv() => match event {
427 730 PeerEvent::Ice(ice_state) => {
428 731 timeline.record("ICE state", format!("{ice_state:?}"));
429 732 if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() {
@@ -456,13 +759,32 @@ async fn drive(
456 759 _ => {}
457 760 }
458 761 }
459 PeerEvent::Track(track) => {
762 PeerEvent::Track(remote_track) => {
460 763 timeline.record("remote audio track", "receiving");
461 764 if options.record_remote {
462 tokio::spawn(record_track(track, recording.clone(), options.tone_hz));
765 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
463 766 }
464 767 }
465 768 },
769 Some(event) = next_peer_event(&mut next) => match event {
770 PeerEvent::Connection(PeerConnectionState::Connected) => {
771 if let Some(pending) = next.take() {
772 timeline.record("escalation", "new peer connection connected, old one dropped");
773 let old = std::mem::replace(&mut current, pending.session);
774 old.peer.close();
775 offered = pending.offered;
776 remote_set = true;
777 }
778 }
779 PeerEvent::Connection(PeerConnectionState::Failed) => {
780 negotiator.escalation_failed();
781 if let Some(pending) = next.take() {
782 pending.session.peer.close();
783 }
784 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
785 }
786 _ => {}
787 },
466 788 command = control.recv() => match command {
467 789 Some(CallCommand::Mute(mute)) => {
468 790 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), &remote, control);
@@ -484,13 +806,26 @@ async fn drive(
484 806 Some(CallCommand::RefreshDevices) => {
485 807 control.send(CallUpdate::Devices(devices::list_devices(&factory)));
486 808 }
809 Some(CallCommand::EndMeeting) => {
810 if is_meeting {
811 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
812 Ok(()) => {
813 live.skip_leave = true;
814 report.left_cleanly = true;
815 }
816 Err(error) => timeline.record("end meeting failed", error.to_string()),
817 }
818 }
819 advance(state, CallSignal::LocalLeave, control);
820 break;
821 }
487 822 Some(CallCommand::Hangup) | None => {
488 823 advance(state, CallSignal::LocalLeave, control);
489 824 break;
490 825 }
491 826 },
492 827 _ = stats_tick.tick(), if remote_set => {
493 let snapshot = collect_stats(&peer).await;
828 let snapshot = collect_stats(&current.peer).await;
494 829 ticks += 1;
495 830 let local_level = if muted { 0.0 } else { snapshot.local_level as f32 };
496 831 control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
@@ -542,11 +877,80 @@ async fn drive(
542 877 advance(state, CallSignal::LocalLeave, control);
543 878 break;
544 879 }
880 _ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => {
881 timeline.record("no answer", "outgoing call timed out");
882 live.cancel_leave = true;
883 advance(state, CallSignal::RemoteEnd(EndKind::NoAnswer), control);
884 break;
885 }
886 _ = sleep_until(keep_alive_at.unwrap_or_else(far_future)), if keep_alive_at.is_some() => {
887 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
888 let remote = remote.clone();
889 let links = links.clone();
890 let call_leg = keep_alive_link.clone();
891 tokio::spawn(async move {
892 if let Some(url) = call_leg {
893 let _ = remote.signaling.keep_call_alive(&url).await;
894 }
895 let _ = remote.signaling.keep_conversation_alive(&remote.conversation, &remote.participant, &links).await;
896 });
897 }
545 898 }
546 899 }
900 live.callbacks = Some(callbacks);
547 901 Ok(())
548 902 }
549 903
904 #[allow(clippy::too_many_arguments)]
905 async fn start_escalation(
906 factory: &PeerConnectionFactory,
907 grant: &RelayGrant,
908 options: &CallOptions,
909 track: &RtcAudioTrack,
910 remote: &RemoteCall,
911 links: &CallbackLinks,
912 media_leg_id: &str,
913 acceptance_links: &BTreeMap<String, String>,
914 ) -> Result<NextPeer> {
915 let url = acceptance_links
916 .get("mediaRenegotiation")
917 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
918 let session = open_peer(factory, grant, &options.relay_host)?;
919 let media = create_offer(&session.peer, track).await?;
920 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id);
921 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
922 Ok(NextPeer {
923 session,
924 offered: Some(media),
925 })
926 }
927
928 async fn answer_on_new_peer(
929 factory: &PeerConnectionFactory,
930 grant: &RelayGrant,
931 options: &CallOptions,
932 track: &RtcAudioTrack,
933 teams_offer: &str,
934 ) -> Result<(PeerSession, AnsweredMedia)> {
935 let session = open_peer(factory, grant, &options.relay_host)?;
936 let answered = answer_offer(&session.peer, Some(track), teams_offer).await?;
937 Ok((session, answered))
938 }
939
940 async fn send_media_answer(
941 remote: &RemoteCall,
942 links: &CallbackLinks,
943 reply_links: &BTreeMap<String, String>,
944 answered: &AnsweredMedia,
945 media_leg_id: &str,
946 ) -> Result<()> {
947 let url = reply_links
948 .get("mediaAnswer")
949 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
950 let body = escalation_answer_body(&remote.participant, links, &answered.answer_sdp, media_leg_id);
951 remote.signaling.post_json("POST mediaAnswer", url, body).await
952 }
953
550 954 fn far_future() -> Instant {
551 955 Instant::now() + FAR_FUTURE
552 956 }
@@ -565,26 +969,29 @@ fn apply_mute(command: MuteCommand, currently_muted: bool, audio: &AudioSetup, r
565 969 effect.muted
566 970 }
567 971
568 async fn tear_down(mut live: Live, timeline: &Timeline, report: &mut TestCallReport) {
972 async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) {
569 973 if let Some(audio) = &live.audio {
570 974 audio.track.set_enabled(false);
571 975 }
572 976 live.broker_running.store(false, Ordering::SeqCst);
573 if let Some(remote) = &live.remote {
574 match remote.signaling.leave(&remote.conversation, &remote.participant).await {
977 if !live.skip_leave
978 && let Some(remote) = &live.remote
979 {
980 let reason = if cancelled { LeaveReason::Cancel } else { LeaveReason::Hangup };
981 match remote.signaling.leave(&remote.conversation, &remote.participant, reason).await {
575 982 Ok(()) => report.left_cleanly = true,
576 983 Err(error) => timeline.record("leave failed", error.to_string()),
577 984 }
578 985 }
579 986 if report.end.is_none()
580 && let (Some(callbacks), Some(replier)) = (live.callbacks.as_mut(), live.replier.as_ref())
987 && let Some(callbacks) = live.callbacks.as_mut()
581 988 && live.remote.is_some()
582 989 {
583 990 let waited = timeout(END_CALLBACK_WAIT, async {
584 991 while let Some(callback) = callbacks.recv().await {
585 992 let request_id = callback.request_id;
586 993 let event = handle_callback(&callback, timeline);
587 replier.reply(request_id, 200, "");
994 inner.replier.reply(request_id, 200, "");
588 995 if let Ok(CallEvent::End(end)) = event {
589 996 return Some(end);
590 997 }
@@ -594,7 +1001,7 @@ async fn tear_down(mut live: Live, timeline: &Timeline, report: &mut TestCallRep
594 1001 .await;
595 1002 report.end = waited.ok().flatten();
596 1003 }
597 if let Some(peer) = &live.peer {
1004 for peer in &live.peers {
598 1005 peer.close();
599 1006 }
600 1007 if let Some(audio) = live.audio.take() {
@@ -603,12 +1010,26 @@ async fn tear_down(mut live: Live, timeline: &Timeline, report: &mut TestCallRep
603 1010 if let Some(broker) = live.broker.take() {
604 1011 broker.abort();
605 1012 }
606 if let Some(realtime) = live.realtime.take() {
607 realtime.stop().await;
1013 if let Some(route_id) = &live.route_id {
1014 inner.unregister_route(route_id);
608 1015 }
609 timeline.record("closed", "peer closed, Trouter registration removed");
1016 timeline.record("closed", "peer closed, call route removed");
1017 }
1018
1019 fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
1020 let body = decode_body(callback)?;
1021 let (_, event) = classify(&callback.path, body)?;
1022 let detail = match &event {
1023 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
1024 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
1025 CallEvent::Progress(status) => format!("{status:?}"),
1026 _ => String::new(),
1027 };
1028 timeline.record(format!("Trouter {}", event.name()), detail);
1029 Ok(event)
610 1030 }
611 1031
1032
612 1033 async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
613 1034 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
614 1035 let description =
@@ -619,7 +1040,7 @@ async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &Sign
619 1040 }
620 1041
621 1042 /// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect.
622 fn dump_sdp(options: &TestCallOptions, name: &str, sdp: &str) {
1043 fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
623 1044 let Some(directory) = &options.sdp_dump_dir else {
624 1045 return;
625 1046 };
@@ -648,18 +1069,6 @@ fn mask_address(token: &str) -> String {
648 1069 }
649 1070 }
650 1071
651 fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
652 let body = decode_body(callback)?;
653 let (_, event) = classify(&callback.path, body)?;
654 let detail = match &event {
655 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
656 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
657 _ => String::new(),
658 };
659 timeline.record(format!("Trouter {}", event.name()), detail);
660 Ok(event)
661 }
662
663 1072 async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, tone_hz: f32) {
664 1073 let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1);
665 1074 while let Some(frame) = stream.next().await {
@@ -771,11 +1180,27 @@ mod tests {
771 1180 use super::*;
772 1181
773 1182 #[test]
774 fn callback_base_comes_from_the_presence_uri() {
775 assert_eq!(
776 callback_base("https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc//unifiedPresenceService"),
777 "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc/"
778 );
779 assert_eq!(callback_base("https://h/v4/f/abc/unifiedPresenceService"), "https://h/v4/f/abc/");
1183 fn keep_alive_fires_at_ninety_percent_of_the_interval() {
1184 assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430));
1185 assert_eq!(keep_alive_period(None), Duration::from_secs(2430));
1186 assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54));
1187 }
1188
1189 #[test]
1190 fn specs_map_to_invitation_targets() {
1191 assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
1192 let people = CallSpec::People {
1193 callees: vec![Callee { mri: "8:orgid:b".into(), display_name: "Bea".into() }],
1194 thread_id: "19:t@thread.v2".into(),
1195 };
1196 assert!(people.is_people() && !people.is_meeting());
1197 assert!(matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2"));
1198 let meeting = CallSpec::Meeting(MeetingTarget {
1199 thread_id: "19:meeting@thread.v2".into(),
1200 tenant_id: "t".into(),
1201 organizer_id: "o".into(),
1202 meeting_data: None,
1203 });
1204 assert!(meeting.is_meeting() && !meeting.is_people());
780 1205 }
781 1206 }
@@ -1,9 +1,10 @@
1use std::collections::BTreeMap;
1use std::path::PathBuf;
2use std::path::PathBuf;
2use std::sync::Arc;
3use std::sync::Arc;
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::atomic::{AtomicBool, Ordering};
4use std::time::Duration;
5use std::time::Duration;
5
6
6use chatsvc::{CallbackReplier, InstanceNames, Realtime, RealtimeConfig, RealtimeEvent, TrouterCallback};
7use chatsvc::TrouterCallback;
7use futures_util::StreamExt;
8use futures_util::StreamExt;
8use libwebrtc::audio_stream::native::NativeAudioStream;
9use libwebrtc::audio_stream::native::NativeAudioStream;
9use libwebrtc::prelude::*;
10use libwebrtc::prelude::*;
@@ -17,30 +18,40 @@ use tokio::time::{Instant, interval, sleep_until, timeout};
17
18
18use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};
19use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};
19use crate::audio_io::{AudioMode, AudioSetup};
20use crate::audio_io::{AudioMode, AudioSetup};
20use crate::control::{CallCommand, CallControl, CallUpdate};
21use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
21use crate::devices::{self, DeviceChoice};
22use crate::devices::{self, DeviceChoice};
23use crate::end::EndKind;
24use crate::engine::{CallEngine, EngineConfig, Inner};
22use crate::error::{Error, Result};
25use crate::error::{Error, Result};
23use crate::mute::{MuteCommand, MuteEffect};
26use crate::mute::{MuteCommand, MuteEffect};
24use crate::relay::{DEFAULT_RELAY_HOST, fetch_relay_grant};
27use crate::push::CallNotification;
25use crate::sdp::{OfferPlan, SignaledOffer, to_browser_answer, to_teams_offer};
28use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
29use crate::renegotiation::{MediaAction, MediaNegotiator};
30use crate::roster::Roster;
31use crate::sdp::{OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, to_browser_answer, to_teams_answer, to_teams_offer};
26use crate::signaling::{
32use crate::signaling::{
27 Conversation, EchoInvitation, Participant, Signaling, TenantRouting, fetch_self, find_echo_bot_thread,
33 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling,
34 TenantRouting, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
28};
35};
29use crate::state::{CallSignal, CallState};
36use crate::state::{CallSignal, CallState};
30use crate::timeline::{Timeline, TimelineEntry};
37use crate::timeline::{Timeline, TimelineEntry};
31use crate::trouter_events::{CallEnd, CallEvent, CallbackLinks, acceptance_acknowledgement, classify, decode_body};
38use crate::trouter_events::{
39 CallEnd, CallEvent, CallbackLinks, ProgressStatus, acceptance_acknowledgement, classify, decode_body,
40};
32
41
33const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
34const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
42const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
35const STATS_PERIOD: Duration = Duration::from_millis(200);
43const STATS_PERIOD: Duration = Duration::from_millis(200);
36const TICKS_PER_SECOND: u32 = 5;
44const TICKS_PER_SECOND: u32 = 5;
37const RECONNECT_WINDOW: Duration = Duration::from_secs(30);
45const RECONNECT_WINDOW: Duration = Duration::from_secs(30);
46const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90);
38const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365);
47const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365);
39const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
48const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700;
40pub const TRACE_ENV: &str = "CALLING_TRACE";
49const MIN_KEEP_ALIVE_SECONDS: u64 = 60;
50const KEEP_ALIVE_FRACTION: f64 = 0.9;
51const MIC_STREAM: &str = "microphone";
41
52
42#[derive(Debug, Clone)]
53#[derive(Debug, Clone)]
43pub struct TestCallOptions {
54pub struct CallOptions {
44 pub hold_after_connected: Option<Duration>,
55 pub hold_after_connected: Option<Duration>,
45 pub hard_limit: Option<Duration>,
56 pub hard_limit: Option<Duration>,
46 pub reconnect_window: Duration,
57 pub reconnect_window: Duration,
@@ -56,9 +67,9 @@ pub struct TestCallOptions {
56 pub trace: bool,
67 pub trace: bool,
57}
68}
58
69
59impl Default for TestCallOptions {
70impl Default for CallOptions {
60 fn default() -> Self {
71 fn default() -> Self {
61 TestCallOptions {
72 CallOptions {
62 hold_after_connected: None,
73 hold_after_connected: None,
63 hard_limit: None,
74 hard_limit: None,
64 reconnect_window: RECONNECT_WINDOW,
75 reconnect_window: RECONNECT_WINDOW,
@@ -71,7 +82,7 @@ impl Default for TestCallOptions {
71 record_remote: false,
82 record_remote: false,
72 wav_path: None,
83 wav_path: None,
73 sdp_dump_dir: None,
84 sdp_dump_dir: None,
74 trace: std::env::var_os(TRACE_ENV).is_some(),
85 trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(),
75 }
86 }
76 }
87 }
77}
88}
@@ -87,7 +98,7 @@ pub struct AudioSecond {
87}
98}
88
99
89#[derive(Debug, Clone, Default)]
100#[derive(Debug, Clone, Default)]
90pub struct TestCallReport {
101pub struct CallReport {
91 pub timeline: Vec<TimelineEntry>,
102 pub timeline: Vec<TimelineEntry>,
92 pub ice_connected_ms: Option<u128>,
103 pub ice_connected_ms: Option<u128>,
93 pub peer_connected_ms: Option<u128>,
104 pub peer_connected_ms: Option<u128>,
@@ -105,28 +116,57 @@ pub struct TestCallReport {
105 pub recorded_samples: usize,
116 pub recorded_samples: usize,
106}
117}
107
118
108pub fn calling_realtime_config() -> RealtimeConfig {
119#[derive(Debug, Clone)]
109 RealtimeConfig {
120pub enum CallSpec {
110 instance: InstanceNames {
121 Echo,
111 global: "__callingTrouter".into(),
122 People { callees: Vec<Callee>, thread_id: String },
112 binding: "__callingRealtime".into(),
123 Meeting(MeetingTarget),
113 endpoint_storage_key: "__callingEpid".into(),
124}
114 },
125
115 forward_callbacks: true,
126impl CallSpec {
116 ..RealtimeConfig::default()
127 fn target(&self) -> InviteTarget {
128 match self {
129 CallSpec::Echo => InviteTarget::Echo,
130 CallSpec::People { callees, thread_id } => InviteTarget::People {
131 callees: callees.clone(),
132 thread_id: thread_id.clone(),
133 },
134 CallSpec::Meeting(meeting) => InviteTarget::Meeting(meeting.clone()),
135 }
136 }
137
138 fn is_meeting(&self) -> bool {
139 matches!(self, CallSpec::Meeting(_))
140 }
141
142 fn is_people(&self) -> bool {
143 matches!(self, CallSpec::People { .. })
117 }
144 }
118}
145}
119
146
147pub(crate) struct IncomingCall {
148 pub notification: CallNotification,
149 pub attached: Attached,
150 pub links: CallbackLinks,
151 pub participant: Participant,
152 pub callbacks: mpsc::UnboundedReceiver<TrouterCallback>,
153}
154
155pub(crate) enum Plan {
156 Outgoing(CallSpec),
157 Incoming(Box<IncomingCall>),
158}
159
160pub fn keep_alive_period(seconds: Option<u64>) -> Duration {
161 let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS);
162 Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)
163}
164
120fn random_u32() -> u32 {
165fn random_u32() -> u32 {
121 let bytes = uuid::Uuid::new_v4().into_bytes();
166 let bytes = uuid::Uuid::new_v4().into_bytes();
122 u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff
167 u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff
123}
168}
124
169
125fn callback_base(trouter_uri: &str) -> String {
126 let trimmed = trouter_uri.strip_suffix(PRESENCE_SUFFIX).unwrap_or(trouter_uri).trim_end_matches('/');
127 format!("{trimmed}/")
128}
129
130#[derive(Default)]
170#[derive(Default)]
131struct Recording {
171struct Recording {
132 samples: Vec<i16>,
172 samples: Vec<i16>,
@@ -140,6 +180,26 @@ enum PeerEvent {
140 Track(RtcAudioTrack),
180 Track(RtcAudioTrack),
141}
181}
142
182
183struct PeerSession {
184 peer: PeerConnection,
185 events: mpsc::UnboundedReceiver<PeerEvent>,
186}
187
188struct OfferedMedia {
189 browser_offer: String,
190 signaled: SignaledOffer,
191}
192
193struct NextPeer {
194 session: PeerSession,
195 offered: Option<OfferedMedia>,
196}
197
198struct AnsweredMedia {
199 remote: RemoteOffer,
200 answer_sdp: String,
201}
202
143#[derive(Clone)]
203#[derive(Clone)]
144struct RemoteCall {
204struct RemoteCall {
145 signaling: Arc<Signaling>,
205 signaling: Arc<Signaling>,
@@ -149,14 +209,15 @@ struct RemoteCall {
149
209
150#[derive(Default)]
210#[derive(Default)]
151struct Live {
211struct Live {
152 realtime: Option<Realtime>,
212 peers: Vec<PeerConnection>,
153 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
154 replier: Option<CallbackReplier>,
155 peer: Option<PeerConnection>,
156 audio: Option<AudioSetup>,
213 audio: Option<AudioSetup>,
157 remote: Option<RemoteCall>,
214 remote: Option<RemoteCall>,
158 broker: Option<JoinHandle<()>>,
215 broker: Option<JoinHandle<()>>,
159 broker_running: Arc<AtomicBool>,
216 broker_running: Arc<AtomicBool>,
217 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
218 route_id: Option<String>,
219 skip_leave: bool,
220 cancel_leave: bool,
160}
221}
161
222
162fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool {
223fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool {
@@ -169,147 +230,109 @@ fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) ->
169 true
230 true
170}
231}
171
232
233/// Places the Echo test call on its own non-ringable Trouter instance; the app uses a shared engine instead.
172pub async fn run_test_call(
234pub async fn run_test_call(
173 session: &Session,
235 session: &Session,
174 poll_session: &Session,
236 poll_session: &Session,
175 options: TestCallOptions,
237 options: CallOptions,
176 mut control: CallControl,
238 control: CallControl,
177) -> Result<TestCallReport> {
239) -> Result<CallReport> {
178 let timeline = Timeline::new(options.trace);
240 let config = EngineConfig {
179 let mut report = TestCallReport::default();
241 ringable: false,
180 let mut state = CallState::Idle;
242 routing: options.routing.clone(),
181 advance(&mut state, CallSignal::Dial, &control);
243 relay_host: options.relay_host.clone(),
182 let mut live = Live::default();
244 trace: options.trace,
183 let recording = Arc::new(Mutex::new(Recording::default()));
245 instance: chatsvc::InstanceNames {
184 let setup = CallSetup {
246 global: "__testCallTrouter".into(),
185 session,
247 binding: "__testCallRealtime".into(),
186 poll_session,
248 endpoint_storage_key: "__testCallEpid".into(),
187 options: &options,
249 },
188 timeline: &timeline,
189 recording: &recording,
190 };
250 };
191 let outcome = drive(&mut live, &setup, &mut control, &mut state, &mut report).await;
251 let (engine, _events) = CallEngine::start(session.clone(), poll_session.clone(), config).await?;
192 let failure = match outcome {
252 let report = engine.run(Plan::Outgoing(CallSpec::Echo), options, control).await;
193 Ok(()) => None,
253 engine.stop().await;
194 Err(Error::Cancelled) => {
254 report
195 advance(&mut state, CallSignal::LocalLeave, &control);
255}
196 None
256
257impl CallEngine {
258 pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
259 let inner = self.inner.as_ref();
260 let _one_call_at_a_time = inner.gate.lock().await;
261 let timeline = Timeline::new(options.trace);
262 let mut report = CallReport::default();
263 let mut state = CallState::Idle;
264 advance(&mut state, CallSignal::Dial, &control);
265 let mut live = Live::default();
266 let recording = Arc::new(Mutex::new(Recording::default()));
267 let outcome = drive(
268 inner,
269 &options,
270 &timeline,
271 &recording,
272 plan,
273 &mut live,
274 &mut control,
275 &mut state,
276 &mut report,
277 )
278 .await;
279 let failure = match outcome {
280 Ok(()) => None,
281 Err(Error::Cancelled) => {
282 advance(&mut state, CallSignal::LocalLeave, &control);
283 None
284 }
285 Err(error) => {
286 advance(&mut state, CallSignal::Error(error.to_string()), &control);
287 Some(error)
288 }
289 };
290 let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled });
291 tear_down(live, inner, &timeline, &mut report, cancelled).await;
292 let recording = recording.lock().await;
293 report.recorded_samples = recording.samples.len();
294 if let Some(path) = &options.wav_path {
295 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
197 }
296 }
198 Err(error) => {
297 report.timeline = timeline.entries();
199 advance(&mut state, CallSignal::Error(error.to_string()), &control);
298 match failure {
200 Some(error)
299 Some(error) => Err(error),
300 None => Ok(report),
201 }
301 }
202 };
203 tear_down(live, &timeline, &mut report).await;
204 let recording = recording.lock().await;
205 report.recorded_samples = recording.samples.len();
206 if let Some(path) = &options.wav_path {
207 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
208 }
209 report.timeline = timeline.entries();
210 match failure {
211 Some(error) => Err(error),
212 None => Ok(report),
213 }
302 }
214}
303}
215
304
216struct CallSetup<'a> {
305fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str) -> Result<PeerSession> {
217 session: &'a Session,
218 poll_session: &'a Session,
219 options: &'a TestCallOptions,
220 timeline: &'a Timeline,
221 recording: &'a Arc<Mutex<Recording>>,
222}
223
224async fn drive(
225 live: &mut Live,
226 setup: &CallSetup<'_>,
227 control: &mut CallControl,
228 state: &mut CallState,
229 report: &mut TestCallReport,
230) -> Result<()> {
231 let CallSetup {
232 session,
233 poll_session,
234 options,
235 timeline,
236 recording,
237 } = *setup;
238 let mut realtime = Realtime::start_with(session, calling_realtime_config()).await?;
239 live.callbacks = Some(
240 realtime
241 .take_callbacks()
242 .ok_or_else(|| Error::Callback("callback stream already taken".into()))?,
243 );
244 live.replier = Some(realtime.callback_replier());
245 let endpoint = control
246 .until_hangup(timeout(ENDPOINT_WAIT, async {
247 while let Some(event) = realtime.recv().await {
248 if let RealtimeEvent::Endpoint(endpoint) = event {
249 return Some(endpoint);
250 }
251 }
252 None
253 }))
254 .await;
255 live.realtime = Some(realtime);
256 let endpoint = endpoint?
257 .ok()
258 .flatten()
259 .ok_or_else(|| Error::Callback("Trouter socket never announced its endpoint".into()))?;
260 timeline.record("Trouter connected", "callback socket ready");
261
262 let identity = control.until_hangup(fetch_self(session)).await??;
263 let thread_id = control
264 .until_hangup(find_echo_bot_thread(session, &identity.object_id))
265 .await??;
266 timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" });
267 let grant = control.until_hangup(fetch_relay_grant(session)).await??;
268 timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds));
269
270 let factory = devices::shared_factory();
271 let mut input = options.input.clone();
272 let mut output = options.output.clone();
273 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
274 control.send(CallUpdate::ListenOnly(audio.listen_only));
275 control.send(CallUpdate::Devices(devices::list_devices(&factory)));
276 control.send(CallUpdate::Selected {
277 input: input.clone(),
278 output: output.clone(),
279 });
280 let track = audio.track.clone();
281 live.audio = Some(audio);
282
283 let mut configuration = RtcConfiguration::default();
306 let mut configuration = RtcConfiguration::default();
284 configuration.ice_servers = vec![grant.ice_server(&options.relay_host)];
307 configuration.ice_servers = vec![grant.ice_server(relay_host)];
285 let peer = factory
308 let peer = factory
286 .create_peer_connection(configuration)
309 .create_peer_connection(configuration)
287 .map_err(|error| Error::Webrtc(error.to_string()))?;
310 .map_err(|error| Error::Webrtc(error.to_string()))?;
288 live.peer = Some(peer.clone());
311 let (sender, events) = mpsc::unbounded_channel();
289 let (peer_events, mut peer_receiver) = mpsc::unbounded_channel();
312 let ice_sender = sender.clone();
290 let ice_sender = peer_events.clone();
291 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
313 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
292 let _ = ice_sender.send(PeerEvent::Ice(state));
314 let _ = ice_sender.send(PeerEvent::Ice(state));
293 })));
315 })));
294 let connection_sender = peer_events.clone();
316 let connection_sender = sender.clone();
295 peer.on_connection_state_change(Some(Box::new(move |state| {
317 peer.on_connection_state_change(Some(Box::new(move |state| {
296 let _ = connection_sender.send(PeerEvent::Connection(state));
318 let _ = connection_sender.send(PeerEvent::Connection(state));
297 })));
319 })));
298 let track_sender = peer_events;
299 peer.on_track(Some(Box::new(move |event| {
320 peer.on_track(Some(Box::new(move |event| {
300 if let MediaStreamTrack::Audio(track) = event.track {
321 if let MediaStreamTrack::Audio(track) = event.track {
301 let _ = track_sender.send(PeerEvent::Track(track));
322 let _ = sender.send(PeerEvent::Track(track));
302 }
323 }
303 })));
324 })));
325 Ok(PeerSession { peer, events })
326}
304
327
328async fn create_offer(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<OfferedMedia> {
305 let transceiver_init = RtpTransceiverInit {
329 let transceiver_init = RtpTransceiverInit {
306 direction: RtpTransceiverDirection::SendRecv,
330 direction: RtpTransceiverDirection::SendRecv,
307 stream_ids: vec!["microphone".into()],
331 stream_ids: vec![MIC_STREAM.into()],
308 send_encodings: Vec::new(),
332 send_encodings: Vec::new(),
309 };
333 };
310 peer.add_transceiver(MediaStreamTrack::Audio(track), transceiver_init)
334 peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init)
311 .map_err(|error| Error::Webrtc(error.to_string()))?;
335 .map_err(|error| Error::Webrtc(error.to_string()))?;
312
313 let offer = peer
336 let offer = peer
314 .create_offer(OfferOptions {
337 .create_offer(OfferOptions {
315 offer_to_receive_audio: true,
338 offer_to_receive_audio: true,
@@ -323,40 +346,212 @@ async fn drive(
323 let browser_offer = offer.to_string();
346 let browser_offer = offer.to_string();
324 let mut numbers = random_u32;
347 let mut numbers = random_u32;
325 let signaled = to_teams_offer(&browser_offer, &OfferPlan::default(), &mut numbers)?;
348 let signaled = to_teams_offer(&browser_offer, &OfferPlan::default(), &mut numbers)?;
326 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", signaled.lines.len()));
349 Ok(OfferedMedia { browser_offer, signaled })
327 dump_sdp(options, "1-browser-offer.sdp", &browser_offer);
350}
328 dump_sdp(options, "2-teams-offer.sdp", &signaled.sdp);
351
329
352/// Video lines of a Teams offer are stopped so the answer rejects them; audio is all this client does.
330 let participant = Participant {
353async fn answer_offer(
331 mri: format!("8:orgid:{}", identity.object_id),
354 peer: &PeerConnection,
332 display_name: identity.display_name.clone(),
355 track: Option<&RtcAudioTrack>,
333 endpoint_id: endpoint.endpoint_id.clone(),
356 teams_offer: &str,
334 participant_id: uuid::Uuid::new_v4().to_string(),
357) -> Result<AnsweredMedia> {
335 language_id: "en-gb".into(),
358 let remote = from_teams_offer(teams_offer)?;
359 let description =
360 SessionDescription::parse(&remote.browser_sdp, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;
361 peer.set_remote_description(description)
362 .await
363 .map_err(|error| Error::Webrtc(error.to_string()))?;
364 for transceiver in peer.transceivers() {
365 if matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_))) {
366 let _ = transceiver.stop();
367 }
368 }
369 if let Some(track) = track {
370 peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
371 .map_err(|error| Error::Webrtc(error.to_string()))?;
372 }
373 let answer = peer
374 .create_answer(AnswerOptions::default())
375 .await
376 .map_err(|error| Error::Webrtc(error.to_string()))?;
377 peer.set_local_description(answer.clone())
378 .await
379 .map_err(|error| Error::Webrtc(error.to_string()))?;
380 let mut numbers = random_u32;
381 let signaled = to_teams_answer(&answer.to_string(), &remote, &mut numbers)?;
382 Ok(AnsweredMedia {
383 remote,
384 answer_sdp: signaled.sdp,
385 })
386}
387
388fn new_media_leg_id() -> String {
389 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
390}
391
392async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> {
393 match next {
394 Some(next) => next.session.events.recv().await,
395 None => std::future::pending().await,
396 }
397}
398
399#[allow(clippy::too_many_arguments)]
400async fn drive(
401 inner: &Inner,
402 options: &CallOptions,
403 timeline: &Timeline,
404 recording: &Arc<Mutex<Recording>>,
405 plan: Plan,
406 live: &mut Live,
407 control: &mut CallControl,
408 state: &mut CallState,
409 report: &mut CallReport,
410) -> Result<()> {
411 let own_mri = format!("8:orgid:{}", inner.identity.object_id);
412 control.send(CallUpdate::OwnIdentity { mri: own_mri.clone() });
413 let (spec, incoming) = match plan {
414 Plan::Outgoing(spec) => (Some(spec), None),
415 Plan::Incoming(incoming) => (None, Some(*incoming)),
336 };
416 };
337 let links = CallbackLinks::new(&callback_base(&endpoint.trouter_uri), &uuid::Uuid::new_v4().to_string());
417 let (links, participant, mut callbacks, incoming_media) = match incoming {
338 let media_leg_id = uuid::Uuid::new_v4().simple().to_string().to_uppercase();
418 Some(IncomingCall {
339 let signaling = Arc::new(Signaling::new(
419 notification,
340 session.clone(),
420 attached,
341 poll_session.clone(),
421 links,
342 options.routing.clone(),
422 participant,
343 timeline.clone(),
423 callbacks,
344 ));
424 }) => (links, participant, callbacks, Some((notification, attached))),
425 None => {
426 let links = inner.callback_links();
427 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
428 let callbacks = inner.register_route(links.call_id());
429 (links, participant, callbacks, None)
430 }
431 };
432 live.route_id = Some(links.call_id().to_owned());
433 timeline.record("Trouter connected", "callback socket ready");
434
435 let thread_id = if matches!(spec, Some(CallSpec::Echo)) {
436 let thread_id = control
437 .until_hangup(find_echo_bot_thread(&inner.session, &inner.identity.object_id))
438 .await??;
439 timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" });
440 thread_id
441 } else {
442 None
443 };
444 let grant = control.until_hangup(fetch_relay_grant(&inner.session)).await??;
445 timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds));
446
447 let factory = devices::shared_factory();
448 let mut input = options.input.clone();
449 let mut output = options.output.clone();
450 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
451 control.send(CallUpdate::ListenOnly(audio.listen_only));
452 control.send(CallUpdate::Devices(devices::list_devices(&factory)));
453 control.send(CallUpdate::Selected {
454 input: input.clone(),
455 output: output.clone(),
456 });
457 let track = audio.track.clone();
458 live.audio = Some(audio);
459
460 let mut current = open_peer(&factory, &grant, &options.relay_host)?;
461 live.peers.push(current.peer.clone());
462
463 let signaling = Arc::new(inner.signaling(timeline.clone()));
464 let media_leg_id = new_media_leg_id();
345 let call_started = Instant::now();
465 let call_started = Instant::now();
346 let conversation = control
466 let mut offered: Option<OfferedMedia> = None;
347 .until_hangup(signaling.create_conversation(&EchoInvitation {
467 let mut negotiator = MediaNegotiator::default();
348 from: &participant,
468 let mut remote_set = false;
349 offer_sdp: &signaled.sdp,
469 let mut keep_alive_link: Option<String> = None;
350 media_leg_id: &media_leg_id,
470 let mut keep_alive_seconds: Option<u64> = None;
351 callbacks: &links,
471 let mut keep_alive_at: Option<Instant> = None;
352 }))
472 let mut outgoing_deadline: Option<Instant> = None;
353 .await??;
473 let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
354 let remote = RemoteCall {
474 let is_echo = matches!(spec, Some(CallSpec::Echo));
355 signaling: signaling.clone(),
475
356 conversation: conversation.clone(),
476 let conversation = match (spec, incoming_media) {
357 participant: participant.clone(),
477 (Some(spec), None) => {
478 let media = create_offer(&current.peer, &track).await?;
479 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
480 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
481 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
482 let target = spec.target();
483 let invitation = Invitation {
484 from: &participant,
485 offer_sdp: &media.signaled.sdp,
486 media_leg_id: &media_leg_id,
487 callbacks: &links,
488 target: &target,
489 };
490 let conversation = match &target {
491 InviteTarget::Meeting(meeting) => {
492 let subscribed = control
493 .until_hangup(signaling.subscribe_meeting(&participant, &links, meeting))
494 .await??;
495 signaling.join_meeting(&subscribed, &invitation).await?
496 }
497 _ => signaling.create_conversation(&invitation).await?,
498 };
499 if spec.is_people() {
500 control.send(CallUpdate::Progress(Progress::Calling));
501 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
502 }
503 offered = Some(media);
504 live.remote = Some(RemoteCall {
505 signaling: signaling.clone(),
506 conversation: conversation.clone(),
507 participant: participant.clone(),
508 });
509 conversation
510 }
511 (None, Some((_notification, attached))) => {
512 let teams_offer = attached
513 .offer_sdp
514 .clone()
515 .ok_or_else(|| Error::Signaling("attach answer without an offer".into()))?;
516 let conversation = attached
517 .conversation
518 .clone()
519 .ok_or_else(|| Error::Signaling("attach answer without a conversation".into()))?;
520 live.remote = Some(RemoteCall {
521 signaling: signaling.clone(),
522 conversation: conversation.clone(),
523 participant: participant.clone(),
524 });
525 let answered = answer_offer(&current.peer, Some(&track), &teams_offer).await?;
526 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
527 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
528 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
529 let acceptance_url = attached
530 .links
531 .get("acceptance")
532 .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
533 let modalities = vec!["Audio".to_owned()];
534 signaling
535 .accept(
536 acceptance_url,
537 &Answer {
538 from: &participant,
539 answer_sdp: &answered.answer_sdp,
540 media_leg_id: &media_leg_id,
541 callbacks: &links,
542 modalities: &modalities,
543 },
544 )
545 .await?;
546 negotiator.answered_incoming(attached.from_mixer);
547 remote_set = true;
548 keep_alive_link = attached.links.get("callLeg").cloned();
549 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
550 conversation
551 }
552 _ => return Err(Error::Callback("call plan without an offer or an invitation".into())),
358 };
553 };
359 live.remote = Some(remote.clone());
554 let remote = live.remote.clone().expect("remote call set above");
360 live.broker_running.store(true, Ordering::SeqCst);
555 live.broker_running.store(true, Ordering::SeqCst);
361 live.broker = Some(tokio::spawn(poll_broker(
556 live.broker = Some(tokio::spawn(poll_broker(
362 signaling.clone(),
557 signaling.clone(),
@@ -364,21 +559,28 @@ async fn drive(
364 live.broker_running.clone(),
559 live.broker_running.clone(),
365 )));
560 )));
366
561
367 let mut muted = false;
562 let initial = MuteEffect::initial(is_meeting);
368 if let Err(error) = signaling.update_endpoint_state(&conversation, &participant, muted).await {
563 let mut muted = initial.muted;
564 live.audio.as_ref().expect("audio set above").track.set_enabled(initial.track_enabled);
565 if muted {
566 control.send(CallUpdate::Muted(true));
567 }
568 if let Err(error) = signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted).await {
369 timeline.record("updateEndpointState failed", error.to_string());
569 timeline.record("updateEndpointState failed", error.to_string());
370 }
570 }
371
571
372 let callbacks = live.callbacks.as_mut().expect("callbacks set above");
572 let replier = inner.replier.clone();
373 let replier = live.replier.clone().expect("replier set above");
374 let mut stats_tick = interval(STATS_PERIOD);
573 let mut stats_tick = interval(STATS_PERIOD);
375 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
574 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
376 let mut leave_at = hard_deadline;
575 let mut leave_at = hard_deadline;
377 let mut reconnect_deadline: Option<Instant> = None;
576 let mut reconnect_deadline: Option<Instant> = None;
378 let mut remote_set = false;
577 let mut next: Option<NextPeer> = None;
578 let mut roster = Roster::default();
579 let mut lobby = false;
379 let mut previous_packets = 0u64;
580 let mut previous_packets = 0u64;
380 let mut ticks = 0u32;
581 let mut ticks = 0u32;
381 let mut second = 0u32;
582 let mut second = 0u32;
583 let echo_thread = thread_id;
382 loop {
584 loop {
383 tokio::select! {
585 tokio::select! {
384 Some(callback) = callbacks.recv() => {
586 Some(callback) = callbacks.recv() => {
@@ -386,34 +588,135 @@ async fn drive(
386 match handle_callback(&callback, timeline) {
588 match handle_callback(&callback, timeline) {
387 Ok(CallEvent::Acceptance(acceptance)) => {
589 Ok(CallEvent::Acceptance(acceptance)) => {
388 replier.reply(request_id, 200, acceptance_acknowledgement(&links).to_string());
590 replier.reply(request_id, 200, acceptance_acknowledgement(&links).to_string());
389 dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp);
591 match negotiator.on_acceptance(acceptance.from_mixer) {
390 if let Ok(answer) = to_browser_answer(&acceptance.sdp, &signaled, &browser_offer) {
592 MediaAction::ApplyAnswer => {
391 dump_sdp(options, "4-browser-answer.sdp", &answer);
593 let Some(media) = offered.as_ref() else { continue };
594 dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp);
595 if let Ok(answer) = to_browser_answer(&acceptance.sdp, &media.signaled, &media.browser_offer) {
596 dump_sdp(options, "4-browser-answer.sdp", &answer);
597 }
598 apply_answer(&current.peer, &acceptance.sdp, &media.signaled, &media.browser_offer)
599 .await
600 .inspect_err(|error| timeline.record("answer rejected", error.to_string()))?;
601 remote_set = true;
602 outgoing_deadline = None;
603 let directions: Vec<String> = current
604 .peer
605 .transceivers()
606 .iter()
607 .map(|transceiver| format!("{:?}", transceiver.current_direction()))
608 .collect();
609 timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(",")));
610 if acceptance.in_lobby() {
611 lobby = true;
612 control.send(CallUpdate::Lobby(true));
613 }
614 keep_alive_link = acceptance.links.get("callLeg").cloned();
615 keep_alive_seconds = acceptance.keep_alive_seconds;
616 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
617 let remote = remote.clone();
618 let links = links.clone();
619 let thread_id = echo_thread.clone();
620 tokio::spawn(async move {
621 if is_echo {
622 let _ = remote.signaling.add_echo_bot(&remote.conversation, &remote.participant, thread_id.as_deref(), &links).await;
623 }
624 let _ = remote.signaling.update_endpoint_metadata(&remote.conversation, &remote.participant).await;
625 });
626 }
627 MediaAction::Escalate => {
628 match start_escalation(&factory, &grant, options, &track, &remote, &links, &media_leg_id, &acceptance.links).await {
629 Ok(pending) => {
630 timeline.record("escalation", "new peer connection, new offer sent");
631 live.peers.push(pending.session.peer.clone());
632 next = Some(pending);
633 }
634 Err(error) => {
635 negotiator.escalation_failed();
636 timeline.record("escalation failed", error.to_string());
637 }
638 }
639 }
640 _ => {}
641 }
642 }
643 Ok(CallEvent::MediaAnswer(answer)) => {
644 replier.reply(request_id, 200, "");
645 if negotiator.on_media_answer() == MediaAction::ApplyOnNewPeer {
646 let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) {
647 Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await,
648 None => Err(Error::Webrtc("no pending peer connection for the answer".into())),
649 };
650 match applied {
651 Ok(()) => {
652 if let Some(url) = answer.links.get("mediaAcknowledgement") {
653 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
654 }
655 }
656 Err(error) => {
657 negotiator.escalation_failed();
658 next = None;
659 timeline.record("escalation answer rejected", error.to_string());
660 }
661 }
662 }
663 }
664 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
665 replier.reply(request_id, 200, "");
666 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
667 let result = match action {
668 MediaAction::AnswerOnNewPeer => {
669 match answer_on_new_peer(&factory, &grant, options, &track, &renegotiation.sdp).await {
670 Ok((session, answered)) => {
671 live.peers.push(session.peer.clone());
672 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
673 next = Some(NextPeer { session, offered: None });
674 sent
675 }
676 Err(error) => Err(error),
677 }
678 }
679 MediaAction::AnswerOnSamePeer => {
680 match answer_offer(&current.peer, None, &renegotiation.sdp).await {
681 Ok(answered) => send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await,
682 Err(error) => Err(error),
683 }
684 }
685 _ => Ok(()),
686 };
687 if let Err(error) = result {
688 timeline.record("renegotiation failed", error.to_string());
392 }
689 }
393 apply_answer(&peer, &acceptance.sdp, &signaled, &browser_offer).await.inspect_err(|error| {
690 }
394 timeline.record("answer rejected", error.to_string());
691 Ok(CallEvent::RosterUpdate(body)) => {
395 })?;
692 replier.reply(request_id, 200, "");
396 remote_set = true;
693 if roster.apply(&body) {
397 let directions: Vec<String> = peer
694 let entries = roster.entries();
398 .transceivers()
695 timeline.record("roster", format!("{} participant(s)", entries.len()));
399 .iter()
696 control.send(CallUpdate::Roster(entries));
400 .map(|transceiver| format!("{:?}", transceiver.current_direction()))
697 if let Some(in_lobby) = roster.is_in_lobby(&own_mri)
401 .collect();
698 && in_lobby != lobby
402 timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(",")));
699 {
403 let signaling = signaling.clone();
700 lobby = in_lobby;
404 let conversation = conversation.clone();
701 control.send(CallUpdate::Lobby(lobby));
405 let participant = participant.clone();
702 }
406 let links = links.clone();
703 }
407 let thread_id = thread_id.clone();
704 }
408 tokio::spawn(async move {
705 Ok(CallEvent::Progress(status)) => {
409 let _ = signaling.add_echo_bot(&conversation, &participant, thread_id.as_deref(), &links).await;
706 replier.reply(request_id, 200, "");
410 let _ = signaling.update_endpoint_metadata(&conversation, &participant).await;
707 if status == ProgressStatus::Ringing {
411 });
708 control.send(CallUpdate::Progress(Progress::Ringing));
709 }
710 }
711 Ok(CallEvent::Speakers(sources)) => {
712 replier.reply(request_id, 200, "");
713 control.send(CallUpdate::Speakers(roster.mris_for_sources(&sources)));
412 }
714 }
413 Ok(CallEvent::End(end)) => {
715 Ok(CallEvent::End(end)) => {
414 replier.reply(request_id, 200, "");
716 replier.reply(request_id, 200, "");
717 let kind = end.kind();
415 report.end = Some(end);
718 report.end = Some(end);
416 advance(state, CallSignal::RemoteEnd, control);
719 advance(state, CallSignal::RemoteEnd(kind), control);
417 break;
720 break;
418 }
721 }
419 Ok(_) => replier.reply(request_id, 200, ""),
722 Ok(_) => replier.reply(request_id, 200, ""),
@@ -423,7 +726,7 @@ async fn drive(
423 }
726 }
424 }
727 }
425 }
728 }
426 Some(event) = peer_receiver.recv() => match event {
729 Some(event) = current.events.recv() => match event {
427 PeerEvent::Ice(ice_state) => {
730 PeerEvent::Ice(ice_state) => {
428 timeline.record("ICE state", format!("{ice_state:?}"));
731 timeline.record("ICE state", format!("{ice_state:?}"));
429 if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() {
732 if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() {
@@ -456,13 +759,32 @@ async fn drive(
456 _ => {}
759 _ => {}
457 }
760 }
458 }
761 }
459 PeerEvent::Track(track) => {
762 PeerEvent::Track(remote_track) => {
460 timeline.record("remote audio track", "receiving");
763 timeline.record("remote audio track", "receiving");
461 if options.record_remote {
764 if options.record_remote {
462 tokio::spawn(record_track(track, recording.clone(), options.tone_hz));
765 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
463 }
766 }
464 }
767 }
465 },
768 },
769 Some(event) = next_peer_event(&mut next) => match event {
770 PeerEvent::Connection(PeerConnectionState::Connected) => {
771 if let Some(pending) = next.take() {
772 timeline.record("escalation", "new peer connection connected, old one dropped");
773 let old = std::mem::replace(&mut current, pending.session);
774 old.peer.close();
775 offered = pending.offered;
776 remote_set = true;
777 }
778 }
779 PeerEvent::Connection(PeerConnectionState::Failed) => {
780 negotiator.escalation_failed();
781 if let Some(pending) = next.take() {
782 pending.session.peer.close();
783 }
784 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
785 }
786 _ => {}
787 },
466 command = control.recv() => match command {
788 command = control.recv() => match command {
467 Some(CallCommand::Mute(mute)) => {
789 Some(CallCommand::Mute(mute)) => {
468 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), &remote, control);
790 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), &remote, control);
@@ -484,13 +806,26 @@ async fn drive(
484 Some(CallCommand::RefreshDevices) => {
806 Some(CallCommand::RefreshDevices) => {
485 control.send(CallUpdate::Devices(devices::list_devices(&factory)));
807 control.send(CallUpdate::Devices(devices::list_devices(&factory)));
486 }
808 }
809 Some(CallCommand::EndMeeting) => {
810 if is_meeting {
811 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
812 Ok(()) => {
813 live.skip_leave = true;
814 report.left_cleanly = true;
815 }
816 Err(error) => timeline.record("end meeting failed", error.to_string()),
817 }
818 }
819 advance(state, CallSignal::LocalLeave, control);
820 break;
821 }
487 Some(CallCommand::Hangup) | None => {
822 Some(CallCommand::Hangup) | None => {
488 advance(state, CallSignal::LocalLeave, control);
823 advance(state, CallSignal::LocalLeave, control);
489 break;
824 break;
490 }
825 }
491 },
826 },
492 _ = stats_tick.tick(), if remote_set => {
827 _ = stats_tick.tick(), if remote_set => {
493 let snapshot = collect_stats(&peer).await;
828 let snapshot = collect_stats(&current.peer).await;
494 ticks += 1;
829 ticks += 1;
495 let local_level = if muted { 0.0 } else { snapshot.local_level as f32 };
830 let local_level = if muted { 0.0 } else { snapshot.local_level as f32 };
496 control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
831 control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
@@ -542,11 +877,80 @@ async fn drive(
542 advance(state, CallSignal::LocalLeave, control);
877 advance(state, CallSignal::LocalLeave, control);
543 break;
878 break;
544 }
879 }
880 _ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => {
881 timeline.record("no answer", "outgoing call timed out");
882 live.cancel_leave = true;
883 advance(state, CallSignal::RemoteEnd(EndKind::NoAnswer), control);
884 break;
885 }
886 _ = sleep_until(keep_alive_at.unwrap_or_else(far_future)), if keep_alive_at.is_some() => {
887 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
888 let remote = remote.clone();
889 let links = links.clone();
890 let call_leg = keep_alive_link.clone();
891 tokio::spawn(async move {
892 if let Some(url) = call_leg {
893 let _ = remote.signaling.keep_call_alive(&url).await;
894 }
895 let _ = remote.signaling.keep_conversation_alive(&remote.conversation, &remote.participant, &links).await;
896 });
897 }
545 }
898 }
546 }
899 }
900 live.callbacks = Some(callbacks);
547 Ok(())
901 Ok(())
548}
902}
549
903
904#[allow(clippy::too_many_arguments)]
905async fn start_escalation(
906 factory: &PeerConnectionFactory,
907 grant: &RelayGrant,
908 options: &CallOptions,
909 track: &RtcAudioTrack,
910 remote: &RemoteCall,
911 links: &CallbackLinks,
912 media_leg_id: &str,
913 acceptance_links: &BTreeMap<String, String>,
914) -> Result<NextPeer> {
915 let url = acceptance_links
916 .get("mediaRenegotiation")
917 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
918 let session = open_peer(factory, grant, &options.relay_host)?;
919 let media = create_offer(&session.peer, track).await?;
920 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id);
921 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
922 Ok(NextPeer {
923 session,
924 offered: Some(media),
925 })
926}
927
928async fn answer_on_new_peer(
929 factory: &PeerConnectionFactory,
930 grant: &RelayGrant,
931 options: &CallOptions,
932 track: &RtcAudioTrack,
933 teams_offer: &str,
934) -> Result<(PeerSession, AnsweredMedia)> {
935 let session = open_peer(factory, grant, &options.relay_host)?;
936 let answered = answer_offer(&session.peer, Some(track), teams_offer).await?;
937 Ok((session, answered))
938}
939
940async fn send_media_answer(
941 remote: &RemoteCall,
942 links: &CallbackLinks,
943 reply_links: &BTreeMap<String, String>,
944 answered: &AnsweredMedia,
945 media_leg_id: &str,
946) -> Result<()> {
947 let url = reply_links
948 .get("mediaAnswer")
949 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
950 let body = escalation_answer_body(&remote.participant, links, &answered.answer_sdp, media_leg_id);
951 remote.signaling.post_json("POST mediaAnswer", url, body).await
952}
953
550fn far_future() -> Instant {
954fn far_future() -> Instant {
551 Instant::now() + FAR_FUTURE
955 Instant::now() + FAR_FUTURE
552}
956}
@@ -565,26 +969,29 @@ fn apply_mute(command: MuteCommand, currently_muted: bool, audio: &AudioSetup, r
565 effect.muted
969 effect.muted
566}
970}
567
971
568async fn tear_down(mut live: Live, timeline: &Timeline, report: &mut TestCallReport) {
972async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) {
569 if let Some(audio) = &live.audio {
973 if let Some(audio) = &live.audio {
570 audio.track.set_enabled(false);
974 audio.track.set_enabled(false);
571 }
975 }
572 live.broker_running.store(false, Ordering::SeqCst);
976 live.broker_running.store(false, Ordering::SeqCst);
573 if let Some(remote) = &live.remote {
977 if !live.skip_leave
574 match remote.signaling.leave(&remote.conversation, &remote.participant).await {
978 && let Some(remote) = &live.remote
979 {
980 let reason = if cancelled { LeaveReason::Cancel } else { LeaveReason::Hangup };
981 match remote.signaling.leave(&remote.conversation, &remote.participant, reason).await {
575 Ok(()) => report.left_cleanly = true,
982 Ok(()) => report.left_cleanly = true,
576 Err(error) => timeline.record("leave failed", error.to_string()),
983 Err(error) => timeline.record("leave failed", error.to_string()),
577 }
984 }
578 }
985 }
579 if report.end.is_none()
986 if report.end.is_none()
580 && let (Some(callbacks), Some(replier)) = (live.callbacks.as_mut(), live.replier.as_ref())
987 && let Some(callbacks) = live.callbacks.as_mut()
581 && live.remote.is_some()
988 && live.remote.is_some()
582 {
989 {
583 let waited = timeout(END_CALLBACK_WAIT, async {
990 let waited = timeout(END_CALLBACK_WAIT, async {
584 while let Some(callback) = callbacks.recv().await {
991 while let Some(callback) = callbacks.recv().await {
585 let request_id = callback.request_id;
992 let request_id = callback.request_id;
586 let event = handle_callback(&callback, timeline);
993 let event = handle_callback(&callback, timeline);
587 replier.reply(request_id, 200, "");
994 inner.replier.reply(request_id, 200, "");
588 if let Ok(CallEvent::End(end)) = event {
995 if let Ok(CallEvent::End(end)) = event {
589 return Some(end);
996 return Some(end);
590 }
997 }
@@ -594,7 +1001,7 @@ async fn tear_down(mut live: Live, timeline: &Timeline, report: &mut TestCallRep
594 .await;
1001 .await;
595 report.end = waited.ok().flatten();
1002 report.end = waited.ok().flatten();
596 }
1003 }
597 if let Some(peer) = &live.peer {
1004 for peer in &live.peers {
598 peer.close();
1005 peer.close();
599 }
1006 }
600 if let Some(audio) = live.audio.take() {
1007 if let Some(audio) = live.audio.take() {
@@ -603,12 +1010,26 @@ async fn tear_down(mut live: Live, timeline: &Timeline, report: &mut TestCallRep
603 if let Some(broker) = live.broker.take() {
1010 if let Some(broker) = live.broker.take() {
604 broker.abort();
1011 broker.abort();
605 }
1012 }
606 if let Some(realtime) = live.realtime.take() {
1013 if let Some(route_id) = &live.route_id {
607 realtime.stop().await;
1014 inner.unregister_route(route_id);
608 }
1015 }
609 timeline.record("closed", "peer closed, Trouter registration removed");
1016 timeline.record("closed", "peer closed, call route removed");
1017}
1018
1019fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
1020 let body = decode_body(callback)?;
1021 let (_, event) = classify(&callback.path, body)?;
1022 let detail = match &event {
1023 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
1024 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
1025 CallEvent::Progress(status) => format!("{status:?}"),
1026 _ => String::new(),
1027 };
1028 timeline.record(format!("Trouter {}", event.name()), detail);
1029 Ok(event)
610}
1030}
611
1031
1032
612async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
1033async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
613 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
1034 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
614 let description =
1035 let description =
@@ -619,7 +1040,7 @@ async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &Sign
619}
1040}
620
1041
621/// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect.
1042/// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect.
622fn dump_sdp(options: &TestCallOptions, name: &str, sdp: &str) {
1043fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
623 let Some(directory) = &options.sdp_dump_dir else {
1044 let Some(directory) = &options.sdp_dump_dir else {
624 return;
1045 return;
625 };
1046 };
@@ -648,18 +1069,6 @@ fn mask_address(token: &str) -> String {
648 }
1069 }
649}
1070}
650
1071
651fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
652 let body = decode_body(callback)?;
653 let (_, event) = classify(&callback.path, body)?;
654 let detail = match &event {
655 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
656 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
657 _ => String::new(),
658 };
659 timeline.record(format!("Trouter {}", event.name()), detail);
660 Ok(event)
661}
662
663async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, tone_hz: f32) {
1072async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, tone_hz: f32) {
664 let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1);
1073 let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1);
665 while let Some(frame) = stream.next().await {
1074 while let Some(frame) = stream.next().await {
@@ -771,11 +1180,27 @@ mod tests {
771 use super::*;
1180 use super::*;
772
1181
773 #[test]
1182 #[test]
774 fn callback_base_comes_from_the_presence_uri() {
1183 fn keep_alive_fires_at_ninety_percent_of_the_interval() {
775 assert_eq!(
1184 assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430));
776 callback_base("https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc//unifiedPresenceService"),
1185 assert_eq!(keep_alive_period(None), Duration::from_secs(2430));
777 "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc/"
1186 assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54));
778 );
1187 }
779 assert_eq!(callback_base("https://h/v4/f/abc/unifiedPresenceService"), "https://h/v4/f/abc/");
1188
1189 #[test]
1190 fn specs_map_to_invitation_targets() {
1191 assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
1192 let people = CallSpec::People {
1193 callees: vec![Callee { mri: "8:orgid:b".into(), display_name: "Bea".into() }],
1194 thread_id: "19:t@thread.v2".into(),
1195 };
1196 assert!(people.is_people() && !people.is_meeting());
1197 assert!(matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2"));
1198 let meeting = CallSpec::Meeting(MeetingTarget {
1199 thread_id: "19:meeting@thread.v2".into(),
1200 tenant_id: "t".into(),
1201 organizer_id: "o".into(),
1202 meeting_data: None,
1203 });
1204 assert!(meeting.is_meeting() && !meeting.is_people());
780 }
1205 }
781}
1206}
crates/calling/src/control.rs +13 −0
@@ -5,6 +5,7 @@ use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
5 5 use crate::devices::{DeviceChoice, DeviceLists};
6 6 use crate::error::{Error, Result};
7 7 use crate::mute::MuteCommand;
8 use crate::roster::RosterEntry;
8 9 use crate::state::CallState;
9 10
10 11 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -14,6 +15,13 @@ pub enum CallCommand {
14 15 SelectOutput(DeviceChoice),
15 16 RefreshDevices,
16 17 Hangup,
18 EndMeeting,
19 }
20
21 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
22 pub enum Progress {
23 Calling,
24 Ringing,
17 25 }
18 26
19 27 #[derive(Debug, Clone, PartialEq)]
@@ -25,6 +33,11 @@ pub enum CallUpdate {
25 33 Selected { input: DeviceChoice, output: DeviceChoice },
26 34 ListenOnly(bool),
27 35 Stats { inbound_packets: u64, outbound_packets: u64 },
36 Progress(Progress),
37 Roster(Vec<RosterEntry>),
38 Speakers(Vec<String>),
39 Lobby(bool),
40 OwnIdentity { mri: String },
28 41 }
29 42
30 43 pub struct CallHandle {
@@ -5,6 +5,7 @@ use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
5use crate::devices::{DeviceChoice, DeviceLists};
5use crate::devices::{DeviceChoice, DeviceLists};
6use crate::error::{Error, Result};
6use crate::error::{Error, Result};
7use crate::mute::MuteCommand;
7use crate::mute::MuteCommand;
8use crate::roster::RosterEntry;
8use crate::state::CallState;
9use crate::state::CallState;
9
10
10#[derive(Debug, Clone, PartialEq, Eq)]
11#[derive(Debug, Clone, PartialEq, Eq)]
@@ -14,6 +15,13 @@ pub enum CallCommand {
14 SelectOutput(DeviceChoice),
15 SelectOutput(DeviceChoice),
15 RefreshDevices,
16 RefreshDevices,
16 Hangup,
17 Hangup,
18 EndMeeting,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum Progress {
23 Calling,
24 Ringing,
17}
25}
18
26
19#[derive(Debug, Clone, PartialEq)]
27#[derive(Debug, Clone, PartialEq)]
@@ -25,6 +33,11 @@ pub enum CallUpdate {
25 Selected { input: DeviceChoice, output: DeviceChoice },
33 Selected { input: DeviceChoice, output: DeviceChoice },
26 ListenOnly(bool),
34 ListenOnly(bool),
27 Stats { inbound_packets: u64, outbound_packets: u64 },
35 Stats { inbound_packets: u64, outbound_packets: u64 },
36 Progress(Progress),
37 Roster(Vec<RosterEntry>),
38 Speakers(Vec<String>),
39 Lobby(bool),
40 OwnIdentity { mri: String },
28}
41}
29
42
30pub struct CallHandle {
43pub struct CallHandle {
crates/calling/src/end.rs added +58 −0
@@ -0,0 +1,58 @@
1 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2 pub enum EndKind {
3 Normal,
4 Cancelled,
5 Declined,
6 NoAnswer,
7 Unavailable,
8 AnsweredElsewhere,
9 Forwarded,
10 MediaError,
11 Other,
12 }
13
14 const SUB_CODE_DECLINED: i64 = 10603;
15 const SUB_CODES_NO_ANSWER: [i64; 2] = [10408, 10486];
16
17 pub fn classify_end(code: i64, sub_code: i64) -> EndKind {
18 match code {
19 0 => EndKind::Normal,
20 487 => EndKind::Cancelled,
21 603 => EndKind::Declined,
22 408 => EndKind::NoAnswer,
23 480 => EndKind::Unavailable,
24 450 => EndKind::AnsweredElsewhere,
25 451 | 452 => EndKind::Forwarded,
26 410 => EndKind::MediaError,
27 _ if sub_code == SUB_CODE_DECLINED => EndKind::Declined,
28 _ if SUB_CODES_NO_ANSWER.contains(&sub_code) => EndKind::NoAnswer,
29 _ => EndKind::Other,
30 }
31 }
32
33 #[cfg(test)]
34 mod tests {
35 use super::*;
36
37 #[test]
38 fn codes_map_to_their_meaning() {
39 assert_eq!(classify_end(0, 5001), EndKind::Normal);
40 assert_eq!(classify_end(487, 0), EndKind::Cancelled);
41 assert_eq!(classify_end(603, 0), EndKind::Declined);
42 assert_eq!(classify_end(408, 0), EndKind::NoAnswer);
43 assert_eq!(classify_end(480, 0), EndKind::Unavailable);
44 assert_eq!(classify_end(450, 0), EndKind::AnsweredElsewhere);
45 assert_eq!(classify_end(451, 0), EndKind::Forwarded);
46 assert_eq!(classify_end(452, 0), EndKind::Forwarded);
47 assert_eq!(classify_end(410, 0), EndKind::MediaError);
48 }
49
50 #[test]
51 fn unknown_codes_fall_back_to_the_sub_code() {
52 assert_eq!(classify_end(500, 10603), EndKind::Declined);
53 assert_eq!(classify_end(500, 10408), EndKind::NoAnswer);
54 assert_eq!(classify_end(500, 10486), EndKind::NoAnswer);
55 assert_eq!(classify_end(500, 10600), EndKind::Other);
56 assert_eq!(classify_end(500, 0), EndKind::Other);
57 }
58 }
@@ -0,0 +1,58 @@
1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2pub enum EndKind {
3 Normal,
4 Cancelled,
5 Declined,
6 NoAnswer,
7 Unavailable,
8 AnsweredElsewhere,
9 Forwarded,
10 MediaError,
11 Other,
12}
13
14const SUB_CODE_DECLINED: i64 = 10603;
15const SUB_CODES_NO_ANSWER: [i64; 2] = [10408, 10486];
16
17pub fn classify_end(code: i64, sub_code: i64) -> EndKind {
18 match code {
19 0 => EndKind::Normal,
20 487 => EndKind::Cancelled,
21 603 => EndKind::Declined,
22 408 => EndKind::NoAnswer,
23 480 => EndKind::Unavailable,
24 450 => EndKind::AnsweredElsewhere,
25 451 | 452 => EndKind::Forwarded,
26 410 => EndKind::MediaError,
27 _ if sub_code == SUB_CODE_DECLINED => EndKind::Declined,
28 _ if SUB_CODES_NO_ANSWER.contains(&sub_code) => EndKind::NoAnswer,
29 _ => EndKind::Other,
30 }
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36
37 #[test]
38 fn codes_map_to_their_meaning() {
39 assert_eq!(classify_end(0, 5001), EndKind::Normal);
40 assert_eq!(classify_end(487, 0), EndKind::Cancelled);
41 assert_eq!(classify_end(603, 0), EndKind::Declined);
42 assert_eq!(classify_end(408, 0), EndKind::NoAnswer);
43 assert_eq!(classify_end(480, 0), EndKind::Unavailable);
44 assert_eq!(classify_end(450, 0), EndKind::AnsweredElsewhere);
45 assert_eq!(classify_end(451, 0), EndKind::Forwarded);
46 assert_eq!(classify_end(452, 0), EndKind::Forwarded);
47 assert_eq!(classify_end(410, 0), EndKind::MediaError);
48 }
49
50 #[test]
51 fn unknown_codes_fall_back_to_the_sub_code() {
52 assert_eq!(classify_end(500, 10603), EndKind::Declined);
53 assert_eq!(classify_end(500, 10408), EndKind::NoAnswer);
54 assert_eq!(classify_end(500, 10486), EndKind::NoAnswer);
55 assert_eq!(classify_end(500, 10600), EndKind::Other);
56 assert_eq!(classify_end(500, 0), EndKind::Other);
57 }
58}
crates/calling/src/engine.rs added +476 −0
@@ -0,0 +1,476 @@
1 use std::collections::HashMap;
2 use std::sync::atomic::{AtomicU64, Ordering};
3 use std::sync::{Arc, Mutex};
4 use std::time::{Duration, Instant};
5
6 use chatsvc::{CallbackReplier, InstanceNames, Realtime, RealtimeConfig, RealtimeEvent, TrouterCallback, TrouterEndpoint};
7 use session::Session;
8 use tokio::sync::{mpsc, oneshot};
9 use tokio::task::JoinHandle;
10 use tokio::time::timeout;
11
12 use crate::call::{CallOptions, CallSpec, IncomingCall, Plan};
13 use crate::control::{CallHandle, call_channel};
14 use crate::end::EndKind;
15 use crate::error::{Error, Result};
16 use crate::push::{CallNotification, Caller, PushEvent, decode_push};
17 use crate::relay::DEFAULT_RELAY_HOST;
18 use crate::signaling::{AttachRequest, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self};
19 use crate::timeline::Timeline;
20 use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, classify, decode_body};
21
22 const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
23 const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
24 const SEEN_WINDOW: Duration = Duration::from_secs(120);
25 const RING_ID_START: u64 = 1;
26 pub const TRACE_ENV: &str = "CALLING_TRACE";
27
28 pub fn calling_instance_names() -> InstanceNames {
29 InstanceNames {
30 global: "__callingTrouter".into(),
31 binding: "__callingRealtime".into(),
32 endpoint_storage_key: "__callingEpid".into(),
33 }
34 }
35
36 pub fn calling_realtime_config(ringable: bool, instance: InstanceNames) -> RealtimeConfig {
37 RealtimeConfig {
38 instance,
39 forward_callbacks: true,
40 ringable,
41 ..RealtimeConfig::default()
42 }
43 }
44
45 pub(crate) fn callback_base(trouter_uri: &str) -> String {
46 let trimmed = trouter_uri.strip_suffix(PRESENCE_SUFFIX).unwrap_or(trouter_uri).trim_end_matches('/');
47 format!("{trimmed}/")
48 }
49
50 #[derive(Debug, Clone)]
51 pub struct EngineConfig {
52 pub ringable: bool,
53 pub routing: TenantRouting,
54 pub relay_host: String,
55 pub trace: bool,
56 /// Page globals of the Trouter client; a second engine in the same tab needs its own.
57 pub instance: InstanceNames,
58 }
59
60 impl Default for EngineConfig {
61 fn default() -> Self {
62 EngineConfig {
63 ringable: true,
64 routing: TenantRouting::default(),
65 relay_host: DEFAULT_RELAY_HOST.to_owned(),
66 trace: std::env::var_os(TRACE_ENV).is_some(),
67 instance: calling_instance_names(),
68 }
69 }
70 }
71
72 #[derive(Debug, Clone, PartialEq)]
73 pub struct IncomingRing {
74 pub ring_id: u64,
75 pub caller: Caller,
76 pub thread_id: Option<String>,
77 pub video: bool,
78 pub is_group: bool,
79 pub subject: Option<String>,
80 }
81
82 #[derive(Debug, Clone, PartialEq)]
83 pub enum EngineEvent {
84 Incoming(IncomingRing),
85 RingEnded {
86 ring_id: u64,
87 kind: EndKind,
88 answered_by: Option<String>,
89 },
90 }
91
92 enum RingCommand {
93 Accept(oneshot::Sender<Option<CallHandle>>),
94 Decline,
95 Drop,
96 }
97
98 pub(crate) struct Inner {
99 pub(crate) session: Session,
100 pub(crate) poll_session: Session,
101 pub(crate) config: EngineConfig,
102 pub(crate) identity: SelfIdentity,
103 pub(crate) replier: CallbackReplier,
104 pub(crate) gate: Arc<tokio::sync::Mutex<()>>,
105 endpoint: Mutex<TrouterEndpoint>,
106 routes: Mutex<HashMap<String, mpsc::UnboundedSender<TrouterCallback>>>,
107 rings: Mutex<HashMap<u64, mpsc::UnboundedSender<RingCommand>>>,
108 seen: Mutex<HashMap<(String, String), Instant>>,
109 next_ring_id: AtomicU64,
110 runtime: tokio::runtime::Handle,
111 events: mpsc::UnboundedSender<EngineEvent>,
112 stop: Mutex<Option<oneshot::Sender<()>>>,
113 tasks: Mutex<Vec<JoinHandle<()>>>,
114 }
115
116 impl Inner {
117 pub(crate) fn endpoint(&self) -> TrouterEndpoint {
118 self.endpoint.lock().expect("endpoint lock").clone()
119 }
120
121 pub(crate) fn register_route(&self, call_id: &str) -> mpsc::UnboundedReceiver<TrouterCallback> {
122 let (sender, receiver) = mpsc::unbounded_channel();
123 self.routes.lock().expect("routes lock").insert(call_id.to_owned(), sender);
124 receiver
125 }
126
127 pub(crate) fn unregister_route(&self, call_id: &str) {
128 self.routes.lock().expect("routes lock").remove(call_id);
129 }
130
131 pub(crate) fn participant(&self, participant_id: &str) -> Participant {
132 Participant {
133 mri: format!("8:orgid:{}", self.identity.object_id),
134 display_name: self.identity.display_name.clone(),
135 endpoint_id: self.endpoint().endpoint_id,
136 participant_id: participant_id.to_owned(),
137 language_id: "en-gb".into(),
138 }
139 }
140
141 pub(crate) fn callback_links(&self) -> CallbackLinks {
142 CallbackLinks::new(&callback_base(&self.endpoint().trouter_uri), &uuid::Uuid::new_v4().to_string())
143 }
144
145 pub(crate) fn signaling(&self, timeline: Timeline) -> Signaling {
146 Signaling::new(self.session.clone(), self.poll_session.clone(), self.config.routing.clone(), timeline)
147 }
148
149 pub(crate) fn call_options(&self) -> CallOptions {
150 CallOptions {
151 relay_host: self.config.relay_host.clone(),
152 routing: self.config.routing.clone(),
153 trace: self.config.trace,
154 ..CallOptions::default()
155 }
156 }
157
158 fn route(&self, callback: TrouterCallback) {
159 let Some(call_id) = callback_call_id(&callback.path) else {
160 self.replier.reply(callback.request_id, 200, "");
161 return;
162 };
163 let sender = self.routes.lock().expect("routes lock").get(&call_id).cloned();
164 match sender {
165 Some(sender) => {
166 if let Err(rejected) = sender.send(callback) {
167 self.replier.reply(rejected.0.request_id, 200, "");
168 }
169 }
170 None => self.replier.reply(callback.request_id, 200, ""),
171 }
172 }
173
174 fn already_seen(&self, notification: &CallNotification) -> bool {
175 let mut seen = self.seen.lock().expect("seen lock");
176 let now = Instant::now();
177 seen.retain(|_, at| now.duration_since(*at) < SEEN_WINDOW);
178 seen.insert(notification.dedupe_key(), now).is_some()
179 }
180
181 fn emit(&self, event: EngineEvent) {
182 let _ = self.events.send(event);
183 }
184 }
185
186 #[derive(Clone)]
187 pub struct CallEngine {
188 pub(crate) inner: Arc<Inner>,
189 }
190
191 impl CallEngine {
192 pub async fn start(
193 session: Session,
194 poll_session: Session,
195 config: EngineConfig,
196 ) -> Result<(CallEngine, mpsc::UnboundedReceiver<EngineEvent>)> {
197 let mut realtime = Realtime::start_with(&session, calling_realtime_config(config.ringable, config.instance.clone())).await?;
198 let callbacks = realtime
199 .take_callbacks()
200 .ok_or_else(|| Error::Callback("callback stream already taken".into()))?;
201 let replier = realtime.callback_replier();
202 let endpoint = timeout(ENDPOINT_WAIT, async {
203 while let Some(event) = realtime.recv().await {
204 if let RealtimeEvent::Endpoint(endpoint) = event {
205 return Some(endpoint);
206 }
207 }
208 None
209 })
210 .await
211 .ok()
212 .flatten();
213 let Some(endpoint) = endpoint else {
214 realtime.stop().await;
215 return Err(Error::Callback("Trouter socket never announced its endpoint".into()));
216 };
217 let identity = match fetch_self(&session).await {
218 Ok(identity) => identity,
219 Err(error) => {
220 realtime.stop().await;
221 return Err(error);
222 }
223 };
224 let (events, event_receiver) = mpsc::unbounded_channel();
225 let (stop, stop_receiver) = oneshot::channel();
226 let inner = Arc::new(Inner {
227 session,
228 poll_session,
229 config,
230 identity,
231 replier,
232 gate: Arc::new(tokio::sync::Mutex::new(())),
233 endpoint: Mutex::new(endpoint),
234 routes: Mutex::default(),
235 rings: Mutex::default(),
236 seen: Mutex::default(),
237 next_ring_id: AtomicU64::new(RING_ID_START),
238 runtime: tokio::runtime::Handle::current(),
239 events,
240 stop: Mutex::new(Some(stop)),
241 tasks: Mutex::default(),
242 });
243 let engine = CallEngine { inner: inner.clone() };
244 let pump = tokio::spawn(pump_realtime(realtime, inner.clone(), stop_receiver));
245 let router = tokio::spawn(route_callbacks(callbacks, engine.clone()));
246 inner.tasks.lock().expect("tasks lock").extend([pump, router]);
247 Ok((engine, event_receiver))
248 }
249
250 pub fn session(&self) -> Session {
251 self.inner.session.clone()
252 }
253
254 pub fn start_call(&self, spec: CallSpec) -> CallHandle {
255 let (handle, control) = call_channel();
256 let engine = self.clone();
257 self.inner.runtime.spawn(async move {
258 let options = engine.inner.call_options();
259 let _ = engine.run(Plan::Outgoing(spec), options, control).await;
260 });
261 handle
262 }
263
264 pub async fn accept_ring(&self, ring_id: u64) -> Option<CallHandle> {
265 let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned()?;
266 let (answer, handle) = oneshot::channel();
267 commands.send(RingCommand::Accept(answer)).ok()?;
268 handle.await.ok().flatten()
269 }
270
271 /// Only for a click on Decline: it ends the call for all of the user's devices.
272 pub fn decline_ring(&self, ring_id: u64) {
273 self.send_ring_command(ring_id, RingCommand::Decline);
274 }
275
276 /// Stops ringing locally without telling Teams; the call keeps ringing elsewhere.
277 pub fn drop_ring(&self, ring_id: u64) {
278 self.send_ring_command(ring_id, RingCommand::Drop);
279 }
280
281 fn send_ring_command(&self, ring_id: u64, command: RingCommand) {
282 let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned();
283 if let Some(commands) = commands {
284 let _ = commands.send(command);
285 }
286 }
287
288 pub async fn stop(&self) {
289 let stop = self.inner.stop.lock().expect("stop lock").take();
290 if let Some(stop) = stop {
291 let _ = stop.send(());
292 }
293 let tasks: Vec<JoinHandle<()>> = std::mem::take(&mut *self.inner.tasks.lock().expect("tasks lock"));
294 for task in tasks {
295 let _ = task.await;
296 }
297 }
298 }
299
300 async fn pump_realtime(mut realtime: Realtime, inner: Arc<Inner>, mut stop: oneshot::Receiver<()>) {
301 let mut last_status = None;
302 loop {
303 tokio::select! {
304 event = realtime.recv() => match event {
305 Some(RealtimeEvent::Endpoint(endpoint)) => *inner.endpoint.lock().expect("endpoint lock") = endpoint,
306 Some(RealtimeEvent::Status(status)) => {
307 if last_status.as_ref() != Some(&status) {
308 eprintln!("calls: trouter {:?} {}", status.kind, status.detail);
309 last_status = Some(status);
310 }
311 }
312 Some(_) => {}
313 None => return,
314 },
315 _ = &mut stop => {
316 realtime.stop().await;
317 return;
318 }
319 }
320 }
321 }
322
323 async fn route_callbacks(mut callbacks: mpsc::UnboundedReceiver<TrouterCallback>, engine: CallEngine) {
324 while let Some(callback) = callbacks.recv().await {
325 if callback.path.is_empty() {
326 engine.handle_push(callback);
327 } else {
328 engine.inner.route(callback);
329 }
330 }
331 }
332
333 impl CallEngine {
334 fn handle_push(&self, callback: TrouterCallback) {
335 self.inner.replier.reply(callback.request_id, 200, "");
336 if !self.inner.config.ringable {
337 return;
338 }
339 let Ok(PushEvent::IncomingCall(notification)) = decode_push(&callback.body) else {
340 return;
341 };
342 let notification = *notification;
343 if self.inner.already_seen(&notification) {
344 return;
345 }
346 let ring_id = self.inner.next_ring_id.fetch_add(1, Ordering::SeqCst);
347 let (commands, receiver) = mpsc::unbounded_channel();
348 self.inner.rings.lock().expect("rings lock").insert(ring_id, commands);
349 tokio::spawn(ring_task(self.clone(), notification, ring_id, receiver));
350 }
351 }
352
353 async fn ring_task(
354 engine: CallEngine,
355 notification: CallNotification,
356 ring_id: u64,
357 mut commands: mpsc::UnboundedReceiver<RingCommand>,
358 ) {
359 let inner = engine.inner.clone();
360 let links = inner.callback_links();
361 let route_id = links.call_id().to_owned();
362 let mut callbacks = inner.register_route(&route_id);
363 let timeline = Timeline::new(inner.config.trace);
364 let signaling = inner.signaling(timeline.clone());
365 let participant_id = if notification.participant_id.is_empty() {
366 uuid::Uuid::new_v4().to_string()
367 } else {
368 notification.participant_id.clone()
369 };
370 let participant = inner.participant(&participant_id);
371 let cleanup = |inner: &Inner| {
372 inner.unregister_route(&route_id);
373 inner.rings.lock().expect("rings lock").remove(&ring_id);
374 };
375 let Some(attach_url) = notification.links.get("attach") else {
376 cleanup(&inner);
377 return;
378 };
379 let request = AttachRequest {
380 from: &participant,
381 callbacks: &links,
382 controller: notification.conversation_controller.as_deref(),
383 needs_media: notification.offer_sdp.is_none(),
384 };
385 let mut attached = match signaling.attach(attach_url, &request).await {
386 Ok(attached) => attached,
387 Err(error) => {
388 timeline.record("attach failed", error.to_string());
389 cleanup(&inner);
390 return;
391 }
392 };
393 if attached.offer_sdp.is_none() {
394 attached.offer_sdp = notification.offer_sdp.clone();
395 }
396 if let Some(progress) = attached.links.get("progress")
397 && let Err(error) = signaling.send_ringing(progress, &participant).await
398 {
399 timeline.record("ringing progress failed", error.to_string());
400 }
401 inner.emit(EngineEvent::Incoming(IncomingRing {
402 ring_id,
403 caller: notification.caller.clone(),
404 thread_id: notification.thread_id.clone(),
405 video: notification.video,
406 is_group: notification.is_multi_party,
407 subject: notification.subject.clone(),
408 }));
409 loop {
410 tokio::select! {
411 callback = callbacks.recv() => {
412 let Some(callback) = callback else { break };
413 inner.replier.reply(callback.request_id, 200, "");
414 let event = decode_body(&callback).and_then(|body| classify(&callback.path, body));
415 if let Ok((_, CallEvent::End(end))) = event {
416 inner.emit(EngineEvent::RingEnded {
417 ring_id,
418 kind: end.kind(),
419 answered_by: end.accepted_elsewhere_by,
420 });
421 break;
422 }
423 }
424 command = commands.recv() => match command {
425 Some(RingCommand::Accept(answer)) => {
426 let (handle, control) = call_channel();
427 let incoming = IncomingCall {
428 notification,
429 attached,
430 links,
431 participant,
432 callbacks,
433 };
434 let _ = answer.send(Some(handle));
435 inner.rings.lock().expect("rings lock").remove(&ring_id);
436 let options = inner.call_options();
437 tokio::spawn(async move {
438 let _ = engine.run(Plan::Incoming(Box::new(incoming)), options, control).await;
439 });
440 return;
441 }
442 Some(RingCommand::Decline) => {
443 if let Some(call_leg) = attached.links.get("callLeg")
444 && let Err(error) = signaling.decline(call_leg).await
445 {
446 timeline.record("decline failed", error.to_string());
447 }
448 break;
449 }
450 Some(RingCommand::Drop) | None => break,
451 }
452 }
453 }
454 cleanup(&inner);
455 }
456
457 #[cfg(test)]
458 mod tests {
459 use super::*;
460
461 #[test]
462 fn callback_base_comes_from_the_presence_uri() {
463 assert_eq!(
464 callback_base("https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc//unifiedPresenceService"),
465 "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc/"
466 );
467 assert_eq!(callback_base("https://h/v4/f/abc/unifiedPresenceService"), "https://h/v4/f/abc/");
468 }
469
470 #[test]
471 fn only_the_ringable_engine_registers_for_calls() {
472 assert!(calling_realtime_config(true, calling_instance_names()).ringable);
473 assert!(!calling_realtime_config(false, calling_instance_names()).ringable);
474 assert!(calling_realtime_config(true, calling_instance_names()).forward_callbacks);
475 }
476 }
@@ -0,0 +1,476 @@
1use std::collections::HashMap;
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::sync::{Arc, Mutex};
4use std::time::{Duration, Instant};
5
6use chatsvc::{CallbackReplier, InstanceNames, Realtime, RealtimeConfig, RealtimeEvent, TrouterCallback, TrouterEndpoint};
7use session::Session;
8use tokio::sync::{mpsc, oneshot};
9use tokio::task::JoinHandle;
10use tokio::time::timeout;
11
12use crate::call::{CallOptions, CallSpec, IncomingCall, Plan};
13use crate::control::{CallHandle, call_channel};
14use crate::end::EndKind;
15use crate::error::{Error, Result};
16use crate::push::{CallNotification, Caller, PushEvent, decode_push};
17use crate::relay::DEFAULT_RELAY_HOST;
18use crate::signaling::{AttachRequest, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self};
19use crate::timeline::Timeline;
20use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, classify, decode_body};
21
22const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
23const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
24const SEEN_WINDOW: Duration = Duration::from_secs(120);
25const RING_ID_START: u64 = 1;
26pub const TRACE_ENV: &str = "CALLING_TRACE";
27
28pub fn calling_instance_names() -> InstanceNames {
29 InstanceNames {
30 global: "__callingTrouter".into(),
31 binding: "__callingRealtime".into(),
32 endpoint_storage_key: "__callingEpid".into(),
33 }
34}
35
36pub fn calling_realtime_config(ringable: bool, instance: InstanceNames) -> RealtimeConfig {
37 RealtimeConfig {
38 instance,
39 forward_callbacks: true,
40 ringable,
41 ..RealtimeConfig::default()
42 }
43}
44
45pub(crate) fn callback_base(trouter_uri: &str) -> String {
46 let trimmed = trouter_uri.strip_suffix(PRESENCE_SUFFIX).unwrap_or(trouter_uri).trim_end_matches('/');
47 format!("{trimmed}/")
48}
49
50#[derive(Debug, Clone)]
51pub struct EngineConfig {
52 pub ringable: bool,
53 pub routing: TenantRouting,
54 pub relay_host: String,
55 pub trace: bool,
56 /// Page globals of the Trouter client; a second engine in the same tab needs its own.
57 pub instance: InstanceNames,
58}
59
60impl Default for EngineConfig {
61 fn default() -> Self {
62 EngineConfig {
63 ringable: true,
64 routing: TenantRouting::default(),
65 relay_host: DEFAULT_RELAY_HOST.to_owned(),
66 trace: std::env::var_os(TRACE_ENV).is_some(),
67 instance: calling_instance_names(),
68 }
69 }
70}
71
72#[derive(Debug, Clone, PartialEq)]
73pub struct IncomingRing {
74 pub ring_id: u64,
75 pub caller: Caller,
76 pub thread_id: Option<String>,
77 pub video: bool,
78 pub is_group: bool,
79 pub subject: Option<String>,
80}
81
82#[derive(Debug, Clone, PartialEq)]
83pub enum EngineEvent {
84 Incoming(IncomingRing),
85 RingEnded {
86 ring_id: u64,
87 kind: EndKind,
88 answered_by: Option<String>,
89 },
90}
91
92enum RingCommand {
93 Accept(oneshot::Sender<Option<CallHandle>>),
94 Decline,
95 Drop,
96}
97
98pub(crate) struct Inner {
99 pub(crate) session: Session,
100 pub(crate) poll_session: Session,
101 pub(crate) config: EngineConfig,
102 pub(crate) identity: SelfIdentity,
103 pub(crate) replier: CallbackReplier,
104 pub(crate) gate: Arc<tokio::sync::Mutex<()>>,
105 endpoint: Mutex<TrouterEndpoint>,
106 routes: Mutex<HashMap<String, mpsc::UnboundedSender<TrouterCallback>>>,
107 rings: Mutex<HashMap<u64, mpsc::UnboundedSender<RingCommand>>>,
108 seen: Mutex<HashMap<(String, String), Instant>>,
109 next_ring_id: AtomicU64,
110 runtime: tokio::runtime::Handle,
111 events: mpsc::UnboundedSender<EngineEvent>,
112 stop: Mutex<Option<oneshot::Sender<()>>>,
113 tasks: Mutex<Vec<JoinHandle<()>>>,
114}
115
116impl Inner {
117 pub(crate) fn endpoint(&self) -> TrouterEndpoint {
118 self.endpoint.lock().expect("endpoint lock").clone()
119 }
120
121 pub(crate) fn register_route(&self, call_id: &str) -> mpsc::UnboundedReceiver<TrouterCallback> {
122 let (sender, receiver) = mpsc::unbounded_channel();
123 self.routes.lock().expect("routes lock").insert(call_id.to_owned(), sender);
124 receiver
125 }
126
127 pub(crate) fn unregister_route(&self, call_id: &str) {
128 self.routes.lock().expect("routes lock").remove(call_id);
129 }
130
131 pub(crate) fn participant(&self, participant_id: &str) -> Participant {
132 Participant {
133 mri: format!("8:orgid:{}", self.identity.object_id),
134 display_name: self.identity.display_name.clone(),
135 endpoint_id: self.endpoint().endpoint_id,
136 participant_id: participant_id.to_owned(),
137 language_id: "en-gb".into(),
138 }
139 }
140
141 pub(crate) fn callback_links(&self) -> CallbackLinks {
142 CallbackLinks::new(&callback_base(&self.endpoint().trouter_uri), &uuid::Uuid::new_v4().to_string())
143 }
144
145 pub(crate) fn signaling(&self, timeline: Timeline) -> Signaling {
146 Signaling::new(self.session.clone(), self.poll_session.clone(), self.config.routing.clone(), timeline)
147 }
148
149 pub(crate) fn call_options(&self) -> CallOptions {
150 CallOptions {
151 relay_host: self.config.relay_host.clone(),
152 routing: self.config.routing.clone(),
153 trace: self.config.trace,
154 ..CallOptions::default()
155 }
156 }
157
158 fn route(&self, callback: TrouterCallback) {
159 let Some(call_id) = callback_call_id(&callback.path) else {
160 self.replier.reply(callback.request_id, 200, "");
161 return;
162 };
163 let sender = self.routes.lock().expect("routes lock").get(&call_id).cloned();
164 match sender {
165 Some(sender) => {
166 if let Err(rejected) = sender.send(callback) {
167 self.replier.reply(rejected.0.request_id, 200, "");
168 }
169 }
170 None => self.replier.reply(callback.request_id, 200, ""),
171 }
172 }
173
174 fn already_seen(&self, notification: &CallNotification) -> bool {
175 let mut seen = self.seen.lock().expect("seen lock");
176 let now = Instant::now();
177 seen.retain(|_, at| now.duration_since(*at) < SEEN_WINDOW);
178 seen.insert(notification.dedupe_key(), now).is_some()
179 }
180
181 fn emit(&self, event: EngineEvent) {
182 let _ = self.events.send(event);
183 }
184}
185
186#[derive(Clone)]
187pub struct CallEngine {
188 pub(crate) inner: Arc<Inner>,
189}
190
191impl CallEngine {
192 pub async fn start(
193 session: Session,
194 poll_session: Session,
195 config: EngineConfig,
196 ) -> Result<(CallEngine, mpsc::UnboundedReceiver<EngineEvent>)> {
197 let mut realtime = Realtime::start_with(&session, calling_realtime_config(config.ringable, config.instance.clone())).await?;
198 let callbacks = realtime
199 .take_callbacks()
200 .ok_or_else(|| Error::Callback("callback stream already taken".into()))?;
201 let replier = realtime.callback_replier();
202 let endpoint = timeout(ENDPOINT_WAIT, async {
203 while let Some(event) = realtime.recv().await {
204 if let RealtimeEvent::Endpoint(endpoint) = event {
205 return Some(endpoint);
206 }
207 }
208 None
209 })
210 .await
211 .ok()
212 .flatten();
213 let Some(endpoint) = endpoint else {
214 realtime.stop().await;
215 return Err(Error::Callback("Trouter socket never announced its endpoint".into()));
216 };
217 let identity = match fetch_self(&session).await {
218 Ok(identity) => identity,
219 Err(error) => {
220 realtime.stop().await;
221 return Err(error);
222 }
223 };
224 let (events, event_receiver) = mpsc::unbounded_channel();
225 let (stop, stop_receiver) = oneshot::channel();
226 let inner = Arc::new(Inner {
227 session,
228 poll_session,
229 config,
230 identity,
231 replier,
232 gate: Arc::new(tokio::sync::Mutex::new(())),
233 endpoint: Mutex::new(endpoint),
234 routes: Mutex::default(),
235 rings: Mutex::default(),
236 seen: Mutex::default(),
237 next_ring_id: AtomicU64::new(RING_ID_START),
238 runtime: tokio::runtime::Handle::current(),
239 events,
240 stop: Mutex::new(Some(stop)),
241 tasks: Mutex::default(),
242 });
243 let engine = CallEngine { inner: inner.clone() };
244 let pump = tokio::spawn(pump_realtime(realtime, inner.clone(), stop_receiver));
245 let router = tokio::spawn(route_callbacks(callbacks, engine.clone()));
246 inner.tasks.lock().expect("tasks lock").extend([pump, router]);
247 Ok((engine, event_receiver))
248 }
249
250 pub fn session(&self) -> Session {
251 self.inner.session.clone()
252 }
253
254 pub fn start_call(&self, spec: CallSpec) -> CallHandle {
255 let (handle, control) = call_channel();
256 let engine = self.clone();
257 self.inner.runtime.spawn(async move {
258 let options = engine.inner.call_options();
259 let _ = engine.run(Plan::Outgoing(spec), options, control).await;
260 });
261 handle
262 }
263
264 pub async fn accept_ring(&self, ring_id: u64) -> Option<CallHandle> {
265 let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned()?;
266 let (answer, handle) = oneshot::channel();
267 commands.send(RingCommand::Accept(answer)).ok()?;
268 handle.await.ok().flatten()
269 }
270
271 /// Only for a click on Decline: it ends the call for all of the user's devices.
272 pub fn decline_ring(&self, ring_id: u64) {
273 self.send_ring_command(ring_id, RingCommand::Decline);
274 }
275
276 /// Stops ringing locally without telling Teams; the call keeps ringing elsewhere.
277 pub fn drop_ring(&self, ring_id: u64) {
278 self.send_ring_command(ring_id, RingCommand::Drop);
279 }
280
281 fn send_ring_command(&self, ring_id: u64, command: RingCommand) {
282 let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned();
283 if let Some(commands) = commands {
284 let _ = commands.send(command);
285 }
286 }
287
288 pub async fn stop(&self) {
289 let stop = self.inner.stop.lock().expect("stop lock").take();
290 if let Some(stop) = stop {
291 let _ = stop.send(());
292 }
293 let tasks: Vec<JoinHandle<()>> = std::mem::take(&mut *self.inner.tasks.lock().expect("tasks lock"));
294 for task in tasks {
295 let _ = task.await;
296 }
297 }
298}
299
300async fn pump_realtime(mut realtime: Realtime, inner: Arc<Inner>, mut stop: oneshot::Receiver<()>) {
301 let mut last_status = None;
302 loop {
303 tokio::select! {
304 event = realtime.recv() => match event {
305 Some(RealtimeEvent::Endpoint(endpoint)) => *inner.endpoint.lock().expect("endpoint lock") = endpoint,
306 Some(RealtimeEvent::Status(status)) => {
307 if last_status.as_ref() != Some(&status) {
308 eprintln!("calls: trouter {:?} {}", status.kind, status.detail);
309 last_status = Some(status);
310 }
311 }
312 Some(_) => {}
313 None => return,
314 },
315 _ = &mut stop => {
316 realtime.stop().await;
317 return;
318 }
319 }
320 }
321}
322
323async fn route_callbacks(mut callbacks: mpsc::UnboundedReceiver<TrouterCallback>, engine: CallEngine) {
324 while let Some(callback) = callbacks.recv().await {
325 if callback.path.is_empty() {
326 engine.handle_push(callback);
327 } else {
328 engine.inner.route(callback);
329 }
330 }
331}
332
333impl CallEngine {
334 fn handle_push(&self, callback: TrouterCallback) {
335 self.inner.replier.reply(callback.request_id, 200, "");
336 if !self.inner.config.ringable {
337 return;
338 }
339 let Ok(PushEvent::IncomingCall(notification)) = decode_push(&callback.body) else {
340 return;
341 };
342 let notification = *notification;
343 if self.inner.already_seen(&notification) {
344 return;
345 }
346 let ring_id = self.inner.next_ring_id.fetch_add(1, Ordering::SeqCst);
347 let (commands, receiver) = mpsc::unbounded_channel();
348 self.inner.rings.lock().expect("rings lock").insert(ring_id, commands);
349 tokio::spawn(ring_task(self.clone(), notification, ring_id, receiver));
350 }
351}
352
353async fn ring_task(
354 engine: CallEngine,
355 notification: CallNotification,
356 ring_id: u64,
357 mut commands: mpsc::UnboundedReceiver<RingCommand>,
358) {
359 let inner = engine.inner.clone();
360 let links = inner.callback_links();
361 let route_id = links.call_id().to_owned();
362 let mut callbacks = inner.register_route(&route_id);
363 let timeline = Timeline::new(inner.config.trace);
364 let signaling = inner.signaling(timeline.clone());
365 let participant_id = if notification.participant_id.is_empty() {
366 uuid::Uuid::new_v4().to_string()
367 } else {
368 notification.participant_id.clone()
369 };
370 let participant = inner.participant(&participant_id);
371 let cleanup = |inner: &Inner| {
372 inner.unregister_route(&route_id);
373 inner.rings.lock().expect("rings lock").remove(&ring_id);
374 };
375 let Some(attach_url) = notification.links.get("attach") else {
376 cleanup(&inner);
377 return;
378 };
379 let request = AttachRequest {
380 from: &participant,
381 callbacks: &links,
382 controller: notification.conversation_controller.as_deref(),
383 needs_media: notification.offer_sdp.is_none(),
384 };
385 let mut attached = match signaling.attach(attach_url, &request).await {
386 Ok(attached) => attached,
387 Err(error) => {
388 timeline.record("attach failed", error.to_string());
389 cleanup(&inner);
390 return;
391 }
392 };
393 if attached.offer_sdp.is_none() {
394 attached.offer_sdp = notification.offer_sdp.clone();
395 }
396 if let Some(progress) = attached.links.get("progress")
397 && let Err(error) = signaling.send_ringing(progress, &participant).await
398 {
399 timeline.record("ringing progress failed", error.to_string());
400 }
401 inner.emit(EngineEvent::Incoming(IncomingRing {
402 ring_id,
403 caller: notification.caller.clone(),
404 thread_id: notification.thread_id.clone(),
405 video: notification.video,
406 is_group: notification.is_multi_party,
407 subject: notification.subject.clone(),
408 }));
409 loop {
410 tokio::select! {
411 callback = callbacks.recv() => {
412 let Some(callback) = callback else { break };
413 inner.replier.reply(callback.request_id, 200, "");
414 let event = decode_body(&callback).and_then(|body| classify(&callback.path, body));
415 if let Ok((_, CallEvent::End(end))) = event {
416 inner.emit(EngineEvent::RingEnded {
417 ring_id,
418 kind: end.kind(),
419 answered_by: end.accepted_elsewhere_by,
420 });
421 break;
422 }
423 }
424 command = commands.recv() => match command {
425 Some(RingCommand::Accept(answer)) => {
426 let (handle, control) = call_channel();
427 let incoming = IncomingCall {
428 notification,
429 attached,
430 links,
431 participant,
432 callbacks,
433 };
434 let _ = answer.send(Some(handle));
435 inner.rings.lock().expect("rings lock").remove(&ring_id);
436 let options = inner.call_options();
437 tokio::spawn(async move {
438 let _ = engine.run(Plan::Incoming(Box::new(incoming)), options, control).await;
439 });
440 return;
441 }
442 Some(RingCommand::Decline) => {
443 if let Some(call_leg) = attached.links.get("callLeg")
444 && let Err(error) = signaling.decline(call_leg).await
445 {
446 timeline.record("decline failed", error.to_string());
447 }
448 break;
449 }
450 Some(RingCommand::Drop) | None => break,
451 }
452 }
453 }
454 cleanup(&inner);
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460
461 #[test]
462 fn callback_base_comes_from_the_presence_uri() {
463 assert_eq!(
464 callback_base("https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc//unifiedPresenceService"),
465 "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc/"
466 );
467 assert_eq!(callback_base("https://h/v4/f/abc/unifiedPresenceService"), "https://h/v4/f/abc/");
468 }
469
470 #[test]
471 fn only_the_ringable_engine_registers_for_calls() {
472 assert!(calling_realtime_config(true, calling_instance_names()).ringable);
473 assert!(!calling_realtime_config(false, calling_instance_names()).ringable);
474 assert!(calling_realtime_config(true, calling_instance_names()).forward_callbacks);
475 }
476}
crates/calling/src/lib.rs +15 −2
@@ -3,10 +3,17 @@ pub mod audio_io;
3 3 pub mod call;
4 4 pub mod control;
5 5 pub mod devices;
6 pub mod engine;
7 pub mod end;
6 8 pub mod error;
7 9 pub mod level;
10 pub mod meeting;
8 11 pub mod mute;
12 pub mod push;
9 13 pub mod relay;
14 pub mod renegotiation;
15 pub mod ring;
16 pub mod roster;
10 17 pub mod sdp;
11 18 pub mod signaling;
12 19 pub mod state;
@@ -14,8 +21,14 @@ pub mod timeline;
14 21 pub mod trouter_events;
15 22
16 23 pub use audio_io::AudioMode;
17 pub use call::{TestCallOptions, TestCallReport, run_test_call};
18 pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, call_channel};
24 pub use call::{CallOptions, CallReport, CallSpec, run_test_call};
25 pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};
26 pub use end::EndKind;
27 pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
28 pub use push::Caller;
29 pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
30 pub use roster::RosterEntry;
31 pub use signaling::{Callee, MeetingTarget};
19 32 pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
20 33 pub use error::{Error, Result};
21 34 pub use level::SpeakingDetector;
@@ -3,10 +3,17 @@ pub mod audio_io;
3pub mod call;
3pub mod call;
4pub mod control;
4pub mod control;
5pub mod devices;
5pub mod devices;
6pub mod engine;
7pub mod end;
6pub mod error;
8pub mod error;
7pub mod level;
9pub mod level;
10pub mod meeting;
8pub mod mute;
11pub mod mute;
12pub mod push;
9pub mod relay;
13pub mod relay;
14pub mod renegotiation;
15pub mod ring;
16pub mod roster;
10pub mod sdp;
17pub mod sdp;
11pub mod signaling;
18pub mod signaling;
12pub mod state;
19pub mod state;
@@ -14,8 +21,14 @@ pub mod timeline;
14pub mod trouter_events;
21pub mod trouter_events;
15
22
16pub use audio_io::AudioMode;
23pub use audio_io::AudioMode;
17pub use call::{TestCallOptions, TestCallReport, run_test_call};
24pub use call::{CallOptions, CallReport, CallSpec, run_test_call};
18pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, call_channel};
25pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};
26pub use end::EndKind;
27pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
28pub use push::Caller;
29pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
30pub use roster::RosterEntry;
31pub use signaling::{Callee, MeetingTarget};
19pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
32pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
20pub use error::{Error, Result};
33pub use error::{Error, Result};
21pub use level::SpeakingDetector;
34pub use level::SpeakingDetector;
crates/calling/src/meeting.rs added +210 −0
@@ -0,0 +1,210 @@
1 use serde_json::Value;
2 use session::{Request, Session};
3
4 use crate::error::Result;
5 use crate::relay::ic3_scope;
6 use crate::signaling::{CHATSVC_REGION, MeetingTarget};
7
8 const LIVE_STATE_PREFIX: &str = "awareness_conversationLiveState";
9 const MEETING_PROPERTY: &str = "meeting";
10 const ACTIVE_STATUS: &str = "Active";
11 const MILLISECOND_EPOCH_FLOOR: i64 = 1_000_000_000_000;
12
13 #[derive(Debug, Clone, PartialEq, Eq)]
14 pub struct LiveMeeting {
15 pub thread_id: String,
16 pub conversation_url: Option<String>,
17 pub expiration: Option<i64>,
18 pub organizer_id: Option<String>,
19 pub tenant_id: Option<String>,
20 pub meeting_code: Option<String>,
21 pub passcode: Option<String>,
22 }
23
24 impl LiveMeeting {
25 pub fn is_running(&self, now_unix: i64) -> bool {
26 self.expiration.is_none_or(|expires| expires > now_unix)
27 }
28
29 pub fn target(&self) -> Option<MeetingTarget> {
30 let meeting_data = self.meeting_code.as_ref().map(|code| {
31 serde_json::json!({"meetingCode": code, "passcode": self.passcode})
32 });
33 Some(MeetingTarget {
34 thread_id: self.thread_id.clone(),
35 tenant_id: self.tenant_id.clone()?,
36 organizer_id: self.organizer_id.clone()?,
37 meeting_data,
38 })
39 }
40 }
41
42 fn as_object(value: &Value) -> Option<Value> {
43 match value {
44 Value::String(text) => serde_json::from_str(text).ok(),
45 Value::Object(_) => Some(value.clone()),
46 _ => None,
47 }
48 }
49
50 fn expiration_seconds(value: &Value) -> Option<i64> {
51 let raw = value.as_i64().or_else(|| value.as_str()?.parse().ok())?;
52 Some(if raw >= MILLISECOND_EPOCH_FLOOR { raw / 1000 } else { raw })
53 }
54
55 fn property_text(value: &Value, key: &str) -> Option<String> {
56 value[key].as_str().filter(|text| !text.is_empty()).map(str::to_owned)
57 }
58
59 fn thread_properties(body: &Value) -> Value {
60 let mut merged = serde_json::Map::new();
61 for key in ["properties", "threadProperties"] {
62 if let Some(properties) = body.get(key).and_then(Value::as_object) {
63 merged.extend(properties.clone());
64 }
65 }
66 Value::Object(merged)
67 }
68
69 pub fn live_meeting(thread_id: &str, properties: &Value, now_unix: i64) -> Option<LiveMeeting> {
70 let meeting = properties.get(MEETING_PROPERTY).and_then(as_object);
71 let entries = properties.as_object()?;
72 entries
73 .iter()
74 .filter(|(key, _)| key.starts_with(LIVE_STATE_PREFIX))
75 .filter_map(|(_, value)| as_object(value))
76 .filter(|state| state["status"].as_str() == Some(ACTIVE_STATUS))
77 .filter_map(|state| {
78 let expiration = expiration_seconds(&state["expiration"]);
79 if expiration.is_some_and(|expires| expires <= now_unix) {
80 return None;
81 }
82 let info = &state["meetingInfo"];
83 let fallback = meeting.as_ref();
84 Some(LiveMeeting {
85 thread_id: thread_id.to_owned(),
86 conversation_url: property_text(&state, "conversationUrl"),
87 expiration,
88 organizer_id: property_text(info, "organizerId")
89 .or_else(|| fallback.and_then(|meeting| property_text(meeting, "organizerId"))),
90 tenant_id: property_text(info, "tenantId")
91 .or_else(|| fallback.and_then(|meeting| property_text(meeting, "tenantId"))),
92 meeting_code: property_text(&state["meetingData"], "meetingCode"),
93 passcode: property_text(&state["meetingData"], "passcode"),
94 })
95 })
96 .next()
97 }
98
99 pub async fn fetch_live_meeting(session: &Session, thread_id: &str) -> Result<Option<LiveMeeting>> {
100 let url = format!(
101 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
102 thread_id.replace(':', "%3A").replace('@', "%40")
103 );
104 let response = session.send(Request::get(url), &ic3_scope()).await?;
105 let now = std::time::SystemTime::now()
106 .duration_since(std::time::UNIX_EPOCH)
107 .map_or(0, |elapsed| elapsed.as_secs() as i64);
108 Ok(live_meeting(thread_id, &thread_properties(&response.body), now))
109 }
110
111 #[cfg(test)]
112 mod tests {
113 use serde_json::json;
114
115 use super::*;
116
117 const NOW: i64 = 1_791_600_000;
118
119 fn live_state(status: &str, expiration: i64) -> String {
120 json!({
121 "conversationUrl": "https://conv/1",
122 "conversationId": "1",
123 "status": status,
124 "expiration": expiration,
125 "conversationType": "scheduledMeeting",
126 "meetingInfo": {"organizerId": "org-1", "tenantId": "tenant-1"},
127 "meetingData": {"meetingCode": "123", "passcode": "pw"},
128 })
129 .to_string()
130 }
131
132 #[test]
133 fn an_active_unexpired_state_is_a_running_meeting() {
134 let properties = json!({"awareness_conversationLiveState:0": live_state("Active", NOW + 600)});
135 let meeting = live_meeting("19:m@thread.v2", &properties, NOW).unwrap();
136 assert_eq!(meeting.organizer_id.as_deref(), Some("org-1"));
137 assert_eq!(meeting.conversation_url.as_deref(), Some("https://conv/1"));
138 let target = meeting.target().unwrap();
139 assert_eq!(target.thread_id, "19:m@thread.v2");
140 assert_eq!(target.tenant_id, "tenant-1");
141 assert_eq!(target.meeting_data.unwrap()["meetingCode"], "123");
142 }
143
144 #[test]
145 fn no_state_expired_or_ended_means_no_join_button() {
146 assert!(live_meeting("t", &json!({}), NOW).is_none());
147 assert!(live_meeting("t", &json!({"topic": "x"}), NOW).is_none());
148 let expired = json!({"awareness_conversationLiveState:0": live_state("Active", NOW - 1)});
149 assert!(live_meeting("t", &expired, NOW).is_none());
150 let ended = json!({"awareness_conversationLiveState:0": live_state("Ended", NOW + 600)});
151 assert!(live_meeting("t", &ended, NOW).is_none());
152 }
153
154 #[test]
155 fn a_known_meeting_stops_running_when_it_expires() {
156 let properties = json!({"awareness_conversationLiveState:0": live_state("Active", NOW + 600)});
157 let meeting = live_meeting("t", &properties, NOW).unwrap();
158 assert!(meeting.is_running(NOW + 599));
159 assert!(!meeting.is_running(NOW + 600));
160 }
161
162 #[test]
163 fn a_second_parallel_state_still_counts() {
164 let properties = json!({
165 "awareness_conversationLiveState:0": live_state("Ended", NOW + 600),
166 "awareness_conversationLiveState:1": live_state("Active", NOW + 600),
167 });
168 assert!(live_meeting("t", &properties, NOW).is_some());
169 }
170
171 #[test]
172 fn expiration_in_milliseconds_is_understood() {
173 let properties = json!({"awareness_conversationLiveState": live_state("Active", (NOW + 600) * 1000)});
174 assert!(live_meeting("t", &properties, NOW).is_some());
175 let past = json!({"awareness_conversationLiveState": live_state("Active", (NOW - 600) * 1000)});
176 assert!(live_meeting("t", &past, NOW).is_none());
177 }
178
179 #[test]
180 fn meeting_info_falls_back_to_the_meeting_property() {
181 let mut state: Value = serde_json::from_str(&live_state("Active", NOW + 600)).unwrap();
182 state.as_object_mut().unwrap().remove("meetingInfo");
183 let properties = json!({
184 "awareness_conversationLiveState:0": state.to_string(),
185 "meeting": json!({"organizerId": "org-2", "tenantId": "tenant-2"}).to_string(),
186 });
187 let meeting = live_meeting("t", &properties, NOW).unwrap();
188 assert_eq!(meeting.organizer_id.as_deref(), Some("org-2"));
189 assert_eq!(meeting.tenant_id.as_deref(), Some("tenant-2"));
190 }
191
192 #[test]
193 fn without_organizer_or_tenant_there_is_no_join_target() {
194 let state = json!({"status": "Active", "expiration": NOW + 600});
195 let properties = json!({"awareness_conversationLiveState:0": state.to_string()});
196 let meeting = live_meeting("t", &properties, NOW).unwrap();
197 assert!(meeting.target().is_none());
198 }
199
200 #[test]
201 fn thread_and_conversation_properties_merge() {
202 let body = json!({
203 "properties": {"a": 1},
204 "threadProperties": {"awareness_conversationLiveState:0": live_state("Active", NOW + 600)},
205 });
206 let merged = thread_properties(&body);
207 assert!(merged.get("a").is_some());
208 assert!(live_meeting("t", &merged, NOW).is_some());
209 }
210 }
@@ -0,0 +1,210 @@
1use serde_json::Value;
2use session::{Request, Session};
3
4use crate::error::Result;
5use crate::relay::ic3_scope;
6use crate::signaling::{CHATSVC_REGION, MeetingTarget};
7
8const LIVE_STATE_PREFIX: &str = "awareness_conversationLiveState";
9const MEETING_PROPERTY: &str = "meeting";
10const ACTIVE_STATUS: &str = "Active";
11const MILLISECOND_EPOCH_FLOOR: i64 = 1_000_000_000_000;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct LiveMeeting {
15 pub thread_id: String,
16 pub conversation_url: Option<String>,
17 pub expiration: Option<i64>,
18 pub organizer_id: Option<String>,
19 pub tenant_id: Option<String>,
20 pub meeting_code: Option<String>,
21 pub passcode: Option<String>,
22}
23
24impl LiveMeeting {
25 pub fn is_running(&self, now_unix: i64) -> bool {
26 self.expiration.is_none_or(|expires| expires > now_unix)
27 }
28
29 pub fn target(&self) -> Option<MeetingTarget> {
30 let meeting_data = self.meeting_code.as_ref().map(|code| {
31 serde_json::json!({"meetingCode": code, "passcode": self.passcode})
32 });
33 Some(MeetingTarget {
34 thread_id: self.thread_id.clone(),
35 tenant_id: self.tenant_id.clone()?,
36 organizer_id: self.organizer_id.clone()?,
37 meeting_data,
38 })
39 }
40}
41
42fn as_object(value: &Value) -> Option<Value> {
43 match value {
44 Value::String(text) => serde_json::from_str(text).ok(),
45 Value::Object(_) => Some(value.clone()),
46 _ => None,
47 }
48}
49
50fn expiration_seconds(value: &Value) -> Option<i64> {
51 let raw = value.as_i64().or_else(|| value.as_str()?.parse().ok())?;
52 Some(if raw >= MILLISECOND_EPOCH_FLOOR { raw / 1000 } else { raw })
53}
54
55fn property_text(value: &Value, key: &str) -> Option<String> {
56 value[key].as_str().filter(|text| !text.is_empty()).map(str::to_owned)
57}
58
59fn thread_properties(body: &Value) -> Value {
60 let mut merged = serde_json::Map::new();
61 for key in ["properties", "threadProperties"] {
62 if let Some(properties) = body.get(key).and_then(Value::as_object) {
63 merged.extend(properties.clone());
64 }
65 }
66 Value::Object(merged)
67}
68
69pub fn live_meeting(thread_id: &str, properties: &Value, now_unix: i64) -> Option<LiveMeeting> {
70 let meeting = properties.get(MEETING_PROPERTY).and_then(as_object);
71 let entries = properties.as_object()?;
72 entries
73 .iter()
74 .filter(|(key, _)| key.starts_with(LIVE_STATE_PREFIX))
75 .filter_map(|(_, value)| as_object(value))
76 .filter(|state| state["status"].as_str() == Some(ACTIVE_STATUS))
77 .filter_map(|state| {
78 let expiration = expiration_seconds(&state["expiration"]);
79 if expiration.is_some_and(|expires| expires <= now_unix) {
80 return None;
81 }
82 let info = &state["meetingInfo"];
83 let fallback = meeting.as_ref();
84 Some(LiveMeeting {
85 thread_id: thread_id.to_owned(),
86 conversation_url: property_text(&state, "conversationUrl"),
87 expiration,
88 organizer_id: property_text(info, "organizerId")
89 .or_else(|| fallback.and_then(|meeting| property_text(meeting, "organizerId"))),
90 tenant_id: property_text(info, "tenantId")
91 .or_else(|| fallback.and_then(|meeting| property_text(meeting, "tenantId"))),
92 meeting_code: property_text(&state["meetingData"], "meetingCode"),
93 passcode: property_text(&state["meetingData"], "passcode"),
94 })
95 })
96 .next()
97}
98
99pub async fn fetch_live_meeting(session: &Session, thread_id: &str) -> Result<Option<LiveMeeting>> {
100 let url = format!(
101 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
102 thread_id.replace(':', "%3A").replace('@', "%40")
103 );
104 let response = session.send(Request::get(url), &ic3_scope()).await?;
105 let now = std::time::SystemTime::now()
106 .duration_since(std::time::UNIX_EPOCH)
107 .map_or(0, |elapsed| elapsed.as_secs() as i64);
108 Ok(live_meeting(thread_id, &thread_properties(&response.body), now))
109}
110
111#[cfg(test)]
112mod tests {
113 use serde_json::json;
114
115 use super::*;
116
117 const NOW: i64 = 1_791_600_000;
118
119 fn live_state(status: &str, expiration: i64) -> String {
120 json!({
121 "conversationUrl": "https://conv/1",
122 "conversationId": "1",
123 "status": status,
124 "expiration": expiration,
125 "conversationType": "scheduledMeeting",
126 "meetingInfo": {"organizerId": "org-1", "tenantId": "tenant-1"},
127 "meetingData": {"meetingCode": "123", "passcode": "pw"},
128 })
129 .to_string()
130 }
131
132 #[test]
133 fn an_active_unexpired_state_is_a_running_meeting() {
134 let properties = json!({"awareness_conversationLiveState:0": live_state("Active", NOW + 600)});
135 let meeting = live_meeting("19:m@thread.v2", &properties, NOW).unwrap();
136 assert_eq!(meeting.organizer_id.as_deref(), Some("org-1"));
137 assert_eq!(meeting.conversation_url.as_deref(), Some("https://conv/1"));
138 let target = meeting.target().unwrap();
139 assert_eq!(target.thread_id, "19:m@thread.v2");
140 assert_eq!(target.tenant_id, "tenant-1");
141 assert_eq!(target.meeting_data.unwrap()["meetingCode"], "123");
142 }
143
144 #[test]
145 fn no_state_expired_or_ended_means_no_join_button() {
146 assert!(live_meeting("t", &json!({}), NOW).is_none());
147 assert!(live_meeting("t", &json!({"topic": "x"}), NOW).is_none());
148 let expired = json!({"awareness_conversationLiveState:0": live_state("Active", NOW - 1)});
149 assert!(live_meeting("t", &expired, NOW).is_none());
150 let ended = json!({"awareness_conversationLiveState:0": live_state("Ended", NOW + 600)});
151 assert!(live_meeting("t", &ended, NOW).is_none());
152 }
153
154 #[test]
155 fn a_known_meeting_stops_running_when_it_expires() {
156 let properties = json!({"awareness_conversationLiveState:0": live_state("Active", NOW + 600)});
157 let meeting = live_meeting("t", &properties, NOW).unwrap();
158 assert!(meeting.is_running(NOW + 599));
159 assert!(!meeting.is_running(NOW + 600));
160 }
161
162 #[test]
163 fn a_second_parallel_state_still_counts() {
164 let properties = json!({
165 "awareness_conversationLiveState:0": live_state("Ended", NOW + 600),
166 "awareness_conversationLiveState:1": live_state("Active", NOW + 600),
167 });
168 assert!(live_meeting("t", &properties, NOW).is_some());
169 }
170
171 #[test]
172 fn expiration_in_milliseconds_is_understood() {
173 let properties = json!({"awareness_conversationLiveState": live_state("Active", (NOW + 600) * 1000)});
174 assert!(live_meeting("t", &properties, NOW).is_some());
175 let past = json!({"awareness_conversationLiveState": live_state("Active", (NOW - 600) * 1000)});
176 assert!(live_meeting("t", &past, NOW).is_none());
177 }
178
179 #[test]
180 fn meeting_info_falls_back_to_the_meeting_property() {
181 let mut state: Value = serde_json::from_str(&live_state("Active", NOW + 600)).unwrap();
182 state.as_object_mut().unwrap().remove("meetingInfo");
183 let properties = json!({
184 "awareness_conversationLiveState:0": state.to_string(),
185 "meeting": json!({"organizerId": "org-2", "tenantId": "tenant-2"}).to_string(),
186 });
187 let meeting = live_meeting("t", &properties, NOW).unwrap();
188 assert_eq!(meeting.organizer_id.as_deref(), Some("org-2"));
189 assert_eq!(meeting.tenant_id.as_deref(), Some("tenant-2"));
190 }
191
192 #[test]
193 fn without_organizer_or_tenant_there_is_no_join_target() {
194 let state = json!({"status": "Active", "expiration": NOW + 600});
195 let properties = json!({"awareness_conversationLiveState:0": state.to_string()});
196 let meeting = live_meeting("t", &properties, NOW).unwrap();
197 assert!(meeting.target().is_none());
198 }
199
200 #[test]
201 fn thread_and_conversation_properties_merge() {
202 let body = json!({
203 "properties": {"a": 1},
204 "threadProperties": {"awareness_conversationLiveState:0": live_state("Active", NOW + 600)},
205 });
206 let merged = thread_properties(&body);
207 assert!(merged.get("a").is_some());
208 assert!(live_meeting("t", &merged, NOW).is_some());
209 }
210}
crates/calling/src/mute.rs +12 −0
@@ -30,6 +30,10 @@ impl MuteEffect {
30 30 endpoint_is_muted: muted,
31 31 }
32 32 }
33
34 pub fn initial(is_meeting: bool) -> Self {
35 MuteEffect::for_muted(is_meeting)
36 }
33 37 }
34 38
35 39 #[cfg(test)]
@@ -54,4 +58,12 @@ mod tests {
54 58 assert!(open.track_enabled);
55 59 assert!(!open.endpoint_is_muted);
56 60 }
61
62 #[test]
63 fn meetings_start_muted_and_other_calls_do_not() {
64 let meeting = MuteEffect::initial(true);
65 assert!(meeting.muted && !meeting.track_enabled && meeting.endpoint_is_muted);
66 let direct = MuteEffect::initial(false);
67 assert!(!direct.muted && direct.track_enabled && !direct.endpoint_is_muted);
68 }
57 69 }
@@ -30,6 +30,10 @@ impl MuteEffect {
30 endpoint_is_muted: muted,
30 endpoint_is_muted: muted,
31 }
31 }
32 }
32 }
33
34 pub fn initial(is_meeting: bool) -> Self {
35 MuteEffect::for_muted(is_meeting)
36 }
33}
37}
34
38
35#[cfg(test)]
39#[cfg(test)]
@@ -54,4 +58,12 @@ mod tests {
54 assert!(open.track_enabled);
58 assert!(open.track_enabled);
55 assert!(!open.endpoint_is_muted);
59 assert!(!open.endpoint_is_muted);
56 }
60 }
61
62 #[test]
63 fn meetings_start_muted_and_other_calls_do_not() {
64 let meeting = MuteEffect::initial(true);
65 assert!(meeting.muted && !meeting.track_enabled && meeting.endpoint_is_muted);
66 let direct = MuteEffect::initial(false);
67 assert!(!direct.muted && direct.track_enabled && !direct.endpoint_is_muted);
68 }
57}
69}
crates/calling/src/push.rs added +240 −0
@@ -0,0 +1,240 @@
1 use std::collections::BTreeMap;
2 use std::io::Read;
3
4 use base64::Engine;
5 use flate2::read::{DeflateDecoder, GzDecoder, ZlibDecoder};
6 use serde_json::Value;
7
8 use crate::error::{Error, Result};
9
10 pub const EVT_TEAMS_CALL: i64 = 107;
11 pub const EVT_GROUP_VIDEO_CALL: i64 = 109;
12 const MAX_INFLATED_BYTES: u64 = 8 * 1024 * 1024;
13 const VIDEO_MODALITY: &str = "Video";
14
15 #[derive(Debug, Clone, PartialEq, Eq)]
16 pub struct Caller {
17 pub mri: String,
18 pub display_name: String,
19 }
20
21 #[derive(Debug, Clone, PartialEq)]
22 pub struct CallNotification {
23 pub call_id: String,
24 pub participant_id: String,
25 pub caller: Caller,
26 pub links: BTreeMap<String, String>,
27 pub offer_sdp: Option<String>,
28 pub controller_name: Option<String>,
29 pub conversation_controller: Option<String>,
30 pub is_multi_party: bool,
31 pub subject: Option<String>,
32 pub thread_id: Option<String>,
33 pub video: bool,
34 }
35
36 impl CallNotification {
37 pub fn dedupe_key(&self) -> (String, String) {
38 (self.call_id.clone(), self.participant_id.clone())
39 }
40 }
41
42 #[derive(Debug, Clone, PartialEq)]
43 pub enum PushEvent {
44 IncomingCall(Box<CallNotification>),
45 Other(i64),
46 }
47
48 /// `body` is the raw Trouter request body: `{evt, gp}` or `{evt, cp}`.
49 pub fn decode_push(body: &str) -> Result<PushEvent> {
50 let push: Value = serde_json::from_str(body).map_err(|error| Error::Callback(format!("push is not JSON: {error}")))?;
51 let evt = push["evt"].as_i64().ok_or_else(|| Error::Callback("push without evt".into()))?;
52 if evt != EVT_TEAMS_CALL && evt != EVT_GROUP_VIDEO_CALL {
53 return Ok(PushEvent::Other(evt));
54 }
55 let payload = payload_of(&push)?;
56 Ok(PushEvent::IncomingCall(Box::new(notification_from(&payload, evt)?)))
57 }
58
59 fn payload_of(push: &Value) -> Result<Value> {
60 if let Some(plain) = push["gp"].as_str() {
61 return serde_json::from_slice(&base64_bytes(plain)?)
62 .map_err(|error| Error::Callback(format!("gp is not JSON: {error}")));
63 }
64 if let Some(compressed) = push["cp"].as_str() {
65 let bytes = base64_bytes(compressed)?;
66 return inflated_json(&bytes).ok_or_else(|| Error::Callback("cp is not deflated JSON".into()));
67 }
68 Err(Error::Callback("push has neither gp nor cp".into()))
69 }
70
71 fn base64_bytes(text: &str) -> Result<Vec<u8>> {
72 base64::engine::general_purpose::STANDARD
73 .decode(text.trim())
74 .map_err(|error| Error::Callback(format!("push payload is not base64: {error}")))
75 }
76
77 fn inflated_json(bytes: &[u8]) -> Option<Value> {
78 json_from(ZlibDecoder::new(bytes))
79 .or_else(|| json_from(DeflateDecoder::new(bytes)))
80 .or_else(|| json_from(GzDecoder::new(bytes)))
81 }
82
83 fn json_from(reader: impl Read) -> Option<Value> {
84 serde_json::from_str(&read_all(reader)?).ok()
85 }
86
87 fn read_all(reader: impl Read) -> Option<String> {
88 let mut text = String::new();
89 reader.take(MAX_INFLATED_BYTES).read_to_string(&mut text).ok()?;
90 Some(text)
91 }
92
93 fn text_of(value: &Value) -> Option<String> {
94 value.as_str().filter(|text| !text.is_empty()).map(str::to_owned)
95 }
96
97 fn notification_from(payload: &Value, evt: i64) -> Result<CallNotification> {
98 let notification = &payload["callNotification"];
99 let caller_mri = text_of(&notification["from"]["id"])
100 .ok_or_else(|| Error::Callback("call notification without caller".into()))?;
101 let links: BTreeMap<String, String> = notification["links"]
102 .as_object()
103 .map(|links| {
104 links
105 .iter()
106 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
107 .collect()
108 })
109 .unwrap_or_default();
110 let attach = links
111 .get("attach")
112 .ok_or_else(|| Error::Callback("call notification without attach link".into()))?;
113 let participant_id = text_of(&payload["debugContent"]["participantId"])
114 .or_else(|| text_of(&notification["to"]["participantId"]))
115 .unwrap_or_default();
116 let call_id = text_of(&payload["debugContent"]["callId"]).unwrap_or_else(|| attach.clone());
117 let modalities_have_video = notification["callModalities"]
118 .as_array()
119 .is_some_and(|items| items.iter().any(|item| item.as_str() == Some(VIDEO_MODALITY)));
120 let invitation = &payload["conversationInvitation"];
121 Ok(CallNotification {
122 call_id,
123 participant_id,
124 caller: Caller {
125 mri: caller_mri,
126 display_name: notification["from"]["displayName"].as_str().unwrap_or_default().to_owned(),
127 },
128 links,
129 offer_sdp: text_of(&notification["mediaContent"]["blob"]),
130 controller_name: text_of(&notification["controllerName"]),
131 conversation_controller: text_of(&invitation["conversationController"]),
132 is_multi_party: invitation["isMultiParty"].as_bool().unwrap_or(false),
133 subject: text_of(&invitation["subject"]),
134 thread_id: text_of(&payload["groupChat"]["threadId"]),
135 video: evt == EVT_GROUP_VIDEO_CALL || modalities_have_video,
136 })
137 }
138
139 #[cfg(test)]
140 mod tests {
141 use std::io::Write;
142
143 use flate2::Compression;
144 use flate2::write::{DeflateEncoder, ZlibEncoder};
145 use serde_json::json;
146
147 use super::*;
148
149 fn payload() -> Value {
150 json!({
151 "callNotification": {
152 "from": {"id": "8:orgid:caller", "displayName": "Cara"},
153 "to": {"participantId": "to-participant"},
154 "links": {"attach": "https://cc.skype.com/attach", "redirection": "https://cc.skype.com/redirect"},
155 "controllerName": "mixer",
156 },
157 "conversationInvitation": {"conversationController": "https://conv.skype.com/c", "isMultiParty": false},
158 "groupChat": {"threadId": "19:a_b@unq.gbl.spaces"},
159 "debugContent": {"callId": "call-1", "participantId": "participant-1"},
160 })
161 }
162
163 fn base64_of(bytes: &[u8]) -> String {
164 base64::engine::general_purpose::STANDARD.encode(bytes)
165 }
166
167 fn gp_body(payload: &Value) -> String {
168 json!({"evt": 107, "gp": base64_of(payload.to_string().as_bytes())}).to_string()
169 }
170
171 fn incoming(body: &str) -> CallNotification {
172 match decode_push(body).unwrap() {
173 PushEvent::IncomingCall(notification) => *notification,
174 other => panic!("not a call: {other:?}"),
175 }
176 }
177
178 #[test]
179 fn a_plain_push_decodes_to_the_notification() {
180 let notification = incoming(&gp_body(&payload()));
181 assert_eq!(notification.caller, Caller { mri: "8:orgid:caller".into(), display_name: "Cara".into() });
182 assert_eq!(notification.call_id, "call-1");
183 assert_eq!(notification.participant_id, "participant-1");
184 assert_eq!(notification.links["attach"], "https://cc.skype.com/attach");
185 assert_eq!(notification.thread_id.as_deref(), Some("19:a_b@unq.gbl.spaces"));
186 assert_eq!(notification.conversation_controller.as_deref(), Some("https://conv.skype.com/c"));
187 assert!(!notification.video && !notification.is_multi_party);
188 assert!(notification.offer_sdp.is_none());
189 assert_eq!(notification.dedupe_key(), ("call-1".to_owned(), "participant-1".to_owned()));
190 }
191
192 #[test]
193 fn compressed_pushes_decode_with_zlib_and_raw_deflate() {
194 let text = payload().to_string();
195 let mut zlib = ZlibEncoder::new(Vec::new(), Compression::default());
196 zlib.write_all(text.as_bytes()).unwrap();
197 let mut raw = DeflateEncoder::new(Vec::new(), Compression::default());
198 raw.write_all(text.as_bytes()).unwrap();
199 for compressed in [zlib.finish().unwrap(), raw.finish().unwrap()] {
200 let body = json!({"evt": 107, "cp": base64_of(&compressed)}).to_string();
201 assert_eq!(incoming(&body).call_id, "call-1");
202 }
203 }
204
205 #[test]
206 fn group_video_pushes_and_video_modalities_are_video_calls() {
207 let body = json!({"evt": 109, "gp": base64_of(payload().to_string().as_bytes())}).to_string();
208 assert!(incoming(&body).video);
209 let mut with_video = payload();
210 with_video["callNotification"]["callModalities"] = json!(["Audio", "Video"]);
211 assert!(incoming(&gp_body(&with_video)).video);
212 }
213
214 #[test]
215 fn an_offer_in_the_push_is_kept() {
216 let mut with_offer = payload();
217 with_offer["callNotification"]["mediaContent"] = json!({"blob": "v=0\r\n"});
218 assert_eq!(incoming(&gp_body(&with_offer)).offer_sdp.as_deref(), Some("v=0\r\n"));
219 }
220
221 #[test]
222 fn other_events_are_passed_on_without_decoding() {
223 assert_eq!(decode_push(r#"{"evt":115,"cp":"x"}"#).unwrap(), PushEvent::Other(115));
224 assert_eq!(decode_push(r#"{"evt":116}"#).unwrap(), PushEvent::Other(116));
225 }
226
227 #[test]
228 fn broken_pushes_are_errors() {
229 assert!(decode_push("garbage").is_err());
230 assert!(decode_push(r#"{"gp":"x"}"#).is_err());
231 assert!(decode_push(r#"{"evt":107}"#).is_err());
232 assert!(decode_push(r#"{"evt":107,"gp":"!!"}"#).is_err());
233 let mut without_attach = payload();
234 without_attach["callNotification"]["links"] = json!({});
235 assert!(decode_push(&gp_body(&without_attach)).is_err());
236 let mut without_caller = payload();
237 without_caller["callNotification"]["from"] = json!({});
238 assert!(decode_push(&gp_body(&without_caller)).is_err());
239 }
240 }
@@ -0,0 +1,240 @@
1use std::collections::BTreeMap;
2use std::io::Read;
3
4use base64::Engine;
5use flate2::read::{DeflateDecoder, GzDecoder, ZlibDecoder};
6use serde_json::Value;
7
8use crate::error::{Error, Result};
9
10pub const EVT_TEAMS_CALL: i64 = 107;
11pub const EVT_GROUP_VIDEO_CALL: i64 = 109;
12const MAX_INFLATED_BYTES: u64 = 8 * 1024 * 1024;
13const VIDEO_MODALITY: &str = "Video";
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Caller {
17 pub mri: String,
18 pub display_name: String,
19}
20
21#[derive(Debug, Clone, PartialEq)]
22pub struct CallNotification {
23 pub call_id: String,
24 pub participant_id: String,
25 pub caller: Caller,
26 pub links: BTreeMap<String, String>,
27 pub offer_sdp: Option<String>,
28 pub controller_name: Option<String>,
29 pub conversation_controller: Option<String>,
30 pub is_multi_party: bool,
31 pub subject: Option<String>,
32 pub thread_id: Option<String>,
33 pub video: bool,
34}
35
36impl CallNotification {
37 pub fn dedupe_key(&self) -> (String, String) {
38 (self.call_id.clone(), self.participant_id.clone())
39 }
40}
41
42#[derive(Debug, Clone, PartialEq)]
43pub enum PushEvent {
44 IncomingCall(Box<CallNotification>),
45 Other(i64),
46}
47
48/// `body` is the raw Trouter request body: `{evt, gp}` or `{evt, cp}`.
49pub fn decode_push(body: &str) -> Result<PushEvent> {
50 let push: Value = serde_json::from_str(body).map_err(|error| Error::Callback(format!("push is not JSON: {error}")))?;
51 let evt = push["evt"].as_i64().ok_or_else(|| Error::Callback("push without evt".into()))?;
52 if evt != EVT_TEAMS_CALL && evt != EVT_GROUP_VIDEO_CALL {
53 return Ok(PushEvent::Other(evt));
54 }
55 let payload = payload_of(&push)?;
56 Ok(PushEvent::IncomingCall(Box::new(notification_from(&payload, evt)?)))
57}
58
59fn payload_of(push: &Value) -> Result<Value> {
60 if let Some(plain) = push["gp"].as_str() {
61 return serde_json::from_slice(&base64_bytes(plain)?)
62 .map_err(|error| Error::Callback(format!("gp is not JSON: {error}")));
63 }
64 if let Some(compressed) = push["cp"].as_str() {
65 let bytes = base64_bytes(compressed)?;
66 return inflated_json(&bytes).ok_or_else(|| Error::Callback("cp is not deflated JSON".into()));
67 }
68 Err(Error::Callback("push has neither gp nor cp".into()))
69}
70
71fn base64_bytes(text: &str) -> Result<Vec<u8>> {
72 base64::engine::general_purpose::STANDARD
73 .decode(text.trim())
74 .map_err(|error| Error::Callback(format!("push payload is not base64: {error}")))
75}
76
77fn inflated_json(bytes: &[u8]) -> Option<Value> {
78 json_from(ZlibDecoder::new(bytes))
79 .or_else(|| json_from(DeflateDecoder::new(bytes)))
80 .or_else(|| json_from(GzDecoder::new(bytes)))
81}
82
83fn json_from(reader: impl Read) -> Option<Value> {
84 serde_json::from_str(&read_all(reader)?).ok()
85}
86
87fn read_all(reader: impl Read) -> Option<String> {
88 let mut text = String::new();
89 reader.take(MAX_INFLATED_BYTES).read_to_string(&mut text).ok()?;
90 Some(text)
91}
92
93fn text_of(value: &Value) -> Option<String> {
94 value.as_str().filter(|text| !text.is_empty()).map(str::to_owned)
95}
96
97fn notification_from(payload: &Value, evt: i64) -> Result<CallNotification> {
98 let notification = &payload["callNotification"];
99 let caller_mri = text_of(&notification["from"]["id"])
100 .ok_or_else(|| Error::Callback("call notification without caller".into()))?;
101 let links: BTreeMap<String, String> = notification["links"]
102 .as_object()
103 .map(|links| {
104 links
105 .iter()
106 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
107 .collect()
108 })
109 .unwrap_or_default();
110 let attach = links
111 .get("attach")
112 .ok_or_else(|| Error::Callback("call notification without attach link".into()))?;
113 let participant_id = text_of(&payload["debugContent"]["participantId"])
114 .or_else(|| text_of(&notification["to"]["participantId"]))
115 .unwrap_or_default();
116 let call_id = text_of(&payload["debugContent"]["callId"]).unwrap_or_else(|| attach.clone());
117 let modalities_have_video = notification["callModalities"]
118 .as_array()
119 .is_some_and(|items| items.iter().any(|item| item.as_str() == Some(VIDEO_MODALITY)));
120 let invitation = &payload["conversationInvitation"];
121 Ok(CallNotification {
122 call_id,
123 participant_id,
124 caller: Caller {
125 mri: caller_mri,
126 display_name: notification["from"]["displayName"].as_str().unwrap_or_default().to_owned(),
127 },
128 links,
129 offer_sdp: text_of(&notification["mediaContent"]["blob"]),
130 controller_name: text_of(&notification["controllerName"]),
131 conversation_controller: text_of(&invitation["conversationController"]),
132 is_multi_party: invitation["isMultiParty"].as_bool().unwrap_or(false),
133 subject: text_of(&invitation["subject"]),
134 thread_id: text_of(&payload["groupChat"]["threadId"]),
135 video: evt == EVT_GROUP_VIDEO_CALL || modalities_have_video,
136 })
137}
138
139#[cfg(test)]
140mod tests {
141 use std::io::Write;
142
143 use flate2::Compression;
144 use flate2::write::{DeflateEncoder, ZlibEncoder};
145 use serde_json::json;
146
147 use super::*;
148
149 fn payload() -> Value {
150 json!({
151 "callNotification": {
152 "from": {"id": "8:orgid:caller", "displayName": "Cara"},
153 "to": {"participantId": "to-participant"},
154 "links": {"attach": "https://cc.skype.com/attach", "redirection": "https://cc.skype.com/redirect"},
155 "controllerName": "mixer",
156 },
157 "conversationInvitation": {"conversationController": "https://conv.skype.com/c", "isMultiParty": false},
158 "groupChat": {"threadId": "19:a_b@unq.gbl.spaces"},
159 "debugContent": {"callId": "call-1", "participantId": "participant-1"},
160 })
161 }
162
163 fn base64_of(bytes: &[u8]) -> String {
164 base64::engine::general_purpose::STANDARD.encode(bytes)
165 }
166
167 fn gp_body(payload: &Value) -> String {
168 json!({"evt": 107, "gp": base64_of(payload.to_string().as_bytes())}).to_string()
169 }
170
171 fn incoming(body: &str) -> CallNotification {
172 match decode_push(body).unwrap() {
173 PushEvent::IncomingCall(notification) => *notification,
174 other => panic!("not a call: {other:?}"),
175 }
176 }
177
178 #[test]
179 fn a_plain_push_decodes_to_the_notification() {
180 let notification = incoming(&gp_body(&payload()));
181 assert_eq!(notification.caller, Caller { mri: "8:orgid:caller".into(), display_name: "Cara".into() });
182 assert_eq!(notification.call_id, "call-1");
183 assert_eq!(notification.participant_id, "participant-1");
184 assert_eq!(notification.links["attach"], "https://cc.skype.com/attach");
185 assert_eq!(notification.thread_id.as_deref(), Some("19:a_b@unq.gbl.spaces"));
186 assert_eq!(notification.conversation_controller.as_deref(), Some("https://conv.skype.com/c"));
187 assert!(!notification.video && !notification.is_multi_party);
188 assert!(notification.offer_sdp.is_none());
189 assert_eq!(notification.dedupe_key(), ("call-1".to_owned(), "participant-1".to_owned()));
190 }
191
192 #[test]
193 fn compressed_pushes_decode_with_zlib_and_raw_deflate() {
194 let text = payload().to_string();
195 let mut zlib = ZlibEncoder::new(Vec::new(), Compression::default());
196 zlib.write_all(text.as_bytes()).unwrap();
197 let mut raw = DeflateEncoder::new(Vec::new(), Compression::default());
198 raw.write_all(text.as_bytes()).unwrap();
199 for compressed in [zlib.finish().unwrap(), raw.finish().unwrap()] {
200 let body = json!({"evt": 107, "cp": base64_of(&compressed)}).to_string();
201 assert_eq!(incoming(&body).call_id, "call-1");
202 }
203 }
204
205 #[test]
206 fn group_video_pushes_and_video_modalities_are_video_calls() {
207 let body = json!({"evt": 109, "gp": base64_of(payload().to_string().as_bytes())}).to_string();
208 assert!(incoming(&body).video);
209 let mut with_video = payload();
210 with_video["callNotification"]["callModalities"] = json!(["Audio", "Video"]);
211 assert!(incoming(&gp_body(&with_video)).video);
212 }
213
214 #[test]
215 fn an_offer_in_the_push_is_kept() {
216 let mut with_offer = payload();
217 with_offer["callNotification"]["mediaContent"] = json!({"blob": "v=0\r\n"});
218 assert_eq!(incoming(&gp_body(&with_offer)).offer_sdp.as_deref(), Some("v=0\r\n"));
219 }
220
221 #[test]
222 fn other_events_are_passed_on_without_decoding() {
223 assert_eq!(decode_push(r#"{"evt":115,"cp":"x"}"#).unwrap(), PushEvent::Other(115));
224 assert_eq!(decode_push(r#"{"evt":116}"#).unwrap(), PushEvent::Other(116));
225 }
226
227 #[test]
228 fn broken_pushes_are_errors() {
229 assert!(decode_push("garbage").is_err());
230 assert!(decode_push(r#"{"gp":"x"}"#).is_err());
231 assert!(decode_push(r#"{"evt":107}"#).is_err());
232 assert!(decode_push(r#"{"evt":107,"gp":"!!"}"#).is_err());
233 let mut without_attach = payload();
234 without_attach["callNotification"]["links"] = json!({});
235 assert!(decode_push(&gp_body(&without_attach)).is_err());
236 let mut without_caller = payload();
237 without_caller["callNotification"]["from"] = json!({});
238 assert!(decode_push(&gp_body(&without_caller)).is_err());
239 }
240}
crates/calling/src/renegotiation.rs added +155 −0
@@ -0,0 +1,155 @@
1 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2 pub enum MediaPath {
3 Pending,
4 Direct,
5 Mixer,
6 }
7
8 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9 pub enum MediaAction {
10 ApplyAnswer,
11 Escalate,
12 ApplyOnNewPeer,
13 AnswerOnNewPeer,
14 AnswerOnSamePeer,
15 RejectGlare,
16 Ignore,
17 }
18
19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
20 pub struct MediaNegotiator {
21 path: MediaPath,
22 own_offer_pending: bool,
23 }
24
25 impl Default for MediaNegotiator {
26 fn default() -> Self {
27 MediaNegotiator {
28 path: MediaPath::Pending,
29 own_offer_pending: false,
30 }
31 }
32 }
33
34 impl MediaNegotiator {
35 pub fn path(&self) -> MediaPath {
36 self.path
37 }
38
39 pub fn answered_incoming(&mut self, from_mixer: bool) {
40 self.path = if from_mixer { MediaPath::Mixer } else { MediaPath::Direct };
41 }
42
43 pub fn on_acceptance(&mut self, from_mixer: bool) -> MediaAction {
44 match (self.path, from_mixer) {
45 (MediaPath::Pending, _) => {
46 self.path = if from_mixer { MediaPath::Mixer } else { MediaPath::Direct };
47 MediaAction::ApplyAnswer
48 }
49 (MediaPath::Direct, true) if !self.own_offer_pending => {
50 self.own_offer_pending = true;
51 MediaAction::Escalate
52 }
53 _ => MediaAction::Ignore,
54 }
55 }
56
57 pub fn on_media_answer(&mut self) -> MediaAction {
58 if !self.own_offer_pending {
59 return MediaAction::Ignore;
60 }
61 self.own_offer_pending = false;
62 self.path = MediaPath::Mixer;
63 MediaAction::ApplyOnNewPeer
64 }
65
66 pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {
67 if self.own_offer_pending {
68 return MediaAction::RejectGlare;
69 }
70 if escalation {
71 self.path = MediaPath::Mixer;
72 }
73 if new_offer || escalation {
74 MediaAction::AnswerOnNewPeer
75 } else {
76 MediaAction::AnswerOnSamePeer
77 }
78 }
79
80 pub fn escalation_failed(&mut self) {
81 self.own_offer_pending = false;
82 }
83 }
84
85 #[cfg(test)]
86 mod tests {
87 use super::*;
88
89 #[test]
90 fn the_first_answer_decides_the_path() {
91 let mut direct = MediaNegotiator::default();
92 assert_eq!(direct.on_acceptance(false), MediaAction::ApplyAnswer);
93 assert_eq!(direct.path(), MediaPath::Direct);
94 let mut mixer = MediaNegotiator::default();
95 assert_eq!(mixer.on_acceptance(true), MediaAction::ApplyAnswer);
96 assert_eq!(mixer.path(), MediaPath::Mixer);
97 }
98
99 #[test]
100 fn a_mixer_answer_during_a_direct_call_escalates_once() {
101 let mut negotiator = MediaNegotiator::default();
102 negotiator.on_acceptance(false);
103 assert_eq!(negotiator.on_acceptance(true), MediaAction::Escalate);
104 assert_eq!(negotiator.on_acceptance(true), MediaAction::Ignore);
105 assert_eq!(negotiator.on_media_answer(), MediaAction::ApplyOnNewPeer);
106 assert_eq!(negotiator.path(), MediaPath::Mixer);
107 assert_eq!(negotiator.on_acceptance(true), MediaAction::Ignore);
108 }
109
110 #[test]
111 fn later_acceptances_on_a_settled_path_are_ignored() {
112 let mut mixer = MediaNegotiator::default();
113 mixer.on_acceptance(true);
114 assert_eq!(mixer.on_acceptance(true), MediaAction::Ignore);
115 let mut direct = MediaNegotiator::default();
116 direct.on_acceptance(false);
117 assert_eq!(direct.on_acceptance(false), MediaAction::Ignore);
118 }
119
120 #[test]
121 fn a_media_answer_without_our_offer_is_ignored() {
122 let mut negotiator = MediaNegotiator::default();
123 assert_eq!(negotiator.on_media_answer(), MediaAction::Ignore);
124 negotiator.on_acceptance(false);
125 assert_eq!(negotiator.on_media_answer(), MediaAction::Ignore);
126 }
127
128 #[test]
129 fn an_incoming_escalation_gets_a_new_peer_and_moves_to_the_mixer() {
130 let mut negotiator = MediaNegotiator::default();
131 negotiator.answered_incoming(false);
132 assert_eq!(negotiator.path(), MediaPath::Direct);
133 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::AnswerOnNewPeer);
134 assert_eq!(negotiator.path(), MediaPath::Mixer);
135 }
136
137 #[test]
138 fn a_plain_renegotiation_stays_on_the_same_peer() {
139 let mut negotiator = MediaNegotiator::default();
140 negotiator.answered_incoming(true);
141 assert_eq!(negotiator.on_renegotiation(false, false), MediaAction::AnswerOnSamePeer);
142 assert_eq!(negotiator.on_renegotiation(true, false), MediaAction::AnswerOnNewPeer);
143 assert_eq!(negotiator.path(), MediaPath::Mixer);
144 }
145
146 #[test]
147 fn two_offers_at_once_are_glare() {
148 let mut negotiator = MediaNegotiator::default();
149 negotiator.on_acceptance(false);
150 negotiator.on_acceptance(true);
151 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::RejectGlare);
152 negotiator.escalation_failed();
153 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::AnswerOnNewPeer);
154 }
155 }
@@ -0,0 +1,155 @@
1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2pub enum MediaPath {
3 Pending,
4 Direct,
5 Mixer,
6}
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum MediaAction {
10 ApplyAnswer,
11 Escalate,
12 ApplyOnNewPeer,
13 AnswerOnNewPeer,
14 AnswerOnSamePeer,
15 RejectGlare,
16 Ignore,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct MediaNegotiator {
21 path: MediaPath,
22 own_offer_pending: bool,
23}
24
25impl Default for MediaNegotiator {
26 fn default() -> Self {
27 MediaNegotiator {
28 path: MediaPath::Pending,
29 own_offer_pending: false,
30 }
31 }
32}
33
34impl MediaNegotiator {
35 pub fn path(&self) -> MediaPath {
36 self.path
37 }
38
39 pub fn answered_incoming(&mut self, from_mixer: bool) {
40 self.path = if from_mixer { MediaPath::Mixer } else { MediaPath::Direct };
41 }
42
43 pub fn on_acceptance(&mut self, from_mixer: bool) -> MediaAction {
44 match (self.path, from_mixer) {
45 (MediaPath::Pending, _) => {
46 self.path = if from_mixer { MediaPath::Mixer } else { MediaPath::Direct };
47 MediaAction::ApplyAnswer
48 }
49 (MediaPath::Direct, true) if !self.own_offer_pending => {
50 self.own_offer_pending = true;
51 MediaAction::Escalate
52 }
53 _ => MediaAction::Ignore,
54 }
55 }
56
57 pub fn on_media_answer(&mut self) -> MediaAction {
58 if !self.own_offer_pending {
59 return MediaAction::Ignore;
60 }
61 self.own_offer_pending = false;
62 self.path = MediaPath::Mixer;
63 MediaAction::ApplyOnNewPeer
64 }
65
66 pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {
67 if self.own_offer_pending {
68 return MediaAction::RejectGlare;
69 }
70 if escalation {
71 self.path = MediaPath::Mixer;
72 }
73 if new_offer || escalation {
74 MediaAction::AnswerOnNewPeer
75 } else {
76 MediaAction::AnswerOnSamePeer
77 }
78 }
79
80 pub fn escalation_failed(&mut self) {
81 self.own_offer_pending = false;
82 }
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88
89 #[test]
90 fn the_first_answer_decides_the_path() {
91 let mut direct = MediaNegotiator::default();
92 assert_eq!(direct.on_acceptance(false), MediaAction::ApplyAnswer);
93 assert_eq!(direct.path(), MediaPath::Direct);
94 let mut mixer = MediaNegotiator::default();
95 assert_eq!(mixer.on_acceptance(true), MediaAction::ApplyAnswer);
96 assert_eq!(mixer.path(), MediaPath::Mixer);
97 }
98
99 #[test]
100 fn a_mixer_answer_during_a_direct_call_escalates_once() {
101 let mut negotiator = MediaNegotiator::default();
102 negotiator.on_acceptance(false);
103 assert_eq!(negotiator.on_acceptance(true), MediaAction::Escalate);
104 assert_eq!(negotiator.on_acceptance(true), MediaAction::Ignore);
105 assert_eq!(negotiator.on_media_answer(), MediaAction::ApplyOnNewPeer);
106 assert_eq!(negotiator.path(), MediaPath::Mixer);
107 assert_eq!(negotiator.on_acceptance(true), MediaAction::Ignore);
108 }
109
110 #[test]
111 fn later_acceptances_on_a_settled_path_are_ignored() {
112 let mut mixer = MediaNegotiator::default();
113 mixer.on_acceptance(true);
114 assert_eq!(mixer.on_acceptance(true), MediaAction::Ignore);
115 let mut direct = MediaNegotiator::default();
116 direct.on_acceptance(false);
117 assert_eq!(direct.on_acceptance(false), MediaAction::Ignore);
118 }
119
120 #[test]
121 fn a_media_answer_without_our_offer_is_ignored() {
122 let mut negotiator = MediaNegotiator::default();
123 assert_eq!(negotiator.on_media_answer(), MediaAction::Ignore);
124 negotiator.on_acceptance(false);
125 assert_eq!(negotiator.on_media_answer(), MediaAction::Ignore);
126 }
127
128 #[test]
129 fn an_incoming_escalation_gets_a_new_peer_and_moves_to_the_mixer() {
130 let mut negotiator = MediaNegotiator::default();
131 negotiator.answered_incoming(false);
132 assert_eq!(negotiator.path(), MediaPath::Direct);
133 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::AnswerOnNewPeer);
134 assert_eq!(negotiator.path(), MediaPath::Mixer);
135 }
136
137 #[test]
138 fn a_plain_renegotiation_stays_on_the_same_peer() {
139 let mut negotiator = MediaNegotiator::default();
140 negotiator.answered_incoming(true);
141 assert_eq!(negotiator.on_renegotiation(false, false), MediaAction::AnswerOnSamePeer);
142 assert_eq!(negotiator.on_renegotiation(true, false), MediaAction::AnswerOnNewPeer);
143 assert_eq!(negotiator.path(), MediaPath::Mixer);
144 }
145
146 #[test]
147 fn two_offers_at_once_are_glare() {
148 let mut negotiator = MediaNegotiator::default();
149 negotiator.on_acceptance(false);
150 negotiator.on_acceptance(true);
151 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::RejectGlare);
152 negotiator.escalation_failed();
153 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::AnswerOnNewPeer);
154 }
155}
crates/calling/src/ring.rs added +129 −0
@@ -0,0 +1,129 @@
1 use std::time::{Duration, Instant};
2
3 use crate::end::EndKind;
4
5 pub const RING_TIMEOUT: Duration = Duration::from_secs(30);
6
7 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
8 pub enum RingEnd {
9 CallerCancelled,
10 AnsweredElsewhere,
11 Other,
12 TimedOut,
13 }
14
15 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16 pub enum RingState {
17 Ringing { since: Instant },
18 Accepted,
19 Declined,
20 Ended(RingEnd),
21 }
22
23 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
24 pub enum RingSignal {
25 Accept,
26 Decline,
27 Remote(EndKind),
28 Tick,
29 }
30
31 impl RingState {
32 pub fn start(now: Instant) -> RingState {
33 RingState::Ringing { since: now }
34 }
35
36 pub fn next(self, signal: RingSignal, now: Instant) -> RingState {
37 let RingState::Ringing { since } = self else {
38 return self;
39 };
40 match signal {
41 RingSignal::Accept => RingState::Accepted,
42 RingSignal::Decline => RingState::Declined,
43 RingSignal::Remote(EndKind::AnsweredElsewhere) => RingState::Ended(RingEnd::AnsweredElsewhere),
44 RingSignal::Remote(EndKind::Cancelled) => RingState::Ended(RingEnd::CallerCancelled),
45 RingSignal::Remote(_) => RingState::Ended(RingEnd::Other),
46 RingSignal::Tick if now.saturating_duration_since(since) >= RING_TIMEOUT => {
47 RingState::Ended(RingEnd::TimedOut)
48 }
49 RingSignal::Tick => self,
50 }
51 }
52
53 pub fn is_ringing(&self) -> bool {
54 matches!(self, RingState::Ringing { .. })
55 }
56
57 pub fn is_missed(&self) -> bool {
58 matches!(self, RingState::Ended(RingEnd::CallerCancelled | RingEnd::TimedOut | RingEnd::Other))
59 }
60 }
61
62 #[cfg(test)]
63 mod tests {
64 use super::*;
65
66 fn after(start: Instant, seconds: u64) -> Instant {
67 start + Duration::from_secs(seconds)
68 }
69
70 #[test]
71 fn ringing_until_something_happens() {
72 let start = Instant::now();
73 let state = RingState::start(start);
74 assert!(state.is_ringing());
75 assert_eq!(state.next(RingSignal::Tick, after(start, 29)), state);
76 }
77
78 #[test]
79 fn accept_and_decline_settle_the_ring() {
80 let start = Instant::now();
81 let state = RingState::start(start);
82 assert_eq!(state.next(RingSignal::Accept, start), RingState::Accepted);
83 assert_eq!(state.next(RingSignal::Decline, start), RingState::Declined);
84 assert!(!RingState::Accepted.is_ringing());
85 }
86
87 #[test]
88 fn thirty_seconds_without_an_answer_time_out() {
89 let start = Instant::now();
90 let state = RingState::start(start).next(RingSignal::Tick, after(start, 30));
91 assert_eq!(state, RingState::Ended(RingEnd::TimedOut));
92 assert!(state.is_missed());
93 }
94
95 #[test]
96 fn the_caller_hanging_up_is_a_missed_call() {
97 let start = Instant::now();
98 let state = RingState::start(start).next(RingSignal::Remote(EndKind::Cancelled), start);
99 assert_eq!(state, RingState::Ended(RingEnd::CallerCancelled));
100 assert!(state.is_missed());
101 }
102
103 #[test]
104 fn answering_elsewhere_stops_the_ring_without_a_missed_call() {
105 let start = Instant::now();
106 let state = RingState::start(start).next(RingSignal::Remote(EndKind::AnsweredElsewhere), start);
107 assert_eq!(state, RingState::Ended(RingEnd::AnsweredElsewhere));
108 assert!(!state.is_missed());
109 }
110
111 #[test]
112 fn any_other_remote_end_counts_as_missed() {
113 let start = Instant::now();
114 let state = RingState::start(start).next(RingSignal::Remote(EndKind::Normal), start);
115 assert_eq!(state, RingState::Ended(RingEnd::Other));
116 assert!(state.is_missed());
117 }
118
119 #[test]
120 fn a_settled_ring_ignores_later_signals() {
121 let start = Instant::now();
122 let accepted = RingState::start(start).next(RingSignal::Accept, start);
123 assert_eq!(accepted.next(RingSignal::Remote(EndKind::Cancelled), start), RingState::Accepted);
124 assert_eq!(accepted.next(RingSignal::Tick, after(start, 60)), RingState::Accepted);
125 let declined = RingState::start(start).next(RingSignal::Decline, start);
126 assert_eq!(declined.next(RingSignal::Accept, start), RingState::Declined);
127 assert!(!declined.is_missed());
128 }
129 }
@@ -0,0 +1,129 @@
1use std::time::{Duration, Instant};
2
3use crate::end::EndKind;
4
5pub const RING_TIMEOUT: Duration = Duration::from_secs(30);
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum RingEnd {
9 CallerCancelled,
10 AnsweredElsewhere,
11 Other,
12 TimedOut,
13}
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum RingState {
17 Ringing { since: Instant },
18 Accepted,
19 Declined,
20 Ended(RingEnd),
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum RingSignal {
25 Accept,
26 Decline,
27 Remote(EndKind),
28 Tick,
29}
30
31impl RingState {
32 pub fn start(now: Instant) -> RingState {
33 RingState::Ringing { since: now }
34 }
35
36 pub fn next(self, signal: RingSignal, now: Instant) -> RingState {
37 let RingState::Ringing { since } = self else {
38 return self;
39 };
40 match signal {
41 RingSignal::Accept => RingState::Accepted,
42 RingSignal::Decline => RingState::Declined,
43 RingSignal::Remote(EndKind::AnsweredElsewhere) => RingState::Ended(RingEnd::AnsweredElsewhere),
44 RingSignal::Remote(EndKind::Cancelled) => RingState::Ended(RingEnd::CallerCancelled),
45 RingSignal::Remote(_) => RingState::Ended(RingEnd::Other),
46 RingSignal::Tick if now.saturating_duration_since(since) >= RING_TIMEOUT => {
47 RingState::Ended(RingEnd::TimedOut)
48 }
49 RingSignal::Tick => self,
50 }
51 }
52
53 pub fn is_ringing(&self) -> bool {
54 matches!(self, RingState::Ringing { .. })
55 }
56
57 pub fn is_missed(&self) -> bool {
58 matches!(self, RingState::Ended(RingEnd::CallerCancelled | RingEnd::TimedOut | RingEnd::Other))
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 fn after(start: Instant, seconds: u64) -> Instant {
67 start + Duration::from_secs(seconds)
68 }
69
70 #[test]
71 fn ringing_until_something_happens() {
72 let start = Instant::now();
73 let state = RingState::start(start);
74 assert!(state.is_ringing());
75 assert_eq!(state.next(RingSignal::Tick, after(start, 29)), state);
76 }
77
78 #[test]
79 fn accept_and_decline_settle_the_ring() {
80 let start = Instant::now();
81 let state = RingState::start(start);
82 assert_eq!(state.next(RingSignal::Accept, start), RingState::Accepted);
83 assert_eq!(state.next(RingSignal::Decline, start), RingState::Declined);
84 assert!(!RingState::Accepted.is_ringing());
85 }
86
87 #[test]
88 fn thirty_seconds_without_an_answer_time_out() {
89 let start = Instant::now();
90 let state = RingState::start(start).next(RingSignal::Tick, after(start, 30));
91 assert_eq!(state, RingState::Ended(RingEnd::TimedOut));
92 assert!(state.is_missed());
93 }
94
95 #[test]
96 fn the_caller_hanging_up_is_a_missed_call() {
97 let start = Instant::now();
98 let state = RingState::start(start).next(RingSignal::Remote(EndKind::Cancelled), start);
99 assert_eq!(state, RingState::Ended(RingEnd::CallerCancelled));
100 assert!(state.is_missed());
101 }
102
103 #[test]
104 fn answering_elsewhere_stops_the_ring_without_a_missed_call() {
105 let start = Instant::now();
106 let state = RingState::start(start).next(RingSignal::Remote(EndKind::AnsweredElsewhere), start);
107 assert_eq!(state, RingState::Ended(RingEnd::AnsweredElsewhere));
108 assert!(!state.is_missed());
109 }
110
111 #[test]
112 fn any_other_remote_end_counts_as_missed() {
113 let start = Instant::now();
114 let state = RingState::start(start).next(RingSignal::Remote(EndKind::Normal), start);
115 assert_eq!(state, RingState::Ended(RingEnd::Other));
116 assert!(state.is_missed());
117 }
118
119 #[test]
120 fn a_settled_ring_ignores_later_signals() {
121 let start = Instant::now();
122 let accepted = RingState::start(start).next(RingSignal::Accept, start);
123 assert_eq!(accepted.next(RingSignal::Remote(EndKind::Cancelled), start), RingState::Accepted);
124 assert_eq!(accepted.next(RingSignal::Tick, after(start, 60)), RingState::Accepted);
125 let declined = RingState::start(start).next(RingSignal::Decline, start);
126 assert_eq!(declined.next(RingSignal::Accept, start), RingState::Declined);
127 assert!(!declined.is_missed());
128 }
129}
crates/calling/src/roster.rs added +240 −0
@@ -0,0 +1,240 @@
1 use serde_json::Value;
2
3 const ACTIVE: &str = "active";
4 const AUDIO: &str = "audio";
5
6 #[derive(Debug, Clone, PartialEq, Eq)]
7 pub struct Member {
8 pub mri: String,
9 pub display_name: String,
10 pub muted: bool,
11 pub in_lobby: bool,
12 pub audio_sources: Vec<u32>,
13 version: u64,
14 }
15
16 #[derive(Debug, Clone, PartialEq, Eq)]
17 pub struct RosterEntry {
18 pub mri: String,
19 pub display_name: String,
20 pub muted: bool,
21 pub in_lobby: bool,
22 }
23
24 #[derive(Debug, Clone, Default, PartialEq, Eq)]
25 pub struct Roster {
26 members: Vec<Member>,
27 pub lobby_count: u32,
28 }
29
30 impl Roster {
31 pub fn members(&self) -> &[Member] {
32 &self.members
33 }
34
35 pub fn entries(&self) -> Vec<RosterEntry> {
36 self.members
37 .iter()
38 .map(|member| RosterEntry {
39 mri: member.mri.clone(),
40 display_name: member.display_name.clone(),
41 muted: member.muted,
42 in_lobby: member.in_lobby,
43 })
44 .collect()
45 }
46
47 pub fn apply(&mut self, body: &Value) -> bool {
48 let before = self.clone();
49 if let Some(count) = body["participantCounts"]["lobbyParticipants"].as_u64() {
50 self.lobby_count = u32::try_from(count).unwrap_or(u32::MAX);
51 }
52 let Some(participants) = body["participants"].as_object() else {
53 return *self != before;
54 };
55 for (mri, participant) in participants {
56 let version = participant["version"].as_u64().unwrap_or_default();
57 let known = self.members.iter().position(|member| &member.mri == mri);
58 if known.is_some_and(|index| self.members[index].version > version) {
59 continue;
60 }
61 if participant["state"].as_str() != Some(ACTIVE) {
62 if let Some(index) = known {
63 self.members.remove(index);
64 }
65 continue;
66 }
67 let member = member_from(mri, participant, version, known.map(|index| &self.members[index]));
68 match known {
69 Some(index) => self.members[index] = member,
70 None => self.members.push(member),
71 }
72 }
73 *self != before
74 }
75
76 pub fn is_in_lobby(&self, mri: &str) -> Option<bool> {
77 self.members.iter().find(|member| member.mri == mri).map(|member| member.in_lobby)
78 }
79
80 pub fn mris_for_sources(&self, sources: &[u32]) -> Vec<String> {
81 self.members
82 .iter()
83 .filter(|member| member.audio_sources.iter().any(|source| sources.contains(source)))
84 .map(|member| member.mri.clone())
85 .collect()
86 }
87 }
88
89 fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&Member>) -> Member {
90 let display_name = participant["details"]["displayName"]
91 .as_str()
92 .filter(|name| !name.is_empty())
93 .map(str::to_owned)
94 .or_else(|| previous.map(|member| member.display_name.clone()))
95 .unwrap_or_default();
96 let endpoints: Vec<&Value> = participant["endpoints"]
97 .as_object()
98 .map(|endpoints| endpoints.values().collect())
99 .unwrap_or_default();
100 let in_call: Vec<&&Value> = endpoints.iter().filter(|endpoint| endpoint.get("call").is_some()).collect();
101 let in_lobby = in_call.is_empty() && endpoints.iter().any(|endpoint| endpoint.get("lobby").is_some());
102 let muted = !in_call.is_empty() && in_call.iter().all(|endpoint| endpoint_muted(endpoint));
103 let audio_sources = in_call
104 .iter()
105 .flat_map(|endpoint| audio_streams(endpoint))
106 .filter_map(|stream| source_id(&stream["sourceId"]))
107 .collect();
108 Member {
109 mri: mri.to_owned(),
110 display_name,
111 muted,
112 in_lobby,
113 audio_sources,
114 version,
115 }
116 }
117
118 fn audio_streams(endpoint: &Value) -> impl Iterator<Item = &Value> {
119 endpoint["call"]["mediaStreams"]
120 .as_array()
121 .into_iter()
122 .flatten()
123 .filter(|stream| stream["type"].as_str() == Some(AUDIO))
124 }
125
126 fn endpoint_muted(endpoint: &Value) -> bool {
127 endpoint["endpointState"]["state"]["isMuted"].as_bool() == Some(true)
128 || audio_streams(endpoint).any(|stream| stream["serverMuted"].as_bool() == Some(true))
129 }
130
131 fn source_id(value: &Value) -> Option<u32> {
132 value
133 .as_u64()
134 .or_else(|| value.as_str()?.parse().ok())
135 .and_then(|id| u32::try_from(id).ok())
136 }
137
138 #[cfg(test)]
139 mod tests {
140 use serde_json::json;
141
142 use super::*;
143
144 fn delta(participants: Value) -> Value {
145 json!({"type": "Delta", "sequenceNumber": 1, "participants": participants})
146 }
147
148 fn participant(name: &str, version: u64, state: &str, muted: bool, source: u32) -> Value {
149 json!({
150 "version": version,
151 "state": state,
152 "details": {"displayName": name},
153 "endpoints": {"ep": {
154 "call": {"mediaStreams": [{"type": "audio", "sourceId": source, "serverMuted": false},
155 {"type": "video", "sourceId": source + 1}]},
156 "endpointState": {"state": {"isMuted": muted}},
157 }},
158 })
159 }
160
161 #[test]
162 fn active_participants_join_and_inactive_ones_leave() {
163 let mut roster = Roster::default();
164 assert!(roster.apply(&delta(json!({
165 "8:orgid:a": participant("Ana", 1, "active", false, 201),
166 "8:orgid:b": participant("Bo", 1, "active", true, 301),
167 }))));
168 assert_eq!(roster.members().len(), 2);
169 assert!(roster.members().iter().any(|member| member.display_name == "Bo" && member.muted));
170 assert!(roster.apply(&delta(json!({"8:orgid:b": participant("Bo", 2, "inactive", true, 301)}))));
171 assert_eq!(roster.members().len(), 1);
172 assert_eq!(roster.members()[0].mri, "8:orgid:a");
173 }
174
175 #[test]
176 fn older_versions_are_ignored() {
177 let mut roster = Roster::default();
178 roster.apply(&delta(json!({"8:orgid:a": participant("Ana", 5, "active", false, 201)})));
179 let changed = roster.apply(&delta(json!({"8:orgid:a": participant("Old", 4, "active", true, 201)})));
180 assert!(!changed);
181 assert_eq!(roster.members()[0].display_name, "Ana");
182 assert!(!roster.members()[0].muted);
183 }
184
185 #[test]
186 fn a_repeated_delta_changes_nothing() {
187 let mut roster = Roster::default();
188 let body = delta(json!({"8:orgid:a": participant("Ana", 1, "active", false, 201)}));
189 assert!(roster.apply(&body));
190 assert!(!roster.apply(&body));
191 }
192
193 #[test]
194 fn server_mute_counts_as_muted() {
195 let mut roster = Roster::default();
196 let mut forced = participant("Ana", 1, "active", false, 201);
197 forced["endpoints"]["ep"]["call"]["mediaStreams"][0]["serverMuted"] = json!(true);
198 roster.apply(&delta(json!({"8:orgid:a": forced})));
199 assert!(roster.members()[0].muted);
200 }
201
202 #[test]
203 fn lobby_endpoints_are_marked_and_admission_clears_it() {
204 let mut roster = Roster::default();
205 roster.apply(&delta(json!({"8:orgid:me": {
206 "version": 1, "state": "active", "details": {"displayName": "Me"},
207 "endpoints": {"ep": {"lobby": {"mediaStreams": []}}},
208 }})));
209 assert_eq!(roster.is_in_lobby("8:orgid:me"), Some(true));
210 roster.apply(&delta(json!({"8:orgid:me": participant("Me", 2, "active", true, 201)})));
211 assert_eq!(roster.is_in_lobby("8:orgid:me"), Some(false));
212 assert_eq!(roster.is_in_lobby("8:orgid:nobody"), None);
213 }
214
215 #[test]
216 fn lobby_counts_come_from_participant_counts() {
217 let mut roster = Roster::default();
218 roster.apply(&json!({"participantCounts": {"lobbyParticipants": 3, "totalParticipants": 5}}));
219 assert_eq!(roster.lobby_count, 3);
220 }
221
222 #[test]
223 fn speaking_sources_map_to_participants() {
224 let mut roster = Roster::default();
225 roster.apply(&delta(json!({
226 "8:orgid:a": participant("Ana", 1, "active", false, 201),
227 "8:orgid:b": participant("Bo", 1, "active", false, 301),
228 })));
229 assert_eq!(roster.mris_for_sources(&[301]), vec!["8:orgid:b".to_owned()]);
230 assert!(roster.mris_for_sources(&[999]).is_empty());
231 }
232
233 #[test]
234 fn missing_name_keeps_the_known_one() {
235 let mut roster = Roster::default();
236 roster.apply(&delta(json!({"8:orgid:a": participant("Ana", 1, "active", false, 201)})));
237 roster.apply(&delta(json!({"8:orgid:a": {"version": 2, "state": "active", "endpoints": {"ep": {"call": {}}}}})));
238 assert_eq!(roster.members()[0].display_name, "Ana");
239 }
240 }
@@ -0,0 +1,240 @@
1use serde_json::Value;
2
3const ACTIVE: &str = "active";
4const AUDIO: &str = "audio";
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct Member {
8 pub mri: String,
9 pub display_name: String,
10 pub muted: bool,
11 pub in_lobby: bool,
12 pub audio_sources: Vec<u32>,
13 version: u64,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct RosterEntry {
18 pub mri: String,
19 pub display_name: String,
20 pub muted: bool,
21 pub in_lobby: bool,
22}
23
24#[derive(Debug, Clone, Default, PartialEq, Eq)]
25pub struct Roster {
26 members: Vec<Member>,
27 pub lobby_count: u32,
28}
29
30impl Roster {
31 pub fn members(&self) -> &[Member] {
32 &self.members
33 }
34
35 pub fn entries(&self) -> Vec<RosterEntry> {
36 self.members
37 .iter()
38 .map(|member| RosterEntry {
39 mri: member.mri.clone(),
40 display_name: member.display_name.clone(),
41 muted: member.muted,
42 in_lobby: member.in_lobby,
43 })
44 .collect()
45 }
46
47 pub fn apply(&mut self, body: &Value) -> bool {
48 let before = self.clone();
49 if let Some(count) = body["participantCounts"]["lobbyParticipants"].as_u64() {
50 self.lobby_count = u32::try_from(count).unwrap_or(u32::MAX);
51 }
52 let Some(participants) = body["participants"].as_object() else {
53 return *self != before;
54 };
55 for (mri, participant) in participants {
56 let version = participant["version"].as_u64().unwrap_or_default();
57 let known = self.members.iter().position(|member| &member.mri == mri);
58 if known.is_some_and(|index| self.members[index].version > version) {
59 continue;
60 }
61 if participant["state"].as_str() != Some(ACTIVE) {
62 if let Some(index) = known {
63 self.members.remove(index);
64 }
65 continue;
66 }
67 let member = member_from(mri, participant, version, known.map(|index| &self.members[index]));
68 match known {
69 Some(index) => self.members[index] = member,
70 None => self.members.push(member),
71 }
72 }
73 *self != before
74 }
75
76 pub fn is_in_lobby(&self, mri: &str) -> Option<bool> {
77 self.members.iter().find(|member| member.mri == mri).map(|member| member.in_lobby)
78 }
79
80 pub fn mris_for_sources(&self, sources: &[u32]) -> Vec<String> {
81 self.members
82 .iter()
83 .filter(|member| member.audio_sources.iter().any(|source| sources.contains(source)))
84 .map(|member| member.mri.clone())
85 .collect()
86 }
87}
88
89fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&Member>) -> Member {
90 let display_name = participant["details"]["displayName"]
91 .as_str()
92 .filter(|name| !name.is_empty())
93 .map(str::to_owned)
94 .or_else(|| previous.map(|member| member.display_name.clone()))
95 .unwrap_or_default();
96 let endpoints: Vec<&Value> = participant["endpoints"]
97 .as_object()
98 .map(|endpoints| endpoints.values().collect())
99 .unwrap_or_default();
100 let in_call: Vec<&&Value> = endpoints.iter().filter(|endpoint| endpoint.get("call").is_some()).collect();
101 let in_lobby = in_call.is_empty() && endpoints.iter().any(|endpoint| endpoint.get("lobby").is_some());
102 let muted = !in_call.is_empty() && in_call.iter().all(|endpoint| endpoint_muted(endpoint));
103 let audio_sources = in_call
104 .iter()
105 .flat_map(|endpoint| audio_streams(endpoint))
106 .filter_map(|stream| source_id(&stream["sourceId"]))
107 .collect();
108 Member {
109 mri: mri.to_owned(),
110 display_name,
111 muted,
112 in_lobby,
113 audio_sources,
114 version,
115 }
116}
117
118fn audio_streams(endpoint: &Value) -> impl Iterator<Item = &Value> {
119 endpoint["call"]["mediaStreams"]
120 .as_array()
121 .into_iter()
122 .flatten()
123 .filter(|stream| stream["type"].as_str() == Some(AUDIO))
124}
125
126fn endpoint_muted(endpoint: &Value) -> bool {
127 endpoint["endpointState"]["state"]["isMuted"].as_bool() == Some(true)
128 || audio_streams(endpoint).any(|stream| stream["serverMuted"].as_bool() == Some(true))
129}
130
131fn source_id(value: &Value) -> Option<u32> {
132 value
133 .as_u64()
134 .or_else(|| value.as_str()?.parse().ok())
135 .and_then(|id| u32::try_from(id).ok())
136}
137
138#[cfg(test)]
139mod tests {
140 use serde_json::json;
141
142 use super::*;
143
144 fn delta(participants: Value) -> Value {
145 json!({"type": "Delta", "sequenceNumber": 1, "participants": participants})
146 }
147
148 fn participant(name: &str, version: u64, state: &str, muted: bool, source: u32) -> Value {
149 json!({
150 "version": version,
151 "state": state,
152 "details": {"displayName": name},
153 "endpoints": {"ep": {
154 "call": {"mediaStreams": [{"type": "audio", "sourceId": source, "serverMuted": false},
155 {"type": "video", "sourceId": source + 1}]},
156 "endpointState": {"state": {"isMuted": muted}},
157 }},
158 })
159 }
160
161 #[test]
162 fn active_participants_join_and_inactive_ones_leave() {
163 let mut roster = Roster::default();
164 assert!(roster.apply(&delta(json!({
165 "8:orgid:a": participant("Ana", 1, "active", false, 201),
166 "8:orgid:b": participant("Bo", 1, "active", true, 301),
167 }))));
168 assert_eq!(roster.members().len(), 2);
169 assert!(roster.members().iter().any(|member| member.display_name == "Bo" && member.muted));
170 assert!(roster.apply(&delta(json!({"8:orgid:b": participant("Bo", 2, "inactive", true, 301)}))));
171 assert_eq!(roster.members().len(), 1);
172 assert_eq!(roster.members()[0].mri, "8:orgid:a");
173 }
174
175 #[test]
176 fn older_versions_are_ignored() {
177 let mut roster = Roster::default();
178 roster.apply(&delta(json!({"8:orgid:a": participant("Ana", 5, "active", false, 201)})));
179 let changed = roster.apply(&delta(json!({"8:orgid:a": participant("Old", 4, "active", true, 201)})));
180 assert!(!changed);
181 assert_eq!(roster.members()[0].display_name, "Ana");
182 assert!(!roster.members()[0].muted);
183 }
184
185 #[test]
186 fn a_repeated_delta_changes_nothing() {
187 let mut roster = Roster::default();
188 let body = delta(json!({"8:orgid:a": participant("Ana", 1, "active", false, 201)}));
189 assert!(roster.apply(&body));
190 assert!(!roster.apply(&body));
191 }
192
193 #[test]
194 fn server_mute_counts_as_muted() {
195 let mut roster = Roster::default();
196 let mut forced = participant("Ana", 1, "active", false, 201);
197 forced["endpoints"]["ep"]["call"]["mediaStreams"][0]["serverMuted"] = json!(true);
198 roster.apply(&delta(json!({"8:orgid:a": forced})));
199 assert!(roster.members()[0].muted);
200 }
201
202 #[test]
203 fn lobby_endpoints_are_marked_and_admission_clears_it() {
204 let mut roster = Roster::default();
205 roster.apply(&delta(json!({"8:orgid:me": {
206 "version": 1, "state": "active", "details": {"displayName": "Me"},
207 "endpoints": {"ep": {"lobby": {"mediaStreams": []}}},
208 }})));
209 assert_eq!(roster.is_in_lobby("8:orgid:me"), Some(true));
210 roster.apply(&delta(json!({"8:orgid:me": participant("Me", 2, "active", true, 201)})));
211 assert_eq!(roster.is_in_lobby("8:orgid:me"), Some(false));
212 assert_eq!(roster.is_in_lobby("8:orgid:nobody"), None);
213 }
214
215 #[test]
216 fn lobby_counts_come_from_participant_counts() {
217 let mut roster = Roster::default();
218 roster.apply(&json!({"participantCounts": {"lobbyParticipants": 3, "totalParticipants": 5}}));
219 assert_eq!(roster.lobby_count, 3);
220 }
221
222 #[test]
223 fn speaking_sources_map_to_participants() {
224 let mut roster = Roster::default();
225 roster.apply(&delta(json!({
226 "8:orgid:a": participant("Ana", 1, "active", false, 201),
227 "8:orgid:b": participant("Bo", 1, "active", false, 301),
228 })));
229 assert_eq!(roster.mris_for_sources(&[301]), vec!["8:orgid:b".to_owned()]);
230 assert!(roster.mris_for_sources(&[999]).is_empty());
231 }
232
233 #[test]
234 fn missing_name_keeps_the_known_one() {
235 let mut roster = Roster::default();
236 roster.apply(&delta(json!({"8:orgid:a": participant("Ana", 1, "active", false, 201)})));
237 roster.apply(&delta(json!({"8:orgid:a": {"version": 2, "state": "active", "endpoints": {"ep": {"call": {}}}}})));
238 assert_eq!(roster.members()[0].display_name, "Ana");
239 }
240}
crates/calling/src/sdp.rs +275 −2
@@ -322,7 +322,9 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
322 322 };
323 323 let multi_stream = (Some(&mid) == gallery_carrier.as_ref()).then_some(plan.gallery_mids.len());
324 324 let is_first = media.is_empty();
325 let signaled = if role == LineRole::Data {
325 let signaled = if source.port == "0" {
326 signal_rejected_line(source, role)
327 } else if role == LineRole::Data {
326 328 signal_data_line(source, numbers)
327 329 } else {
328 330 signal_rtp_line(source, role, multi_stream, &cname, is_first, numbers)
@@ -342,7 +344,7 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
342 344 match attribute.name.as_str() {
343 345 "msid-semantic" => attribute.value = Some(" WMS *".to_owned()),
344 346 "group" if attribute.value.as_deref().is_some_and(|value| value.starts_with("BUNDLE")) => {
345 let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect();
347 let mids: Vec<&str> = media.iter().filter(|line| line.port != "0").filter_map(Media::mid).collect();
346 348 attribute.value = Some(format!("BUNDLE {}", mids.join(" ")));
347 349 }
348 350 _ => {}
@@ -355,6 +357,23 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
355 357 })
356 358 }
357 359
360 fn signal_rejected_line(source: &Media, role: LineRole) -> Media {
361 let attributes = vec![
362 Attribute::new("mid", source.mid().unwrap_or_default()),
363 Attribute::flag("inactive"),
364 Attribute::new("label", role.label()),
365 ];
366 Media {
367 kind: if role == LineRole::Data { "x-data".to_owned() } else { source.kind.clone() },
368 port: "0".to_owned(),
369 proto: SIGNALED_PROTO.to_owned(),
370 formats: source.formats.clone(),
371 connection: Some(PLACEHOLDER_CONNECTION.to_owned()),
372 bandwidths: Vec::new(),
373 attributes,
374 }
375 }
376
358 377 fn signal_rtp_line(
359 378 source: &Media,
360 379 role: LineRole,
@@ -770,6 +789,215 @@ fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) ->
770 789 }
771 790 }
772 791
792 const BROWSER_PORT: &str = "9";
793 const BROWSER_PROTO: &str = "UDP/TLS/RTP/SAVPF";
794 const BROWSER_CONNECTION: &str = "IN IP4 0.0.0.0";
795 const BROWSER_RTCP: &str = "9 IN IP4 0.0.0.0";
796 const BROWSER_DATA_PROTO: &str = "UDP/DTLS/SCTP";
797 const BROWSER_DATA_FORMAT: &str = "webrtc-datachannel";
798 const SCTP_PORT: &str = "5000";
799 const SCTP_MAX_MESSAGE_SIZE: &str = "262144";
800 const PLACEHOLDER_CANDIDATE_TAIL: &str = " 1234 typ host";
801 const TEAMS_ONLY_ATTRIBUTES: [&str; 6] = [
802 "x-multi-stream",
803 "x-signaling-fb",
804 "x-ssrc-range",
805 "x-source-streamid",
806 "x-data-protocol",
807 "label",
808 ];
809 const TRANSPORT_ATTRIBUTES: [&str; 5] = ["setup", "ice-ufrag", "ice-pwd", "fingerprint", "ice-options"];
810
811 /// A Teams offer translated for libwebrtc; `lines` remembers which browser mids each signaled line stands for.
812 #[derive(Debug, Clone)]
813 pub struct RemoteOffer {
814 pub browser_sdp: String,
815 pub lines: Vec<SignaledLine>,
816 }
817
818 impl RemoteOffer {
819 pub fn plan(&self) -> OfferPlan {
820 let mut plan = OfferPlan::default();
821 for line in &self.lines {
822 match line.role {
823 LineRole::ScreenShare => plan.screen_share_mids.extend(line.browser_mids.iter().cloned()),
824 _ if line.browser_mids.len() > 1 => plan.gallery_mids.extend(line.browser_mids.iter().cloned()),
825 _ => {}
826 }
827 }
828 plan
829 }
830 }
831
832 fn role_of_teams_line(line: &Media) -> LineRole {
833 match line.value("label") {
834 Some("main-audio") => LineRole::MainAudio,
835 Some("main-video") => LineRole::MainVideo,
836 Some("applicationsharing-video") => LineRole::ScreenShare,
837 Some("data") => LineRole::Data,
838 _ => match line.kind.as_str() {
839 "audio" => LineRole::MainAudio,
840 "x-data" | "application" => LineRole::Data,
841 _ => LineRole::MainVideo,
842 },
843 }
844 }
845
846 /// Folded gallery lines get the mids just below the carrier line's own mid.
847 fn folded_mids(carrier: &str, count: usize) -> Vec<String> {
848 match carrier.parse::<usize>() {
849 Ok(last) if last + 1 >= count => (last + 1 - count..=last).map(|mid| mid.to_string()).collect(),
850 _ => (0..count)
851 .map(|index| if index + 1 == count { carrier.to_owned() } else { format!("{carrier}-{index}") })
852 .collect(),
853 }
854 }
855
856 pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
857 let teams = parse(teams_sdp)?;
858 let mut media = Vec::new();
859 let mut lines = Vec::new();
860 for source in &teams.media {
861 let role = role_of_teams_line(source);
862 let carrier = source.mid().unwrap_or_default().to_owned();
863 let folded = source
864 .value("x-multi-stream")
865 .and_then(|value| value.split(' ').next()?.parse::<usize>().ok())
866 .filter(|count| *count > 1);
867 let mids = match folded {
868 Some(count) => folded_mids(&carrier, count),
869 None => vec![carrier.clone()],
870 };
871 for (index, mid) in mids.iter().enumerate() {
872 let converted = if role == LineRole::Data {
873 browser_data_from_teams(source, mid, &teams.session)
874 } else {
875 browser_rtp_from_teams(source, mid, folded.is_some(), index == 0 && lines.is_empty(), &teams.session)
876 };
877 media.push(converted);
878 }
879 lines.push(SignaledLine {
880 browser_mids: mids,
881 role,
882 });
883 }
884 let mut session = teams.session.clone();
885 session.bandwidths.clear();
886 session.connection = None;
887 session.attributes.retain(|attribute| matches!(attribute.name.as_str(), "extmap-allow-mixed" | "msid-semantic"));
888 let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect();
889 session.attributes.push(Attribute::new("group", format!("BUNDLE {}", mids.join(" "))));
890 Ok(RemoteOffer {
891 browser_sdp: write(&SessionDescription { session, media }),
892 lines,
893 })
894 }
895
896 fn transport_from_teams(source: &Media, session: &Session) -> Vec<Attribute> {
897 TRANSPORT_ATTRIBUTES
898 .iter()
899 .filter_map(|name| {
900 source
901 .attributes
902 .iter()
903 .chain(&session.attributes)
904 .find(|attribute| attribute.name == *name)
905 .cloned()
906 })
907 .collect()
908 }
909
910 fn browser_data_from_teams(source: &Media, mid: &str, session: &Session) -> Media {
911 let mut attributes = transport_from_teams(source, session);
912 attributes.push(Attribute::new("mid", mid));
913 attributes.push(Attribute::new("sctp-port", SCTP_PORT));
914 attributes.push(Attribute::new("max-message-size", SCTP_MAX_MESSAGE_SIZE));
915 Media {
916 kind: "application".to_owned(),
917 port: BROWSER_PORT.to_owned(),
918 proto: BROWSER_DATA_PROTO.to_owned(),
919 formats: vec![BROWSER_DATA_FORMAT.to_owned()],
920 connection: Some(BROWSER_CONNECTION.to_owned()),
921 bandwidths: Vec::new(),
922 attributes,
923 }
924 }
925
926 fn browser_rtp_from_teams(source: &Media, mid: &str, folded: bool, carries_candidate: bool, session: &Session) -> Media {
927 let rtpmap = source.rtpmap();
928 let is_rtx = |payload: &str| rtpmap.get(payload).is_some_and(|encoding| encoding.starts_with("rtx/"));
929 let mut attributes = Vec::new();
930 let mut expanded_feedback: Vec<Attribute> = Vec::new();
931 for attribute in &source.attributes {
932 let value = attribute.value.as_deref().unwrap_or_default();
933 match attribute.name.as_str() {
934 name if TEAMS_ONLY_ATTRIBUTES.contains(&name) => {}
935 name if name.starts_with("x-") => {}
936 "mid" | "rtcp-mux" => {}
937 name if TRANSPORT_ATTRIBUTES.contains(&name) => {}
938 "candidate" => {
939 if carries_candidate && !value.contains(PLACEHOLDER_CANDIDATE_TAIL) {
940 attributes.push(attribute.clone());
941 }
942 }
943 "ssrc" => {
944 let placeholder = value.contains("fake_attribute") || value.starts_with("1 ");
945 if !folded && !placeholder {
946 attributes.push(attribute.clone());
947 }
948 }
949 "ssrc-group" => {
950 if !folded {
951 attributes.push(attribute.clone());
952 }
953 }
954 "rtcp" => attributes.push(Attribute::new("rtcp", BROWSER_RTCP)),
955 "rtpmap" => attributes.push(Attribute::new("rtpmap", browser_rtpmap(value))),
956 "extmap" => attributes.push(Attribute::new("extmap", browser_extmap(value))),
957 "rtcp-fb" => match value.strip_prefix("* ") {
958 Some(kind) => expanded_feedback.extend(
959 source
960 .formats
961 .iter()
962 .filter(|payload| !is_rtx(payload))
963 .map(|payload| Attribute::new("rtcp-fb", format!("{payload} {kind}"))),
964 ),
965 None => attributes.push(attribute.clone()),
966 },
967 _ => attributes.push(attribute.clone()),
968 }
969 }
970 attributes.extend(expanded_feedback);
971 attributes.extend(transport_from_teams(source, session));
972 attributes.push(Attribute::new("mid", mid));
973 attributes.push(Attribute::flag("rtcp-mux"));
974 Media {
975 kind: source.kind.clone(),
976 port: BROWSER_PORT.to_owned(),
977 proto: BROWSER_PROTO.to_owned(),
978 formats: source.formats.clone(),
979 connection: Some(BROWSER_CONNECTION.to_owned()),
980 bandwidths: Vec::new(),
981 attributes,
982 }
983 }
984
985 fn browser_rtpmap(value: &str) -> String {
986 match value.split_once(' ') {
987 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => format!("{payload} red/48000/2"),
988 _ => value.to_owned(),
989 }
990 }
991
992 fn browser_extmap(value: &str) -> String {
993 value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "")
994 }
995
996 /// libwebrtc answers every offered line in the offer's order and with its mids, so the offer's plan applies unchanged.
997 pub fn to_teams_answer(browser_answer_sdp: &str, remote: &RemoteOffer, numbers: &mut impl NumberSource) -> Result<SignaledOffer> {
998 to_teams_offer(browser_answer_sdp, &remote.plan(), numbers)
999 }
1000
773 1001 #[cfg(test)]
774 1002 mod tests {
775 1003 use super::*;
@@ -828,4 +1056,49 @@ mod tests {
828 1056 assert!(browser.contains("a=group:BUNDLE 0\n"));
829 1057 assert!(!browser.contains("SATINFB") && !browser.contains("MTURNID") && !browser.contains("label"));
830 1058 }
1059 #[test]
1060 fn an_audio_offer_from_teams_gets_the_browser_shape_back() {
1061 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1062 let remote = from_teams_offer(&offer.sdp).unwrap();
1063 let text = remote.browser_sdp.replace("\r\n", "\n");
1064 assert!(text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"), "{text}");
1065 assert!(text.contains("c=IN IP4 0.0.0.0\n"));
1066 assert!(text.contains("a=rtcp:9 IN IP4 0.0.0.0\n"));
1067 assert!(text.contains("a=rtpmap:63 red/48000/2\n"));
1068 assert!(text.contains("a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"));
1069 assert!(text.contains("a=ice-ufrag:u\n") && text.contains("a=fingerprint:sha-256 AA\n") && text.contains("a=setup:actpass\n"));
1070 assert!(text.contains("a=mid:0\n") && text.contains("a=group:BUNDLE 0\n"));
1071 assert!(!text.contains("10.10.10.10") && !text.contains("x-ssrc-range") && !text.contains("label") && !text.contains("1234"));
1072 assert_eq!(remote.lines, offer.lines);
1073 }
1074
1075 #[test]
1076 fn shared_video_feedback_is_spelled_out_per_codec_again() {
1077 let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=video 1234 RTP/SAVP 102 103\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=rtpmap:103 rtx/90000\r\na=fmtp:103 apt=102\r\na=rtcp-fb:* nack\r\na=rtcp-fb:* nack pli\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=label:main-video\r\n";
1078 let remote = from_teams_offer(teams).unwrap();
1079 let text = remote.browser_sdp.replace("\r\n", "\n");
1080 assert!(text.contains("a=rtcp-fb:102 nack\n") && text.contains("a=rtcp-fb:102 nack pli\n"));
1081 assert!(!text.contains("a=rtcp-fb:103") && !text.contains("a=rtcp-fb:*"));
1082 }
1083
1084 #[test]
1085 fn a_rejected_video_line_stays_rejected_and_out_of_the_bundle() {
1086 let audio_and_video = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=label:main-audio\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\n";
1087 let remote = from_teams_offer(audio_and_video).unwrap();
1088 let answer = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 BB\r\na=setup:active\r\na=ssrc:7 cname:x\r\nm=video 0 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na=inactive\r\n";
1089 let signaled = to_teams_answer(answer, &remote, &mut counter()).unwrap();
1090 let text = signaled.sdp.replace("\r\n", "\n");
1091 assert!(text.contains("m=video 0 RTP/SAVP 102\n"), "{text}");
1092 assert!(text.contains("a=group:BUNDLE 0\n"));
1093 let parsed = parse(&signaled.sdp).unwrap();
1094 assert_eq!(parsed.media.len(), 2);
1095 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1096 assert_eq!(parsed.media[1].direction(), Some("inactive"));
1097 }
1098
1099 #[test]
1100 fn folded_gallery_lines_expand_below_their_carrier_mid() {
1101 assert_eq!(folded_mids("17", 8), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());
1102 assert_eq!(folded_mids("x", 2), vec!["x-0".to_owned(), "x".to_owned()]);
1103 }
831 1104 }
@@ -322,7 +322,9 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
322 };
322 };
323 let multi_stream = (Some(&mid) == gallery_carrier.as_ref()).then_some(plan.gallery_mids.len());
323 let multi_stream = (Some(&mid) == gallery_carrier.as_ref()).then_some(plan.gallery_mids.len());
324 let is_first = media.is_empty();
324 let is_first = media.is_empty();
325 let signaled = if role == LineRole::Data {
325 let signaled = if source.port == "0" {
326 signal_rejected_line(source, role)
327 } else if role == LineRole::Data {
326 signal_data_line(source, numbers)
328 signal_data_line(source, numbers)
327 } else {
329 } else {
328 signal_rtp_line(source, role, multi_stream, &cname, is_first, numbers)
330 signal_rtp_line(source, role, multi_stream, &cname, is_first, numbers)
@@ -342,7 +344,7 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
342 match attribute.name.as_str() {
344 match attribute.name.as_str() {
343 "msid-semantic" => attribute.value = Some(" WMS *".to_owned()),
345 "msid-semantic" => attribute.value = Some(" WMS *".to_owned()),
344 "group" if attribute.value.as_deref().is_some_and(|value| value.starts_with("BUNDLE")) => {
346 "group" if attribute.value.as_deref().is_some_and(|value| value.starts_with("BUNDLE")) => {
345 let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect();
347 let mids: Vec<&str> = media.iter().filter(|line| line.port != "0").filter_map(Media::mid).collect();
346 attribute.value = Some(format!("BUNDLE {}", mids.join(" ")));
348 attribute.value = Some(format!("BUNDLE {}", mids.join(" ")));
347 }
349 }
348 _ => {}
350 _ => {}
@@ -355,6 +357,23 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
355 })
357 })
356}
358}
357
359
360fn signal_rejected_line(source: &Media, role: LineRole) -> Media {
361 let attributes = vec![
362 Attribute::new("mid", source.mid().unwrap_or_default()),
363 Attribute::flag("inactive"),
364 Attribute::new("label", role.label()),
365 ];
366 Media {
367 kind: if role == LineRole::Data { "x-data".to_owned() } else { source.kind.clone() },
368 port: "0".to_owned(),
369 proto: SIGNALED_PROTO.to_owned(),
370 formats: source.formats.clone(),
371 connection: Some(PLACEHOLDER_CONNECTION.to_owned()),
372 bandwidths: Vec::new(),
373 attributes,
374 }
375}
376
358fn signal_rtp_line(
377fn signal_rtp_line(
359 source: &Media,
378 source: &Media,
360 role: LineRole,
379 role: LineRole,
@@ -770,6 +789,215 @@ fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) ->
770 }
789 }
771}
790}
772
791
792const BROWSER_PORT: &str = "9";
793const BROWSER_PROTO: &str = "UDP/TLS/RTP/SAVPF";
794const BROWSER_CONNECTION: &str = "IN IP4 0.0.0.0";
795const BROWSER_RTCP: &str = "9 IN IP4 0.0.0.0";
796const BROWSER_DATA_PROTO: &str = "UDP/DTLS/SCTP";
797const BROWSER_DATA_FORMAT: &str = "webrtc-datachannel";
798const SCTP_PORT: &str = "5000";
799const SCTP_MAX_MESSAGE_SIZE: &str = "262144";
800const PLACEHOLDER_CANDIDATE_TAIL: &str = " 1234 typ host";
801const TEAMS_ONLY_ATTRIBUTES: [&str; 6] = [
802 "x-multi-stream",
803 "x-signaling-fb",
804 "x-ssrc-range",
805 "x-source-streamid",
806 "x-data-protocol",
807 "label",
808];
809const TRANSPORT_ATTRIBUTES: [&str; 5] = ["setup", "ice-ufrag", "ice-pwd", "fingerprint", "ice-options"];
810
811/// A Teams offer translated for libwebrtc; `lines` remembers which browser mids each signaled line stands for.
812#[derive(Debug, Clone)]
813pub struct RemoteOffer {
814 pub browser_sdp: String,
815 pub lines: Vec<SignaledLine>,
816}
817
818impl RemoteOffer {
819 pub fn plan(&self) -> OfferPlan {
820 let mut plan = OfferPlan::default();
821 for line in &self.lines {
822 match line.role {
823 LineRole::ScreenShare => plan.screen_share_mids.extend(line.browser_mids.iter().cloned()),
824 _ if line.browser_mids.len() > 1 => plan.gallery_mids.extend(line.browser_mids.iter().cloned()),
825 _ => {}
826 }
827 }
828 plan
829 }
830}
831
832fn role_of_teams_line(line: &Media) -> LineRole {
833 match line.value("label") {
834 Some("main-audio") => LineRole::MainAudio,
835 Some("main-video") => LineRole::MainVideo,
836 Some("applicationsharing-video") => LineRole::ScreenShare,
837 Some("data") => LineRole::Data,
838 _ => match line.kind.as_str() {
839 "audio" => LineRole::MainAudio,
840 "x-data" | "application" => LineRole::Data,
841 _ => LineRole::MainVideo,
842 },
843 }
844}
845
846/// Folded gallery lines get the mids just below the carrier line's own mid.
847fn folded_mids(carrier: &str, count: usize) -> Vec<String> {
848 match carrier.parse::<usize>() {
849 Ok(last) if last + 1 >= count => (last + 1 - count..=last).map(|mid| mid.to_string()).collect(),
850 _ => (0..count)
851 .map(|index| if index + 1 == count { carrier.to_owned() } else { format!("{carrier}-{index}") })
852 .collect(),
853 }
854}
855
856pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
857 let teams = parse(teams_sdp)?;
858 let mut media = Vec::new();
859 let mut lines = Vec::new();
860 for source in &teams.media {
861 let role = role_of_teams_line(source);
862 let carrier = source.mid().unwrap_or_default().to_owned();
863 let folded = source
864 .value("x-multi-stream")
865 .and_then(|value| value.split(' ').next()?.parse::<usize>().ok())
866 .filter(|count| *count > 1);
867 let mids = match folded {
868 Some(count) => folded_mids(&carrier, count),
869 None => vec![carrier.clone()],
870 };
871 for (index, mid) in mids.iter().enumerate() {
872 let converted = if role == LineRole::Data {
873 browser_data_from_teams(source, mid, &teams.session)
874 } else {
875 browser_rtp_from_teams(source, mid, folded.is_some(), index == 0 && lines.is_empty(), &teams.session)
876 };
877 media.push(converted);
878 }
879 lines.push(SignaledLine {
880 browser_mids: mids,
881 role,
882 });
883 }
884 let mut session = teams.session.clone();
885 session.bandwidths.clear();
886 session.connection = None;
887 session.attributes.retain(|attribute| matches!(attribute.name.as_str(), "extmap-allow-mixed" | "msid-semantic"));
888 let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect();
889 session.attributes.push(Attribute::new("group", format!("BUNDLE {}", mids.join(" "))));
890 Ok(RemoteOffer {
891 browser_sdp: write(&SessionDescription { session, media }),
892 lines,
893 })
894}
895
896fn transport_from_teams(source: &Media, session: &Session) -> Vec<Attribute> {
897 TRANSPORT_ATTRIBUTES
898 .iter()
899 .filter_map(|name| {
900 source
901 .attributes
902 .iter()
903 .chain(&session.attributes)
904 .find(|attribute| attribute.name == *name)
905 .cloned()
906 })
907 .collect()
908}
909
910fn browser_data_from_teams(source: &Media, mid: &str, session: &Session) -> Media {
911 let mut attributes = transport_from_teams(source, session);
912 attributes.push(Attribute::new("mid", mid));
913 attributes.push(Attribute::new("sctp-port", SCTP_PORT));
914 attributes.push(Attribute::new("max-message-size", SCTP_MAX_MESSAGE_SIZE));
915 Media {
916 kind: "application".to_owned(),
917 port: BROWSER_PORT.to_owned(),
918 proto: BROWSER_DATA_PROTO.to_owned(),
919 formats: vec![BROWSER_DATA_FORMAT.to_owned()],
920 connection: Some(BROWSER_CONNECTION.to_owned()),
921 bandwidths: Vec::new(),
922 attributes,
923 }
924}
925
926fn browser_rtp_from_teams(source: &Media, mid: &str, folded: bool, carries_candidate: bool, session: &Session) -> Media {
927 let rtpmap = source.rtpmap();
928 let is_rtx = |payload: &str| rtpmap.get(payload).is_some_and(|encoding| encoding.starts_with("rtx/"));
929 let mut attributes = Vec::new();
930 let mut expanded_feedback: Vec<Attribute> = Vec::new();
931 for attribute in &source.attributes {
932 let value = attribute.value.as_deref().unwrap_or_default();
933 match attribute.name.as_str() {
934 name if TEAMS_ONLY_ATTRIBUTES.contains(&name) => {}
935 name if name.starts_with("x-") => {}
936 "mid" | "rtcp-mux" => {}
937 name if TRANSPORT_ATTRIBUTES.contains(&name) => {}
938 "candidate" => {
939 if carries_candidate && !value.contains(PLACEHOLDER_CANDIDATE_TAIL) {
940 attributes.push(attribute.clone());
941 }
942 }
943 "ssrc" => {
944 let placeholder = value.contains("fake_attribute") || value.starts_with("1 ");
945 if !folded && !placeholder {
946 attributes.push(attribute.clone());
947 }
948 }
949 "ssrc-group" => {
950 if !folded {
951 attributes.push(attribute.clone());
952 }
953 }
954 "rtcp" => attributes.push(Attribute::new("rtcp", BROWSER_RTCP)),
955 "rtpmap" => attributes.push(Attribute::new("rtpmap", browser_rtpmap(value))),
956 "extmap" => attributes.push(Attribute::new("extmap", browser_extmap(value))),
957 "rtcp-fb" => match value.strip_prefix("* ") {
958 Some(kind) => expanded_feedback.extend(
959 source
960 .formats
961 .iter()
962 .filter(|payload| !is_rtx(payload))
963 .map(|payload| Attribute::new("rtcp-fb", format!("{payload} {kind}"))),
964 ),
965 None => attributes.push(attribute.clone()),
966 },
967 _ => attributes.push(attribute.clone()),
968 }
969 }
970 attributes.extend(expanded_feedback);
971 attributes.extend(transport_from_teams(source, session));
972 attributes.push(Attribute::new("mid", mid));
973 attributes.push(Attribute::flag("rtcp-mux"));
974 Media {
975 kind: source.kind.clone(),
976 port: BROWSER_PORT.to_owned(),
977 proto: BROWSER_PROTO.to_owned(),
978 formats: source.formats.clone(),
979 connection: Some(BROWSER_CONNECTION.to_owned()),
980 bandwidths: Vec::new(),
981 attributes,
982 }
983}
984
985fn browser_rtpmap(value: &str) -> String {
986 match value.split_once(' ') {
987 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => format!("{payload} red/48000/2"),
988 _ => value.to_owned(),
989 }
990}
991
992fn browser_extmap(value: &str) -> String {
993 value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "")
994}
995
996/// libwebrtc answers every offered line in the offer's order and with its mids, so the offer's plan applies unchanged.
997pub fn to_teams_answer(browser_answer_sdp: &str, remote: &RemoteOffer, numbers: &mut impl NumberSource) -> Result<SignaledOffer> {
998 to_teams_offer(browser_answer_sdp, &remote.plan(), numbers)
999}
1000
773#[cfg(test)]
1001#[cfg(test)]
774mod tests {
1002mod tests {
775 use super::*;
1003 use super::*;
@@ -828,4 +1056,49 @@ mod tests {
828 assert!(browser.contains("a=group:BUNDLE 0\n"));
1056 assert!(browser.contains("a=group:BUNDLE 0\n"));
829 assert!(!browser.contains("SATINFB") && !browser.contains("MTURNID") && !browser.contains("label"));
1057 assert!(!browser.contains("SATINFB") && !browser.contains("MTURNID") && !browser.contains("label"));
830 }
1058 }
1059 #[test]
1060 fn an_audio_offer_from_teams_gets_the_browser_shape_back() {
1061 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1062 let remote = from_teams_offer(&offer.sdp).unwrap();
1063 let text = remote.browser_sdp.replace("\r\n", "\n");
1064 assert!(text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"), "{text}");
1065 assert!(text.contains("c=IN IP4 0.0.0.0\n"));
1066 assert!(text.contains("a=rtcp:9 IN IP4 0.0.0.0\n"));
1067 assert!(text.contains("a=rtpmap:63 red/48000/2\n"));
1068 assert!(text.contains("a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"));
1069 assert!(text.contains("a=ice-ufrag:u\n") && text.contains("a=fingerprint:sha-256 AA\n") && text.contains("a=setup:actpass\n"));
1070 assert!(text.contains("a=mid:0\n") && text.contains("a=group:BUNDLE 0\n"));
1071 assert!(!text.contains("10.10.10.10") && !text.contains("x-ssrc-range") && !text.contains("label") && !text.contains("1234"));
1072 assert_eq!(remote.lines, offer.lines);
1073 }
1074
1075 #[test]
1076 fn shared_video_feedback_is_spelled_out_per_codec_again() {
1077 let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=video 1234 RTP/SAVP 102 103\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=rtpmap:103 rtx/90000\r\na=fmtp:103 apt=102\r\na=rtcp-fb:* nack\r\na=rtcp-fb:* nack pli\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=label:main-video\r\n";
1078 let remote = from_teams_offer(teams).unwrap();
1079 let text = remote.browser_sdp.replace("\r\n", "\n");
1080 assert!(text.contains("a=rtcp-fb:102 nack\n") && text.contains("a=rtcp-fb:102 nack pli\n"));
1081 assert!(!text.contains("a=rtcp-fb:103") && !text.contains("a=rtcp-fb:*"));
1082 }
1083
1084 #[test]
1085 fn a_rejected_video_line_stays_rejected_and_out_of_the_bundle() {
1086 let audio_and_video = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=label:main-audio\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\n";
1087 let remote = from_teams_offer(audio_and_video).unwrap();
1088 let answer = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 BB\r\na=setup:active\r\na=ssrc:7 cname:x\r\nm=video 0 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na=inactive\r\n";
1089 let signaled = to_teams_answer(answer, &remote, &mut counter()).unwrap();
1090 let text = signaled.sdp.replace("\r\n", "\n");
1091 assert!(text.contains("m=video 0 RTP/SAVP 102\n"), "{text}");
1092 assert!(text.contains("a=group:BUNDLE 0\n"));
1093 let parsed = parse(&signaled.sdp).unwrap();
1094 assert_eq!(parsed.media.len(), 2);
1095 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1096 assert_eq!(parsed.media[1].direction(), Some("inactive"));
1097 }
1098
1099 #[test]
1100 fn folded_gallery_lines_expand_below_their_carrier_mid() {
1101 assert_eq!(folded_mids("17", 8), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());
1102 assert_eq!(folded_mids("x", 2), vec!["x-0".to_owned(), "x".to_owned()]);
1103 }
831}
1104}
crates/calling/src/signaling.rs +692 −99
@@ -1,12 +1,12 @@
1 1 use std::collections::BTreeMap;
2 2
3 use serde_json::{Value, json};
3 use serde_json::{Map, Value, json};
4 4 use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
5 5
6 6 use crate::error::{Error, Result};
7 7 use crate::relay::ic3_scope;
8 8 use crate::timeline::Timeline;
9 use crate::trouter_events::CallbackLinks;
9 use crate::trouter_events::{CallbackLinks, acceptance_links};
10 10
11 11 pub const EPCONV_URL: &str = "https://api-emea.flightproxy.teams.microsoft.com/api/v2/epconv";
12 12 pub const ECHO_BOT_MRI: &str = "28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0";
@@ -17,6 +17,32 @@ const SDP_CONTENT_TYPE: &str = "application/sdp-ngc-1.0";
17 17 const ENDPOINT_CAPABILITIES: u64 = 73463;
18 18 const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
19 19 const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
20 const BACKEND_SUFFIX: &str = ".skype.com";
21 const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
22 const CONVERSATION_LINK_NAMES: [&str; 9] = [
23 "conversationEnd",
24 "conversationUpdate",
25 "localParticipantUpdate",
26 "addParticipantSuccess",
27 "addParticipantFailure",
28 "addModalitySuccess",
29 "addModalityFailure",
30 "confirmUnmute",
31 "receiveMessage",
32 ];
33 const SUBSCRIBE_LINK_NAMES: [&str; 6] = [
34 "conversationEnd",
35 "conversationUpdate",
36 "localParticipantUpdate",
37 "addParticipantSuccess",
38 "addParticipantFailure",
39 "receiveMessage",
40 ];
41 const CALL_LINK_NAMES: [&str; 5] = ["progress", "mediaAnswer", "acceptance", "redirection", "end"];
42 const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
43 const MEETING_MESSAGE_ID: &str = "0";
44 const CANCEL_CODE: i64 = 487;
45 const DECLINE_CODE: i64 = 603;
20 46
21 47 #[derive(Debug, Clone)]
22 48 pub struct Participant {
@@ -28,7 +54,7 @@ pub struct Participant {
28 54 }
29 55
30 56 impl Participant {
31 fn wire(&self) -> Value {
57 pub fn wire(&self) -> Value {
32 58 json!({
33 59 "id": self.mri,
34 60 "displayName": self.display_name,
@@ -39,6 +65,27 @@ impl Participant {
39 65 }
40 66 }
41 67
68 #[derive(Debug, Clone, PartialEq, Eq)]
69 pub struct Callee {
70 pub mri: String,
71 pub display_name: String,
72 }
73
74 #[derive(Debug, Clone, PartialEq)]
75 pub struct MeetingTarget {
76 pub thread_id: String,
77 pub tenant_id: String,
78 pub organizer_id: String,
79 pub meeting_data: Option<Value>,
80 }
81
82 #[derive(Debug, Clone, PartialEq)]
83 pub enum InviteTarget {
84 Echo,
85 People { callees: Vec<Callee>, thread_id: String },
86 Meeting(MeetingTarget),
87 }
88
42 89 #[derive(Debug, Clone)]
43 90 pub struct TenantRouting {
44 91 pub region: String,
@@ -71,13 +118,16 @@ impl Conversation {
71 118 }
72 119 }
73 120
74 /// Bearer requests only go to Teams hosts; links come from server answers.
75 pub fn ensure_teams_url(url: &str) -> Result<()> {
76 let host = url
77 .strip_prefix("https://")
121 fn host_of(url: &str) -> Result<&str> {
122 url.strip_prefix("https://")
78 123 .and_then(|rest| rest.split(['/', '?']).next())
79 124 .map(|authority| authority.split(':').next().unwrap_or(authority))
80 .ok_or_else(|| Error::Signaling("link is not https".into()))?;
125 .ok_or_else(|| Error::Signaling("link is not https".into()))
126 }
127
128 /// Bearer requests only go to Teams hosts; links come from server answers.
129 pub fn ensure_teams_url(url: &str) -> Result<()> {
130 let host = host_of(url)?;
81 131 if ALLOWED_HOST_SUFFIXES.iter().any(|suffix| host.ends_with(suffix)) || host == "teams.microsoft.com" {
82 132 Ok(())
83 133 } else {
@@ -85,6 +135,34 @@ pub fn ensure_teams_url(url: &str) -> Result<()> {
85 135 }
86 136 }
87 137
138 fn is_backend_host(host: &str) -> bool {
139 host.len() > BACKEND_SUFFIX.len()
140 && host.ends_with(BACKEND_SUFFIX)
141 && !host.starts_with('.')
142 && !host.contains("..")
143 && host
144 .bytes()
145 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-')
146 }
147
148 /// Push links may name a backend host directly; the browser always reaches those through flightproxy.
149 pub fn routed_url(url: &str) -> Result<String> {
150 let host = host_of(url)?;
151 if !is_backend_host(host) {
152 ensure_teams_url(url)?;
153 return Ok(url.to_owned());
154 }
155 let rest = &url["https://".len()..];
156 let path = rest.find(['/', '?']).map_or("", |position| &rest[position..]);
157 Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))
158 }
159
160 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
161 pub enum LeaveReason {
162 Hangup,
163 Cancel,
164 }
165
88 166 pub struct Signaling {
89 167 session: Session,
90 168 poll_session: Session,
@@ -94,11 +172,36 @@ pub struct Signaling {
94 172 endpoint_state_sequence: std::sync::atomic::AtomicU32,
95 173 }
96 174
97 pub struct EchoInvitation<'a> {
175 pub struct Invitation<'a> {
98 176 pub from: &'a Participant,
99 177 pub offer_sdp: &'a str,
100 178 pub media_leg_id: &'a str,
101 179 pub callbacks: &'a CallbackLinks,
180 pub target: &'a InviteTarget,
181 }
182
183 pub struct Answer<'a> {
184 pub from: &'a Participant,
185 pub answer_sdp: &'a str,
186 pub media_leg_id: &'a str,
187 pub callbacks: &'a CallbackLinks,
188 pub modalities: &'a [String],
189 }
190
191 pub struct AttachRequest<'a> {
192 pub from: &'a Participant,
193 pub callbacks: &'a CallbackLinks,
194 pub controller: Option<&'a str>,
195 pub needs_media: bool,
196 }
197
198 #[derive(Debug, Clone)]
199 pub struct Attached {
200 pub offer_sdp: Option<String>,
201 pub from_mixer: bool,
202 pub modalities: Vec<String>,
203 pub links: BTreeMap<String, String>,
204 pub conversation: Option<Conversation>,
102 205 }
103 206
104 207 impl Signaling {
@@ -132,8 +235,8 @@ impl Signaling {
132 235 request
133 236 }
134 237
135 async fn exchange(&self, session: &Session, label: &str, request: Request) -> Result<ApiResponse> {
136 ensure_teams_url(&request.url)?;
238 async fn exchange(&self, session: &Session, label: &str, mut request: Request) -> Result<ApiResponse> {
239 request.url = routed_url(&request.url)?;
137 240 let response = session.batch(&[request], &ic3_scope()).await?.remove(0);
138 241 self.timeline.record(label, format!("HTTP {}", response.status));
139 242 if !response.is_success() {
@@ -142,31 +245,66 @@ impl Signaling {
142 245 Ok(response)
143 246 }
144 247
145 pub async fn create_conversation(&self, invitation: &EchoInvitation<'_>) -> Result<Conversation> {
146 let body = epconv_body(invitation);
248 async fn send(&self, label: &str, method: Method, url: &str, body: Option<Value>) -> Result<ApiResponse> {
249 self.exchange(&self.session, label, self.request(method, url, body)).await
250 }
251
252 pub async fn post_json(&self, label: &str, url: &str, body: Value) -> Result<()> {
253 self.send(label, Method::Post, url, Some(body)).await.map(|_| ())
254 }
255
256 pub async fn post_empty(&self, label: &str, url: &str) -> Result<()> {
257 self.send(label, Method::Post, url, None).await.map(|_| ())
258 }
259
260 pub async fn create_conversation(&self, invitation: &Invitation<'_>) -> Result<Conversation> {
147 261 let response = self
148 .exchange(&self.session, "POST epconv", self.request(Method::Post, EPCONV_URL, Some(body)))
262 .send("POST epconv", Method::Post, EPCONV_URL, Some(epconv_body(invitation)))
149 263 .await?;
150 264 conversation_from(&response.body)
151 265 }
152 266
267 pub async fn subscribe_meeting(
268 &self,
269 from: &Participant,
270 callbacks: &CallbackLinks,
271 meeting: &MeetingTarget,
272 ) -> Result<Conversation> {
273 let body = subscribe_body(from, callbacks, meeting);
274 let response = self.send("POST epconv subscribe", Method::Post, EPCONV_URL, Some(body)).await?;
275 conversation_from(&response.body)
276 }
277
278 /// Joins with the offer; the answer may restate the conversation links, otherwise the subscribed ones stay.
279 pub async fn join_meeting(&self, subscribed: &Conversation, invitation: &Invitation<'_>) -> Result<Conversation> {
280 let response = self
281 .send("POST join", Method::Post, &subscribed.controller, Some(epconv_body(invitation)))
282 .await?;
283 let mut links = subscribed.links.clone();
284 if let Ok(joined) = conversation_from(&response.body) {
285 links.extend(joined.links);
286 }
287 Ok(Conversation {
288 controller: subscribed.controller.clone(),
289 links,
290 })
291 }
292
293 pub fn next_endpoint_sequence(&self) -> u32 {
294 self.endpoint_state_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1
295 }
296
153 297 pub async fn update_endpoint_state(&self, conversation: &Conversation, from: &Participant, muted: bool) -> Result<()> {
154 let sequence = self
155 .endpoint_state_sequence
156 .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
157 + 1;
158 298 let body = json!({
159 299 "from": from.wire(),
160 300 "endpointState": {
161 "endpointStateSequenceNumber": sequence,
301 "endpointStateSequenceNumber": self.next_endpoint_sequence(),
162 302 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
163 303 "state": {"isMuted": muted},
164 304 },
165 305 });
166 306 let url = conversation.link("updateEndpointState")?;
167 self.exchange(&self.session, "POST updateEndpointState", self.request(Method::Post, url, Some(body)))
168 .await
169 .map(|_| ())
307 self.post_json("POST updateEndpointState", url, body).await
170 308 }
171 309
172 310 pub async fn add_echo_bot(
@@ -192,9 +330,7 @@ impl Signaling {
192 330 },
193 331 });
194 332 let url = conversation.link("addParticipantAndModality")?;
195 self.exchange(&self.session, "POST add (echo bot)", self.request(Method::Post, url, Some(body)))
196 .await
197 .map(|_| ())
333 self.post_json("POST add (echo bot)", url, body).await
198 334 }
199 335
200 336 pub async fn update_endpoint_metadata(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
@@ -203,9 +339,7 @@ impl Signaling {
203 339 "endpointMetadata": {"holographicCapabilities": 3},
204 340 });
205 341 let url = conversation.link("updateEndpointMetadata")?;
206 self.exchange(&self.session, "PUT updateEndpointMetadata", self.request(Method::Put, url, Some(body)))
207 .await
208 .map(|_| ())
342 self.send("PUT updateEndpointMetadata", Method::Put, url, Some(body)).await.map(|_| ())
209 343 }
210 344
211 345 /// One broker long poll; answers the next subscribe URL.
@@ -216,96 +350,313 @@ impl Signaling {
216 350 Ok(response.body["nextSubscribeUrl"].as_str().map(str::to_owned))
217 351 }
218 352
219 pub async fn leave(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
220 let body = json!({
221 "participants": {"from": from.wire()},
222 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"},
223 "callTransactionEnd": {"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]},
224 });
353 pub async fn leave(&self, conversation: &Conversation, from: &Participant, reason: LeaveReason) -> Result<()> {
225 354 let url = conversation.link("leave")?;
226 self.exchange(&self.session, "POST leave", self.request(Method::Post, url, Some(body)))
355 self.post_json("POST leave", url, leave_body(from, reason)).await
356 }
357
358 pub async fn end_for_all(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
359 self.send(
360 "DELETE conversation",
361 Method::Delete,
362 &conversation.controller,
363 Some(end_for_all_body(from)),
364 )
365 .await
366 .map(|_| ())
367 }
368
369 pub async fn attach(&self, url: &str, request: &AttachRequest<'_>) -> Result<Attached> {
370 let response = self
371 .send("POST attach", Method::Post, url, Some(attach_body(request)))
372 .await?;
373 attached_from(&response.body)
374 }
375
376 pub async fn send_ringing(&self, url: &str, from: &Participant) -> Result<()> {
377 self.post_json("POST progress", url, ringing_body(from)).await
378 }
379
380 pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<()> {
381 self.post_json("POST acceptance", url, acceptance_body(answer)).await
382 }
383
384 pub async fn decline(&self, call_leg_url: &str) -> Result<()> {
385 self.send("DELETE callLeg (decline)", Method::Delete, call_leg_url, Some(decline_body()))
227 386 .await
228 387 .map(|_| ())
229 388 }
389
390 pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> {
391 self.post_json("POST callLeg keep-alive", call_leg_url, json!({"callParticipantUpdate": {}}))
392 .await
393 }
394
395 pub async fn keep_conversation_alive(
396 &self,
397 conversation: &Conversation,
398 from: &Participant,
399 callbacks: &CallbackLinks,
400 ) -> Result<()> {
401 let url = conversation.link("notificationLinks")?;
402 self.post_json("POST notificationLinks", url, notification_links_body(from, callbacks)).await
403 }
404 }
405
406 fn link_map(names: &[&str], make: impl Fn(&str) -> String) -> Map<String, Value> {
407 names
408 .iter()
409 .map(|name| ((*name).to_owned(), Value::String(make(name))))
410 .collect()
411 }
412
413 fn roster_request(callbacks: &CallbackLinks) -> Value {
414 json!({"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")})
415 }
416
417 fn conversation_properties() -> Value {
418 json!({
419 "allowConversationWithoutHost": true,
420 "enableGroupCallEventMessages": true,
421 "enableGroupCallUpgradeMessage": false,
422 "enableGroupCallMeetupGeneration": false,
423 })
424 }
425
426 fn endpoint_state() -> Value {
427 json!({
428 "endpointStateSequenceNumber": 2,
429 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
430 })
431 }
432
433 fn media_content(sdp: &str, media_leg_id: &str, with_descriptions: bool) -> Value {
434 let mut content = json!({
435 "contentType": SDP_CONTENT_TYPE,
436 "blob": sdp,
437 "clientLocation": "DE",
438 "mediaLegId": media_leg_id,
439 });
440 if with_descriptions {
441 content["mediaDescriptions"] = json!({"descriptions": [], "requestId": 1});
442 }
443 content
444 }
445
446 fn media_controller_links(callbacks: &CallbackLinks) -> Value {
447 json!({
448 "controlVideoStreaming": callbacks.call("controlVideoStreaming"),
449 "csrcInfo": callbacks.call("csrcInfo"),
450 })
451 }
452
453 fn group_chat(target: &InviteTarget) -> Value {
454 match target {
455 InviteTarget::Echo => Value::Null,
456 InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}),
457 InviteTarget::Meeting(meeting) => json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}),
458 }
459 }
460
461 fn callee_wire(callee: &Callee) -> Value {
462 json!({"id": callee.mri, "displayName": callee.display_name})
230 463 }
231 464
232 pub fn epconv_body(invitation: &EchoInvitation<'_>) -> Value {
465 pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
233 466 let callbacks = invitation.callbacks;
234 let conversation_links: serde_json::Map<String, Value> = [
235 "conversationEnd",
236 "conversationUpdate",
237 "localParticipantUpdate",
238 "addParticipantSuccess",
239 "addParticipantFailure",
240 "addModalitySuccess",
241 "addModalityFailure",
242 "confirmUnmute",
243 "receiveMessage",
244 ]
245 .into_iter()
246 .map(|name| (name.to_owned(), Value::String(callbacks.conversation(name))))
247 .collect();
248 let call_links: serde_json::Map<String, Value> = ["progress", "mediaAnswer", "acceptance", "redirection", "end"]
249 .into_iter()
250 .map(|name| (name.to_owned(), Value::String(callbacks.call(name))))
251 .collect();
467 let target = invitation.target;
468 let to: Vec<Value> = match target {
469 InviteTarget::People { callees, .. } => callees.iter().map(callee_wire).collect(),
470 InviteTarget::Echo | InviteTarget::Meeting(_) => Vec::new(),
471 };
472 let mut request = json!({
473 "conversationType": null,
474 "subject": null,
475 "suppressDialout": true,
476 "roster": roster_request(callbacks),
477 "properties": conversation_properties(),
478 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
479 });
480 if matches!(target, InviteTarget::Echo) {
481 request["scenario"] = json!("UserInitiatedTestCall");
482 }
483 let (meeting_info, meeting_data) = match target {
484 InviteTarget::Meeting(meeting) => (
485 json!({"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}),
486 meeting.meeting_data.clone().unwrap_or(Value::Null),
487 ),
488 _ => (Value::Null, Value::Null),
489 };
252 490 json!({
253 "conversationRequest": {
254 "conversationType": null,
255 "subject": null,
256 "suppressDialout": true,
257 "roster": {"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")},
258 "properties": {
259 "allowConversationWithoutHost": true,
260 "enableGroupCallEventMessages": true,
261 "enableGroupCallUpgradeMessage": false,
262 "enableGroupCallMeetupGeneration": false,
263 },
264 "links": conversation_links,
265 "scenario": "UserInitiatedTestCall",
266 },
491 "conversationRequest": request,
267 492 "contentSharing": null,
268 "participants": {"from": invitation.from.wire(), "to": []},
493 "participants": {"from": invitation.from.wire(), "to": to},
269 494 "capabilities": null,
270 495 "endpointCapabilities": ENDPOINT_CAPABILITIES,
271 496 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
272 497 "endpointMetadata": {"holographicCapabilities": 3},
273 498 "groupContext": null,
274 "groupChat": null,
275 "meetingInfo": null,
276 "meetingData": null,
277 "endpointState": {
278 "endpointStateSequenceNumber": 2,
279 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
280 },
499 "groupChat": group_chat(target),
500 "meetingInfo": meeting_info,
501 "meetingData": meeting_data,
502 "endpointState": endpoint_state(),
281 503 "callInvitation": {
282 "callModalities": ["Audio"],
504 "callModalities": AUDIO_MODALITIES,
283 505 "replaces": null,
284 506 "transferor": null,
285 507 "clientTransferContext": null,
286 508 "customContext": null,
287 "links": call_links,
288 "clientContentForMediaController": {
289 "controlVideoStreaming": callbacks.call("controlVideoStreaming"),
290 "csrcInfo": callbacks.call("csrcInfo"),
291 },
509 "links": link_map(&CALL_LINK_NAMES, |name| callbacks.call(name)),
510 "clientContentForMediaController": media_controller_links(callbacks),
292 511 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
293 512 "emergencyContent": null,
294 "mediaContent": {
295 "contentType": SDP_CONTENT_TYPE,
296 "blob": invitation.offer_sdp,
297 "clientLocation": "DE",
298 "mediaDescriptions": {"descriptions": [], "requestId": 1},
299 "mediaLegId": invitation.media_leg_id,
513 "mediaContent": media_content(invitation.offer_sdp, invitation.media_leg_id, true),
514 },
515 })
516 }
517
518 pub fn subscribe_body(from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget) -> Value {
519 json!({
520 "conversationRequest": {
521 "roster": roster_request(callbacks),
522 "properties": conversation_properties(),
523 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
524 },
525 "participants": {"from": from.wire()},
526 "groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID},
527 "meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id},
528 "endpointState": endpoint_state(),
529 })
530 }
531
532 pub fn leave_body(from: &Participant, reason: LeaveReason) -> Value {
533 let call_end = match reason {
534 LeaveReason::Hangup => json!({"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}),
535 LeaveReason::Cancel => json!({"code": CANCEL_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated"}),
536 };
537 json!({
538 "participants": {"from": from.wire()},
539 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"},
540 "callTransactionEnd": call_end,
541 })
542 }
543
544 pub fn end_for_all_body(from: &Participant) -> Value {
545 json!({
546 "participants": {"from": from.wire()},
547 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndForAllInitiated"},
548 "callTransactionEnd": {"code": 0, "phrase": "CallEndReasonLocalUserInitiated"},
549 })
550 }
551
552 pub fn decline_body() -> Value {
553 json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
554 }
555
556 pub fn ringing_body(from: &Participant) -> Value {
557 json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}})
558 }
559
560 pub fn attach_body(request: &AttachRequest<'_>) -> Value {
561 let callbacks = request.callbacks;
562 let mut body = json!({
563 "attach": {
564 "requireMediaContent": request.needs_media,
565 "links": {"end": callbacks.call("end")},
566 },
567 "capabilities": null,
568 "endpointCapabilities": ENDPOINT_CAPABILITIES,
569 });
570 if let Some(controller) = request.controller {
571 body["additionalActions"] = json!([{
572 "name": "join",
573 "url": controller,
574 "waitForResponse": true,
575 "input": {
576 "conversationRequest": {
577 "roster": roster_request(callbacks),
578 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
579 },
580 "participants": {"from": request.from.wire()},
581 "endpointMetadata": {"holographicCapabilities": 3},
582 "endpointCapabilities": ENDPOINT_CAPABILITIES,
300 583 },
584 }]);
585 }
586 body
587 }
588
589 pub fn acceptance_body(answer: &Answer<'_>) -> Value {
590 let callbacks = answer.callbacks;
591 json!({
592 "callAcceptance": {
593 "acceptedBy": answer.from.wire(),
594 "acceptedCallModalities": answer.modalities,
595 "endpointCapabilities": ENDPOINT_CAPABILITIES,
596 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
597 "links": acceptance_links(callbacks),
598 "clientContentForMediaController": media_controller_links(callbacks),
599 "mediaContent": media_content(answer.answer_sdp, answer.media_leg_id, false),
600 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
601 "callKeepAliveInterval": null,
602 },
603 })
604 }
605
606 pub fn renegotiation_body(
607 from: &Participant,
608 callbacks: &CallbackLinks,
609 offer_sdp: &str,
610 media_leg_id: &str,
611 ) -> Value {
612 json!({
613 "mediaNegotiation": {
614 "callModalities": AUDIO_MODALITIES,
615 "sender": from.wire(),
616 "links": {
617 "mediaAnswer": callbacks.call("mediaAnswer"),
618 "rejection": callbacks.call("rejection"),
619 },
620 "mediaContent": renegotiation_content(offer_sdp, media_leg_id),
621 },
622 })
623 }
624
625 fn renegotiation_content(sdp: &str, media_leg_id: &str) -> Value {
626 let mut content = media_content(sdp, media_leg_id, true);
627 content["newOffer"] = json!(true);
628 content
629 }
630
631 pub fn escalation_answer_body(
632 from: &Participant,
633 callbacks: &CallbackLinks,
634 answer_sdp: &str,
635 media_leg_id: &str,
636 ) -> Value {
637 json!({
638 "mediaAnswer": {
639 "callModalities": AUDIO_MODALITIES,
640 "sender": from.wire(),
641 "links": {"mediaAcknowledgement": callbacks.call("mediaAcknowledgement")},
642 "clientContentForMediaController": media_controller_links(callbacks),
643 "mediaContent": media_content(answer_sdp, media_leg_id, false),
301 644 },
302 645 })
303 646 }
304 647
648 pub fn notification_links_body(from: &Participant, callbacks: &CallbackLinks) -> Value {
649 json!({
650 "participants": {"from": from.wire()},
651 "roster": roster_request(callbacks),
652 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
653 })
654 }
655
305 656 fn conversation_from(body: &Value) -> Result<Conversation> {
306 657 let controller = body["conversationController"]
307 658 .as_str()
308 .ok_or_else(|| Error::Signaling("epconv answer without conversationController".into()))?
659 .ok_or_else(|| Error::Signaling("answer without conversationController".into()))?
309 660 .to_owned();
310 661 let links = body["links"]
311 662 .as_object()
@@ -319,6 +670,33 @@ fn conversation_from(body: &Value) -> Result<Conversation> {
319 670 Ok(Conversation { controller, links })
320 671 }
321 672
673 fn attached_from(body: &Value) -> Result<Attached> {
674 let invitation = &body["callInvitation"];
675 if invitation.is_null() {
676 return Err(Error::Signaling("attach answer without callInvitation".into()));
677 }
678 let links = invitation["links"]
679 .as_object()
680 .map(|links| {
681 links
682 .iter()
683 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
684 .collect()
685 })
686 .unwrap_or_default();
687 let modalities = invitation["callModalities"]
688 .as_array()
689 .map(|items| items.iter().filter_map(|item| item.as_str().map(str::to_owned)).collect())
690 .unwrap_or_default();
691 Ok(Attached {
692 offer_sdp: invitation["mediaContent"]["blob"].as_str().map(str::to_owned),
693 from_mixer: invitation["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
694 modalities,
695 links,
696 conversation: conversation_from(&body["additionalActionResponses"][0]["output"]).ok(),
697 })
698 }
699
322 700 #[derive(Debug, Clone)]
323 701 pub struct SelfIdentity {
324 702 pub object_id: String,
@@ -366,6 +744,39 @@ pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Re
366 744 mod tests {
367 745 use super::*;
368 746
747 fn from() -> Participant {
748 Participant {
749 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
750 display_name: "Test".into(),
751 endpoint_id: "e".into(),
752 participant_id: "p".into(),
753 language_id: "en-gb".into(),
754 }
755 }
756
757 fn callbacks() -> CallbackLinks {
758 CallbackLinks::new("https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/", "call-1")
759 }
760
761 fn body_for(target: &InviteTarget) -> Value {
762 let from = from();
763 let callbacks = callbacks();
764 epconv_body(&Invitation {
765 from: &from,
766 offer_sdp: "v=0\r\n",
767 media_leg_id: "AB",
768 callbacks: &callbacks,
769 target,
770 })
771 }
772
773 fn callee(mri: &str, name: &str) -> Callee {
774 Callee {
775 mri: mri.into(),
776 display_name: name.into(),
777 }
778 }
779
369 780 #[test]
370 781 fn only_teams_hosts_get_the_bearer() {
371 782 assert!(ensure_teams_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/conv-x/conv/1/leave?i=1").is_ok());
@@ -377,20 +788,202 @@ mod tests {
377 788 }
378 789
379 790 #[test]
380 fn epconv_body_matches_the_captured_test_call_shape() {
381 let from = Participant {
382 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
383 display_name: "Test".into(),
384 endpoint_id: "e".into(),
385 participant_id: "p".into(),
386 language_id: "en-gb".into(),
387 };
388 let callbacks = CallbackLinks::new("https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/", "call-1");
389 let body = epconv_body(&EchoInvitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks });
791 fn backend_links_go_through_flightproxy() {
792 assert_eq!(
793 routed_url("https://cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2").unwrap(),
794 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2"
795 );
796 assert_eq!(
797 routed_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y").unwrap(),
798 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
799 );
800 assert!(routed_url("https://evil.skype.com.example/x").is_err());
801 assert!(routed_url("https://Evil.skype.com/x").is_err());
802 assert!(routed_url("https://user@cc.skype.com/x").is_err());
803 assert!(routed_url("http://cc.skype.com/x").is_err());
804 assert!(routed_url("https://.skype.com/x").is_err());
805 }
806
807 #[test]
808 fn echo_body_matches_the_captured_test_call_shape() {
809 let body = body_for(&InviteTarget::Echo);
390 810 assert_eq!(body["conversationRequest"]["scenario"], "UserInitiatedTestCall");
391 811 assert_eq!(body["participants"]["to"], json!([]));
812 assert_eq!(body["groupChat"], Value::Null);
813 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
392 814 assert_eq!(body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE);
393 815 assert!(body["callInvitation"]["links"]["acceptance"].as_str().unwrap().ends_with("/call/acceptance/"));
394 816 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 9);
395 817 }
818
819 #[test]
820 fn one_to_one_body_names_the_callee_and_the_chat() {
821 let target = InviteTarget::People {
822 callees: vec![callee("8:orgid:b", "Bea")],
823 thread_id: "19:a_b@unq.gbl.spaces".into(),
824 };
825 let body = body_for(&target);
826 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:b", "displayName": "Bea"}]));
827 assert_eq!(body["groupChat"], json!({"threadId": "19:a_b@unq.gbl.spaces", "messageId": null}));
828 assert!(body["conversationRequest"].get("scenario").is_none());
829 assert_eq!(body["meetingInfo"], Value::Null);
830 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
831 }
832
833 #[test]
834 fn group_body_invites_every_callee_on_the_group_thread() {
835 let target = InviteTarget::People {
836 callees: vec![callee("8:orgid:b", "Bea"), callee("8:orgid:c", "Cy"), callee("8:orgid:d", "Di")],
837 thread_id: "19:group@thread.v2".into(),
838 };
839 let body = body_for(&target);
840 let to = body["participants"]["to"].as_array().unwrap();
841 assert_eq!(to.len(), 3);
842 assert_eq!(to[2]["id"], "8:orgid:d");
843 assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2");
844 assert_eq!(body["groupChat"]["messageId"], Value::Null);
845 }
846
847 #[test]
848 fn meeting_join_body_carries_thread_and_meeting_info() {
849 let target = InviteTarget::Meeting(MeetingTarget {
850 thread_id: "19:meeting_x@thread.v2".into(),
851 tenant_id: "tenant".into(),
852 organizer_id: "organizer".into(),
853 meeting_data: Some(json!({"meetingCode": "123"})),
854 });
855 let body = body_for(&target);
856 assert_eq!(body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}));
857 assert_eq!(body["meetingInfo"], json!({"tenantId": "tenant", "organizerId": "organizer"}));
858 assert_eq!(body["meetingData"]["meetingCode"], "123");
859 assert_eq!(body["participants"]["to"], json!([]));
860 assert!(body["conversationRequest"].get("scenario").is_none());
861 assert!(body["endpointState"]["endpointProperties"].get("preheatProperties").is_none());
862 }
863
864 #[test]
865 fn meeting_subscribe_is_roster_only() {
866 let meeting = MeetingTarget {
867 thread_id: "19:meeting_x@thread.v2".into(),
868 tenant_id: "tenant".into(),
869 organizer_id: "organizer".into(),
870 meeting_data: None,
871 };
872 let body = subscribe_body(&from(), &callbacks(), &meeting);
873 assert!(body.get("callInvitation").is_none());
874 assert!(body["participants"].get("to").is_none());
875 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 6);
876 assert_eq!(body["groupChat"]["messageId"], "0");
877 assert_eq!(body["meetingInfo"]["organizerId"], "organizer");
878 }
879
880 #[test]
881 fn leave_bodies_differ_by_reason() {
882 let hangup = leave_body(&from(), LeaveReason::Hangup);
883 assert_eq!(hangup["callTransactionEnd"]["code"], 0);
884 let cancel = leave_body(&from(), LeaveReason::Cancel);
885 assert_eq!(cancel["callTransactionEnd"]["code"], 487);
886 assert_eq!(cancel["callTransactionEnd"]["phrase"], "CallEndReasonLocalUserInitiated");
887 assert_eq!(cancel["conversationTransactionEnd"]["phrase"], "ConversationEndNoModalityConnected");
888 let end = end_for_all_body(&from());
889 assert_eq!(end["conversationTransactionEnd"]["phrase"], "ConversationEndForAllInitiated");
890 }
891
892 #[test]
893 fn decline_uses_603() {
894 let body = decline_body();
895 assert_eq!(body["callEnd"]["code"], 603);
896 assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"]));
897 }
898
899 #[test]
900 fn attach_asks_for_media_and_joins_the_conversation() {
901 let from = from();
902 let callbacks = callbacks();
903 let body = attach_body(&AttachRequest {
904 from: &from,
905 callbacks: &callbacks,
906 controller: Some("https://conv/controller"),
907 needs_media: true,
908 });
909 assert_eq!(body["attach"]["requireMediaContent"], true);
910 assert!(body["attach"]["links"]["end"].as_str().unwrap().ends_with("/call/end/"));
911 let action = &body["additionalActions"][0];
912 assert_eq!(action["name"], "join");
913 assert_eq!(action["url"], "https://conv/controller");
914 assert_eq!(action["waitForResponse"], true);
915 assert_eq!(action["input"]["conversationRequest"]["links"].as_object().unwrap().len(), 6);
916 let without = attach_body(&AttachRequest {
917 from: &from,
918 callbacks: &callbacks,
919 controller: None,
920 needs_media: false,
921 });
922 assert!(without.get("additionalActions").is_none());
923 assert_eq!(without["attach"]["requireMediaContent"], false);
924 }
925
926 #[test]
927 fn attach_answer_yields_offer_links_and_conversation() {
928 let body = json!({
929 "callInvitation": {
930 "links": {"acceptance": "https://cc/accept", "callLeg": "https://cc/leg", "progress": "https://cc/progress"},
931 "mediaContent": {"blob": "v=0\r\n"},
932 "callModalities": ["Audio"],
933 },
934 "additionalActionResponses": [{"output": {"conversationController": "https://conv/c", "links": {"leave": "https://conv/leave"}}}],
935 });
936 let attached = attached_from(&body).unwrap();
937 assert_eq!(attached.offer_sdp.as_deref(), Some("v=0\r\n"));
938 assert_eq!(attached.links["callLeg"], "https://cc/leg");
939 assert_eq!(attached.modalities, vec!["Audio".to_owned()]);
940 let conversation = attached.conversation.unwrap();
941 assert_eq!(conversation.controller, "https://conv/c");
942 assert_eq!(conversation.link("leave").unwrap(), "https://conv/leave");
943 assert!(attached_from(&json!({})).is_err());
944 }
945
946 #[test]
947 fn acceptance_carries_the_answer_and_callback_links() {
948 let from = from();
949 let callbacks = callbacks();
950 let modalities = vec!["Audio".to_owned()];
951 let body = acceptance_body(&Answer {
952 from: &from,
953 answer_sdp: "v=0\r\n",
954 media_leg_id: "AB",
955 callbacks: &callbacks,
956 modalities: &modalities,
957 });
958 let accepted = &body["callAcceptance"];
959 assert_eq!(accepted["acceptedBy"]["id"], from.mri);
960 assert_eq!(accepted["acceptedCallModalities"], json!(["Audio"]));
961 assert_eq!(accepted["mediaContent"]["blob"], "v=0\r\n");
962 assert_eq!(accepted["links"].as_object().unwrap().len(), 7);
963 assert!(accepted["links"]["mediaRenegotiation"].as_str().unwrap().ends_with("/call/mediaRenegotiation/"));
964 assert_eq!(accepted["callKeepAliveInterval"], Value::Null);
965 }
966
967 #[test]
968 fn renegotiation_messages_name_their_reply_links() {
969 let from = from();
970 let callbacks = callbacks();
971 let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB");
972 let negotiation = &offer["mediaNegotiation"];
973 assert_eq!(negotiation["mediaContent"]["newOffer"], true);
974 assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));
975 assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));
976 let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB");
977 assert!(answer["mediaAnswer"]["links"]["mediaAcknowledgement"]
978 .as_str()
979 .unwrap()
980 .ends_with("/call/mediaAcknowledgement/"));
981 }
982
983 #[test]
984 fn ringing_progress_names_the_sender() {
985 let body = ringing_body(&from());
986 assert_eq!(body["callProgress"]["status"], "ringing");
987 assert_eq!(body["callProgress"]["sender"]["id"], from().mri);
988 }
396 989 }
@@ -1,12 +1,12 @@
1use std::collections::BTreeMap;
1use std::collections::BTreeMap;
2
2
3use serde_json::{Value, json};
3use serde_json::{Map, Value, json};
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::relay::ic3_scope;
7use crate::relay::ic3_scope;
8use crate::timeline::Timeline;
8use crate::timeline::Timeline;
9use crate::trouter_events::CallbackLinks;
9use crate::trouter_events::{CallbackLinks, acceptance_links};
10
10
11pub const EPCONV_URL: &str = "https://api-emea.flightproxy.teams.microsoft.com/api/v2/epconv";
11pub const EPCONV_URL: &str = "https://api-emea.flightproxy.teams.microsoft.com/api/v2/epconv";
12pub const ECHO_BOT_MRI: &str = "28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0";
12pub const ECHO_BOT_MRI: &str = "28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0";
@@ -17,6 +17,32 @@ const SDP_CONTENT_TYPE: &str = "application/sdp-ngc-1.0";
17const ENDPOINT_CAPABILITIES: u64 = 73463;
17const ENDPOINT_CAPABILITIES: u64 = 73463;
18const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
18const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
19const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
19const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
20const BACKEND_SUFFIX: &str = ".skype.com";
21const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
22const CONVERSATION_LINK_NAMES: [&str; 9] = [
23 "conversationEnd",
24 "conversationUpdate",
25 "localParticipantUpdate",
26 "addParticipantSuccess",
27 "addParticipantFailure",
28 "addModalitySuccess",
29 "addModalityFailure",
30 "confirmUnmute",
31 "receiveMessage",
32];
33const SUBSCRIBE_LINK_NAMES: [&str; 6] = [
34 "conversationEnd",
35 "conversationUpdate",
36 "localParticipantUpdate",
37 "addParticipantSuccess",
38 "addParticipantFailure",
39 "receiveMessage",
40];
41const CALL_LINK_NAMES: [&str; 5] = ["progress", "mediaAnswer", "acceptance", "redirection", "end"];
42const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
43const MEETING_MESSAGE_ID: &str = "0";
44const CANCEL_CODE: i64 = 487;
45const DECLINE_CODE: i64 = 603;
20
46
21#[derive(Debug, Clone)]
47#[derive(Debug, Clone)]
22pub struct Participant {
48pub struct Participant {
@@ -28,7 +54,7 @@ pub struct Participant {
28}
54}
29
55
30impl Participant {
56impl Participant {
31 fn wire(&self) -> Value {
57 pub fn wire(&self) -> Value {
32 json!({
58 json!({
33 "id": self.mri,
59 "id": self.mri,
34 "displayName": self.display_name,
60 "displayName": self.display_name,
@@ -39,6 +65,27 @@ impl Participant {
39 }
65 }
40}
66}
41
67
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Callee {
70 pub mri: String,
71 pub display_name: String,
72}
73
74#[derive(Debug, Clone, PartialEq)]
75pub struct MeetingTarget {
76 pub thread_id: String,
77 pub tenant_id: String,
78 pub organizer_id: String,
79 pub meeting_data: Option<Value>,
80}
81
82#[derive(Debug, Clone, PartialEq)]
83pub enum InviteTarget {
84 Echo,
85 People { callees: Vec<Callee>, thread_id: String },
86 Meeting(MeetingTarget),
87}
88
42#[derive(Debug, Clone)]
89#[derive(Debug, Clone)]
43pub struct TenantRouting {
90pub struct TenantRouting {
44 pub region: String,
91 pub region: String,
@@ -71,13 +118,16 @@ impl Conversation {
71 }
118 }
72}
119}
73
120
74/// Bearer requests only go to Teams hosts; links come from server answers.
121fn host_of(url: &str) -> Result<&str> {
75pub fn ensure_teams_url(url: &str) -> Result<()> {
122 url.strip_prefix("https://")
76 let host = url
77 .strip_prefix("https://")
78 .and_then(|rest| rest.split(['/', '?']).next())
123 .and_then(|rest| rest.split(['/', '?']).next())
79 .map(|authority| authority.split(':').next().unwrap_or(authority))
124 .map(|authority| authority.split(':').next().unwrap_or(authority))
80 .ok_or_else(|| Error::Signaling("link is not https".into()))?;
125 .ok_or_else(|| Error::Signaling("link is not https".into()))
126}
127
128/// Bearer requests only go to Teams hosts; links come from server answers.
129pub fn ensure_teams_url(url: &str) -> Result<()> {
130 let host = host_of(url)?;
81 if ALLOWED_HOST_SUFFIXES.iter().any(|suffix| host.ends_with(suffix)) || host == "teams.microsoft.com" {
131 if ALLOWED_HOST_SUFFIXES.iter().any(|suffix| host.ends_with(suffix)) || host == "teams.microsoft.com" {
82 Ok(())
132 Ok(())
83 } else {
133 } else {
@@ -85,6 +135,34 @@ pub fn ensure_teams_url(url: &str) -> Result<()> {
85 }
135 }
86}
136}
87
137
138fn is_backend_host(host: &str) -> bool {
139 host.len() > BACKEND_SUFFIX.len()
140 && host.ends_with(BACKEND_SUFFIX)
141 && !host.starts_with('.')
142 && !host.contains("..")
143 && host
144 .bytes()
145 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-')
146}
147
148/// Push links may name a backend host directly; the browser always reaches those through flightproxy.
149pub fn routed_url(url: &str) -> Result<String> {
150 let host = host_of(url)?;
151 if !is_backend_host(host) {
152 ensure_teams_url(url)?;
153 return Ok(url.to_owned());
154 }
155 let rest = &url["https://".len()..];
156 let path = rest.find(['/', '?']).map_or("", |position| &rest[position..]);
157 Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum LeaveReason {
162 Hangup,
163 Cancel,
164}
165
88pub struct Signaling {
166pub struct Signaling {
89 session: Session,
167 session: Session,
90 poll_session: Session,
168 poll_session: Session,
@@ -94,11 +172,36 @@ pub struct Signaling {
94 endpoint_state_sequence: std::sync::atomic::AtomicU32,
172 endpoint_state_sequence: std::sync::atomic::AtomicU32,
95}
173}
96
174
97pub struct EchoInvitation<'a> {
175pub struct Invitation<'a> {
98 pub from: &'a Participant,
176 pub from: &'a Participant,
99 pub offer_sdp: &'a str,
177 pub offer_sdp: &'a str,
100 pub media_leg_id: &'a str,
178 pub media_leg_id: &'a str,
101 pub callbacks: &'a CallbackLinks,
179 pub callbacks: &'a CallbackLinks,
180 pub target: &'a InviteTarget,
181}
182
183pub struct Answer<'a> {
184 pub from: &'a Participant,
185 pub answer_sdp: &'a str,
186 pub media_leg_id: &'a str,
187 pub callbacks: &'a CallbackLinks,
188 pub modalities: &'a [String],
189}
190
191pub struct AttachRequest<'a> {
192 pub from: &'a Participant,
193 pub callbacks: &'a CallbackLinks,
194 pub controller: Option<&'a str>,
195 pub needs_media: bool,
196}
197
198#[derive(Debug, Clone)]
199pub struct Attached {
200 pub offer_sdp: Option<String>,
201 pub from_mixer: bool,
202 pub modalities: Vec<String>,
203 pub links: BTreeMap<String, String>,
204 pub conversation: Option<Conversation>,
102}
205}
103
206
104impl Signaling {
207impl Signaling {
@@ -132,8 +235,8 @@ impl Signaling {
132 request
235 request
133 }
236 }
134
237
135 async fn exchange(&self, session: &Session, label: &str, request: Request) -> Result<ApiResponse> {
238 async fn exchange(&self, session: &Session, label: &str, mut request: Request) -> Result<ApiResponse> {
136 ensure_teams_url(&request.url)?;
239 request.url = routed_url(&request.url)?;
137 let response = session.batch(&[request], &ic3_scope()).await?.remove(0);
240 let response = session.batch(&[request], &ic3_scope()).await?.remove(0);
138 self.timeline.record(label, format!("HTTP {}", response.status));
241 self.timeline.record(label, format!("HTTP {}", response.status));
139 if !response.is_success() {
242 if !response.is_success() {
@@ -142,31 +245,66 @@ impl Signaling {
142 Ok(response)
245 Ok(response)
143 }
246 }
144
247
145 pub async fn create_conversation(&self, invitation: &EchoInvitation<'_>) -> Result<Conversation> {
248 async fn send(&self, label: &str, method: Method, url: &str, body: Option<Value>) -> Result<ApiResponse> {
146 let body = epconv_body(invitation);
249 self.exchange(&self.session, label, self.request(method, url, body)).await
250 }
251
252 pub async fn post_json(&self, label: &str, url: &str, body: Value) -> Result<()> {
253 self.send(label, Method::Post, url, Some(body)).await.map(|_| ())
254 }
255
256 pub async fn post_empty(&self, label: &str, url: &str) -> Result<()> {
257 self.send(label, Method::Post, url, None).await.map(|_| ())
258 }
259
260 pub async fn create_conversation(&self, invitation: &Invitation<'_>) -> Result<Conversation> {
147 let response = self
261 let response = self
148 .exchange(&self.session, "POST epconv", self.request(Method::Post, EPCONV_URL, Some(body)))
262 .send("POST epconv", Method::Post, EPCONV_URL, Some(epconv_body(invitation)))
149 .await?;
263 .await?;
150 conversation_from(&response.body)
264 conversation_from(&response.body)
151 }
265 }
152
266
267 pub async fn subscribe_meeting(
268 &self,
269 from: &Participant,
270 callbacks: &CallbackLinks,
271 meeting: &MeetingTarget,
272 ) -> Result<Conversation> {
273 let body = subscribe_body(from, callbacks, meeting);
274 let response = self.send("POST epconv subscribe", Method::Post, EPCONV_URL, Some(body)).await?;
275 conversation_from(&response.body)
276 }
277
278 /// Joins with the offer; the answer may restate the conversation links, otherwise the subscribed ones stay.
279 pub async fn join_meeting(&self, subscribed: &Conversation, invitation: &Invitation<'_>) -> Result<Conversation> {
280 let response = self
281 .send("POST join", Method::Post, &subscribed.controller, Some(epconv_body(invitation)))
282 .await?;
283 let mut links = subscribed.links.clone();
284 if let Ok(joined) = conversation_from(&response.body) {
285 links.extend(joined.links);
286 }
287 Ok(Conversation {
288 controller: subscribed.controller.clone(),
289 links,
290 })
291 }
292
293 pub fn next_endpoint_sequence(&self) -> u32 {
294 self.endpoint_state_sequence.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1
295 }
296
153 pub async fn update_endpoint_state(&self, conversation: &Conversation, from: &Participant, muted: bool) -> Result<()> {
297 pub async fn update_endpoint_state(&self, conversation: &Conversation, from: &Participant, muted: bool) -> Result<()> {
154 let sequence = self
155 .endpoint_state_sequence
156 .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
157 + 1;
158 let body = json!({
298 let body = json!({
159 "from": from.wire(),
299 "from": from.wire(),
160 "endpointState": {
300 "endpointState": {
161 "endpointStateSequenceNumber": sequence,
301 "endpointStateSequenceNumber": self.next_endpoint_sequence(),
162 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
302 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
163 "state": {"isMuted": muted},
303 "state": {"isMuted": muted},
164 },
304 },
165 });
305 });
166 let url = conversation.link("updateEndpointState")?;
306 let url = conversation.link("updateEndpointState")?;
167 self.exchange(&self.session, "POST updateEndpointState", self.request(Method::Post, url, Some(body)))
307 self.post_json("POST updateEndpointState", url, body).await
168 .await
169 .map(|_| ())
170 }
308 }
171
309
172 pub async fn add_echo_bot(
310 pub async fn add_echo_bot(
@@ -192,9 +330,7 @@ impl Signaling {
192 },
330 },
193 });
331 });
194 let url = conversation.link("addParticipantAndModality")?;
332 let url = conversation.link("addParticipantAndModality")?;
195 self.exchange(&self.session, "POST add (echo bot)", self.request(Method::Post, url, Some(body)))
333 self.post_json("POST add (echo bot)", url, body).await
196 .await
197 .map(|_| ())
198 }
334 }
199
335
200 pub async fn update_endpoint_metadata(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
336 pub async fn update_endpoint_metadata(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
@@ -203,9 +339,7 @@ impl Signaling {
203 "endpointMetadata": {"holographicCapabilities": 3},
339 "endpointMetadata": {"holographicCapabilities": 3},
204 });
340 });
205 let url = conversation.link("updateEndpointMetadata")?;
341 let url = conversation.link("updateEndpointMetadata")?;
206 self.exchange(&self.session, "PUT updateEndpointMetadata", self.request(Method::Put, url, Some(body)))
342 self.send("PUT updateEndpointMetadata", Method::Put, url, Some(body)).await.map(|_| ())
207 .await
208 .map(|_| ())
209 }
343 }
210
344
211 /// One broker long poll; answers the next subscribe URL.
345 /// One broker long poll; answers the next subscribe URL.
@@ -216,96 +350,313 @@ impl Signaling {
216 Ok(response.body["nextSubscribeUrl"].as_str().map(str::to_owned))
350 Ok(response.body["nextSubscribeUrl"].as_str().map(str::to_owned))
217 }
351 }
218
352
219 pub async fn leave(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
353 pub async fn leave(&self, conversation: &Conversation, from: &Participant, reason: LeaveReason) -> Result<()> {
220 let body = json!({
221 "participants": {"from": from.wire()},
222 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"},
223 "callTransactionEnd": {"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]},
224 });
225 let url = conversation.link("leave")?;
354 let url = conversation.link("leave")?;
226 self.exchange(&self.session, "POST leave", self.request(Method::Post, url, Some(body)))
355 self.post_json("POST leave", url, leave_body(from, reason)).await
356 }
357
358 pub async fn end_for_all(&self, conversation: &Conversation, from: &Participant) -> Result<()> {
359 self.send(
360 "DELETE conversation",
361 Method::Delete,
362 &conversation.controller,
363 Some(end_for_all_body(from)),
364 )
365 .await
366 .map(|_| ())
367 }
368
369 pub async fn attach(&self, url: &str, request: &AttachRequest<'_>) -> Result<Attached> {
370 let response = self
371 .send("POST attach", Method::Post, url, Some(attach_body(request)))
372 .await?;
373 attached_from(&response.body)
374 }
375
376 pub async fn send_ringing(&self, url: &str, from: &Participant) -> Result<()> {
377 self.post_json("POST progress", url, ringing_body(from)).await
378 }
379
380 pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<()> {
381 self.post_json("POST acceptance", url, acceptance_body(answer)).await
382 }
383
384 pub async fn decline(&self, call_leg_url: &str) -> Result<()> {
385 self.send("DELETE callLeg (decline)", Method::Delete, call_leg_url, Some(decline_body()))
227 .await
386 .await
228 .map(|_| ())
387 .map(|_| ())
229 }
388 }
389
390 pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> {
391 self.post_json("POST callLeg keep-alive", call_leg_url, json!({"callParticipantUpdate": {}}))
392 .await
393 }
394
395 pub async fn keep_conversation_alive(
396 &self,
397 conversation: &Conversation,
398 from: &Participant,
399 callbacks: &CallbackLinks,
400 ) -> Result<()> {
401 let url = conversation.link("notificationLinks")?;
402 self.post_json("POST notificationLinks", url, notification_links_body(from, callbacks)).await
403 }
404}
405
406fn link_map(names: &[&str], make: impl Fn(&str) -> String) -> Map<String, Value> {
407 names
408 .iter()
409 .map(|name| ((*name).to_owned(), Value::String(make(name))))
410 .collect()
411}
412
413fn roster_request(callbacks: &CallbackLinks) -> Value {
414 json!({"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")})
415}
416
417fn conversation_properties() -> Value {
418 json!({
419 "allowConversationWithoutHost": true,
420 "enableGroupCallEventMessages": true,
421 "enableGroupCallUpgradeMessage": false,
422 "enableGroupCallMeetupGeneration": false,
423 })
424}
425
426fn endpoint_state() -> Value {
427 json!({
428 "endpointStateSequenceNumber": 2,
429 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
430 })
431}
432
433fn media_content(sdp: &str, media_leg_id: &str, with_descriptions: bool) -> Value {
434 let mut content = json!({
435 "contentType": SDP_CONTENT_TYPE,
436 "blob": sdp,
437 "clientLocation": "DE",
438 "mediaLegId": media_leg_id,
439 });
440 if with_descriptions {
441 content["mediaDescriptions"] = json!({"descriptions": [], "requestId": 1});
442 }
443 content
444}
445
446fn media_controller_links(callbacks: &CallbackLinks) -> Value {
447 json!({
448 "controlVideoStreaming": callbacks.call("controlVideoStreaming"),
449 "csrcInfo": callbacks.call("csrcInfo"),
450 })
451}
452
453fn group_chat(target: &InviteTarget) -> Value {
454 match target {
455 InviteTarget::Echo => Value::Null,
456 InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}),
457 InviteTarget::Meeting(meeting) => json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}),
458 }
459}
460
461fn callee_wire(callee: &Callee) -> Value {
462 json!({"id": callee.mri, "displayName": callee.display_name})
230}
463}
231
464
232pub fn epconv_body(invitation: &EchoInvitation<'_>) -> Value {
465pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
233 let callbacks = invitation.callbacks;
466 let callbacks = invitation.callbacks;
234 let conversation_links: serde_json::Map<String, Value> = [
467 let target = invitation.target;
235 "conversationEnd",
468 let to: Vec<Value> = match target {
236 "conversationUpdate",
469 InviteTarget::People { callees, .. } => callees.iter().map(callee_wire).collect(),
237 "localParticipantUpdate",
470 InviteTarget::Echo | InviteTarget::Meeting(_) => Vec::new(),
238 "addParticipantSuccess",
471 };
239 "addParticipantFailure",
472 let mut request = json!({
240 "addModalitySuccess",
473 "conversationType": null,
241 "addModalityFailure",
474 "subject": null,
242 "confirmUnmute",
475 "suppressDialout": true,
243 "receiveMessage",
476 "roster": roster_request(callbacks),
244 ]
477 "properties": conversation_properties(),
245 .into_iter()
478 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
246 .map(|name| (name.to_owned(), Value::String(callbacks.conversation(name))))
479 });
247 .collect();
480 if matches!(target, InviteTarget::Echo) {
248 let call_links: serde_json::Map<String, Value> = ["progress", "mediaAnswer", "acceptance", "redirection", "end"]
481 request["scenario"] = json!("UserInitiatedTestCall");
249 .into_iter()
482 }
250 .map(|name| (name.to_owned(), Value::String(callbacks.call(name))))
483 let (meeting_info, meeting_data) = match target {
251 .collect();
484 InviteTarget::Meeting(meeting) => (
485 json!({"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}),
486 meeting.meeting_data.clone().unwrap_or(Value::Null),
487 ),
488 _ => (Value::Null, Value::Null),
489 };
252 json!({
490 json!({
253 "conversationRequest": {
491 "conversationRequest": request,
254 "conversationType": null,
255 "subject": null,
256 "suppressDialout": true,
257 "roster": {"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")},
258 "properties": {
259 "allowConversationWithoutHost": true,
260 "enableGroupCallEventMessages": true,
261 "enableGroupCallUpgradeMessage": false,
262 "enableGroupCallMeetupGeneration": false,
263 },
264 "links": conversation_links,
265 "scenario": "UserInitiatedTestCall",
266 },
267 "contentSharing": null,
492 "contentSharing": null,
268 "participants": {"from": invitation.from.wire(), "to": []},
493 "participants": {"from": invitation.from.wire(), "to": to},
269 "capabilities": null,
494 "capabilities": null,
270 "endpointCapabilities": ENDPOINT_CAPABILITIES,
495 "endpointCapabilities": ENDPOINT_CAPABILITIES,
271 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
496 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
272 "endpointMetadata": {"holographicCapabilities": 3},
497 "endpointMetadata": {"holographicCapabilities": 3},
273 "groupContext": null,
498 "groupContext": null,
274 "groupChat": null,
499 "groupChat": group_chat(target),
275 "meetingInfo": null,
500 "meetingInfo": meeting_info,
276 "meetingData": null,
501 "meetingData": meeting_data,
277 "endpointState": {
502 "endpointState": endpoint_state(),
278 "endpointStateSequenceNumber": 2,
279 "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
280 },
281 "callInvitation": {
503 "callInvitation": {
282 "callModalities": ["Audio"],
504 "callModalities": AUDIO_MODALITIES,
283 "replaces": null,
505 "replaces": null,
284 "transferor": null,
506 "transferor": null,
285 "clientTransferContext": null,
507 "clientTransferContext": null,
286 "customContext": null,
508 "customContext": null,
287 "links": call_links,
509 "links": link_map(&CALL_LINK_NAMES, |name| callbacks.call(name)),
288 "clientContentForMediaController": {
510 "clientContentForMediaController": media_controller_links(callbacks),
289 "controlVideoStreaming": callbacks.call("controlVideoStreaming"),
290 "csrcInfo": callbacks.call("csrcInfo"),
291 },
292 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
511 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
293 "emergencyContent": null,
512 "emergencyContent": null,
294 "mediaContent": {
513 "mediaContent": media_content(invitation.offer_sdp, invitation.media_leg_id, true),
295 "contentType": SDP_CONTENT_TYPE,
514 },
296 "blob": invitation.offer_sdp,
515 })
297 "clientLocation": "DE",
516}
298 "mediaDescriptions": {"descriptions": [], "requestId": 1},
517
299 "mediaLegId": invitation.media_leg_id,
518pub fn subscribe_body(from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget) -> Value {
519 json!({
520 "conversationRequest": {
521 "roster": roster_request(callbacks),
522 "properties": conversation_properties(),
523 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
524 },
525 "participants": {"from": from.wire()},
526 "groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID},
527 "meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id},
528 "endpointState": endpoint_state(),
529 })
530}
531
532pub fn leave_body(from: &Participant, reason: LeaveReason) -> Value {
533 let call_end = match reason {
534 LeaveReason::Hangup => json!({"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}),
535 LeaveReason::Cancel => json!({"code": CANCEL_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated"}),
536 };
537 json!({
538 "participants": {"from": from.wire()},
539 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"},
540 "callTransactionEnd": call_end,
541 })
542}
543
544pub fn end_for_all_body(from: &Participant) -> Value {
545 json!({
546 "participants": {"from": from.wire()},
547 "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndForAllInitiated"},
548 "callTransactionEnd": {"code": 0, "phrase": "CallEndReasonLocalUserInitiated"},
549 })
550}
551
552pub fn decline_body() -> Value {
553 json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
554}
555
556pub fn ringing_body(from: &Participant) -> Value {
557 json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}})
558}
559
560pub fn attach_body(request: &AttachRequest<'_>) -> Value {
561 let callbacks = request.callbacks;
562 let mut body = json!({
563 "attach": {
564 "requireMediaContent": request.needs_media,
565 "links": {"end": callbacks.call("end")},
566 },
567 "capabilities": null,
568 "endpointCapabilities": ENDPOINT_CAPABILITIES,
569 });
570 if let Some(controller) = request.controller {
571 body["additionalActions"] = json!([{
572 "name": "join",
573 "url": controller,
574 "waitForResponse": true,
575 "input": {
576 "conversationRequest": {
577 "roster": roster_request(callbacks),
578 "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
579 },
580 "participants": {"from": request.from.wire()},
581 "endpointMetadata": {"holographicCapabilities": 3},
582 "endpointCapabilities": ENDPOINT_CAPABILITIES,
300 },
583 },
584 }]);
585 }
586 body
587}
588
589pub fn acceptance_body(answer: &Answer<'_>) -> Value {
590 let callbacks = answer.callbacks;
591 json!({
592 "callAcceptance": {
593 "acceptedBy": answer.from.wire(),
594 "acceptedCallModalities": answer.modalities,
595 "endpointCapabilities": ENDPOINT_CAPABILITIES,
596 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
597 "links": acceptance_links(callbacks),
598 "clientContentForMediaController": media_controller_links(callbacks),
599 "mediaContent": media_content(answer.answer_sdp, answer.media_leg_id, false),
600 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
601 "callKeepAliveInterval": null,
602 },
603 })
604}
605
606pub fn renegotiation_body(
607 from: &Participant,
608 callbacks: &CallbackLinks,
609 offer_sdp: &str,
610 media_leg_id: &str,
611) -> Value {
612 json!({
613 "mediaNegotiation": {
614 "callModalities": AUDIO_MODALITIES,
615 "sender": from.wire(),
616 "links": {
617 "mediaAnswer": callbacks.call("mediaAnswer"),
618 "rejection": callbacks.call("rejection"),
619 },
620 "mediaContent": renegotiation_content(offer_sdp, media_leg_id),
621 },
622 })
623}
624
625fn renegotiation_content(sdp: &str, media_leg_id: &str) -> Value {
626 let mut content = media_content(sdp, media_leg_id, true);
627 content["newOffer"] = json!(true);
628 content
629}
630
631pub fn escalation_answer_body(
632 from: &Participant,
633 callbacks: &CallbackLinks,
634 answer_sdp: &str,
635 media_leg_id: &str,
636) -> Value {
637 json!({
638 "mediaAnswer": {
639 "callModalities": AUDIO_MODALITIES,
640 "sender": from.wire(),
641 "links": {"mediaAcknowledgement": callbacks.call("mediaAcknowledgement")},
642 "clientContentForMediaController": media_controller_links(callbacks),
643 "mediaContent": media_content(answer_sdp, media_leg_id, false),
301 },
644 },
302 })
645 })
303}
646}
304
647
648pub fn notification_links_body(from: &Participant, callbacks: &CallbackLinks) -> Value {
649 json!({
650 "participants": {"from": from.wire()},
651 "roster": roster_request(callbacks),
652 "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)),
653 })
654}
655
305fn conversation_from(body: &Value) -> Result<Conversation> {
656fn conversation_from(body: &Value) -> Result<Conversation> {
306 let controller = body["conversationController"]
657 let controller = body["conversationController"]
307 .as_str()
658 .as_str()
308 .ok_or_else(|| Error::Signaling("epconv answer without conversationController".into()))?
659 .ok_or_else(|| Error::Signaling("answer without conversationController".into()))?
309 .to_owned();
660 .to_owned();
310 let links = body["links"]
661 let links = body["links"]
311 .as_object()
662 .as_object()
@@ -319,6 +670,33 @@ fn conversation_from(body: &Value) -> Result<Conversation> {
319 Ok(Conversation { controller, links })
670 Ok(Conversation { controller, links })
320}
671}
321
672
673fn attached_from(body: &Value) -> Result<Attached> {
674 let invitation = &body["callInvitation"];
675 if invitation.is_null() {
676 return Err(Error::Signaling("attach answer without callInvitation".into()));
677 }
678 let links = invitation["links"]
679 .as_object()
680 .map(|links| {
681 links
682 .iter()
683 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
684 .collect()
685 })
686 .unwrap_or_default();
687 let modalities = invitation["callModalities"]
688 .as_array()
689 .map(|items| items.iter().filter_map(|item| item.as_str().map(str::to_owned)).collect())
690 .unwrap_or_default();
691 Ok(Attached {
692 offer_sdp: invitation["mediaContent"]["blob"].as_str().map(str::to_owned),
693 from_mixer: invitation["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
694 modalities,
695 links,
696 conversation: conversation_from(&body["additionalActionResponses"][0]["output"]).ok(),
697 })
698}
699
322#[derive(Debug, Clone)]
700#[derive(Debug, Clone)]
323pub struct SelfIdentity {
701pub struct SelfIdentity {
324 pub object_id: String,
702 pub object_id: String,
@@ -366,6 +744,39 @@ pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Re
366mod tests {
744mod tests {
367 use super::*;
745 use super::*;
368
746
747 fn from() -> Participant {
748 Participant {
749 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
750 display_name: "Test".into(),
751 endpoint_id: "e".into(),
752 participant_id: "p".into(),
753 language_id: "en-gb".into(),
754 }
755 }
756
757 fn callbacks() -> CallbackLinks {
758 CallbackLinks::new("https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/", "call-1")
759 }
760
761 fn body_for(target: &InviteTarget) -> Value {
762 let from = from();
763 let callbacks = callbacks();
764 epconv_body(&Invitation {
765 from: &from,
766 offer_sdp: "v=0\r\n",
767 media_leg_id: "AB",
768 callbacks: &callbacks,
769 target,
770 })
771 }
772
773 fn callee(mri: &str, name: &str) -> Callee {
774 Callee {
775 mri: mri.into(),
776 display_name: name.into(),
777 }
778 }
779
369 #[test]
780 #[test]
370 fn only_teams_hosts_get_the_bearer() {
781 fn only_teams_hosts_get_the_bearer() {
371 assert!(ensure_teams_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/conv-x/conv/1/leave?i=1").is_ok());
782 assert!(ensure_teams_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/conv-x/conv/1/leave?i=1").is_ok());
@@ -377,20 +788,202 @@ mod tests {
377 }
788 }
378
789
379 #[test]
790 #[test]
380 fn epconv_body_matches_the_captured_test_call_shape() {
791 fn backend_links_go_through_flightproxy() {
381 let from = Participant {
792 assert_eq!(
382 mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(),
793 routed_url("https://cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2").unwrap(),
383 display_name: "Test".into(),
794 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2"
384 endpoint_id: "e".into(),
795 );
385 participant_id: "p".into(),
796 assert_eq!(
386 language_id: "en-gb".into(),
797 routed_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y").unwrap(),
387 };
798 "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
388 let callbacks = CallbackLinks::new("https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/", "call-1");
799 );
389 let body = epconv_body(&EchoInvitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks });
800 assert!(routed_url("https://evil.skype.com.example/x").is_err());
801 assert!(routed_url("https://Evil.skype.com/x").is_err());
802 assert!(routed_url("https://user@cc.skype.com/x").is_err());
803 assert!(routed_url("http://cc.skype.com/x").is_err());
804 assert!(routed_url("https://.skype.com/x").is_err());
805 }
806
807 #[test]
808 fn echo_body_matches_the_captured_test_call_shape() {
809 let body = body_for(&InviteTarget::Echo);
390 assert_eq!(body["conversationRequest"]["scenario"], "UserInitiatedTestCall");
810 assert_eq!(body["conversationRequest"]["scenario"], "UserInitiatedTestCall");
391 assert_eq!(body["participants"]["to"], json!([]));
811 assert_eq!(body["participants"]["to"], json!([]));
812 assert_eq!(body["groupChat"], Value::Null);
813 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
392 assert_eq!(body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE);
814 assert_eq!(body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE);
393 assert!(body["callInvitation"]["links"]["acceptance"].as_str().unwrap().ends_with("/call/acceptance/"));
815 assert!(body["callInvitation"]["links"]["acceptance"].as_str().unwrap().ends_with("/call/acceptance/"));
394 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 9);
816 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 9);
395 }
817 }
818
819 #[test]
820 fn one_to_one_body_names_the_callee_and_the_chat() {
821 let target = InviteTarget::People {
822 callees: vec![callee("8:orgid:b", "Bea")],
823 thread_id: "19:a_b@unq.gbl.spaces".into(),
824 };
825 let body = body_for(&target);
826 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:b", "displayName": "Bea"}]));
827 assert_eq!(body["groupChat"], json!({"threadId": "19:a_b@unq.gbl.spaces", "messageId": null}));
828 assert!(body["conversationRequest"].get("scenario").is_none());
829 assert_eq!(body["meetingInfo"], Value::Null);
830 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
831 }
832
833 #[test]
834 fn group_body_invites_every_callee_on_the_group_thread() {
835 let target = InviteTarget::People {
836 callees: vec![callee("8:orgid:b", "Bea"), callee("8:orgid:c", "Cy"), callee("8:orgid:d", "Di")],
837 thread_id: "19:group@thread.v2".into(),
838 };
839 let body = body_for(&target);
840 let to = body["participants"]["to"].as_array().unwrap();
841 assert_eq!(to.len(), 3);
842 assert_eq!(to[2]["id"], "8:orgid:d");
843 assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2");
844 assert_eq!(body["groupChat"]["messageId"], Value::Null);
845 }
846
847 #[test]
848 fn meeting_join_body_carries_thread_and_meeting_info() {
849 let target = InviteTarget::Meeting(MeetingTarget {
850 thread_id: "19:meeting_x@thread.v2".into(),
851 tenant_id: "tenant".into(),
852 organizer_id: "organizer".into(),
853 meeting_data: Some(json!({"meetingCode": "123"})),
854 });
855 let body = body_for(&target);
856 assert_eq!(body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}));
857 assert_eq!(body["meetingInfo"], json!({"tenantId": "tenant", "organizerId": "organizer"}));
858 assert_eq!(body["meetingData"]["meetingCode"], "123");
859 assert_eq!(body["participants"]["to"], json!([]));
860 assert!(body["conversationRequest"].get("scenario").is_none());
861 assert!(body["endpointState"]["endpointProperties"].get("preheatProperties").is_none());
862 }
863
864 #[test]
865 fn meeting_subscribe_is_roster_only() {
866 let meeting = MeetingTarget {
867 thread_id: "19:meeting_x@thread.v2".into(),
868 tenant_id: "tenant".into(),
869 organizer_id: "organizer".into(),
870 meeting_data: None,
871 };
872 let body = subscribe_body(&from(), &callbacks(), &meeting);
873 assert!(body.get("callInvitation").is_none());
874 assert!(body["participants"].get("to").is_none());
875 assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 6);
876 assert_eq!(body["groupChat"]["messageId"], "0");
877 assert_eq!(body["meetingInfo"]["organizerId"], "organizer");
878 }
879
880 #[test]
881 fn leave_bodies_differ_by_reason() {
882 let hangup = leave_body(&from(), LeaveReason::Hangup);
883 assert_eq!(hangup["callTransactionEnd"]["code"], 0);
884 let cancel = leave_body(&from(), LeaveReason::Cancel);
885 assert_eq!(cancel["callTransactionEnd"]["code"], 487);
886 assert_eq!(cancel["callTransactionEnd"]["phrase"], "CallEndReasonLocalUserInitiated");
887 assert_eq!(cancel["conversationTransactionEnd"]["phrase"], "ConversationEndNoModalityConnected");
888 let end = end_for_all_body(&from());
889 assert_eq!(end["conversationTransactionEnd"]["phrase"], "ConversationEndForAllInitiated");
890 }
891
892 #[test]
893 fn decline_uses_603() {
894 let body = decline_body();
895 assert_eq!(body["callEnd"]["code"], 603);
896 assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"]));
897 }
898
899 #[test]
900 fn attach_asks_for_media_and_joins_the_conversation() {
901 let from = from();
902 let callbacks = callbacks();
903 let body = attach_body(&AttachRequest {
904 from: &from,
905 callbacks: &callbacks,
906 controller: Some("https://conv/controller"),
907 needs_media: true,
908 });
909 assert_eq!(body["attach"]["requireMediaContent"], true);
910 assert!(body["attach"]["links"]["end"].as_str().unwrap().ends_with("/call/end/"));
911 let action = &body["additionalActions"][0];
912 assert_eq!(action["name"], "join");
913 assert_eq!(action["url"], "https://conv/controller");
914 assert_eq!(action["waitForResponse"], true);
915 assert_eq!(action["input"]["conversationRequest"]["links"].as_object().unwrap().len(), 6);
916 let without = attach_body(&AttachRequest {
917 from: &from,
918 callbacks: &callbacks,
919 controller: None,
920 needs_media: false,
921 });
922 assert!(without.get("additionalActions").is_none());
923 assert_eq!(without["attach"]["requireMediaContent"], false);
924 }
925
926 #[test]
927 fn attach_answer_yields_offer_links_and_conversation() {
928 let body = json!({
929 "callInvitation": {
930 "links": {"acceptance": "https://cc/accept", "callLeg": "https://cc/leg", "progress": "https://cc/progress"},
931 "mediaContent": {"blob": "v=0\r\n"},
932 "callModalities": ["Audio"],
933 },
934 "additionalActionResponses": [{"output": {"conversationController": "https://conv/c", "links": {"leave": "https://conv/leave"}}}],
935 });
936 let attached = attached_from(&body).unwrap();
937 assert_eq!(attached.offer_sdp.as_deref(), Some("v=0\r\n"));
938 assert_eq!(attached.links["callLeg"], "https://cc/leg");
939 assert_eq!(attached.modalities, vec!["Audio".to_owned()]);
940 let conversation = attached.conversation.unwrap();
941 assert_eq!(conversation.controller, "https://conv/c");
942 assert_eq!(conversation.link("leave").unwrap(), "https://conv/leave");
943 assert!(attached_from(&json!({})).is_err());
944 }
945
946 #[test]
947 fn acceptance_carries_the_answer_and_callback_links() {
948 let from = from();
949 let callbacks = callbacks();
950 let modalities = vec!["Audio".to_owned()];
951 let body = acceptance_body(&Answer {
952 from: &from,
953 answer_sdp: "v=0\r\n",
954 media_leg_id: "AB",
955 callbacks: &callbacks,
956 modalities: &modalities,
957 });
958 let accepted = &body["callAcceptance"];
959 assert_eq!(accepted["acceptedBy"]["id"], from.mri);
960 assert_eq!(accepted["acceptedCallModalities"], json!(["Audio"]));
961 assert_eq!(accepted["mediaContent"]["blob"], "v=0\r\n");
962 assert_eq!(accepted["links"].as_object().unwrap().len(), 7);
963 assert!(accepted["links"]["mediaRenegotiation"].as_str().unwrap().ends_with("/call/mediaRenegotiation/"));
964 assert_eq!(accepted["callKeepAliveInterval"], Value::Null);
965 }
966
967 #[test]
968 fn renegotiation_messages_name_their_reply_links() {
969 let from = from();
970 let callbacks = callbacks();
971 let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB");
972 let negotiation = &offer["mediaNegotiation"];
973 assert_eq!(negotiation["mediaContent"]["newOffer"], true);
974 assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));
975 assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));
976 let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB");
977 assert!(answer["mediaAnswer"]["links"]["mediaAcknowledgement"]
978 .as_str()
979 .unwrap()
980 .ends_with("/call/mediaAcknowledgement/"));
981 }
982
983 #[test]
984 fn ringing_progress_names_the_sender() {
985 let body = ringing_body(&from());
986 assert_eq!(body["callProgress"]["status"], "ringing");
987 assert_eq!(body["callProgress"]["sender"]["id"], from().mri);
988 }
396}
989}
crates/calling/src/state.rs +12 −7
@@ -1,10 +1,12 @@
1 1 use std::time::Instant;
2 2
3 use crate::end::EndKind;
4
3 5 #[derive(Debug, Clone, PartialEq, Eq)]
4 6 pub enum EndReason {
5 7 LocalHangup,
6 8 Cancelled,
7 RemoteEnded,
9 Remote(EndKind),
8 10 Dropped,
9 11 Failed(String),
10 12 }
@@ -26,7 +28,7 @@ pub enum CallSignal {
26 28 MediaFailed,
27 29 ReconnectTimedOut,
28 30 LocalLeave,
29 RemoteEnd,
31 RemoteEnd(EndKind),
30 32 Error(String),
31 33 }
32 34
@@ -41,7 +43,7 @@ impl CallState {
41 43 (CallState::Connected { since }, MediaDisconnected) => CallState::Reconnecting { since: *since },
42 44 (CallState::Connecting, LocalLeave) => ended(EndReason::Cancelled),
43 45 (_, LocalLeave) => ended(EndReason::LocalHangup),
44 (_, RemoteEnd) => ended(EndReason::RemoteEnded),
46 (_, RemoteEnd(kind)) => ended(EndReason::Remote(kind)),
45 47 (CallState::Reconnecting { .. }, ReconnectTimedOut | MediaFailed) => ended(EndReason::Dropped),
46 48 (CallState::Connected { .. }, MediaFailed) => ended(EndReason::Dropped),
47 49 (CallState::Connecting, MediaFailed) => ended(EndReason::Failed("connection failed".into())),
@@ -131,16 +133,19 @@ mod tests {
131 133
132 134 #[test]
133 135 fn remote_end_wins_in_every_active_state() {
134 assert_eq!(run(&[CallSignal::Dial, CallSignal::RemoteEnd]), ended(EndReason::RemoteEnded));
135 136 assert_eq!(
136 run(&[CallSignal::Dial, CallSignal::MediaConnected, CallSignal::RemoteEnd]),
137 ended(EndReason::RemoteEnded)
137 run(&[CallSignal::Dial, CallSignal::RemoteEnd(EndKind::Declined)]),
138 ended(EndReason::Remote(EndKind::Declined))
139 );
140 assert_eq!(
141 run(&[CallSignal::Dial, CallSignal::MediaConnected, CallSignal::RemoteEnd(EndKind::Normal)]),
142 ended(EndReason::Remote(EndKind::Normal))
138 143 );
139 144 }
140 145
141 146 #[test]
142 147 fn ended_is_final_until_the_next_dial() {
143 let state = run(&[CallSignal::Dial, CallSignal::LocalLeave, CallSignal::MediaConnected, CallSignal::RemoteEnd]);
148 let state = run(&[CallSignal::Dial, CallSignal::LocalLeave, CallSignal::MediaConnected, CallSignal::RemoteEnd(EndKind::Normal)]);
144 149 assert_eq!(state, ended(EndReason::Cancelled));
145 150 assert_eq!(state.next(CallSignal::Dial, Instant::now()), CallState::Connecting);
146 151 }
@@ -1,10 +1,12 @@
1use std::time::Instant;
1use std::time::Instant;
2
2
3use crate::end::EndKind;
4
3#[derive(Debug, Clone, PartialEq, Eq)]
5#[derive(Debug, Clone, PartialEq, Eq)]
4pub enum EndReason {
6pub enum EndReason {
5 LocalHangup,
7 LocalHangup,
6 Cancelled,
8 Cancelled,
7 RemoteEnded,
9 Remote(EndKind),
8 Dropped,
10 Dropped,
9 Failed(String),
11 Failed(String),
10}
12}
@@ -26,7 +28,7 @@ pub enum CallSignal {
26 MediaFailed,
28 MediaFailed,
27 ReconnectTimedOut,
29 ReconnectTimedOut,
28 LocalLeave,
30 LocalLeave,
29 RemoteEnd,
31 RemoteEnd(EndKind),
30 Error(String),
32 Error(String),
31}
33}
32
34
@@ -41,7 +43,7 @@ impl CallState {
41 (CallState::Connected { since }, MediaDisconnected) => CallState::Reconnecting { since: *since },
43 (CallState::Connected { since }, MediaDisconnected) => CallState::Reconnecting { since: *since },
42 (CallState::Connecting, LocalLeave) => ended(EndReason::Cancelled),
44 (CallState::Connecting, LocalLeave) => ended(EndReason::Cancelled),
43 (_, LocalLeave) => ended(EndReason::LocalHangup),
45 (_, LocalLeave) => ended(EndReason::LocalHangup),
44 (_, RemoteEnd) => ended(EndReason::RemoteEnded),
46 (_, RemoteEnd(kind)) => ended(EndReason::Remote(kind)),
45 (CallState::Reconnecting { .. }, ReconnectTimedOut | MediaFailed) => ended(EndReason::Dropped),
47 (CallState::Reconnecting { .. }, ReconnectTimedOut | MediaFailed) => ended(EndReason::Dropped),
46 (CallState::Connected { .. }, MediaFailed) => ended(EndReason::Dropped),
48 (CallState::Connected { .. }, MediaFailed) => ended(EndReason::Dropped),
47 (CallState::Connecting, MediaFailed) => ended(EndReason::Failed("connection failed".into())),
49 (CallState::Connecting, MediaFailed) => ended(EndReason::Failed("connection failed".into())),
@@ -131,16 +133,19 @@ mod tests {
131
133
132 #[test]
134 #[test]
133 fn remote_end_wins_in_every_active_state() {
135 fn remote_end_wins_in_every_active_state() {
134 assert_eq!(run(&[CallSignal::Dial, CallSignal::RemoteEnd]), ended(EndReason::RemoteEnded));
135 assert_eq!(
136 assert_eq!(
136 run(&[CallSignal::Dial, CallSignal::MediaConnected, CallSignal::RemoteEnd]),
137 run(&[CallSignal::Dial, CallSignal::RemoteEnd(EndKind::Declined)]),
137 ended(EndReason::RemoteEnded)
138 ended(EndReason::Remote(EndKind::Declined))
139 );
140 assert_eq!(
141 run(&[CallSignal::Dial, CallSignal::MediaConnected, CallSignal::RemoteEnd(EndKind::Normal)]),
142 ended(EndReason::Remote(EndKind::Normal))
138 );
143 );
139 }
144 }
140
145
141 #[test]
146 #[test]
142 fn ended_is_final_until_the_next_dial() {
147 fn ended_is_final_until_the_next_dial() {
143 let state = run(&[CallSignal::Dial, CallSignal::LocalLeave, CallSignal::MediaConnected, CallSignal::RemoteEnd]);
148 let state = run(&[CallSignal::Dial, CallSignal::LocalLeave, CallSignal::MediaConnected, CallSignal::RemoteEnd(EndKind::Normal)]);
144 assert_eq!(state, ended(EndReason::Cancelled));
149 assert_eq!(state, ended(EndReason::Cancelled));
145 assert_eq!(state.next(CallSignal::Dial, Instant::now()), CallState::Connecting);
150 assert_eq!(state.next(CallSignal::Dial, Instant::now()), CallState::Connecting);
146 }
151 }
crates/calling/src/trouter_events.rs +268 −23
@@ -6,11 +6,22 @@ use chatsvc::TrouterCallback;
6 6 use flate2::read::GzDecoder;
7 7 use serde_json::{Value, json};
8 8
9 use crate::end::{EndKind, classify_end};
9 10 use crate::error::{Error, Result};
10 11
11 12 const CALLBACK_ROOT: &str = "callAgent/";
12 13 const GZIP_ENCODING: &str = "gzip";
13 14 const MAX_INFLATED_BYTES: u64 = 8 * 1024 * 1024;
15 const SPEAKER_KEYS: [&str; 7] = [
16 "csrcs",
17 "csrc",
18 "sources",
19 "sourceIds",
20 "dominantSpeakers",
21 "activeSpeakers",
22 "speakers",
23 ];
24 const MAX_SPEAKER_DEPTH: usize = 4;
14 25
15 26 pub fn decode_body(callback: &TrouterCallback) -> Result<Value> {
16 27 let text = if callback
@@ -45,6 +56,13 @@ pub struct CallEnd {
45 56 pub code: i64,
46 57 pub sub_code: i64,
47 58 pub phrase: String,
59 pub accepted_elsewhere_by: Option<String>,
60 }
61
62 impl CallEnd {
63 pub fn kind(&self) -> EndKind {
64 classify_end(self.code, self.sub_code)
65 }
48 66 }
49 67
50 68 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -52,6 +70,37 @@ pub struct Acceptance {
52 70 pub sdp: String,
53 71 pub from_mixer: bool,
54 72 pub links: BTreeMap<String, String>,
73 pub controller_name: Option<String>,
74 pub keep_alive_seconds: Option<u64>,
75 }
76
77 impl Acceptance {
78 pub fn in_lobby(&self) -> bool {
79 self.controller_name.as_deref() == Some(LOBBY_CONTROLLER)
80 }
81 }
82
83 pub const LOBBY_CONTROLLER: &str = "lobby";
84
85 #[derive(Debug, Clone, PartialEq, Eq)]
86 pub enum ProgressStatus {
87 Ringing,
88 Forwarded,
89 Other(String),
90 }
91
92 #[derive(Debug, Clone, PartialEq, Eq)]
93 pub struct MediaAnswer {
94 pub sdp: String,
95 pub links: BTreeMap<String, String>,
96 }
97
98 #[derive(Debug, Clone, PartialEq, Eq)]
99 pub struct Renegotiation {
100 pub sdp: String,
101 pub new_offer: bool,
102 pub escalation: bool,
103 pub links: BTreeMap<String, String>,
55 104 }
56 105
57 106 #[derive(Debug, Clone, PartialEq)]
@@ -59,6 +108,10 @@ pub enum CallEvent {
59 108 ConversationUpdate(Value),
60 109 RosterUpdate(Value),
61 110 Acceptance(Acceptance),
111 Progress(ProgressStatus),
112 MediaAnswer(MediaAnswer),
113 MediaRenegotiation(Renegotiation),
114 Speakers(Vec<u32>),
62 115 AddParticipantSuccess(Value),
63 116 AddParticipantFailure(Value),
64 117 End(CallEnd),
@@ -71,6 +124,10 @@ impl CallEvent {
71 124 CallEvent::ConversationUpdate(_) => "conversation/conversationUpdate".into(),
72 125 CallEvent::RosterUpdate(_) => "conversation/rosterUpdate".into(),
73 126 CallEvent::Acceptance(_) => "call/acceptance".into(),
127 CallEvent::Progress(_) => "call/progress".into(),
128 CallEvent::MediaAnswer(_) => "call/mediaAnswer".into(),
129 CallEvent::MediaRenegotiation(_) => "call/mediaRenegotiation".into(),
130 CallEvent::Speakers(_) => "call/speakers".into(),
74 131 CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
75 132 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
76 133 CallEvent::End(_) => "call/end".into(),
@@ -81,36 +138,43 @@ impl CallEvent {
81 138
82 139 /// `path` is `callAgent/<callId>/<tag>/<call|conversation>/<event>/`.
83 140 pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
84 let rest = path
85 .strip_prefix(CALLBACK_ROOT)
86 .ok_or_else(|| Error::Callback(format!("not a call callback: {path}")))?;
87 let parts: Vec<&str> = rest.trim_end_matches('/').split('/').collect();
88 let [call_id, _tag, scope, event] = parts.as_slice() else {
89 return Err(Error::Callback(format!("unexpected callback path shape ({} parts)", parts.len())));
90 };
91 let event = match (*scope, *event) {
141 let (call_id, scope, event) = split_callback_path(path)?;
142 let event = match (scope.as_str(), event.as_str()) {
92 143 ("conversation", "conversationUpdate") => CallEvent::ConversationUpdate(body),
93 144 ("conversation", "rosterUpdate") => CallEvent::RosterUpdate(body),
94 145 ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
95 146 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
96 147 ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
148 ("call", "progress") => CallEvent::Progress(progress(&body)),
149 ("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),
150 ("call", "mediaRenegotiation") => CallEvent::MediaRenegotiation(renegotiation(&body)?),
151 ("call", "csrcInfo" | "dominantSpeakerInfo") => CallEvent::Speakers(speaker_sources(&body)),
97 152 ("call", "end") => CallEvent::End(call_end(&body)),
98 153 (scope, event) => CallEvent::Other {
99 154 scope: scope.to_owned(),
100 155 event: event.to_owned(),
101 156 },
102 157 };
103 Ok((call_id.to_string(), event))
158 Ok((call_id, event))
104 159 }
105 160
106 fn acceptance(body: &Value) -> Result<Acceptance> {
107 let accepted = &body["callAcceptance"];
108 let media = &accepted["mediaContent"];
109 let sdp = media["blob"]
110 .as_str()
111 .ok_or_else(|| Error::Callback("acceptance without mediaContent.blob".into()))?
112 .to_owned();
113 let links = accepted["links"]
161 pub fn callback_call_id(path: &str) -> Option<String> {
162 split_callback_path(path).ok().map(|(call_id, _, _)| call_id)
163 }
164
165 fn split_callback_path(path: &str) -> Result<(String, String, String)> {
166 let rest = path
167 .strip_prefix(CALLBACK_ROOT)
168 .ok_or_else(|| Error::Callback(format!("not a call callback: {path}")))?;
169 let parts: Vec<&str> = rest.trim_end_matches('/').split('/').collect();
170 let [call_id, _tag, scope, event] = parts.as_slice() else {
171 return Err(Error::Callback(format!("unexpected callback path shape ({} parts)", parts.len())));
172 };
173 Ok(((*call_id).to_owned(), (*scope).to_owned(), (*event).to_owned()))
174 }
175
176 fn string_links(value: &Value) -> BTreeMap<String, String> {
177 value
114 178 .as_object()
115 179 .map(|links| {
116 180 links
@@ -118,20 +182,121 @@ fn acceptance(body: &Value) -> Result<Acceptance> {
118 182 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
119 183 .collect()
120 184 })
121 .unwrap_or_default();
185 .unwrap_or_default()
186 }
187
188 fn acceptance(body: &Value) -> Result<Acceptance> {
189 let accepted = &body["callAcceptance"];
190 let media = &accepted["mediaContent"];
191 let sdp = media["blob"]
192 .as_str()
193 .ok_or_else(|| Error::Callback("acceptance without mediaContent.blob".into()))?
194 .to_owned();
122 195 Ok(Acceptance {
123 196 sdp,
124 197 from_mixer: media["fromMixer"].as_bool().unwrap_or(false),
125 links,
198 links: string_links(&accepted["links"]),
199 controller_name: accepted["controllerName"].as_str().map(str::to_owned),
200 keep_alive_seconds: accepted["callKeepAliveInterval"].as_u64(),
201 })
202 }
203
204 fn progress(body: &Value) -> ProgressStatus {
205 match body["callProgress"]["status"].as_str().map(str::to_ascii_lowercase).as_deref() {
206 Some("ringing") => ProgressStatus::Ringing,
207 Some("forwarded") => ProgressStatus::Forwarded,
208 other => ProgressStatus::Other(other.unwrap_or_default().to_owned()),
209 }
210 }
211
212 fn media_answer(body: &Value) -> Result<MediaAnswer> {
213 let answer = &body["mediaAnswer"];
214 let sdp = answer["mediaContent"]["blob"]
215 .as_str()
216 .ok_or_else(|| Error::Callback("mediaAnswer without mediaContent.blob".into()))?
217 .to_owned();
218 Ok(MediaAnswer {
219 sdp,
220 links: string_links(&answer["links"]),
221 })
222 }
223
224 /// The renegotiation message nests its offer under a key the captures do not show, so any object holding `mediaContent` counts.
225 fn media_holder(body: &Value) -> Option<&Value> {
226 if body.get("mediaContent").is_some() {
227 return Some(body);
228 }
229 body.as_object()?.values().find(|value| value.get("mediaContent").is_some())
230 }
231
232 fn renegotiation(body: &Value) -> Result<Renegotiation> {
233 let holder = media_holder(body)
234 .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent".into()))?;
235 let media = &holder["mediaContent"];
236 let sdp = media["blob"]
237 .as_str()
238 .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent.blob".into()))?
239 .to_owned();
240 Ok(Renegotiation {
241 sdp,
242 new_offer: media["newOffer"].as_bool().unwrap_or(false),
243 escalation: media["escalationOccurring"].as_bool().unwrap_or(false)
244 || media["isTwoPartyToMultiPartyEscalation"].as_bool().unwrap_or(false),
245 links: string_links(&holder["links"]),
126 246 })
127 247 }
128 248
249 /// Speaker lists come as arrays of source ids under keys the captures do not show.
250 pub fn speaker_sources(body: &Value) -> Vec<u32> {
251 let mut sources = Vec::new();
252 collect_sources(body, 0, &mut sources);
253 sources.sort_unstable();
254 sources.dedup();
255 sources
256 }
257
258 fn collect_sources(value: &Value, depth: usize, sources: &mut Vec<u32>) {
259 if depth > MAX_SPEAKER_DEPTH {
260 return;
261 }
262 match value {
263 Value::Object(map) => {
264 for (key, child) in map {
265 if SPEAKER_KEYS.contains(&key.as_str()) {
266 push_ids(child, sources);
267 } else {
268 collect_sources(child, depth + 1, sources);
269 }
270 }
271 }
272 Value::Array(items) => items.iter().for_each(|item| collect_sources(item, depth + 1, sources)),
273 _ => {}
274 }
275 }
276
277 fn push_ids(value: &Value, sources: &mut Vec<u32>) {
278 match value {
279 Value::Number(number) => sources.extend(number.as_u64().and_then(|id| u32::try_from(id).ok())),
280 Value::Array(items) => items.iter().for_each(|item| push_ids(item, sources)),
281 Value::Object(map) => {
282 if let Some(id) = map.get("sourceId") {
283 push_ids(id, sources);
284 }
285 }
286 _ => {}
287 }
288 }
289
129 290 fn call_end(body: &Value) -> CallEnd {
130 291 let end = &body["callEnd"];
131 292 CallEnd {
132 293 code: end["code"].as_i64().unwrap_or_default(),
133 294 sub_code: end["subCode"].as_i64().unwrap_or_default(),
134 295 phrase: end["phrase"].as_str().unwrap_or_default().to_owned(),
296 accepted_elsewhere_by: end["acceptedElsewhereBy"]["displayName"]
297 .as_str()
298 .or_else(|| end["acceptedElsewhereBy"]["id"].as_str())
299 .map(str::to_owned),
135 300 }
136 301 }
137 302
@@ -154,6 +319,10 @@ impl CallbackLinks {
154 319 }
155 320 }
156 321
322 pub fn call_id(&self) -> &str {
323 &self.call_id
324 }
325
157 326 pub fn link(&self, scope: &str, event: &str) -> String {
158 327 let tag = &uuid::Uuid::new_v4().simple().to_string()[..8];
159 328 format!("{}{CALLBACK_ROOT}{}/{tag}/{scope}/{event}/", self.base, self.call_id)
@@ -169,6 +338,10 @@ impl CallbackLinks {
169 338 }
170 339
171 340 pub fn acceptance_acknowledgement(links: &CallbackLinks) -> Value {
341 json!({"callAcceptanceAcknowledgement": {"links": acceptance_links(links)}})
342 }
343
344 pub fn acceptance_links(links: &CallbackLinks) -> serde_json::Map<String, Value> {
172 345 let names = [
173 346 "mediaRenegotiation",
174 347 "transfer",
@@ -178,11 +351,10 @@ pub fn acceptance_acknowledgement(links: &CallbackLinks) -> Value {
178 351 "controlVideoStreaming",
179 352 "updateMediaDescriptions",
180 353 ];
181 let links: serde_json::Map<String, Value> = names
354 names
182 355 .into_iter()
183 356 .map(|name| (name.to_owned(), Value::String(links.call(name))))
184 .collect();
185 json!({"callAcceptanceAcknowledgement": {"links": links}})
357 .collect()
186 358 }
187 359
188 360 #[cfg(test)]
@@ -233,7 +405,7 @@ mod tests {
233 405 #[test]
234 406 fn classifies_end_and_unknown_events() {
235 407 let (_, end) = classify("callAgent/abc/1/call/end/", json!({"callEnd": {"code": 0, "subCode": 5, "phrase": "x"}})).unwrap();
236 assert_eq!(end, CallEvent::End(CallEnd { code: 0, sub_code: 5, phrase: "x".into() }));
408 assert_eq!(end, CallEvent::End(CallEnd { code: 0, sub_code: 5, phrase: "x".into(), accepted_elsewhere_by: None }));
237 409 let (_, other) = classify("callAgent/abc/1/call/updateMediaDescriptions", Value::Null).unwrap();
238 410 assert_eq!(other.name(), "call/updateMediaDescriptions");
239 411 assert!(classify("unifiedPresenceService", Value::Null).is_err());
@@ -251,4 +423,77 @@ mod tests {
251 423 .unwrap()
252 424 .ends_with("/call/mediaRenegotiation/"));
253 425 }
426 #[test]
427 fn progress_reports_ringing_and_forwarding() {
428 let ringing = json!({"callProgress": {"sender": "x", "status": "ringing", "phrase": "ringing"}});
429 let (_, event) = classify("callAgent/abc/1/call/progress/", ringing).unwrap();
430 assert_eq!(event, CallEvent::Progress(ProgressStatus::Ringing));
431 let forwarded = json!({"callProgress": {"status": "forwarded"}});
432 let (_, event) = classify("callAgent/abc/1/call/progress/", forwarded).unwrap();
433 assert_eq!(event, CallEvent::Progress(ProgressStatus::Forwarded));
434 let (_, other) = classify("callAgent/abc/1/call/progress/", json!({})).unwrap();
435 assert_eq!(other, CallEvent::Progress(ProgressStatus::Other(String::new())));
436 }
437
438 #[test]
439 fn provisional_answers_carry_sdp_and_links() {
440 let body = json!({"mediaAnswer": {"sender": "x", "mediaContent": {"blob": "v=0\r\n"},
441 "links": {"mediaAcknowledgement": "https://cc/ack"}}});
442 let (_, event) = classify("callAgent/abc/1/call/mediaAnswer/", body).unwrap();
443 let CallEvent::MediaAnswer(answer) = event else { panic!("not a media answer") };
444 assert_eq!(answer.sdp, "v=0\r\n");
445 assert_eq!(answer.links["mediaAcknowledgement"], "https://cc/ack");
446 assert!(classify("callAgent/abc/1/call/mediaAnswer/", json!({})).is_err());
447 }
448
449 #[test]
450 fn renegotiation_finds_its_offer_under_any_key() {
451 let nested = json!({"mediaNegotiation": {"mediaContent": {"blob": "v=0\r\n", "newOffer": true,
452 "escalationOccurring": true}, "links": {"mediaAnswer": "https://cc/answer"}}});
453 let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", nested).unwrap();
454 let CallEvent::MediaRenegotiation(renegotiation) = event else { panic!("not a renegotiation") };
455 assert!(renegotiation.new_offer && renegotiation.escalation);
456 assert_eq!(renegotiation.links["mediaAnswer"], "https://cc/answer");
457 let flat = json!({"mediaContent": {"blob": "v=0\r\n", "isTwoPartyToMultiPartyEscalation": true}});
458 let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", flat).unwrap();
459 let CallEvent::MediaRenegotiation(renegotiation) = event else { panic!("not a renegotiation") };
460 assert!(!renegotiation.new_offer && renegotiation.escalation);
461 assert!(classify("callAgent/abc/1/call/mediaRenegotiation/", json!({"x": 1})).is_err());
462 }
463
464 #[test]
465 fn speaker_sources_come_from_known_list_keys() {
466 assert_eq!(speaker_sources(&json!({"csrcInfo": {"csrcs": [201, 205, 201]}})), vec![201, 205]);
467 assert_eq!(speaker_sources(&json!({"dominantSpeakers": [{"sourceId": 7}]})), vec![7]);
468 assert!(speaker_sources(&json!({"other": [1, 2]})).is_empty());
469 let (_, event) = classify("callAgent/abc/1/call/csrcInfo/", json!({"sources": [3]})).unwrap();
470 assert_eq!(event, CallEvent::Speakers(vec![3]));
471 }
472
473 #[test]
474 fn end_names_who_answered_elsewhere() {
475 let body = json!({"callEnd": {"code": 450, "subCode": 0, "phrase": "x",
476 "acceptedElsewhereBy": {"id": "8:orgid:1", "displayName": "Daniel"}}});
477 let (_, event) = classify("callAgent/abc/1/call/end/", body).unwrap();
478 let CallEvent::End(end) = event else { panic!("not an end") };
479 assert_eq!(end.kind(), EndKind::AnsweredElsewhere);
480 assert_eq!(end.accepted_elsewhere_by.as_deref(), Some("Daniel"));
481 }
482
483 #[test]
484 fn acceptance_in_the_lobby_is_flagged() {
485 let body = json!({"callAcceptance": {"controllerName": "lobby", "callKeepAliveInterval": 2700,
486 "mediaContent": {"blob": "v=0\r\n"}}});
487 let (_, event) = classify("callAgent/abc/1/call/acceptance/", body).unwrap();
488 let CallEvent::Acceptance(acceptance) = event else { panic!("not acceptance") };
489 assert!(acceptance.in_lobby());
490 assert_eq!(acceptance.keep_alive_seconds, Some(2700));
491 }
492
493 #[test]
494 fn call_ids_come_from_the_path_alone() {
495 assert_eq!(callback_call_id("callAgent/abc/1/call/end/").as_deref(), Some("abc"));
496 assert_eq!(callback_call_id("unifiedPresenceService"), None);
497 assert_eq!(callback_call_id(""), None);
498 }
254 499 }
@@ -6,11 +6,22 @@ use chatsvc::TrouterCallback;
6use flate2::read::GzDecoder;
6use flate2::read::GzDecoder;
7use serde_json::{Value, json};
7use serde_json::{Value, json};
8
8
9use crate::end::{EndKind, classify_end};
9use crate::error::{Error, Result};
10use crate::error::{Error, Result};
10
11
11const CALLBACK_ROOT: &str = "callAgent/";
12const CALLBACK_ROOT: &str = "callAgent/";
12const GZIP_ENCODING: &str = "gzip";
13const GZIP_ENCODING: &str = "gzip";
13const MAX_INFLATED_BYTES: u64 = 8 * 1024 * 1024;
14const MAX_INFLATED_BYTES: u64 = 8 * 1024 * 1024;
15const SPEAKER_KEYS: [&str; 7] = [
16 "csrcs",
17 "csrc",
18 "sources",
19 "sourceIds",
20 "dominantSpeakers",
21 "activeSpeakers",
22 "speakers",
23];
24const MAX_SPEAKER_DEPTH: usize = 4;
14
25
15pub fn decode_body(callback: &TrouterCallback) -> Result<Value> {
26pub fn decode_body(callback: &TrouterCallback) -> Result<Value> {
16 let text = if callback
27 let text = if callback
@@ -45,6 +56,13 @@ pub struct CallEnd {
45 pub code: i64,
56 pub code: i64,
46 pub sub_code: i64,
57 pub sub_code: i64,
47 pub phrase: String,
58 pub phrase: String,
59 pub accepted_elsewhere_by: Option<String>,
60}
61
62impl CallEnd {
63 pub fn kind(&self) -> EndKind {
64 classify_end(self.code, self.sub_code)
65 }
48}
66}
49
67
50#[derive(Debug, Clone, PartialEq, Eq)]
68#[derive(Debug, Clone, PartialEq, Eq)]
@@ -52,6 +70,37 @@ pub struct Acceptance {
52 pub sdp: String,
70 pub sdp: String,
53 pub from_mixer: bool,
71 pub from_mixer: bool,
54 pub links: BTreeMap<String, String>,
72 pub links: BTreeMap<String, String>,
73 pub controller_name: Option<String>,
74 pub keep_alive_seconds: Option<u64>,
75}
76
77impl Acceptance {
78 pub fn in_lobby(&self) -> bool {
79 self.controller_name.as_deref() == Some(LOBBY_CONTROLLER)
80 }
81}
82
83pub const LOBBY_CONTROLLER: &str = "lobby";
84
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum ProgressStatus {
87 Ringing,
88 Forwarded,
89 Other(String),
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct MediaAnswer {
94 pub sdp: String,
95 pub links: BTreeMap<String, String>,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct Renegotiation {
100 pub sdp: String,
101 pub new_offer: bool,
102 pub escalation: bool,
103 pub links: BTreeMap<String, String>,
55}
104}
56
105
57#[derive(Debug, Clone, PartialEq)]
106#[derive(Debug, Clone, PartialEq)]
@@ -59,6 +108,10 @@ pub enum CallEvent {
59 ConversationUpdate(Value),
108 ConversationUpdate(Value),
60 RosterUpdate(Value),
109 RosterUpdate(Value),
61 Acceptance(Acceptance),
110 Acceptance(Acceptance),
111 Progress(ProgressStatus),
112 MediaAnswer(MediaAnswer),
113 MediaRenegotiation(Renegotiation),
114 Speakers(Vec<u32>),
62 AddParticipantSuccess(Value),
115 AddParticipantSuccess(Value),
63 AddParticipantFailure(Value),
116 AddParticipantFailure(Value),
64 End(CallEnd),
117 End(CallEnd),
@@ -71,6 +124,10 @@ impl CallEvent {
71 CallEvent::ConversationUpdate(_) => "conversation/conversationUpdate".into(),
124 CallEvent::ConversationUpdate(_) => "conversation/conversationUpdate".into(),
72 CallEvent::RosterUpdate(_) => "conversation/rosterUpdate".into(),
125 CallEvent::RosterUpdate(_) => "conversation/rosterUpdate".into(),
73 CallEvent::Acceptance(_) => "call/acceptance".into(),
126 CallEvent::Acceptance(_) => "call/acceptance".into(),
127 CallEvent::Progress(_) => "call/progress".into(),
128 CallEvent::MediaAnswer(_) => "call/mediaAnswer".into(),
129 CallEvent::MediaRenegotiation(_) => "call/mediaRenegotiation".into(),
130 CallEvent::Speakers(_) => "call/speakers".into(),
74 CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
131 CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
75 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
132 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
76 CallEvent::End(_) => "call/end".into(),
133 CallEvent::End(_) => "call/end".into(),
@@ -81,36 +138,43 @@ impl CallEvent {
81
138
82/// `path` is `callAgent/<callId>/<tag>/<call|conversation>/<event>/`.
139/// `path` is `callAgent/<callId>/<tag>/<call|conversation>/<event>/`.
83pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
140pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
84 let rest = path
141 let (call_id, scope, event) = split_callback_path(path)?;
85 .strip_prefix(CALLBACK_ROOT)
142 let event = match (scope.as_str(), event.as_str()) {
86 .ok_or_else(|| Error::Callback(format!("not a call callback: {path}")))?;
87 let parts: Vec<&str> = rest.trim_end_matches('/').split('/').collect();
88 let [call_id, _tag, scope, event] = parts.as_slice() else {
89 return Err(Error::Callback(format!("unexpected callback path shape ({} parts)", parts.len())));
90 };
91 let event = match (*scope, *event) {
92 ("conversation", "conversationUpdate") => CallEvent::ConversationUpdate(body),
143 ("conversation", "conversationUpdate") => CallEvent::ConversationUpdate(body),
93 ("conversation", "rosterUpdate") => CallEvent::RosterUpdate(body),
144 ("conversation", "rosterUpdate") => CallEvent::RosterUpdate(body),
94 ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
145 ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
95 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
146 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
96 ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
147 ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
148 ("call", "progress") => CallEvent::Progress(progress(&body)),
149 ("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),
150 ("call", "mediaRenegotiation") => CallEvent::MediaRenegotiation(renegotiation(&body)?),
151 ("call", "csrcInfo" | "dominantSpeakerInfo") => CallEvent::Speakers(speaker_sources(&body)),
97 ("call", "end") => CallEvent::End(call_end(&body)),
152 ("call", "end") => CallEvent::End(call_end(&body)),
98 (scope, event) => CallEvent::Other {
153 (scope, event) => CallEvent::Other {
99 scope: scope.to_owned(),
154 scope: scope.to_owned(),
100 event: event.to_owned(),
155 event: event.to_owned(),
101 },
156 },
102 };
157 };
103 Ok((call_id.to_string(), event))
158 Ok((call_id, event))
104}
159}
105
160
106fn acceptance(body: &Value) -> Result<Acceptance> {
161pub fn callback_call_id(path: &str) -> Option<String> {
107 let accepted = &body["callAcceptance"];
162 split_callback_path(path).ok().map(|(call_id, _, _)| call_id)
108 let media = &accepted["mediaContent"];
163}
109 let sdp = media["blob"]
164
110 .as_str()
165fn split_callback_path(path: &str) -> Result<(String, String, String)> {
111 .ok_or_else(|| Error::Callback("acceptance without mediaContent.blob".into()))?
166 let rest = path
112 .to_owned();
167 .strip_prefix(CALLBACK_ROOT)
113 let links = accepted["links"]
168 .ok_or_else(|| Error::Callback(format!("not a call callback: {path}")))?;
169 let parts: Vec<&str> = rest.trim_end_matches('/').split('/').collect();
170 let [call_id, _tag, scope, event] = parts.as_slice() else {
171 return Err(Error::Callback(format!("unexpected callback path shape ({} parts)", parts.len())));
172 };
173 Ok(((*call_id).to_owned(), (*scope).to_owned(), (*event).to_owned()))
174}
175
176fn string_links(value: &Value) -> BTreeMap<String, String> {
177 value
114 .as_object()
178 .as_object()
115 .map(|links| {
179 .map(|links| {
116 links
180 links
@@ -118,20 +182,121 @@ fn acceptance(body: &Value) -> Result<Acceptance> {
118 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
182 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
119 .collect()
183 .collect()
120 })
184 })
121 .unwrap_or_default();
185 .unwrap_or_default()
186}
187
188fn acceptance(body: &Value) -> Result<Acceptance> {
189 let accepted = &body["callAcceptance"];
190 let media = &accepted["mediaContent"];
191 let sdp = media["blob"]
192 .as_str()
193 .ok_or_else(|| Error::Callback("acceptance without mediaContent.blob".into()))?
194 .to_owned();
122 Ok(Acceptance {
195 Ok(Acceptance {
123 sdp,
196 sdp,
124 from_mixer: media["fromMixer"].as_bool().unwrap_or(false),
197 from_mixer: media["fromMixer"].as_bool().unwrap_or(false),
125 links,
198 links: string_links(&accepted["links"]),
199 controller_name: accepted["controllerName"].as_str().map(str::to_owned),
200 keep_alive_seconds: accepted["callKeepAliveInterval"].as_u64(),
201 })
202}
203
204fn progress(body: &Value) -> ProgressStatus {
205 match body["callProgress"]["status"].as_str().map(str::to_ascii_lowercase).as_deref() {
206 Some("ringing") => ProgressStatus::Ringing,
207 Some("forwarded") => ProgressStatus::Forwarded,
208 other => ProgressStatus::Other(other.unwrap_or_default().to_owned()),
209 }
210}
211
212fn media_answer(body: &Value) -> Result<MediaAnswer> {
213 let answer = &body["mediaAnswer"];
214 let sdp = answer["mediaContent"]["blob"]
215 .as_str()
216 .ok_or_else(|| Error::Callback("mediaAnswer without mediaContent.blob".into()))?
217 .to_owned();
218 Ok(MediaAnswer {
219 sdp,
220 links: string_links(&answer["links"]),
221 })
222}
223
224/// The renegotiation message nests its offer under a key the captures do not show, so any object holding `mediaContent` counts.
225fn media_holder(body: &Value) -> Option<&Value> {
226 if body.get("mediaContent").is_some() {
227 return Some(body);
228 }
229 body.as_object()?.values().find(|value| value.get("mediaContent").is_some())
230}
231
232fn renegotiation(body: &Value) -> Result<Renegotiation> {
233 let holder = media_holder(body)
234 .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent".into()))?;
235 let media = &holder["mediaContent"];
236 let sdp = media["blob"]
237 .as_str()
238 .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent.blob".into()))?
239 .to_owned();
240 Ok(Renegotiation {
241 sdp,
242 new_offer: media["newOffer"].as_bool().unwrap_or(false),
243 escalation: media["escalationOccurring"].as_bool().unwrap_or(false)
244 || media["isTwoPartyToMultiPartyEscalation"].as_bool().unwrap_or(false),
245 links: string_links(&holder["links"]),
126 })
246 })
127}
247}
128
248
249/// Speaker lists come as arrays of source ids under keys the captures do not show.
250pub fn speaker_sources(body: &Value) -> Vec<u32> {
251 let mut sources = Vec::new();
252 collect_sources(body, 0, &mut sources);
253 sources.sort_unstable();
254 sources.dedup();
255 sources
256}
257
258fn collect_sources(value: &Value, depth: usize, sources: &mut Vec<u32>) {
259 if depth > MAX_SPEAKER_DEPTH {
260 return;
261 }
262 match value {
263 Value::Object(map) => {
264 for (key, child) in map {
265 if SPEAKER_KEYS.contains(&key.as_str()) {
266 push_ids(child, sources);
267 } else {
268 collect_sources(child, depth + 1, sources);
269 }
270 }
271 }
272 Value::Array(items) => items.iter().for_each(|item| collect_sources(item, depth + 1, sources)),
273 _ => {}
274 }
275}
276
277fn push_ids(value: &Value, sources: &mut Vec<u32>) {
278 match value {
279 Value::Number(number) => sources.extend(number.as_u64().and_then(|id| u32::try_from(id).ok())),
280 Value::Array(items) => items.iter().for_each(|item| push_ids(item, sources)),
281 Value::Object(map) => {
282 if let Some(id) = map.get("sourceId") {
283 push_ids(id, sources);
284 }
285 }
286 _ => {}
287 }
288}
289
129fn call_end(body: &Value) -> CallEnd {
290fn call_end(body: &Value) -> CallEnd {
130 let end = &body["callEnd"];
291 let end = &body["callEnd"];
131 CallEnd {
292 CallEnd {
132 code: end["code"].as_i64().unwrap_or_default(),
293 code: end["code"].as_i64().unwrap_or_default(),
133 sub_code: end["subCode"].as_i64().unwrap_or_default(),
294 sub_code: end["subCode"].as_i64().unwrap_or_default(),
134 phrase: end["phrase"].as_str().unwrap_or_default().to_owned(),
295 phrase: end["phrase"].as_str().unwrap_or_default().to_owned(),
296 accepted_elsewhere_by: end["acceptedElsewhereBy"]["displayName"]
297 .as_str()
298 .or_else(|| end["acceptedElsewhereBy"]["id"].as_str())
299 .map(str::to_owned),
135 }
300 }
136}
301}
137
302
@@ -154,6 +319,10 @@ impl CallbackLinks {
154 }
319 }
155 }
320 }
156
321
322 pub fn call_id(&self) -> &str {
323 &self.call_id
324 }
325
157 pub fn link(&self, scope: &str, event: &str) -> String {
326 pub fn link(&self, scope: &str, event: &str) -> String {
158 let tag = &uuid::Uuid::new_v4().simple().to_string()[..8];
327 let tag = &uuid::Uuid::new_v4().simple().to_string()[..8];
159 format!("{}{CALLBACK_ROOT}{}/{tag}/{scope}/{event}/", self.base, self.call_id)
328 format!("{}{CALLBACK_ROOT}{}/{tag}/{scope}/{event}/", self.base, self.call_id)
@@ -169,6 +338,10 @@ impl CallbackLinks {
169}
338}
170
339
171pub fn acceptance_acknowledgement(links: &CallbackLinks) -> Value {
340pub fn acceptance_acknowledgement(links: &CallbackLinks) -> Value {
341 json!({"callAcceptanceAcknowledgement": {"links": acceptance_links(links)}})
342}
343
344pub fn acceptance_links(links: &CallbackLinks) -> serde_json::Map<String, Value> {
172 let names = [
345 let names = [
173 "mediaRenegotiation",
346 "mediaRenegotiation",
174 "transfer",
347 "transfer",
@@ -178,11 +351,10 @@ pub fn acceptance_acknowledgement(links: &CallbackLinks) -> Value {
178 "controlVideoStreaming",
351 "controlVideoStreaming",
179 "updateMediaDescriptions",
352 "updateMediaDescriptions",
180 ];
353 ];
181 let links: serde_json::Map<String, Value> = names
354 names
182 .into_iter()
355 .into_iter()
183 .map(|name| (name.to_owned(), Value::String(links.call(name))))
356 .map(|name| (name.to_owned(), Value::String(links.call(name))))
184 .collect();
357 .collect()
185 json!({"callAcceptanceAcknowledgement": {"links": links}})
186}
358}
187
359
188#[cfg(test)]
360#[cfg(test)]
@@ -233,7 +405,7 @@ mod tests {
233 #[test]
405 #[test]
234 fn classifies_end_and_unknown_events() {
406 fn classifies_end_and_unknown_events() {
235 let (_, end) = classify("callAgent/abc/1/call/end/", json!({"callEnd": {"code": 0, "subCode": 5, "phrase": "x"}})).unwrap();
407 let (_, end) = classify("callAgent/abc/1/call/end/", json!({"callEnd": {"code": 0, "subCode": 5, "phrase": "x"}})).unwrap();
236 assert_eq!(end, CallEvent::End(CallEnd { code: 0, sub_code: 5, phrase: "x".into() }));
408 assert_eq!(end, CallEvent::End(CallEnd { code: 0, sub_code: 5, phrase: "x".into(), accepted_elsewhere_by: None }));
237 let (_, other) = classify("callAgent/abc/1/call/updateMediaDescriptions", Value::Null).unwrap();
409 let (_, other) = classify("callAgent/abc/1/call/updateMediaDescriptions", Value::Null).unwrap();
238 assert_eq!(other.name(), "call/updateMediaDescriptions");
410 assert_eq!(other.name(), "call/updateMediaDescriptions");
239 assert!(classify("unifiedPresenceService", Value::Null).is_err());
411 assert!(classify("unifiedPresenceService", Value::Null).is_err());
@@ -251,4 +423,77 @@ mod tests {
251 .unwrap()
423 .unwrap()
252 .ends_with("/call/mediaRenegotiation/"));
424 .ends_with("/call/mediaRenegotiation/"));
253 }
425 }
426 #[test]
427 fn progress_reports_ringing_and_forwarding() {
428 let ringing = json!({"callProgress": {"sender": "x", "status": "ringing", "phrase": "ringing"}});
429 let (_, event) = classify("callAgent/abc/1/call/progress/", ringing).unwrap();
430 assert_eq!(event, CallEvent::Progress(ProgressStatus::Ringing));
431 let forwarded = json!({"callProgress": {"status": "forwarded"}});
432 let (_, event) = classify("callAgent/abc/1/call/progress/", forwarded).unwrap();
433 assert_eq!(event, CallEvent::Progress(ProgressStatus::Forwarded));
434 let (_, other) = classify("callAgent/abc/1/call/progress/", json!({})).unwrap();
435 assert_eq!(other, CallEvent::Progress(ProgressStatus::Other(String::new())));
436 }
437
438 #[test]
439 fn provisional_answers_carry_sdp_and_links() {
440 let body = json!({"mediaAnswer": {"sender": "x", "mediaContent": {"blob": "v=0\r\n"},
441 "links": {"mediaAcknowledgement": "https://cc/ack"}}});
442 let (_, event) = classify("callAgent/abc/1/call/mediaAnswer/", body).unwrap();
443 let CallEvent::MediaAnswer(answer) = event else { panic!("not a media answer") };
444 assert_eq!(answer.sdp, "v=0\r\n");
445 assert_eq!(answer.links["mediaAcknowledgement"], "https://cc/ack");
446 assert!(classify("callAgent/abc/1/call/mediaAnswer/", json!({})).is_err());
447 }
448
449 #[test]
450 fn renegotiation_finds_its_offer_under_any_key() {
451 let nested = json!({"mediaNegotiation": {"mediaContent": {"blob": "v=0\r\n", "newOffer": true,
452 "escalationOccurring": true}, "links": {"mediaAnswer": "https://cc/answer"}}});
453 let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", nested).unwrap();
454 let CallEvent::MediaRenegotiation(renegotiation) = event else { panic!("not a renegotiation") };
455 assert!(renegotiation.new_offer && renegotiation.escalation);
456 assert_eq!(renegotiation.links["mediaAnswer"], "https://cc/answer");
457 let flat = json!({"mediaContent": {"blob": "v=0\r\n", "isTwoPartyToMultiPartyEscalation": true}});
458 let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", flat).unwrap();
459 let CallEvent::MediaRenegotiation(renegotiation) = event else { panic!("not a renegotiation") };
460 assert!(!renegotiation.new_offer && renegotiation.escalation);
461 assert!(classify("callAgent/abc/1/call/mediaRenegotiation/", json!({"x": 1})).is_err());
462 }
463
464 #[test]
465 fn speaker_sources_come_from_known_list_keys() {
466 assert_eq!(speaker_sources(&json!({"csrcInfo": {"csrcs": [201, 205, 201]}})), vec![201, 205]);
467 assert_eq!(speaker_sources(&json!({"dominantSpeakers": [{"sourceId": 7}]})), vec![7]);
468 assert!(speaker_sources(&json!({"other": [1, 2]})).is_empty());
469 let (_, event) = classify("callAgent/abc/1/call/csrcInfo/", json!({"sources": [3]})).unwrap();
470 assert_eq!(event, CallEvent::Speakers(vec![3]));
471 }
472
473 #[test]
474 fn end_names_who_answered_elsewhere() {
475 let body = json!({"callEnd": {"code": 450, "subCode": 0, "phrase": "x",
476 "acceptedElsewhereBy": {"id": "8:orgid:1", "displayName": "Daniel"}}});
477 let (_, event) = classify("callAgent/abc/1/call/end/", body).unwrap();
478 let CallEvent::End(end) = event else { panic!("not an end") };
479 assert_eq!(end.kind(), EndKind::AnsweredElsewhere);
480 assert_eq!(end.accepted_elsewhere_by.as_deref(), Some("Daniel"));
481 }
482
483 #[test]
484 fn acceptance_in_the_lobby_is_flagged() {
485 let body = json!({"callAcceptance": {"controllerName": "lobby", "callKeepAliveInterval": 2700,
486 "mediaContent": {"blob": "v=0\r\n"}}});
487 let (_, event) = classify("callAgent/abc/1/call/acceptance/", body).unwrap();
488 let CallEvent::Acceptance(acceptance) = event else { panic!("not acceptance") };
489 assert!(acceptance.in_lobby());
490 assert_eq!(acceptance.keep_alive_seconds, Some(2700));
491 }
492
493 #[test]
494 fn call_ids_come_from_the_path_alone() {
495 assert_eq!(callback_call_id("callAgent/abc/1/call/end/").as_deref(), Some("abc"));
496 assert_eq!(callback_call_id("unifiedPresenceService"), None);
497 assert_eq!(callback_call_id(""), None);
498 }
254}
499}
crates/calling/tests/sdp_golden.rs +62 −1
@@ -1,4 +1,4 @@
1 use calling::sdp::{self, OfferPlan, SessionDescription, to_browser_answer, to_teams_offer};
1 use calling::sdp::{self, OfferPlan, SessionDescription, from_teams_offer, to_browser_answer, to_teams_answer, to_teams_offer};
2 2
3 3 const BROWSER_OFFER: &str = include_str!("fixtures/browser_offer.sdp");
4 4 const TEAMS_OFFER: &str = include_str!("fixtures/teams_offer.sdp");
@@ -111,3 +111,64 @@ fn captured_teams_answer_translates_to_the_captured_browser_answer() {
111 111 let expected = sections(&sdp::parse(BROWSER_ANSWER).unwrap());
112 112 assert_same(actual, expected, differs_per_run);
113 113 }
114
115 fn kinds(description: &SessionDescription) -> Vec<String> {
116 description.media.iter().map(|media| media.kind.clone()).collect()
117 }
118
119 #[test]
120 fn captured_teams_offer_translates_to_a_browser_offer() {
121 let remote = from_teams_offer(TEAMS_OFFER).unwrap();
122 let browser = sdp::parse(&remote.browser_sdp).unwrap();
123 assert_eq!(browser.media.len(), 20);
124 let mids: Vec<&str> = browser.media.iter().filter_map(|media| media.mid()).collect();
125 assert_eq!(mids, (0..20).map(|mid| mid.to_string()).collect::<Vec<_>>().iter().map(String::as_str).collect::<Vec<_>>());
126 let kinds = kinds(&browser);
127 assert_eq!(kinds.iter().filter(|kind| *kind == "audio").count(), 1);
128 assert_eq!(kinds.iter().filter(|kind| *kind == "video").count(), 18);
129 assert_eq!(kinds.last().map(String::as_str), Some("application"));
130 assert!(browser.media.iter().all(|media| media.port == "9"));
131 assert!(browser.media[..19].iter().all(|media| media.proto == "UDP/TLS/RTP/SAVPF"));
132 assert!(!remote.browser_sdp.contains("x-ssrc-range") && !remote.browser_sdp.contains("a=label"));
133 assert!(!remote.browser_sdp.contains("10.10.10.10") && !remote.browser_sdp.contains("1234"));
134 assert!(remote.browser_sdp.contains("a=group:BUNDLE 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19"));
135 assert_eq!(remote.lines.len(), 13);
136 assert_eq!(remote.lines[10].browser_mids.len(), 8);
137 }
138
139 #[test]
140 fn a_teams_offer_survives_the_trip_through_libwebrtc_form_and_back() {
141 let remote = from_teams_offer(TEAMS_OFFER).unwrap();
142 let back = to_teams_offer(&remote.browser_sdp, &remote.plan(), &mut counter()).unwrap();
143 let actual = sections(&sdp::parse(&back.sdp).unwrap());
144 let expected = sections(&sdp::parse(TEAMS_OFFER).unwrap());
145 let per_run_ssrcs = |_: usize, line: &str| {
146 is_teams_codec_policy(line) || line.starts_with("a=ssrc:") || line.starts_with("a=x-ssrc-range:")
147 };
148 assert_same(actual, expected, per_run_ssrcs);
149 assert_eq!(back.lines, remote.lines);
150 }
151
152 #[test]
153 fn an_answer_to_a_teams_offer_comes_back_in_the_teams_dialect() {
154 let remote = from_teams_offer(TEAMS_OFFER).unwrap();
155 let answer = to_teams_answer(BROWSER_ANSWER, &remote, &mut counter()).unwrap();
156 let described = sdp::parse(&answer.sdp).unwrap();
157 let captured = sdp::parse(TEAMS_ANSWER).unwrap();
158 assert_eq!(described.media.len(), captured.media.len());
159 for (ours, theirs) in described.media.iter().zip(&captured.media) {
160 assert_eq!(ours.kind, theirs.kind);
161 assert_eq!(ours.value("label"), theirs.value("label"));
162 assert_eq!(ours.port, "1234");
163 assert_eq!(ours.proto, "RTP/SAVP");
164 }
165 assert_eq!(answer.lines, remote.lines);
166 let bundle = described
167 .session
168 .attributes
169 .iter()
170 .find(|attribute| attribute.name == "group")
171 .and_then(|attribute| attribute.value.clone())
172 .unwrap();
173 assert_eq!(bundle, "BUNDLE 0 1 2 3 4 5 6 7 8 9 17 18 19");
174 }
@@ -1,4 +1,4 @@
1use calling::sdp::{self, OfferPlan, SessionDescription, to_browser_answer, to_teams_offer};
1use calling::sdp::{self, OfferPlan, SessionDescription, from_teams_offer, to_browser_answer, to_teams_answer, to_teams_offer};
2
2
3const BROWSER_OFFER: &str = include_str!("fixtures/browser_offer.sdp");
3const BROWSER_OFFER: &str = include_str!("fixtures/browser_offer.sdp");
4const TEAMS_OFFER: &str = include_str!("fixtures/teams_offer.sdp");
4const TEAMS_OFFER: &str = include_str!("fixtures/teams_offer.sdp");
@@ -111,3 +111,64 @@ fn captured_teams_answer_translates_to_the_captured_browser_answer() {
111 let expected = sections(&sdp::parse(BROWSER_ANSWER).unwrap());
111 let expected = sections(&sdp::parse(BROWSER_ANSWER).unwrap());
112 assert_same(actual, expected, differs_per_run);
112 assert_same(actual, expected, differs_per_run);
113}
113}
114
115fn kinds(description: &SessionDescription) -> Vec<String> {
116 description.media.iter().map(|media| media.kind.clone()).collect()
117}
118
119#[test]
120fn captured_teams_offer_translates_to_a_browser_offer() {
121 let remote = from_teams_offer(TEAMS_OFFER).unwrap();
122 let browser = sdp::parse(&remote.browser_sdp).unwrap();
123 assert_eq!(browser.media.len(), 20);
124 let mids: Vec<&str> = browser.media.iter().filter_map(|media| media.mid()).collect();
125 assert_eq!(mids, (0..20).map(|mid| mid.to_string()).collect::<Vec<_>>().iter().map(String::as_str).collect::<Vec<_>>());
126 let kinds = kinds(&browser);
127 assert_eq!(kinds.iter().filter(|kind| *kind == "audio").count(), 1);
128 assert_eq!(kinds.iter().filter(|kind| *kind == "video").count(), 18);
129 assert_eq!(kinds.last().map(String::as_str), Some("application"));
130 assert!(browser.media.iter().all(|media| media.port == "9"));
131 assert!(browser.media[..19].iter().all(|media| media.proto == "UDP/TLS/RTP/SAVPF"));
132 assert!(!remote.browser_sdp.contains("x-ssrc-range") && !remote.browser_sdp.contains("a=label"));
133 assert!(!remote.browser_sdp.contains("10.10.10.10") && !remote.browser_sdp.contains("1234"));
134 assert!(remote.browser_sdp.contains("a=group:BUNDLE 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19"));
135 assert_eq!(remote.lines.len(), 13);
136 assert_eq!(remote.lines[10].browser_mids.len(), 8);
137}
138
139#[test]
140fn a_teams_offer_survives_the_trip_through_libwebrtc_form_and_back() {
141 let remote = from_teams_offer(TEAMS_OFFER).unwrap();
142 let back = to_teams_offer(&remote.browser_sdp, &remote.plan(), &mut counter()).unwrap();
143 let actual = sections(&sdp::parse(&back.sdp).unwrap());
144 let expected = sections(&sdp::parse(TEAMS_OFFER).unwrap());
145 let per_run_ssrcs = |_: usize, line: &str| {
146 is_teams_codec_policy(line) || line.starts_with("a=ssrc:") || line.starts_with("a=x-ssrc-range:")
147 };
148 assert_same(actual, expected, per_run_ssrcs);
149 assert_eq!(back.lines, remote.lines);
150}
151
152#[test]
153fn an_answer_to_a_teams_offer_comes_back_in_the_teams_dialect() {
154 let remote = from_teams_offer(TEAMS_OFFER).unwrap();
155 let answer = to_teams_answer(BROWSER_ANSWER, &remote, &mut counter()).unwrap();
156 let described = sdp::parse(&answer.sdp).unwrap();
157 let captured = sdp::parse(TEAMS_ANSWER).unwrap();
158 assert_eq!(described.media.len(), captured.media.len());
159 for (ours, theirs) in described.media.iter().zip(&captured.media) {
160 assert_eq!(ours.kind, theirs.kind);
161 assert_eq!(ours.value("label"), theirs.value("label"));
162 assert_eq!(ours.port, "1234");
163 assert_eq!(ours.proto, "RTP/SAVP");
164 }
165 assert_eq!(answer.lines, remote.lines);
166 let bundle = described
167 .session
168 .attributes
169 .iter()
170 .find(|attribute| attribute.name == "group")
171 .and_then(|attribute| attribute.value.clone())
172 .unwrap();
173 assert_eq!(bundle, "BUNDLE 0 1 2 3 4 5 6 7 8 9 17 18 19");
174}
crates/chatsvc/assets/trouter.js +13 −3
@@ -1,10 +1,12 @@
1 1 (() => {
2 const VERSION = 4;
2 const VERSION = 5;
3 3 const GLOBAL_NAME = '__chatsvcTrouter';
4 4 const BINDING_NAME = '__chatsvcRealtime';
5 5 const EPID_KEY = '__chatsvcEpid';
6 6 const REGISTRAR = 'https://teams.cloud.microsoft/registrar/prod/V2/registrations';
7 7 const UI_VERSION = '1415/26091712213';
8 const WORKER_REGISTRATION = {appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'};
9 const CALLING_REGISTRATION = {appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'};
8 10 const PING_MS = 30000;
9 11 const SILENCE_LIMIT_MS = 100000;
10 12 const REREGISTER_MS = 40 * 60 * 1000;
@@ -15,6 +17,7 @@
15 17 const MAX_PRESENCE_FIELD = 128;
16 18 const MAX_SENDER_NAME = 256;
17 19 const FORWARD_CALLBACKS = false;
20 const RINGABLE = false;
18 21 const CALLBACK_PREFIX = 'callAgent/';
19 22 const CALLBACK_REPLY_TIMEOUT_MS = 5000;
20 23
@@ -143,9 +146,11 @@
143 146
144 147 const register = async (surl) => {
145 148 state.surl = surl || state.surl;
149 const registration = RINGABLE ? CALLING_REGISTRATION : WORKER_REGISTRATION;
146 150 const body = {
147 clientDescription: {appId: 'TeamsCDLWebWorker', aesKey: '', languageId: 'en-US', platform: 'chrome',
148 templateKey: 'TeamsCDLWebWorker_2.6', platformUIVersion: UI_VERSION},
151 clientDescription: {appId: registration.appId, aesKey: '', languageId: 'en-US', platform: 'chrome',
152 templateKey: registration.templateKey, platformUIVersion: UI_VERSION,
153 ...(RINGABLE ? {productContext: ''} : {})},
149 154 registrationId: state.epid, nodeId: '',
150 155 transports: {TROUTER: [{context: '', path: state.surl, ttl: 3600}]},
151 156 };
@@ -212,6 +217,11 @@
212 217 send('3:::' + JSON.stringify({id: request.id, status: 200, headers: {}, body: ''}));
213 218 let body = null;
214 219 try { body = JSON.parse(request.body); } catch (error) {}
220 if (FORWARD_CALLBACKS && body && typeof body.evt === 'number') {
221 forward({channel: 'callback', requestId: request.id, path: '', contentEncoding: null,
222 body: typeof request.body === 'string' ? request.body : JSON.stringify(request.body)});
223 return;
224 }
215 225 forwardNotification(path, body);
216 226 }
217 227 };
@@ -1,10 +1,12 @@
1(() => {
1(() => {
2 const VERSION = 4;
2 const VERSION = 5;
3 const GLOBAL_NAME = '__chatsvcTrouter';
3 const GLOBAL_NAME = '__chatsvcTrouter';
4 const BINDING_NAME = '__chatsvcRealtime';
4 const BINDING_NAME = '__chatsvcRealtime';
5 const EPID_KEY = '__chatsvcEpid';
5 const EPID_KEY = '__chatsvcEpid';
6 const REGISTRAR = 'https://teams.cloud.microsoft/registrar/prod/V2/registrations';
6 const REGISTRAR = 'https://teams.cloud.microsoft/registrar/prod/V2/registrations';
7 const UI_VERSION = '1415/26091712213';
7 const UI_VERSION = '1415/26091712213';
8 const WORKER_REGISTRATION = {appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'};
9 const CALLING_REGISTRATION = {appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'};
8 const PING_MS = 30000;
10 const PING_MS = 30000;
9 const SILENCE_LIMIT_MS = 100000;
11 const SILENCE_LIMIT_MS = 100000;
10 const REREGISTER_MS = 40 * 60 * 1000;
12 const REREGISTER_MS = 40 * 60 * 1000;
@@ -15,6 +17,7 @@
15 const MAX_PRESENCE_FIELD = 128;
17 const MAX_PRESENCE_FIELD = 128;
16 const MAX_SENDER_NAME = 256;
18 const MAX_SENDER_NAME = 256;
17 const FORWARD_CALLBACKS = false;
19 const FORWARD_CALLBACKS = false;
20 const RINGABLE = false;
18 const CALLBACK_PREFIX = 'callAgent/';
21 const CALLBACK_PREFIX = 'callAgent/';
19 const CALLBACK_REPLY_TIMEOUT_MS = 5000;
22 const CALLBACK_REPLY_TIMEOUT_MS = 5000;
20
23
@@ -143,9 +146,11 @@
143
146
144 const register = async (surl) => {
147 const register = async (surl) => {
145 state.surl = surl || state.surl;
148 state.surl = surl || state.surl;
149 const registration = RINGABLE ? CALLING_REGISTRATION : WORKER_REGISTRATION;
146 const body = {
150 const body = {
147 clientDescription: {appId: 'TeamsCDLWebWorker', aesKey: '', languageId: 'en-US', platform: 'chrome',
151 clientDescription: {appId: registration.appId, aesKey: '', languageId: 'en-US', platform: 'chrome',
148 templateKey: 'TeamsCDLWebWorker_2.6', platformUIVersion: UI_VERSION},
152 templateKey: registration.templateKey, platformUIVersion: UI_VERSION,
153 ...(RINGABLE ? {productContext: ''} : {})},
149 registrationId: state.epid, nodeId: '',
154 registrationId: state.epid, nodeId: '',
150 transports: {TROUTER: [{context: '', path: state.surl, ttl: 3600}]},
155 transports: {TROUTER: [{context: '', path: state.surl, ttl: 3600}]},
151 };
156 };
@@ -212,6 +217,11 @@
212 send('3:::' + JSON.stringify({id: request.id, status: 200, headers: {}, body: ''}));
217 send('3:::' + JSON.stringify({id: request.id, status: 200, headers: {}, body: ''}));
213 let body = null;
218 let body = null;
214 try { body = JSON.parse(request.body); } catch (error) {}
219 try { body = JSON.parse(request.body); } catch (error) {}
220 if (FORWARD_CALLBACKS && body && typeof body.evt === 'number') {
221 forward({channel: 'callback', requestId: request.id, path: '', contentEncoding: null,
222 body: typeof request.body === 'string' ? request.body : JSON.stringify(request.body)});
223 return;
224 }
215 forwardNotification(path, body);
225 forwardNotification(path, body);
216 }
226 }
217 };
227 };
crates/chatsvc/src/realtime/mod.rs +2 −0
@@ -34,6 +34,7 @@ pub struct RealtimeConfig {
34 34 pub max_reattach_backoff: Duration,
35 35 pub instance: InstanceNames,
36 36 pub forward_callbacks: bool,
37 pub ringable: bool,
37 38 }
38 39
39 40 /// Page globals of one Trouter client; a second client in the same tab needs its own names.
@@ -65,6 +66,7 @@ impl Default for RealtimeConfig {
65 66 max_reattach_backoff: Duration::from_secs(30),
66 67 instance: InstanceNames::default(),
67 68 forward_callbacks: false,
69 ringable: false,
68 70 }
69 71 }
70 72 }
@@ -34,6 +34,7 @@ pub struct RealtimeConfig {
34 pub max_reattach_backoff: Duration,
34 pub max_reattach_backoff: Duration,
35 pub instance: InstanceNames,
35 pub instance: InstanceNames,
36 pub forward_callbacks: bool,
36 pub forward_callbacks: bool,
37 pub ringable: bool,
37}
38}
38
39
39/// Page globals of one Trouter client; a second client in the same tab needs its own names.
40/// Page globals of one Trouter client; a second client in the same tab needs its own names.
@@ -65,6 +66,7 @@ impl Default for RealtimeConfig {
65 max_reattach_backoff: Duration::from_secs(30),
66 max_reattach_backoff: Duration::from_secs(30),
66 instance: InstanceNames::default(),
67 instance: InstanceNames::default(),
67 forward_callbacks: false,
68 forward_callbacks: false,
69 ringable: false,
68 }
70 }
69 }
71 }
70}
72}
crates/chatsvc/src/realtime/runner.rs +20 −0
@@ -15,6 +15,7 @@ pub(super) const DEFAULT_BINDING_NAME: &str = "__chatsvcRealtime";
15 15 pub(super) const DEFAULT_EPID_KEY: &str = "__chatsvcEpid";
16 16 const WORKER_TEMPLATE: &str = include_str!("../../assets/trouter.js");
17 17 const FORWARD_CALLBACKS_OFF: &str = "const FORWARD_CALLBACKS = false;";
18 const REGISTRATION_OFF: &str = "const RINGABLE = false;";
18 19 const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10);
19 20
20 21 /// The page worker with this instance's names baked in.
@@ -36,6 +37,9 @@ impl PageScript {
36 37 if config.forward_callbacks {
37 38 worker_source = worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
38 39 }
40 if config.ringable {
41 worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");
42 }
39 43 PageScript {
40 44 global_name: names.global.clone(),
41 45 binding_name: names.binding.clone(),
@@ -338,4 +342,20 @@ mod tests {
338 342 let default_script = PageScript::new(&RealtimeConfig::default());
339 343 assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
340 344 }
345
346 #[test]
347 fn only_the_ringable_instance_registers_for_calls() {
348 let ringable = PageScript::new(&RealtimeConfig {
349 ringable: true,
350 ..RealtimeConfig::default()
351 });
352 assert!(ringable.worker_source.contains("const RINGABLE = true;"));
353 let quiet = PageScript::new(&RealtimeConfig::default());
354 assert!(quiet.worker_source.contains(REGISTRATION_OFF));
355 for script in [ringable, quiet] {
356 assert!(script.worker_source.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}"));
357 assert!(script.worker_source.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}"));
358 assert!(script.worker_source.contains("RINGABLE ? {productContext: ''} : {}"));
359 }
360 }
341 361 }
@@ -15,6 +15,7 @@ pub(super) const DEFAULT_BINDING_NAME: &str = "__chatsvcRealtime";
15pub(super) const DEFAULT_EPID_KEY: &str = "__chatsvcEpid";
15pub(super) const DEFAULT_EPID_KEY: &str = "__chatsvcEpid";
16const WORKER_TEMPLATE: &str = include_str!("../../assets/trouter.js");
16const WORKER_TEMPLATE: &str = include_str!("../../assets/trouter.js");
17const FORWARD_CALLBACKS_OFF: &str = "const FORWARD_CALLBACKS = false;";
17const FORWARD_CALLBACKS_OFF: &str = "const FORWARD_CALLBACKS = false;";
18const REGISTRATION_OFF: &str = "const RINGABLE = false;";
18const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10);
19const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10);
19
20
20/// The page worker with this instance's names baked in.
21/// The page worker with this instance's names baked in.
@@ -36,6 +37,9 @@ impl PageScript {
36 if config.forward_callbacks {
37 if config.forward_callbacks {
37 worker_source = worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
38 worker_source = worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
38 }
39 }
40 if config.ringable {
41 worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");
42 }
39 PageScript {
43 PageScript {
40 global_name: names.global.clone(),
44 global_name: names.global.clone(),
41 binding_name: names.binding.clone(),
45 binding_name: names.binding.clone(),
@@ -338,4 +342,20 @@ mod tests {
338 let default_script = PageScript::new(&RealtimeConfig::default());
342 let default_script = PageScript::new(&RealtimeConfig::default());
339 assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
343 assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
340 }
344 }
345
346 #[test]
347 fn only_the_ringable_instance_registers_for_calls() {
348 let ringable = PageScript::new(&RealtimeConfig {
349 ringable: true,
350 ..RealtimeConfig::default()
351 });
352 assert!(ringable.worker_source.contains("const RINGABLE = true;"));
353 let quiet = PageScript::new(&RealtimeConfig::default());
354 assert!(quiet.worker_source.contains(REGISTRATION_OFF));
355 for script in [ringable, quiet] {
356 assert!(script.worker_source.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}"));
357 assert!(script.worker_source.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}"));
358 assert!(script.worker_source.contains("RINGABLE ? {productContext: ''} : {}"));
359 }
360 }
341}
361}