feat(calls): calls tab, join by ID or link, recording, hold and transfer, video calls, breakout rooms, whiteboard, image backgrounds
| Before | After | |---|---| | No call history | Calls tab (Ctrl+5): missed in red, outgoing, incoming, meetings with duration; click calls back or opens the meeting chat | | Join only from a meeting chat | Join with ID (meeting ID + passcode), Paste a meeting link, Join chip next to Teams meeting links | | No recording | Organizer Start/Stop recording, red Recording dot for everyone, consent notice | | - | 1:1 Hold / Resume, Transfer (blind or consult first) | | Audio-only 1:1 and incoming calls | Camera in 1:1 calls; incoming video ring: Decline / Audio / Video | | - | Breakout rooms as participant: moved with a notice, Return to main meeting | | - | Whiteboard: '<name> is sharing a whiteboard' with Open in browser | | Blur only | Microsoft's default background images (downloaded at runtime) and own images | - Verified live on Daniel's own account (self-created meetings, nobody invited): join with the extended join body, recording start/stop with the state seen on and off (test recording deleted), 70 background images listed and applied at 10.9 ms per frame, call log read (194 entries), join by meeting ID resolved a self-created scheduled meeting to the same chat (meeting deleted). - Join by ID is a roster-only conversation on epconv with callback links, like Teams web; it is left right after the lookup. - Not built: give/take control (Teams web cannot either), phone dialing (no Teams Phone license), breakout organizer side. - Needs a second person: hold/transfer, video in 1:1 and incoming calls, being moved to a breakout room, whiteboard sharing, recording consent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -1045,6 +1045,7 @@ dependencies = [
1045
1045
"cpal",
1046
1046
"flate2",
1047
1047
"futures-util",
1048
"image",
1048
1049
"libwebrtc",
1049
1050
"nokhwa",
1050
1051
"serde",
@@ -1045,6 +1045,7 @@ dependencies = [1045
"cpal",1045
"cpal",1046
"flate2",1046
"flate2",1047
"futures-util",1047
"futures-util",1048
"image",1048
"libwebrtc",1049
"libwebrtc",1049
"nokhwa",1050
"nokhwa",1050
"serde",1051
"serde",@@ -2,7 +2,7 @@
2
2
3
3
Feature parity with the Microsoft Teams desktop client.
4
4
5
**Parity: 91 %** (79 done, 9 partial, 4 missing of 92). Partial counts half.
5
**Parity: 89 %** (81 done, 14 partial, 4 missing of 99). 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) | 100 % | 5 | 0 | 0 |
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) | 60 % | 2 | 8 | 0 |
21
| [Calls and meetings](#calls-and-meetings) | 62 % | 4 | 13 | 0 |
22
22
23
23
## Next
24
24
@@ -166,11 +166,18 @@ Feature parity with the Microsoft Teams desktop client.
166
166
| 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 |
167
167
| 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 |
168
168
| 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 |
169
| Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person. Incoming calls stay audio-only |
169
| Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person |
170
170
| Meeting extras | Partial | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Checked with synthetic sources and the demo only; not yet live in a meeting or with a second person |
171
171
| Organizer controls | Partial | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Request bodies built from the Teams code and unit tested; demo checked, not yet live with a second person |
172
172
| Live captions | Partial | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. Message framing and parsing from the Teams code; not yet seen with real speech |
173
| Background blur | Partial | Camera menu Background: None / Blur (remembered). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |
173
| Backgrounds | Partial | Camera menu Background: None / Blur / Microsoft's default images / "Add image..." (remembered). The image list and thumbnails are fetched at runtime into the app data folder, nothing of Microsoft's ships with the app; the picture is cover-scaled behind the same segmentation mask (checked with a synthetic mask, demo with generated pictures, the CDN download only through `meet_now --background`). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |
174
| Video calls (1:1 and incoming) | Partial | Camera button in 1:1 calls renegotiates a video line on the same peer connection (modalities Audio and Video), incoming video ring toast with Decline / Audio / Video, accept with video answers the video line sending, accept with audio receive-only. Offer and answer built from the Teams code and unit tested at SDP level; needs a second person |
175
| Recording | Partial | Organizer "..." > Start recording / Stop recording (confirm) through the recorder bot, red dot and "Recording" in the header for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; start and stop run live through `meet_now --record`, consent needs a tenant with the policy on and a second person |
176
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |
177
| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |
178
| Whiteboard | Partial | Stage shows "<name> is sharing a whiteboard" with Open in browser, "..." > Whiteboard opens the meeting's board. State parsing unit tested; the share callback link is registered on join but not yet seen live |
179
| Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |
180
| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |
174
181
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |
175
182
176
183
## Agents
@@ -2,7 +2,7 @@2
2
3
Feature parity with the Microsoft Teams desktop client.3
Feature parity with the Microsoft Teams desktop client.4
4
5
**Parity: 91 %** (79 done, 9 partial, 4 missing of 92). Partial counts half.5
**Parity: 89 %** (81 done, 14 partial, 4 missing of 99). Partial counts half.6
6
7
## By area7
## By area8
8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.18
| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |18
| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |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) | 60 % | 2 | 8 | 0 |21
| [Calls and meetings](#calls-and-meetings) | 62 % | 4 | 13 | 0 |22
22
23
## Next23
## Next24
24
@@ -166,11 +166,18 @@ Feature parity with the Microsoft Teams desktop client.166
| 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 |166
| 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 |167
| 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 |167
| 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 |168
| 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 |168
| 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 |169
| Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person. Incoming calls stay audio-only |169
| Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person |170
| Meeting extras | Partial | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Checked with synthetic sources and the demo only; not yet live in a meeting or with a second person |170
| Meeting extras | Partial | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Checked with synthetic sources and the demo only; not yet live in a meeting or with a second person |171
| Organizer controls | Partial | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Request bodies built from the Teams code and unit tested; demo checked, not yet live with a second person |171
| Organizer controls | Partial | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Request bodies built from the Teams code and unit tested; demo checked, not yet live with a second person |172
| Live captions | Partial | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. Message framing and parsing from the Teams code; not yet seen with real speech |172
| Live captions | Partial | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. Message framing and parsing from the Teams code; not yet seen with real speech |173
| Background blur | Partial | Camera menu Background: None / Blur (remembered). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |173
| Backgrounds | Partial | Camera menu Background: None / Blur / Microsoft's default images / "Add image..." (remembered). The image list and thumbnails are fetched at runtime into the app data folder, nothing of Microsoft's ships with the app; the picture is cover-scaled behind the same segmentation mask (checked with a synthetic mask, demo with generated pictures, the CDN download only through `meet_now --background`). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |174
| Video calls (1:1 and incoming) | Partial | Camera button in 1:1 calls renegotiates a video line on the same peer connection (modalities Audio and Video), incoming video ring toast with Decline / Audio / Video, accept with video answers the video line sending, accept with audio receive-only. Offer and answer built from the Teams code and unit tested at SDP level; needs a second person |175
| Recording | Partial | Organizer "..." > Start recording / Stop recording (confirm) through the recorder bot, red dot and "Recording" in the header for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; start and stop run live through `meet_now --record`, consent needs a tenant with the policy on and a second person |176
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |177
| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |178
| Whiteboard | Partial | Stage shows "<name> is sharing a whiteboard" with Open in browser, "..." > Whiteboard opens the meeting's board. State parsing unit tested; the share callback link is registered on join but not yet seen live |179
| Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |180
| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |174
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |181
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |175
182
176
## Agents183
## Agents@@ -56,6 +56,7 @@ pub enum AppEvent {
56
56
Scheduled,
57
57
Pins(String),
58
58
Saved,
59
CallHistory,
59
60
Translation,
60
61
Forward,
61
62
StatusMessage,
@@ -103,6 +104,7 @@ pub struct AppState {
103
104
pub scheduled: Vec<ScheduledDraft>,
104
105
pub scheduled_polling: bool,
105
106
pub saved: SavedSet,
107
pub call_history: Vec<teams_core::CallLogEntry>,
106
108
pub pins: HashMap<String, Vec<PinnedMessage>>,
107
109
pub forward_request: Option<ForwardSource>,
108
110
pub own_status: PresenceStatus,
@@ -115,7 +117,9 @@ pub struct AppState {
115
117
pub call_launcher: Option<Arc<CallLauncher>>,
116
118
pub call_count: u64,
117
119
pub call_share_sound: bool,
118
pub call_background_blur: bool,
120
pub call_background: crate::call::BackgroundPick,
121
pub call_backgrounds: crate::call::BackgroundLibrary,
122
pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
119
123
pub rings: Rings,
120
124
pub live_meetings: HashMap<String, LiveMeeting>,
121
125
pub live_refreshing: HashSet<String>,
@@ -195,6 +199,7 @@ impl AppState {
195
199
scheduled: Vec::new(),
196
200
scheduled_polling: false,
197
201
saved: SavedSet::default(),
202
call_history: Vec::new(),
198
203
pins: HashMap::new(),
199
204
forward_request: None,
200
205
own_status: PresenceStatus::default(),
@@ -207,7 +212,13 @@ impl AppState {
207
212
call_launcher: None,
208
213
call_count: 0,
209
214
call_share_sound: false,
210
call_background_blur: false,
215
call_background: crate::call::BackgroundPick::None,
216
call_backgrounds: if mode.demo {
217
crate::call::demo_library()
218
} else {
219
crate::call::BackgroundLibrary::new(crate::call::default_cache_directory())
220
},
221
transfer_picker: None,
211
222
rings: Rings::default(),
212
223
live_meetings: HashMap::new(),
213
224
live_refreshing: HashSet::new(),
@@ -216,7 +227,8 @@ impl AppState {
216
227
state.local_previews = load_local_previews(&state.store);
217
228
state.collapsed = state.load_collapsed();
218
229
state.call_share_sound = crate::call::load_share_sound(&state.store);
219
state.call_background_blur = crate::call::load_background_blur(&state.store);
230
state.call_background = crate::call::load_background(&state.store);
231
state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
220
232
state.load_cached_translation_settings();
221
233
if !mode.demo {
222
234
state.directory.load_cached_presence(&state.store);
@@ -56,6 +56,7 @@ pub enum AppEvent {56
Scheduled,56
Scheduled,57
Pins(String),57
Pins(String),58
Saved,58
Saved,59
CallHistory,59
Translation,60
Translation,60
Forward,61
Forward,61
StatusMessage,62
StatusMessage,@@ -103,6 +104,7 @@ pub struct AppState {103
pub scheduled: Vec<ScheduledDraft>,104
pub scheduled: Vec<ScheduledDraft>,104
pub scheduled_polling: bool,105
pub scheduled_polling: bool,105
pub saved: SavedSet,106
pub saved: SavedSet,107
pub call_history: Vec<teams_core::CallLogEntry>,106
pub pins: HashMap<String, Vec<PinnedMessage>>,108
pub pins: HashMap<String, Vec<PinnedMessage>>,107
pub forward_request: Option<ForwardSource>,109
pub forward_request: Option<ForwardSource>,108
pub own_status: PresenceStatus,110
pub own_status: PresenceStatus,@@ -115,7 +117,9 @@ pub struct AppState {115
pub call_launcher: Option<Arc<CallLauncher>>,117
pub call_launcher: Option<Arc<CallLauncher>>,116
pub call_count: u64,118
pub call_count: u64,117
pub call_share_sound: bool,119
pub call_share_sound: bool,118
pub call_background_blur: bool,120
pub call_background: crate::call::BackgroundPick,121
pub call_backgrounds: crate::call::BackgroundLibrary,122
pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,119
pub rings: Rings,123
pub rings: Rings,120
pub live_meetings: HashMap<String, LiveMeeting>,124
pub live_meetings: HashMap<String, LiveMeeting>,121
pub live_refreshing: HashSet<String>,125
pub live_refreshing: HashSet<String>,@@ -195,6 +199,7 @@ impl AppState {195
scheduled: Vec::new(),199
scheduled: Vec::new(),196
scheduled_polling: false,200
scheduled_polling: false,197
saved: SavedSet::default(),201
saved: SavedSet::default(),202
call_history: Vec::new(),198
pins: HashMap::new(),203
pins: HashMap::new(),199
forward_request: None,204
forward_request: None,200
own_status: PresenceStatus::default(),205
own_status: PresenceStatus::default(),@@ -207,7 +212,13 @@ impl AppState {207
call_launcher: None,212
call_launcher: None,208
call_count: 0,213
call_count: 0,209
call_share_sound: false,214
call_share_sound: false,210
call_background_blur: false,215
call_background: crate::call::BackgroundPick::None,216
call_backgrounds: if mode.demo {217
crate::call::demo_library()218
} else {219
crate::call::BackgroundLibrary::new(crate::call::default_cache_directory())220
},221
transfer_picker: None,211
rings: Rings::default(),222
rings: Rings::default(),212
live_meetings: HashMap::new(),223
live_meetings: HashMap::new(),213
live_refreshing: HashSet::new(),224
live_refreshing: HashSet::new(),@@ -216,7 +227,8 @@ impl AppState {216
state.local_previews = load_local_previews(&state.store);227
state.local_previews = load_local_previews(&state.store);217
state.collapsed = state.load_collapsed();228
state.collapsed = state.load_collapsed();218
state.call_share_sound = crate::call::load_share_sound(&state.store);229
state.call_share_sound = crate::call::load_share_sound(&state.store);219
state.call_background_blur = crate::call::load_background_blur(&state.store);230
state.call_background = crate::call::load_background(&state.store);231
state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);220
state.load_cached_translation_settings();232
state.load_cached_translation_settings();221
if !mode.demo {233
if !mode.demo {222
state.directory.load_cached_presence(&state.store);234
state.directory.load_cached_presence(&state.store);@@ -2,13 +2,14 @@ use std::time::{Duration, Instant};
2
2
3
3
use calling::meeting::LiveMeeting;
4
4
use calling::{
5
CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
5
AcceptMode, CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
6
6
};
7
7
use gpui_kit::*;
8
8
9
use super::demo::{DemoCall, demo_caller, demo_guests, demo_ring, start_demo_call};
9
use super::background::{BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds};
10
use super::demo::{DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call, start_demo_scene_call};
11
use super::features::room_closed_move;
10
12
use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
11
use super::pictures::CallPictures;
12
13
use super::ring::{MissedCall, RingOutcome};
13
14
use super::target::{is_organizer, plan_for_chat};
14
15
use crate::app_state::{AppEvent, AppState, Selection, chat_title};
@@ -16,10 +17,10 @@ use crate::notify::selection_for;
16
17
17
18
const TIMER_REFRESH: Duration = Duration::from_millis(500);
18
19
const SHARE_SOURCES_EVERY_TICKS: u32 = 10;
19
const NOT_CONNECTED_NOTICE: &str = "Not connected to Teams yet";
20
pub(super) const NOT_CONNECTED_NOTICE: &str = "Not connected to Teams yet";
20
21
const READ_ONLY_NOTICE: &str = "Calls are off in read-only mode";
21
22
const NOT_CALLABLE_NOTICE: &str = "This chat cannot be called";
22
const MEETING_UNAVAILABLE_NOTICE: &str = "This meeting cannot be joined";
23
pub(super) const MEETING_UNAVAILABLE_NOTICE: &str = "This meeting cannot be joined";
23
24
const ANSWER_FAILED_NOTICE: &str = "Could not answer the call";
24
25
const MEETING_KIND: &str = "meeting";
25
26
const DEMO_LOBBY_MEETING: &str = "demo-chat-meeting-retro";
@@ -28,16 +29,11 @@ const DEMO_SMALL_MEETING: usize = 4;
28
29
const DEMO_LIVE_MINUTES: i64 = 60;
29
30
const ORGID_PREFIX: &str = "8:orgid:";
30
31
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
31
pub const BACKGROUND_BLUR_META_KEY: &str = "call_background_blur";
32
32
33
33
pub fn load_share_sound(store: &store::Store) -> bool {
34
34
store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")
35
35
}
36
36
37
pub fn load_background_blur(store: &store::Store) -> bool {
38
store.meta(BACKGROUND_BLUR_META_KEY).ok().flatten().as_deref() == Some("1")
39
}
40
41
37
fn now_unix() -> i64 {
42
38
chrono::Utc::now().timestamp()
43
39
}
@@ -112,7 +108,7 @@ impl AppState {
112
108
lobby: conversation_id == DEMO_LOBBY_MEETING,
113
109
organizer: conversation_id != DEMO_LOBBY_MEETING,
114
110
};
115
let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, cx) else {
111
let Some(handle) = self.place_call(CallSpec::Meeting(target.clone()), demo, cx) else {
116
112
return;
117
113
};
118
114
let title = selection_for(&self.sidebar, conversation_id)
@@ -120,9 +116,12 @@ impl AppState {
120
116
.unwrap_or_else(|| "Meeting".to_owned());
121
117
let model = CallModel::meeting(&title, is_organizer(&meeting, self.directory.me.as_ref()));
122
118
self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
119
if let Some(call) = self.call.as_mut() {
120
call.meeting_target = Some(target);
121
}
123
122
}
124
123
125
fn place_call(&mut self, spec: CallSpec, demo: DemoCall, cx: &mut Context<Self>) -> Option<CallHandle> {
124
pub(super) fn place_call(&mut self, spec: CallSpec, demo: DemoCall, cx: &mut Context<Self>) -> Option<CallHandle> {
126
125
if self.mode.demo {
127
126
return Some(start_demo_call(demo));
128
127
}
@@ -139,7 +138,7 @@ impl AppState {
139
138
}
140
139
}
141
140
142
fn begin_call(
141
pub(super) fn begin_call(
143
142
&mut self,
144
143
handle: CallHandle,
145
144
model: CallModel,
@@ -149,26 +148,17 @@ impl AppState {
149
148
self.call_count += 1;
150
149
let call_id = self.call_count;
151
150
let CallHandle { commands, updates, video } = handle;
152
self.call = Some(ActiveCall {
153
id: call_id,
154
model,
155
commands,
156
viewing: true,
157
conversation_id,
158
video,
159
pictures: CallPictures::default(),
160
stage_fullscreen: false,
161
chat_open: false,
162
});
151
self.call = Some(ActiveCall::new(call_id, model, commands, conversation_id, video));
163
152
if self.call_share_sound {
164
153
self.send_call_command(CallCommand::SetShareSound(true));
165
154
}
166
if self.call_background_blur {
167
self.send_call_command(CallCommand::SetBlur(true));
168
if let Some(call) = self.call.as_mut() {
169
call.model.blur = true;
170
}
155
if let Some(call) = self.call.as_mut() {
156
call.model.background = self.call_background.clone();
157
}
158
if self.call_background != BackgroundPick::None {
159
self.send_background_command(cx);
171
160
}
161
self.refresh_call_backgrounds(cx);
172
162
self.new_chat = false;
173
163
self.follow_call(call_id, updates, cx);
174
164
cx.emit(AppEvent::Call);
@@ -227,6 +217,14 @@ impl AppState {
227
217
self.raise_notice(text, None, cx);
228
218
return;
229
219
}
220
CallUpdate::WhiteboardUrl(url) => {
221
cx.open_url(&url);
222
return;
223
}
224
CallUpdate::BreakoutMove(moved) => {
225
self.begin_breakout_move(moved, cx);
226
return;
227
}
230
228
_ => {}
231
229
}
232
230
call.model.apply(update);
@@ -244,14 +242,23 @@ impl AppState {
244
242
};
245
243
let elapsed = call.model.elapsed(Instant::now());
246
244
let notice = ended_notice(&reason, elapsed, &call.model.peer_name);
245
let next_move = call.pending_move.take().or_else(|| room_closed_move(call, &reason));
246
let consult = call.consult.take();
247
247
call.pictures.clear(cx);
248
248
self.call = None;
249
self.raise_notice(notice, None, cx);
249
if let Some(consult) = consult {
250
let _ = consult.commands.send(CallCommand::Hangup);
251
}
252
match next_move {
253
Some(next_move) => self.join_moved_call(next_move, cx),
254
None => self.raise_notice(notice, None, cx),
255
}
256
self.refresh_call_history_after_call(cx);
250
257
cx.emit(AppEvent::Call);
251
258
cx.notify();
252
259
}
253
260
254
fn send_call_command(&self, command: CallCommand) {
261
pub(super) fn send_call_command(&self, command: CallCommand) {
255
262
if let Some(call) = &self.call {
256
263
let _ = call.commands.send(command);
257
264
}
@@ -458,16 +465,84 @@ impl AppState {
458
465
self.send_call_command(CallCommand::SetCaptions(on));
459
466
}
460
467
461
pub fn set_call_background_blur(&mut self, on: bool, cx: &mut Context<Self>) {
462
self.call_background_blur = on;
463
let _ = self.store.set_meta(BACKGROUND_BLUR_META_KEY, if on { "1" } else { "0" });
468
pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
469
let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());
470
self.call_background = pick.clone();
464
471
if let Some(call) = self.call.as_mut() {
465
call.model.blur = on;
472
call.model.background = pick;
466
473
}
467
self.send_call_command(CallCommand::SetBlur(on));
474
self.send_background_command(cx);
468
475
cx.notify();
469
476
}
470
477
478
pub(super) fn send_background_command(&mut self, cx: &mut Context<Self>) {
479
let pick = self.call_background.clone();
480
if let Some(choice) = self.call_backgrounds.choice_for(&pick) {
481
self.send_call_command(CallCommand::SetBackground(choice));
482
return;
483
}
484
let BackgroundPick::Default(id) = pick else { return };
485
let Some(image) = self.call_backgrounds.find(&id).cloned() else { return };
486
let Some(launcher) = self.call_launcher.clone() else { return };
487
let cache = self.call_backgrounds.cache.clone();
488
let receiver = crate::runtime::spawn(async move { launcher.download_background(&cache, &image).await });
489
cx.spawn(async move |this, cx| {
490
let path = receiver.await.ok().flatten();
491
this.update(cx, |state, cx| match path {
492
Some(path) if state.call_background == BackgroundPick::Default(id) => {
493
state.send_call_command(CallCommand::SetBackground(calling::BackgroundChoice::Image(path)));
494
}
495
Some(_) => {}
496
None => state.raise_notice("That background could not be downloaded".to_owned(), None, cx),
497
})
498
.ok();
499
})
500
.detach();
501
}
502
503
pub fn refresh_call_backgrounds(&mut self, cx: &mut Context<Self>) {
504
if self.mode.demo || !self.call_backgrounds.needs_refresh() {
505
return;
506
}
507
let Some(launcher) = self.call_launcher.clone() else { return };
508
self.call_backgrounds.refreshing = true;
509
let cache = self.call_backgrounds.cache.clone();
510
let wanted = SHOWN_IMAGES;
511
let receiver = crate::runtime::spawn(async move { launcher.refresh_backgrounds(&cache, wanted).await });
512
cx.spawn(async move |this, cx| {
513
let catalog = receiver.await.ok().flatten();
514
this.update(cx, |state, cx| {
515
state.call_backgrounds.refreshing = false;
516
if let Some(catalog) = catalog {
517
state.call_backgrounds.images = catalog;
518
}
519
cx.notify();
520
})
521
.ok();
522
})
523
.detach();
524
}
525
526
pub fn add_call_background(&mut self, cx: &mut Context<Self>) {
527
let receiver = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: None });
528
cx.spawn(async move |this, cx| {
529
let Some(path) = receiver.await.ok().and_then(Result::ok).flatten().and_then(|paths| paths.into_iter().next()) else {
530
return;
531
};
532
this.update(cx, |state, cx| {
533
if !is_image_file(&path) {
534
state.raise_notice("Pick a JPG or PNG picture".to_owned(), None, cx);
535
return;
536
}
537
state.call_backgrounds.add_custom(path.clone());
538
save_custom_backgrounds(&state.store, &state.call_backgrounds.customs);
539
state.set_call_background(BackgroundPick::Custom(path), cx);
540
})
541
.ok();
542
})
543
.detach();
544
}
545
471
546
pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
472
547
let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
473
548
return;
@@ -519,6 +594,32 @@ impl AppState {
519
594
self.push_ring(demo_ring(), true, cx);
520
595
}
521
596
597
pub fn demo_incoming_video_ring(&mut self, cx: &mut Context<Self>) {
598
self.push_ring(demo_video_ring(), true, cx);
599
}
600
601
pub fn start_demo_scene(&mut self, scene: DemoScene, cx: &mut Context<Self>) {
602
if self.call.is_some() {
603
return;
604
}
605
let (script, model, conversation_id) = if scene.is_one_to_one() {
606
(DemoCall::People(vec![demo_caller()]), CallModel::people("Mara Lindqvist", &[demo_caller()]), "demo-chat-mara")
607
} else {
608
let script = DemoCall::Meeting { guests: demo_guests(DEMO_SMALL_MEETING), lobby: false, organizer: true };
609
(script, CallModel::meeting("Standup", true), "demo-chat-meeting-standup")
610
};
611
let handle = start_demo_scene_call(script, scene);
612
self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
613
if let Some(call) = self.call.as_mut().filter(|_| !scene.is_one_to_one()) {
614
call.meeting_target = Some(calling::MeetingTarget {
615
thread_id: conversation_id.to_owned(),
616
tenant_id: "demo-tenant".to_owned(),
617
organizer_id: "demo-me".to_owned(),
618
meeting_data: None,
619
});
620
}
621
}
622
522
623
fn signal_ring(&mut self, ring_id: u64, signal: RingSignal, cx: &mut Context<Self>) {
523
624
if let Some(outcome) = self.rings.signal(ring_id, signal, Instant::now()) {
524
625
self.finish_ring(ring_id, outcome, cx);
@@ -547,7 +648,7 @@ impl AppState {
547
648
548
649
pub fn accept_ringing_call(&mut self, cx: &mut Context<Self>) {
549
650
if let Some(ring_id) = self.rings.first_ringing_id() {
550
self.accept_ring(ring_id, cx);
651
self.accept_ring(ring_id, AcceptMode::Audio, cx);
551
652
}
552
653
}
553
654
@@ -557,7 +658,7 @@ impl AppState {
557
658
}
558
659
}
559
660
560
pub fn accept_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {
661
pub fn accept_ring(&mut self, ring_id: u64, mode: AcceptMode, cx: &mut Context<Self>) {
561
662
let Some(entry) = self.rings.get(ring_id).cloned() else {
562
663
return;
563
664
};
@@ -576,13 +677,16 @@ impl AppState {
576
677
if entry.demo {
577
678
let handle = start_demo_call(DemoCall::Incoming(demo_caller()));
578
679
self.begin_call(handle, model, conversation_id, cx);
680
if mode == AcceptMode::Video {
681
self.send_call_command(CallCommand::SetCamera(true));
682
}
579
683
return;
580
684
}
581
685
let Some(launcher) = self.call_launcher.clone() else {
582
686
self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);
583
687
return;
584
688
};
585
let receiver = crate::runtime::spawn(async move { launcher.accept_ring(ring_id).await });
689
let receiver = crate::runtime::spawn(async move { launcher.accept_ring(ring_id, mode).await });
586
690
cx.spawn(async move |this, cx| {
587
691
let handle = receiver.await.ok().flatten();
588
692
this.update(cx, |state, cx| match handle {
@@ -696,13 +800,19 @@ mod tests {
696
800
use std::sync::Arc;
697
801
use std::time::{Duration, Instant};
698
802
699
use calling::{CallCommand, CallControl, CallState, CallUpdate, EndKind, EndReason, EngineEvent, Reaction, call_channel};
803
use std::path::PathBuf;
804
805
use calling::{BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel};
700
806
use gpui_kit::{AppContext as _, Entity, TestAppContext};
701
807
use store::{ChatRecord, MemberRecord, Store};
702
808
703
use super::{ActiveCall, CallModel, CallPictures};
809
use super::{ActiveCall, CallModel};
704
810
use crate::app_state::{AppState, Mode, Selection};
811
use crate::call::TransferCandidate;
812
use crate::call::background::BackgroundPick;
705
813
use crate::call::demo::demo_ring;
814
use crate::call::features::room_closed_move;
815
use crate::call::model::{BreakoutState, ConsultCall};
706
816
use crate::data::Person;
707
817
708
818
fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
@@ -712,17 +822,7 @@ mod tests {
712
822
let (handle, _control) = call_channel();
713
823
cx.update(|cx| {
714
824
app.update(cx, |state, _| {
715
state.call = Some(ActiveCall {
716
id: 7,
717
model: CallModel::test(),
718
commands: handle.commands,
719
viewing: true,
720
conversation_id: None,
721
video: handle.video,
722
pictures: CallPictures::default(),
723
stage_fullscreen: false,
724
chat_open: false,
725
});
825
state.call = Some(ActiveCall::new(7, CallModel::test(), handle.commands, None, handle.video));
726
826
})
727
827
});
728
828
app
@@ -736,17 +836,7 @@ mod tests {
736
836
let conversation_id = conversation_id.map(str::to_owned);
737
837
cx.update(|cx| {
738
838
app.update(cx, |state, _| {
739
state.call = Some(ActiveCall {
740
id: 7,
741
model,
742
commands: handle.commands,
743
viewing: true,
744
conversation_id,
745
video: handle.video,
746
pictures: CallPictures::default(),
747
stage_fullscreen: false,
748
chat_open: false,
749
});
839
state.call = Some(ActiveCall::new(7, model, handle.commands, conversation_id, handle.video));
750
840
})
751
841
});
752
842
(app, control)
@@ -897,15 +987,221 @@ mod tests {
897
987
fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
898
988
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
899
989
let store = cx.update(|cx| app.read(cx).store.clone());
900
assert!(!cx.update(|cx| app.read(cx).call_background_blur));
901
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background_blur(true, cx)));
902
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBlur(true)));
903
assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.blur));
990
assert_eq!(cx.update(|cx| app.read(cx).call_background.clone()), BackgroundPick::None);
991
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Blur, cx)));
992
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::Blur)));
993
assert_eq!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.background.clone()), BackgroundPick::Blur);
904
994
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
905
assert!(cx.update(|cx| reopened.read(cx).call_background_blur));
906
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background_blur(false, cx)));
995
assert_eq!(cx.update(|cx| reopened.read(cx).call_background.clone()), BackgroundPick::Blur);
996
let picture = PathBuf::from("/pictures/wall.jpg");
997
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Custom(picture.clone()), cx)));
998
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::Image(picture.clone()))));
907
999
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
908
assert!(!cx.update(|cx| reopened.read(cx).call_background_blur));
1000
assert_eq!(cx.update(|cx| reopened.read(cx).call_background.clone()), BackgroundPick::Custom(picture));
1001
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::None, cx)));
1002
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::None)));
1003
}
1004
1005
#[gpui_kit::test]
1006
fn a_default_image_that_is_not_downloaded_yet_sends_nothing(cx: &mut TestAppContext) {
1007
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1008
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Default("office_01".into()), cx)));
1009
assert_eq!(control.try_recv_command(), None);
1010
}
1011
1012
#[gpui_kit::test]
1013
fn only_the_organizer_starts_a_recording_and_the_notice_needs_a_consent_request(cx: &mut TestAppContext) {
1014
let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);
1015
cx.update(|cx| {
1016
attendee.update(cx, |state, cx| {
1017
state.set_call_recording(true, cx);
1018
state.accept_recording_notice(cx);
1019
})
1020
});
1021
assert_eq!(attendee_control.try_recv_command(), None);
1022
let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1023
cx.update(|cx| {
1024
organizer.update(cx, |state, cx| {
1025
state.set_call_recording(true, cx);
1026
state.apply_call_update(7, CallUpdate::Recording(true), cx);
1027
state.set_call_recording(false, cx);
1028
state.accept_recording_notice(cx);
1029
state.apply_call_update(7, CallUpdate::ConsentRequired(true), cx);
1030
state.accept_recording_notice(cx);
1031
})
1032
});
1033
assert_eq!(control.try_recv_command(), Some(CallCommand::SetRecording { on: true, title: "Standup".into() }));
1034
assert_eq!(control.try_recv_command(), Some(CallCommand::SetRecording { on: false, title: "Standup".into() }));
1035
assert_eq!(control.try_recv_command(), Some(CallCommand::ConsentToRecording));
1036
assert_eq!(control.try_recv_command(), None);
1037
}
1038
1039
fn live_one_to_one() -> CallModel {
1040
let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
1041
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1042
model
1043
}
1044
1045
#[gpui_kit::test]
1046
fn hold_and_resume_alternate_and_stop_while_the_other_side_holds(cx: &mut TestAppContext) {
1047
let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
1048
cx.update(|cx| {
1049
app.update(cx, |state, cx| {
1050
state.toggle_call_hold(cx);
1051
state.apply_call_update(7, CallUpdate::Hold(HoldState::Local), cx);
1052
state.toggle_call_hold(cx);
1053
state.apply_call_update(7, CallUpdate::Hold(HoldState::Remote), cx);
1054
state.toggle_call_hold(cx);
1055
})
1056
});
1057
assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(true)));
1058
assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(false)));
1059
assert_eq!(control.try_recv_command(), None);
1060
let (meeting, mut meeting_control) = app_with_commands(cx, live_meeting(true), None);
1061
cx.update(|cx| meeting.update(cx, |state, cx| state.toggle_call_hold(cx)));
1062
assert_eq!(meeting_control.try_recv_command(), None);
1063
}
1064
1065
fn candidate(name: &str) -> TransferCandidate {
1066
TransferCandidate { mri: format!("8:orgid:{name}"), name: name.into(), user_id: Some(name.into()), chat_id: format!("19:{name}") }
1067
}
1068
1069
#[gpui_kit::test]
1070
fn a_blind_transfer_names_the_target_and_a_consulted_one_carries_the_replacement_link(cx: &mut TestAppContext) {
1071
let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
1072
cx.update(|cx| app.update(cx, |state, cx| state.transfer_call_blind(candidate("ana"), cx)));
1073
assert_eq!(
1074
control.try_recv_command(),
1075
Some(CallCommand::Transfer { target: calling::Callee { mri: "8:orgid:ana".into(), display_name: "ana".into() }, replaces: None })
1076
);
1077
let (consulting, mut consult_control) = app_with_commands(cx, live_one_to_one(), None);
1078
let (consult_handle, _consult_updates) = call_channel();
1079
cx.update(|cx| {
1080
consulting.update(cx, |state, cx| {
1081
state.call.as_mut().unwrap().consult = Some(ConsultCall {
1082
id: 8,
1083
target: ("8:orgid:ana".into(), "Ana".into()),
1084
commands: consult_handle.commands,
1085
state: CallState::Connecting,
1086
replacement: Some("https://cc.skype.com/replacement".into()),
1087
transferring: false,
1088
});
1089
state.transfer_consulted(cx);
1090
state.call.as_mut().unwrap().consult.as_mut().unwrap().state = CallState::Connected { since: Instant::now() };
1091
state.transfer_consulted(cx);
1092
})
1093
});
1094
assert_eq!(
1095
consult_control.try_recv_command(),
1096
Some(CallCommand::Transfer {
1097
target: calling::Callee { mri: "8:orgid:ana".into(), display_name: "Ana".into() },
1098
replaces: Some("https://cc.skype.com/replacement".into()),
1099
})
1100
);
1101
assert_eq!(consult_control.try_recv_command(), None);
1102
}
1103
1104
#[gpui_kit::test]
1105
fn the_transfer_list_holds_one_to_one_chats_without_the_person_on_the_call(cx: &mut TestAppContext) {
1106
let app = app_with_chats(cx);
1107
cx.update(|cx| {
1108
app.update(cx, |state, cx| {
1109
let names: Vec<String> = state.transfer_candidates().into_iter().map(|candidate| candidate.name).collect();
1110
assert_eq!(names, vec!["Bea".to_owned()]);
1111
let (handle, _control) = call_channel();
1112
let mut on_the_call = CallModel::people("Bea", &[("8:orgid:bea-id".into(), "Bea".into())]);
1113
on_the_call.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1114
state.call = Some(ActiveCall::new(9, on_the_call, handle.commands, None, handle.video));
1115
assert!(state.transfer_candidates().is_empty());
1116
cx.notify();
1117
})
1118
});
1119
}
1120
1121
fn room_move(returning: bool) -> calling::BreakoutMove {
1122
calling::BreakoutMove {
1123
room_name: "Room 1".into(),
1124
target: calling::MeetingTarget { thread_id: "19:meeting_room@thread.v2".into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None },
1125
returning,
1126
}
1127
}
1128
1129
fn main_target() -> calling::MeetingTarget {
1130
calling::MeetingTarget { thread_id: "19:meeting_main@thread.v2".into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None }
1131
}
1132
1133
#[gpui_kit::test]
1134
fn being_moved_to_a_room_leaves_the_call_and_remembers_the_way_back(cx: &mut TestAppContext) {
1135
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1136
cx.update(|cx| {
1137
app.update(cx, |state, cx| {
1138
state.call.as_mut().unwrap().meeting_target = Some(main_target());
1139
state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
1140
let pending = state.call.as_ref().unwrap().pending_move.clone().expect("a move is pending");
1141
assert_eq!(pending.target.thread_id, "19:meeting_room@thread.v2");
1142
assert_eq!(pending.title, "Room 1");
1143
let room = pending.breakout.expect("a room");
1144
assert_eq!(room.main, Some(main_target()));
1145
assert_eq!(room.main_title, "Standup");
1146
assert_eq!(state.notice.as_ref().map(|notice| notice.text.as_str()), Some("Moving you to Room 1"));
1147
state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
1148
})
1149
});
1150
assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));
1151
assert_eq!(control.try_recv_command(), None);
1152
}
1153
1154
#[gpui_kit::test]
1155
fn the_return_button_and_a_closed_room_both_lead_back_to_the_main_meeting(cx: &mut TestAppContext) {
1156
let mut room = live_meeting(false);
1157
room.breakout = Some(BreakoutState { room_name: "Room 1".into(), main: Some(main_target()), main_title: "Standup".into() });
1158
let (app, mut control) = app_with_commands(cx, room.clone(), None);
1159
cx.update(|cx| {
1160
app.update(cx, |state, cx| {
1161
state.return_to_main_meeting(cx);
1162
let pending = state.call.as_ref().unwrap().pending_move.clone().expect("a move is pending");
1163
assert_eq!(pending.target, main_target());
1164
assert_eq!(pending.title, "Standup");
1165
assert!(pending.breakout.is_none());
1166
})
1167
});
1168
assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));
1169
let (closed, _control) = app_with_commands(cx, room, None);
1170
cx.update(|cx| {
1171
closed.update(cx, |state, _| {
1172
let call = state.call.as_ref().unwrap();
1173
let moved = room_closed_move(call, &EndReason::Remote(EndKind::RoomClosed)).expect("goes back");
1174
assert_eq!(moved.target, main_target());
1175
assert!(room_closed_move(call, &EndReason::Remote(EndKind::Normal)).is_none());
1176
assert!(room_closed_move(call, &EndReason::LocalHangup).is_none());
1177
})
1178
});
1179
let (plain, _control) = app_with_commands(cx, live_meeting(false), None);
1180
cx.update(|cx| plain.update(cx, |state, _| assert!(room_closed_move(state.call.as_ref().unwrap(), &EndReason::Remote(EndKind::RoomClosed)).is_none())));
1181
}
1182
1183
#[gpui_kit::test]
1184
fn the_whiteboard_menu_asks_for_the_board_unless_someone_already_shares_one(cx: &mut TestAppContext) {
1185
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1186
cx.update(|cx| {
1187
app.update(cx, |state, cx| {
1188
state.open_call_whiteboard(cx);
1189
state.apply_call_update(
1190
7,
1191
CallUpdate::Whiteboard(Some(calling::ContentShare {
1192
session_id: "s".into(),
1193
presenter: Some("8:orgid:ana".into()),
1194
subject: "Whiteboard".into(),
1195
url: Some("https://app.whiteboard.microsoft.com/x".into()),
1196
whiteboard: true,
1197
})),
1198
cx,
1199
);
1200
state.open_call_whiteboard(cx);
1201
})
1202
});
1203
assert_eq!(control.try_recv_command(), Some(CallCommand::OpenWhiteboard { title: "Standup".into() }));
1204
assert_eq!(control.try_recv_command(), None);
909
1205
}
910
1206
911
1207
#[gpui_kit::test]
@@ -2,13 +2,14 @@ use std::time::{Duration, Instant};2
2
3
use calling::meeting::LiveMeeting;3
use calling::meeting::LiveMeeting;4
use calling::{4
use calling::{5
CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,5
AcceptMode, CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,6
};6
};7
use gpui_kit::*;7
use gpui_kit::*;8
8
9
use super::demo::{DemoCall, demo_caller, demo_guests, demo_ring, start_demo_call};9
use super::background::{BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds};10
use super::demo::{DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call, start_demo_scene_call};11
use super::features::room_closed_move;10
use super::model::{ActiveCall, CallKind, CallModel, ended_notice};12
use super::model::{ActiveCall, CallKind, CallModel, ended_notice};11
use super::pictures::CallPictures;12
use super::ring::{MissedCall, RingOutcome};13
use super::ring::{MissedCall, RingOutcome};13
use super::target::{is_organizer, plan_for_chat};14
use super::target::{is_organizer, plan_for_chat};14
use crate::app_state::{AppEvent, AppState, Selection, chat_title};15
use crate::app_state::{AppEvent, AppState, Selection, chat_title};@@ -16,10 +17,10 @@ use crate::notify::selection_for;16
17
17
const TIMER_REFRESH: Duration = Duration::from_millis(500);18
const TIMER_REFRESH: Duration = Duration::from_millis(500);18
const SHARE_SOURCES_EVERY_TICKS: u32 = 10;19
const SHARE_SOURCES_EVERY_TICKS: u32 = 10;19
const NOT_CONNECTED_NOTICE: &str = "Not connected to Teams yet";20
pub(super) const NOT_CONNECTED_NOTICE: &str = "Not connected to Teams yet";20
const READ_ONLY_NOTICE: &str = "Calls are off in read-only mode";21
const READ_ONLY_NOTICE: &str = "Calls are off in read-only mode";21
const NOT_CALLABLE_NOTICE: &str = "This chat cannot be called";22
const NOT_CALLABLE_NOTICE: &str = "This chat cannot be called";22
const MEETING_UNAVAILABLE_NOTICE: &str = "This meeting cannot be joined";23
pub(super) const MEETING_UNAVAILABLE_NOTICE: &str = "This meeting cannot be joined";23
const ANSWER_FAILED_NOTICE: &str = "Could not answer the call";24
const ANSWER_FAILED_NOTICE: &str = "Could not answer the call";24
const MEETING_KIND: &str = "meeting";25
const MEETING_KIND: &str = "meeting";25
const DEMO_LOBBY_MEETING: &str = "demo-chat-meeting-retro";26
const DEMO_LOBBY_MEETING: &str = "demo-chat-meeting-retro";@@ -28,16 +29,11 @@ const DEMO_SMALL_MEETING: usize = 4;28
const DEMO_LIVE_MINUTES: i64 = 60;29
const DEMO_LIVE_MINUTES: i64 = 60;29
const ORGID_PREFIX: &str = "8:orgid:";30
const ORGID_PREFIX: &str = "8:orgid:";30
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";31
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";31
pub const BACKGROUND_BLUR_META_KEY: &str = "call_background_blur";32
32
33
pub fn load_share_sound(store: &store::Store) -> bool {33
pub fn load_share_sound(store: &store::Store) -> bool {34
store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")34
store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")35
}35
}36
36
37
pub fn load_background_blur(store: &store::Store) -> bool {38
store.meta(BACKGROUND_BLUR_META_KEY).ok().flatten().as_deref() == Some("1")39
}40
41
fn now_unix() -> i64 {37
fn now_unix() -> i64 {42
chrono::Utc::now().timestamp()38
chrono::Utc::now().timestamp()43
}39
}@@ -112,7 +108,7 @@ impl AppState {112
lobby: conversation_id == DEMO_LOBBY_MEETING,108
lobby: conversation_id == DEMO_LOBBY_MEETING,113
organizer: conversation_id != DEMO_LOBBY_MEETING,109
organizer: conversation_id != DEMO_LOBBY_MEETING,114
};110
};115
let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, cx) else {111
let Some(handle) = self.place_call(CallSpec::Meeting(target.clone()), demo, cx) else {116
return;112
return;117
};113
};118
let title = selection_for(&self.sidebar, conversation_id)114
let title = selection_for(&self.sidebar, conversation_id)@@ -120,9 +116,12 @@ impl AppState {120
.unwrap_or_else(|| "Meeting".to_owned());116
.unwrap_or_else(|| "Meeting".to_owned());121
let model = CallModel::meeting(&title, is_organizer(&meeting, self.directory.me.as_ref()));117
let model = CallModel::meeting(&title, is_organizer(&meeting, self.directory.me.as_ref()));122
self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);118
self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);119
if let Some(call) = self.call.as_mut() {120
call.meeting_target = Some(target);121
}123
}122
}124
123
125
fn place_call(&mut self, spec: CallSpec, demo: DemoCall, cx: &mut Context<Self>) -> Option<CallHandle> {124
pub(super) fn place_call(&mut self, spec: CallSpec, demo: DemoCall, cx: &mut Context<Self>) -> Option<CallHandle> {126
if self.mode.demo {125
if self.mode.demo {127
return Some(start_demo_call(demo));126
return Some(start_demo_call(demo));128
}127
}@@ -139,7 +138,7 @@ impl AppState {139
}138
}140
}139
}141
140
142
fn begin_call(141
pub(super) fn begin_call(143
&mut self,142
&mut self,144
handle: CallHandle,143
handle: CallHandle,145
model: CallModel,144
model: CallModel,@@ -149,26 +148,17 @@ impl AppState {149
self.call_count += 1;148
self.call_count += 1;150
let call_id = self.call_count;149
let call_id = self.call_count;151
let CallHandle { commands, updates, video } = handle;150
let CallHandle { commands, updates, video } = handle;152
self.call = Some(ActiveCall {151
self.call = Some(ActiveCall::new(call_id, model, commands, conversation_id, video));153
id: call_id,154
model,155
commands,156
viewing: true,157
conversation_id,158
video,159
pictures: CallPictures::default(),160
stage_fullscreen: false,161
chat_open: false,162
});163
if self.call_share_sound {152
if self.call_share_sound {164
self.send_call_command(CallCommand::SetShareSound(true));153
self.send_call_command(CallCommand::SetShareSound(true));165
}154
}166
if self.call_background_blur {155
if let Some(call) = self.call.as_mut() {167
self.send_call_command(CallCommand::SetBlur(true));156
call.model.background = self.call_background.clone();168
if let Some(call) = self.call.as_mut() {157
}169
call.model.blur = true;158
if self.call_background != BackgroundPick::None {170
}159
self.send_background_command(cx);171
}160
}161
self.refresh_call_backgrounds(cx);172
self.new_chat = false;162
self.new_chat = false;173
self.follow_call(call_id, updates, cx);163
self.follow_call(call_id, updates, cx);174
cx.emit(AppEvent::Call);164
cx.emit(AppEvent::Call);@@ -227,6 +217,14 @@ impl AppState {227
self.raise_notice(text, None, cx);217
self.raise_notice(text, None, cx);228
return;218
return;229
}219
}220
CallUpdate::WhiteboardUrl(url) => {221
cx.open_url(&url);222
return;223
}224
CallUpdate::BreakoutMove(moved) => {225
self.begin_breakout_move(moved, cx);226
return;227
}230
_ => {}228
_ => {}231
}229
}232
call.model.apply(update);230
call.model.apply(update);@@ -244,14 +242,23 @@ impl AppState {244
};242
};245
let elapsed = call.model.elapsed(Instant::now());243
let elapsed = call.model.elapsed(Instant::now());246
let notice = ended_notice(&reason, elapsed, &call.model.peer_name);244
let notice = ended_notice(&reason, elapsed, &call.model.peer_name);245
let next_move = call.pending_move.take().or_else(|| room_closed_move(call, &reason));246
let consult = call.consult.take();247
call.pictures.clear(cx);247
call.pictures.clear(cx);248
self.call = None;248
self.call = None;249
self.raise_notice(notice, None, cx);249
if let Some(consult) = consult {250
let _ = consult.commands.send(CallCommand::Hangup);251
}252
match next_move {253
Some(next_move) => self.join_moved_call(next_move, cx),254
None => self.raise_notice(notice, None, cx),255
}256
self.refresh_call_history_after_call(cx);250
cx.emit(AppEvent::Call);257
cx.emit(AppEvent::Call);251
cx.notify();258
cx.notify();252
}259
}253
260
254
fn send_call_command(&self, command: CallCommand) {261
pub(super) fn send_call_command(&self, command: CallCommand) {255
if let Some(call) = &self.call {262
if let Some(call) = &self.call {256
let _ = call.commands.send(command);263
let _ = call.commands.send(command);257
}264
}@@ -458,16 +465,84 @@ impl AppState {458
self.send_call_command(CallCommand::SetCaptions(on));465
self.send_call_command(CallCommand::SetCaptions(on));459
}466
}460
467
461
pub fn set_call_background_blur(&mut self, on: bool, cx: &mut Context<Self>) {468
pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {462
self.call_background_blur = on;469
let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());463
let _ = self.store.set_meta(BACKGROUND_BLUR_META_KEY, if on { "1" } else { "0" });470
self.call_background = pick.clone();464
if let Some(call) = self.call.as_mut() {471
if let Some(call) = self.call.as_mut() {465
call.model.blur = on;472
call.model.background = pick;466
}473
}467
self.send_call_command(CallCommand::SetBlur(on));474
self.send_background_command(cx);468
cx.notify();475
cx.notify();469
}476
}470
477
478
pub(super) fn send_background_command(&mut self, cx: &mut Context<Self>) {479
let pick = self.call_background.clone();480
if let Some(choice) = self.call_backgrounds.choice_for(&pick) {481
self.send_call_command(CallCommand::SetBackground(choice));482
return;483
}484
let BackgroundPick::Default(id) = pick else { return };485
let Some(image) = self.call_backgrounds.find(&id).cloned() else { return };486
let Some(launcher) = self.call_launcher.clone() else { return };487
let cache = self.call_backgrounds.cache.clone();488
let receiver = crate::runtime::spawn(async move { launcher.download_background(&cache, &image).await });489
cx.spawn(async move |this, cx| {490
let path = receiver.await.ok().flatten();491
this.update(cx, |state, cx| match path {492
Some(path) if state.call_background == BackgroundPick::Default(id) => {493
state.send_call_command(CallCommand::SetBackground(calling::BackgroundChoice::Image(path)));494
}495
Some(_) => {}496
None => state.raise_notice("That background could not be downloaded".to_owned(), None, cx),497
})498
.ok();499
})500
.detach();501
}502
503
pub fn refresh_call_backgrounds(&mut self, cx: &mut Context<Self>) {504
if self.mode.demo || !self.call_backgrounds.needs_refresh() {505
return;506
}507
let Some(launcher) = self.call_launcher.clone() else { return };508
self.call_backgrounds.refreshing = true;509
let cache = self.call_backgrounds.cache.clone();510
let wanted = SHOWN_IMAGES;511
let receiver = crate::runtime::spawn(async move { launcher.refresh_backgrounds(&cache, wanted).await });512
cx.spawn(async move |this, cx| {513
let catalog = receiver.await.ok().flatten();514
this.update(cx, |state, cx| {515
state.call_backgrounds.refreshing = false;516
if let Some(catalog) = catalog {517
state.call_backgrounds.images = catalog;518
}519
cx.notify();520
})521
.ok();522
})523
.detach();524
}525
526
pub fn add_call_background(&mut self, cx: &mut Context<Self>) {527
let receiver = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: None });528
cx.spawn(async move |this, cx| {529
let Some(path) = receiver.await.ok().and_then(Result::ok).flatten().and_then(|paths| paths.into_iter().next()) else {530
return;531
};532
this.update(cx, |state, cx| {533
if !is_image_file(&path) {534
state.raise_notice("Pick a JPG or PNG picture".to_owned(), None, cx);535
return;536
}537
state.call_backgrounds.add_custom(path.clone());538
save_custom_backgrounds(&state.store, &state.call_backgrounds.customs);539
state.set_call_background(BackgroundPick::Custom(path), cx);540
})541
.ok();542
})543
.detach();544
}545
471
pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {546
pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {472
let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {547
let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {473
return;548
return;@@ -519,6 +594,32 @@ impl AppState {519
self.push_ring(demo_ring(), true, cx);594
self.push_ring(demo_ring(), true, cx);520
}595
}521
596
597
pub fn demo_incoming_video_ring(&mut self, cx: &mut Context<Self>) {598
self.push_ring(demo_video_ring(), true, cx);599
}600
601
pub fn start_demo_scene(&mut self, scene: DemoScene, cx: &mut Context<Self>) {602
if self.call.is_some() {603
return;604
}605
let (script, model, conversation_id) = if scene.is_one_to_one() {606
(DemoCall::People(vec![demo_caller()]), CallModel::people("Mara Lindqvist", &[demo_caller()]), "demo-chat-mara")607
} else {608
let script = DemoCall::Meeting { guests: demo_guests(DEMO_SMALL_MEETING), lobby: false, organizer: true };609
(script, CallModel::meeting("Standup", true), "demo-chat-meeting-standup")610
};611
let handle = start_demo_scene_call(script, scene);612
self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);613
if let Some(call) = self.call.as_mut().filter(|_| !scene.is_one_to_one()) {614
call.meeting_target = Some(calling::MeetingTarget {615
thread_id: conversation_id.to_owned(),616
tenant_id: "demo-tenant".to_owned(),617
organizer_id: "demo-me".to_owned(),618
meeting_data: None,619
});620
}621
}622
522
fn signal_ring(&mut self, ring_id: u64, signal: RingSignal, cx: &mut Context<Self>) {623
fn signal_ring(&mut self, ring_id: u64, signal: RingSignal, cx: &mut Context<Self>) {523
if let Some(outcome) = self.rings.signal(ring_id, signal, Instant::now()) {624
if let Some(outcome) = self.rings.signal(ring_id, signal, Instant::now()) {524
self.finish_ring(ring_id, outcome, cx);625
self.finish_ring(ring_id, outcome, cx);@@ -547,7 +648,7 @@ impl AppState {547
648
548
pub fn accept_ringing_call(&mut self, cx: &mut Context<Self>) {649
pub fn accept_ringing_call(&mut self, cx: &mut Context<Self>) {549
if let Some(ring_id) = self.rings.first_ringing_id() {650
if let Some(ring_id) = self.rings.first_ringing_id() {550
self.accept_ring(ring_id, cx);651
self.accept_ring(ring_id, AcceptMode::Audio, cx);551
}652
}552
}653
}553
654
@@ -557,7 +658,7 @@ impl AppState {557
}658
}558
}659
}559
660
560
pub fn accept_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {661
pub fn accept_ring(&mut self, ring_id: u64, mode: AcceptMode, cx: &mut Context<Self>) {561
let Some(entry) = self.rings.get(ring_id).cloned() else {662
let Some(entry) = self.rings.get(ring_id).cloned() else {562
return;663
return;563
};664
};@@ -576,13 +677,16 @@ impl AppState {576
if entry.demo {677
if entry.demo {577
let handle = start_demo_call(DemoCall::Incoming(demo_caller()));678
let handle = start_demo_call(DemoCall::Incoming(demo_caller()));578
self.begin_call(handle, model, conversation_id, cx);679
self.begin_call(handle, model, conversation_id, cx);680
if mode == AcceptMode::Video {681
self.send_call_command(CallCommand::SetCamera(true));682
}579
return;683
return;580
}684
}581
let Some(launcher) = self.call_launcher.clone() else {685
let Some(launcher) = self.call_launcher.clone() else {582
self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);686
self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);583
return;687
return;584
};688
};585
let receiver = crate::runtime::spawn(async move { launcher.accept_ring(ring_id).await });689
let receiver = crate::runtime::spawn(async move { launcher.accept_ring(ring_id, mode).await });586
cx.spawn(async move |this, cx| {690
cx.spawn(async move |this, cx| {587
let handle = receiver.await.ok().flatten();691
let handle = receiver.await.ok().flatten();588
this.update(cx, |state, cx| match handle {692
this.update(cx, |state, cx| match handle {@@ -696,13 +800,19 @@ mod tests {696
use std::sync::Arc;800
use std::sync::Arc;697
use std::time::{Duration, Instant};801
use std::time::{Duration, Instant};698
802
699
use calling::{CallCommand, CallControl, CallState, CallUpdate, EndKind, EndReason, EngineEvent, Reaction, call_channel};803
use std::path::PathBuf;804
805
use calling::{BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel};700
use gpui_kit::{AppContext as _, Entity, TestAppContext};806
use gpui_kit::{AppContext as _, Entity, TestAppContext};701
use store::{ChatRecord, MemberRecord, Store};807
use store::{ChatRecord, MemberRecord, Store};702
808
703
use super::{ActiveCall, CallModel, CallPictures};809
use super::{ActiveCall, CallModel};704
use crate::app_state::{AppState, Mode, Selection};810
use crate::app_state::{AppState, Mode, Selection};811
use crate::call::TransferCandidate;812
use crate::call::background::BackgroundPick;705
use crate::call::demo::demo_ring;813
use crate::call::demo::demo_ring;814
use crate::call::features::room_closed_move;815
use crate::call::model::{BreakoutState, ConsultCall};706
use crate::data::Person;816
use crate::data::Person;707
817
708
fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {818
fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {@@ -712,17 +822,7 @@ mod tests {712
let (handle, _control) = call_channel();822
let (handle, _control) = call_channel();713
cx.update(|cx| {823
cx.update(|cx| {714
app.update(cx, |state, _| {824
app.update(cx, |state, _| {715
state.call = Some(ActiveCall {825
state.call = Some(ActiveCall::new(7, CallModel::test(), handle.commands, None, handle.video));716
id: 7,717
model: CallModel::test(),718
commands: handle.commands,719
viewing: true,720
conversation_id: None,721
video: handle.video,722
pictures: CallPictures::default(),723
stage_fullscreen: false,724
chat_open: false,725
});726
})826
})727
});827
});728
app828
app@@ -736,17 +836,7 @@ mod tests {736
let conversation_id = conversation_id.map(str::to_owned);836
let conversation_id = conversation_id.map(str::to_owned);737
cx.update(|cx| {837
cx.update(|cx| {738
app.update(cx, |state, _| {838
app.update(cx, |state, _| {739
state.call = Some(ActiveCall {839
state.call = Some(ActiveCall::new(7, model, handle.commands, conversation_id, handle.video));740
id: 7,741
model,742
commands: handle.commands,743
viewing: true,744
conversation_id,745
video: handle.video,746
pictures: CallPictures::default(),747
stage_fullscreen: false,748
chat_open: false,749
});750
})840
})751
});841
});752
(app, control)842
(app, control)@@ -897,15 +987,221 @@ mod tests {897
fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {987
fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {898
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);988
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);899
let store = cx.update(|cx| app.read(cx).store.clone());989
let store = cx.update(|cx| app.read(cx).store.clone());900
assert!(!cx.update(|cx| app.read(cx).call_background_blur));990
assert_eq!(cx.update(|cx| app.read(cx).call_background.clone()), BackgroundPick::None);901
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background_blur(true, cx)));991
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Blur, cx)));902
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBlur(true)));992
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::Blur)));903
assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.blur));993
assert_eq!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.background.clone()), BackgroundPick::Blur);904
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));994
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));905
assert!(cx.update(|cx| reopened.read(cx).call_background_blur));995
assert_eq!(cx.update(|cx| reopened.read(cx).call_background.clone()), BackgroundPick::Blur);906
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background_blur(false, cx)));996
let picture = PathBuf::from("/pictures/wall.jpg");997
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Custom(picture.clone()), cx)));998
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::Image(picture.clone()))));907
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));999
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));908
assert!(!cx.update(|cx| reopened.read(cx).call_background_blur));1000
assert_eq!(cx.update(|cx| reopened.read(cx).call_background.clone()), BackgroundPick::Custom(picture));1001
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::None, cx)));1002
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::None)));1003
}1004
1005
#[gpui_kit::test]1006
fn a_default_image_that_is_not_downloaded_yet_sends_nothing(cx: &mut TestAppContext) {1007
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1008
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Default("office_01".into()), cx)));1009
assert_eq!(control.try_recv_command(), None);1010
}1011
1012
#[gpui_kit::test]1013
fn only_the_organizer_starts_a_recording_and_the_notice_needs_a_consent_request(cx: &mut TestAppContext) {1014
let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);1015
cx.update(|cx| {1016
attendee.update(cx, |state, cx| {1017
state.set_call_recording(true, cx);1018
state.accept_recording_notice(cx);1019
})1020
});1021
assert_eq!(attendee_control.try_recv_command(), None);1022
let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);1023
cx.update(|cx| {1024
organizer.update(cx, |state, cx| {1025
state.set_call_recording(true, cx);1026
state.apply_call_update(7, CallUpdate::Recording(true), cx);1027
state.set_call_recording(false, cx);1028
state.accept_recording_notice(cx);1029
state.apply_call_update(7, CallUpdate::ConsentRequired(true), cx);1030
state.accept_recording_notice(cx);1031
})1032
});1033
assert_eq!(control.try_recv_command(), Some(CallCommand::SetRecording { on: true, title: "Standup".into() }));1034
assert_eq!(control.try_recv_command(), Some(CallCommand::SetRecording { on: false, title: "Standup".into() }));1035
assert_eq!(control.try_recv_command(), Some(CallCommand::ConsentToRecording));1036
assert_eq!(control.try_recv_command(), None);1037
}1038
1039
fn live_one_to_one() -> CallModel {1040
let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);1041
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1042
model1043
}1044
1045
#[gpui_kit::test]1046
fn hold_and_resume_alternate_and_stop_while_the_other_side_holds(cx: &mut TestAppContext) {1047
let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);1048
cx.update(|cx| {1049
app.update(cx, |state, cx| {1050
state.toggle_call_hold(cx);1051
state.apply_call_update(7, CallUpdate::Hold(HoldState::Local), cx);1052
state.toggle_call_hold(cx);1053
state.apply_call_update(7, CallUpdate::Hold(HoldState::Remote), cx);1054
state.toggle_call_hold(cx);1055
})1056
});1057
assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(true)));1058
assert_eq!(control.try_recv_command(), Some(CallCommand::Hold(false)));1059
assert_eq!(control.try_recv_command(), None);1060
let (meeting, mut meeting_control) = app_with_commands(cx, live_meeting(true), None);1061
cx.update(|cx| meeting.update(cx, |state, cx| state.toggle_call_hold(cx)));1062
assert_eq!(meeting_control.try_recv_command(), None);1063
}1064
1065
fn candidate(name: &str) -> TransferCandidate {1066
TransferCandidate { mri: format!("8:orgid:{name}"), name: name.into(), user_id: Some(name.into()), chat_id: format!("19:{name}") }1067
}1068
1069
#[gpui_kit::test]1070
fn a_blind_transfer_names_the_target_and_a_consulted_one_carries_the_replacement_link(cx: &mut TestAppContext) {1071
let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);1072
cx.update(|cx| app.update(cx, |state, cx| state.transfer_call_blind(candidate("ana"), cx)));1073
assert_eq!(1074
control.try_recv_command(),1075
Some(CallCommand::Transfer { target: calling::Callee { mri: "8:orgid:ana".into(), display_name: "ana".into() }, replaces: None })1076
);1077
let (consulting, mut consult_control) = app_with_commands(cx, live_one_to_one(), None);1078
let (consult_handle, _consult_updates) = call_channel();1079
cx.update(|cx| {1080
consulting.update(cx, |state, cx| {1081
state.call.as_mut().unwrap().consult = Some(ConsultCall {1082
id: 8,1083
target: ("8:orgid:ana".into(), "Ana".into()),1084
commands: consult_handle.commands,1085
state: CallState::Connecting,1086
replacement: Some("https://cc.skype.com/replacement".into()),1087
transferring: false,1088
});1089
state.transfer_consulted(cx);1090
state.call.as_mut().unwrap().consult.as_mut().unwrap().state = CallState::Connected { since: Instant::now() };1091
state.transfer_consulted(cx);1092
})1093
});1094
assert_eq!(1095
consult_control.try_recv_command(),1096
Some(CallCommand::Transfer {1097
target: calling::Callee { mri: "8:orgid:ana".into(), display_name: "Ana".into() },1098
replaces: Some("https://cc.skype.com/replacement".into()),1099
})1100
);1101
assert_eq!(consult_control.try_recv_command(), None);1102
}1103
1104
#[gpui_kit::test]1105
fn the_transfer_list_holds_one_to_one_chats_without_the_person_on_the_call(cx: &mut TestAppContext) {1106
let app = app_with_chats(cx);1107
cx.update(|cx| {1108
app.update(cx, |state, cx| {1109
let names: Vec<String> = state.transfer_candidates().into_iter().map(|candidate| candidate.name).collect();1110
assert_eq!(names, vec!["Bea".to_owned()]);1111
let (handle, _control) = call_channel();1112
let mut on_the_call = CallModel::people("Bea", &[("8:orgid:bea-id".into(), "Bea".into())]);1113
on_the_call.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1114
state.call = Some(ActiveCall::new(9, on_the_call, handle.commands, None, handle.video));1115
assert!(state.transfer_candidates().is_empty());1116
cx.notify();1117
})1118
});1119
}1120
1121
fn room_move(returning: bool) -> calling::BreakoutMove {1122
calling::BreakoutMove {1123
room_name: "Room 1".into(),1124
target: calling::MeetingTarget { thread_id: "19:meeting_room@thread.v2".into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None },1125
returning,1126
}1127
}1128
1129
fn main_target() -> calling::MeetingTarget {1130
calling::MeetingTarget { thread_id: "19:meeting_main@thread.v2".into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None }1131
}1132
1133
#[gpui_kit::test]1134
fn being_moved_to_a_room_leaves_the_call_and_remembers_the_way_back(cx: &mut TestAppContext) {1135
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1136
cx.update(|cx| {1137
app.update(cx, |state, cx| {1138
state.call.as_mut().unwrap().meeting_target = Some(main_target());1139
state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);1140
let pending = state.call.as_ref().unwrap().pending_move.clone().expect("a move is pending");1141
assert_eq!(pending.target.thread_id, "19:meeting_room@thread.v2");1142
assert_eq!(pending.title, "Room 1");1143
let room = pending.breakout.expect("a room");1144
assert_eq!(room.main, Some(main_target()));1145
assert_eq!(room.main_title, "Standup");1146
assert_eq!(state.notice.as_ref().map(|notice| notice.text.as_str()), Some("Moving you to Room 1"));1147
state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);1148
})1149
});1150
assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));1151
assert_eq!(control.try_recv_command(), None);1152
}1153
1154
#[gpui_kit::test]1155
fn the_return_button_and_a_closed_room_both_lead_back_to_the_main_meeting(cx: &mut TestAppContext) {1156
let mut room = live_meeting(false);1157
room.breakout = Some(BreakoutState { room_name: "Room 1".into(), main: Some(main_target()), main_title: "Standup".into() });1158
let (app, mut control) = app_with_commands(cx, room.clone(), None);1159
cx.update(|cx| {1160
app.update(cx, |state, cx| {1161
state.return_to_main_meeting(cx);1162
let pending = state.call.as_ref().unwrap().pending_move.clone().expect("a move is pending");1163
assert_eq!(pending.target, main_target());1164
assert_eq!(pending.title, "Standup");1165
assert!(pending.breakout.is_none());1166
})1167
});1168
assert_eq!(control.try_recv_command(), Some(CallCommand::Hangup));1169
let (closed, _control) = app_with_commands(cx, room, None);1170
cx.update(|cx| {1171
closed.update(cx, |state, _| {1172
let call = state.call.as_ref().unwrap();1173
let moved = room_closed_move(call, &EndReason::Remote(EndKind::RoomClosed)).expect("goes back");1174
assert_eq!(moved.target, main_target());1175
assert!(room_closed_move(call, &EndReason::Remote(EndKind::Normal)).is_none());1176
assert!(room_closed_move(call, &EndReason::LocalHangup).is_none());1177
})1178
});1179
let (plain, _control) = app_with_commands(cx, live_meeting(false), None);1180
cx.update(|cx| plain.update(cx, |state, _| assert!(room_closed_move(state.call.as_ref().unwrap(), &EndReason::Remote(EndKind::RoomClosed)).is_none())));1181
}1182
1183
#[gpui_kit::test]1184
fn the_whiteboard_menu_asks_for_the_board_unless_someone_already_shares_one(cx: &mut TestAppContext) {1185
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1186
cx.update(|cx| {1187
app.update(cx, |state, cx| {1188
state.open_call_whiteboard(cx);1189
state.apply_call_update(1190
7,1191
CallUpdate::Whiteboard(Some(calling::ContentShare {1192
session_id: "s".into(),1193
presenter: Some("8:orgid:ana".into()),1194
subject: "Whiteboard".into(),1195
url: Some("https://app.whiteboard.microsoft.com/x".into()),1196
whiteboard: true,1197
})),1198
cx,1199
);1200
state.open_call_whiteboard(cx);1201
})1202
});1203
assert_eq!(control.try_recv_command(), Some(CallCommand::OpenWhiteboard { title: "Standup".into() }));1204
assert_eq!(control.try_recv_command(), None);909
}1205
}910
1206
911
#[gpui_kit::test]1207
#[gpui_kit::test]@@ -0,0 +1,236 @@
1
use std::path::{Path, PathBuf};
2
3
use calling::{BackgroundCache, BackgroundChoice, DefaultBackground};
4
5
pub const BACKGROUND_META_KEY: &str = "call_background";
6
pub const CUSTOM_BACKGROUNDS_META_KEY: &str = "call_background_custom";
7
pub const SHOWN_IMAGES: usize = 12;
8
const DEFAULT_PREFIX: &str = "default:";
9
const FILE_PREFIX: &str = "file:";
10
const CACHE_DIR: &str = "call-backgrounds";
11
const MAX_CUSTOM: usize = 6;
12
13
#[derive(Debug, Clone, PartialEq, Eq, Default)]
14
pub enum BackgroundPick {
15
#[default]
16
None,
17
Blur,
18
Default(String),
19
Custom(PathBuf),
20
}
21
22
impl BackgroundPick {
23
pub fn to_meta(&self) -> String {
24
match self {
25
BackgroundPick::None => "none".to_owned(),
26
BackgroundPick::Blur => "blur".to_owned(),
27
BackgroundPick::Default(id) => format!("{DEFAULT_PREFIX}{id}"),
28
BackgroundPick::Custom(path) => format!("{FILE_PREFIX}{}", path.display()),
29
}
30
}
31
32
pub fn from_meta(value: &str) -> Self {
33
match value {
34
"blur" | "1" => BackgroundPick::Blur,
35
other => match (other.strip_prefix(DEFAULT_PREFIX), other.strip_prefix(FILE_PREFIX)) {
36
(Some(id), _) if !id.is_empty() => BackgroundPick::Default(id.to_owned()),
37
(_, Some(path)) if !path.is_empty() => BackgroundPick::Custom(PathBuf::from(path)),
38
_ => BackgroundPick::None,
39
},
40
}
41
}
42
43
pub fn is_blur(&self) -> bool {
44
*self == BackgroundPick::Blur
45
}
46
}
47
48
pub fn load_background(store: &store::Store) -> BackgroundPick {
49
store.meta(BACKGROUND_META_KEY).ok().flatten().or_else(|| store.meta("call_background_blur").ok().flatten()).map_or(BackgroundPick::None, |value| BackgroundPick::from_meta(&value))
50
}
51
52
pub fn load_custom_backgrounds(store: &store::Store) -> Vec<PathBuf> {
53
store
54
.meta(CUSTOM_BACKGROUNDS_META_KEY)
55
.ok()
56
.flatten()
57
.map(|value| value.lines().filter(|line| !line.is_empty()).map(PathBuf::from).collect())
58
.unwrap_or_default()
59
}
60
61
pub fn save_custom_backgrounds(store: &store::Store, customs: &[PathBuf]) {
62
let joined: Vec<String> = customs.iter().map(|path| path.display().to_string()).collect();
63
let _ = store.set_meta(CUSTOM_BACKGROUNDS_META_KEY, &joined.join("\n"));
64
}
65
66
pub fn default_cache_directory() -> PathBuf {
67
directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
68
.map(|directories| directories.data_local_dir().join(CACHE_DIR))
69
.unwrap_or_else(|| PathBuf::from(CACHE_DIR))
70
}
71
72
pub struct BackgroundLibrary {
73
pub cache: BackgroundCache,
74
pub images: Vec<DefaultBackground>,
75
pub customs: Vec<PathBuf>,
76
pub refreshing: bool,
77
}
78
79
impl BackgroundLibrary {
80
pub fn new(directory: PathBuf) -> Self {
81
let cache = BackgroundCache::new(directory);
82
let images = cache.cached_catalog();
83
BackgroundLibrary { cache, images, customs: Vec::new(), refreshing: false }
84
}
85
86
pub fn shown(&self) -> &[DefaultBackground] {
87
&self.images[..self.images.len().min(SHOWN_IMAGES)]
88
}
89
90
pub fn thumbnail(&self, image: &DefaultBackground) -> Option<PathBuf> {
91
Some(self.cache.thumbnail_path(image)).filter(|path| path.exists())
92
}
93
94
pub fn cached_image(&self, id: &str) -> Option<PathBuf> {
95
let image = self.images.iter().find(|image| image.id == id)?;
96
Some(self.cache.image_path(image)).filter(|path| path.exists())
97
}
98
99
pub fn find(&self, id: &str) -> Option<&DefaultBackground> {
100
self.images.iter().find(|image| image.id == id)
101
}
102
103
pub fn add_custom(&mut self, path: PathBuf) {
104
self.customs.retain(|known| *known != path);
105
self.customs.insert(0, path);
106
self.customs.truncate(MAX_CUSTOM);
107
}
108
109
pub fn needs_refresh(&self) -> bool {
110
!self.refreshing && (self.images.is_empty() || self.shown().iter().any(|image| self.thumbnail(image).is_none()))
111
}
112
113
pub fn choice_for(&self, pick: &BackgroundPick) -> Option<BackgroundChoice> {
114
match pick {
115
BackgroundPick::None => Some(BackgroundChoice::None),
116
BackgroundPick::Blur => Some(BackgroundChoice::Blur),
117
BackgroundPick::Custom(path) => Some(BackgroundChoice::Image(path.clone())),
118
BackgroundPick::Default(id) => self.cached_image(id).map(BackgroundChoice::Image),
119
}
120
}
121
}
122
123
const DEMO_NAMES: [&str; SHOWN_IMAGES] = [
124
"Office", "Loft", "Library", "Beach", "Forest", "Sunset", "Studio", "Garden", "Cafe", "Mountains", "Cabin", "City",
125
];
126
const DEMO_THUMBNAIL: (u32, u32) = (96, 54);
127
const DEMO_IMAGE: (u32, u32) = (640, 360);
128
129
fn demo_gradient(index: usize, (width, height): (u32, u32)) -> image::RgbaImage {
130
let hue = index as f32 / SHOWN_IMAGES as f32;
131
let channel = |offset: f32, row: f32| (((hue + offset).fract() * 0.55 + 0.25 + row * 0.2) * 255.).min(255.) as u8;
132
image::RgbaImage::from_fn(width, height, |_, row| {
133
let row = row as f32 / height as f32;
134
image::Rgba([channel(0., row), channel(0.33, row), channel(0.66, 1. - row), 255])
135
})
136
}
137
138
pub fn demo_library() -> BackgroundLibrary {
139
let directory = std::env::temp_dir().join(format!("teams-demo-backgrounds-{}", std::process::id()));
140
let mut library = BackgroundLibrary::new(directory);
141
library.images = DEMO_NAMES
142
.iter()
143
.enumerate()
144
.map(|(index, name)| DefaultBackground {
145
id: format!("demo_{index}"),
146
name: (*name).to_owned(),
147
image_url: format!("https://demo.invalid/images/demo_{index}.png"),
148
thumbnail_url: format!("https://demo.invalid/thumbnails/demo_{index}.png"),
149
})
150
.collect();
151
for (index, image) in library.images.iter().enumerate() {
152
for (path, size) in [(library.cache.thumbnail_path(image), DEMO_THUMBNAIL), (library.cache.image_path(image), DEMO_IMAGE)] {
153
if let Some(parent) = path.parent() {
154
let _ = std::fs::create_dir_all(parent);
155
}
156
let _ = demo_gradient(index, size).save(path);
157
}
158
}
159
library
160
}
161
162
pub fn is_image_file(path: &Path) -> bool {
163
path.extension()
164
.and_then(|extension| extension.to_str())
165
.is_some_and(|extension| ["jpg", "jpeg", "png"].iter().any(|known| extension.eq_ignore_ascii_case(known)))
166
}
167
168
#[cfg(test)]
169
mod tests {
170
use super::*;
171
172
#[test]
173
fn a_choice_survives_the_round_trip_through_the_store_value() {
174
for pick in [
175
BackgroundPick::None,
176
BackgroundPick::Blur,
177
BackgroundPick::Default("office_01".into()),
178
BackgroundPick::Custom(PathBuf::from("/home/me/pictures/wall.jpg")),
179
] {
180
assert_eq!(BackgroundPick::from_meta(&pick.to_meta()), pick);
181
}
182
}
183
184
#[test]
185
fn the_old_blur_switch_and_unknown_values_still_read() {
186
assert_eq!(BackgroundPick::from_meta("1"), BackgroundPick::Blur);
187
assert_eq!(BackgroundPick::from_meta("0"), BackgroundPick::None);
188
assert_eq!(BackgroundPick::from_meta("default:"), BackgroundPick::None);
189
assert_eq!(BackgroundPick::from_meta("nonsense"), BackgroundPick::None);
190
}
191
192
#[test]
193
fn the_store_keeps_the_choice_and_the_own_images() {
194
let store = store::Store::open_in_memory().unwrap();
195
assert_eq!(load_background(&store), BackgroundPick::None);
196
store.set_meta(BACKGROUND_META_KEY, &BackgroundPick::Default("beach".into()).to_meta()).unwrap();
197
assert_eq!(load_background(&store), BackgroundPick::Default("beach".into()));
198
save_custom_backgrounds(&store, &[PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]);
199
assert_eq!(load_custom_backgrounds(&store), vec![PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]);
200
}
201
202
#[test]
203
fn the_legacy_blur_key_is_read_until_a_new_choice_is_saved() {
204
let store = store::Store::open_in_memory().unwrap();
205
store.set_meta("call_background_blur", "1").unwrap();
206
assert_eq!(load_background(&store), BackgroundPick::Blur);
207
}
208
209
#[test]
210
fn own_images_come_first_without_duplicates_and_stay_few() {
211
let mut library = BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));
212
for index in 0..8 {
213
library.add_custom(PathBuf::from(format!("/pictures/{index}.png")));
214
}
215
library.add_custom(PathBuf::from("/pictures/3.png"));
216
assert_eq!(library.customs.len(), MAX_CUSTOM);
217
assert_eq!(library.customs[0], PathBuf::from("/pictures/3.png"));
218
assert_eq!(library.customs.iter().filter(|path| path.as_path() == Path::new("/pictures/3.png")).count(), 1);
219
}
220
221
#[test]
222
fn a_default_image_is_only_usable_once_it_is_cached() {
223
let library = BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));
224
assert_eq!(library.choice_for(&BackgroundPick::Default("office_01".into())), None);
225
assert_eq!(library.choice_for(&BackgroundPick::Blur), Some(BackgroundChoice::Blur));
226
assert!(library.needs_refresh());
227
}
228
229
#[test]
230
fn only_pictures_are_accepted_as_own_backgrounds() {
231
assert!(is_image_file(Path::new("/a/b.JPG")));
232
assert!(is_image_file(Path::new("c.png")));
233
assert!(!is_image_file(Path::new("d.gif")));
234
assert!(!is_image_file(Path::new("noextension")));
235
}
236
}
@@ -0,0 +1,236 @@1
use std::path::{Path, PathBuf};2
3
use calling::{BackgroundCache, BackgroundChoice, DefaultBackground};4
5
pub const BACKGROUND_META_KEY: &str = "call_background";6
pub const CUSTOM_BACKGROUNDS_META_KEY: &str = "call_background_custom";7
pub const SHOWN_IMAGES: usize = 12;8
const DEFAULT_PREFIX: &str = "default:";9
const FILE_PREFIX: &str = "file:";10
const CACHE_DIR: &str = "call-backgrounds";11
const MAX_CUSTOM: usize = 6;12
13
#[derive(Debug, Clone, PartialEq, Eq, Default)]14
pub enum BackgroundPick {15
#[default]16
None,17
Blur,18
Default(String),19
Custom(PathBuf),20
}21
22
impl BackgroundPick {23
pub fn to_meta(&self) -> String {24
match self {25
BackgroundPick::None => "none".to_owned(),26
BackgroundPick::Blur => "blur".to_owned(),27
BackgroundPick::Default(id) => format!("{DEFAULT_PREFIX}{id}"),28
BackgroundPick::Custom(path) => format!("{FILE_PREFIX}{}", path.display()),29
}30
}31
32
pub fn from_meta(value: &str) -> Self {33
match value {34
"blur" | "1" => BackgroundPick::Blur,35
other => match (other.strip_prefix(DEFAULT_PREFIX), other.strip_prefix(FILE_PREFIX)) {36
(Some(id), _) if !id.is_empty() => BackgroundPick::Default(id.to_owned()),37
(_, Some(path)) if !path.is_empty() => BackgroundPick::Custom(PathBuf::from(path)),38
_ => BackgroundPick::None,39
},40
}41
}42
43
pub fn is_blur(&self) -> bool {44
*self == BackgroundPick::Blur45
}46
}47
48
pub fn load_background(store: &store::Store) -> BackgroundPick {49
store.meta(BACKGROUND_META_KEY).ok().flatten().or_else(|| store.meta("call_background_blur").ok().flatten()).map_or(BackgroundPick::None, |value| BackgroundPick::from_meta(&value))50
}51
52
pub fn load_custom_backgrounds(store: &store::Store) -> Vec<PathBuf> {53
store54
.meta(CUSTOM_BACKGROUNDS_META_KEY)55
.ok()56
.flatten()57
.map(|value| value.lines().filter(|line| !line.is_empty()).map(PathBuf::from).collect())58
.unwrap_or_default()59
}60
61
pub fn save_custom_backgrounds(store: &store::Store, customs: &[PathBuf]) {62
let joined: Vec<String> = customs.iter().map(|path| path.display().to_string()).collect();63
let _ = store.set_meta(CUSTOM_BACKGROUNDS_META_KEY, &joined.join("\n"));64
}65
66
pub fn default_cache_directory() -> PathBuf {67
directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)68
.map(|directories| directories.data_local_dir().join(CACHE_DIR))69
.unwrap_or_else(|| PathBuf::from(CACHE_DIR))70
}71
72
pub struct BackgroundLibrary {73
pub cache: BackgroundCache,74
pub images: Vec<DefaultBackground>,75
pub customs: Vec<PathBuf>,76
pub refreshing: bool,77
}78
79
impl BackgroundLibrary {80
pub fn new(directory: PathBuf) -> Self {81
let cache = BackgroundCache::new(directory);82
let images = cache.cached_catalog();83
BackgroundLibrary { cache, images, customs: Vec::new(), refreshing: false }84
}85
86
pub fn shown(&self) -> &[DefaultBackground] {87
&self.images[..self.images.len().min(SHOWN_IMAGES)]88
}89
90
pub fn thumbnail(&self, image: &DefaultBackground) -> Option<PathBuf> {91
Some(self.cache.thumbnail_path(image)).filter(|path| path.exists())92
}93
94
pub fn cached_image(&self, id: &str) -> Option<PathBuf> {95
let image = self.images.iter().find(|image| image.id == id)?;96
Some(self.cache.image_path(image)).filter(|path| path.exists())97
}98
99
pub fn find(&self, id: &str) -> Option<&DefaultBackground> {100
self.images.iter().find(|image| image.id == id)101
}102
103
pub fn add_custom(&mut self, path: PathBuf) {104
self.customs.retain(|known| *known != path);105
self.customs.insert(0, path);106
self.customs.truncate(MAX_CUSTOM);107
}108
109
pub fn needs_refresh(&self) -> bool {110
!self.refreshing && (self.images.is_empty() || self.shown().iter().any(|image| self.thumbnail(image).is_none()))111
}112
113
pub fn choice_for(&self, pick: &BackgroundPick) -> Option<BackgroundChoice> {114
match pick {115
BackgroundPick::None => Some(BackgroundChoice::None),116
BackgroundPick::Blur => Some(BackgroundChoice::Blur),117
BackgroundPick::Custom(path) => Some(BackgroundChoice::Image(path.clone())),118
BackgroundPick::Default(id) => self.cached_image(id).map(BackgroundChoice::Image),119
}120
}121
}122
123
const DEMO_NAMES: [&str; SHOWN_IMAGES] = [124
"Office", "Loft", "Library", "Beach", "Forest", "Sunset", "Studio", "Garden", "Cafe", "Mountains", "Cabin", "City",125
];126
const DEMO_THUMBNAIL: (u32, u32) = (96, 54);127
const DEMO_IMAGE: (u32, u32) = (640, 360);128
129
fn demo_gradient(index: usize, (width, height): (u32, u32)) -> image::RgbaImage {130
let hue = index as f32 / SHOWN_IMAGES as f32;131
let channel = |offset: f32, row: f32| (((hue + offset).fract() * 0.55 + 0.25 + row * 0.2) * 255.).min(255.) as u8;132
image::RgbaImage::from_fn(width, height, |_, row| {133
let row = row as f32 / height as f32;134
image::Rgba([channel(0., row), channel(0.33, row), channel(0.66, 1. - row), 255])135
})136
}137
138
pub fn demo_library() -> BackgroundLibrary {139
let directory = std::env::temp_dir().join(format!("teams-demo-backgrounds-{}", std::process::id()));140
let mut library = BackgroundLibrary::new(directory);141
library.images = DEMO_NAMES142
.iter()143
.enumerate()144
.map(|(index, name)| DefaultBackground {145
id: format!("demo_{index}"),146
name: (*name).to_owned(),147
image_url: format!("https://demo.invalid/images/demo_{index}.png"),148
thumbnail_url: format!("https://demo.invalid/thumbnails/demo_{index}.png"),149
})150
.collect();151
for (index, image) in library.images.iter().enumerate() {152
for (path, size) in [(library.cache.thumbnail_path(image), DEMO_THUMBNAIL), (library.cache.image_path(image), DEMO_IMAGE)] {153
if let Some(parent) = path.parent() {154
let _ = std::fs::create_dir_all(parent);155
}156
let _ = demo_gradient(index, size).save(path);157
}158
}159
library160
}161
162
pub fn is_image_file(path: &Path) -> bool {163
path.extension()164
.and_then(|extension| extension.to_str())165
.is_some_and(|extension| ["jpg", "jpeg", "png"].iter().any(|known| extension.eq_ignore_ascii_case(known)))166
}167
168
#[cfg(test)]169
mod tests {170
use super::*;171
172
#[test]173
fn a_choice_survives_the_round_trip_through_the_store_value() {174
for pick in [175
BackgroundPick::None,176
BackgroundPick::Blur,177
BackgroundPick::Default("office_01".into()),178
BackgroundPick::Custom(PathBuf::from("/home/me/pictures/wall.jpg")),179
] {180
assert_eq!(BackgroundPick::from_meta(&pick.to_meta()), pick);181
}182
}183
184
#[test]185
fn the_old_blur_switch_and_unknown_values_still_read() {186
assert_eq!(BackgroundPick::from_meta("1"), BackgroundPick::Blur);187
assert_eq!(BackgroundPick::from_meta("0"), BackgroundPick::None);188
assert_eq!(BackgroundPick::from_meta("default:"), BackgroundPick::None);189
assert_eq!(BackgroundPick::from_meta("nonsense"), BackgroundPick::None);190
}191
192
#[test]193
fn the_store_keeps_the_choice_and_the_own_images() {194
let store = store::Store::open_in_memory().unwrap();195
assert_eq!(load_background(&store), BackgroundPick::None);196
store.set_meta(BACKGROUND_META_KEY, &BackgroundPick::Default("beach".into()).to_meta()).unwrap();197
assert_eq!(load_background(&store), BackgroundPick::Default("beach".into()));198
save_custom_backgrounds(&store, &[PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]);199
assert_eq!(load_custom_backgrounds(&store), vec![PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]);200
}201
202
#[test]203
fn the_legacy_blur_key_is_read_until_a_new_choice_is_saved() {204
let store = store::Store::open_in_memory().unwrap();205
store.set_meta("call_background_blur", "1").unwrap();206
assert_eq!(load_background(&store), BackgroundPick::Blur);207
}208
209
#[test]210
fn own_images_come_first_without_duplicates_and_stay_few() {211
let mut library = BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));212
for index in 0..8 {213
library.add_custom(PathBuf::from(format!("/pictures/{index}.png")));214
}215
library.add_custom(PathBuf::from("/pictures/3.png"));216
assert_eq!(library.customs.len(), MAX_CUSTOM);217
assert_eq!(library.customs[0], PathBuf::from("/pictures/3.png"));218
assert_eq!(library.customs.iter().filter(|path| path.as_path() == Path::new("/pictures/3.png")).count(), 1);219
}220
221
#[test]222
fn a_default_image_is_only_usable_once_it_is_cached() {223
let library = BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));224
assert_eq!(library.choice_for(&BackgroundPick::Default("office_01".into())), None);225
assert_eq!(library.choice_for(&BackgroundPick::Blur), Some(BackgroundChoice::Blur));226
assert!(library.needs_refresh());227
}228
229
#[test]230
fn only_pictures_are_accepted_as_own_backgrounds() {231
assert!(is_image_file(Path::new("/a/b.JPG")));232
assert!(is_image_file(Path::new("c.png")));233
assert!(!is_image_file(Path::new("d.gif")));234
assert!(!is_image_file(Path::new("noextension")));235
}236
}@@ -3,8 +3,9 @@ use std::time::{Duration, Instant};
3
3
use calling::video_frame::bgra_from_i420;
4
4
use calling::video_pattern::{PatternKind, pattern_frame};
5
5
use calling::{
6
AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, CaptionEntry, CaptionState, DeviceChoice, DeviceLists,
7
EndReason, IncomingRing, Progress, PublishedState, RaisedHand, Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,
6
AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, CaptionEntry, CaptionState,
7
ContentShare, DeviceChoice, DeviceLists, EndReason, HoldState, IncomingRing, MeetingTarget, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,
8
ShareKind, ShareSource, VideoKey, call_channel,
8
9
};
9
10
use calling::CameraDevice;
10
11
@@ -61,6 +62,44 @@ const DEMO_GUESTS: [&str; 11] = [
61
62
62
63
pub type Person = (String, String);
63
64
65
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
66
pub enum DemoScene {
67
#[default]
68
Plain,
69
Call,
70
Recording,
71
Consent,
72
Hold,
73
Held,
74
Breakout,
75
Whiteboard,
76
}
77
78
impl DemoScene {
79
pub fn from_name(name: &str) -> Option<Self> {
80
Some(match name.trim() {
81
"call" => DemoScene::Call,
82
"recording" => DemoScene::Recording,
83
"consent" => DemoScene::Consent,
84
"hold" => DemoScene::Hold,
85
"held" => DemoScene::Held,
86
"breakout" => DemoScene::Breakout,
87
"whiteboard" => DemoScene::Whiteboard,
88
_ => return None,
89
})
90
}
91
92
pub fn is_one_to_one(self) -> bool {
93
matches!(self, DemoScene::Call | DemoScene::Hold | DemoScene::Held)
94
}
95
}
96
97
const BREAKOUT_AT_TICKS: u32 = 20;
98
const WHITEBOARD_AT_TICKS: u32 = 5;
99
const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
100
const DEMO_REPLACEMENT_LINK: &str = "https://demo.invalid/replacement";
101
const DEMO_ROOM_THREAD: &str = "19:meeting_demo-room-1@thread.v2";
102
64
103
pub enum DemoCall {
65
104
Test,
66
105
People(Vec<Person>),
@@ -81,6 +120,10 @@ pub fn demo_caller() -> Person {
81
120
(DEMO_CALLER.0.to_owned(), DEMO_CALLER.1.to_owned())
82
121
}
83
122
123
pub fn demo_video_ring() -> IncomingRing {
124
IncomingRing { video: true, ..demo_ring() }
125
}
126
84
127
pub fn demo_ring() -> IncomingRing {
85
128
let (mri, display_name) = demo_caller();
86
129
IncomingRing {
@@ -126,8 +169,12 @@ fn demo_devices() -> DeviceLists {
126
169
}
127
170
128
171
pub fn start_demo_call(script: DemoCall) -> CallHandle {
172
start_demo_scene_call(script, DemoScene::Plain)
173
}
174
175
pub fn start_demo_scene_call(script: DemoCall, scene: DemoScene) -> CallHandle {
129
176
let (handle, control) = call_channel();
130
crate::runtime::handle().spawn(run_demo_call(control, script));
177
crate::runtime::handle().spawn(run_demo_call(control, script, scene));
131
178
handle
132
179
}
133
180
@@ -149,7 +196,7 @@ fn roster_of(people: &[Person]) -> Vec<RosterEntry> {
149
196
.collect()
150
197
}
151
198
152
async fn run_demo_call(mut control: CallControl, script: DemoCall) {
199
async fn run_demo_call(mut control: CallControl, script: DemoCall, scene: DemoScene) {
153
200
control.send(CallUpdate::OwnIdentity {
154
201
mri: DEMO_OWN_MRI.to_owned(),
155
202
});
@@ -185,6 +232,9 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall) {
185
232
control.send(CallUpdate::Lobby(false));
186
233
}
187
234
let mut roster = roster_of(&people);
235
if matches!(script, DemoCall::People(_)) {
236
control.send(CallUpdate::ReplacementLink(DEMO_REPLACEMENT_LINK.to_owned()));
237
}
188
238
if matches!(script, DemoCall::Meeting { organizer: true, .. }) {
189
239
roster.push(demo_organizer());
190
240
roster.extend(DEMO_WAITING.iter().enumerate().map(|(index, name)| demo_waiting(index, name)));
@@ -199,7 +249,8 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall) {
199
249
control.send(CallUpdate::Roster(roster.clone()));
200
250
let video = !matches!(script, DemoCall::Test);
201
251
let sharer = matches!(script, DemoCall::Meeting { .. }).then(|| people.get(1).map(|person| person.0.clone())).flatten();
202
speak_until_hangup(control, people, roster, video, sharer).await;
252
start_scene(&control, scene);
253
speak_until_hangup(control, people, roster, video, sharer, scene).await;
203
254
}
204
255
205
256
async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bool {
@@ -235,7 +286,38 @@ fn publish_demo_video(control: &CallControl, people: &[Person], tick: u32, shari
235
286
}
236
287
}
237
288
238
async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut roster: Vec<RosterEntry>, video: bool, sharer: Option<String>) {
289
fn start_scene(control: &CallControl, scene: DemoScene) {
290
match scene {
291
DemoScene::Recording => control.send(CallUpdate::Recording(true)),
292
DemoScene::Consent => {
293
control.send(CallUpdate::Recording(true));
294
control.send(CallUpdate::ConsentRequired(true));
295
}
296
DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),
297
DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),
298
DemoScene::Call | DemoScene::Breakout | DemoScene::Whiteboard | DemoScene::Plain => {}
299
}
300
}
301
302
fn scene_tick(control: &CallControl, scene: DemoScene, ticks: u32, people: &[Person]) {
303
match scene {
304
DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => control.send(CallUpdate::BreakoutMove(BreakoutMove {
305
room_name: "Room 1".to_owned(),
306
target: MeetingTarget { thread_id: DEMO_ROOM_THREAD.to_owned(), tenant_id: "demo-tenant".to_owned(), organizer_id: "demo-me".to_owned(), meeting_data: None },
307
returning: false,
308
})),
309
DemoScene::Whiteboard if ticks == WHITEBOARD_AT_TICKS => control.send(CallUpdate::Whiteboard(Some(ContentShare {
310
session_id: "demo-whiteboard".to_owned(),
311
presenter: people.first().map(|person| person.0.clone()),
312
subject: "Whiteboard".to_owned(),
313
url: Some(DEMO_BOARD_URL.to_owned()),
314
whiteboard: true,
315
}))),
316
_ => {}
317
}
318
}
319
320
async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut roster: Vec<RosterEntry>, video: bool, sharer: Option<String>, scene: DemoScene) {
239
321
let started = Instant::now();
240
322
let mut video_ticks = 0u32;
241
323
let mut sharing = false;
@@ -285,6 +367,7 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r
285
367
}
286
368
caption_ticks += 1;
287
369
}
370
scene_tick(&control, scene, ticks, &people);
288
371
ticks += 1;
289
372
}
290
373
command = control.recv() => match command {
@@ -365,7 +448,16 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r
365
448
caption_ticks = 0;
366
449
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));
367
450
}
368
Some(CallCommand::SetBlur(on)) => blur = on,
451
Some(CallCommand::SetBackground(choice)) => blur = choice != BackgroundChoice::None,
452
Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),
453
Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
454
Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
455
Some(CallCommand::Transfer { .. }) => {
456
control.send(CallUpdate::Notice("Call transferred".to_owned()));
457
end(&control, EndReason::LocalHangup);
458
return;
459
}
460
Some(CallCommand::OpenWhiteboard { .. }) => control.send(CallUpdate::WhiteboardUrl(DEMO_BOARD_URL.to_owned())),
369
461
Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),
370
462
Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {
371
463
end(&control, EndReason::LocalHangup);
@@ -3,8 +3,9 @@ use std::time::{Duration, Instant};3
use calling::video_frame::bgra_from_i420;3
use calling::video_frame::bgra_from_i420;4
use calling::video_pattern::{PatternKind, pattern_frame};4
use calling::video_pattern::{PatternKind, pattern_frame};5
use calling::{5
use calling::{6
AudioDevice, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, CaptionEntry, CaptionState, DeviceChoice, DeviceLists,6
AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, CaptionEntry, CaptionState,7
EndReason, IncomingRing, Progress, PublishedState, RaisedHand, Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,7
ContentShare, DeviceChoice, DeviceLists, EndReason, HoldState, IncomingRing, MeetingTarget, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,8
ShareKind, ShareSource, VideoKey, call_channel,8
};9
};9
use calling::CameraDevice;10
use calling::CameraDevice;10
11
@@ -61,6 +62,44 @@ const DEMO_GUESTS: [&str; 11] = [61
62
62
pub type Person = (String, String);63
pub type Person = (String, String);63
64
65
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]66
pub enum DemoScene {67
#[default]68
Plain,69
Call,70
Recording,71
Consent,72
Hold,73
Held,74
Breakout,75
Whiteboard,76
}77
78
impl DemoScene {79
pub fn from_name(name: &str) -> Option<Self> {80
Some(match name.trim() {81
"call" => DemoScene::Call,82
"recording" => DemoScene::Recording,83
"consent" => DemoScene::Consent,84
"hold" => DemoScene::Hold,85
"held" => DemoScene::Held,86
"breakout" => DemoScene::Breakout,87
"whiteboard" => DemoScene::Whiteboard,88
_ => return None,89
})90
}91
92
pub fn is_one_to_one(self) -> bool {93
matches!(self, DemoScene::Call | DemoScene::Hold | DemoScene::Held)94
}95
}96
97
const BREAKOUT_AT_TICKS: u32 = 20;98
const WHITEBOARD_AT_TICKS: u32 = 5;99
const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";100
const DEMO_REPLACEMENT_LINK: &str = "https://demo.invalid/replacement";101
const DEMO_ROOM_THREAD: &str = "19:meeting_demo-room-1@thread.v2";102
64
pub enum DemoCall {103
pub enum DemoCall {65
Test,104
Test,66
People(Vec<Person>),105
People(Vec<Person>),@@ -81,6 +120,10 @@ pub fn demo_caller() -> Person {81
(DEMO_CALLER.0.to_owned(), DEMO_CALLER.1.to_owned())120
(DEMO_CALLER.0.to_owned(), DEMO_CALLER.1.to_owned())82
}121
}83
122
123
pub fn demo_video_ring() -> IncomingRing {124
IncomingRing { video: true, ..demo_ring() }125
}126
84
pub fn demo_ring() -> IncomingRing {127
pub fn demo_ring() -> IncomingRing {85
let (mri, display_name) = demo_caller();128
let (mri, display_name) = demo_caller();86
IncomingRing {129
IncomingRing {@@ -126,8 +169,12 @@ fn demo_devices() -> DeviceLists {126
}169
}127
170
128
pub fn start_demo_call(script: DemoCall) -> CallHandle {171
pub fn start_demo_call(script: DemoCall) -> CallHandle {172
start_demo_scene_call(script, DemoScene::Plain)173
}174
175
pub fn start_demo_scene_call(script: DemoCall, scene: DemoScene) -> CallHandle {129
let (handle, control) = call_channel();176
let (handle, control) = call_channel();130
crate::runtime::handle().spawn(run_demo_call(control, script));177
crate::runtime::handle().spawn(run_demo_call(control, script, scene));131
handle178
handle132
}179
}133
180
@@ -149,7 +196,7 @@ fn roster_of(people: &[Person]) -> Vec<RosterEntry> {149
.collect()196
.collect()150
}197
}151
198
152
async fn run_demo_call(mut control: CallControl, script: DemoCall) {199
async fn run_demo_call(mut control: CallControl, script: DemoCall, scene: DemoScene) {153
control.send(CallUpdate::OwnIdentity {200
control.send(CallUpdate::OwnIdentity {154
mri: DEMO_OWN_MRI.to_owned(),201
mri: DEMO_OWN_MRI.to_owned(),155
});202
});@@ -185,6 +232,9 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall) {185
control.send(CallUpdate::Lobby(false));232
control.send(CallUpdate::Lobby(false));186
}233
}187
let mut roster = roster_of(&people);234
let mut roster = roster_of(&people);235
if matches!(script, DemoCall::People(_)) {236
control.send(CallUpdate::ReplacementLink(DEMO_REPLACEMENT_LINK.to_owned()));237
}188
if matches!(script, DemoCall::Meeting { organizer: true, .. }) {238
if matches!(script, DemoCall::Meeting { organizer: true, .. }) {189
roster.push(demo_organizer());239
roster.push(demo_organizer());190
roster.extend(DEMO_WAITING.iter().enumerate().map(|(index, name)| demo_waiting(index, name)));240
roster.extend(DEMO_WAITING.iter().enumerate().map(|(index, name)| demo_waiting(index, name)));@@ -199,7 +249,8 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall) {199
control.send(CallUpdate::Roster(roster.clone()));249
control.send(CallUpdate::Roster(roster.clone()));200
let video = !matches!(script, DemoCall::Test);250
let video = !matches!(script, DemoCall::Test);201
let sharer = matches!(script, DemoCall::Meeting { .. }).then(|| people.get(1).map(|person| person.0.clone())).flatten();251
let sharer = matches!(script, DemoCall::Meeting { .. }).then(|| people.get(1).map(|person| person.0.clone())).flatten();202
speak_until_hangup(control, people, roster, video, sharer).await;252
start_scene(&control, scene);253
speak_until_hangup(control, people, roster, video, sharer, scene).await;203
}254
}204
255
205
async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bool {256
async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bool {@@ -235,7 +286,38 @@ fn publish_demo_video(control: &CallControl, people: &[Person], tick: u32, shari235
}286
}236
}287
}237
288
238
async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut roster: Vec<RosterEntry>, video: bool, sharer: Option<String>) {289
fn start_scene(control: &CallControl, scene: DemoScene) {290
match scene {291
DemoScene::Recording => control.send(CallUpdate::Recording(true)),292
DemoScene::Consent => {293
control.send(CallUpdate::Recording(true));294
control.send(CallUpdate::ConsentRequired(true));295
}296
DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),297
DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),298
DemoScene::Call | DemoScene::Breakout | DemoScene::Whiteboard | DemoScene::Plain => {}299
}300
}301
302
fn scene_tick(control: &CallControl, scene: DemoScene, ticks: u32, people: &[Person]) {303
match scene {304
DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => control.send(CallUpdate::BreakoutMove(BreakoutMove {305
room_name: "Room 1".to_owned(),306
target: MeetingTarget { thread_id: DEMO_ROOM_THREAD.to_owned(), tenant_id: "demo-tenant".to_owned(), organizer_id: "demo-me".to_owned(), meeting_data: None },307
returning: false,308
})),309
DemoScene::Whiteboard if ticks == WHITEBOARD_AT_TICKS => control.send(CallUpdate::Whiteboard(Some(ContentShare {310
session_id: "demo-whiteboard".to_owned(),311
presenter: people.first().map(|person| person.0.clone()),312
subject: "Whiteboard".to_owned(),313
url: Some(DEMO_BOARD_URL.to_owned()),314
whiteboard: true,315
}))),316
_ => {}317
}318
}319
320
async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut roster: Vec<RosterEntry>, video: bool, sharer: Option<String>, scene: DemoScene) {239
let started = Instant::now();321
let started = Instant::now();240
let mut video_ticks = 0u32;322
let mut video_ticks = 0u32;241
let mut sharing = false;323
let mut sharing = false;@@ -285,6 +367,7 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r285
}367
}286
caption_ticks += 1;368
caption_ticks += 1;287
}369
}370
scene_tick(&control, scene, ticks, &people);288
ticks += 1;371
ticks += 1;289
}372
}290
command = control.recv() => match command {373
command = control.recv() => match command {@@ -365,7 +448,16 @@ async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut r365
caption_ticks = 0;448
caption_ticks = 0;366
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));449
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));367
}450
}368
Some(CallCommand::SetBlur(on)) => blur = on,451
Some(CallCommand::SetBackground(choice)) => blur = choice != BackgroundChoice::None,452
Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),453
Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),454
Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),455
Some(CallCommand::Transfer { .. }) => {456
control.send(CallUpdate::Notice("Call transferred".to_owned()));457
end(&control, EndReason::LocalHangup);458
return;459
}460
Some(CallCommand::OpenWhiteboard { .. }) => control.send(CallUpdate::WhiteboardUrl(DEMO_BOARD_URL.to_owned())),369
Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),461
Some(CallCommand::RefreshShareSources) => control.send(CallUpdate::ShareSources(demo_share_sources())),370
Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {462
Some(CallCommand::Hangup | CallCommand::EndMeeting) | None => {371
end(&control, EndReason::LocalHangup);463
end(&control, EndReason::LocalHangup);@@ -0,0 +1,246 @@
1
use calling::{CallCommand, CallHandle, CallSpec, CallState, Callee, EndKind, EndReason, HoldState};
2
use gpui_kit::*;
3
4
use super::demo::{DemoCall, start_demo_call};
5
use super::model::{ActiveCall, BreakoutState, CallModel, ConsultCall, PendingMove};
6
use super::target::plan_for_chat;
7
use crate::app_state::AppState;
8
use crate::data::is_one_on_one;
9
10
const DEMO_ROOM_GUESTS: usize = 3;
11
12
#[derive(Debug, Clone, PartialEq, Eq)]
13
pub struct TransferCandidate {
14
pub mri: String,
15
pub name: String,
16
pub user_id: Option<String>,
17
pub chat_id: String,
18
}
19
20
pub fn room_closed_move(call: &ActiveCall, reason: &EndReason) -> Option<PendingMove> {
21
let room = call.model.breakout.as_ref()?;
22
if *reason != EndReason::Remote(EndKind::RoomClosed) {
23
return None;
24
}
25
Some(return_move(room))
26
}
27
28
fn return_move(room: &BreakoutState) -> PendingMove {
29
PendingMove { target: room.main.clone().expect("a room with a way back"), title: room.main_title.clone(), breakout: None }
30
}
31
32
impl AppState {
33
pub fn set_call_recording(&mut self, on: bool, _cx: &mut Context<Self>) {
34
let Some(call) = self.call.as_ref().filter(|call| call.model.can_record()) else {
35
return;
36
};
37
let title = call.model.title.clone();
38
self.send_call_command(CallCommand::SetRecording { on, title });
39
}
40
41
pub fn accept_recording_notice(&mut self, _cx: &mut Context<Self>) {
42
if self.call.as_ref().is_some_and(|call| call.model.consent_required) {
43
self.send_call_command(CallCommand::ConsentToRecording);
44
}
45
}
46
47
pub fn toggle_call_hold(&mut self, _cx: &mut Context<Self>) {
48
let Some(call) = self.call.as_ref() else {
49
return;
50
};
51
let hold = match call.model.hold {
52
HoldState::Local => false,
53
HoldState::Active if call.model.can_hold() => true,
54
_ => return,
55
};
56
self.send_call_command(CallCommand::Hold(hold));
57
}
58
59
pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {
60
let Some(call) = self.call.as_ref().filter(|call| call.model.can_open_whiteboard()) else {
61
return;
62
};
63
if let Some(url) = call.model.whiteboard_url() {
64
cx.open_url(url);
65
return;
66
}
67
let title = call.model.title.clone();
68
self.send_call_command(CallCommand::OpenWhiteboard { title });
69
}
70
71
pub fn transfer_candidates(&self) -> Vec<TransferCandidate> {
72
let peer = self.call.as_ref().and_then(|call| call.model.tiles.first().map(|tile| tile.mri.clone()));
73
self.sidebar
74
.chats
75
.iter()
76
.filter(|chat| is_one_on_one(chat))
77
.filter_map(|chat| {
78
let plan = plan_for_chat(chat, self.directory.me.as_ref())?;
79
let (mri, name) = plan.callees.into_iter().next()?;
80
Some(TransferCandidate { user_id: mri.strip_prefix("8:orgid:").map(str::to_owned), mri, name, chat_id: chat.id.clone() })
81
})
82
.filter(|candidate| Some(&candidate.mri) != peer.as_ref())
83
.collect()
84
}
85
86
pub fn can_transfer_call(&self) -> bool {
87
self.call.as_ref().is_some_and(|call| call.model.can_transfer() && call.consult.is_none())
88
}
89
90
pub fn open_transfer_picker(&mut self, picker: Entity<crate::views::transfer_picker::TransferPicker>, cx: &mut Context<Self>) {
91
if self.can_transfer_call() {
92
self.transfer_picker = Some(picker);
93
cx.notify();
94
}
95
}
96
97
pub fn close_transfer_picker(&mut self, cx: &mut Context<Self>) {
98
if self.transfer_picker.take().is_some() {
99
cx.notify();
100
}
101
}
102
103
pub fn transfer_call_blind(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {
104
self.close_transfer_picker(cx);
105
if !self.can_transfer_call() {
106
return;
107
}
108
let callee = Callee { mri: target.mri, display_name: target.name };
109
self.send_call_command(CallCommand::Transfer { target: callee, replaces: None });
110
}
111
112
pub fn start_consult(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {
113
self.close_transfer_picker(cx);
114
if !self.can_transfer_call() {
115
return;
116
}
117
let spec = CallSpec::People {
118
callees: vec![Callee { mri: target.mri.clone(), display_name: target.name.clone() }],
119
thread_id: target.chat_id.clone(),
120
};
121
let handle = if self.mode.demo {
122
Some(start_demo_call(DemoCall::People(vec![(target.mri.clone(), target.name.clone())])))
123
} else {
124
self.call_launcher.clone().map(|launcher| launcher.start_consult(spec))
125
};
126
let Some(CallHandle { commands, updates, .. }) = handle else {
127
self.raise_notice("Not connected to Teams yet".to_owned(), None, cx);
128
return;
129
};
130
self.send_call_command(CallCommand::Hold(true));
131
self.call_count += 1;
132
let consult_id = self.call_count;
133
let Some(call) = self.call.as_mut() else {
134
return;
135
};
136
let call_id = call.id;
137
call.consult = Some(ConsultCall {
138
id: consult_id,
139
target: (target.mri, target.name),
140
commands,
141
state: CallState::Connecting,
142
replacement: None,
143
transferring: false,
144
});
145
self.follow_consult(call_id, consult_id, updates, cx);
146
cx.notify();
147
}
148
149
fn follow_consult(&mut self, call_id: u64, consult_id: u64, mut updates: tokio::sync::mpsc::UnboundedReceiver<calling::CallUpdate>, cx: &mut Context<Self>) {
150
cx.spawn(async move |this, cx| {
151
while let Some(update) = updates.recv().await {
152
if this.update(cx, |state, cx| state.apply_consult_update(call_id, consult_id, update, cx)).is_err() {
153
return;
154
}
155
}
156
})
157
.detach();
158
}
159
160
pub(super) fn apply_consult_update(&mut self, call_id: u64, consult_id: u64, update: calling::CallUpdate, cx: &mut Context<Self>) {
161
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
162
return;
163
};
164
let Some(consult) = call.consult.as_mut().filter(|consult| consult.id == consult_id) else {
165
return;
166
};
167
match update {
168
calling::CallUpdate::ReplacementLink(link) => consult.replacement = Some(link),
169
calling::CallUpdate::Notice(text) => self.raise_notice(text, None, cx),
170
calling::CallUpdate::State(state) => {
171
let ended = matches!(state, CallState::Ended { .. });
172
consult.state = state;
173
if ended {
174
let transferring = consult.transferring;
175
call.consult = None;
176
if !transferring {
177
self.raise_notice("The consultation ended".to_owned(), None, cx);
178
self.send_call_command(CallCommand::Hold(false));
179
}
180
}
181
}
182
_ => {}
183
}
184
cx.notify();
185
}
186
187
pub fn transfer_consulted(&mut self, _cx: &mut Context<Self>) {
188
let Some(consult) = self.call.as_mut().and_then(|call| call.consult.as_mut()).filter(|consult| consult.ready_to_transfer()) else {
189
return;
190
};
191
consult.transferring = true;
192
let (mri, name) = consult.target.clone();
193
let replaces = consult.replacement.clone();
194
self.send_call_command(CallCommand::Transfer { target: Callee { mri, display_name: name }, replaces });
195
}
196
197
pub fn cancel_consult(&mut self, _cx: &mut Context<Self>) {
198
if let Some(consult) = self.call.as_ref().and_then(|call| call.consult.as_ref()) {
199
let _ = consult.commands.send(CallCommand::Hangup);
200
}
201
}
202
203
pub(super) fn begin_breakout_move(&mut self, moved: calling::BreakoutMove, cx: &mut Context<Self>) {
204
let Some(call) = self.call.as_mut().filter(|call| call.pending_move.is_none()) else {
205
return;
206
};
207
let (main, main_title) = match &call.model.breakout {
208
Some(room) => (room.main.clone().or_else(|| call.model.main_meeting.clone()), room.main_title.clone()),
209
None => (call.meeting_target.clone(), call.model.title.clone()),
210
};
211
let pending = if moved.returning {
212
PendingMove { target: moved.target, title: main_title, breakout: None }
213
} else {
214
let breakout = BreakoutState { room_name: moved.room_name.clone(), main, main_title };
215
PendingMove { target: moved.target, title: moved.room_name.clone(), breakout: Some(breakout) }
216
};
217
let notice = if moved.returning { "Moving you back to the main meeting".to_owned() } else { format!("Moving you to {}", moved.room_name) };
218
call.pending_move = Some(pending);
219
self.raise_notice(notice, None, cx);
220
self.send_call_command(CallCommand::Hangup);
221
}
222
223
pub fn return_to_main_meeting(&mut self, _cx: &mut Context<Self>) {
224
let Some(call) = self.call.as_mut().filter(|call| call.pending_move.is_none()) else {
225
return;
226
};
227
let Some(room) = call.model.breakout.as_ref().filter(|room| room.main.is_some()) else {
228
return;
229
};
230
call.pending_move = Some(return_move(room));
231
self.send_call_command(CallCommand::Hangup);
232
}
233
234
pub(super) fn join_moved_call(&mut self, moved: PendingMove, cx: &mut Context<Self>) {
235
let demo = DemoCall::Meeting { guests: super::demo::demo_guests(DEMO_ROOM_GUESTS), lobby: false, organizer: false };
236
let Some(handle) = self.place_call(CallSpec::Meeting(moved.target.clone()), demo, cx) else {
237
return;
238
};
239
let mut model = CallModel::meeting(&moved.title, false);
240
model.breakout = moved.breakout;
241
self.begin_call(handle, model, Some(moved.target.thread_id.clone()), cx);
242
if let Some(call) = self.call.as_mut() {
243
call.meeting_target = Some(moved.target);
244
}
245
}
246
}
@@ -0,0 +1,246 @@1
use calling::{CallCommand, CallHandle, CallSpec, CallState, Callee, EndKind, EndReason, HoldState};2
use gpui_kit::*;3
4
use super::demo::{DemoCall, start_demo_call};5
use super::model::{ActiveCall, BreakoutState, CallModel, ConsultCall, PendingMove};6
use super::target::plan_for_chat;7
use crate::app_state::AppState;8
use crate::data::is_one_on_one;9
10
const DEMO_ROOM_GUESTS: usize = 3;11
12
#[derive(Debug, Clone, PartialEq, Eq)]13
pub struct TransferCandidate {14
pub mri: String,15
pub name: String,16
pub user_id: Option<String>,17
pub chat_id: String,18
}19
20
pub fn room_closed_move(call: &ActiveCall, reason: &EndReason) -> Option<PendingMove> {21
let room = call.model.breakout.as_ref()?;22
if *reason != EndReason::Remote(EndKind::RoomClosed) {23
return None;24
}25
Some(return_move(room))26
}27
28
fn return_move(room: &BreakoutState) -> PendingMove {29
PendingMove { target: room.main.clone().expect("a room with a way back"), title: room.main_title.clone(), breakout: None }30
}31
32
impl AppState {33
pub fn set_call_recording(&mut self, on: bool, _cx: &mut Context<Self>) {34
let Some(call) = self.call.as_ref().filter(|call| call.model.can_record()) else {35
return;36
};37
let title = call.model.title.clone();38
self.send_call_command(CallCommand::SetRecording { on, title });39
}40
41
pub fn accept_recording_notice(&mut self, _cx: &mut Context<Self>) {42
if self.call.as_ref().is_some_and(|call| call.model.consent_required) {43
self.send_call_command(CallCommand::ConsentToRecording);44
}45
}46
47
pub fn toggle_call_hold(&mut self, _cx: &mut Context<Self>) {48
let Some(call) = self.call.as_ref() else {49
return;50
};51
let hold = match call.model.hold {52
HoldState::Local => false,53
HoldState::Active if call.model.can_hold() => true,54
_ => return,55
};56
self.send_call_command(CallCommand::Hold(hold));57
}58
59
pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {60
let Some(call) = self.call.as_ref().filter(|call| call.model.can_open_whiteboard()) else {61
return;62
};63
if let Some(url) = call.model.whiteboard_url() {64
cx.open_url(url);65
return;66
}67
let title = call.model.title.clone();68
self.send_call_command(CallCommand::OpenWhiteboard { title });69
}70
71
pub fn transfer_candidates(&self) -> Vec<TransferCandidate> {72
let peer = self.call.as_ref().and_then(|call| call.model.tiles.first().map(|tile| tile.mri.clone()));73
self.sidebar74
.chats75
.iter()76
.filter(|chat| is_one_on_one(chat))77
.filter_map(|chat| {78
let plan = plan_for_chat(chat, self.directory.me.as_ref())?;79
let (mri, name) = plan.callees.into_iter().next()?;80
Some(TransferCandidate { user_id: mri.strip_prefix("8:orgid:").map(str::to_owned), mri, name, chat_id: chat.id.clone() })81
})82
.filter(|candidate| Some(&candidate.mri) != peer.as_ref())83
.collect()84
}85
86
pub fn can_transfer_call(&self) -> bool {87
self.call.as_ref().is_some_and(|call| call.model.can_transfer() && call.consult.is_none())88
}89
90
pub fn open_transfer_picker(&mut self, picker: Entity<crate::views::transfer_picker::TransferPicker>, cx: &mut Context<Self>) {91
if self.can_transfer_call() {92
self.transfer_picker = Some(picker);93
cx.notify();94
}95
}96
97
pub fn close_transfer_picker(&mut self, cx: &mut Context<Self>) {98
if self.transfer_picker.take().is_some() {99
cx.notify();100
}101
}102
103
pub fn transfer_call_blind(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {104
self.close_transfer_picker(cx);105
if !self.can_transfer_call() {106
return;107
}108
let callee = Callee { mri: target.mri, display_name: target.name };109
self.send_call_command(CallCommand::Transfer { target: callee, replaces: None });110
}111
112
pub fn start_consult(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {113
self.close_transfer_picker(cx);114
if !self.can_transfer_call() {115
return;116
}117
let spec = CallSpec::People {118
callees: vec![Callee { mri: target.mri.clone(), display_name: target.name.clone() }],119
thread_id: target.chat_id.clone(),120
};121
let handle = if self.mode.demo {122
Some(start_demo_call(DemoCall::People(vec![(target.mri.clone(), target.name.clone())])))123
} else {124
self.call_launcher.clone().map(|launcher| launcher.start_consult(spec))125
};126
let Some(CallHandle { commands, updates, .. }) = handle else {127
self.raise_notice("Not connected to Teams yet".to_owned(), None, cx);128
return;129
};130
self.send_call_command(CallCommand::Hold(true));131
self.call_count += 1;132
let consult_id = self.call_count;133
let Some(call) = self.call.as_mut() else {134
return;135
};136
let call_id = call.id;137
call.consult = Some(ConsultCall {138
id: consult_id,139
target: (target.mri, target.name),140
commands,141
state: CallState::Connecting,142
replacement: None,143
transferring: false,144
});145
self.follow_consult(call_id, consult_id, updates, cx);146
cx.notify();147
}148
149
fn follow_consult(&mut self, call_id: u64, consult_id: u64, mut updates: tokio::sync::mpsc::UnboundedReceiver<calling::CallUpdate>, cx: &mut Context<Self>) {150
cx.spawn(async move |this, cx| {151
while let Some(update) = updates.recv().await {152
if this.update(cx, |state, cx| state.apply_consult_update(call_id, consult_id, update, cx)).is_err() {153
return;154
}155
}156
})157
.detach();158
}159
160
pub(super) fn apply_consult_update(&mut self, call_id: u64, consult_id: u64, update: calling::CallUpdate, cx: &mut Context<Self>) {161
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {162
return;163
};164
let Some(consult) = call.consult.as_mut().filter(|consult| consult.id == consult_id) else {165
return;166
};167
match update {168
calling::CallUpdate::ReplacementLink(link) => consult.replacement = Some(link),169
calling::CallUpdate::Notice(text) => self.raise_notice(text, None, cx),170
calling::CallUpdate::State(state) => {171
let ended = matches!(state, CallState::Ended { .. });172
consult.state = state;173
if ended {174
let transferring = consult.transferring;175
call.consult = None;176
if !transferring {177
self.raise_notice("The consultation ended".to_owned(), None, cx);178
self.send_call_command(CallCommand::Hold(false));179
}180
}181
}182
_ => {}183
}184
cx.notify();185
}186
187
pub fn transfer_consulted(&mut self, _cx: &mut Context<Self>) {188
let Some(consult) = self.call.as_mut().and_then(|call| call.consult.as_mut()).filter(|consult| consult.ready_to_transfer()) else {189
return;190
};191
consult.transferring = true;192
let (mri, name) = consult.target.clone();193
let replaces = consult.replacement.clone();194
self.send_call_command(CallCommand::Transfer { target: Callee { mri, display_name: name }, replaces });195
}196
197
pub fn cancel_consult(&mut self, _cx: &mut Context<Self>) {198
if let Some(consult) = self.call.as_ref().and_then(|call| call.consult.as_ref()) {199
let _ = consult.commands.send(CallCommand::Hangup);200
}201
}202
203
pub(super) fn begin_breakout_move(&mut self, moved: calling::BreakoutMove, cx: &mut Context<Self>) {204
let Some(call) = self.call.as_mut().filter(|call| call.pending_move.is_none()) else {205
return;206
};207
let (main, main_title) = match &call.model.breakout {208
Some(room) => (room.main.clone().or_else(|| call.model.main_meeting.clone()), room.main_title.clone()),209
None => (call.meeting_target.clone(), call.model.title.clone()),210
};211
let pending = if moved.returning {212
PendingMove { target: moved.target, title: main_title, breakout: None }213
} else {214
let breakout = BreakoutState { room_name: moved.room_name.clone(), main, main_title };215
PendingMove { target: moved.target, title: moved.room_name.clone(), breakout: Some(breakout) }216
};217
let notice = if moved.returning { "Moving you back to the main meeting".to_owned() } else { format!("Moving you to {}", moved.room_name) };218
call.pending_move = Some(pending);219
self.raise_notice(notice, None, cx);220
self.send_call_command(CallCommand::Hangup);221
}222
223
pub fn return_to_main_meeting(&mut self, _cx: &mut Context<Self>) {224
let Some(call) = self.call.as_mut().filter(|call| call.pending_move.is_none()) else {225
return;226
};227
let Some(room) = call.model.breakout.as_ref().filter(|room| room.main.is_some()) else {228
return;229
};230
call.pending_move = Some(return_move(room));231
self.send_call_command(CallCommand::Hangup);232
}233
234
pub(super) fn join_moved_call(&mut self, moved: PendingMove, cx: &mut Context<Self>) {235
let demo = DemoCall::Meeting { guests: super::demo::demo_guests(DEMO_ROOM_GUESTS), lobby: false, organizer: false };236
let Some(handle) = self.place_call(CallSpec::Meeting(moved.target.clone()), demo, cx) else {237
return;238
};239
let mut model = CallModel::meeting(&moved.title, false);240
model.breakout = moved.breakout;241
self.begin_call(handle, model, Some(moved.target.thread_id.clone()), cx);242
if let Some(call) = self.call.as_mut() {243
call.meeting_target = Some(moved.target);244
}245
}246
}@@ -0,0 +1,450 @@
1
use std::collections::HashMap;
2
3
use chrono::{DateTime, Duration, FixedOffset, Utc};
4
use gpui_kit::Context;
5
use store::ChatRecord;
6
use teams_core::{CallDirection, CallLogEntry, CallOutcome};
7
8
use crate::app_state::{AppEvent, AppState, Selection, chat_title};
9
use crate::data::is_one_on_one;
10
use crate::format;
11
use crate::notice::short_error;
12
use crate::runtime;
13
14
const ORGID_PREFIX: &str = "8:orgid:";
15
const UNKNOWN_NAME: &str = "Unknown";
16
const MEETING_TITLE: &str = "Meeting";
17
const NO_CHAT_NOTICE: &str = "No chat with this person yet";
18
const NO_MEETING_CHAT_NOTICE: &str = "This meeting chat is not available";
19
const REFRESH_DELAY_AFTER_CALL: std::time::Duration = std::time::Duration::from_secs(4);
20
21
#[derive(Debug, Clone, PartialEq, Eq)]
22
pub struct CallRow {
23
pub key: String,
24
pub title: String,
25
pub subline: String,
26
pub time_label: String,
27
pub missed: bool,
28
pub meeting: bool,
29
pub user_id: Option<String>,
30
pub thread_id: Option<String>,
31
}
32
33
pub fn duration_label(seconds: i64) -> String {
34
let seconds = seconds.max(0);
35
let (hours, minutes, rest) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
36
match (hours, minutes, rest) {
37
(0, 0, _) => format!("{rest}s"),
38
(0, minutes, 0) => format!("{minutes}m"),
39
(0, minutes, rest) if minutes < 10 => format!("{minutes}m {rest}s"),
40
(0, minutes, _) => format!("{minutes}m"),
41
(hours, 0, _) => format!("{hours}h"),
42
(hours, minutes, _) => format!("{hours}h {minutes}m"),
43
}
44
}
45
46
pub fn subline(entry: &CallLogEntry) -> String {
47
if entry.missed() {
48
return "Missed call".to_owned();
49
}
50
let kind = if entry.is_meeting {
51
"Meeting"
52
} else {
53
match (entry.direction, entry.outcome) {
54
(CallDirection::Incoming, CallOutcome::Declined) => return "Declined call".to_owned(),
55
(CallDirection::Incoming, _) => "Incoming",
56
(CallDirection::Outgoing, _) => "Outgoing",
57
}
58
};
59
match entry.duration_seconds {
60
Some(seconds) => format!("{kind} \u{b7} {}", duration_label(seconds)),
61
None => kind.to_owned(),
62
}
63
}
64
65
fn user_id_of(mri: &str) -> Option<String> {
66
mri.strip_prefix(ORGID_PREFIX).map(str::to_owned)
67
}
68
69
fn known_names(chats: &[ChatRecord]) -> HashMap<&str, &str> {
70
chats
71
.iter()
72
.flat_map(|chat| chat.members.iter())
73
.filter_map(|member| Some((member.user_id.as_deref()?, member.display_name.as_str())))
74
.filter(|(_, name)| !name.is_empty())
75
.collect()
76
}
77
78
pub fn call_rows(
79
entries: &[CallLogEntry],
80
chats: &[ChatRecord],
81
now: DateTime<Utc>,
82
offset: FixedOffset,
83
) -> Vec<CallRow> {
84
let names = known_names(chats);
85
let today = now.with_timezone(&offset).date_naive();
86
entries
87
.iter()
88
.map(|entry| {
89
let user_id = entry
90
.peer_id
91
.as_deref()
92
.and_then(user_id_of)
93
.filter(|_| !entry.is_meeting);
94
let thread_chat = entry
95
.thread_id
96
.as_deref()
97
.and_then(|thread_id| chats.iter().find(|chat| chat.id == thread_id));
98
let title = if entry.is_meeting {
99
thread_chat.map_or_else(|| MEETING_TITLE.to_owned(), chat_title)
100
} else {
101
entry
102
.peer_name
103
.clone()
104
.or_else(|| {
105
let user_id = user_id.as_deref()?;
106
names.get(user_id).map(|name| (*name).to_owned())
107
})
108
.unwrap_or_else(|| UNKNOWN_NAME.to_owned())
109
};
110
CallRow {
111
key: entry.call_id.clone(),
112
title,
113
subline: subline(entry),
114
time_label: format::list_time_label(entry.started_at, today, offset),
115
missed: entry.missed(),
116
meeting: entry.is_meeting,
117
user_id,
118
thread_id: entry.thread_id.clone().filter(|_| entry.is_meeting),
119
}
120
})
121
.collect()
122
}
123
124
pub fn demo_call_log(now: DateTime<Utc>) -> Vec<CallLogEntry> {
125
let entry = |id: &str,
126
minutes_ago: i64,
127
direction: CallDirection,
128
outcome: CallOutcome,
129
duration_seconds: Option<i64>,
130
peer: Option<(&str, &str)>,
131
thread_id: Option<&str>| CallLogEntry {
132
call_id: id.to_owned(),
133
started_at: now - Duration::minutes(minutes_ago),
134
duration_seconds,
135
direction,
136
outcome,
137
is_meeting: thread_id.is_some(),
138
peer_id: peer.map(|(user_id, _)| format!("{ORGID_PREFIX}{user_id}")),
139
peer_name: peer.map(|(_, name)| name.to_owned()),
140
thread_id: thread_id.map(str::to_owned),
141
};
142
let incoming = CallDirection::Incoming;
143
let outgoing = CallDirection::Outgoing;
144
let accepted = CallOutcome::Accepted;
145
let mara = Some(("demo-mara", "Mara Lindqvist"));
146
let jonas = Some(("demo-jonas", "Jonas Ortega"));
147
let priya = Some(("demo-priya", "Priya Nair"));
148
vec![
149
entry(
150
"demo-call-1",
151
35,
152
incoming,
153
CallOutcome::Missed,
154
None,
155
mara,
156
None,
157
),
158
entry(
159
"demo-call-2",
160
190,
161
outgoing,
162
accepted,
163
Some(252),
164
jonas,
165
None,
166
),
167
entry(
168
"demo-call-3",
169
1500,
170
incoming,
171
accepted,
172
Some(720),
173
priya,
174
None,
175
),
176
entry(
177
"demo-call-4",
178
1620,
179
incoming,
180
accepted,
181
Some(2280),
182
None,
183
Some("demo-chat-meeting-standup"),
184
),
185
entry(
186
"demo-call-5",
187
4400,
188
incoming,
189
CallOutcome::Missed,
190
None,
191
jonas,
192
None,
193
),
194
entry(
195
"demo-call-6",
196
8200,
197
outgoing,
198
accepted,
199
Some(95),
200
mara,
201
None,
202
),
203
entry(
204
"demo-call-7",
205
11000,
206
incoming,
207
accepted,
208
Some(3900),
209
None,
210
Some("demo-chat-meeting-retro"),
211
),
212
]
213
}
214
215
impl AppState {
216
pub fn refresh_call_history(&mut self, cx: &mut Context<Self>) {
217
if self.mode.demo {
218
self.call_history = demo_call_log(Utc::now());
219
cx.emit(AppEvent::CallHistory);
220
cx.notify();
221
return;
222
}
223
let Some(engine) = self.engine.clone() else {
224
return;
225
};
226
let receiver = runtime::spawn(async move { engine.list_call_logs().await });
227
cx.spawn(async move |this, cx| match receiver.await {
228
Ok(Ok(entries)) => {
229
this.update(cx, |state, cx| {
230
state.call_history = entries;
231
cx.emit(AppEvent::CallHistory);
232
cx.notify();
233
})
234
.ok();
235
}
236
Ok(Err(error)) => eprintln!("calls: history not loaded: {}", short_error(&error)),
237
Err(_) => {}
238
})
239
.detach();
240
}
241
242
pub fn refresh_call_history_after_call(&mut self, cx: &mut Context<Self>) {
243
cx.spawn(async move |this, cx| {
244
cx.background_executor()
245
.timer(REFRESH_DELAY_AFTER_CALL)
246
.await;
247
this.update(cx, |state, cx| state.refresh_call_history(cx))
248
.ok();
249
})
250
.detach();
251
}
252
253
fn one_on_one_chat_with(&self, user_id: &str) -> Option<String> {
254
self.sidebar
255
.chats
256
.iter()
257
.find(|chat| {
258
is_one_on_one(chat)
259
&& chat
260
.members
261
.iter()
262
.any(|member| member.user_id.as_deref() == Some(user_id))
263
})
264
.map(|chat| chat.id.clone())
265
}
266
267
fn chat_of_call_row(&self, row: &CallRow) -> Option<String> {
268
match (&row.thread_id, &row.user_id) {
269
(Some(thread_id), _) => self
270
.sidebar
271
.chats
272
.iter()
273
.any(|chat| &chat.id == thread_id)
274
.then(|| thread_id.clone()),
275
(None, Some(user_id)) => self.one_on_one_chat_with(user_id),
276
(None, None) => None,
277
}
278
}
279
280
pub fn call_back_from_history(&mut self, row: &CallRow, cx: &mut Context<Self>) {
281
let Some(user_id) = row.user_id.as_deref() else {
282
return;
283
};
284
match self.one_on_one_chat_with(user_id) {
285
Some(chat_id) => self.start_chat_call(&chat_id, cx),
286
None => self.raise_notice(NO_CHAT_NOTICE.to_owned(), None, cx),
287
}
288
}
289
290
pub fn open_chat_of_call_row(&mut self, row: &CallRow, cx: &mut Context<Self>) {
291
let notice = if row.meeting {
292
NO_MEETING_CHAT_NOTICE
293
} else {
294
NO_CHAT_NOTICE
295
};
296
match self.chat_of_call_row(row) {
297
Some(chat_id) => self.select(Selection::Chat(chat_id), cx),
298
None => self.raise_notice(notice.to_owned(), None, cx),
299
}
300
}
301
302
pub fn activate_call_row(&mut self, row: &CallRow, cx: &mut Context<Self>) {
303
if row.meeting {
304
self.open_chat_of_call_row(row, cx);
305
} else {
306
self.call_back_from_history(row, cx);
307
}
308
}
309
310
pub fn can_open_chat_of_call_row(&self, row: &CallRow) -> bool {
311
self.chat_of_call_row(row).is_some()
312
}
313
}
314
315
#[cfg(test)]
316
mod tests {
317
use chrono::TimeZone;
318
use store::MemberRecord;
319
320
use super::*;
321
322
fn entry(direction: CallDirection, outcome: CallOutcome, seconds: Option<i64>) -> CallLogEntry {
323
CallLogEntry {
324
call_id: "c".into(),
325
started_at: Utc.with_ymd_and_hms(2026, 10, 9, 8, 0, 0).unwrap(),
326
duration_seconds: seconds,
327
direction,
328
outcome,
329
is_meeting: false,
330
peer_id: Some("8:orgid:bea-id".into()),
331
peer_name: None,
332
thread_id: None,
333
}
334
}
335
336
fn chat(id: &str, kind: &str, title: &str, members: &[(&str, &str)]) -> ChatRecord {
337
ChatRecord {
338
id: id.into(),
339
kind: kind.into(),
340
title: title.into(),
341
members: members
342
.iter()
343
.map(|(user_id, name)| MemberRecord {
344
user_id: Some((*user_id).to_owned()),
345
display_name: (*name).to_owned(),
346
})
347
.collect(),
348
..Default::default()
349
}
350
}
351
352
fn rows(entries: &[CallLogEntry], chats: &[ChatRecord]) -> Vec<CallRow> {
353
let now = Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap();
354
call_rows(entries, chats, now, FixedOffset::east_opt(0).unwrap())
355
}
356
357
#[test]
358
fn durations_show_seconds_only_for_short_calls() {
359
assert_eq!(duration_label(45), "45s");
360
assert_eq!(duration_label(252), "4m 12s");
361
assert_eq!(duration_label(240), "4m");
362
assert_eq!(duration_label(720), "12m");
363
assert_eq!(duration_label(2280), "38m");
364
assert_eq!(duration_label(3600), "1h");
365
assert_eq!(duration_label(3900), "1h 5m");
366
}
367
368
#[test]
369
fn sublines_follow_direction_and_outcome() {
370
let missed = entry(CallDirection::Incoming, CallOutcome::Missed, None);
371
assert_eq!(subline(&missed), "Missed call");
372
let outgoing = entry(CallDirection::Outgoing, CallOutcome::Accepted, Some(252));
373
assert_eq!(subline(&outgoing), "Outgoing \u{b7} 4m 12s");
374
let incoming = entry(CallDirection::Incoming, CallOutcome::Accepted, Some(720));
375
assert_eq!(subline(&incoming), "Incoming \u{b7} 12m");
376
let declined = entry(CallDirection::Incoming, CallOutcome::Declined, None);
377
assert_eq!(subline(&declined), "Declined call");
378
let unanswered = entry(CallDirection::Outgoing, CallOutcome::Missed, None);
379
assert_eq!(subline(&unanswered), "Outgoing");
380
let meeting = CallLogEntry {
381
is_meeting: true,
382
..entry(CallDirection::Incoming, CallOutcome::Accepted, Some(2280))
383
};
384
assert_eq!(subline(&meeting), "Meeting \u{b7} 38m");
385
}
386
387
#[test]
388
fn a_missing_display_name_comes_from_the_chat_members() {
389
let chats = [chat("19:a", "oneOnOne", "", &[("bea-id", "Bea")])];
390
let list = rows(
391
&[entry(
392
CallDirection::Outgoing,
393
CallOutcome::Accepted,
394
Some(60),
395
)],
396
&chats,
397
);
398
assert_eq!(list[0].title, "Bea");
399
assert_eq!(list[0].user_id.as_deref(), Some("bea-id"));
400
let unknown = rows(
401
&[entry(
402
CallDirection::Outgoing,
403
CallOutcome::Accepted,
404
Some(60),
405
)],
406
&[],
407
);
408
assert_eq!(unknown[0].title, "Unknown");
409
}
410
411
#[test]
412
fn a_meeting_takes_the_meeting_chat_title() {
413
let chats = [chat("19:meeting_x", "meeting", "Sprint retro", &[])];
414
let meeting = CallLogEntry {
415
is_meeting: true,
416
thread_id: Some("19:meeting_x".into()),
417
..entry(CallDirection::Incoming, CallOutcome::Accepted, Some(60))
418
};
419
let list = rows(std::slice::from_ref(&meeting), &chats);
420
assert_eq!(list[0].title, "Sprint retro");
421
assert_eq!(list[0].thread_id.as_deref(), Some("19:meeting_x"));
422
assert_eq!(list[0].user_id, None);
423
assert_eq!(rows(&[meeting], &[])[0].title, "Meeting");
424
}
425
426
#[test]
427
fn rows_carry_the_chat_list_time_label_and_the_missed_flag() {
428
let missed = entry(CallDirection::Incoming, CallOutcome::Missed, None);
429
let list = rows(&[missed], &[]);
430
assert_eq!(list[0].time_label, "08:00");
431
assert!(list[0].missed);
432
}
433
434
#[test]
435
fn the_demo_history_has_every_kind_of_row() {
436
let log = demo_call_log(Utc::now());
437
assert!(log.iter().any(CallLogEntry::missed));
438
assert!(
439
log.iter()
440
.any(|entry| entry.direction == CallDirection::Outgoing)
441
);
442
assert!(log.iter().any(|entry| entry.is_meeting));
443
assert!(
444
log.iter()
445
.any(|entry| entry.direction == CallDirection::Incoming
446
&& entry.outcome == CallOutcome::Accepted
447
&& !entry.is_meeting)
448
);
449
}
450
}
@@ -0,0 +1,450 @@1
use std::collections::HashMap;2
3
use chrono::{DateTime, Duration, FixedOffset, Utc};4
use gpui_kit::Context;5
use store::ChatRecord;6
use teams_core::{CallDirection, CallLogEntry, CallOutcome};7
8
use crate::app_state::{AppEvent, AppState, Selection, chat_title};9
use crate::data::is_one_on_one;10
use crate::format;11
use crate::notice::short_error;12
use crate::runtime;13
14
const ORGID_PREFIX: &str = "8:orgid:";15
const UNKNOWN_NAME: &str = "Unknown";16
const MEETING_TITLE: &str = "Meeting";17
const NO_CHAT_NOTICE: &str = "No chat with this person yet";18
const NO_MEETING_CHAT_NOTICE: &str = "This meeting chat is not available";19
const REFRESH_DELAY_AFTER_CALL: std::time::Duration = std::time::Duration::from_secs(4);20
21
#[derive(Debug, Clone, PartialEq, Eq)]22
pub struct CallRow {23
pub key: String,24
pub title: String,25
pub subline: String,26
pub time_label: String,27
pub missed: bool,28
pub meeting: bool,29
pub user_id: Option<String>,30
pub thread_id: Option<String>,31
}32
33
pub fn duration_label(seconds: i64) -> String {34
let seconds = seconds.max(0);35
let (hours, minutes, rest) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);36
match (hours, minutes, rest) {37
(0, 0, _) => format!("{rest}s"),38
(0, minutes, 0) => format!("{minutes}m"),39
(0, minutes, rest) if minutes < 10 => format!("{minutes}m {rest}s"),40
(0, minutes, _) => format!("{minutes}m"),41
(hours, 0, _) => format!("{hours}h"),42
(hours, minutes, _) => format!("{hours}h {minutes}m"),43
}44
}45
46
pub fn subline(entry: &CallLogEntry) -> String {47
if entry.missed() {48
return "Missed call".to_owned();49
}50
let kind = if entry.is_meeting {51
"Meeting"52
} else {53
match (entry.direction, entry.outcome) {54
(CallDirection::Incoming, CallOutcome::Declined) => return "Declined call".to_owned(),55
(CallDirection::Incoming, _) => "Incoming",56
(CallDirection::Outgoing, _) => "Outgoing",57
}58
};59
match entry.duration_seconds {60
Some(seconds) => format!("{kind} \u{b7} {}", duration_label(seconds)),61
None => kind.to_owned(),62
}63
}64
65
fn user_id_of(mri: &str) -> Option<String> {66
mri.strip_prefix(ORGID_PREFIX).map(str::to_owned)67
}68
69
fn known_names(chats: &[ChatRecord]) -> HashMap<&str, &str> {70
chats71
.iter()72
.flat_map(|chat| chat.members.iter())73
.filter_map(|member| Some((member.user_id.as_deref()?, member.display_name.as_str())))74
.filter(|(_, name)| !name.is_empty())75
.collect()76
}77
78
pub fn call_rows(79
entries: &[CallLogEntry],80
chats: &[ChatRecord],81
now: DateTime<Utc>,82
offset: FixedOffset,83
) -> Vec<CallRow> {84
let names = known_names(chats);85
let today = now.with_timezone(&offset).date_naive();86
entries87
.iter()88
.map(|entry| {89
let user_id = entry90
.peer_id91
.as_deref()92
.and_then(user_id_of)93
.filter(|_| !entry.is_meeting);94
let thread_chat = entry95
.thread_id96
.as_deref()97
.and_then(|thread_id| chats.iter().find(|chat| chat.id == thread_id));98
let title = if entry.is_meeting {99
thread_chat.map_or_else(|| MEETING_TITLE.to_owned(), chat_title)100
} else {101
entry102
.peer_name103
.clone()104
.or_else(|| {105
let user_id = user_id.as_deref()?;106
names.get(user_id).map(|name| (*name).to_owned())107
})108
.unwrap_or_else(|| UNKNOWN_NAME.to_owned())109
};110
CallRow {111
key: entry.call_id.clone(),112
title,113
subline: subline(entry),114
time_label: format::list_time_label(entry.started_at, today, offset),115
missed: entry.missed(),116
meeting: entry.is_meeting,117
user_id,118
thread_id: entry.thread_id.clone().filter(|_| entry.is_meeting),119
}120
})121
.collect()122
}123
124
pub fn demo_call_log(now: DateTime<Utc>) -> Vec<CallLogEntry> {125
let entry = |id: &str,126
minutes_ago: i64,127
direction: CallDirection,128
outcome: CallOutcome,129
duration_seconds: Option<i64>,130
peer: Option<(&str, &str)>,131
thread_id: Option<&str>| CallLogEntry {132
call_id: id.to_owned(),133
started_at: now - Duration::minutes(minutes_ago),134
duration_seconds,135
direction,136
outcome,137
is_meeting: thread_id.is_some(),138
peer_id: peer.map(|(user_id, _)| format!("{ORGID_PREFIX}{user_id}")),139
peer_name: peer.map(|(_, name)| name.to_owned()),140
thread_id: thread_id.map(str::to_owned),141
};142
let incoming = CallDirection::Incoming;143
let outgoing = CallDirection::Outgoing;144
let accepted = CallOutcome::Accepted;145
let mara = Some(("demo-mara", "Mara Lindqvist"));146
let jonas = Some(("demo-jonas", "Jonas Ortega"));147
let priya = Some(("demo-priya", "Priya Nair"));148
vec![149
entry(150
"demo-call-1",151
35,152
incoming,153
CallOutcome::Missed,154
None,155
mara,156
None,157
),158
entry(159
"demo-call-2",160
190,161
outgoing,162
accepted,163
Some(252),164
jonas,165
None,166
),167
entry(168
"demo-call-3",169
1500,170
incoming,171
accepted,172
Some(720),173
priya,174
None,175
),176
entry(177
"demo-call-4",178
1620,179
incoming,180
accepted,181
Some(2280),182
None,183
Some("demo-chat-meeting-standup"),184
),185
entry(186
"demo-call-5",187
4400,188
incoming,189
CallOutcome::Missed,190
None,191
jonas,192
None,193
),194
entry(195
"demo-call-6",196
8200,197
outgoing,198
accepted,199
Some(95),200
mara,201
None,202
),203
entry(204
"demo-call-7",205
11000,206
incoming,207
accepted,208
Some(3900),209
None,210
Some("demo-chat-meeting-retro"),211
),212
]213
}214
215
impl AppState {216
pub fn refresh_call_history(&mut self, cx: &mut Context<Self>) {217
if self.mode.demo {218
self.call_history = demo_call_log(Utc::now());219
cx.emit(AppEvent::CallHistory);220
cx.notify();221
return;222
}223
let Some(engine) = self.engine.clone() else {224
return;225
};226
let receiver = runtime::spawn(async move { engine.list_call_logs().await });227
cx.spawn(async move |this, cx| match receiver.await {228
Ok(Ok(entries)) => {229
this.update(cx, |state, cx| {230
state.call_history = entries;231
cx.emit(AppEvent::CallHistory);232
cx.notify();233
})234
.ok();235
}236
Ok(Err(error)) => eprintln!("calls: history not loaded: {}", short_error(&error)),237
Err(_) => {}238
})239
.detach();240
}241
242
pub fn refresh_call_history_after_call(&mut self, cx: &mut Context<Self>) {243
cx.spawn(async move |this, cx| {244
cx.background_executor()245
.timer(REFRESH_DELAY_AFTER_CALL)246
.await;247
this.update(cx, |state, cx| state.refresh_call_history(cx))248
.ok();249
})250
.detach();251
}252
253
fn one_on_one_chat_with(&self, user_id: &str) -> Option<String> {254
self.sidebar255
.chats256
.iter()257
.find(|chat| {258
is_one_on_one(chat)259
&& chat260
.members261
.iter()262
.any(|member| member.user_id.as_deref() == Some(user_id))263
})264
.map(|chat| chat.id.clone())265
}266
267
fn chat_of_call_row(&self, row: &CallRow) -> Option<String> {268
match (&row.thread_id, &row.user_id) {269
(Some(thread_id), _) => self270
.sidebar271
.chats272
.iter()273
.any(|chat| &chat.id == thread_id)274
.then(|| thread_id.clone()),275
(None, Some(user_id)) => self.one_on_one_chat_with(user_id),276
(None, None) => None,277
}278
}279
280
pub fn call_back_from_history(&mut self, row: &CallRow, cx: &mut Context<Self>) {281
let Some(user_id) = row.user_id.as_deref() else {282
return;283
};284
match self.one_on_one_chat_with(user_id) {285
Some(chat_id) => self.start_chat_call(&chat_id, cx),286
None => self.raise_notice(NO_CHAT_NOTICE.to_owned(), None, cx),287
}288
}289
290
pub fn open_chat_of_call_row(&mut self, row: &CallRow, cx: &mut Context<Self>) {291
let notice = if row.meeting {292
NO_MEETING_CHAT_NOTICE293
} else {294
NO_CHAT_NOTICE295
};296
match self.chat_of_call_row(row) {297
Some(chat_id) => self.select(Selection::Chat(chat_id), cx),298
None => self.raise_notice(notice.to_owned(), None, cx),299
}300
}301
302
pub fn activate_call_row(&mut self, row: &CallRow, cx: &mut Context<Self>) {303
if row.meeting {304
self.open_chat_of_call_row(row, cx);305
} else {306
self.call_back_from_history(row, cx);307
}308
}309
310
pub fn can_open_chat_of_call_row(&self, row: &CallRow) -> bool {311
self.chat_of_call_row(row).is_some()312
}313
}314
315
#[cfg(test)]316
mod tests {317
use chrono::TimeZone;318
use store::MemberRecord;319
320
use super::*;321
322
fn entry(direction: CallDirection, outcome: CallOutcome, seconds: Option<i64>) -> CallLogEntry {323
CallLogEntry {324
call_id: "c".into(),325
started_at: Utc.with_ymd_and_hms(2026, 10, 9, 8, 0, 0).unwrap(),326
duration_seconds: seconds,327
direction,328
outcome,329
is_meeting: false,330
peer_id: Some("8:orgid:bea-id".into()),331
peer_name: None,332
thread_id: None,333
}334
}335
336
fn chat(id: &str, kind: &str, title: &str, members: &[(&str, &str)]) -> ChatRecord {337
ChatRecord {338
id: id.into(),339
kind: kind.into(),340
title: title.into(),341
members: members342
.iter()343
.map(|(user_id, name)| MemberRecord {344
user_id: Some((*user_id).to_owned()),345
display_name: (*name).to_owned(),346
})347
.collect(),348
..Default::default()349
}350
}351
352
fn rows(entries: &[CallLogEntry], chats: &[ChatRecord]) -> Vec<CallRow> {353
let now = Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap();354
call_rows(entries, chats, now, FixedOffset::east_opt(0).unwrap())355
}356
357
#[test]358
fn durations_show_seconds_only_for_short_calls() {359
assert_eq!(duration_label(45), "45s");360
assert_eq!(duration_label(252), "4m 12s");361
assert_eq!(duration_label(240), "4m");362
assert_eq!(duration_label(720), "12m");363
assert_eq!(duration_label(2280), "38m");364
assert_eq!(duration_label(3600), "1h");365
assert_eq!(duration_label(3900), "1h 5m");366
}367
368
#[test]369
fn sublines_follow_direction_and_outcome() {370
let missed = entry(CallDirection::Incoming, CallOutcome::Missed, None);371
assert_eq!(subline(&missed), "Missed call");372
let outgoing = entry(CallDirection::Outgoing, CallOutcome::Accepted, Some(252));373
assert_eq!(subline(&outgoing), "Outgoing \u{b7} 4m 12s");374
let incoming = entry(CallDirection::Incoming, CallOutcome::Accepted, Some(720));375
assert_eq!(subline(&incoming), "Incoming \u{b7} 12m");376
let declined = entry(CallDirection::Incoming, CallOutcome::Declined, None);377
assert_eq!(subline(&declined), "Declined call");378
let unanswered = entry(CallDirection::Outgoing, CallOutcome::Missed, None);379
assert_eq!(subline(&unanswered), "Outgoing");380
let meeting = CallLogEntry {381
is_meeting: true,382
..entry(CallDirection::Incoming, CallOutcome::Accepted, Some(2280))383
};384
assert_eq!(subline(&meeting), "Meeting \u{b7} 38m");385
}386
387
#[test]388
fn a_missing_display_name_comes_from_the_chat_members() {389
let chats = [chat("19:a", "oneOnOne", "", &[("bea-id", "Bea")])];390
let list = rows(391
&[entry(392
CallDirection::Outgoing,393
CallOutcome::Accepted,394
Some(60),395
)],396
&chats,397
);398
assert_eq!(list[0].title, "Bea");399
assert_eq!(list[0].user_id.as_deref(), Some("bea-id"));400
let unknown = rows(401
&[entry(402
CallDirection::Outgoing,403
CallOutcome::Accepted,404
Some(60),405
)],406
&[],407
);408
assert_eq!(unknown[0].title, "Unknown");409
}410
411
#[test]412
fn a_meeting_takes_the_meeting_chat_title() {413
let chats = [chat("19:meeting_x", "meeting", "Sprint retro", &[])];414
let meeting = CallLogEntry {415
is_meeting: true,416
thread_id: Some("19:meeting_x".into()),417
..entry(CallDirection::Incoming, CallOutcome::Accepted, Some(60))418
};419
let list = rows(std::slice::from_ref(&meeting), &chats);420
assert_eq!(list[0].title, "Sprint retro");421
assert_eq!(list[0].thread_id.as_deref(), Some("19:meeting_x"));422
assert_eq!(list[0].user_id, None);423
assert_eq!(rows(&[meeting], &[])[0].title, "Meeting");424
}425
426
#[test]427
fn rows_carry_the_chat_list_time_label_and_the_missed_flag() {428
let missed = entry(CallDirection::Incoming, CallOutcome::Missed, None);429
let list = rows(&[missed], &[]);430
assert_eq!(list[0].time_label, "08:00");431
assert!(list[0].missed);432
}433
434
#[test]435
fn the_demo_history_has_every_kind_of_row() {436
let log = demo_call_log(Utc::now());437
assert!(log.iter().any(CallLogEntry::missed));438
assert!(439
log.iter()440
.any(|entry| entry.direction == CallDirection::Outgoing)441
);442
assert!(log.iter().any(|entry| entry.is_meeting));443
assert!(444
log.iter()445
.any(|entry| entry.direction == CallDirection::Incoming446
&& entry.outcome == CallOutcome::Accepted447
&& !entry.is_meeting)448
);449
}450
}@@ -0,0 +1,126 @@
1
use calling::{CallSpec, MeetingTarget};
2
use gpui_kit::*;
3
use teams_core::{
4
MeetingCode, MeetingLink, ThreadMeeting, find_meeting_link, meeting_code_from_id,
5
parse_meeting_link,
6
};
7
8
use super::actions::{MEETING_UNAVAILABLE_NOTICE, NOT_CONNECTED_NOTICE};
9
use super::demo::{DemoCall, demo_guests};
10
use super::model::CallModel;
11
use crate::app_state::{AppState, selection_title};
12
use crate::notify::selection_for;
13
use crate::runtime;
14
15
const NO_LINK_NOTICE: &str = "No Teams meeting link in the clipboard";
16
const NOT_FOUND_NOTICE: &str = "Could not find that meeting";
17
const BAD_ID_MESSAGE: &str = "Enter the meeting ID from the invitation.";
18
const DEMO_GUEST_COUNT: usize = 4;
19
const DEMO_CODE_THREAD: &str = "19:meeting_demo@thread.v2";
20
const MEETING_TITLE: &str = "Meeting";
21
22
pub fn meeting_target(meeting: &ThreadMeeting) -> MeetingTarget {
23
MeetingTarget {
24
thread_id: meeting.thread_id.clone(),
25
tenant_id: meeting.tenant_id.clone(),
26
organizer_id: meeting.organizer_id.clone(),
27
meeting_data: None,
28
}
29
}
30
31
impl AppState {
32
fn join_resolved_meeting(&mut self, target: MeetingTarget, cx: &mut Context<Self>) {
33
if self.call.is_some() {
34
self.show_call(true, cx);
35
return;
36
}
37
let title = selection_for(&self.sidebar, &target.thread_id)
38
.map(|selection| selection_title(&self.sidebar, &selection))
39
.unwrap_or_else(|| MEETING_TITLE.to_owned());
40
let organizer = self
41
.directory
42
.me
43
.as_ref()
44
.is_some_and(|me| me.user_id.eq_ignore_ascii_case(&target.organizer_id));
45
let thread_id = target.thread_id.clone();
46
let demo = DemoCall::Meeting {
47
guests: demo_guests(DEMO_GUEST_COUNT),
48
lobby: false,
49
organizer: false,
50
};
51
let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, cx) else {
52
return;
53
};
54
self.begin_call(
55
handle,
56
CallModel::meeting(&title, organizer),
57
Some(thread_id),
58
cx,
59
);
60
}
61
62
fn join_meeting_code(&mut self, code: MeetingCode, cx: &mut Context<Self>) {
63
if self.call.is_some() {
64
self.show_call(true, cx);
65
return;
66
}
67
let meeting_data = code.meeting_data();
68
if self.mode.demo {
69
let target = MeetingTarget {
70
thread_id: DEMO_CODE_THREAD.to_owned(),
71
tenant_id: "demo-tenant".to_owned(),
72
organizer_id: "demo-organizer".to_owned(),
73
meeting_data: Some(meeting_data),
74
};
75
self.join_resolved_meeting(target, cx);
76
return;
77
}
78
let Some(launcher) = self.call_launcher.clone() else {
79
self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);
80
return;
81
};
82
let receiver = runtime::spawn(async move { launcher.resolve_meeting(&meeting_data).await });
83
cx.spawn(async move |this, cx| {
84
let resolved = receiver.await.ok().and_then(Result::ok);
85
this.update(cx, |state, cx| match resolved {
86
Some(target) => state.join_resolved_meeting(target, cx),
87
None => state.raise_notice(NOT_FOUND_NOTICE.to_owned(), None, cx),
88
})
89
.ok();
90
})
91
.detach();
92
}
93
94
pub fn join_meeting_link(&mut self, text: &str, cx: &mut Context<Self>) {
95
match parse_meeting_link(text) {
96
Some(MeetingLink::Thread(meeting)) => {
97
self.join_resolved_meeting(meeting_target(&meeting), cx)
98
}
99
Some(MeetingLink::Code(code)) => self.join_meeting_code(code, cx),
100
None => self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx),
101
}
102
}
103
104
pub fn join_meeting_from_clipboard(&mut self, cx: &mut Context<Self>) {
105
let link = cx
106
.read_from_clipboard()
107
.and_then(|item| item.text())
108
.and_then(|text| find_meeting_link(&text));
109
match link {
110
Some((url, _)) => self.join_meeting_link(&url, cx),
111
None => self.raise_notice(NO_LINK_NOTICE.to_owned(), None, cx),
112
}
113
}
114
115
pub fn join_meeting_by_id(
116
&mut self,
117
meeting_id: &str,
118
passcode: &str,
119
cx: &mut Context<Self>,
120
) -> Result<(), String> {
121
let code =
122
meeting_code_from_id(meeting_id, passcode).ok_or_else(|| BAD_ID_MESSAGE.to_owned())?;
123
self.join_meeting_code(code, cx);
124
Ok(())
125
}
126
}
@@ -0,0 +1,126 @@1
use calling::{CallSpec, MeetingTarget};2
use gpui_kit::*;3
use teams_core::{4
MeetingCode, MeetingLink, ThreadMeeting, find_meeting_link, meeting_code_from_id,5
parse_meeting_link,6
};7
8
use super::actions::{MEETING_UNAVAILABLE_NOTICE, NOT_CONNECTED_NOTICE};9
use super::demo::{DemoCall, demo_guests};10
use super::model::CallModel;11
use crate::app_state::{AppState, selection_title};12
use crate::notify::selection_for;13
use crate::runtime;14
15
const NO_LINK_NOTICE: &str = "No Teams meeting link in the clipboard";16
const NOT_FOUND_NOTICE: &str = "Could not find that meeting";17
const BAD_ID_MESSAGE: &str = "Enter the meeting ID from the invitation.";18
const DEMO_GUEST_COUNT: usize = 4;19
const DEMO_CODE_THREAD: &str = "19:meeting_demo@thread.v2";20
const MEETING_TITLE: &str = "Meeting";21
22
pub fn meeting_target(meeting: &ThreadMeeting) -> MeetingTarget {23
MeetingTarget {24
thread_id: meeting.thread_id.clone(),25
tenant_id: meeting.tenant_id.clone(),26
organizer_id: meeting.organizer_id.clone(),27
meeting_data: None,28
}29
}30
31
impl AppState {32
fn join_resolved_meeting(&mut self, target: MeetingTarget, cx: &mut Context<Self>) {33
if self.call.is_some() {34
self.show_call(true, cx);35
return;36
}37
let title = selection_for(&self.sidebar, &target.thread_id)38
.map(|selection| selection_title(&self.sidebar, &selection))39
.unwrap_or_else(|| MEETING_TITLE.to_owned());40
let organizer = self41
.directory42
.me43
.as_ref()44
.is_some_and(|me| me.user_id.eq_ignore_ascii_case(&target.organizer_id));45
let thread_id = target.thread_id.clone();46
let demo = DemoCall::Meeting {47
guests: demo_guests(DEMO_GUEST_COUNT),48
lobby: false,49
organizer: false,50
};51
let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, cx) else {52
return;53
};54
self.begin_call(55
handle,56
CallModel::meeting(&title, organizer),57
Some(thread_id),58
cx,59
);60
}61
62
fn join_meeting_code(&mut self, code: MeetingCode, cx: &mut Context<Self>) {63
if self.call.is_some() {64
self.show_call(true, cx);65
return;66
}67
let meeting_data = code.meeting_data();68
if self.mode.demo {69
let target = MeetingTarget {70
thread_id: DEMO_CODE_THREAD.to_owned(),71
tenant_id: "demo-tenant".to_owned(),72
organizer_id: "demo-organizer".to_owned(),73
meeting_data: Some(meeting_data),74
};75
self.join_resolved_meeting(target, cx);76
return;77
}78
let Some(launcher) = self.call_launcher.clone() else {79
self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);80
return;81
};82
let receiver = runtime::spawn(async move { launcher.resolve_meeting(&meeting_data).await });83
cx.spawn(async move |this, cx| {84
let resolved = receiver.await.ok().and_then(Result::ok);85
this.update(cx, |state, cx| match resolved {86
Some(target) => state.join_resolved_meeting(target, cx),87
None => state.raise_notice(NOT_FOUND_NOTICE.to_owned(), None, cx),88
})89
.ok();90
})91
.detach();92
}93
94
pub fn join_meeting_link(&mut self, text: &str, cx: &mut Context<Self>) {95
match parse_meeting_link(text) {96
Some(MeetingLink::Thread(meeting)) => {97
self.join_resolved_meeting(meeting_target(&meeting), cx)98
}99
Some(MeetingLink::Code(code)) => self.join_meeting_code(code, cx),100
None => self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx),101
}102
}103
104
pub fn join_meeting_from_clipboard(&mut self, cx: &mut Context<Self>) {105
let link = cx106
.read_from_clipboard()107
.and_then(|item| item.text())108
.and_then(|text| find_meeting_link(&text));109
match link {110
Some((url, _)) => self.join_meeting_link(&url, cx),111
None => self.raise_notice(NO_LINK_NOTICE.to_owned(), None, cx),112
}113
}114
115
pub fn join_meeting_by_id(116
&mut self,117
meeting_id: &str,118
passcode: &str,119
cx: &mut Context<Self>,120
) -> Result<(), String> {121
let code =122
meeting_code_from_id(meeting_id, passcode).ok_or_else(|| BAD_ID_MESSAGE.to_owned())?;123
self.join_meeting_code(code, cx);124
Ok(())125
}126
}@@ -4,7 +4,7 @@ use std::time::Duration;
4
4
5
5
use calling::meeting::{LiveMeeting, fetch_live_meeting};
6
6
use calling::{
7
CallEngine, CallHandle, CallSpec, CallState, CallUpdate, EndReason, EngineConfig, EngineEvent, call_channel,
7
AcceptMode, BackgroundCache, CallEngine, CallHandle, CallSpec, CallState, CallUpdate, DefaultBackground, EndReason, EngineConfig, EngineEvent, MeetingTarget, call_channel,
8
8
};
9
9
use session::{Session, SessionConfig, Transport};
10
10
@@ -49,8 +49,15 @@ impl CallLauncher {
49
49
}
50
50
}
51
51
52
pub async fn accept_ring(&self, ring_id: u64) -> Option<CallHandle> {
53
self.engine()?.accept_ring(ring_id).await
52
pub fn start_consult(&self, spec: CallSpec) -> CallHandle {
53
match self.engine() {
54
Some(engine) => engine.start_consult(spec),
55
None => failed_handle(NOT_READY),
56
}
57
}
58
59
pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {
60
self.engine()?.accept_ring(ring_id, mode).await
54
61
}
55
62
56
63
pub fn decline_ring(&self, ring_id: u64) {
@@ -65,6 +72,28 @@ impl CallLauncher {
65
72
}
66
73
}
67
74
75
pub async fn refresh_backgrounds(&self, cache: &BackgroundCache, thumbnails: usize) -> Option<Vec<DefaultBackground>> {
76
let session = self.engine()?.session();
77
let catalog = cache.refresh_catalog(&session).await.ok()?;
78
for image in catalog.iter().take(thumbnails) {
79
let _ = cache.ensure_thumbnail(&session, image).await;
80
}
81
Some(catalog)
82
}
83
84
pub async fn download_background(&self, cache: &BackgroundCache, image: &DefaultBackground) -> Option<std::path::PathBuf> {
85
let session = self.engine()?.session();
86
cache.ensure_image(&session, image).await.ok()
87
}
88
89
pub async fn resolve_meeting(&self, meeting_data: &serde_json::Value) -> Result<MeetingTarget, String> {
90
self.engine()
91
.ok_or_else(|| NOT_READY.to_owned())?
92
.resolve_meeting(meeting_data)
93
.await
94
.map_err(|error| error.to_string())
95
}
96
68
97
pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {
69
98
let session = self.engine()?.session();
70
99
fetch_live_meeting(&session, thread_id).await.ok().flatten()
@@ -4,7 +4,7 @@ use std::time::Duration;4
4
5
use calling::meeting::{LiveMeeting, fetch_live_meeting};5
use calling::meeting::{LiveMeeting, fetch_live_meeting};6
use calling::{6
use calling::{7
CallEngine, CallHandle, CallSpec, CallState, CallUpdate, EndReason, EngineConfig, EngineEvent, call_channel,7
AcceptMode, BackgroundCache, CallEngine, CallHandle, CallSpec, CallState, CallUpdate, DefaultBackground, EndReason, EngineConfig, EngineEvent, MeetingTarget, call_channel,8
};8
};9
use session::{Session, SessionConfig, Transport};9
use session::{Session, SessionConfig, Transport};10
10
@@ -49,8 +49,15 @@ impl CallLauncher {49
}49
}50
}50
}51
51
52
pub async fn accept_ring(&self, ring_id: u64) -> Option<CallHandle> {52
pub fn start_consult(&self, spec: CallSpec) -> CallHandle {53
self.engine()?.accept_ring(ring_id).await53
match self.engine() {54
Some(engine) => engine.start_consult(spec),55
None => failed_handle(NOT_READY),56
}57
}58
59
pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {60
self.engine()?.accept_ring(ring_id, mode).await54
}61
}55
62
56
pub fn decline_ring(&self, ring_id: u64) {63
pub fn decline_ring(&self, ring_id: u64) {@@ -65,6 +72,28 @@ impl CallLauncher {65
}72
}66
}73
}67
74
75
pub async fn refresh_backgrounds(&self, cache: &BackgroundCache, thumbnails: usize) -> Option<Vec<DefaultBackground>> {76
let session = self.engine()?.session();77
let catalog = cache.refresh_catalog(&session).await.ok()?;78
for image in catalog.iter().take(thumbnails) {79
let _ = cache.ensure_thumbnail(&session, image).await;80
}81
Some(catalog)82
}83
84
pub async fn download_background(&self, cache: &BackgroundCache, image: &DefaultBackground) -> Option<std::path::PathBuf> {85
let session = self.engine()?.session();86
cache.ensure_image(&session, image).await.ok()87
}88
89
pub async fn resolve_meeting(&self, meeting_data: &serde_json::Value) -> Result<MeetingTarget, String> {90
self.engine()91
.ok_or_else(|| NOT_READY.to_owned())?92
.resolve_meeting(meeting_data)93
.await94
.map_err(|error| error.to_string())95
}96
68
pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {97
pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {69
let session = self.engine()?.session();98
let session = self.engine()?.session();70
fetch_live_meeting(&session, thread_id).await.ok().flatten()99
fetch_live_meeting(&session, thread_id).await.ok().flatten()@@ -1,17 +1,25 @@
1
1
mod actions;
2
mod background;
2
3
mod demo;
3
4
mod demo_scene;
5
mod features;
6
mod history;
7
mod join;
4
8
mod launcher;
5
9
mod model;
6
10
mod pictures;
7
11
mod ring;
8
12
mod target;
9
13
10
pub use actions::{load_background_blur, load_share_sound};
14
pub use actions::load_share_sound;
15
pub use background::{BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background, load_custom_backgrounds};
16
pub use features::TransferCandidate;
17
pub use demo::DemoScene;
18
pub use history::{CallRow, call_rows};
11
19
pub use launcher::CallLauncher;
12
20
pub use model::{
13
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState, grid_layout,
14
tile_size,
21
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,
22
grid_layout, tile_size,
15
23
};
16
24
pub use ring::{MissedCall, RingEntry, Rings};
17
25
pub use target::plan_for_chat;
@@ -1,17 +1,25 @@1
mod actions;1
mod actions;2
mod background;2
mod demo;3
mod demo;3
mod demo_scene;4
mod demo_scene;5
mod features;6
mod history;7
mod join;4
mod launcher;8
mod launcher;5
mod model;9
mod model;6
mod pictures;10
mod pictures;7
mod ring;11
mod ring;8
mod target;12
mod target;9
13
10
pub use actions::{load_background_blur, load_share_sound};14
pub use actions::load_share_sound;15
pub use background::{BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background, load_custom_backgrounds};16
pub use features::TransferCandidate;17
pub use demo::DemoScene;18
pub use history::{CallRow, call_rows};11
pub use launcher::CallLauncher;19
pub use launcher::CallLauncher;12
pub use model::{20
pub use model::{13
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState, grid_layout,21
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,14
tile_size,22
grid_layout, tile_size,15
};23
};16
pub use ring::{MissedCall, RingEntry, Rings};24
pub use ring::{MissedCall, RingEntry, Rings};17
pub use target::plan_for_chat;25
pub use target::plan_for_chat;@@ -2,11 +2,12 @@ use std::sync::Arc;
2
2
use std::time::{Duration, Instant};
3
3
4
4
use calling::{
5
CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, DeviceChoice, DeviceLists, EndKind, EndReason, Progress,
6
Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
5
CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare, DeviceChoice, DeviceLists, EndKind, EndReason,
6
HoldState, MeetingTarget, Progress, Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
7
7
};
8
8
use tokio::sync::mpsc::UnboundedSender;
9
9
10
use super::background::BackgroundPick;
10
11
use super::pictures::CallPictures;
11
12
12
13
pub const TEST_CALL_TITLE: &str = "Test call";
@@ -31,9 +32,63 @@ pub struct ActiveCall {
31
32
pub pictures: CallPictures,
32
33
pub stage_fullscreen: bool,
33
34
pub chat_open: bool,
35
pub meeting_target: Option<MeetingTarget>,
36
pub pending_move: Option<PendingMove>,
37
pub consult: Option<ConsultCall>,
38
}
39
40
#[derive(Debug, Clone, PartialEq)]
41
pub struct PendingMove {
42
pub target: MeetingTarget,
43
pub title: String,
44
pub breakout: Option<BreakoutState>,
45
}
46
47
pub struct ConsultCall {
48
pub id: u64,
49
pub target: (String, String),
50
pub commands: UnboundedSender<CallCommand>,
51
pub state: CallState,
52
pub replacement: Option<String>,
53
pub transferring: bool,
54
}
55
56
impl ConsultCall {
57
pub fn connected(&self) -> bool {
58
matches!(self.state, CallState::Connected { .. })
59
}
60
61
pub fn ready_to_transfer(&self) -> bool {
62
self.connected() && self.replacement.is_some()
63
}
64
65
pub fn status_text(&self) -> String {
66
let name = &self.target.1;
67
match &self.state {
68
CallState::Connected { .. } => format!("Consulting {name}"),
69
_ => format!("Calling {name}..."),
70
}
71
}
34
72
}
35
73
36
74
impl ActiveCall {
75
pub fn new(id: u64, model: CallModel, commands: UnboundedSender<CallCommand>, conversation_id: Option<String>, video: Arc<VideoHub>) -> Self {
76
ActiveCall {
77
id,
78
model,
79
commands,
80
viewing: true,
81
conversation_id,
82
video,
83
pictures: CallPictures::default(),
84
stage_fullscreen: false,
85
chat_open: false,
86
meeting_target: None,
87
pending_move: None,
88
consult: None,
89
}
90
}
91
37
92
pub fn chat_thread(&self) -> Option<&str> {
38
93
chat_thread(self.model.kind, self.model.meeting_chat.as_deref(), self.conversation_id.as_deref())
39
94
}
@@ -91,6 +146,13 @@ impl Tile {
91
146
}
92
147
}
93
148
149
#[derive(Debug, Clone, PartialEq)]
150
pub struct BreakoutState {
151
pub room_name: String,
152
pub main: Option<MeetingTarget>,
153
pub main_title: String,
154
}
155
94
156
#[derive(Debug, Clone, PartialEq, Eq)]
95
157
pub struct Focus {
96
158
pub mri: String,
@@ -199,7 +261,13 @@ pub struct CallModel {
199
261
pub pinned: Option<String>,
200
262
pub captions: CaptionState,
201
263
pub caption_lines: Vec<CaptionLine>,
202
pub blur: bool,
264
pub background: BackgroundPick,
265
pub recording: bool,
266
pub consent_required: bool,
267
pub hold: HoldState,
268
pub whiteboard: Option<ContentShare>,
269
pub breakout: Option<BreakoutState>,
270
pub main_meeting: Option<MeetingTarget>,
203
271
pub reactions: Vec<ReactionChip>,
204
272
reaction_serial: u64,
205
273
pub meeting_chat: Option<String>,
@@ -242,7 +310,13 @@ impl CallModel {
242
310
pinned: None,
243
311
captions: CaptionState::Off,
244
312
caption_lines: Vec::new(),
245
blur: false,
313
background: BackgroundPick::None,
314
recording: false,
315
consent_required: false,
316
hold: HoldState::Active,
317
whiteboard: None,
318
breakout: None,
319
main_meeting: None,
246
320
reactions: Vec::new(),
247
321
reaction_serial: 0,
248
322
meeting_chat: None,
@@ -345,7 +419,16 @@ impl CallModel {
345
419
self.captions = state;
346
420
}
347
421
CallUpdate::Caption(entry) => self.note_caption(entry, Instant::now()),
348
CallUpdate::BlurTiming(_) | CallUpdate::Organizer { .. } => {}
422
CallUpdate::Recording(on) => self.recording = on,
423
CallUpdate::ConsentRequired(required) => self.consent_required = required,
424
CallUpdate::Hold(hold) => self.hold = hold,
425
CallUpdate::Whiteboard(share) => self.whiteboard = share,
426
CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
427
CallUpdate::BlurTiming(_)
428
| CallUpdate::Organizer { .. }
429
| CallUpdate::WhiteboardUrl(_)
430
| CallUpdate::BreakoutMove(_)
431
| CallUpdate::ReplacementLink(_) => {}
349
432
}
350
433
}
351
434
@@ -538,6 +621,42 @@ impl CallModel {
538
621
Some(format!("{name} is sharing"))
539
622
}
540
623
624
pub fn whiteboard_label(&self) -> Option<String> {
625
let share = self.whiteboard.as_ref()?;
626
let name = share
627
.presenter
628
.as_deref()
629
.and_then(|presenter| self.tiles.iter().find(|tile| tile.mri == presenter))
630
.map(|tile| tile.name.as_str())
631
.filter(|name| !name.is_empty())
632
.unwrap_or("Someone");
633
Some(format!("{name} is sharing a whiteboard"))
634
}
635
636
pub fn whiteboard_url(&self) -> Option<&str> {
637
self.whiteboard.as_ref()?.url.as_deref()
638
}
639
640
pub fn is_one_to_one(&self) -> bool {
641
self.kind == CallKind::Direct
642
}
643
644
pub fn can_hold(&self) -> bool {
645
self.is_one_to_one() && self.is_live() && self.hold != HoldState::Remote
646
}
647
648
pub fn can_transfer(&self) -> bool {
649
self.is_one_to_one() && self.is_live() && self.hold == HoldState::Active
650
}
651
652
pub fn can_record(&self) -> bool {
653
self.organizes_meeting() && self.is_live() && !self.lobby
654
}
655
656
pub fn can_open_whiteboard(&self) -> bool {
657
self.kind == CallKind::Meeting && self.is_live() && !self.lobby
658
}
659
541
660
pub fn tile_speaking(&self, tile: &Tile) -> bool {
542
661
if self.speaking_mris.contains(&tile.mri) {
543
662
return true;
@@ -1096,4 +1215,81 @@ mod tests {
1096
1215
model.apply(CallUpdate::Captions(CaptionState::Off));
1097
1216
assert!(model.caption_lines.is_empty() && !model.captions_on());
1098
1217
}
1218
1219
fn one_to_one() -> CallModel {
1220
let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
1221
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1222
model
1223
}
1224
1225
#[test]
1226
fn hold_and_transfer_belong_to_one_to_one_calls_and_follow_the_hold_state() {
1227
let mut model = one_to_one();
1228
assert!(model.can_hold() && model.can_transfer());
1229
model.apply(CallUpdate::Hold(HoldState::Local));
1230
assert!(model.can_hold() && !model.can_transfer());
1231
model.apply(CallUpdate::Hold(HoldState::Remote));
1232
assert!(!model.can_hold() && !model.can_transfer());
1233
let meeting = meeting_with_me();
1234
assert!(!meeting.can_hold() && !meeting.can_transfer());
1235
assert!(!CallModel::people("Group", &[("8:orgid:a".into(), "A".into()), ("8:orgid:b".into(), "B".into())]).can_hold());
1236
}
1237
1238
#[test]
1239
fn recording_and_consent_follow_the_call_updates_and_only_organizers_may_record() {
1240
let mut model = meeting_with_me();
1241
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1242
assert!(!model.can_record());
1243
model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me")]));
1244
assert!(model.can_record());
1245
model.apply(CallUpdate::Recording(true));
1246
model.apply(CallUpdate::ConsentRequired(true));
1247
assert!(model.recording && model.consent_required);
1248
model.apply(CallUpdate::ConsentRequired(false));
1249
assert!(model.recording && !model.consent_required);
1250
model.apply(CallUpdate::Recording(false));
1251
assert!(!model.recording);
1252
}
1253
1254
#[test]
1255
fn a_whiteboard_share_names_the_presenter_and_offers_the_browser_only_with_a_link() {
1256
let mut model = meeting_with_me();
1257
model.apply(CallUpdate::Roster(vec![entry("8:orgid:ana", "Ana", false, false)]));
1258
assert_eq!(model.whiteboard_label(), None);
1259
let share = |presenter: &str, url: Option<&str>| calling::ContentShare {
1260
session_id: "s".into(),
1261
presenter: Some(presenter.into()),
1262
subject: "Whiteboard".into(),
1263
url: url.map(str::to_owned),
1264
whiteboard: true,
1265
};
1266
model.apply(CallUpdate::Whiteboard(Some(share("8:orgid:ana", Some("https://app.whiteboard.microsoft.com/x")))));
1267
assert_eq!(model.whiteboard_label().as_deref(), Some("Ana is sharing a whiteboard"));
1268
assert_eq!(model.whiteboard_url(), Some("https://app.whiteboard.microsoft.com/x"));
1269
model.apply(CallUpdate::Whiteboard(Some(share("8:orgid:stranger", None))));
1270
assert_eq!(model.whiteboard_label().as_deref(), Some("Someone is sharing a whiteboard"));
1271
assert_eq!(model.whiteboard_url(), None);
1272
model.apply(CallUpdate::Whiteboard(None));
1273
assert_eq!(model.whiteboard_label(), None);
1274
}
1275
1276
#[test]
1277
fn a_consultation_can_transfer_once_connected_with_a_replacement_link() {
1278
let (handle, _control) = calling::call_channel();
1279
let mut consult = ConsultCall {
1280
id: 3,
1281
target: ("8:orgid:ana".into(), "Ana".into()),
1282
commands: handle.commands,
1283
state: CallState::Connecting,
1284
replacement: None,
1285
transferring: false,
1286
};
1287
assert_eq!(consult.status_text(), "Calling Ana...");
1288
assert!(!consult.ready_to_transfer());
1289
consult.state = CallState::Connected { since: Instant::now() };
1290
assert_eq!(consult.status_text(), "Consulting Ana");
1291
assert!(!consult.ready_to_transfer());
1292
consult.replacement = Some("https://cc/replacement".into());
1293
assert!(consult.ready_to_transfer());
1294
}
1099
1295
}
@@ -2,11 +2,12 @@ use std::sync::Arc;2
use std::time::{Duration, Instant};2
use std::time::{Duration, Instant};3
3
4
use calling::{4
use calling::{5
CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, DeviceChoice, DeviceLists, EndKind, EndReason, Progress,5
CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare, DeviceChoice, DeviceLists, EndKind, EndReason,6
Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,6
HoldState, MeetingTarget, Progress, Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,7
};7
};8
use tokio::sync::mpsc::UnboundedSender;8
use tokio::sync::mpsc::UnboundedSender;9
9
10
use super::background::BackgroundPick;10
use super::pictures::CallPictures;11
use super::pictures::CallPictures;11
12
12
pub const TEST_CALL_TITLE: &str = "Test call";13
pub const TEST_CALL_TITLE: &str = "Test call";@@ -31,9 +32,63 @@ pub struct ActiveCall {31
pub pictures: CallPictures,32
pub pictures: CallPictures,32
pub stage_fullscreen: bool,33
pub stage_fullscreen: bool,33
pub chat_open: bool,34
pub chat_open: bool,35
pub meeting_target: Option<MeetingTarget>,36
pub pending_move: Option<PendingMove>,37
pub consult: Option<ConsultCall>,38
}39
40
#[derive(Debug, Clone, PartialEq)]41
pub struct PendingMove {42
pub target: MeetingTarget,43
pub title: String,44
pub breakout: Option<BreakoutState>,45
}46
47
pub struct ConsultCall {48
pub id: u64,49
pub target: (String, String),50
pub commands: UnboundedSender<CallCommand>,51
pub state: CallState,52
pub replacement: Option<String>,53
pub transferring: bool,54
}55
56
impl ConsultCall {57
pub fn connected(&self) -> bool {58
matches!(self.state, CallState::Connected { .. })59
}60
61
pub fn ready_to_transfer(&self) -> bool {62
self.connected() && self.replacement.is_some()63
}64
65
pub fn status_text(&self) -> String {66
let name = &self.target.1;67
match &self.state {68
CallState::Connected { .. } => format!("Consulting {name}"),69
_ => format!("Calling {name}..."),70
}71
}34
}72
}35
73
36
impl ActiveCall {74
impl ActiveCall {75
pub fn new(id: u64, model: CallModel, commands: UnboundedSender<CallCommand>, conversation_id: Option<String>, video: Arc<VideoHub>) -> Self {76
ActiveCall {77
id,78
model,79
commands,80
viewing: true,81
conversation_id,82
video,83
pictures: CallPictures::default(),84
stage_fullscreen: false,85
chat_open: false,86
meeting_target: None,87
pending_move: None,88
consult: None,89
}90
}91
37
pub fn chat_thread(&self) -> Option<&str> {92
pub fn chat_thread(&self) -> Option<&str> {38
chat_thread(self.model.kind, self.model.meeting_chat.as_deref(), self.conversation_id.as_deref())93
chat_thread(self.model.kind, self.model.meeting_chat.as_deref(), self.conversation_id.as_deref())39
}94
}@@ -91,6 +146,13 @@ impl Tile {91
}146
}92
}147
}93
148
149
#[derive(Debug, Clone, PartialEq)]150
pub struct BreakoutState {151
pub room_name: String,152
pub main: Option<MeetingTarget>,153
pub main_title: String,154
}155
94
#[derive(Debug, Clone, PartialEq, Eq)]156
#[derive(Debug, Clone, PartialEq, Eq)]95
pub struct Focus {157
pub struct Focus {96
pub mri: String,158
pub mri: String,@@ -199,7 +261,13 @@ pub struct CallModel {199
pub pinned: Option<String>,261
pub pinned: Option<String>,200
pub captions: CaptionState,262
pub captions: CaptionState,201
pub caption_lines: Vec<CaptionLine>,263
pub caption_lines: Vec<CaptionLine>,202
pub blur: bool,264
pub background: BackgroundPick,265
pub recording: bool,266
pub consent_required: bool,267
pub hold: HoldState,268
pub whiteboard: Option<ContentShare>,269
pub breakout: Option<BreakoutState>,270
pub main_meeting: Option<MeetingTarget>,203
pub reactions: Vec<ReactionChip>,271
pub reactions: Vec<ReactionChip>,204
reaction_serial: u64,272
reaction_serial: u64,205
pub meeting_chat: Option<String>,273
pub meeting_chat: Option<String>,@@ -242,7 +310,13 @@ impl CallModel {242
pinned: None,310
pinned: None,243
captions: CaptionState::Off,311
captions: CaptionState::Off,244
caption_lines: Vec::new(),312
caption_lines: Vec::new(),245
blur: false,313
background: BackgroundPick::None,314
recording: false,315
consent_required: false,316
hold: HoldState::Active,317
whiteboard: None,318
breakout: None,319
main_meeting: None,246
reactions: Vec::new(),320
reactions: Vec::new(),247
reaction_serial: 0,321
reaction_serial: 0,248
meeting_chat: None,322
meeting_chat: None,@@ -345,7 +419,16 @@ impl CallModel {345
self.captions = state;419
self.captions = state;346
}420
}347
CallUpdate::Caption(entry) => self.note_caption(entry, Instant::now()),421
CallUpdate::Caption(entry) => self.note_caption(entry, Instant::now()),348
CallUpdate::BlurTiming(_) | CallUpdate::Organizer { .. } => {}422
CallUpdate::Recording(on) => self.recording = on,423
CallUpdate::ConsentRequired(required) => self.consent_required = required,424
CallUpdate::Hold(hold) => self.hold = hold,425
CallUpdate::Whiteboard(share) => self.whiteboard = share,426
CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),427
CallUpdate::BlurTiming(_)428
| CallUpdate::Organizer { .. }429
| CallUpdate::WhiteboardUrl(_)430
| CallUpdate::BreakoutMove(_)431
| CallUpdate::ReplacementLink(_) => {}349
}432
}350
}433
}351
434
@@ -538,6 +621,42 @@ impl CallModel {538
Some(format!("{name} is sharing"))621
Some(format!("{name} is sharing"))539
}622
}540
623
624
pub fn whiteboard_label(&self) -> Option<String> {625
let share = self.whiteboard.as_ref()?;626
let name = share627
.presenter628
.as_deref()629
.and_then(|presenter| self.tiles.iter().find(|tile| tile.mri == presenter))630
.map(|tile| tile.name.as_str())631
.filter(|name| !name.is_empty())632
.unwrap_or("Someone");633
Some(format!("{name} is sharing a whiteboard"))634
}635
636
pub fn whiteboard_url(&self) -> Option<&str> {637
self.whiteboard.as_ref()?.url.as_deref()638
}639
640
pub fn is_one_to_one(&self) -> bool {641
self.kind == CallKind::Direct642
}643
644
pub fn can_hold(&self) -> bool {645
self.is_one_to_one() && self.is_live() && self.hold != HoldState::Remote646
}647
648
pub fn can_transfer(&self) -> bool {649
self.is_one_to_one() && self.is_live() && self.hold == HoldState::Active650
}651
652
pub fn can_record(&self) -> bool {653
self.organizes_meeting() && self.is_live() && !self.lobby654
}655
656
pub fn can_open_whiteboard(&self) -> bool {657
self.kind == CallKind::Meeting && self.is_live() && !self.lobby658
}659
541
pub fn tile_speaking(&self, tile: &Tile) -> bool {660
pub fn tile_speaking(&self, tile: &Tile) -> bool {542
if self.speaking_mris.contains(&tile.mri) {661
if self.speaking_mris.contains(&tile.mri) {543
return true;662
return true;@@ -1096,4 +1215,81 @@ mod tests {1096
model.apply(CallUpdate::Captions(CaptionState::Off));1215
model.apply(CallUpdate::Captions(CaptionState::Off));1097
assert!(model.caption_lines.is_empty() && !model.captions_on());1216
assert!(model.caption_lines.is_empty() && !model.captions_on());1098
}1217
}1218
1219
fn one_to_one() -> CallModel {1220
let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);1221
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1222
model1223
}1224
1225
#[test]1226
fn hold_and_transfer_belong_to_one_to_one_calls_and_follow_the_hold_state() {1227
let mut model = one_to_one();1228
assert!(model.can_hold() && model.can_transfer());1229
model.apply(CallUpdate::Hold(HoldState::Local));1230
assert!(model.can_hold() && !model.can_transfer());1231
model.apply(CallUpdate::Hold(HoldState::Remote));1232
assert!(!model.can_hold() && !model.can_transfer());1233
let meeting = meeting_with_me();1234
assert!(!meeting.can_hold() && !meeting.can_transfer());1235
assert!(!CallModel::people("Group", &[("8:orgid:a".into(), "A".into()), ("8:orgid:b".into(), "B".into())]).can_hold());1236
}1237
1238
#[test]1239
fn recording_and_consent_follow_the_call_updates_and_only_organizers_may_record() {1240
let mut model = meeting_with_me();1241
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1242
assert!(!model.can_record());1243
model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me")]));1244
assert!(model.can_record());1245
model.apply(CallUpdate::Recording(true));1246
model.apply(CallUpdate::ConsentRequired(true));1247
assert!(model.recording && model.consent_required);1248
model.apply(CallUpdate::ConsentRequired(false));1249
assert!(model.recording && !model.consent_required);1250
model.apply(CallUpdate::Recording(false));1251
assert!(!model.recording);1252
}1253
1254
#[test]1255
fn a_whiteboard_share_names_the_presenter_and_offers_the_browser_only_with_a_link() {1256
let mut model = meeting_with_me();1257
model.apply(CallUpdate::Roster(vec![entry("8:orgid:ana", "Ana", false, false)]));1258
assert_eq!(model.whiteboard_label(), None);1259
let share = |presenter: &str, url: Option<&str>| calling::ContentShare {1260
session_id: "s".into(),1261
presenter: Some(presenter.into()),1262
subject: "Whiteboard".into(),1263
url: url.map(str::to_owned),1264
whiteboard: true,1265
};1266
model.apply(CallUpdate::Whiteboard(Some(share("8:orgid:ana", Some("https://app.whiteboard.microsoft.com/x")))));1267
assert_eq!(model.whiteboard_label().as_deref(), Some("Ana is sharing a whiteboard"));1268
assert_eq!(model.whiteboard_url(), Some("https://app.whiteboard.microsoft.com/x"));1269
model.apply(CallUpdate::Whiteboard(Some(share("8:orgid:stranger", None))));1270
assert_eq!(model.whiteboard_label().as_deref(), Some("Someone is sharing a whiteboard"));1271
assert_eq!(model.whiteboard_url(), None);1272
model.apply(CallUpdate::Whiteboard(None));1273
assert_eq!(model.whiteboard_label(), None);1274
}1275
1276
#[test]1277
fn a_consultation_can_transfer_once_connected_with_a_replacement_link() {1278
let (handle, _control) = calling::call_channel();1279
let mut consult = ConsultCall {1280
id: 3,1281
target: ("8:orgid:ana".into(), "Ana".into()),1282
commands: handle.commands,1283
state: CallState::Connecting,1284
replacement: None,1285
transferring: false,1286
};1287
assert_eq!(consult.status_text(), "Calling Ana...");1288
assert!(!consult.ready_to_transfer());1289
consult.state = CallState::Connected { since: Instant::now() };1290
assert_eq!(consult.status_text(), "Consulting Ana");1291
assert!(!consult.ready_to_transfer());1292
consult.replacement = Some("https://cc/replacement".into());1293
assert!(consult.ready_to_transfer());1294
}1099
}1295
}@@ -23,14 +23,14 @@ impl RingEntry {
23
23
24
24
pub fn subtitle(&self) -> &'static str {
25
25
match (self.ring.video, self.ring.is_group) {
26
(true, _) => "Incoming call",
26
(true, _) => "Incoming video call",
27
27
(false, true) => "Incoming group audio call",
28
28
(false, false) => "Incoming audio call",
29
29
}
30
30
}
31
31
32
32
pub fn accept_label(&self) -> &'static str {
33
if self.ring.video { "Accept with audio" } else { "Accept" }
33
if self.ring.video { "Audio" } else { "Accept" }
34
34
}
35
35
}
36
36
@@ -203,13 +203,13 @@ mod tests {
203
203
}
204
204
205
205
#[test]
206
fn video_calls_offer_accept_with_audio() {
206
fn video_calls_offer_audio_and_video_answers() {
207
207
let audio = RingEntry { ring: ring(1, false), state: RingState::start(Instant::now()), demo: false };
208
208
let video = RingEntry { ring: ring(2, true), ..audio.clone() };
209
209
assert_eq!(audio.subtitle(), "Incoming audio call");
210
210
assert_eq!(audio.accept_label(), "Accept");
211
assert_eq!(video.subtitle(), "Incoming call");
212
assert_eq!(video.accept_label(), "Accept with audio");
211
assert_eq!(video.subtitle(), "Incoming video call");
212
assert_eq!(video.accept_label(), "Audio");
213
213
assert_eq!(audio.caller_user_id().as_deref(), Some("caller"));
214
214
}
215
215
@@ -23,14 +23,14 @@ impl RingEntry {23
23
24
pub fn subtitle(&self) -> &'static str {24
pub fn subtitle(&self) -> &'static str {25
match (self.ring.video, self.ring.is_group) {25
match (self.ring.video, self.ring.is_group) {26
(true, _) => "Incoming call",26
(true, _) => "Incoming video call",27
(false, true) => "Incoming group audio call",27
(false, true) => "Incoming group audio call",28
(false, false) => "Incoming audio call",28
(false, false) => "Incoming audio call",29
}29
}30
}30
}31
31
32
pub fn accept_label(&self) -> &'static str {32
pub fn accept_label(&self) -> &'static str {33
if self.ring.video { "Accept with audio" } else { "Accept" }33
if self.ring.video { "Audio" } else { "Accept" }34
}34
}35
}35
}36
36
@@ -203,13 +203,13 @@ mod tests {203
}203
}204
204
205
#[test]205
#[test]206
fn video_calls_offer_accept_with_audio() {206
fn video_calls_offer_audio_and_video_answers() {207
let audio = RingEntry { ring: ring(1, false), state: RingState::start(Instant::now()), demo: false };207
let audio = RingEntry { ring: ring(1, false), state: RingState::start(Instant::now()), demo: false };208
let video = RingEntry { ring: ring(2, true), ..audio.clone() };208
let video = RingEntry { ring: ring(2, true), ..audio.clone() };209
assert_eq!(audio.subtitle(), "Incoming audio call");209
assert_eq!(audio.subtitle(), "Incoming audio call");210
assert_eq!(audio.accept_label(), "Accept");210
assert_eq!(audio.accept_label(), "Accept");211
assert_eq!(video.subtitle(), "Incoming call");211
assert_eq!(video.subtitle(), "Incoming video call");212
assert_eq!(video.accept_label(), "Accept with audio");212
assert_eq!(video.accept_label(), "Audio");213
assert_eq!(audio.caller_user_id().as_deref(), Some("caller"));213
assert_eq!(audio.caller_user_id().as_deref(), Some("caller"));214
}214
}215
215
@@ -769,6 +769,7 @@ pub fn seed(store: &Store) {
769
769
let _ = store.upsert_messages(&unread_messages());
770
770
let _ = store.upsert_messages(&channel_messages());
771
771
let _ = store.upsert_messages(&priority_messages());
772
let _ = store.upsert_messages(&meeting_link_messages());
772
773
let _ = store.upsert_messages(&bot_messages());
773
774
}
774
775
@@ -1183,6 +1184,22 @@ fn settings_card() -> serde_json::Value {
1183
1184
})
1184
1185
}
1185
1186
1187
const DEMO_MEETING_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZGVtbw%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-mara%22%7d";
1188
1189
fn meeting_link_messages() -> Vec<MessageRecord> {
1190
let mara = (MARA_ID, "Mara Lindqvist");
1191
vec![message(
1192
"demo-chat-mara",
1193
"ml1",
1194
None,
1195
mara,
1196
at(0, 13, 38),
1197
&format!("<p>Let's sync live, here is the meeting: <a href=\"{DEMO_MEETING_LINK}\">Join the Teams meeting</a></p>"),
1198
"[]",
1199
false,
1200
)]
1201
}
1202
1186
1203
fn priority_messages() -> Vec<MessageRecord> {
1187
1204
let priya = (PRIYA_ID, "Priya Nair");
1188
1205
let me = (DEMO_USER_ID, DEMO_USER_NAME);
@@ -769,6 +769,7 @@ pub fn seed(store: &Store) {769
let _ = store.upsert_messages(&unread_messages());769
let _ = store.upsert_messages(&unread_messages());770
let _ = store.upsert_messages(&channel_messages());770
let _ = store.upsert_messages(&channel_messages());771
let _ = store.upsert_messages(&priority_messages());771
let _ = store.upsert_messages(&priority_messages());772
let _ = store.upsert_messages(&meeting_link_messages());772
let _ = store.upsert_messages(&bot_messages());773
let _ = store.upsert_messages(&bot_messages());773
}774
}774
775
@@ -1183,6 +1184,22 @@ fn settings_card() -> serde_json::Value {1183
})1184
})1184
}1185
}1185
1186
1187
const DEMO_MEETING_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZGVtbw%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-mara%22%7d";1188
1189
fn meeting_link_messages() -> Vec<MessageRecord> {1190
let mara = (MARA_ID, "Mara Lindqvist");1191
vec![message(1192
"demo-chat-mara",1193
"ml1",1194
None,1195
mara,1196
at(0, 13, 38),1197
&format!("<p>Let's sync live, here is the meeting: <a href=\"{DEMO_MEETING_LINK}\">Join the Teams meeting</a></p>"),1198
"[]",1199
false,1200
)]1201
}1202
1186
fn priority_messages() -> Vec<MessageRecord> {1203
fn priority_messages() -> Vec<MessageRecord> {1187
let priya = (PRIYA_ID, "Priya Nair");1204
let priya = (PRIYA_ID, "Priya Nair");1188
let me = (DEMO_USER_ID, DEMO_USER_NAME);1205
let me = (DEMO_USER_ID, DEMO_USER_NAME);@@ -22,6 +22,7 @@ use super::text::describe;
22
22
use super::ring_view::RingView;
23
23
use super::toast::{PillView, ToastView};
24
24
use crate::app_state::{AppEvent, AppState, Selection};
25
use crate::call::DemoScene;
25
26
use crate::data::{self, Directory, PresenceKind};
26
27
use crate::runtime;
27
28
use crate::single_instance;
@@ -31,6 +32,9 @@ const SLIDE_DURATION: Duration = Duration::from_millis(180);
31
32
const SLIDE_DISTANCE: f32 = 48.;
32
33
const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);
33
34
const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING";
35
const DEMO_RING_KIND_ENV: &str = "TEAMS_DEMO_RING_KIND";
36
const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL";
37
const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);
34
38
35
39
struct OpenWindow {
36
40
handle: AnyWindowHandle,
@@ -120,17 +124,34 @@ impl NotificationCenter {
120
124
})
121
125
.detach();
122
126
if center.app.read(cx).mode.demo {
123
cx.spawn(async move |this, cx| {
124
cx.background_executor().timer(DEMO_SPEC_DELAY).await;
125
this.update(cx, |center, cx| center.show_demo_toasts(cx))
126
.ok();
127
})
128
.detach();
127
if demo_scene().is_none() {
128
cx.spawn(async move |this, cx| {
129
cx.background_executor().timer(DEMO_SPEC_DELAY).await;
130
this.update(cx, |center, cx| center.show_demo_toasts(cx))
131
.ok();
132
})
133
.detach();
134
}
129
135
if let Some(delay) = demo_ring_delay() {
130
136
let app = center.app.clone();
137
let video = std::env::var(DEMO_RING_KIND_ENV).is_ok_and(|kind| kind.trim() == "video");
131
138
cx.spawn(async move |_, cx| {
132
139
cx.background_executor().timer(delay).await;
133
app.update(cx, |state, cx| state.demo_incoming_ring(cx));
140
app.update(cx, |state, cx| {
141
if video {
142
state.demo_incoming_video_ring(cx)
143
} else {
144
state.demo_incoming_ring(cx)
145
}
146
});
147
})
148
.detach();
149
}
150
if let Some(scene) = demo_scene() {
151
let app = center.app.clone();
152
cx.spawn(async move |_, cx| {
153
cx.background_executor().timer(DEMO_SCENE_DELAY).await;
154
app.update(cx, |state, cx| state.start_demo_scene(scene, cx));
134
155
})
135
156
.detach();
136
157
}
@@ -902,6 +923,10 @@ fn open_popup<V: Render>(
902
923
});
903
924
}
904
925
926
fn demo_scene() -> Option<DemoScene> {
927
DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
928
}
929
905
930
/// `TEAMS_DEMO_RING=<seconds>` rings a fake incoming call that long after the demo starts.
906
931
fn demo_ring_delay() -> Option<Duration> {
907
932
let seconds: f32 = std::env::var(DEMO_RING_ENV).ok()?.trim().parse().ok()?;
@@ -22,6 +22,7 @@ use super::text::describe;22
use super::ring_view::RingView;22
use super::ring_view::RingView;23
use super::toast::{PillView, ToastView};23
use super::toast::{PillView, ToastView};24
use crate::app_state::{AppEvent, AppState, Selection};24
use crate::app_state::{AppEvent, AppState, Selection};25
use crate::call::DemoScene;25
use crate::data::{self, Directory, PresenceKind};26
use crate::data::{self, Directory, PresenceKind};26
use crate::runtime;27
use crate::runtime;27
use crate::single_instance;28
use crate::single_instance;@@ -31,6 +32,9 @@ const SLIDE_DURATION: Duration = Duration::from_millis(180);31
const SLIDE_DISTANCE: f32 = 48.;32
const SLIDE_DISTANCE: f32 = 48.;32
const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);33
const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);33
const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING";34
const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING";35
const DEMO_RING_KIND_ENV: &str = "TEAMS_DEMO_RING_KIND";36
const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL";37
const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);34
38
35
struct OpenWindow {39
struct OpenWindow {36
handle: AnyWindowHandle,40
handle: AnyWindowHandle,@@ -120,17 +124,34 @@ impl NotificationCenter {120
})124
})121
.detach();125
.detach();122
if center.app.read(cx).mode.demo {126
if center.app.read(cx).mode.demo {123
cx.spawn(async move |this, cx| {127
if demo_scene().is_none() {124
cx.background_executor().timer(DEMO_SPEC_DELAY).await;128
cx.spawn(async move |this, cx| {125
this.update(cx, |center, cx| center.show_demo_toasts(cx))129
cx.background_executor().timer(DEMO_SPEC_DELAY).await;126
.ok();130
this.update(cx, |center, cx| center.show_demo_toasts(cx))127
})131
.ok();128
.detach();132
})133
.detach();134
}129
if let Some(delay) = demo_ring_delay() {135
if let Some(delay) = demo_ring_delay() {130
let app = center.app.clone();136
let app = center.app.clone();137
let video = std::env::var(DEMO_RING_KIND_ENV).is_ok_and(|kind| kind.trim() == "video");131
cx.spawn(async move |_, cx| {138
cx.spawn(async move |_, cx| {132
cx.background_executor().timer(delay).await;139
cx.background_executor().timer(delay).await;133
app.update(cx, |state, cx| state.demo_incoming_ring(cx));140
app.update(cx, |state, cx| {141
if video {142
state.demo_incoming_video_ring(cx)143
} else {144
state.demo_incoming_ring(cx)145
}146
});147
})148
.detach();149
}150
if let Some(scene) = demo_scene() {151
let app = center.app.clone();152
cx.spawn(async move |_, cx| {153
cx.background_executor().timer(DEMO_SCENE_DELAY).await;154
app.update(cx, |state, cx| state.start_demo_scene(scene, cx));134
})155
})135
.detach();156
.detach();136
}157
}@@ -902,6 +923,10 @@ fn open_popup<V: Render>(902
});923
});903
}924
}904
925
926
fn demo_scene() -> Option<DemoScene> {927
DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)928
}929
905
/// `TEAMS_DEMO_RING=<seconds>` rings a fake incoming call that long after the demo starts.930
/// `TEAMS_DEMO_RING=<seconds>` rings a fake incoming call that long after the demo starts.906
fn demo_ring_delay() -> Option<Duration> {931
fn demo_ring_delay() -> Option<Duration> {907
let seconds: f32 = std::env::var(DEMO_RING_ENV).ok()?.trim().parse().ok()?;932
let seconds: f32 = std::env::var(DEMO_RING_ENV).ok()?.trim().parse().ok()?;@@ -1,3 +1,4 @@
1
use calling::AcceptMode;
1
2
use gpui_kit::assets::IconName;
2
3
use gpui_kit::component::{h_flex, v_flex};
3
4
use gpui_kit::prelude::FluentBuilder as _;
@@ -42,8 +43,8 @@ fn answer_button(id: &'static str, label: &str, glyph: IconName, fill: Hsla) ->
42
43
h_flex()
43
44
.id(id)
44
45
.h(px(BUTTON_HEIGHT))
45
.px(px(14.))
46
.gap(px(6.))
46
.px(px(10.))
47
.gap(px(5.))
47
48
.flex_none()
48
49
.items_center()
49
50
.justify_center()
@@ -95,9 +96,16 @@ impl Render for RingView {
95
96
let accept = answer_button("ring-accept", entry.accept_label(), IconName::Phone, theme::green()).on_click(
96
97
move |_, _, cx| {
97
98
cx.stop_propagation();
98
accept_app.update(cx, |state, cx| state.accept_ring(ring_id, cx));
99
accept_app.update(cx, |state, cx| state.accept_ring(ring_id, AcceptMode::Audio, cx));
99
100
},
100
101
);
102
let video_app = self.app.clone();
103
let accept_video = entry.ring.video.then(|| {
104
answer_button("ring-accept-video", "Video", IconName::Video, theme::green()).on_click(move |_, _, cx| {
105
cx.stop_propagation();
106
video_app.update(cx, |state, cx| state.accept_ring(ring_id, AcceptMode::Video, cx));
107
})
108
});
101
109
div()
102
110
.id(("ring", ring_id))
103
111
.size_full()
@@ -140,7 +148,7 @@ impl Render for RingView {
140
148
.child(ENDS_CURRENT_CALL),
141
149
)
142
150
})
143
.child(h_flex().mt(px(8.)).gap(px(8.)).child(decline).child(accept)),
151
.child(h_flex().mt(px(8.)).gap(px(6.)).child(decline).child(accept).children(accept_video)),
144
152
),
145
153
),
146
154
)
@@ -1,3 +1,4 @@1
use calling::AcceptMode;1
use gpui_kit::assets::IconName;2
use gpui_kit::assets::IconName;2
use gpui_kit::component::{h_flex, v_flex};3
use gpui_kit::component::{h_flex, v_flex};3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::prelude::FluentBuilder as _;@@ -42,8 +43,8 @@ fn answer_button(id: &'static str, label: &str, glyph: IconName, fill: Hsla) ->42
h_flex()43
h_flex()43
.id(id)44
.id(id)44
.h(px(BUTTON_HEIGHT))45
.h(px(BUTTON_HEIGHT))45
.px(px(14.))46
.px(px(10.))46
.gap(px(6.))47
.gap(px(5.))47
.flex_none()48
.flex_none()48
.items_center()49
.items_center()49
.justify_center()50
.justify_center()@@ -95,9 +96,16 @@ impl Render for RingView {95
let accept = answer_button("ring-accept", entry.accept_label(), IconName::Phone, theme::green()).on_click(96
let accept = answer_button("ring-accept", entry.accept_label(), IconName::Phone, theme::green()).on_click(96
move |_, _, cx| {97
move |_, _, cx| {97
cx.stop_propagation();98
cx.stop_propagation();98
accept_app.update(cx, |state, cx| state.accept_ring(ring_id, cx));99
accept_app.update(cx, |state, cx| state.accept_ring(ring_id, AcceptMode::Audio, cx));99
},100
},100
);101
);102
let video_app = self.app.clone();103
let accept_video = entry.ring.video.then(|| {104
answer_button("ring-accept-video", "Video", IconName::Video, theme::green()).on_click(move |_, _, cx| {105
cx.stop_propagation();106
video_app.update(cx, |state, cx| state.accept_ring(ring_id, AcceptMode::Video, cx));107
})108
});101
div()109
div()102
.id(("ring", ring_id))110
.id(("ring", ring_id))103
.size_full()111
.size_full()@@ -140,7 +148,7 @@ impl Render for RingView {140
.child(ENDS_CURRENT_CALL),148
.child(ENDS_CURRENT_CALL),141
)149
)142
})150
})143
.child(h_flex().mt(px(8.)).gap(px(8.)).child(decline).child(accept)),151
.child(h_flex().mt(px(8.)).gap(px(6.)).child(decline).child(accept).children(accept_video)),144
),152
),145
),153
),146
)154
)@@ -53,6 +53,7 @@ pub fn pending_row(
53
53
.collect(),
54
54
adaptive_cards: Vec::new(),
55
55
link_preview: outgoing.link_preview.clone(),
56
meeting_link: teams_core::meeting_link_in_html(&outgoing.html()),
56
57
files: outgoing
57
58
.files
58
59
.iter()
@@ -53,6 +53,7 @@ pub fn pending_row(53
.collect(),53
.collect(),54
adaptive_cards: Vec::new(),54
adaptive_cards: Vec::new(),55
link_preview: outgoing.link_preview.clone(),55
link_preview: outgoing.link_preview.clone(),56
meeting_link: teams_core::meeting_link_in_html(&outgoing.html()),56
files: outgoing57
files: outgoing57
.files58
.files58
.iter()59
.iter()@@ -7,8 +7,8 @@ use gpui_kit::Image;
7
7
use store::MessageRecord;
8
8
use teams_core::{
9
9
AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,
10
card_texts, files, images, link_preview, linked_message_spans, message_spans, reactions,
11
translated_spans,
10
card_texts, files, images, link_preview, linked_message_spans, meeting_link_in_html,
11
message_spans, reactions, translated_spans,
12
12
};
13
13
14
14
use crate::card_state::CardOverride;
@@ -138,6 +138,7 @@ pub struct MessageRow {
138
138
pub local_images: Vec<LocalImage>,
139
139
pub files: Vec<FileCard>,
140
140
pub link_preview: Option<LinkPreview>,
141
pub meeting_link: Option<String>,
141
142
pub adaptive_cards: Vec<AdaptiveCard>,
142
143
pub subject: Option<String>,
143
144
pub new_marker: bool,
@@ -565,6 +566,9 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
565
566
local_images: Vec::new(),
566
567
files: files(record),
567
568
link_preview: link_preview(record),
569
meeting_link: (!record.deleted)
570
.then(|| meeting_link_in_html(&record.body_html))
571
.flatten(),
568
572
adaptive_cards: match context.card_overrides.get(&record.message_id) {
569
573
Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
570
574
_ => adaptive_cards(record),
@@ -7,8 +7,8 @@ use gpui_kit::Image;7
use store::MessageRecord;7
use store::MessageRecord;8
use teams_core::{8
use teams_core::{9
AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,9
AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,10
card_texts, files, images, link_preview, linked_message_spans, message_spans, reactions,10
card_texts, files, images, link_preview, linked_message_spans, meeting_link_in_html,11
translated_spans,11
message_spans, reactions, translated_spans,12
};12
};13
13
14
use crate::card_state::CardOverride;14
use crate::card_state::CardOverride;@@ -138,6 +138,7 @@ pub struct MessageRow {138
pub local_images: Vec<LocalImage>,138
pub local_images: Vec<LocalImage>,139
pub files: Vec<FileCard>,139
pub files: Vec<FileCard>,140
pub link_preview: Option<LinkPreview>,140
pub link_preview: Option<LinkPreview>,141
pub meeting_link: Option<String>,141
pub adaptive_cards: Vec<AdaptiveCard>,142
pub adaptive_cards: Vec<AdaptiveCard>,142
pub subject: Option<String>,143
pub subject: Option<String>,143
pub new_marker: bool,144
pub new_marker: bool,@@ -565,6 +566,9 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {565
local_images: Vec::new(),566
local_images: Vec::new(),566
files: files(record),567
files: files(record),567
link_preview: link_preview(record),568
link_preview: link_preview(record),569
meeting_link: (!record.deleted)570
.then(|| meeting_link_in_html(&record.body_html))571
.flatten(),568
adaptive_cards: match context.card_overrides.get(&record.message_id) {572
adaptive_cards: match context.card_overrides.get(&record.message_id) {569
Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),573
Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),570
_ => adaptive_cards(record),574
_ => adaptive_cards(record),@@ -0,0 +1,306 @@
1
use std::path::PathBuf;
2
3
use calling::HoldState;
4
use gpui_kit::assets::IconName;
5
use gpui_kit::component::button::{Button, ButtonVariants as _};
6
use gpui_kit::component::dialog::DialogFooter;
7
use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
8
use gpui_kit::component::tooltip::Tooltip;
9
use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
10
use gpui_kit::*;
11
12
use super::call_organizer::pill;
13
use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
14
use super::transfer_picker::TransferPicker;
15
use super::widgets::icon;
16
use crate::app_state::AppState;
17
use crate::call::{BackgroundPick, CallModel};
18
use crate::theme;
19
20
const STAGE_RADIUS: f32 = 12.;
21
const THUMBNAIL_WIDTH: f32 = 64.;
22
const THUMBNAIL_HEIGHT: f32 = 36.;
23
const THUMBNAIL_GAP: f32 = 6.;
24
const MENU_PADDING: f32 = 24.;
25
const BACKDROP_OPACITY: f32 = 0.55;
26
const CARD_WIDTH: f32 = 420.;
27
28
fn dark_text() -> Hsla {
29
hsla(0., 0., 0.08, 1.)
30
}
31
32
pub fn recording_chip(model: &CallModel) -> Option<AnyElement> {
33
model.recording.then(|| {
34
h_flex()
35
.id("call-recording")
36
.flex_none()
37
.gap(px(6.))
38
.items_center()
39
.text_size(px(13.))
40
.font_weight(FontWeight::SEMIBOLD)
41
.text_color(theme::red())
42
.child(div().size(px(9.)).rounded_full().bg(theme::red()))
43
.child("Recording")
44
.into_any_element()
45
})
46
}
47
48
pub fn return_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
49
model.breakout.as_ref().filter(|room| room.main.is_some())?;
50
let app = app.clone();
51
Some(
52
Button::new("call-return-main")
53
.label("Return to main meeting")
54
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.return_to_main_meeting(cx)))
55
.into_any_element(),
56
)
57
}
58
59
pub fn room_chip(model: &CallModel) -> Option<AnyElement> {
60
model.breakout.as_ref()?;
61
Some(div().flex_none().text_size(px(13.)).text_color(theme::text_muted()).child("Breakout room").into_any_element())
62
}
63
64
pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
65
let (title, detail) = match model.hold {
66
HoldState::Active => return None,
67
HoldState::Local => ("On hold".to_owned(), format!("{} cannot hear you and you cannot hear them.", model.peer_name)),
68
HoldState::Remote => ("You're on hold".to_owned(), format!("{} put the call on hold.", model.peer_name)),
69
};
70
let resume = (model.hold == HoldState::Local).then(|| {
71
let app = app.clone();
72
Button::new("call-resume").label("Resume").on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_hold(cx)))
73
});
74
Some(
75
v_flex()
76
.id("call-hold")
77
.flex_1()
78
.min_h_0()
79
.items_center()
80
.justify_center()
81
.gap(px(14.))
82
.child(
83
div()
84
.size(px(96.))
85
.flex()
86
.items_center()
87
.justify_center()
88
.rounded_full()
89
.bg(theme::surface_raised())
90
.child(icon(IconName::Clock, 48., theme::text())),
91
)
92
.child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child(title))
93
.child(div().text_size(px(14.)).text_color(theme::text_muted()).child(detail))
94
.children(resume)
95
.into_any_element(),
96
)
97
}
98
99
pub fn whiteboard_stage(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
100
let label = model.whiteboard_label()?;
101
let open = model.whiteboard_url().is_some().then(|| {
102
let app = app.clone();
103
Button::new("call-whiteboard-open")
104
.label("Open in browser")
105
.icon(IconName::ExternalLink)
106
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.open_call_whiteboard(cx)))
107
});
108
Some(
109
v_flex()
110
.id("call-whiteboard-stage")
111
.flex_1()
112
.min_w_0()
113
.h_full()
114
.items_center()
115
.justify_center()
116
.gap(px(14.))
117
.rounded(px(STAGE_RADIUS))
118
.bg(hsla(0., 0., 0.04, 1.))
119
.text_color(theme::white())
120
.child(icon(IconName::Pencil, 56., theme::white()))
121
.child(div().text_size(px(18.)).font_weight(FontWeight::SEMIBOLD).child(label))
122
.children(open)
123
.into_any_element(),
124
)
125
}
126
127
pub fn consult_banner(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
128
let consult = state.call.as_ref()?.consult.as_ref()?;
129
let text = consult.status_text();
130
let ready = consult.ready_to_transfer();
131
let (transfer_app, cancel_app) = (app.clone(), app.clone());
132
let transfer = pill("call-consult-transfer", "Transfer now", true);
133
let transfer = if ready {
134
transfer.on_click(move |_, _, cx| transfer_app.update(cx, |state, cx| state.transfer_consulted(cx)))
135
} else {
136
transfer.opacity(0.5).cursor_default()
137
};
138
Some(
139
h_flex()
140
.id("call-consult-banner")
141
.w_full()
142
.h(px(BANNER_HEIGHT))
143
.flex_none()
144
.px(px(20.))
145
.gap(px(12.))
146
.items_center()
147
.justify_center()
148
.bg(theme::amber())
149
.text_color(dark_text())
150
.text_size(px(13.))
151
.font_weight(FontWeight::SEMIBOLD)
152
.child(text)
153
.child(transfer)
154
.child(pill("call-consult-cancel", "Cancel", false).on_click(move |_, _, cx| cancel_app.update(cx, |state, cx| state.cancel_consult(cx))))
155
.into_any_element(),
156
)
157
}
158
159
pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
160
if !model.consent_required {
161
return None;
162
}
163
let app = app.clone();
164
Some(
165
div()
166
.id("call-consent-layer")
167
.absolute()
168
.top_0()
169
.left_0()
170
.size_full()
171
.flex()
172
.items_center()
173
.justify_center()
174
.child(div().id("call-consent-backdrop").absolute().top_0().left_0().size_full().bg(black().opacity(BACKDROP_OPACITY)).occlude())
175
.child(
176
v_flex()
177
.id("call-consent-card")
178
.w(px(CARD_WIDTH))
179
.max_w(relative(1.))
180
.p(px(20.))
181
.gap(px(12.))
182
.rounded(px(12.))
183
.bg(theme::background())
184
.border_1()
185
.border_color(theme::border_strong())
186
.text_color(theme::text())
187
.shadow_lg()
188
.occlude()
189
.child(
190
h_flex()
191
.gap(px(8.))
192
.items_center()
193
.child(div().size(px(10.)).rounded_full().bg(theme::red()))
194
.child(div().text_size(px(16.)).font_weight(FontWeight::SEMIBOLD).child("This meeting is being recorded")),
195
)
196
.child(
197
div()
198
.text_size(px(13.))
199
.text_color(theme::text_muted())
200
.child("Your microphone and camera stay off until you accept."),
201
)
202
.child(
203
h_flex().w_full().justify_end().child(
204
Button::new("call-consent-ok")
205
.label("OK")
206
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.accept_recording_notice(cx))),
207
),
208
),
209
)
210
.into_any_element(),
211
)
212
}
213
214
pub fn confirm_stop_recording(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
215
let app = app.clone();
216
window.open_alert_dialog(cx, move |alert, _, _| {
217
let app = app.clone();
218
let cancel = Button::new("recording-cancel").label("Cancel").on_click(|_, window, cx| window.close_dialog(cx));
219
let stop = Button::new("recording-stop").label("Stop").danger().on_click(move |_, window, cx| {
220
app.update(cx, |state, cx| state.set_call_recording(false, cx));
221
window.close_dialog(cx);
222
});
223
alert
224
.title("Stop recording and transcription?")
225
.description("The recording is saved to the organizer's OneDrive and the link arrives in the meeting chat.")
226
.footer(DialogFooter::new().child(cancel).child(stop))
227
.on_ok(|_, _, _| false)
228
});
229
}
230
231
pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
232
let candidates = app.read(cx).transfer_candidates();
233
let picker_app = app.clone();
234
let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, window, cx));
235
app.update(cx, |state, cx| state.open_transfer_picker(picker, cx));
236
}
237
238
#[derive(Clone)]
239
pub struct BackgroundMenu {
240
pub pick: BackgroundPick,
241
pub images: Vec<(String, String, Option<PathBuf>)>,
242
pub customs: Vec<PathBuf>,
243
}
244
245
impl BackgroundMenu {
246
pub fn of(state: &AppState) -> Self {
247
let library = &state.call_backgrounds;
248
BackgroundMenu {
249
pick: state.call_background.clone(),
250
images: library.shown().iter().map(|image| (image.id.clone(), image.name.clone(), library.thumbnail(image))).collect(),
251
customs: library.customs.clone(),
252
}
253
}
254
}
255
256
fn thumbnail(app: &Entity<AppState>, index: usize, label: String, path: Option<PathBuf>, selected: bool, pick: BackgroundPick) -> AnyElement {
257
let app = app.clone();
258
let tooltip = label.clone();
259
div()
260
.id(("call-background", index))
261
.w(px(THUMBNAIL_WIDTH))
262
.h(px(THUMBNAIL_HEIGHT))
263
.flex_none()
264
.overflow_hidden()
265
.rounded(px(6.))
266
.border_2()
267
.border_color(if selected { theme::accent() } else { transparent_black() })
268
.bg(theme::surface())
269
.cursor_pointer()
270
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
271
.child(match path {
272
Some(path) => img(path).size_full().object_fit(ObjectFit::Cover).into_any_element(),
273
None => div().size_full().into_any_element(),
274
})
275
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_background(pick.clone(), cx)))
276
.into_any_element()
277
}
278
279
pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &BackgroundMenu) -> PopupMenu {
280
let (none_app, blur_app, add_app, grid_app) = (app.clone(), app.clone(), app.clone(), app.clone());
281
let grid_menu = menu.clone();
282
let mut popup = popup
283
.separator()
284
.item(PopupMenuItem::label("Background"))
285
.item(PopupMenuItem::new("None").checked(menu.pick == BackgroundPick::None).on_click(move |_, _, cx| none_app.update(cx, |state, cx| state.set_call_background(BackgroundPick::None, cx))))
286
.item(PopupMenuItem::new("Blur").checked(menu.pick.is_blur()).on_click(move |_, _, cx| blur_app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Blur, cx))));
287
if !menu.images.is_empty() || !menu.customs.is_empty() {
288
popup = popup.item(PopupMenuItem::element(move |_, _| {
289
let defaults = grid_menu.images.iter().enumerate().map(|(index, (id, name, path))| {
290
let pick = BackgroundPick::Default(id.clone());
291
thumbnail(&grid_app, index, name.clone(), path.clone(), grid_menu.pick == pick, pick)
292
});
293
let customs = grid_menu.customs.iter().enumerate().map(|(index, path)| {
294
let pick = BackgroundPick::Custom(path.clone());
295
let name = path.file_name().map_or_else(String::new, |name| name.to_string_lossy().into_owned());
296
thumbnail(&grid_app, grid_menu.images.len() + index, name, Some(path.clone()), grid_menu.pick == pick, pick)
297
});
298
h_flex().w(px(MENU_WIDTH - MENU_PADDING)).flex_wrap().gap(px(THUMBNAIL_GAP)).children(defaults.chain(customs))
299
}));
300
}
301
popup.item(
302
PopupMenuItem::new("Add image...")
303
.icon(IconName::Plus)
304
.on_click(move |_, _, cx| add_app.update(cx, |state, cx| state.add_call_background(cx))),
305
)
306
}
@@ -0,0 +1,306 @@1
use std::path::PathBuf;2
3
use calling::HoldState;4
use gpui_kit::assets::IconName;5
use gpui_kit::component::button::{Button, ButtonVariants as _};6
use gpui_kit::component::dialog::DialogFooter;7
use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};8
use gpui_kit::component::tooltip::Tooltip;9
use gpui_kit::component::{WindowExt as _, h_flex, v_flex};10
use gpui_kit::*;11
12
use super::call_organizer::pill;13
use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};14
use super::transfer_picker::TransferPicker;15
use super::widgets::icon;16
use crate::app_state::AppState;17
use crate::call::{BackgroundPick, CallModel};18
use crate::theme;19
20
const STAGE_RADIUS: f32 = 12.;21
const THUMBNAIL_WIDTH: f32 = 64.;22
const THUMBNAIL_HEIGHT: f32 = 36.;23
const THUMBNAIL_GAP: f32 = 6.;24
const MENU_PADDING: f32 = 24.;25
const BACKDROP_OPACITY: f32 = 0.55;26
const CARD_WIDTH: f32 = 420.;27
28
fn dark_text() -> Hsla {29
hsla(0., 0., 0.08, 1.)30
}31
32
pub fn recording_chip(model: &CallModel) -> Option<AnyElement> {33
model.recording.then(|| {34
h_flex()35
.id("call-recording")36
.flex_none()37
.gap(px(6.))38
.items_center()39
.text_size(px(13.))40
.font_weight(FontWeight::SEMIBOLD)41
.text_color(theme::red())42
.child(div().size(px(9.)).rounded_full().bg(theme::red()))43
.child("Recording")44
.into_any_element()45
})46
}47
48
pub fn return_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {49
model.breakout.as_ref().filter(|room| room.main.is_some())?;50
let app = app.clone();51
Some(52
Button::new("call-return-main")53
.label("Return to main meeting")54
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.return_to_main_meeting(cx)))55
.into_any_element(),56
)57
}58
59
pub fn room_chip(model: &CallModel) -> Option<AnyElement> {60
model.breakout.as_ref()?;61
Some(div().flex_none().text_size(px(13.)).text_color(theme::text_muted()).child("Breakout room").into_any_element())62
}63
64
pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {65
let (title, detail) = match model.hold {66
HoldState::Active => return None,67
HoldState::Local => ("On hold".to_owned(), format!("{} cannot hear you and you cannot hear them.", model.peer_name)),68
HoldState::Remote => ("You're on hold".to_owned(), format!("{} put the call on hold.", model.peer_name)),69
};70
let resume = (model.hold == HoldState::Local).then(|| {71
let app = app.clone();72
Button::new("call-resume").label("Resume").on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_hold(cx)))73
});74
Some(75
v_flex()76
.id("call-hold")77
.flex_1()78
.min_h_0()79
.items_center()80
.justify_center()81
.gap(px(14.))82
.child(83
div()84
.size(px(96.))85
.flex()86
.items_center()87
.justify_center()88
.rounded_full()89
.bg(theme::surface_raised())90
.child(icon(IconName::Clock, 48., theme::text())),91
)92
.child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child(title))93
.child(div().text_size(px(14.)).text_color(theme::text_muted()).child(detail))94
.children(resume)95
.into_any_element(),96
)97
}98
99
pub fn whiteboard_stage(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {100
let label = model.whiteboard_label()?;101
let open = model.whiteboard_url().is_some().then(|| {102
let app = app.clone();103
Button::new("call-whiteboard-open")104
.label("Open in browser")105
.icon(IconName::ExternalLink)106
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.open_call_whiteboard(cx)))107
});108
Some(109
v_flex()110
.id("call-whiteboard-stage")111
.flex_1()112
.min_w_0()113
.h_full()114
.items_center()115
.justify_center()116
.gap(px(14.))117
.rounded(px(STAGE_RADIUS))118
.bg(hsla(0., 0., 0.04, 1.))119
.text_color(theme::white())120
.child(icon(IconName::Pencil, 56., theme::white()))121
.child(div().text_size(px(18.)).font_weight(FontWeight::SEMIBOLD).child(label))122
.children(open)123
.into_any_element(),124
)125
}126
127
pub fn consult_banner(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {128
let consult = state.call.as_ref()?.consult.as_ref()?;129
let text = consult.status_text();130
let ready = consult.ready_to_transfer();131
let (transfer_app, cancel_app) = (app.clone(), app.clone());132
let transfer = pill("call-consult-transfer", "Transfer now", true);133
let transfer = if ready {134
transfer.on_click(move |_, _, cx| transfer_app.update(cx, |state, cx| state.transfer_consulted(cx)))135
} else {136
transfer.opacity(0.5).cursor_default()137
};138
Some(139
h_flex()140
.id("call-consult-banner")141
.w_full()142
.h(px(BANNER_HEIGHT))143
.flex_none()144
.px(px(20.))145
.gap(px(12.))146
.items_center()147
.justify_center()148
.bg(theme::amber())149
.text_color(dark_text())150
.text_size(px(13.))151
.font_weight(FontWeight::SEMIBOLD)152
.child(text)153
.child(transfer)154
.child(pill("call-consult-cancel", "Cancel", false).on_click(move |_, _, cx| cancel_app.update(cx, |state, cx| state.cancel_consult(cx))))155
.into_any_element(),156
)157
}158
159
pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {160
if !model.consent_required {161
return None;162
}163
let app = app.clone();164
Some(165
div()166
.id("call-consent-layer")167
.absolute()168
.top_0()169
.left_0()170
.size_full()171
.flex()172
.items_center()173
.justify_center()174
.child(div().id("call-consent-backdrop").absolute().top_0().left_0().size_full().bg(black().opacity(BACKDROP_OPACITY)).occlude())175
.child(176
v_flex()177
.id("call-consent-card")178
.w(px(CARD_WIDTH))179
.max_w(relative(1.))180
.p(px(20.))181
.gap(px(12.))182
.rounded(px(12.))183
.bg(theme::background())184
.border_1()185
.border_color(theme::border_strong())186
.text_color(theme::text())187
.shadow_lg()188
.occlude()189
.child(190
h_flex()191
.gap(px(8.))192
.items_center()193
.child(div().size(px(10.)).rounded_full().bg(theme::red()))194
.child(div().text_size(px(16.)).font_weight(FontWeight::SEMIBOLD).child("This meeting is being recorded")),195
)196
.child(197
div()198
.text_size(px(13.))199
.text_color(theme::text_muted())200
.child("Your microphone and camera stay off until you accept."),201
)202
.child(203
h_flex().w_full().justify_end().child(204
Button::new("call-consent-ok")205
.label("OK")206
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.accept_recording_notice(cx))),207
),208
),209
)210
.into_any_element(),211
)212
}213
214
pub fn confirm_stop_recording(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {215
let app = app.clone();216
window.open_alert_dialog(cx, move |alert, _, _| {217
let app = app.clone();218
let cancel = Button::new("recording-cancel").label("Cancel").on_click(|_, window, cx| window.close_dialog(cx));219
let stop = Button::new("recording-stop").label("Stop").danger().on_click(move |_, window, cx| {220
app.update(cx, |state, cx| state.set_call_recording(false, cx));221
window.close_dialog(cx);222
});223
alert224
.title("Stop recording and transcription?")225
.description("The recording is saved to the organizer's OneDrive and the link arrives in the meeting chat.")226
.footer(DialogFooter::new().child(cancel).child(stop))227
.on_ok(|_, _, _| false)228
});229
}230
231
pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {232
let candidates = app.read(cx).transfer_candidates();233
let picker_app = app.clone();234
let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, window, cx));235
app.update(cx, |state, cx| state.open_transfer_picker(picker, cx));236
}237
238
#[derive(Clone)]239
pub struct BackgroundMenu {240
pub pick: BackgroundPick,241
pub images: Vec<(String, String, Option<PathBuf>)>,242
pub customs: Vec<PathBuf>,243
}244
245
impl BackgroundMenu {246
pub fn of(state: &AppState) -> Self {247
let library = &state.call_backgrounds;248
BackgroundMenu {249
pick: state.call_background.clone(),250
images: library.shown().iter().map(|image| (image.id.clone(), image.name.clone(), library.thumbnail(image))).collect(),251
customs: library.customs.clone(),252
}253
}254
}255
256
fn thumbnail(app: &Entity<AppState>, index: usize, label: String, path: Option<PathBuf>, selected: bool, pick: BackgroundPick) -> AnyElement {257
let app = app.clone();258
let tooltip = label.clone();259
div()260
.id(("call-background", index))261
.w(px(THUMBNAIL_WIDTH))262
.h(px(THUMBNAIL_HEIGHT))263
.flex_none()264
.overflow_hidden()265
.rounded(px(6.))266
.border_2()267
.border_color(if selected { theme::accent() } else { transparent_black() })268
.bg(theme::surface())269
.cursor_pointer()270
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))271
.child(match path {272
Some(path) => img(path).size_full().object_fit(ObjectFit::Cover).into_any_element(),273
None => div().size_full().into_any_element(),274
})275
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_background(pick.clone(), cx)))276
.into_any_element()277
}278
279
pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &BackgroundMenu) -> PopupMenu {280
let (none_app, blur_app, add_app, grid_app) = (app.clone(), app.clone(), app.clone(), app.clone());281
let grid_menu = menu.clone();282
let mut popup = popup283
.separator()284
.item(PopupMenuItem::label("Background"))285
.item(PopupMenuItem::new("None").checked(menu.pick == BackgroundPick::None).on_click(move |_, _, cx| none_app.update(cx, |state, cx| state.set_call_background(BackgroundPick::None, cx))))286
.item(PopupMenuItem::new("Blur").checked(menu.pick.is_blur()).on_click(move |_, _, cx| blur_app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Blur, cx))));287
if !menu.images.is_empty() || !menu.customs.is_empty() {288
popup = popup.item(PopupMenuItem::element(move |_, _| {289
let defaults = grid_menu.images.iter().enumerate().map(|(index, (id, name, path))| {290
let pick = BackgroundPick::Default(id.clone());291
thumbnail(&grid_app, index, name.clone(), path.clone(), grid_menu.pick == pick, pick)292
});293
let customs = grid_menu.customs.iter().enumerate().map(|(index, path)| {294
let pick = BackgroundPick::Custom(path.clone());295
let name = path.file_name().map_or_else(String::new, |name| name.to_string_lossy().into_owned());296
thumbnail(&grid_app, grid_menu.images.len() + index, name, Some(path.clone()), grid_menu.pick == pick, pick)297
});298
h_flex().w(px(MENU_WIDTH - MENU_PADDING)).flex_wrap().gap(px(THUMBNAIL_GAP)).children(defaults.chain(customs))299
}));300
}301
popup.item(302
PopupMenuItem::new("Add image...")303
.icon(IconName::Plus)304
.on_click(move |_, _, cx| add_app.update(cx, |state, cx| state.add_call_background(cx))),305
)306
}@@ -1,7 +1,7 @@
1
1
use std::sync::Arc;
2
2
use std::time::Instant;
3
3
4
use calling::{CaptionState, VideoKey};
4
use calling::{CaptionState, HoldState, VideoKey};
5
5
use gpui_kit::assets::IconName;
6
6
use gpui_kit::component::button::{Button, ButtonVariants as _};
7
7
use gpui_kit::component::dialog::DialogFooter;
@@ -12,6 +12,7 @@ use gpui_kit::prelude::FluentBuilder as _;
12
12
use gpui_kit::*;
13
13
14
14
use super::avatar::person_avatar;
15
use super::call_extras::{BackgroundMenu, background_items, confirm_stop_recording, open_transfer_picker};
15
16
use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};
16
17
use super::widgets::icon;
17
18
use crate::app_state::AppState;
@@ -38,7 +39,7 @@ fn dark_text() -> Hsla {
38
39
hsla(0., 0., 0.08, 1.)
39
40
}
40
41
41
fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool) -> Stateful<Div> {
42
pub(super) fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool) -> Stateful<Div> {
42
43
let (background, foreground) = if filled { (dark_text(), theme::white()) } else { (transparent_black(), dark_text()) };
43
44
div()
44
45
.id(id)
@@ -231,12 +232,11 @@ pub fn with_tile_menu(app: &Entity<AppState>, model: &CallModel, mri: &str, name
231
232
232
233
pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
233
234
let in_meeting = model.kind == crate::call::CallKind::Meeting;
234
if !in_meeting {
235
if !in_meeting && !model.is_one_to_one() {
235
236
return None;
236
237
}
237
let (mute_app, captions_app) = (app.clone(), app.clone());
238
let organizes = model.organizes_meeting();
239
let captions_on = model.captions_on();
238
let app = app.clone();
239
let model = model.clone();
240
240
Some(
241
241
Button::new("call-more")
242
242
.ghost()
@@ -244,27 +244,76 @@ pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEleme
244
244
.size(px(CONTROL_SIZE))
245
245
.rounded_full()
246
246
.child(round_control("call-more-face", IconName::Ellipsis, theme::surface_raised(), theme::text()))
247
.dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
248
let (mute_app, captions_app) = (mute_app.clone(), captions_app.clone());
249
let mut popup = popup.min_w(px(MENU_WIDTH));
250
if organizes {
251
popup = popup.item(
252
PopupMenuItem::new("Mute all")
253
.icon(IconName::MicOff)
254
.on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
255
);
256
}
257
popup.item(
258
PopupMenuItem::new(if captions_on { "Turn off live captions" } else { "Turn on live captions" })
259
.icon(if captions_on { IconName::CaptionsOff } else { IconName::Captions })
260
.on_click(move |_, _, cx| captions_app.update(cx, |state, cx| state.toggle_call_captions(cx))),
261
)
262
})
247
.dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| more_menu(popup, &app, &model))
263
248
.into_any_element(),
264
249
)
265
250
}
266
251
267
pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
252
fn more_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
253
let popup = popup.min_w(px(MENU_WIDTH));
254
if model.is_one_to_one() {
255
return one_to_one_items(popup, app, model);
256
}
257
meeting_items(popup, app, model)
258
}
259
260
fn one_to_one_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
261
let (hold_app, transfer_app) = (app.clone(), app.clone());
262
let held = model.hold == HoldState::Local;
263
popup = popup.item(
264
PopupMenuItem::new(if held { "Resume" } else { "Hold" })
265
.icon(IconName::Timer)
266
.disabled(!held && !model.can_hold())
267
.on_click(move |_, _, cx| hold_app.update(cx, |state, cx| state.toggle_call_hold(cx))),
268
);
269
let can_transfer = model.can_transfer();
270
popup.item(
271
PopupMenuItem::new("Transfer...")
272
.icon(IconName::Forward)
273
.disabled(!can_transfer)
274
.on_click(move |_, window, cx| open_transfer_picker(&transfer_app, window, cx)),
275
)
276
}
277
278
fn meeting_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
279
let (mute_app, captions_app, record_app, board_app) = (app.clone(), app.clone(), app.clone(), app.clone());
280
let captions_on = model.captions_on();
281
if model.organizes_meeting() {
282
popup = popup.item(
283
PopupMenuItem::new("Mute all")
284
.icon(IconName::MicOff)
285
.on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
286
);
287
}
288
if model.can_record() {
289
let recording = model.recording;
290
popup = popup.item(
291
PopupMenuItem::new(if recording { "Stop recording" } else { "Start recording" })
292
.icon(IconName::Video)
293
.on_click(move |_, window, cx| {
294
if recording {
295
confirm_stop_recording(&record_app, window, cx);
296
} else {
297
record_app.update(cx, |state, cx| state.set_call_recording(true, cx));
298
}
299
}),
300
);
301
}
302
if model.can_open_whiteboard() {
303
popup = popup.item(
304
PopupMenuItem::new("Whiteboard")
305
.icon(IconName::Frame)
306
.on_click(move |_, _, cx| board_app.update(cx, |state, cx| state.open_call_whiteboard(cx))),
307
);
308
}
309
popup.item(
310
PopupMenuItem::new(if captions_on { "Turn off live captions" } else { "Turn on live captions" })
311
.icon(if captions_on { IconName::CaptionsOff } else { IconName::Captions })
312
.on_click(move |_, _, cx| captions_app.update(cx, |state, cx| state.toggle_call_captions(cx))),
313
)
314
}
315
316
pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel, backgrounds: BackgroundMenu) -> Option<AnyElement> {
268
317
if !model.can_use_camera() {
269
318
return None;
270
319
}
@@ -287,12 +336,12 @@ pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel) -> Option<A
287
336
.bg(theme::surface_raised())
288
337
.child(icon(IconName::ChevronUp, 16., theme::text())),
289
338
)
290
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model))
339
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model, &backgrounds))
291
340
.into_any_element(),
292
341
)
293
342
}
294
343
295
fn camera_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
344
fn camera_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, backgrounds: &BackgroundMenu) -> PopupMenu {
296
345
let camera_app = app.clone();
297
346
let cameras = super::call_view::device_items(calling::camera_entries(&model.cameras), &model.camera, move |choice, cx| {
298
347
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));
@@ -301,11 +350,7 @@ fn camera_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
301
350
for item in cameras {
302
351
popup = popup.item(item);
303
352
}
304
let (none_app, blur_app) = (app.clone(), app.clone());
305
popup
306
.separator()
307
.item(PopupMenuItem::new("Background: None").checked(!model.blur).on_click(move |_, _, cx| none_app.update(cx, |state, cx| state.set_call_background_blur(false, cx))))
308
.item(PopupMenuItem::new("Background: Blur").checked(model.blur).on_click(move |_, _, cx| blur_app.update(cx, |state, cx| state.set_call_background_blur(true, cx))))
353
background_items(popup, app, backgrounds)
309
354
}
310
355
311
356
pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {
@@ -1,7 +1,7 @@1
use std::sync::Arc;1
use std::sync::Arc;2
use std::time::Instant;2
use std::time::Instant;3
3
4
use calling::{CaptionState, VideoKey};4
use calling::{CaptionState, HoldState, VideoKey};5
use gpui_kit::assets::IconName;5
use gpui_kit::assets::IconName;6
use gpui_kit::component::button::{Button, ButtonVariants as _};6
use gpui_kit::component::button::{Button, ButtonVariants as _};7
use gpui_kit::component::dialog::DialogFooter;7
use gpui_kit::component::dialog::DialogFooter;@@ -12,6 +12,7 @@ use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::*;12
use gpui_kit::*;13
13
14
use super::avatar::person_avatar;14
use super::avatar::person_avatar;15
use super::call_extras::{BackgroundMenu, background_items, confirm_stop_recording, open_transfer_picker};15
use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};16
use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};16
use super::widgets::icon;17
use super::widgets::icon;17
use crate::app_state::AppState;18
use crate::app_state::AppState;@@ -38,7 +39,7 @@ fn dark_text() -> Hsla {38
hsla(0., 0., 0.08, 1.)39
hsla(0., 0., 0.08, 1.)39
}40
}40
41
41
fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool) -> Stateful<Div> {42
pub(super) fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool) -> Stateful<Div> {42
let (background, foreground) = if filled { (dark_text(), theme::white()) } else { (transparent_black(), dark_text()) };43
let (background, foreground) = if filled { (dark_text(), theme::white()) } else { (transparent_black(), dark_text()) };43
div()44
div()44
.id(id)45
.id(id)@@ -231,12 +232,11 @@ pub fn with_tile_menu(app: &Entity<AppState>, model: &CallModel, mri: &str, name231
232
232
pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {233
pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {233
let in_meeting = model.kind == crate::call::CallKind::Meeting;234
let in_meeting = model.kind == crate::call::CallKind::Meeting;234
if !in_meeting {235
if !in_meeting && !model.is_one_to_one() {235
return None;236
return None;236
}237
}237
let (mute_app, captions_app) = (app.clone(), app.clone());238
let app = app.clone();238
let organizes = model.organizes_meeting();239
let model = model.clone();239
let captions_on = model.captions_on();240
Some(240
Some(241
Button::new("call-more")241
Button::new("call-more")242
.ghost()242
.ghost()@@ -244,27 +244,76 @@ pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEleme244
.size(px(CONTROL_SIZE))244
.size(px(CONTROL_SIZE))245
.rounded_full()245
.rounded_full()246
.child(round_control("call-more-face", IconName::Ellipsis, theme::surface_raised(), theme::text()))246
.child(round_control("call-more-face", IconName::Ellipsis, theme::surface_raised(), theme::text()))247
.dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {247
.dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| more_menu(popup, &app, &model))248
let (mute_app, captions_app) = (mute_app.clone(), captions_app.clone());249
let mut popup = popup.min_w(px(MENU_WIDTH));250
if organizes {251
popup = popup.item(252
PopupMenuItem::new("Mute all")253
.icon(IconName::MicOff)254
.on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),255
);256
}257
popup.item(258
PopupMenuItem::new(if captions_on { "Turn off live captions" } else { "Turn on live captions" })259
.icon(if captions_on { IconName::CaptionsOff } else { IconName::Captions })260
.on_click(move |_, _, cx| captions_app.update(cx, |state, cx| state.toggle_call_captions(cx))),261
)262
})263
.into_any_element(),248
.into_any_element(),264
)249
)265
}250
}266
251
267
pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {252
fn more_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {253
let popup = popup.min_w(px(MENU_WIDTH));254
if model.is_one_to_one() {255
return one_to_one_items(popup, app, model);256
}257
meeting_items(popup, app, model)258
}259
260
fn one_to_one_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {261
let (hold_app, transfer_app) = (app.clone(), app.clone());262
let held = model.hold == HoldState::Local;263
popup = popup.item(264
PopupMenuItem::new(if held { "Resume" } else { "Hold" })265
.icon(IconName::Timer)266
.disabled(!held && !model.can_hold())267
.on_click(move |_, _, cx| hold_app.update(cx, |state, cx| state.toggle_call_hold(cx))),268
);269
let can_transfer = model.can_transfer();270
popup.item(271
PopupMenuItem::new("Transfer...")272
.icon(IconName::Forward)273
.disabled(!can_transfer)274
.on_click(move |_, window, cx| open_transfer_picker(&transfer_app, window, cx)),275
)276
}277
278
fn meeting_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {279
let (mute_app, captions_app, record_app, board_app) = (app.clone(), app.clone(), app.clone(), app.clone());280
let captions_on = model.captions_on();281
if model.organizes_meeting() {282
popup = popup.item(283
PopupMenuItem::new("Mute all")284
.icon(IconName::MicOff)285
.on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),286
);287
}288
if model.can_record() {289
let recording = model.recording;290
popup = popup.item(291
PopupMenuItem::new(if recording { "Stop recording" } else { "Start recording" })292
.icon(IconName::Video)293
.on_click(move |_, window, cx| {294
if recording {295
confirm_stop_recording(&record_app, window, cx);296
} else {297
record_app.update(cx, |state, cx| state.set_call_recording(true, cx));298
}299
}),300
);301
}302
if model.can_open_whiteboard() {303
popup = popup.item(304
PopupMenuItem::new("Whiteboard")305
.icon(IconName::Frame)306
.on_click(move |_, _, cx| board_app.update(cx, |state, cx| state.open_call_whiteboard(cx))),307
);308
}309
popup.item(310
PopupMenuItem::new(if captions_on { "Turn off live captions" } else { "Turn on live captions" })311
.icon(if captions_on { IconName::CaptionsOff } else { IconName::Captions })312
.on_click(move |_, _, cx| captions_app.update(cx, |state, cx| state.toggle_call_captions(cx))),313
)314
}315
316
pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel, backgrounds: BackgroundMenu) -> Option<AnyElement> {268
if !model.can_use_camera() {317
if !model.can_use_camera() {269
return None;318
return None;270
}319
}@@ -287,12 +336,12 @@ pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel) -> Option<A287
.bg(theme::surface_raised())336
.bg(theme::surface_raised())288
.child(icon(IconName::ChevronUp, 16., theme::text())),337
.child(icon(IconName::ChevronUp, 16., theme::text())),289
)338
)290
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model))339
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model, &backgrounds))291
.into_any_element(),340
.into_any_element(),292
)341
)293
}342
}294
343
295
fn camera_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {344
fn camera_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, backgrounds: &BackgroundMenu) -> PopupMenu {296
let camera_app = app.clone();345
let camera_app = app.clone();297
let cameras = super::call_view::device_items(calling::camera_entries(&model.cameras), &model.camera, move |choice, cx| {346
let cameras = super::call_view::device_items(calling::camera_entries(&model.cameras), &model.camera, move |choice, cx| {298
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));347
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));@@ -301,11 +350,7 @@ fn camera_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P301
for item in cameras {350
for item in cameras {302
popup = popup.item(item);351
popup = popup.item(item);303
}352
}304
let (none_app, blur_app) = (app.clone(), app.clone());353
background_items(popup, app, backgrounds)305
popup306
.separator()307
.item(PopupMenuItem::new("Background: None").checked(!model.blur).on_click(move |_, _, cx| none_app.update(cx, |state, cx| state.set_call_background_blur(false, cx))))308
.item(PopupMenuItem::new("Background: Blur").checked(model.blur).on_click(move |_, _, cx| blur_app.update(cx, |state, cx| state.set_call_background_blur(true, cx))))309
}354
}310
355
311
pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {356
pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {@@ -16,6 +16,7 @@ use gpui_kit::prelude::FluentBuilder as _;
16
16
use gpui_kit::*;
17
17
18
18
use super::avatar::person_avatar;
19
use super::call_extras::{BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button, room_chip, whiteboard_stage};
19
20
use super::call_organizer::{camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner, more_button, pin_chip, render_focus_stage, spotlight_chip, with_tile_menu};
20
21
use super::call_stage::render_stage;
21
22
use super::conversation::ConversationView;
@@ -699,7 +700,7 @@ fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: Ti
699
700
let video = state
700
701
.call
701
702
.as_ref()
702
.filter(|_| remote.has_video)
703
.filter(|_| remote.has_video || model.is_one_to_one())
703
704
.and_then(|call| call.pictures.live(&VideoKey::Person(remote.mri.clone()), now));
704
705
if let Some(image) = video {
705
706
return video_tile(size, image, &remote.name, model.tile_speaking(remote), remote.muted, extras).into_any_element();
@@ -804,7 +805,11 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
804
805
.font_weight(FontWeight::SEMIBOLD)
805
806
.child(model.title.clone()),
806
807
)
807
.child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status));
808
.child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status))
809
.children(recording_chip(model))
810
.children(room_chip(model))
811
.child(div().flex_1())
812
.children(return_button(app, model));
808
813
809
814
let max_tiles = if chat.is_some() { CHAT_OPEN_TILES } else { MAX_TILES };
810
815
let layout = grid_layout(model.visible_tiles().len(), max_tiles);
@@ -814,7 +819,10 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
814
819
let own_index = model.own_cell_index(cells.len());
815
820
cells.insert(own_index, own_tile(app, state, model, size, now));
816
821
let focus = model.focus().filter(|_| model.screen_sharer.is_none());
817
let stage = render_stage(app, state, false).or_else(|| focus.as_ref().and_then(|focus| render_focus_stage(app, state, focus, now)));
822
let stage = render_stage(app, state, false)
823
.or_else(|| whiteboard_stage(app, model))
824
.or_else(|| focus.as_ref().and_then(|focus| render_focus_stage(app, state, focus, now)));
825
let hold = hold_panel(app, model);
818
826
let focused = focus.as_ref().map(|focus| focus.mri.as_str());
819
827
820
828
let controls = h_flex()
@@ -827,7 +835,7 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
827
835
.border_t_1()
828
836
.border_color(theme::border())
829
837
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))
830
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model)))
838
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model, BackgroundMenu::of(state))))
831
839
.child(share_button(app, model, state.call_share_sound))
832
840
.child(hand_button(app, model))
833
841
.child(reactions_button(app, model))
@@ -846,7 +854,9 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
846
854
.child(header)
847
855
.children(lobby_banner(app, model))
848
856
.children(sharing_banner(app, model, state.call_share_sound))
857
.children(consult_banner(app, state))
849
858
.child(match stage {
859
_ if hold.is_some() => hold.expect("checked above"),
850
860
Some(stage) => h_flex()
851
861
.flex_1()
852
862
.min_h_0()
@@ -872,7 +882,9 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
872
882
})
873
883
.child(controls)
874
884
.children(captions_overlay(model, now))
875
.children(captions_hint_chip(model));
885
.children(captions_hint_chip(model))
886
.children(state.transfer_picker.clone())
887
.children(consent_overlay(app, model));
876
888
Some(
877
889
h_flex()
878
890
.flex_1()
@@ -16,6 +16,7 @@ use gpui_kit::prelude::FluentBuilder as _;16
use gpui_kit::*;16
use gpui_kit::*;17
17
18
use super::avatar::person_avatar;18
use super::avatar::person_avatar;19
use super::call_extras::{BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button, room_chip, whiteboard_stage};19
use super::call_organizer::{camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner, more_button, pin_chip, render_focus_stage, spotlight_chip, with_tile_menu};20
use super::call_organizer::{camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner, more_button, pin_chip, render_focus_stage, spotlight_chip, with_tile_menu};20
use super::call_stage::render_stage;21
use super::call_stage::render_stage;21
use super::conversation::ConversationView;22
use super::conversation::ConversationView;@@ -699,7 +700,7 @@ fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: Ti699
let video = state700
let video = state700
.call701
.call701
.as_ref()702
.as_ref()702
.filter(|_| remote.has_video)703
.filter(|_| remote.has_video || model.is_one_to_one())703
.and_then(|call| call.pictures.live(&VideoKey::Person(remote.mri.clone()), now));704
.and_then(|call| call.pictures.live(&VideoKey::Person(remote.mri.clone()), now));704
if let Some(image) = video {705
if let Some(image) = video {705
return video_tile(size, image, &remote.name, model.tile_speaking(remote), remote.muted, extras).into_any_element();706
return video_tile(size, image, &remote.name, model.tile_speaking(remote), remote.muted, extras).into_any_element();@@ -804,7 +805,11 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E804
.font_weight(FontWeight::SEMIBOLD)805
.font_weight(FontWeight::SEMIBOLD)805
.child(model.title.clone()),806
.child(model.title.clone()),806
)807
)807
.child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status));808
.child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status))809
.children(recording_chip(model))810
.children(room_chip(model))811
.child(div().flex_1())812
.children(return_button(app, model));808
813
809
let max_tiles = if chat.is_some() { CHAT_OPEN_TILES } else { MAX_TILES };814
let max_tiles = if chat.is_some() { CHAT_OPEN_TILES } else { MAX_TILES };810
let layout = grid_layout(model.visible_tiles().len(), max_tiles);815
let layout = grid_layout(model.visible_tiles().len(), max_tiles);@@ -814,7 +819,10 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E814
let own_index = model.own_cell_index(cells.len());819
let own_index = model.own_cell_index(cells.len());815
cells.insert(own_index, own_tile(app, state, model, size, now));820
cells.insert(own_index, own_tile(app, state, model, size, now));816
let focus = model.focus().filter(|_| model.screen_sharer.is_none());821
let focus = model.focus().filter(|_| model.screen_sharer.is_none());817
let stage = render_stage(app, state, false).or_else(|| focus.as_ref().and_then(|focus| render_focus_stage(app, state, focus, now)));822
let stage = render_stage(app, state, false)823
.or_else(|| whiteboard_stage(app, model))824
.or_else(|| focus.as_ref().and_then(|focus| render_focus_stage(app, state, focus, now)));825
let hold = hold_panel(app, model);818
let focused = focus.as_ref().map(|focus| focus.mri.as_str());826
let focused = focus.as_ref().map(|focus| focus.mri.as_str());819
827
820
let controls = h_flex()828
let controls = h_flex()@@ -827,7 +835,7 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E827
.border_t_1()835
.border_t_1()828
.border_color(theme::border())836
.border_color(theme::border())829
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))837
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))830
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model)))838
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model, BackgroundMenu::of(state))))831
.child(share_button(app, model, state.call_share_sound))839
.child(share_button(app, model, state.call_share_sound))832
.child(hand_button(app, model))840
.child(hand_button(app, model))833
.child(reactions_button(app, model))841
.child(reactions_button(app, model))@@ -846,7 +854,9 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E846
.child(header)854
.child(header)847
.children(lobby_banner(app, model))855
.children(lobby_banner(app, model))848
.children(sharing_banner(app, model, state.call_share_sound))856
.children(sharing_banner(app, model, state.call_share_sound))857
.children(consult_banner(app, state))849
.child(match stage {858
.child(match stage {859
_ if hold.is_some() => hold.expect("checked above"),850
Some(stage) => h_flex()860
Some(stage) => h_flex()851
.flex_1()861
.flex_1()852
.min_h_0()862
.min_h_0()@@ -872,7 +882,9 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E872
})882
})873
.child(controls)883
.child(controls)874
.children(captions_overlay(model, now))884
.children(captions_overlay(model, now))875
.children(captions_hint_chip(model));885
.children(captions_hint_chip(model))886
.children(state.transfer_picker.clone())887
.children(consent_overlay(app, model));876
Some(888
Some(877
h_flex()889
h_flex()878
.flex_1()890
.flex_1()@@ -0,0 +1,209 @@
1
use chrono::{Local, Offset, Utc};
2
use gpui_kit::assets::IconName;
3
use gpui_kit::component::Sizable as _;
4
use gpui_kit::component::button::Button;
5
use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6
use gpui_kit::component::{h_flex, v_flex};
7
use gpui_kit::prelude::FluentBuilder as _;
8
use gpui_kit::*;
9
10
use super::avatar::person_avatar;
11
use super::join_dialog::open_join_with_id;
12
use super::widgets::icon;
13
use crate::app_state::AppState;
14
use crate::call::{CallRow, call_rows};
15
use crate::theme;
16
17
const ROW_HEIGHT: f32 = 54.;
18
const AVATAR_SIZE: f32 = 36.;
19
const MENU_ICON_SIZE: f32 = 15.;
20
const EMPTY_TEXT: &str = "No calls yet";
21
22
fn meeting_avatar() -> Div {
23
div()
24
.size(px(AVATAR_SIZE))
25
.flex_none()
26
.flex()
27
.items_center()
28
.justify_center()
29
.rounded_full()
30
.bg(theme::border_strong())
31
.child(icon(IconName::Video, 16., theme::text()))
32
}
33
34
fn call_row(
35
state: &Entity<AppState>,
36
row: &CallRow,
37
can_open_chat: bool,
38
directory: &crate::data::Directory,
39
) -> AnyElement {
40
let avatar = if row.meeting {
41
meeting_avatar().into_any_element()
42
} else {
43
person_avatar(directory, row.user_id.as_deref(), &row.title, AVATAR_SIZE)
44
};
45
let title_color = if row.missed {
46
theme::red_soft()
47
} else {
48
theme::text()
49
};
50
let click_state = state.clone();
51
let click_row = row.clone();
52
let menu_state = state.clone();
53
let menu_row = row.clone();
54
let can_call_back = !row.meeting && row.user_id.is_some();
55
h_flex()
56
.id(SharedString::from(format!("call-{}", row.key)))
57
.mx(px(8.))
58
.h(px(ROW_HEIGHT))
59
.px(px(8.))
60
.gap(px(10.))
61
.items_center()
62
.rounded(px(8.))
63
.cursor_pointer()
64
.hover(|row| row.bg(theme::row_hover()))
65
.child(avatar)
66
.child(
67
v_flex()
68
.flex_1()
69
.min_w_0()
70
.gap(px(2.))
71
.child(
72
h_flex()
73
.gap(px(8.))
74
.items_baseline()
75
.child(
76
div()
77
.flex_1()
78
.min_w_0()
79
.truncate()
80
.text_size(px(14.))
81
.text_color(title_color)
82
.child(row.title.clone()),
83
)
84
.child(
85
div()
86
.flex_none()
87
.text_size(px(11.))
88
.text_color(theme::text_muted())
89
.child(row.time_label.clone()),
90
),
91
)
92
.child(
93
div()
94
.truncate()
95
.text_size(px(12.5))
96
.text_color(if row.missed {
97
theme::red_soft()
98
} else {
99
theme::text_muted()
100
})
101
.child(row.subline.clone()),
102
),
103
)
104
.on_click(move |_, _, cx| {
105
click_state.update(cx, |state, cx| state.activate_call_row(&click_row, cx));
106
})
107
.context_menu(move |popup, _, _| {
108
let call_state = menu_state.clone();
109
let call_row = menu_row.clone();
110
let chat_state = menu_state.clone();
111
let chat_row = menu_row.clone();
112
popup
113
.when(can_call_back, |popup| {
114
popup.item(
115
PopupMenuItem::new("Call back")
116
.icon(icon(IconName::Phone, MENU_ICON_SIZE, theme::text_muted()))
117
.on_click(move |_, _, cx| {
118
call_state.update(cx, |state, cx| {
119
state.call_back_from_history(&call_row, cx)
120
});
121
}),
122
)
123
})
124
.when(can_open_chat, |popup| {
125
popup.item(
126
PopupMenuItem::new("Open chat")
127
.icon(icon(
128
IconName::MessageSquare,
129
MENU_ICON_SIZE,
130
theme::text_muted(),
131
))
132
.on_click(move |_, _, cx| {
133
chat_state.update(cx, |state, cx| {
134
state.open_chat_of_call_row(&chat_row, cx)
135
});
136
}),
137
)
138
})
139
})
140
.into_any_element()
141
}
142
143
fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {
144
let id_state = state.clone();
145
let paste_state = state.clone();
146
h_flex()
147
.w_full()
148
.px(px(12.))
149
.pb(px(8.))
150
.gap(px(8.))
151
.child(
152
Button::new("join-with-id")
153
.small()
154
.label("Join with ID")
155
.on_click(move |_, window, cx| open_join_with_id(id_state.clone(), window, cx)),
156
)
157
.child(
158
Button::new("paste-meeting-link")
159
.small()
160
.label("Paste a meeting link")
161
.on_click(move |_, _, cx| {
162
paste_state.update(cx, |state, cx| state.join_meeting_from_clipboard(cx));
163
}),
164
)
165
}
166
167
pub fn calls_body(state: &Entity<AppState>, scroll: &ScrollHandle, cx: &App) -> AnyElement {
168
let app = state.read(cx);
169
let offset = Local::now().offset().fix();
170
let rows = call_rows(&app.call_history, &app.sidebar.chats, Utc::now(), offset);
171
let list = if rows.is_empty() {
172
div()
173
.w_full()
174
.py(px(24.))
175
.flex()
176
.justify_center()
177
.text_size(px(13.))
178
.text_color(theme::text_muted())
179
.child(EMPTY_TEXT)
180
.into_any_element()
181
} else {
182
v_flex()
183
.w_full()
184
.pb(px(12.))
185
.children(rows.iter().map(|row| {
186
call_row(
187
state,
188
row,
189
app.can_open_chat_of_call_row(row),
190
&app.directory,
191
)
192
}))
193
.into_any_element()
194
};
195
v_flex()
196
.flex_1()
197
.min_h_0()
198
.child(join_buttons(state))
199
.child(
200
div()
201
.id("calls-scroll")
202
.flex_1()
203
.min_h_0()
204
.overflow_y_scroll()
205
.track_scroll(scroll)
206
.child(list),
207
)
208
.into_any_element()
209
}
@@ -0,0 +1,209 @@1
use chrono::{Local, Offset, Utc};2
use gpui_kit::assets::IconName;3
use gpui_kit::component::Sizable as _;4
use gpui_kit::component::button::Button;5
use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};6
use gpui_kit::component::{h_flex, v_flex};7
use gpui_kit::prelude::FluentBuilder as _;8
use gpui_kit::*;9
10
use super::avatar::person_avatar;11
use super::join_dialog::open_join_with_id;12
use super::widgets::icon;13
use crate::app_state::AppState;14
use crate::call::{CallRow, call_rows};15
use crate::theme;16
17
const ROW_HEIGHT: f32 = 54.;18
const AVATAR_SIZE: f32 = 36.;19
const MENU_ICON_SIZE: f32 = 15.;20
const EMPTY_TEXT: &str = "No calls yet";21
22
fn meeting_avatar() -> Div {23
div()24
.size(px(AVATAR_SIZE))25
.flex_none()26
.flex()27
.items_center()28
.justify_center()29
.rounded_full()30
.bg(theme::border_strong())31
.child(icon(IconName::Video, 16., theme::text()))32
}33
34
fn call_row(35
state: &Entity<AppState>,36
row: &CallRow,37
can_open_chat: bool,38
directory: &crate::data::Directory,39
) -> AnyElement {40
let avatar = if row.meeting {41
meeting_avatar().into_any_element()42
} else {43
person_avatar(directory, row.user_id.as_deref(), &row.title, AVATAR_SIZE)44
};45
let title_color = if row.missed {46
theme::red_soft()47
} else {48
theme::text()49
};50
let click_state = state.clone();51
let click_row = row.clone();52
let menu_state = state.clone();53
let menu_row = row.clone();54
let can_call_back = !row.meeting && row.user_id.is_some();55
h_flex()56
.id(SharedString::from(format!("call-{}", row.key)))57
.mx(px(8.))58
.h(px(ROW_HEIGHT))59
.px(px(8.))60
.gap(px(10.))61
.items_center()62
.rounded(px(8.))63
.cursor_pointer()64
.hover(|row| row.bg(theme::row_hover()))65
.child(avatar)66
.child(67
v_flex()68
.flex_1()69
.min_w_0()70
.gap(px(2.))71
.child(72
h_flex()73
.gap(px(8.))74
.items_baseline()75
.child(76
div()77
.flex_1()78
.min_w_0()79
.truncate()80
.text_size(px(14.))81
.text_color(title_color)82
.child(row.title.clone()),83
)84
.child(85
div()86
.flex_none()87
.text_size(px(11.))88
.text_color(theme::text_muted())89
.child(row.time_label.clone()),90
),91
)92
.child(93
div()94
.truncate()95
.text_size(px(12.5))96
.text_color(if row.missed {97
theme::red_soft()98
} else {99
theme::text_muted()100
})101
.child(row.subline.clone()),102
),103
)104
.on_click(move |_, _, cx| {105
click_state.update(cx, |state, cx| state.activate_call_row(&click_row, cx));106
})107
.context_menu(move |popup, _, _| {108
let call_state = menu_state.clone();109
let call_row = menu_row.clone();110
let chat_state = menu_state.clone();111
let chat_row = menu_row.clone();112
popup113
.when(can_call_back, |popup| {114
popup.item(115
PopupMenuItem::new("Call back")116
.icon(icon(IconName::Phone, MENU_ICON_SIZE, theme::text_muted()))117
.on_click(move |_, _, cx| {118
call_state.update(cx, |state, cx| {119
state.call_back_from_history(&call_row, cx)120
});121
}),122
)123
})124
.when(can_open_chat, |popup| {125
popup.item(126
PopupMenuItem::new("Open chat")127
.icon(icon(128
IconName::MessageSquare,129
MENU_ICON_SIZE,130
theme::text_muted(),131
))132
.on_click(move |_, _, cx| {133
chat_state.update(cx, |state, cx| {134
state.open_chat_of_call_row(&chat_row, cx)135
});136
}),137
)138
})139
})140
.into_any_element()141
}142
143
fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {144
let id_state = state.clone();145
let paste_state = state.clone();146
h_flex()147
.w_full()148
.px(px(12.))149
.pb(px(8.))150
.gap(px(8.))151
.child(152
Button::new("join-with-id")153
.small()154
.label("Join with ID")155
.on_click(move |_, window, cx| open_join_with_id(id_state.clone(), window, cx)),156
)157
.child(158
Button::new("paste-meeting-link")159
.small()160
.label("Paste a meeting link")161
.on_click(move |_, _, cx| {162
paste_state.update(cx, |state, cx| state.join_meeting_from_clipboard(cx));163
}),164
)165
}166
167
pub fn calls_body(state: &Entity<AppState>, scroll: &ScrollHandle, cx: &App) -> AnyElement {168
let app = state.read(cx);169
let offset = Local::now().offset().fix();170
let rows = call_rows(&app.call_history, &app.sidebar.chats, Utc::now(), offset);171
let list = if rows.is_empty() {172
div()173
.w_full()174
.py(px(24.))175
.flex()176
.justify_center()177
.text_size(px(13.))178
.text_color(theme::text_muted())179
.child(EMPTY_TEXT)180
.into_any_element()181
} else {182
v_flex()183
.w_full()184
.pb(px(12.))185
.children(rows.iter().map(|row| {186
call_row(187
state,188
row,189
app.can_open_chat_of_call_row(row),190
&app.directory,191
)192
}))193
.into_any_element()194
};195
v_flex()196
.flex_1()197
.min_h_0()198
.child(join_buttons(state))199
.child(200
div()201
.id("calls-scroll")202
.flex_1()203
.min_h_0()204
.overflow_y_scroll()205
.track_scroll(scroll)206
.child(list),207
)208
.into_any_element()209
}@@ -42,7 +42,7 @@ use super::avatar::{person_avatar, square_avatar};
42
42
use super::draft_style::draft_style;
43
43
use super::emoji_popup::{self, EmojiPopup};
44
44
use super::format_toolbar::{self, FormatButton};
45
use super::link_preview::{ComposeLink, draft_link, link_preview_card};
45
use super::link_preview::{ComposeLink, draft_link, link_preview_card, meeting_join_chip};
46
46
use super::fun_picker::{FunPicker, FunPickerEvent};
47
47
use super::widgets::{icon, symbol};
48
48
use crate::app_state::AppState;
@@ -1310,9 +1310,11 @@ impl Composer {
1310
1310
return;
1311
1311
}
1312
1312
let draft = self.current_draft(cx);
1313
let meeting = teams_core::meeting_link_in_html(&draft.to_html());
1313
1314
if let Some(url) = self.link.observe(draft_link(&draft), draft.is_blank()) {
1314
1315
self.fetch_link_preview(url, cx);
1315
1316
}
1317
self.link.meeting = meeting;
1316
1318
cx.notify();
1317
1319
}
1318
1320
@@ -1362,6 +1364,16 @@ impl Composer {
1362
1364
.is_some_and(|image| self.app.read(cx).directory.image(&image.url).is_none())
1363
1365
}
1364
1366
1367
fn render_meeting_chip(&self) -> Option<Div> {
1368
let url = self.link.meeting.clone()?;
1369
Some(
1370
h_flex()
1371
.w_full()
1372
.mb(px(6.))
1373
.child(meeting_join_chip("composer-meeting-join".to_owned(), url)),
1374
)
1375
}
1376
1365
1377
fn render_link_preview(&self, cx: &mut Context<Self>) -> Option<Div> {
1366
1378
let preview = self.link.shown()?;
1367
1379
let composer = cx.weak_entity();
@@ -2728,6 +2740,7 @@ impl Render for Composer {
2728
2740
.children(notice)
2729
2741
.children(self.render_reply_strip(cx))
2730
2742
.children(self.render_edit_strip(cx))
2743
.children(self.render_meeting_chip())
2731
2744
.children(self.render_link_preview(cx))
2732
2745
.child(
2733
2746
div()
@@ -42,7 +42,7 @@ use super::avatar::{person_avatar, square_avatar};42
use super::draft_style::draft_style;42
use super::draft_style::draft_style;43
use super::emoji_popup::{self, EmojiPopup};43
use super::emoji_popup::{self, EmojiPopup};44
use super::format_toolbar::{self, FormatButton};44
use super::format_toolbar::{self, FormatButton};45
use super::link_preview::{ComposeLink, draft_link, link_preview_card};45
use super::link_preview::{ComposeLink, draft_link, link_preview_card, meeting_join_chip};46
use super::fun_picker::{FunPicker, FunPickerEvent};46
use super::fun_picker::{FunPicker, FunPickerEvent};47
use super::widgets::{icon, symbol};47
use super::widgets::{icon, symbol};48
use crate::app_state::AppState;48
use crate::app_state::AppState;@@ -1310,9 +1310,11 @@ impl Composer {1310
return;1310
return;1311
}1311
}1312
let draft = self.current_draft(cx);1312
let draft = self.current_draft(cx);1313
let meeting = teams_core::meeting_link_in_html(&draft.to_html());1313
if let Some(url) = self.link.observe(draft_link(&draft), draft.is_blank()) {1314
if let Some(url) = self.link.observe(draft_link(&draft), draft.is_blank()) {1314
self.fetch_link_preview(url, cx);1315
self.fetch_link_preview(url, cx);1315
}1316
}1317
self.link.meeting = meeting;1316
cx.notify();1318
cx.notify();1317
}1319
}1318
1320
@@ -1362,6 +1364,16 @@ impl Composer {1362
.is_some_and(|image| self.app.read(cx).directory.image(&image.url).is_none())1364
.is_some_and(|image| self.app.read(cx).directory.image(&image.url).is_none())1363
}1365
}1364
1366
1367
fn render_meeting_chip(&self) -> Option<Div> {1368
let url = self.link.meeting.clone()?;1369
Some(1370
h_flex()1371
.w_full()1372
.mb(px(6.))1373
.child(meeting_join_chip("composer-meeting-join".to_owned(), url)),1374
)1375
}1376
1365
fn render_link_preview(&self, cx: &mut Context<Self>) -> Option<Div> {1377
fn render_link_preview(&self, cx: &mut Context<Self>) -> Option<Div> {1366
let preview = self.link.shown()?;1378
let preview = self.link.shown()?;1367
let composer = cx.weak_entity();1379
let composer = cx.weak_entity();@@ -2728,6 +2740,7 @@ impl Render for Composer {2728
.children(notice)2740
.children(notice)2729
.children(self.render_reply_strip(cx))2741
.children(self.render_reply_strip(cx))2730
.children(self.render_edit_strip(cx))2742
.children(self.render_edit_strip(cx))2743
.children(self.render_meeting_chip())2731
.children(self.render_link_preview(cx))2744
.children(self.render_link_preview(cx))2732
.child(2745
.child(2733
div()2746
div()@@ -566,6 +566,7 @@ impl ConversationView {
566
566
| AppEvent::StatusMessage
567
567
| AppEvent::NotificationSettings
568
568
| AppEvent::Profile
569
| AppEvent::CallHistory
569
570
| AppEvent::Ring
570
571
| AppEvent::MissedCall(_)
571
572
| AppEvent::Call => {}
@@ -566,6 +566,7 @@ impl ConversationView {566
| AppEvent::StatusMessage566
| AppEvent::StatusMessage567
| AppEvent::NotificationSettings567
| AppEvent::NotificationSettings568
| AppEvent::Profile568
| AppEvent::Profile569
| AppEvent::CallHistory569
| AppEvent::Ring570
| AppEvent::Ring570
| AppEvent::MissedCall(_)571
| AppEvent::MissedCall(_)571
| AppEvent::Call => {}572
| AppEvent::Call => {}@@ -0,0 +1,126 @@
1
use gpui_kit::component::button::{Button, ButtonVariants as _};
2
use gpui_kit::component::dialog::{Dialog, DialogFooter};
3
use gpui_kit::component::input::{Input, InputEvent, InputState};
4
use gpui_kit::component::{WindowExt as _, v_flex};
5
use gpui_kit::prelude::FluentBuilder as _;
6
use gpui_kit::*;
7
8
use crate::app_state::AppState;
9
use crate::theme;
10
11
const DIALOG_WIDTH: f32 = 380.;
12
const FIELD_GAP: f32 = 12.;
13
const LABEL_SIZE: f32 = 12.;
14
const TITLE: &str = "Join with a meeting ID";
15
16
struct JoinForm {
17
state: Entity<AppState>,
18
meeting_id: Entity<InputState>,
19
passcode: Entity<InputState>,
20
error: Option<String>,
21
_subscriptions: [Subscription; 2],
22
}
23
24
impl JoinForm {
25
fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
26
let meeting_id = cx.new(|cx| InputState::new(window, cx).placeholder("123 456 789 012"));
27
let passcode = cx.new(|cx| {
28
InputState::new(window, cx).placeholder("Passcode (if the invitation has one)")
29
});
30
let subscriptions = [
31
cx.subscribe_in(&meeting_id, window, Self::on_enter),
32
cx.subscribe_in(&passcode, window, Self::on_enter),
33
];
34
JoinForm {
35
state,
36
meeting_id,
37
passcode,
38
error: None,
39
_subscriptions: subscriptions,
40
}
41
}
42
43
fn on_enter(
44
&mut self,
45
_: &Entity<InputState>,
46
event: &InputEvent,
47
window: &mut Window,
48
cx: &mut Context<Self>,
49
) {
50
if matches!(event, InputEvent::PressEnter { .. }) && self.submit(cx) {
51
window.close_dialog(cx);
52
}
53
}
54
55
fn submit(&mut self, cx: &mut Context<Self>) -> bool {
56
let meeting_id = self.meeting_id.read(cx).value().to_string();
57
let passcode = self.passcode.read(cx).value().to_string();
58
let joined = self.state.update(cx, |state, cx| {
59
state.join_meeting_by_id(&meeting_id, &passcode, cx)
60
});
61
self.error = joined.as_ref().err().cloned();
62
cx.notify();
63
joined.is_ok()
64
}
65
}
66
67
fn labeled(label: &str, field: impl IntoElement) -> Div {
68
v_flex()
69
.gap(px(4.))
70
.child(
71
div()
72
.text_size(px(LABEL_SIZE))
73
.text_color(theme::text_muted())
74
.child(label.to_owned()),
75
)
76
.child(field)
77
}
78
79
impl Render for JoinForm {
80
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
81
v_flex()
82
.gap(px(FIELD_GAP))
83
.child(labeled("Meeting ID", Input::new(&self.meeting_id)))
84
.child(labeled("Passcode", Input::new(&self.passcode)))
85
.when_some(self.error.clone(), |form, error| {
86
form.child(
87
div()
88
.text_size(px(LABEL_SIZE))
89
.text_color(theme::red_soft())
90
.child(error),
91
)
92
})
93
}
94
}
95
96
pub fn open_join_with_id(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
97
let form = cx.new(|cx| JoinForm::new(state, window, cx));
98
let first_field = form.read(cx).meeting_id.clone();
99
window.open_dialog(cx, move |dialog: Dialog, _, _| {
100
let submit_form = form.clone();
101
let footer = DialogFooter::new()
102
.child(
103
Button::new("join-cancel")
104
.label("Cancel")
105
.on_click(|_, window, cx| window.close_dialog(cx)),
106
)
107
.child(
108
Button::new("join-confirm")
109
.primary()
110
.label("Join")
111
.on_click(move |_, window, cx| {
112
if submit_form.update(cx, |form, cx| form.submit(cx)) {
113
window.close_dialog(cx);
114
}
115
}),
116
);
117
dialog
118
.title(TITLE)
119
.w(px(DIALOG_WIDTH))
120
.child(form.clone())
121
.footer(footer)
122
});
123
window.defer(cx, move |window, cx| {
124
first_field.update(cx, |input, cx| input.focus(window, cx));
125
});
126
}
@@ -0,0 +1,126 @@1
use gpui_kit::component::button::{Button, ButtonVariants as _};2
use gpui_kit::component::dialog::{Dialog, DialogFooter};3
use gpui_kit::component::input::{Input, InputEvent, InputState};4
use gpui_kit::component::{WindowExt as _, v_flex};5
use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::*;7
8
use crate::app_state::AppState;9
use crate::theme;10
11
const DIALOG_WIDTH: f32 = 380.;12
const FIELD_GAP: f32 = 12.;13
const LABEL_SIZE: f32 = 12.;14
const TITLE: &str = "Join with a meeting ID";15
16
struct JoinForm {17
state: Entity<AppState>,18
meeting_id: Entity<InputState>,19
passcode: Entity<InputState>,20
error: Option<String>,21
_subscriptions: [Subscription; 2],22
}23
24
impl JoinForm {25
fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {26
let meeting_id = cx.new(|cx| InputState::new(window, cx).placeholder("123 456 789 012"));27
let passcode = cx.new(|cx| {28
InputState::new(window, cx).placeholder("Passcode (if the invitation has one)")29
});30
let subscriptions = [31
cx.subscribe_in(&meeting_id, window, Self::on_enter),32
cx.subscribe_in(&passcode, window, Self::on_enter),33
];34
JoinForm {35
state,36
meeting_id,37
passcode,38
error: None,39
_subscriptions: subscriptions,40
}41
}42
43
fn on_enter(44
&mut self,45
_: &Entity<InputState>,46
event: &InputEvent,47
window: &mut Window,48
cx: &mut Context<Self>,49
) {50
if matches!(event, InputEvent::PressEnter { .. }) && self.submit(cx) {51
window.close_dialog(cx);52
}53
}54
55
fn submit(&mut self, cx: &mut Context<Self>) -> bool {56
let meeting_id = self.meeting_id.read(cx).value().to_string();57
let passcode = self.passcode.read(cx).value().to_string();58
let joined = self.state.update(cx, |state, cx| {59
state.join_meeting_by_id(&meeting_id, &passcode, cx)60
});61
self.error = joined.as_ref().err().cloned();62
cx.notify();63
joined.is_ok()64
}65
}66
67
fn labeled(label: &str, field: impl IntoElement) -> Div {68
v_flex()69
.gap(px(4.))70
.child(71
div()72
.text_size(px(LABEL_SIZE))73
.text_color(theme::text_muted())74
.child(label.to_owned()),75
)76
.child(field)77
}78
79
impl Render for JoinForm {80
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {81
v_flex()82
.gap(px(FIELD_GAP))83
.child(labeled("Meeting ID", Input::new(&self.meeting_id)))84
.child(labeled("Passcode", Input::new(&self.passcode)))85
.when_some(self.error.clone(), |form, error| {86
form.child(87
div()88
.text_size(px(LABEL_SIZE))89
.text_color(theme::red_soft())90
.child(error),91
)92
})93
}94
}95
96
pub fn open_join_with_id(state: Entity<AppState>, window: &mut Window, cx: &mut App) {97
let form = cx.new(|cx| JoinForm::new(state, window, cx));98
let first_field = form.read(cx).meeting_id.clone();99
window.open_dialog(cx, move |dialog: Dialog, _, _| {100
let submit_form = form.clone();101
let footer = DialogFooter::new()102
.child(103
Button::new("join-cancel")104
.label("Cancel")105
.on_click(|_, window, cx| window.close_dialog(cx)),106
)107
.child(108
Button::new("join-confirm")109
.primary()110
.label("Join")111
.on_click(move |_, window, cx| {112
if submit_form.update(cx, |form, cx| form.submit(cx)) {113
window.close_dialog(cx);114
}115
}),116
);117
dialog118
.title(TITLE)119
.w(px(DIALOG_WIDTH))120
.child(form.clone())121
.footer(footer)122
});123
window.defer(cx, move |window, cx| {124
first_field.update(cx, |input, cx| input.focus(window, cx));125
});126
}@@ -7,6 +7,7 @@ use gpui_kit::*;
7
7
use teams_core::{LinkPreview, first_public_link};
8
8
9
9
use super::widgets::icon;
10
use crate::app_state::AppHandle;
10
11
use crate::data::Directory;
11
12
use crate::theme;
12
13
@@ -17,6 +18,7 @@ const THUMB_MIN_HEIGHT: f32 = 48.;
17
18
const THUMB_MAX_HEIGHT: f32 = 112.;
18
19
const THUMB_RADIUS: f32 = 6.;
19
20
const CLOSE_SIZE: f32 = 22.;
21
const JOIN_CHIP_HEIGHT: f32 = 24.;
20
22
21
23
pub type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
22
24
@@ -161,11 +163,41 @@ pub fn link_preview_card(
161
163
.into_any_element()
162
164
}
163
165
166
pub fn meeting_join_chip(id: String, url: String) -> AnyElement {
167
h_flex()
168
.id(ElementId::Name(id.into()))
169
.flex_none()
170
.self_start()
171
.h(px(JOIN_CHIP_HEIGHT))
172
.px(px(10.))
173
.gap(px(5.))
174
.items_center()
175
.rounded_full()
176
.bg(theme::accent())
177
.text_size(px(12.))
178
.font_weight(FontWeight::SEMIBOLD)
179
.text_color(theme::on_accent())
180
.cursor_pointer()
181
.hover(|chip| chip.opacity(0.85))
182
.child(icon(IconName::Video, 13., theme::on_accent()))
183
.child("Join")
184
.on_click(move |_, _, cx| {
185
cx.stop_propagation();
186
let Some(handle) = cx.try_global::<AppHandle>() else {
187
return;
188
};
189
let app = handle.0.clone();
190
app.update(cx, |state, cx| state.join_meeting_link(&url, cx));
191
})
192
.into_any_element()
193
}
194
164
195
#[derive(Default)]
165
196
pub struct ComposeLink {
166
197
url: Option<String>,
167
198
preview: Option<LinkPreview>,
168
199
dismissed: Option<String>,
200
pub meeting: Option<String>,
169
201
pub lookup: Option<Task<()>>,
170
202
}
171
203
@@ -7,6 +7,7 @@ use gpui_kit::*;7
use teams_core::{LinkPreview, first_public_link};7
use teams_core::{LinkPreview, first_public_link};8
8
9
use super::widgets::icon;9
use super::widgets::icon;10
use crate::app_state::AppHandle;10
use crate::data::Directory;11
use crate::data::Directory;11
use crate::theme;12
use crate::theme;12
13
@@ -17,6 +18,7 @@ const THUMB_MIN_HEIGHT: f32 = 48.;17
const THUMB_MAX_HEIGHT: f32 = 112.;18
const THUMB_MAX_HEIGHT: f32 = 112.;18
const THUMB_RADIUS: f32 = 6.;19
const THUMB_RADIUS: f32 = 6.;19
const CLOSE_SIZE: f32 = 22.;20
const CLOSE_SIZE: f32 = 22.;21
const JOIN_CHIP_HEIGHT: f32 = 24.;20
22
21
pub type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;23
pub type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;22
24
@@ -161,11 +163,41 @@ pub fn link_preview_card(161
.into_any_element()163
.into_any_element()162
}164
}163
165
166
pub fn meeting_join_chip(id: String, url: String) -> AnyElement {167
h_flex()168
.id(ElementId::Name(id.into()))169
.flex_none()170
.self_start()171
.h(px(JOIN_CHIP_HEIGHT))172
.px(px(10.))173
.gap(px(5.))174
.items_center()175
.rounded_full()176
.bg(theme::accent())177
.text_size(px(12.))178
.font_weight(FontWeight::SEMIBOLD)179
.text_color(theme::on_accent())180
.cursor_pointer()181
.hover(|chip| chip.opacity(0.85))182
.child(icon(IconName::Video, 13., theme::on_accent()))183
.child("Join")184
.on_click(move |_, _, cx| {185
cx.stop_propagation();186
let Some(handle) = cx.try_global::<AppHandle>() else {187
return;188
};189
let app = handle.0.clone();190
app.update(cx, |state, cx| state.join_meeting_link(&url, cx));191
})192
.into_any_element()193
}194
164
#[derive(Default)]195
#[derive(Default)]165
pub struct ComposeLink {196
pub struct ComposeLink {166
url: Option<String>,197
url: Option<String>,167
preview: Option<LinkPreview>,198
preview: Option<LinkPreview>,168
dismissed: Option<String>,199
dismissed: Option<String>,200
pub meeting: Option<String>,169
pub lookup: Option<Task<()>>,201
pub lookup: Option<Task<()>>,170
}202
}171
203
@@ -7,7 +7,7 @@ use std::time::Duration;
7
7
use super::adaptive_card::cards_view;
8
8
use super::attachments::{FileActions, attachments_view, message_body};
9
9
use super::avatar::{bot_avatar, person_avatar};
10
use super::link_preview::link_preview_card;
10
use super::link_preview::{link_preview_card, meeting_join_chip};
11
11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
12
12
use super::profile_card::opens_profile;
13
13
use super::reaction_picker::PickHandler;
@@ -175,6 +175,11 @@ fn bubble(
175
175
directory,
176
176
extras.files.as_ref(),
177
177
));
178
content = content.children(
179
row.meeting_link
180
.clone()
181
.map(|url| meeting_join_chip(format!("message-{index}-join"), url)),
182
);
178
183
content = content.children(row.link_preview.as_ref().map(|preview| {
179
184
link_preview_card(
180
185
preview,
@@ -7,7 +7,7 @@ use std::time::Duration;7
use super::adaptive_card::cards_view;7
use super::adaptive_card::cards_view;8
use super::attachments::{FileActions, attachments_view, message_body};8
use super::attachments::{FileActions, attachments_view, message_body};9
use super::avatar::{bot_avatar, person_avatar};9
use super::avatar::{bot_avatar, person_avatar};10
use super::link_preview::link_preview_card;10
use super::link_preview::{link_preview_card, meeting_join_chip};11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};12
use super::profile_card::opens_profile;12
use super::profile_card::opens_profile;13
use super::reaction_picker::PickHandler;13
use super::reaction_picker::PickHandler;@@ -175,6 +175,11 @@ fn bubble(175
directory,175
directory,176
extras.files.as_ref(),176
extras.files.as_ref(),177
));177
));178
content = content.children(179
row.meeting_link180
.clone()181
.map(|url| meeting_join_chip(format!("message-{index}-join"), url)),182
);178
content = content.children(row.link_preview.as_ref().map(|preview| {183
content = content.children(row.link_preview.as_ref().map(|preview| {179
link_preview_card(184
link_preview_card(180
preview,185
preview,@@ -4,6 +4,8 @@ pub mod attachment_tray;
4
4
pub mod attachments;
5
5
pub mod avatar;
6
6
pub mod call_controls;
7
pub mod call_extras;
8
pub mod calls_tab;
7
9
pub mod call_mini;
8
10
pub mod call_organizer;
9
11
pub mod call_stage;
@@ -24,6 +26,7 @@ pub mod draft_style;
24
26
pub mod emoji_popup;
25
27
pub mod format_toolbar;
26
28
pub mod forward_dialog;
29
pub mod join_dialog;
27
30
pub mod link_preview;
28
31
pub mod fun_picker;
29
32
pub mod message_actions;
@@ -46,5 +49,6 @@ pub mod status_menu;
46
49
pub mod status_message_dialog;
47
50
pub mod switcher;
48
51
pub mod title_bar;
52
pub mod transfer_picker;
49
53
pub mod translation_line;
50
54
pub mod widgets;
@@ -4,6 +4,8 @@ pub mod attachment_tray;4
pub mod attachments;4
pub mod attachments;5
pub mod avatar;5
pub mod avatar;6
pub mod call_controls;6
pub mod call_controls;7
pub mod call_extras;8
pub mod calls_tab;7
pub mod call_mini;9
pub mod call_mini;8
pub mod call_organizer;10
pub mod call_organizer;9
pub mod call_stage;11
pub mod call_stage;@@ -24,6 +26,7 @@ pub mod draft_style;24
pub mod emoji_popup;26
pub mod emoji_popup;25
pub mod format_toolbar;27
pub mod format_toolbar;26
pub mod forward_dialog;28
pub mod forward_dialog;29
pub mod join_dialog;27
pub mod link_preview;30
pub mod link_preview;28
pub mod fun_picker;31
pub mod fun_picker;29
pub mod message_actions;32
pub mod message_actions;@@ -46,5 +49,6 @@ pub mod status_menu;46
pub mod status_message_dialog;49
pub mod status_message_dialog;47
pub mod switcher;50
pub mod switcher;48
pub mod title_bar;51
pub mod title_bar;52
pub mod transfer_picker;49
pub mod translation_line;53
pub mod translation_line;50
pub mod widgets;54
pub mod widgets;@@ -7,7 +7,7 @@ use super::adaptive_card::cards_view;
7
7
use super::attachments::{attachments_view, message_body};
8
8
use super::avatar::{bot_avatar, person_avatar};
9
9
use super::profile_card::opens_profile;
10
use super::link_preview::link_preview_card;
10
use super::link_preview::{link_preview_card, meeting_join_chip};
11
11
use super::message_actions::message_toolbar;
12
12
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
13
13
use super::reaction_pills::reaction_pills;
@@ -104,6 +104,11 @@ fn message_content(
104
104
directory,
105
105
actions.files.as_ref(),
106
106
));
107
content = content.children(
108
row.meeting_link
109
.clone()
110
.map(|url| meeting_join_chip(format!("message-{index}-join"), url)),
111
);
107
112
content = content.children(row.link_preview.as_ref().map(|preview| {
108
113
link_preview_card(
109
114
preview,
@@ -7,7 +7,7 @@ use super::adaptive_card::cards_view;7
use super::attachments::{attachments_view, message_body};7
use super::attachments::{attachments_view, message_body};8
use super::avatar::{bot_avatar, person_avatar};8
use super::avatar::{bot_avatar, person_avatar};9
use super::profile_card::opens_profile;9
use super::profile_card::opens_profile;10
use super::link_preview::link_preview_card;10
use super::link_preview::{link_preview_card, meeting_join_chip};11
use super::message_actions::message_toolbar;11
use super::message_actions::message_toolbar;12
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};12
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};13
use super::reaction_pills::reaction_pills;13
use super::reaction_pills::reaction_pills;@@ -104,6 +104,11 @@ fn message_content(104
directory,104
directory,105
actions.files.as_ref(),105
actions.files.as_ref(),106
));106
));107
content = content.children(108
row.meeting_link109
.clone()110
.map(|url| meeting_join_chip(format!("message-{index}-join"), url)),111
);107
content = content.children(row.link_preview.as_ref().map(|preview| {112
content = content.children(row.link_preview.as_ref().map(|preview| {108
link_preview_card(113
link_preview_card(109
preview,114
preview,@@ -12,7 +12,7 @@ use super::profile_card::{ProfileCard, ProfileCardEvent};
12
12
use super::saved_panel::{SavedPanel, SavedPanelEvent};
13
13
use super::shortcuts::{
14
14
AcceptCall, DeclineCall, HangUpCall, NextConversation, OpenActivity, OpenChannelsTab,
15
OpenChatsTab, OpenSaved, PreviousConversation, Scope, ShowShortcuts, ToggleCallCamera,
15
OpenCallsTab, OpenChatsTab, OpenSaved, PreviousConversation, Scope, ShowShortcuts, ToggleCallCamera,
16
16
ToggleCallShare,
17
17
};
18
18
use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
@@ -579,6 +579,9 @@ impl Render for AppShell {
579
579
.on_action(cx.listener(|this, _: &OpenChannelsTab, _, cx| {
580
580
this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));
581
581
}))
582
.on_action(cx.listener(|this, _: &OpenCallsTab, _, cx| {
583
this.sidebar.update(cx, |sidebar, cx| sidebar.show_calls(cx));
584
}))
582
585
.on_action(cx.listener(|this, _: &PreviousConversation, _, cx| {
583
586
this.sidebar
584
587
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));
@@ -12,7 +12,7 @@ use super::profile_card::{ProfileCard, ProfileCardEvent};12
use super::saved_panel::{SavedPanel, SavedPanelEvent};12
use super::saved_panel::{SavedPanel, SavedPanelEvent};13
use super::shortcuts::{13
use super::shortcuts::{14
AcceptCall, DeclineCall, HangUpCall, NextConversation, OpenActivity, OpenChannelsTab,14
AcceptCall, DeclineCall, HangUpCall, NextConversation, OpenActivity, OpenChannelsTab,15
OpenChatsTab, OpenSaved, PreviousConversation, Scope, ShowShortcuts, ToggleCallCamera,15
OpenCallsTab, OpenChatsTab, OpenSaved, PreviousConversation, Scope, ShowShortcuts, ToggleCallCamera,16
ToggleCallShare,16
ToggleCallShare,17
};17
};18
use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};18
use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};@@ -579,6 +579,9 @@ impl Render for AppShell {579
.on_action(cx.listener(|this, _: &OpenChannelsTab, _, cx| {579
.on_action(cx.listener(|this, _: &OpenChannelsTab, _, cx| {580
this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));580
this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));581
}))581
}))582
.on_action(cx.listener(|this, _: &OpenCallsTab, _, cx| {583
this.sidebar.update(cx, |sidebar, cx| sidebar.show_calls(cx));584
}))582
.on_action(cx.listener(|this, _: &PreviousConversation, _, cx| {585
.on_action(cx.listener(|this, _: &PreviousConversation, _, cx| {583
this.sidebar586
this.sidebar584
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));587
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));@@ -17,6 +17,7 @@ actions!(
17
17
OpenChatsTab,
18
18
OpenChannelsTab,
19
19
OpenSaved,
20
OpenCallsTab,
20
21
PreviousConversation,
21
22
NextConversation,
22
23
AcceptCall,
@@ -93,6 +94,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
93
94
shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
94
95
shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
95
96
shortcut!(Navigation, GlobalOverTextFields, "Open Saved", "ctrl-4", Some("cmd-4"), OpenSaved),
97
shortcut!(Navigation, GlobalOverTextFields, "Show Calls", "ctrl-5", Some("cmd-5"), OpenCallsTab),
96
98
shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
97
99
shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
98
100
shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
@@ -17,6 +17,7 @@ actions!(17
OpenChatsTab,17
OpenChatsTab,18
OpenChannelsTab,18
OpenChannelsTab,19
OpenSaved,19
OpenSaved,20
OpenCallsTab,20
PreviousConversation,21
PreviousConversation,21
NextConversation,22
NextConversation,22
AcceptCall,23
AcceptCall,@@ -93,6 +94,7 @@ pub const SHORTCUTS: &[Shortcut] = &[93
shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),94
shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),94
shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),95
shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),95
shortcut!(Navigation, GlobalOverTextFields, "Open Saved", "ctrl-4", Some("cmd-4"), OpenSaved),96
shortcut!(Navigation, GlobalOverTextFields, "Open Saved", "ctrl-4", Some("cmd-4"), OpenSaved),97
shortcut!(Navigation, GlobalOverTextFields, "Show Calls", "ctrl-5", Some("cmd-5"), OpenCallsTab),96
shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),98
shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),97
shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),99
shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),98
shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),100
shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),@@ -13,6 +13,7 @@ use store::{
13
13
};
14
14
15
15
use super::avatar::{spec_avatar, square_avatar, with_presence};
16
use super::calls_tab::calls_body;
16
17
use super::widgets::{count_badge, dot, icon, unread_marker};
17
18
use crate::app_state::{AppEvent, AppState, Selection};
18
19
use crate::chat_actions::TITLE_LIMIT;
@@ -52,6 +53,7 @@ const NOTIFICATION_ICON_SIZE: f32 = 13.;
52
53
enum SidebarTab {
53
54
Chats,
54
55
Channels,
56
Calls,
55
57
}
56
58
57
59
#[derive(Clone)]
@@ -268,6 +270,7 @@ pub struct SidebarView {
268
270
hidden_teams_open: bool,
269
271
chats_scroll: ScrollHandle,
270
272
channels_scroll: ScrollHandle,
273
calls_scroll: ScrollHandle,
271
274
_subscription: Subscription,
272
275
}
273
276
@@ -353,6 +356,7 @@ impl SidebarView {
353
356
hidden_teams_open: false,
354
357
chats_scroll: ScrollHandle::new(),
355
358
channels_scroll: ScrollHandle::new(),
359
calls_scroll: ScrollHandle::new(),
356
360
_subscription: subscription,
357
361
}
358
362
}
@@ -367,6 +371,18 @@ impl SidebarView {
367
371
cx.notify();
368
372
}
369
373
374
pub fn show_calls(&mut self, cx: &mut Context<Self>) {
375
self.open_tab(SidebarTab::Calls, cx);
376
}
377
378
fn open_tab(&mut self, tab: SidebarTab, cx: &mut Context<Self>) {
379
self.tab = tab;
380
if tab == SidebarTab::Calls {
381
self.state.update(cx, |state, cx| state.refresh_call_history(cx));
382
}
383
cx.notify();
384
}
385
370
386
pub fn select_adjacent(&mut self, step: Step, cx: &mut Context<Self>) {
371
387
let selection = match self.tab {
372
388
SidebarTab::Chats => self
@@ -375,6 +391,7 @@ impl SidebarView {
375
391
.adjacent_chat_id(step)
376
392
.map(Selection::Chat),
377
393
SidebarTab::Channels => self.adjacent_channel_id(step, cx).map(Selection::Channel),
394
SidebarTab::Calls => None,
378
395
};
379
396
if let Some(selection) = selection {
380
397
self.state.update(cx, |state, cx| state.select(selection, cx));
@@ -450,10 +467,7 @@ impl SidebarView {
450
467
})
451
468
.child(label.to_owned())
452
469
.children(marker)
453
.on_click(cx.listener(move |this, _, _, cx| {
454
this.tab = tab;
455
cx.notify();
456
}))
470
.on_click(cx.listener(move |this, _, _, cx| this.open_tab(tab, cx)))
457
471
}
458
472
459
473
fn tab_bar(
@@ -482,7 +496,8 @@ impl SidebarView {
482
496
.border_1()
483
497
.border_color(theme::border())
484
498
.child(self.tab_button(SidebarTab::Chats, "Chats", chat_marker, cx))
485
.child(self.tab_button(SidebarTab::Channels, "Channels", channel_marker, cx)),
499
.child(self.tab_button(SidebarTab::Channels, "Channels", channel_marker, cx))
500
.child(self.tab_button(SidebarTab::Calls, "Calls", None, cx)),
486
501
)
487
502
.child(self.new_chat_button(cx))
488
503
}
@@ -1461,6 +1476,7 @@ impl Render for SidebarView {
1461
1476
let body = match self.tab {
1462
1477
SidebarTab::Chats => self.chats_body(window_height, cx),
1463
1478
SidebarTab::Channels => self.channels_body(cx),
1479
SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, cx),
1464
1480
};
1465
1481
v_flex()
1466
1482
.w(px(SIDEBAR_WIDTH))
@@ -13,6 +13,7 @@ use store::{13
};13
};14
14
15
use super::avatar::{spec_avatar, square_avatar, with_presence};15
use super::avatar::{spec_avatar, square_avatar, with_presence};16
use super::calls_tab::calls_body;16
use super::widgets::{count_badge, dot, icon, unread_marker};17
use super::widgets::{count_badge, dot, icon, unread_marker};17
use crate::app_state::{AppEvent, AppState, Selection};18
use crate::app_state::{AppEvent, AppState, Selection};18
use crate::chat_actions::TITLE_LIMIT;19
use crate::chat_actions::TITLE_LIMIT;@@ -52,6 +53,7 @@ const NOTIFICATION_ICON_SIZE: f32 = 13.;52
enum SidebarTab {53
enum SidebarTab {53
Chats,54
Chats,54
Channels,55
Channels,56
Calls,55
}57
}56
58
57
#[derive(Clone)]59
#[derive(Clone)]@@ -268,6 +270,7 @@ pub struct SidebarView {268
hidden_teams_open: bool,270
hidden_teams_open: bool,269
chats_scroll: ScrollHandle,271
chats_scroll: ScrollHandle,270
channels_scroll: ScrollHandle,272
channels_scroll: ScrollHandle,273
calls_scroll: ScrollHandle,271
_subscription: Subscription,274
_subscription: Subscription,272
}275
}273
276
@@ -353,6 +356,7 @@ impl SidebarView {353
hidden_teams_open: false,356
hidden_teams_open: false,354
chats_scroll: ScrollHandle::new(),357
chats_scroll: ScrollHandle::new(),355
channels_scroll: ScrollHandle::new(),358
channels_scroll: ScrollHandle::new(),359
calls_scroll: ScrollHandle::new(),356
_subscription: subscription,360
_subscription: subscription,357
}361
}358
}362
}@@ -367,6 +371,18 @@ impl SidebarView {367
cx.notify();371
cx.notify();368
}372
}369
373
374
pub fn show_calls(&mut self, cx: &mut Context<Self>) {375
self.open_tab(SidebarTab::Calls, cx);376
}377
378
fn open_tab(&mut self, tab: SidebarTab, cx: &mut Context<Self>) {379
self.tab = tab;380
if tab == SidebarTab::Calls {381
self.state.update(cx, |state, cx| state.refresh_call_history(cx));382
}383
cx.notify();384
}385
370
pub fn select_adjacent(&mut self, step: Step, cx: &mut Context<Self>) {386
pub fn select_adjacent(&mut self, step: Step, cx: &mut Context<Self>) {371
let selection = match self.tab {387
let selection = match self.tab {372
SidebarTab::Chats => self388
SidebarTab::Chats => self@@ -375,6 +391,7 @@ impl SidebarView {375
.adjacent_chat_id(step)391
.adjacent_chat_id(step)376
.map(Selection::Chat),392
.map(Selection::Chat),377
SidebarTab::Channels => self.adjacent_channel_id(step, cx).map(Selection::Channel),393
SidebarTab::Channels => self.adjacent_channel_id(step, cx).map(Selection::Channel),394
SidebarTab::Calls => None,378
};395
};379
if let Some(selection) = selection {396
if let Some(selection) = selection {380
self.state.update(cx, |state, cx| state.select(selection, cx));397
self.state.update(cx, |state, cx| state.select(selection, cx));@@ -450,10 +467,7 @@ impl SidebarView {450
})467
})451
.child(label.to_owned())468
.child(label.to_owned())452
.children(marker)469
.children(marker)453
.on_click(cx.listener(move |this, _, _, cx| {470
.on_click(cx.listener(move |this, _, _, cx| this.open_tab(tab, cx)))454
this.tab = tab;455
cx.notify();456
}))457
}471
}458
472
459
fn tab_bar(473
fn tab_bar(@@ -482,7 +496,8 @@ impl SidebarView {482
.border_1()496
.border_1()483
.border_color(theme::border())497
.border_color(theme::border())484
.child(self.tab_button(SidebarTab::Chats, "Chats", chat_marker, cx))498
.child(self.tab_button(SidebarTab::Chats, "Chats", chat_marker, cx))485
.child(self.tab_button(SidebarTab::Channels, "Channels", channel_marker, cx)),499
.child(self.tab_button(SidebarTab::Channels, "Channels", channel_marker, cx))500
.child(self.tab_button(SidebarTab::Calls, "Calls", None, cx)),486
)501
)487
.child(self.new_chat_button(cx))502
.child(self.new_chat_button(cx))488
}503
}@@ -1461,6 +1476,7 @@ impl Render for SidebarView {1461
let body = match self.tab {1476
let body = match self.tab {1462
SidebarTab::Chats => self.chats_body(window_height, cx),1477
SidebarTab::Chats => self.chats_body(window_height, cx),1463
SidebarTab::Channels => self.channels_body(cx),1478
SidebarTab::Channels => self.channels_body(cx),1479
SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, cx),1464
};1480
};1465
v_flex()1481
v_flex()1466
.w(px(SIDEBAR_WIDTH))1482
.w(px(SIDEBAR_WIDTH))@@ -0,0 +1,247 @@
1
use gpui_kit::assets::IconName;
2
use gpui_kit::component::{
3
button::{Button, ButtonVariants as _},
4
h_flex,
5
input::{Input, InputEvent, InputState},
6
v_flex,
7
};
8
use gpui_kit::prelude::FluentBuilder as _;
9
use gpui_kit::*;
10
11
use super::avatar::person_avatar;
12
use super::switcher::clamp_highlight;
13
use super::widgets::icon;
14
use crate::app_state::AppState;
15
use crate::call::TransferCandidate;
16
use crate::fuzzy;
17
use crate::theme;
18
19
const MAX_RESULTS: usize = 6;
20
const CARD_WIDTH: f32 = 440.;
21
const CARD_RADIUS: f32 = 12.;
22
const CARD_PADDING: f32 = 16.;
23
const SECTION_GAP: f32 = 12.;
24
const BACKDROP_OPACITY: f32 = 0.55;
25
const ROW_HEIGHT: f32 = 44.;
26
const AVATAR_SIZE: f32 = 28.;
27
const FIELD_HEIGHT: f32 = 36.;
28
const CLOSE_SIZE: f32 = 28.;
29
const DISABLED_OPACITY: f32 = 0.4;
30
31
pub fn visible_candidates(candidates: &[(String, TransferCandidate)], query: &str) -> Vec<TransferCandidate> {
32
fuzzy::rank(query, candidates, MAX_RESULTS)
33
}
34
35
pub struct TransferPicker {
36
app: Entity<AppState>,
37
candidates: Vec<(String, TransferCandidate)>,
38
search: Entity<InputState>,
39
results: Vec<TransferCandidate>,
40
highlighted: usize,
41
target: Option<TransferCandidate>,
42
_subscription: Subscription,
43
}
44
45
impl TransferPicker {
46
pub fn new(app: Entity<AppState>, candidates: Vec<TransferCandidate>, window: &mut Window, cx: &mut Context<Self>) -> Self {
47
let candidates: Vec<(String, TransferCandidate)> = candidates.into_iter().map(|candidate| (candidate.name.clone(), candidate)).collect();
48
let search = cx.new(|cx| InputState::new(window, cx).placeholder("Search people"));
49
let subscription = cx.subscribe_in(&search, window, Self::on_search_event);
50
search.update(cx, |input, cx| input.focus(window, cx));
51
let results = visible_candidates(&candidates, "");
52
TransferPicker { app, candidates, search, results, highlighted: 0, target: None, _subscription: subscription }
53
}
54
55
pub fn choose(&mut self, candidate: TransferCandidate) {
56
self.target = Some(candidate);
57
}
58
59
fn on_search_event(&mut self, input: &Entity<InputState>, event: &InputEvent, _: &mut Window, cx: &mut Context<Self>) {
60
match event {
61
InputEvent::Change => {
62
let query = input.read(cx).value().to_string();
63
self.results = visible_candidates(&self.candidates, &query);
64
self.highlighted = 0;
65
cx.notify();
66
}
67
InputEvent::PressEnter { .. } => {
68
if let Some(candidate) = self.results.get(self.highlighted).cloned() {
69
self.target = Some(candidate);
70
cx.notify();
71
}
72
}
73
_ => {}
74
}
75
}
76
77
fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
78
match event.keystroke.key.as_str() {
79
"escape" => self.close(cx),
80
"down" => {
81
self.highlighted = clamp_highlight(self.highlighted, 1, self.results.len());
82
cx.notify();
83
}
84
"up" => {
85
self.highlighted = clamp_highlight(self.highlighted, -1, self.results.len());
86
cx.notify();
87
}
88
_ => {}
89
}
90
}
91
92
fn close(&self, cx: &mut Context<Self>) {
93
self.app.update(cx, |state, cx| state.close_transfer_picker(cx));
94
}
95
96
fn list(&self, cx: &mut Context<Self>) -> Stateful<Div> {
97
let directory = &self.app.read(cx).directory;
98
let rows: Vec<AnyElement> = self
99
.results
100
.iter()
101
.enumerate()
102
.map(|(index, candidate)| {
103
let chosen = self.target.as_ref() == Some(candidate);
104
let picked = candidate.clone();
105
h_flex()
106
.id(ElementId::Name(format!("transfer-target-{index}").into()))
107
.h(px(ROW_HEIGHT))
108
.flex_none()
109
.px(px(8.))
110
.gap(px(10.))
111
.items_center()
112
.rounded(px(6.))
113
.cursor_pointer()
114
.when(chosen || (self.target.is_none() && index == self.highlighted), |row| row.bg(theme::surface_raised()))
115
.hover(|row| row.bg(theme::row_hover()))
116
.child(person_avatar(directory, candidate.user_id.as_deref(), &candidate.name, AVATAR_SIZE))
117
.child(div().flex_1().min_w_0().truncate().text_size(px(14.)).child(candidate.name.clone()))
118
.when(chosen, |row| row.child(icon(IconName::Check, 16., theme::accent_text())))
119
.on_click(cx.listener(move |this, _, _, cx| {
120
this.choose(picked.clone());
121
cx.notify();
122
}))
123
.into_any_element()
124
})
125
.collect();
126
v_flex().id("transfer-targets").w_full().max_h(px(ROW_HEIGHT * MAX_RESULTS as f32)).overflow_y_scroll().children(rows)
127
}
128
129
fn action(&self, id: &'static str, label: &'static str, primary: bool, run: fn(&mut AppState, TransferCandidate, &mut Context<AppState>)) -> AnyElement {
130
let button = Button::new(id).label(label);
131
let button = if primary { button } else { button.ghost() };
132
let Some(target) = self.target.clone() else {
133
return button.opacity(DISABLED_OPACITY).into_any_element();
134
};
135
let app = self.app.clone();
136
button.on_click(move |_, _, cx| app.update(cx, |state, cx| run(state, target.clone(), cx))).into_any_element()
137
}
138
}
139
140
impl Render for TransferPicker {
141
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
142
let field = h_flex()
143
.w_full()
144
.h(px(FIELD_HEIGHT))
145
.px(px(10.))
146
.gap(px(8.))
147
.items_center()
148
.rounded(px(6.))
149
.bg(theme::surface())
150
.border_1()
151
.border_color(theme::border())
152
.child(icon(IconName::Search, 14., theme::text_muted()))
153
.child(div().flex_1().child(Input::new(&self.search).appearance(false).bordered(false)));
154
let actions = h_flex()
155
.w_full()
156
.justify_end()
157
.gap(px(8.))
158
.child(Button::new("transfer-cancel").ghost().label("Cancel").on_click(cx.listener(|this, _, _, cx| this.close(cx))))
159
.child(self.action("transfer-consult", "Consult first", false, AppState::start_consult))
160
.child(self.action("transfer-now", "Transfer now", true, AppState::transfer_call_blind));
161
div()
162
.id("transfer-layer")
163
.absolute()
164
.top_0()
165
.left_0()
166
.size_full()
167
.flex()
168
.items_center()
169
.justify_center()
170
.child(
171
div()
172
.id("transfer-backdrop")
173
.absolute()
174
.top_0()
175
.left_0()
176
.size_full()
177
.bg(black().opacity(BACKDROP_OPACITY))
178
.occlude()
179
.on_click(cx.listener(|this, _, _, cx| this.close(cx))),
180
)
181
.child(
182
v_flex()
183
.id("transfer-card")
184
.w(px(CARD_WIDTH))
185
.max_w(relative(1.))
186
.p(px(CARD_PADDING))
187
.gap(px(SECTION_GAP))
188
.rounded(px(CARD_RADIUS))
189
.bg(theme::background())
190
.border_1()
191
.border_color(theme::border_strong())
192
.text_color(theme::text())
193
.shadow_lg()
194
.occlude()
195
.on_key_down(cx.listener(Self::on_key_down))
196
.child(
197
h_flex()
198
.w_full()
199
.items_center()
200
.gap(px(SECTION_GAP))
201
.child(div().flex_1().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Transfer call"))
202
.child(
203
div()
204
.id("transfer-close")
205
.size(px(CLOSE_SIZE))
206
.flex_none()
207
.flex()
208
.items_center()
209
.justify_center()
210
.rounded_full()
211
.cursor_pointer()
212
.hover(|button| button.bg(theme::row_hover()))
213
.on_click(cx.listener(|this, _, _, cx| this.close(cx)))
214
.child(icon(IconName::X, 16., theme::text_muted())),
215
),
216
)
217
.child(field)
218
.child(self.list(cx))
219
.child(actions),
220
)
221
}
222
}
223
224
#[cfg(test)]
225
mod tests {
226
use super::{MAX_RESULTS, visible_candidates};
227
use crate::call::TransferCandidate;
228
229
fn candidate(name: &str) -> (String, TransferCandidate) {
230
(name.to_owned(), TransferCandidate { mri: format!("8:orgid:{name}"), name: name.to_owned(), user_id: Some(name.to_owned()), chat_id: format!("19:{name}") })
231
}
232
233
#[test]
234
fn the_search_ranks_people_by_name() {
235
let people = vec![candidate("Ana Weiss"), candidate("Bo Brandt"), candidate("Anja Vogel")];
236
let found: Vec<String> = visible_candidates(&people, "anj").into_iter().map(|person| person.name).collect();
237
assert_eq!(found.first().map(String::as_str), Some("Anja Vogel"));
238
assert_eq!(visible_candidates(&people, "").len(), 3);
239
assert!(visible_candidates(&people, "zzz").is_empty());
240
}
241
242
#[test]
243
fn the_list_is_capped() {
244
let people: Vec<(String, TransferCandidate)> = (0..20).map(|index| candidate(&format!("Person {index}"))).collect();
245
assert_eq!(visible_candidates(&people, "").len(), MAX_RESULTS);
246
}
247
}
@@ -0,0 +1,247 @@1
use gpui_kit::assets::IconName;2
use gpui_kit::component::{3
button::{Button, ButtonVariants as _},4
h_flex,5
input::{Input, InputEvent, InputState},6
v_flex,7
};8
use gpui_kit::prelude::FluentBuilder as _;9
use gpui_kit::*;10
11
use super::avatar::person_avatar;12
use super::switcher::clamp_highlight;13
use super::widgets::icon;14
use crate::app_state::AppState;15
use crate::call::TransferCandidate;16
use crate::fuzzy;17
use crate::theme;18
19
const MAX_RESULTS: usize = 6;20
const CARD_WIDTH: f32 = 440.;21
const CARD_RADIUS: f32 = 12.;22
const CARD_PADDING: f32 = 16.;23
const SECTION_GAP: f32 = 12.;24
const BACKDROP_OPACITY: f32 = 0.55;25
const ROW_HEIGHT: f32 = 44.;26
const AVATAR_SIZE: f32 = 28.;27
const FIELD_HEIGHT: f32 = 36.;28
const CLOSE_SIZE: f32 = 28.;29
const DISABLED_OPACITY: f32 = 0.4;30
31
pub fn visible_candidates(candidates: &[(String, TransferCandidate)], query: &str) -> Vec<TransferCandidate> {32
fuzzy::rank(query, candidates, MAX_RESULTS)33
}34
35
pub struct TransferPicker {36
app: Entity<AppState>,37
candidates: Vec<(String, TransferCandidate)>,38
search: Entity<InputState>,39
results: Vec<TransferCandidate>,40
highlighted: usize,41
target: Option<TransferCandidate>,42
_subscription: Subscription,43
}44
45
impl TransferPicker {46
pub fn new(app: Entity<AppState>, candidates: Vec<TransferCandidate>, window: &mut Window, cx: &mut Context<Self>) -> Self {47
let candidates: Vec<(String, TransferCandidate)> = candidates.into_iter().map(|candidate| (candidate.name.clone(), candidate)).collect();48
let search = cx.new(|cx| InputState::new(window, cx).placeholder("Search people"));49
let subscription = cx.subscribe_in(&search, window, Self::on_search_event);50
search.update(cx, |input, cx| input.focus(window, cx));51
let results = visible_candidates(&candidates, "");52
TransferPicker { app, candidates, search, results, highlighted: 0, target: None, _subscription: subscription }53
}54
55
pub fn choose(&mut self, candidate: TransferCandidate) {56
self.target = Some(candidate);57
}58
59
fn on_search_event(&mut self, input: &Entity<InputState>, event: &InputEvent, _: &mut Window, cx: &mut Context<Self>) {60
match event {61
InputEvent::Change => {62
let query = input.read(cx).value().to_string();63
self.results = visible_candidates(&self.candidates, &query);64
self.highlighted = 0;65
cx.notify();66
}67
InputEvent::PressEnter { .. } => {68
if let Some(candidate) = self.results.get(self.highlighted).cloned() {69
self.target = Some(candidate);70
cx.notify();71
}72
}73
_ => {}74
}75
}76
77
fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {78
match event.keystroke.key.as_str() {79
"escape" => self.close(cx),80
"down" => {81
self.highlighted = clamp_highlight(self.highlighted, 1, self.results.len());82
cx.notify();83
}84
"up" => {85
self.highlighted = clamp_highlight(self.highlighted, -1, self.results.len());86
cx.notify();87
}88
_ => {}89
}90
}91
92
fn close(&self, cx: &mut Context<Self>) {93
self.app.update(cx, |state, cx| state.close_transfer_picker(cx));94
}95
96
fn list(&self, cx: &mut Context<Self>) -> Stateful<Div> {97
let directory = &self.app.read(cx).directory;98
let rows: Vec<AnyElement> = self99
.results100
.iter()101
.enumerate()102
.map(|(index, candidate)| {103
let chosen = self.target.as_ref() == Some(candidate);104
let picked = candidate.clone();105
h_flex()106
.id(ElementId::Name(format!("transfer-target-{index}").into()))107
.h(px(ROW_HEIGHT))108
.flex_none()109
.px(px(8.))110
.gap(px(10.))111
.items_center()112
.rounded(px(6.))113
.cursor_pointer()114
.when(chosen || (self.target.is_none() && index == self.highlighted), |row| row.bg(theme::surface_raised()))115
.hover(|row| row.bg(theme::row_hover()))116
.child(person_avatar(directory, candidate.user_id.as_deref(), &candidate.name, AVATAR_SIZE))117
.child(div().flex_1().min_w_0().truncate().text_size(px(14.)).child(candidate.name.clone()))118
.when(chosen, |row| row.child(icon(IconName::Check, 16., theme::accent_text())))119
.on_click(cx.listener(move |this, _, _, cx| {120
this.choose(picked.clone());121
cx.notify();122
}))123
.into_any_element()124
})125
.collect();126
v_flex().id("transfer-targets").w_full().max_h(px(ROW_HEIGHT * MAX_RESULTS as f32)).overflow_y_scroll().children(rows)127
}128
129
fn action(&self, id: &'static str, label: &'static str, primary: bool, run: fn(&mut AppState, TransferCandidate, &mut Context<AppState>)) -> AnyElement {130
let button = Button::new(id).label(label);131
let button = if primary { button } else { button.ghost() };132
let Some(target) = self.target.clone() else {133
return button.opacity(DISABLED_OPACITY).into_any_element();134
};135
let app = self.app.clone();136
button.on_click(move |_, _, cx| app.update(cx, |state, cx| run(state, target.clone(), cx))).into_any_element()137
}138
}139
140
impl Render for TransferPicker {141
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {142
let field = h_flex()143
.w_full()144
.h(px(FIELD_HEIGHT))145
.px(px(10.))146
.gap(px(8.))147
.items_center()148
.rounded(px(6.))149
.bg(theme::surface())150
.border_1()151
.border_color(theme::border())152
.child(icon(IconName::Search, 14., theme::text_muted()))153
.child(div().flex_1().child(Input::new(&self.search).appearance(false).bordered(false)));154
let actions = h_flex()155
.w_full()156
.justify_end()157
.gap(px(8.))158
.child(Button::new("transfer-cancel").ghost().label("Cancel").on_click(cx.listener(|this, _, _, cx| this.close(cx))))159
.child(self.action("transfer-consult", "Consult first", false, AppState::start_consult))160
.child(self.action("transfer-now", "Transfer now", true, AppState::transfer_call_blind));161
div()162
.id("transfer-layer")163
.absolute()164
.top_0()165
.left_0()166
.size_full()167
.flex()168
.items_center()169
.justify_center()170
.child(171
div()172
.id("transfer-backdrop")173
.absolute()174
.top_0()175
.left_0()176
.size_full()177
.bg(black().opacity(BACKDROP_OPACITY))178
.occlude()179
.on_click(cx.listener(|this, _, _, cx| this.close(cx))),180
)181
.child(182
v_flex()183
.id("transfer-card")184
.w(px(CARD_WIDTH))185
.max_w(relative(1.))186
.p(px(CARD_PADDING))187
.gap(px(SECTION_GAP))188
.rounded(px(CARD_RADIUS))189
.bg(theme::background())190
.border_1()191
.border_color(theme::border_strong())192
.text_color(theme::text())193
.shadow_lg()194
.occlude()195
.on_key_down(cx.listener(Self::on_key_down))196
.child(197
h_flex()198
.w_full()199
.items_center()200
.gap(px(SECTION_GAP))201
.child(div().flex_1().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Transfer call"))202
.child(203
div()204
.id("transfer-close")205
.size(px(CLOSE_SIZE))206
.flex_none()207
.flex()208
.items_center()209
.justify_center()210
.rounded_full()211
.cursor_pointer()212
.hover(|button| button.bg(theme::row_hover()))213
.on_click(cx.listener(|this, _, _, cx| this.close(cx)))214
.child(icon(IconName::X, 16., theme::text_muted())),215
),216
)217
.child(field)218
.child(self.list(cx))219
.child(actions),220
)221
}222
}223
224
#[cfg(test)]225
mod tests {226
use super::{MAX_RESULTS, visible_candidates};227
use crate::call::TransferCandidate;228
229
fn candidate(name: &str) -> (String, TransferCandidate) {230
(name.to_owned(), TransferCandidate { mri: format!("8:orgid:{name}"), name: name.to_owned(), user_id: Some(name.to_owned()), chat_id: format!("19:{name}") })231
}232
233
#[test]234
fn the_search_ranks_people_by_name() {235
let people = vec![candidate("Ana Weiss"), candidate("Bo Brandt"), candidate("Anja Vogel")];236
let found: Vec<String> = visible_candidates(&people, "anj").into_iter().map(|person| person.name).collect();237
assert_eq!(found.first().map(String::as_str), Some("Anja Vogel"));238
assert_eq!(visible_candidates(&people, "").len(), 3);239
assert!(visible_candidates(&people, "zzz").is_empty());240
}241
242
#[test]243
fn the_list_is_capped() {244
let people: Vec<(String, TransferCandidate)> = (0..20).map(|index| candidate(&format!("Person {index}"))).collect();245
assert_eq!(visible_candidates(&people, "").len(), MAX_RESULTS);246
}247
}@@ -11,6 +11,7 @@ chrono.workspace = true
11
11
cpal = "0.17"
12
12
chatsvc.workspace = true
13
13
flate2 = "1"
14
image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }
14
15
futures-util.workspace = true
15
16
libwebrtc = { version = "0.3.51", features = ["glib-main-loop"] }
16
17
nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }
@@ -11,6 +11,7 @@ chrono.workspace = true11
cpal = "0.17"11
cpal = "0.17"12
chatsvc.workspace = true12
chatsvc.workspace = true13
flate2 = "1"13
flate2 = "1"14
image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }14
futures-util.workspace = true15
futures-util.workspace = true15
libwebrtc = { version = "0.3.51", features = ["glib-main-loop"] }16
libwebrtc = { version = "0.3.51", features = ["glib-main-loop"] }16
nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }17
nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }@@ -20,7 +20,7 @@ fn main() {
20
20
let mut blur = BackgroundBlur::new().expect("model");
21
21
let segmenter = Segmenter::new().expect("model");
22
22
for _ in 0..WARMUP {
23
blur.apply(&mut frame.clone(), WIDTH, HEIGHT);
23
blur.apply(&mut frame.clone(), WIDTH, HEIGHT, None);
24
24
}
25
25
let started = Instant::now();
26
26
for _ in 0..FRAMES {
@@ -31,7 +31,7 @@ fn main() {
31
31
let mut result = frame.clone();
32
32
for _ in 0..FRAMES {
33
33
result.copy_from_slice(&frame);
34
blur.apply(&mut result, WIDTH, HEIGHT);
34
blur.apply(&mut result, WIDTH, HEIGHT, None);
35
35
}
36
36
println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame (running average {:.2} ms)", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64, blur.average_ms());
37
37
if let Some(path) = output {
@@ -20,7 +20,7 @@ fn main() {20
let mut blur = BackgroundBlur::new().expect("model");20
let mut blur = BackgroundBlur::new().expect("model");21
let segmenter = Segmenter::new().expect("model");21
let segmenter = Segmenter::new().expect("model");22
for _ in 0..WARMUP {22
for _ in 0..WARMUP {23
blur.apply(&mut frame.clone(), WIDTH, HEIGHT);23
blur.apply(&mut frame.clone(), WIDTH, HEIGHT, None);24
}24
}25
let started = Instant::now();25
let started = Instant::now();26
for _ in 0..FRAMES {26
for _ in 0..FRAMES {@@ -31,7 +31,7 @@ fn main() {31
let mut result = frame.clone();31
let mut result = frame.clone();32
for _ in 0..FRAMES {32
for _ in 0..FRAMES {33
result.copy_from_slice(&frame);33
result.copy_from_slice(&frame);34
blur.apply(&mut result, WIDTH, HEIGHT);34
blur.apply(&mut result, WIDTH, HEIGHT, None);35
}35
}36
println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame (running average {:.2} ms)", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64, blur.average_ms());36
println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame (running average {:.2} ms)", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64, blur.average_ms());37
if let Some(path) = output {37
if let Some(path) = output {@@ -0,0 +1,38 @@
1
use chrono::{DateTime, Duration, Utc};
2
use serde_json::Value;
3
use session::{DEFAULT_ENDPOINT, Method, Scope, Session};
4
5
const LIST_URL: &str = "https://graph.microsoft.com/v1.0/me/drive/root:/Videos/Recordings:/children?$select=id,name,createdDateTime&$top=50";
6
const SUBJECT: &str = "Native client test";
7
8
#[tokio::main]
9
async fn main() {
10
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
11
let session = Session::connect(&endpoint).await.expect("browser");
12
let scope = Scope::graph("Files.ReadWrite.All");
13
let listed = session.request(Method::Get, LIST_URL, &scope, None).await.expect("list");
14
println!("# list: HTTP {}", listed.status);
15
let cutoff = Utc::now() - Duration::minutes(60);
16
let items = listed.body.get("value").and_then(Value::as_array).cloned().unwrap_or_default();
17
let mut deleted = 0;
18
for item in items {
19
let name = item.get("name").and_then(Value::as_str).unwrap_or_default();
20
let created = item
21
.get("createdDateTime")
22
.and_then(Value::as_str)
23
.and_then(|text| DateTime::parse_from_rfc3339(text).ok())
24
.map(|time| time.with_timezone(&Utc));
25
let recent = created.is_some_and(|time| time > cutoff);
26
if recent {
27
println!("# recent recording, starts with test subject: {}", name.starts_with(SUBJECT));
28
}
29
if recent && name.starts_with(SUBJECT) {
30
let id = item.get("id").and_then(Value::as_str).unwrap_or_default();
31
let url = format!("https://graph.microsoft.com/v1.0/me/drive/items/{id}");
32
let answer = session.request(Method::Delete, &url, &scope, None).await.expect("delete");
33
println!("# delete recent test recording: HTTP {}", answer.status);
34
deleted += 1;
35
}
36
}
37
println!("# deleted {deleted} test recording(s)");
38
}
@@ -0,0 +1,38 @@1
use chrono::{DateTime, Duration, Utc};2
use serde_json::Value;3
use session::{DEFAULT_ENDPOINT, Method, Scope, Session};4
5
const LIST_URL: &str = "https://graph.microsoft.com/v1.0/me/drive/root:/Videos/Recordings:/children?$select=id,name,createdDateTime&$top=50";6
const SUBJECT: &str = "Native client test";7
8
#[tokio::main]9
async fn main() {10
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());11
let session = Session::connect(&endpoint).await.expect("browser");12
let scope = Scope::graph("Files.ReadWrite.All");13
let listed = session.request(Method::Get, LIST_URL, &scope, None).await.expect("list");14
println!("# list: HTTP {}", listed.status);15
let cutoff = Utc::now() - Duration::minutes(60);16
let items = listed.body.get("value").and_then(Value::as_array).cloned().unwrap_or_default();17
let mut deleted = 0;18
for item in items {19
let name = item.get("name").and_then(Value::as_str).unwrap_or_default();20
let created = item21
.get("createdDateTime")22
.and_then(Value::as_str)23
.and_then(|text| DateTime::parse_from_rfc3339(text).ok())24
.map(|time| time.with_timezone(&Utc));25
let recent = created.is_some_and(|time| time > cutoff);26
if recent {27
println!("# recent recording, starts with test subject: {}", name.starts_with(SUBJECT));28
}29
if recent && name.starts_with(SUBJECT) {30
let id = item.get("id").and_then(Value::as_str).unwrap_or_default();31
let url = format!("https://graph.microsoft.com/v1.0/me/drive/items/{id}");32
let answer = session.request(Method::Delete, &url, &scope, None).await.expect("delete");33
println!("# delete recent test recording: HTTP {}", answer.status);34
deleted += 1;35
}36
}37
println!("# deleted {deleted} test recording(s)");38
}@@ -4,7 +4,10 @@ use std::time::{Duration, Instant};
4
4
use calling::meeting::fetch_live_meeting;
5
5
use calling::relay::ic3_scope;
6
6
use calling::signaling::{CHATSVC_REGION, fetch_self};
7
use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingTarget, Reaction, ShareKind, ShareSource};
7
use calling::{
8
BackgroundCache, BackgroundChoice, CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingTarget, Reaction, ShareKind,
9
ShareSource,
10
};
8
11
use chatsvc::InstanceNames;
9
12
use serde_json::{Value, json};
10
13
use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};
@@ -23,8 +26,12 @@ const THREAD_PROPERTY_RETRIES: usize = 8;
23
26
const CAPTIONS_HOLD: Duration = Duration::from_secs(10);
24
27
const FEATURE_LIMIT: Duration = Duration::from_secs(90);
25
28
const VIDEO_ENV: &str = "CALLING_VIDEO";
29
const RECORD_HOLD: Duration = Duration::from_secs(10);
30
const WHITEBOARD_WAIT: Duration = Duration::from_secs(45);
31
const BACKGROUND_CACHE: &str = "calling-meet-now-backgrounds";
26
32
27
33
struct Arguments {
34
resolve_by_id: bool,
28
35
camera: bool,
29
36
share: bool,
30
37
extras: bool,
@@ -32,6 +39,9 @@ struct Arguments {
32
39
captions: bool,
33
40
mute_all: bool,
34
41
blur: bool,
42
record: bool,
43
whiteboard_state: bool,
44
background: bool,
35
45
stop_media_after: Option<Duration>,
36
46
hold: Duration,
37
47
thread_out: Option<PathBuf>,
@@ -40,6 +50,7 @@ struct Arguments {
40
50
41
51
fn arguments() -> Arguments {
42
52
let mut parsed = Arguments {
53
resolve_by_id: false,
43
54
camera: false,
44
55
share: false,
45
56
extras: false,
@@ -47,6 +58,9 @@ fn arguments() -> Arguments {
47
58
captions: false,
48
59
mute_all: false,
49
60
blur: false,
61
record: false,
62
whiteboard_state: false,
63
background: false,
50
64
stop_media_after: None,
51
65
hold: Duration::from_secs(10),
52
66
thread_out: None,
@@ -65,6 +79,13 @@ fn arguments() -> Arguments {
65
79
parsed.blur = true;
66
80
parsed.camera = true;
67
81
}
82
"--record" => parsed.record = true,
83
"--whiteboard-state" => parsed.whiteboard_state = true,
84
"--resolve-by-id" => parsed.resolve_by_id = true,
85
"--background" => {
86
parsed.background = true;
87
parsed.camera = true;
88
}
68
89
"--stop-media-after" => parsed.stop_media_after = input.next().and_then(|value| value.parse().ok()).map(Duration::from_secs),
69
90
"--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),
70
91
"--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
@@ -102,7 +123,8 @@ async fn tenant_and_organizer(session: &Session, thread_id: &str) -> (Option<Str
102
123
}
103
124
104
125
fn main() {
105
if arguments().blur && std::env::var_os(VIDEO_ENV).is_none() {
126
let flags = arguments();
127
if (flags.blur || flags.background) && std::env::var_os(VIDEO_ENV).is_none() {
106
128
// SAFETY: nothing else runs yet; the runtime below starts after this.
107
129
unsafe { std::env::set_var(VIDEO_ENV, "pattern") };
108
130
}
@@ -130,6 +152,13 @@ struct Features {
130
152
caption_events: usize,
131
153
blur_reports: usize,
132
154
blur_total_ms: f64,
155
recording_seen_on: bool,
156
recording_seen_off: bool,
157
recording_stop_due: Option<Instant>,
158
recording_done: bool,
159
whiteboard_url_seen: bool,
160
whiteboard_share_seen: bool,
161
whiteboard_wait_until: Option<Instant>,
133
162
deadline: Option<Instant>,
134
163
}
135
164
@@ -138,7 +167,10 @@ impl Features {
138
167
if self.deadline.is_none_or(|deadline| Instant::now() >= deadline) {
139
168
return false;
140
169
}
141
(arguments.spotlight_self && !self.spotlight_cleared) || (arguments.captions && !self.captions_stopped)
170
(arguments.spotlight_self && !self.spotlight_cleared)
171
|| (arguments.captions && !self.captions_stopped)
172
|| (arguments.record && !self.recording_done)
173
|| (arguments.whiteboard_state && self.whiteboard_wait_until.is_none_or(|until| Instant::now() < until) && !self.whiteboard_share_seen)
142
174
}
143
175
}
144
176
@@ -151,8 +183,8 @@ async fn run() {
151
183
152
184
let started = Instant::now();
153
185
let reused = std::env::args().skip_while(|argument| argument != "--thread").nth(1);
154
let thread_id = match reused {
155
Some(thread_id) => thread_id,
186
let (thread_id, created_meeting) = match reused {
187
Some(thread_id) => (thread_id, None),
156
188
None => {
157
189
let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});
158
190
let created = session
@@ -160,7 +192,8 @@ async fn run() {
160
192
.await
161
193
.expect("create meeting");
162
194
println!("# create MeetNow: HTTP {} after {:?}", created.status, started.elapsed());
163
created.body.pointer("/value/groupContext/threadId").and_then(Value::as_str).expect("meeting thread").to_owned()
195
let thread_id = created.body.pointer("/value/groupContext/threadId").and_then(Value::as_str).expect("meeting thread").to_owned();
196
(thread_id, Some(created.body))
164
197
}
165
198
};
166
199
if let Some(path) = &arguments.thread_out {
@@ -200,6 +233,11 @@ async fn run() {
200
233
};
201
234
let (engine, _events) = CallEngine::start(session.clone(), poll_session, config).await.expect("engine");
202
235
println!("# engine ready after {:?}", started.elapsed());
236
if arguments.resolve_by_id
237
&& let Some(created) = &created_meeting
238
{
239
check_resolve_by_id(&engine, created, &thread_id).await;
240
}
203
241
let join_started = Instant::now();
204
242
let mut handle = engine.start_call(CallSpec::Meeting(target));
205
243
@@ -234,7 +272,30 @@ async fn run() {
234
272
sharing = label.is_some();
235
273
println!("# local share update: {}", label.is_some());
236
274
}
237
Some(CallUpdate::Notice(text)) => println!("# notice: {text}"),
275
Some(CallUpdate::Notice(text)) => {
276
println!("# notice: {text}");
277
if arguments.record && text.to_ascii_lowercase().contains("recording") && !features.recording_seen_on {
278
features.recording_done = true;
279
}
280
}
281
Some(CallUpdate::Recording(on)) => {
282
println!("# recording state: {}", if on { "on" } else { "off" });
283
if on {
284
features.recording_seen_on = true;
285
features.recording_stop_due = Some(Instant::now() + RECORD_HOLD);
286
} else if features.recording_seen_on {
287
features.recording_seen_off = true;
288
features.recording_done = true;
289
}
290
}
291
Some(CallUpdate::Whiteboard(share)) => {
292
println!("# whiteboard share: {}", share.as_ref().map_or_else(|| "ended".to_owned(), |share| format!("presenter {:?}, whiteboard {}, url {}", share.presenter, share.whiteboard, share.url.is_some())));
293
features.whiteboard_share_seen |= share.is_some();
294
}
295
Some(CallUpdate::WhiteboardUrl(url)) => {
296
features.whiteboard_url_seen = true;
297
println!("# whiteboard board url fetched: host {}", url.split('/').nth(2).unwrap_or("?"));
298
}
238
299
Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),
239
300
Some(CallUpdate::OwnIdentity { mri }) => features.own_mri = Some(mri),
240
301
Some(CallUpdate::Captions(state)) => {
@@ -323,6 +384,10 @@ async fn run() {
323
384
features.captions_stopped = true;
324
385
let _ = handle.commands.send(CallCommand::SetCaptions(false));
325
386
}
387
if features.recording_stop_due.is_some_and(|due| Instant::now() >= due) {
388
features.recording_stop_due = None;
389
let _ = handle.commands.send(CallCommand::SetRecording { on: false, title: SUBJECT.to_owned() });
390
}
326
391
if hand_lower_due.is_some_and(|due| Instant::now() >= due) {
327
392
hand_lower_due = None;
328
393
let _ = handle.commands.send(CallCommand::SetHand(false));
@@ -355,7 +420,21 @@ async fn run() {
355
420
let _ = handle.commands.send(CallCommand::SetCaptions(true));
356
421
}
357
422
if arguments.blur {
358
let _ = handle.commands.send(CallCommand::SetBlur(true));
423
let _ = handle.commands.send(CallCommand::SetBackground(BackgroundChoice::Blur));
424
}
425
if arguments.record {
426
let _ = handle.commands.send(CallCommand::SetRecording { on: true, title: SUBJECT.to_owned() });
427
}
428
if arguments.whiteboard_state {
429
features.whiteboard_wait_until = Some(Instant::now() + WHITEBOARD_WAIT);
430
println!("# whiteboard: fetching the board url, then waiting {WHITEBOARD_WAIT:?} for a whiteboard share (start one from Teams web in this meeting)");
431
let _ = handle.commands.send(CallCommand::OpenWhiteboard { title: SUBJECT.to_owned() });
432
}
433
if arguments.background {
434
let image = background_image(&session).await;
435
if let Some(path) = image {
436
let _ = handle.commands.send(CallCommand::SetBackground(BackgroundChoice::Image(path)));
437
}
359
438
}
360
439
if arguments.share {
361
440
let source = ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() };
@@ -406,9 +485,16 @@ async fn run() {
406
485
if arguments.captions {
407
486
println!("# captions: became active {}, caption events {}", features.captions_active, features.caption_events);
408
487
}
409
if arguments.blur {
488
if arguments.blur || arguments.background {
410
489
let average = if features.blur_reports == 0 { 0. } else { features.blur_total_ms / features.blur_reports as f64 };
411
println!("# blur: average processing {average:.1} ms over {} report(s)", features.blur_reports);
490
let label = if arguments.background { "background image" } else { "blur" };
491
println!("# {label}: average processing {average:.1} ms over {} report(s)", features.blur_reports);
492
}
493
if arguments.record {
494
println!("# recording: seen on {}, seen off {}", features.recording_seen_on, features.recording_seen_off);
495
}
496
if arguments.whiteboard_state {
497
println!("# whiteboard: board url fetched {}, share update parsed {}", features.whiteboard_url_seen, features.whiteboard_share_seen);
412
498
}
413
499
let gone_started = Instant::now();
414
500
let mut gone_after = None;
@@ -424,6 +510,33 @@ async fn run() {
424
510
println!("# engine stopped, total {:?}", started.elapsed());
425
511
}
426
512
513
async fn background_image(session: &Session) -> Option<PathBuf> {
514
let cache = BackgroundCache::new(std::env::temp_dir().join(BACKGROUND_CACHE));
515
let catalog = match cache.refresh_catalog(session).await {
516
Ok(catalog) => catalog,
517
Err(error) => {
518
println!("# background image list failed: {error}");
519
return None;
520
}
521
};
522
println!("# background image list downloaded: {} entries", catalog.len());
523
let first = catalog.first()?;
524
match cache.ensure_thumbnail(session, first).await {
525
Ok(path) => println!("# first thumbnail cached: {} bytes", std::fs::metadata(&path).map_or(0, |meta| meta.len())),
526
Err(error) => println!("# first thumbnail failed: {error}"),
527
}
528
match cache.ensure_image(session, first).await {
529
Ok(path) => {
530
println!("# first image {} cached: {} bytes", first.id, std::fs::metadata(&path).map_or(0, |meta| meta.len()));
531
Some(path)
532
}
533
Err(error) => {
534
println!("# first image failed: {error}");
535
None
536
}
537
}
538
}
539
427
540
fn urlencoding_component(value: &str) -> String {
428
541
value
429
542
.bytes()
@@ -433,3 +546,45 @@ fn urlencoding_component(value: &str) -> String {
433
546
})
434
547
.collect()
435
548
}
549
550
fn find_text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
551
match value {
552
Value::Object(map) => {
553
for (key, inner) in map {
554
if keys.iter().any(|wanted| key.eq_ignore_ascii_case(wanted))
555
&& let Some(text) = inner.as_str().filter(|text| !text.is_empty())
556
{
557
return Some(text);
558
}
559
if let Some(found) = find_text(inner, keys) {
560
return Some(found);
561
}
562
}
563
None
564
}
565
Value::Array(items) => items.iter().find_map(|item| find_text(item, keys)),
566
_ => None,
567
}
568
}
569
570
async fn check_resolve_by_id(engine: &CallEngine, created: &Value, thread_id: &str) {
571
let code = find_text(created, &["joinMeetingId", "meetingCode"]).map(|code| code.replace(' ', ""));
572
let passcode = find_text(created, &["passcode"]);
573
println!("# resolve by id: meeting id found {}, passcode found {}", code.is_some(), passcode.is_some());
574
let Some(code) = code else {
575
return;
576
};
577
let url = match passcode {
578
Some(passcode) => format!("https://teams.microsoft.com/meet/{code}?p={passcode}"),
579
None => format!("https://teams.microsoft.com/meet/{code}"),
580
};
581
let meeting_data = json!({"meetingCode": code, "passcode": passcode, "meetingUrl": url});
582
match engine.resolve_meeting(&meeting_data).await {
583
Ok(target) => println!(
584
"# resolve by id: found, same thread {}, tenant and organizer present {}",
585
target.thread_id == thread_id,
586
!target.tenant_id.is_empty() && !target.organizer_id.is_empty()
587
),
588
Err(error) => println!("# resolve by id: failed: {}", error.to_string().chars().take(160).collect::<String>()),
589
}
590
}
@@ -4,7 +4,10 @@ use std::time::{Duration, Instant};4
use calling::meeting::fetch_live_meeting;4
use calling::meeting::fetch_live_meeting;5
use calling::relay::ic3_scope;5
use calling::relay::ic3_scope;6
use calling::signaling::{CHATSVC_REGION, fetch_self};6
use calling::signaling::{CHATSVC_REGION, fetch_self};7
use calling::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingTarget, Reaction, ShareKind, ShareSource};7
use calling::{8
BackgroundCache, BackgroundChoice, CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingTarget, Reaction, ShareKind,9
ShareSource,10
};8
use chatsvc::InstanceNames;11
use chatsvc::InstanceNames;9
use serde_json::{Value, json};12
use serde_json::{Value, json};10
use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};13
use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};@@ -23,8 +26,12 @@ const THREAD_PROPERTY_RETRIES: usize = 8;23
const CAPTIONS_HOLD: Duration = Duration::from_secs(10);26
const CAPTIONS_HOLD: Duration = Duration::from_secs(10);24
const FEATURE_LIMIT: Duration = Duration::from_secs(90);27
const FEATURE_LIMIT: Duration = Duration::from_secs(90);25
const VIDEO_ENV: &str = "CALLING_VIDEO";28
const VIDEO_ENV: &str = "CALLING_VIDEO";29
const RECORD_HOLD: Duration = Duration::from_secs(10);30
const WHITEBOARD_WAIT: Duration = Duration::from_secs(45);31
const BACKGROUND_CACHE: &str = "calling-meet-now-backgrounds";26
32
27
struct Arguments {33
struct Arguments {34
resolve_by_id: bool,28
camera: bool,35
camera: bool,29
share: bool,36
share: bool,30
extras: bool,37
extras: bool,@@ -32,6 +39,9 @@ struct Arguments {32
captions: bool,39
captions: bool,33
mute_all: bool,40
mute_all: bool,34
blur: bool,41
blur: bool,42
record: bool,43
whiteboard_state: bool,44
background: bool,35
stop_media_after: Option<Duration>,45
stop_media_after: Option<Duration>,36
hold: Duration,46
hold: Duration,37
thread_out: Option<PathBuf>,47
thread_out: Option<PathBuf>,@@ -40,6 +50,7 @@ struct Arguments {40
50
41
fn arguments() -> Arguments {51
fn arguments() -> Arguments {42
let mut parsed = Arguments {52
let mut parsed = Arguments {53
resolve_by_id: false,43
camera: false,54
camera: false,44
share: false,55
share: false,45
extras: false,56
extras: false,@@ -47,6 +58,9 @@ fn arguments() -> Arguments {47
captions: false,58
captions: false,48
mute_all: false,59
mute_all: false,49
blur: false,60
blur: false,61
record: false,62
whiteboard_state: false,63
background: false,50
stop_media_after: None,64
stop_media_after: None,51
hold: Duration::from_secs(10),65
hold: Duration::from_secs(10),52
thread_out: None,66
thread_out: None,@@ -65,6 +79,13 @@ fn arguments() -> Arguments {65
parsed.blur = true;79
parsed.blur = true;66
parsed.camera = true;80
parsed.camera = true;67
}81
}82
"--record" => parsed.record = true,83
"--whiteboard-state" => parsed.whiteboard_state = true,84
"--resolve-by-id" => parsed.resolve_by_id = true,85
"--background" => {86
parsed.background = true;87
parsed.camera = true;88
}68
"--stop-media-after" => parsed.stop_media_after = input.next().and_then(|value| value.parse().ok()).map(Duration::from_secs),89
"--stop-media-after" => parsed.stop_media_after = input.next().and_then(|value| value.parse().ok()).map(Duration::from_secs),69
"--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),90
"--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),70
"--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),91
"--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),@@ -102,7 +123,8 @@ async fn tenant_and_organizer(session: &Session, thread_id: &str) -> (Option<Str102
}123
}103
124
104
fn main() {125
fn main() {105
if arguments().blur && std::env::var_os(VIDEO_ENV).is_none() {126
let flags = arguments();127
if (flags.blur || flags.background) && std::env::var_os(VIDEO_ENV).is_none() {106
// SAFETY: nothing else runs yet; the runtime below starts after this.128
// SAFETY: nothing else runs yet; the runtime below starts after this.107
unsafe { std::env::set_var(VIDEO_ENV, "pattern") };129
unsafe { std::env::set_var(VIDEO_ENV, "pattern") };108
}130
}@@ -130,6 +152,13 @@ struct Features {130
caption_events: usize,152
caption_events: usize,131
blur_reports: usize,153
blur_reports: usize,132
blur_total_ms: f64,154
blur_total_ms: f64,155
recording_seen_on: bool,156
recording_seen_off: bool,157
recording_stop_due: Option<Instant>,158
recording_done: bool,159
whiteboard_url_seen: bool,160
whiteboard_share_seen: bool,161
whiteboard_wait_until: Option<Instant>,133
deadline: Option<Instant>,162
deadline: Option<Instant>,134
}163
}135
164
@@ -138,7 +167,10 @@ impl Features {138
if self.deadline.is_none_or(|deadline| Instant::now() >= deadline) {167
if self.deadline.is_none_or(|deadline| Instant::now() >= deadline) {139
return false;168
return false;140
}169
}141
(arguments.spotlight_self && !self.spotlight_cleared) || (arguments.captions && !self.captions_stopped)170
(arguments.spotlight_self && !self.spotlight_cleared)171
|| (arguments.captions && !self.captions_stopped)172
|| (arguments.record && !self.recording_done)173
|| (arguments.whiteboard_state && self.whiteboard_wait_until.is_none_or(|until| Instant::now() < until) && !self.whiteboard_share_seen)142
}174
}143
}175
}144
176
@@ -151,8 +183,8 @@ async fn run() {151
183
152
let started = Instant::now();184
let started = Instant::now();153
let reused = std::env::args().skip_while(|argument| argument != "--thread").nth(1);185
let reused = std::env::args().skip_while(|argument| argument != "--thread").nth(1);154
let thread_id = match reused {186
let (thread_id, created_meeting) = match reused {155
Some(thread_id) => thread_id,187
Some(thread_id) => (thread_id, None),156
None => {188
None => {157
let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});189
let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});158
let created = session190
let created = session@@ -160,7 +192,8 @@ async fn run() {160
.await192
.await161
.expect("create meeting");193
.expect("create meeting");162
println!("# create MeetNow: HTTP {} after {:?}", created.status, started.elapsed());194
println!("# create MeetNow: HTTP {} after {:?}", created.status, started.elapsed());163
created.body.pointer("/value/groupContext/threadId").and_then(Value::as_str).expect("meeting thread").to_owned()195
let thread_id = created.body.pointer("/value/groupContext/threadId").and_then(Value::as_str).expect("meeting thread").to_owned();196
(thread_id, Some(created.body))164
}197
}165
};198
};166
if let Some(path) = &arguments.thread_out {199
if let Some(path) = &arguments.thread_out {@@ -200,6 +233,11 @@ async fn run() {200
};233
};201
let (engine, _events) = CallEngine::start(session.clone(), poll_session, config).await.expect("engine");234
let (engine, _events) = CallEngine::start(session.clone(), poll_session, config).await.expect("engine");202
println!("# engine ready after {:?}", started.elapsed());235
println!("# engine ready after {:?}", started.elapsed());236
if arguments.resolve_by_id237
&& let Some(created) = &created_meeting238
{239
check_resolve_by_id(&engine, created, &thread_id).await;240
}203
let join_started = Instant::now();241
let join_started = Instant::now();204
let mut handle = engine.start_call(CallSpec::Meeting(target));242
let mut handle = engine.start_call(CallSpec::Meeting(target));205
243
@@ -234,7 +272,30 @@ async fn run() {234
sharing = label.is_some();272
sharing = label.is_some();235
println!("# local share update: {}", label.is_some());273
println!("# local share update: {}", label.is_some());236
}274
}237
Some(CallUpdate::Notice(text)) => println!("# notice: {text}"),275
Some(CallUpdate::Notice(text)) => {276
println!("# notice: {text}");277
if arguments.record && text.to_ascii_lowercase().contains("recording") && !features.recording_seen_on {278
features.recording_done = true;279
}280
}281
Some(CallUpdate::Recording(on)) => {282
println!("# recording state: {}", if on { "on" } else { "off" });283
if on {284
features.recording_seen_on = true;285
features.recording_stop_due = Some(Instant::now() + RECORD_HOLD);286
} else if features.recording_seen_on {287
features.recording_seen_off = true;288
features.recording_done = true;289
}290
}291
Some(CallUpdate::Whiteboard(share)) => {292
println!("# whiteboard share: {}", share.as_ref().map_or_else(|| "ended".to_owned(), |share| format!("presenter {:?}, whiteboard {}, url {}", share.presenter, share.whiteboard, share.url.is_some())));293
features.whiteboard_share_seen |= share.is_some();294
}295
Some(CallUpdate::WhiteboardUrl(url)) => {296
features.whiteboard_url_seen = true;297
println!("# whiteboard board url fetched: host {}", url.split('/').nth(2).unwrap_or("?"));298
}238
Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),299
Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),239
Some(CallUpdate::OwnIdentity { mri }) => features.own_mri = Some(mri),300
Some(CallUpdate::OwnIdentity { mri }) => features.own_mri = Some(mri),240
Some(CallUpdate::Captions(state)) => {301
Some(CallUpdate::Captions(state)) => {@@ -323,6 +384,10 @@ async fn run() {323
features.captions_stopped = true;384
features.captions_stopped = true;324
let _ = handle.commands.send(CallCommand::SetCaptions(false));385
let _ = handle.commands.send(CallCommand::SetCaptions(false));325
}386
}387
if features.recording_stop_due.is_some_and(|due| Instant::now() >= due) {388
features.recording_stop_due = None;389
let _ = handle.commands.send(CallCommand::SetRecording { on: false, title: SUBJECT.to_owned() });390
}326
if hand_lower_due.is_some_and(|due| Instant::now() >= due) {391
if hand_lower_due.is_some_and(|due| Instant::now() >= due) {327
hand_lower_due = None;392
hand_lower_due = None;328
let _ = handle.commands.send(CallCommand::SetHand(false));393
let _ = handle.commands.send(CallCommand::SetHand(false));@@ -355,7 +420,21 @@ async fn run() {355
let _ = handle.commands.send(CallCommand::SetCaptions(true));420
let _ = handle.commands.send(CallCommand::SetCaptions(true));356
}421
}357
if arguments.blur {422
if arguments.blur {358
let _ = handle.commands.send(CallCommand::SetBlur(true));423
let _ = handle.commands.send(CallCommand::SetBackground(BackgroundChoice::Blur));424
}425
if arguments.record {426
let _ = handle.commands.send(CallCommand::SetRecording { on: true, title: SUBJECT.to_owned() });427
}428
if arguments.whiteboard_state {429
features.whiteboard_wait_until = Some(Instant::now() + WHITEBOARD_WAIT);430
println!("# whiteboard: fetching the board url, then waiting {WHITEBOARD_WAIT:?} for a whiteboard share (start one from Teams web in this meeting)");431
let _ = handle.commands.send(CallCommand::OpenWhiteboard { title: SUBJECT.to_owned() });432
}433
if arguments.background {434
let image = background_image(&session).await;435
if let Some(path) = image {436
let _ = handle.commands.send(CallCommand::SetBackground(BackgroundChoice::Image(path)));437
}359
}438
}360
if arguments.share {439
if arguments.share {361
let source = ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() };440
let source = ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() };@@ -406,9 +485,16 @@ async fn run() {406
if arguments.captions {485
if arguments.captions {407
println!("# captions: became active {}, caption events {}", features.captions_active, features.caption_events);486
println!("# captions: became active {}, caption events {}", features.captions_active, features.caption_events);408
}487
}409
if arguments.blur {488
if arguments.blur || arguments.background {410
let average = if features.blur_reports == 0 { 0. } else { features.blur_total_ms / features.blur_reports as f64 };489
let average = if features.blur_reports == 0 { 0. } else { features.blur_total_ms / features.blur_reports as f64 };411
println!("# blur: average processing {average:.1} ms over {} report(s)", features.blur_reports);490
let label = if arguments.background { "background image" } else { "blur" };491
println!("# {label}: average processing {average:.1} ms over {} report(s)", features.blur_reports);492
}493
if arguments.record {494
println!("# recording: seen on {}, seen off {}", features.recording_seen_on, features.recording_seen_off);495
}496
if arguments.whiteboard_state {497
println!("# whiteboard: board url fetched {}, share update parsed {}", features.whiteboard_url_seen, features.whiteboard_share_seen);412
}498
}413
let gone_started = Instant::now();499
let gone_started = Instant::now();414
let mut gone_after = None;500
let mut gone_after = None;@@ -424,6 +510,33 @@ async fn run() {424
println!("# engine stopped, total {:?}", started.elapsed());510
println!("# engine stopped, total {:?}", started.elapsed());425
}511
}426
512
513
async fn background_image(session: &Session) -> Option<PathBuf> {514
let cache = BackgroundCache::new(std::env::temp_dir().join(BACKGROUND_CACHE));515
let catalog = match cache.refresh_catalog(session).await {516
Ok(catalog) => catalog,517
Err(error) => {518
println!("# background image list failed: {error}");519
return None;520
}521
};522
println!("# background image list downloaded: {} entries", catalog.len());523
let first = catalog.first()?;524
match cache.ensure_thumbnail(session, first).await {525
Ok(path) => println!("# first thumbnail cached: {} bytes", std::fs::metadata(&path).map_or(0, |meta| meta.len())),526
Err(error) => println!("# first thumbnail failed: {error}"),527
}528
match cache.ensure_image(session, first).await {529
Ok(path) => {530
println!("# first image {} cached: {} bytes", first.id, std::fs::metadata(&path).map_or(0, |meta| meta.len()));531
Some(path)532
}533
Err(error) => {534
println!("# first image failed: {error}");535
None536
}537
}538
}539
427
fn urlencoding_component(value: &str) -> String {540
fn urlencoding_component(value: &str) -> String {428
value541
value429
.bytes()542
.bytes()@@ -433,3 +546,45 @@ fn urlencoding_component(value: &str) -> String {433
})546
})434
.collect()547
.collect()435
}548
}549
550
fn find_text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {551
match value {552
Value::Object(map) => {553
for (key, inner) in map {554
if keys.iter().any(|wanted| key.eq_ignore_ascii_case(wanted))555
&& let Some(text) = inner.as_str().filter(|text| !text.is_empty())556
{557
return Some(text);558
}559
if let Some(found) = find_text(inner, keys) {560
return Some(found);561
}562
}563
None564
}565
Value::Array(items) => items.iter().find_map(|item| find_text(item, keys)),566
_ => None,567
}568
}569
570
async fn check_resolve_by_id(engine: &CallEngine, created: &Value, thread_id: &str) {571
let code = find_text(created, &["joinMeetingId", "meetingCode"]).map(|code| code.replace(' ', ""));572
let passcode = find_text(created, &["passcode"]);573
println!("# resolve by id: meeting id found {}, passcode found {}", code.is_some(), passcode.is_some());574
let Some(code) = code else {575
return;576
};577
let url = match passcode {578
Some(passcode) => format!("https://teams.microsoft.com/meet/{code}?p={passcode}"),579
None => format!("https://teams.microsoft.com/meet/{code}"),580
};581
let meeting_data = json!({"meetingCode": code, "passcode": passcode, "meetingUrl": url});582
match engine.resolve_meeting(&meeting_data).await {583
Ok(target) => println!(584
"# resolve by id: found, same thread {}, tenant and organizer present {}",585
target.thread_id == thread_id,586
!target.tenant_id.is_empty() && !target.organizer_id.is_empty()587
),588
Err(error) => println!("# resolve by id: failed: {}", error.to_string().chars().take(160).collect::<String>()),589
}590
}@@ -0,0 +1,62 @@
1
use calling::{CallEngine, EngineConfig};
2
use chatsvc::InstanceNames;
3
use chrono::{Duration, Utc};
4
use serde_json::{Value, json};
5
use session::{DEFAULT_ENDPOINT, Method, Scope, Session};
6
7
#[tokio::main]
8
async fn main() {
9
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
10
let session = Session::connect(&endpoint).await.expect("browser");
11
let poll_session = Session::connect(&endpoint).await.expect("browser");
12
let scope = Scope::graph("OnlineMeetings.ReadWrite");
13
let start = Utc::now() + Duration::hours(2);
14
let body = json!({
15
"subject": "Native client test",
16
"startDateTime": start.to_rfc3339(),
17
"endDateTime": (start + Duration::minutes(30)).to_rfc3339(),
18
});
19
let created = session
20
.request(Method::Post, "https://graph.microsoft.com/v1.0/me/onlineMeetings", &scope, Some(body))
21
.await
22
.expect("create");
23
println!("# create online meeting: HTTP {}", created.status);
24
let id = created.body.get("id").and_then(Value::as_str).map(str::to_owned);
25
let code = created.body.pointer("/joinMeetingIdSettings/joinMeetingId").and_then(Value::as_str).map(|code| code.replace(' ', ""));
26
let passcode = created.body.pointer("/joinMeetingIdSettings/passcode").and_then(Value::as_str).map(str::to_owned);
27
let thread = created.body.pointer("/chatInfo/threadId").and_then(Value::as_str).map(str::to_owned);
28
println!("# meeting id found {}, passcode found {}, thread found {}", code.is_some(), passcode.is_some(), thread.is_some());
29
if let Some(code) = &code {
30
let config = EngineConfig {
31
ringable: false,
32
instance: InstanceNames {
33
global: "__resolveIdTrouter".into(),
34
binding: "__resolveIdRealtime".into(),
35
endpoint_storage_key: "__resolveIdEpid".into(),
36
},
37
..EngineConfig::default()
38
};
39
let (engine, _events) = CallEngine::start(session.clone(), poll_session, config).await.expect("engine");
40
let url = match &passcode {
41
Some(passcode) => format!("https://teams.microsoft.com/meet/{code}?p={passcode}"),
42
None => format!("https://teams.microsoft.com/meet/{code}"),
43
};
44
let meeting_data = json!({"meetingCode": code, "passcode": passcode, "meetingUrl": url});
45
match engine.resolve_meeting(&meeting_data).await {
46
Ok(target) => println!(
47
"# resolve by id: found, same thread {}, tenant and organizer present {}",
48
thread.as_deref() == Some(target.thread_id.as_str()),
49
!target.tenant_id.is_empty() && !target.organizer_id.is_empty()
50
),
51
Err(error) => println!("# resolve by id: failed: {}", error.to_string().chars().take(200).collect::<String>()),
52
}
53
engine.stop().await;
54
}
55
if let Some(id) = id {
56
let deleted = session
57
.request(Method::Delete, &format!("https://graph.microsoft.com/v1.0/me/onlineMeetings/{id}"), &scope, None)
58
.await
59
.expect("delete");
60
println!("# delete online meeting: HTTP {}", deleted.status);
61
}
62
}
@@ -0,0 +1,62 @@1
use calling::{CallEngine, EngineConfig};2
use chatsvc::InstanceNames;3
use chrono::{Duration, Utc};4
use serde_json::{Value, json};5
use session::{DEFAULT_ENDPOINT, Method, Scope, Session};6
7
#[tokio::main]8
async fn main() {9
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());10
let session = Session::connect(&endpoint).await.expect("browser");11
let poll_session = Session::connect(&endpoint).await.expect("browser");12
let scope = Scope::graph("OnlineMeetings.ReadWrite");13
let start = Utc::now() + Duration::hours(2);14
let body = json!({15
"subject": "Native client test",16
"startDateTime": start.to_rfc3339(),17
"endDateTime": (start + Duration::minutes(30)).to_rfc3339(),18
});19
let created = session20
.request(Method::Post, "https://graph.microsoft.com/v1.0/me/onlineMeetings", &scope, Some(body))21
.await22
.expect("create");23
println!("# create online meeting: HTTP {}", created.status);24
let id = created.body.get("id").and_then(Value::as_str).map(str::to_owned);25
let code = created.body.pointer("/joinMeetingIdSettings/joinMeetingId").and_then(Value::as_str).map(|code| code.replace(' ', ""));26
let passcode = created.body.pointer("/joinMeetingIdSettings/passcode").and_then(Value::as_str).map(str::to_owned);27
let thread = created.body.pointer("/chatInfo/threadId").and_then(Value::as_str).map(str::to_owned);28
println!("# meeting id found {}, passcode found {}, thread found {}", code.is_some(), passcode.is_some(), thread.is_some());29
if let Some(code) = &code {30
let config = EngineConfig {31
ringable: false,32
instance: InstanceNames {33
global: "__resolveIdTrouter".into(),34
binding: "__resolveIdRealtime".into(),35
endpoint_storage_key: "__resolveIdEpid".into(),36
},37
..EngineConfig::default()38
};39
let (engine, _events) = CallEngine::start(session.clone(), poll_session, config).await.expect("engine");40
let url = match &passcode {41
Some(passcode) => format!("https://teams.microsoft.com/meet/{code}?p={passcode}"),42
None => format!("https://teams.microsoft.com/meet/{code}"),43
};44
let meeting_data = json!({"meetingCode": code, "passcode": passcode, "meetingUrl": url});45
match engine.resolve_meeting(&meeting_data).await {46
Ok(target) => println!(47
"# resolve by id: found, same thread {}, tenant and organizer present {}",48
thread.as_deref() == Some(target.thread_id.as_str()),49
!target.tenant_id.is_empty() && !target.organizer_id.is_empty()50
),51
Err(error) => println!("# resolve by id: failed: {}", error.to_string().chars().take(200).collect::<String>()),52
}53
engine.stop().await;54
}55
if let Some(id) = id {56
let deleted = session57
.request(Method::Delete, &format!("https://graph.microsoft.com/v1.0/me/onlineMeetings/{id}"), &scope, None)58
.await59
.expect("delete");60
println!("# delete online meeting: HTTP {}", deleted.status);61
}62
}@@ -0,0 +1,278 @@
1
use std::path::{Path, PathBuf};
2
3
use base64::Engine as _;
4
use serde_json::Value;
5
use session::{Request, Scope, Session};
6
7
use crate::error::{Error, Result};
8
9
pub const CATALOG_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/config.json?v=7";
10
pub const CDN_ROOT: &str = "https://statics.teams.cdn.office.net";
11
const FETCH_SCOPE: &str = "Chat.Read";
12
const MAX_SIDE: u32 = 1920;
13
const CATALOG_FILE: &str = "config.json";
14
const THUMBNAIL_DIR: &str = "thumbnails";
15
const IMAGE_DIR: &str = "images";
16
const CHANNELS: usize = 3;
17
18
#[derive(Debug, Clone, PartialEq, Eq)]
19
pub enum BackgroundChoice {
20
None,
21
Blur,
22
Image(PathBuf),
23
}
24
25
#[derive(Debug, Clone, PartialEq, Eq)]
26
pub struct DefaultBackground {
27
pub id: String,
28
pub name: String,
29
pub image_url: String,
30
pub thumbnail_url: String,
31
}
32
33
fn absolute(source: &str) -> String {
34
if source.starts_with("http") { source.to_owned() } else { format!("{CDN_ROOT}{source}") }
35
}
36
37
fn file_id(id: &str) -> String {
38
id.chars().map(|letter| if letter.is_ascii_alphanumeric() || letter == '-' || letter == '_' { letter } else { '_' }).collect()
39
}
40
41
fn extension_of(url: &str) -> &str {
42
let path = url.split(['?', '#']).next().unwrap_or(url);
43
path.rsplit_once('.').map(|(_, extension)| extension).filter(|extension| (2..=4).contains(&extension.len())).unwrap_or("jpg")
44
}
45
46
pub fn parse_catalog(body: &Value) -> Vec<DefaultBackground> {
47
body["videoBackgroundImages"]
48
.as_array()
49
.into_iter()
50
.flatten()
51
.filter_map(|entry| {
52
let source = entry["src"].as_str().filter(|source| !source.is_empty())?;
53
let id = entry["id"].as_str().filter(|id| !id.is_empty())?;
54
Some(DefaultBackground {
55
id: id.to_owned(),
56
name: entry["name"].as_str().unwrap_or(id).to_owned(),
57
image_url: absolute(source),
58
thumbnail_url: absolute(entry["thumb_src"].as_str().filter(|thumb| !thumb.is_empty()).unwrap_or(source)),
59
})
60
})
61
.collect()
62
}
63
64
#[derive(Debug, Clone)]
65
pub struct BackgroundCache {
66
directory: PathBuf,
67
}
68
69
impl BackgroundCache {
70
pub fn new(directory: PathBuf) -> Self {
71
BackgroundCache { directory }
72
}
73
74
pub fn thumbnail_path(&self, background: &DefaultBackground) -> PathBuf {
75
self.directory.join(THUMBNAIL_DIR).join(format!("{}.{}", file_id(&background.id), extension_of(&background.thumbnail_url)))
76
}
77
78
pub fn image_path(&self, background: &DefaultBackground) -> PathBuf {
79
self.directory.join(IMAGE_DIR).join(format!("{}.{}", file_id(&background.id), extension_of(&background.image_url)))
80
}
81
82
pub fn cached_catalog(&self) -> Vec<DefaultBackground> {
83
std::fs::read(self.directory.join(CATALOG_FILE))
84
.ok()
85
.and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
86
.map(|body| parse_catalog(&body))
87
.unwrap_or_default()
88
}
89
90
pub async fn refresh_catalog(&self, session: &Session) -> Result<Vec<DefaultBackground>> {
91
let bytes = download(session, CATALOG_URL).await?;
92
let body: Value = serde_json::from_slice(&bytes).map_err(|error| Error::Signaling(format!("background list is not JSON: {error}")))?;
93
let catalog = parse_catalog(&body);
94
if !catalog.is_empty() {
95
std::fs::create_dir_all(&self.directory).map_err(|error| Error::Webrtc(format!("background cache: {error}")))?;
96
let _ = std::fs::write(self.directory.join(CATALOG_FILE), &bytes);
97
}
98
Ok(catalog)
99
}
100
101
pub async fn ensure_thumbnail(&self, session: &Session, background: &DefaultBackground) -> Result<PathBuf> {
102
fetch_once(session, &background.thumbnail_url, self.thumbnail_path(background)).await
103
}
104
105
pub async fn ensure_image(&self, session: &Session, background: &DefaultBackground) -> Result<PathBuf> {
106
fetch_once(session, &background.image_url, self.image_path(background)).await
107
}
108
}
109
110
async fn fetch_once(session: &Session, url: &str, path: PathBuf) -> Result<PathBuf> {
111
if path.exists() {
112
return Ok(path);
113
}
114
let bytes = download(session, url).await?;
115
if let Some(parent) = path.parent() {
116
std::fs::create_dir_all(parent).map_err(|error| Error::Webrtc(format!("background cache: {error}")))?;
117
}
118
let partial = path.with_extension("part");
119
std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, &path)).map_err(|error| Error::Webrtc(format!("background cache: {error}")))?;
120
Ok(path)
121
}
122
123
async fn download(session: &Session, url: &str) -> Result<Vec<u8>> {
124
let answer = session.send(Request::anonymous_binary_get(url, Vec::new()), &Scope::graph(FETCH_SCOPE)).await?;
125
let encoded = answer.body["base64"].as_str().ok_or_else(|| Error::Signaling("download without a body".into()))?;
126
base64::engine::general_purpose::STANDARD
127
.decode(encoded)
128
.map_err(|error| Error::Signaling(format!("download is not base64: {error}")))
129
}
130
131
#[derive(Debug, Clone)]
132
pub struct BackgroundPicture {
133
rgb: Vec<u8>,
134
width: usize,
135
height: usize,
136
}
137
138
impl BackgroundPicture {
139
pub fn from_rgb(rgb: Vec<u8>, width: usize, height: usize) -> Option<Self> {
140
(width > 0 && height > 0 && rgb.len() == width * height * CHANNELS).then_some(BackgroundPicture { rgb, width, height })
141
}
142
143
pub fn load(path: &Path) -> Result<Self> {
144
let mut picture = image::open(path).map_err(|error| Error::Webrtc(format!("background image: {error}")))?;
145
if picture.width().max(picture.height()) > MAX_SIDE {
146
picture = picture.resize(MAX_SIDE, MAX_SIDE, image::imageops::FilterType::Triangle);
147
}
148
let rgb = picture.to_rgb8();
149
let (width, height) = (rgb.width() as usize, rgb.height() as usize);
150
BackgroundPicture::from_rgb(rgb.into_raw(), width, height).ok_or_else(|| Error::Webrtc("background image is empty".into()))
151
}
152
153
pub fn size(&self) -> (usize, usize) {
154
(self.width, self.height)
155
}
156
157
fn sample(&self, x: f32, y: f32, channel: usize) -> f32 {
158
let (x, y) = (x.clamp(0., (self.width - 1) as f32), y.clamp(0., (self.height - 1) as f32));
159
let (left, top) = (x.floor() as usize, y.floor() as usize);
160
let (right, bottom) = ((left + 1).min(self.width - 1), (top + 1).min(self.height - 1));
161
let (across, down) = (x - left as f32, y - top as f32);
162
let at = |column: usize, row: usize| f32::from(self.rgb[(row * self.width + column) * CHANNELS + channel]);
163
let upper = at(left, top) * (1. - across) + at(right, top) * across;
164
let lower = at(left, bottom) * (1. - across) + at(right, bottom) * across;
165
upper * (1. - down) + lower * down
166
}
167
168
pub fn covering(&self, width: usize, height: usize) -> Vec<u8> {
169
let scale = (width as f32 / self.width as f32).max(height as f32 / self.height as f32);
170
let offset_x = (self.width as f32 * scale - width as f32) / 2.;
171
let offset_y = (self.height as f32 * scale - height as f32) / 2.;
172
let mut covered = vec![0u8; width * height * CHANNELS];
173
for row in 0..height {
174
let source_y = (row as f32 + 0.5 + offset_y) / scale - 0.5;
175
for column in 0..width {
176
let source_x = (column as f32 + 0.5 + offset_x) / scale - 0.5;
177
for channel in 0..CHANNELS {
178
covered[(row * width + column) * CHANNELS + channel] = (self.sample(source_x, source_y, channel) + 0.5) as u8;
179
}
180
}
181
}
182
covered
183
}
184
}
185
186
#[cfg(test)]
187
mod tests {
188
use serde_json::json;
189
190
use super::*;
191
192
fn catalog() -> Value {
193
json!({"videoBackgroundImages": [
194
{"id": "office_01", "name": "Modern office", "filetype": "jpg", "src": "/evergreen-assets/backgroundimages/office_01.jpg", "thumb_src": "/evergreen-assets/backgroundimages/office_01_thumb.jpg"},
195
{"id": "beach", "name": "Beach", "src": "https://cdn.example/beach.png"},
196
{"id": "", "src": "/x.jpg"},
197
{"id": "no_source"},
198
]})
199
}
200
201
#[test]
202
fn the_catalog_lists_images_with_absolute_urls_and_skips_broken_entries() {
203
let images = parse_catalog(&catalog());
204
assert_eq!(images.len(), 2);
205
assert_eq!(images[0].id, "office_01");
206
assert_eq!(images[0].name, "Modern office");
207
assert_eq!(images[0].image_url, "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/office_01.jpg");
208
assert_eq!(images[0].thumbnail_url, "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/office_01_thumb.jpg");
209
assert_eq!(images[1].image_url, "https://cdn.example/beach.png");
210
assert_eq!(images[1].thumbnail_url, "https://cdn.example/beach.png");
211
assert!(parse_catalog(&json!({})).is_empty());
212
}
213
214
#[test]
215
fn cached_files_live_under_the_cache_directory_by_id() {
216
let cache = BackgroundCache::new(PathBuf::from("cache"));
217
let images = parse_catalog(&catalog());
218
assert_eq!(cache.thumbnail_path(&images[0]), Path::new("cache/thumbnails/office_01.jpg"));
219
assert_eq!(cache.image_path(&images[1]), Path::new("cache/images/beach.png"));
220
let odd = DefaultBackground { id: "a/b c".into(), name: String::new(), image_url: "https://x/y".into(), thumbnail_url: "https://x/y.webp?v=3".into() };
221
assert_eq!(cache.thumbnail_path(&odd), Path::new("cache/thumbnails/a_b_c.webp"));
222
assert_eq!(cache.image_path(&odd), Path::new("cache/images/a_b_c.jpg"));
223
}
224
225
#[test]
226
fn a_saved_catalog_is_read_back_and_a_missing_one_is_empty() {
227
let directory = tempfile_directory("catalog");
228
let cache = BackgroundCache::new(directory.clone());
229
assert!(cache.cached_catalog().is_empty());
230
std::fs::write(directory.join("config.json"), catalog().to_string()).unwrap();
231
assert_eq!(cache.cached_catalog().len(), 2);
232
let _ = std::fs::remove_dir_all(directory);
233
}
234
235
fn tempfile_directory(name: &str) -> PathBuf {
236
let directory = std::env::temp_dir().join(format!("calling-background-{name}-{}", uuid::Uuid::new_v4()));
237
std::fs::create_dir_all(&directory).unwrap();
238
directory
239
}
240
241
fn halves(width: usize, height: usize) -> BackgroundPicture {
242
let rgb = (0..width * height).flat_map(|index| if index % width < width / 2 { [200, 0, 0] } else { [0, 0, 200] }).collect();
243
BackgroundPicture::from_rgb(rgb, width, height).unwrap()
244
}
245
246
#[test]
247
fn a_wide_picture_covers_a_narrow_frame_and_crops_the_sides_evenly() {
248
let covered = halves(40, 10).covering(10, 10);
249
assert_eq!(covered.len(), 10 * 10 * 3);
250
assert_eq!(&covered[(5 * 10) * 3..(5 * 10) * 3 + 3], &[200, 0, 0]);
251
assert_eq!(&covered[(5 * 10 + 9) * 3..(5 * 10 + 9) * 3 + 3], &[0, 0, 200]);
252
}
253
254
#[test]
255
fn a_picture_of_the_frame_shape_is_only_resampled() {
256
let covered = halves(8, 4).covering(16, 8);
257
assert_eq!(&covered[0..3], &[200, 0, 0]);
258
assert_eq!(&covered[15 * 3..15 * 3 + 3], &[0, 0, 200]);
259
assert_eq!(covered.len(), 16 * 8 * 3);
260
}
261
262
#[test]
263
fn pictures_need_pixels_for_their_size() {
264
assert!(BackgroundPicture::from_rgb(vec![0; 5], 2, 2).is_none());
265
assert!(BackgroundPicture::from_rgb(Vec::new(), 0, 0).is_none());
266
}
267
268
#[test]
269
fn a_picture_file_is_loaded_and_missing_ones_fail() {
270
let directory = tempfile_directory("load");
271
let path = directory.join("pic.png");
272
image::RgbImage::from_pixel(6, 4, image::Rgb([10, 20, 30])).save(&path).unwrap();
273
let picture = BackgroundPicture::load(&path).unwrap();
274
assert_eq!(picture.size(), (6, 4));
275
assert!(BackgroundPicture::load(&directory.join("none.png")).is_err());
276
let _ = std::fs::remove_dir_all(directory);
277
}
278
}
@@ -0,0 +1,278 @@1
use std::path::{Path, PathBuf};2
3
use base64::Engine as _;4
use serde_json::Value;5
use session::{Request, Scope, Session};6
7
use crate::error::{Error, Result};8
9
pub const CATALOG_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/config.json?v=7";10
pub const CDN_ROOT: &str = "https://statics.teams.cdn.office.net";11
const FETCH_SCOPE: &str = "Chat.Read";12
const MAX_SIDE: u32 = 1920;13
const CATALOG_FILE: &str = "config.json";14
const THUMBNAIL_DIR: &str = "thumbnails";15
const IMAGE_DIR: &str = "images";16
const CHANNELS: usize = 3;17
18
#[derive(Debug, Clone, PartialEq, Eq)]19
pub enum BackgroundChoice {20
None,21
Blur,22
Image(PathBuf),23
}24
25
#[derive(Debug, Clone, PartialEq, Eq)]26
pub struct DefaultBackground {27
pub id: String,28
pub name: String,29
pub image_url: String,30
pub thumbnail_url: String,31
}32
33
fn absolute(source: &str) -> String {34
if source.starts_with("http") { source.to_owned() } else { format!("{CDN_ROOT}{source}") }35
}36
37
fn file_id(id: &str) -> String {38
id.chars().map(|letter| if letter.is_ascii_alphanumeric() || letter == '-' || letter == '_' { letter } else { '_' }).collect()39
}40
41
fn extension_of(url: &str) -> &str {42
let path = url.split(['?', '#']).next().unwrap_or(url);43
path.rsplit_once('.').map(|(_, extension)| extension).filter(|extension| (2..=4).contains(&extension.len())).unwrap_or("jpg")44
}45
46
pub fn parse_catalog(body: &Value) -> Vec<DefaultBackground> {47
body["videoBackgroundImages"]48
.as_array()49
.into_iter()50
.flatten()51
.filter_map(|entry| {52
let source = entry["src"].as_str().filter(|source| !source.is_empty())?;53
let id = entry["id"].as_str().filter(|id| !id.is_empty())?;54
Some(DefaultBackground {55
id: id.to_owned(),56
name: entry["name"].as_str().unwrap_or(id).to_owned(),57
image_url: absolute(source),58
thumbnail_url: absolute(entry["thumb_src"].as_str().filter(|thumb| !thumb.is_empty()).unwrap_or(source)),59
})60
})61
.collect()62
}63
64
#[derive(Debug, Clone)]65
pub struct BackgroundCache {66
directory: PathBuf,67
}68
69
impl BackgroundCache {70
pub fn new(directory: PathBuf) -> Self {71
BackgroundCache { directory }72
}73
74
pub fn thumbnail_path(&self, background: &DefaultBackground) -> PathBuf {75
self.directory.join(THUMBNAIL_DIR).join(format!("{}.{}", file_id(&background.id), extension_of(&background.thumbnail_url)))76
}77
78
pub fn image_path(&self, background: &DefaultBackground) -> PathBuf {79
self.directory.join(IMAGE_DIR).join(format!("{}.{}", file_id(&background.id), extension_of(&background.image_url)))80
}81
82
pub fn cached_catalog(&self) -> Vec<DefaultBackground> {83
std::fs::read(self.directory.join(CATALOG_FILE))84
.ok()85
.and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())86
.map(|body| parse_catalog(&body))87
.unwrap_or_default()88
}89
90
pub async fn refresh_catalog(&self, session: &Session) -> Result<Vec<DefaultBackground>> {91
let bytes = download(session, CATALOG_URL).await?;92
let body: Value = serde_json::from_slice(&bytes).map_err(|error| Error::Signaling(format!("background list is not JSON: {error}")))?;93
let catalog = parse_catalog(&body);94
if !catalog.is_empty() {95
std::fs::create_dir_all(&self.directory).map_err(|error| Error::Webrtc(format!("background cache: {error}")))?;96
let _ = std::fs::write(self.directory.join(CATALOG_FILE), &bytes);97
}98
Ok(catalog)99
}100
101
pub async fn ensure_thumbnail(&self, session: &Session, background: &DefaultBackground) -> Result<PathBuf> {102
fetch_once(session, &background.thumbnail_url, self.thumbnail_path(background)).await103
}104
105
pub async fn ensure_image(&self, session: &Session, background: &DefaultBackground) -> Result<PathBuf> {106
fetch_once(session, &background.image_url, self.image_path(background)).await107
}108
}109
110
async fn fetch_once(session: &Session, url: &str, path: PathBuf) -> Result<PathBuf> {111
if path.exists() {112
return Ok(path);113
}114
let bytes = download(session, url).await?;115
if let Some(parent) = path.parent() {116
std::fs::create_dir_all(parent).map_err(|error| Error::Webrtc(format!("background cache: {error}")))?;117
}118
let partial = path.with_extension("part");119
std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, &path)).map_err(|error| Error::Webrtc(format!("background cache: {error}")))?;120
Ok(path)121
}122
123
async fn download(session: &Session, url: &str) -> Result<Vec<u8>> {124
let answer = session.send(Request::anonymous_binary_get(url, Vec::new()), &Scope::graph(FETCH_SCOPE)).await?;125
let encoded = answer.body["base64"].as_str().ok_or_else(|| Error::Signaling("download without a body".into()))?;126
base64::engine::general_purpose::STANDARD127
.decode(encoded)128
.map_err(|error| Error::Signaling(format!("download is not base64: {error}")))129
}130
131
#[derive(Debug, Clone)]132
pub struct BackgroundPicture {133
rgb: Vec<u8>,134
width: usize,135
height: usize,136
}137
138
impl BackgroundPicture {139
pub fn from_rgb(rgb: Vec<u8>, width: usize, height: usize) -> Option<Self> {140
(width > 0 && height > 0 && rgb.len() == width * height * CHANNELS).then_some(BackgroundPicture { rgb, width, height })141
}142
143
pub fn load(path: &Path) -> Result<Self> {144
let mut picture = image::open(path).map_err(|error| Error::Webrtc(format!("background image: {error}")))?;145
if picture.width().max(picture.height()) > MAX_SIDE {146
picture = picture.resize(MAX_SIDE, MAX_SIDE, image::imageops::FilterType::Triangle);147
}148
let rgb = picture.to_rgb8();149
let (width, height) = (rgb.width() as usize, rgb.height() as usize);150
BackgroundPicture::from_rgb(rgb.into_raw(), width, height).ok_or_else(|| Error::Webrtc("background image is empty".into()))151
}152
153
pub fn size(&self) -> (usize, usize) {154
(self.width, self.height)155
}156
157
fn sample(&self, x: f32, y: f32, channel: usize) -> f32 {158
let (x, y) = (x.clamp(0., (self.width - 1) as f32), y.clamp(0., (self.height - 1) as f32));159
let (left, top) = (x.floor() as usize, y.floor() as usize);160
let (right, bottom) = ((left + 1).min(self.width - 1), (top + 1).min(self.height - 1));161
let (across, down) = (x - left as f32, y - top as f32);162
let at = |column: usize, row: usize| f32::from(self.rgb[(row * self.width + column) * CHANNELS + channel]);163
let upper = at(left, top) * (1. - across) + at(right, top) * across;164
let lower = at(left, bottom) * (1. - across) + at(right, bottom) * across;165
upper * (1. - down) + lower * down166
}167
168
pub fn covering(&self, width: usize, height: usize) -> Vec<u8> {169
let scale = (width as f32 / self.width as f32).max(height as f32 / self.height as f32);170
let offset_x = (self.width as f32 * scale - width as f32) / 2.;171
let offset_y = (self.height as f32 * scale - height as f32) / 2.;172
let mut covered = vec![0u8; width * height * CHANNELS];173
for row in 0..height {174
let source_y = (row as f32 + 0.5 + offset_y) / scale - 0.5;175
for column in 0..width {176
let source_x = (column as f32 + 0.5 + offset_x) / scale - 0.5;177
for channel in 0..CHANNELS {178
covered[(row * width + column) * CHANNELS + channel] = (self.sample(source_x, source_y, channel) + 0.5) as u8;179
}180
}181
}182
covered183
}184
}185
186
#[cfg(test)]187
mod tests {188
use serde_json::json;189
190
use super::*;191
192
fn catalog() -> Value {193
json!({"videoBackgroundImages": [194
{"id": "office_01", "name": "Modern office", "filetype": "jpg", "src": "/evergreen-assets/backgroundimages/office_01.jpg", "thumb_src": "/evergreen-assets/backgroundimages/office_01_thumb.jpg"},195
{"id": "beach", "name": "Beach", "src": "https://cdn.example/beach.png"},196
{"id": "", "src": "/x.jpg"},197
{"id": "no_source"},198
]})199
}200
201
#[test]202
fn the_catalog_lists_images_with_absolute_urls_and_skips_broken_entries() {203
let images = parse_catalog(&catalog());204
assert_eq!(images.len(), 2);205
assert_eq!(images[0].id, "office_01");206
assert_eq!(images[0].name, "Modern office");207
assert_eq!(images[0].image_url, "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/office_01.jpg");208
assert_eq!(images[0].thumbnail_url, "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/office_01_thumb.jpg");209
assert_eq!(images[1].image_url, "https://cdn.example/beach.png");210
assert_eq!(images[1].thumbnail_url, "https://cdn.example/beach.png");211
assert!(parse_catalog(&json!({})).is_empty());212
}213
214
#[test]215
fn cached_files_live_under_the_cache_directory_by_id() {216
let cache = BackgroundCache::new(PathBuf::from("cache"));217
let images = parse_catalog(&catalog());218
assert_eq!(cache.thumbnail_path(&images[0]), Path::new("cache/thumbnails/office_01.jpg"));219
assert_eq!(cache.image_path(&images[1]), Path::new("cache/images/beach.png"));220
let odd = DefaultBackground { id: "a/b c".into(), name: String::new(), image_url: "https://x/y".into(), thumbnail_url: "https://x/y.webp?v=3".into() };221
assert_eq!(cache.thumbnail_path(&odd), Path::new("cache/thumbnails/a_b_c.webp"));222
assert_eq!(cache.image_path(&odd), Path::new("cache/images/a_b_c.jpg"));223
}224
225
#[test]226
fn a_saved_catalog_is_read_back_and_a_missing_one_is_empty() {227
let directory = tempfile_directory("catalog");228
let cache = BackgroundCache::new(directory.clone());229
assert!(cache.cached_catalog().is_empty());230
std::fs::write(directory.join("config.json"), catalog().to_string()).unwrap();231
assert_eq!(cache.cached_catalog().len(), 2);232
let _ = std::fs::remove_dir_all(directory);233
}234
235
fn tempfile_directory(name: &str) -> PathBuf {236
let directory = std::env::temp_dir().join(format!("calling-background-{name}-{}", uuid::Uuid::new_v4()));237
std::fs::create_dir_all(&directory).unwrap();238
directory239
}240
241
fn halves(width: usize, height: usize) -> BackgroundPicture {242
let rgb = (0..width * height).flat_map(|index| if index % width < width / 2 { [200, 0, 0] } else { [0, 0, 200] }).collect();243
BackgroundPicture::from_rgb(rgb, width, height).unwrap()244
}245
246
#[test]247
fn a_wide_picture_covers_a_narrow_frame_and_crops_the_sides_evenly() {248
let covered = halves(40, 10).covering(10, 10);249
assert_eq!(covered.len(), 10 * 10 * 3);250
assert_eq!(&covered[(5 * 10) * 3..(5 * 10) * 3 + 3], &[200, 0, 0]);251
assert_eq!(&covered[(5 * 10 + 9) * 3..(5 * 10 + 9) * 3 + 3], &[0, 0, 200]);252
}253
254
#[test]255
fn a_picture_of_the_frame_shape_is_only_resampled() {256
let covered = halves(8, 4).covering(16, 8);257
assert_eq!(&covered[0..3], &[200, 0, 0]);258
assert_eq!(&covered[15 * 3..15 * 3 + 3], &[0, 0, 200]);259
assert_eq!(covered.len(), 16 * 8 * 3);260
}261
262
#[test]263
fn pictures_need_pixels_for_their_size() {264
assert!(BackgroundPicture::from_rgb(vec![0; 5], 2, 2).is_none());265
assert!(BackgroundPicture::from_rgb(Vec::new(), 0, 0).is_none());266
}267
268
#[test]269
fn a_picture_file_is_loaded_and_missing_ones_fail() {270
let directory = tempfile_directory("load");271
let path = directory.join("pic.png");272
image::RgbImage::from_pixel(6, 4, image::Rgb([10, 20, 30])).save(&path).unwrap();273
let picture = BackgroundPicture::load(&path).unwrap();274
assert_eq!(picture.size(), (6, 4));275
assert!(BackgroundPicture::load(&directory.join("none.png")).is_err());276
let _ = std::fs::remove_dir_all(directory);277
}278
}@@ -1,5 +1,5 @@
1
1
use std::io::Cursor;
2
use std::sync::Arc;
2
use std::sync::{Arc, Mutex};
3
3
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
4
4
use std::time::{Duration, Instant};
5
5
@@ -7,6 +7,7 @@ use libwebrtc::native::yuv_helper::i420_to_abgr;
7
7
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
8
8
use tract_onnx::prelude::*;
9
9
10
use crate::background::BackgroundPicture;
10
11
use crate::camera::i420_from_rgba;
11
12
use crate::error::{Error, Result};
12
13
@@ -196,18 +197,16 @@ impl Composer<'_> {
196
197
}
197
198
}
198
199
199
/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.
200
pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
201
let (background, small_width, small_height) = blurred_background(rgba, width, height);
200
fn compose_over(rgba: &mut [u8], width: usize, height: usize, mask: &[f32], background: &[u8], background_width: usize, background_height: usize) {
202
201
let composer = Composer {
203
background: &background,
202
background,
204
203
mask,
205
204
width,
206
205
mask_x: axis(width, MASK_WIDTH),
207
206
mask_y: axis(height, MASK_HEIGHT),
208
small_x: axis(width, small_width),
209
small_y: axis(height, small_height),
210
small_width,
207
small_x: axis(width, background_width),
208
small_y: axis(height, background_height),
209
small_width: background_width,
211
210
};
212
211
let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
213
212
let rows_per_band = height.div_ceil(bands);
@@ -219,11 +218,22 @@ pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
219
218
});
220
219
}
221
220
221
/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.
222
pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
223
let (background, small_width, small_height) = blurred_background(rgba, width, height);
224
compose_over(rgba, width, height, mask, &background, small_width, small_height);
225
}
226
227
pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, mask: &[f32], covered: &[u8]) {
228
compose_over(rgba, width, height, mask, covered, width, height);
229
}
230
222
231
/// Shared between the UI command and the camera thread.
223
232
#[derive(Default)]
224
233
pub struct BlurSettings {
225
234
enabled: AtomicBool,
226
235
average_micros: AtomicU32,
236
picture: Mutex<Option<Arc<BackgroundPicture>>>,
227
237
}
228
238
229
239
impl BlurSettings {
@@ -235,6 +245,14 @@ impl BlurSettings {
235
245
self.enabled.load(Ordering::Relaxed)
236
246
}
237
247
248
pub fn set_picture(&self, picture: Option<Arc<BackgroundPicture>>) {
249
*self.picture.lock().expect("picture lock") = picture;
250
}
251
252
fn picture(&self) -> Option<Arc<BackgroundPicture>> {
253
self.picture.lock().expect("picture lock").clone()
254
}
255
238
256
pub fn average_ms(&self) -> f32 {
239
257
self.average_micros.load(Ordering::Relaxed) as f32 / 1000.
240
258
}
@@ -245,11 +263,31 @@ pub struct BlurStage {
245
263
settings: Arc<BlurSettings>,
246
264
blur: Option<BackgroundBlur>,
247
265
unavailable: bool,
266
covered: Option<CoveredPicture>,
267
}
268
269
struct CoveredPicture {
270
picture: Arc<BackgroundPicture>,
271
width: usize,
272
height: usize,
273
rgb: Vec<u8>,
248
274
}
249
275
250
276
impl BlurStage {
251
277
pub fn new(settings: Arc<BlurSettings>) -> Self {
252
BlurStage { settings, blur: None, unavailable: false }
278
BlurStage { settings, blur: None, unavailable: false, covered: None }
279
}
280
281
fn refresh_covered(&mut self, width: usize, height: usize) {
282
let Some(picture) = self.settings.picture() else {
283
self.covered = None;
284
return;
285
};
286
let fresh = self.covered.as_ref().is_some_and(|covered| Arc::ptr_eq(&covered.picture, &picture) && covered.width == width && covered.height == height);
287
if !fresh {
288
let rgb = picture.covering(width, height);
289
self.covered = Some(CoveredPicture { picture, width, height, rgb });
290
}
253
291
}
254
292
255
293
pub fn apply_rgba(&mut self, rgba: &mut [u8], width: usize, height: usize) {
@@ -265,8 +303,9 @@ impl BlurStage {
265
303
}
266
304
}
267
305
}
306
self.refresh_covered(width, height);
268
307
if let Some(blur) = self.blur.as_mut() {
269
blur.apply(rgba, width, height);
308
blur.apply(rgba, width, height, self.covered.as_ref().map(|covered| covered.rgb.as_slice()));
270
309
self.settings.average_micros.store((blur.average_ms() * 1000.) as u32, Ordering::Relaxed);
271
310
}
272
311
}
@@ -300,13 +339,16 @@ impl BackgroundBlur {
300
339
Ok(BackgroundBlur { segmenter: Segmenter::new()?, mask: Vec::new(), frames: 0, stride: 1, average_ms: 0., processed: 0 })
301
340
}
302
341
303
pub fn apply(&mut self, rgba: &mut [u8], width: usize, height: usize) {
342
pub fn apply(&mut self, rgba: &mut [u8], width: usize, height: usize, covered: Option<&[u8]>) {
304
343
let started = Instant::now();
305
344
if self.frames.is_multiple_of(self.stride) || self.mask.is_empty() {
306
345
self.segment(rgba, width, height, started);
307
346
}
308
347
self.frames += 1;
309
compose(rgba, width, height, &self.mask);
348
match covered {
349
Some(covered) => compose_image(rgba, width, height, &self.mask, covered),
350
None => compose(rgba, width, height, &self.mask),
351
}
310
352
let elapsed = started.elapsed().as_secs_f64() * 1000.;
311
353
self.average_ms = if self.processed == 0 { elapsed } else { self.average_ms * (1. - AVERAGE_WEIGHT) + elapsed * AVERAGE_WEIGHT };
312
354
self.processed += 1;
@@ -411,6 +453,40 @@ mod tests {
411
453
assert!(blurred.chunks(CHANNELS).all(|pixel| pixel[3] == 255));
412
454
}
413
455
456
fn cover_of(color: [u8; 3]) -> Vec<u8> {
457
BackgroundPicture::from_rgb(color.repeat(4 * 4), 4, 4).unwrap().covering(WIDTH, HEIGHT)
458
}
459
460
#[test]
461
fn the_person_stays_and_the_picture_replaces_everything_else() {
462
let original = checkerboard();
463
let mut replaced = original.clone();
464
compose_image(&mut replaced, WIDTH, HEIGHT, &oval_mask(), &cover_of([10, 120, 200]));
465
let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);
466
assert_eq!(pixel(&replaced, center_x, center_y), pixel(&original, center_x, center_y));
467
for (x, y) in [(2, 2), (WIDTH - 3, HEIGHT - 3), (2, HEIGHT - 3)] {
468
assert_eq!(&replaced[(y * WIDTH + x) * CHANNELS..][..4], &[10, 120, 200, 255]);
469
}
470
}
471
472
#[test]
473
fn the_picture_edge_is_feathered_like_the_blur_edge() {
474
let original = checkerboard();
475
let mut replaced = original.clone();
476
compose_image(&mut replaced, WIDTH, HEIGHT, &oval_mask(), &cover_of([0, 0, 0]));
477
let edge_row = HEIGHT / 2;
478
let switches = (0..WIDTH - 1)
479
.filter(|&x| pixel(&replaced, x, edge_row) != pixel(&original, x, edge_row) && pixel(&replaced, x + 1, edge_row) == pixel(&original, x + 1, edge_row))
480
.count();
481
assert!(switches <= 2);
482
let mut everyone = original.clone();
483
compose_image(&mut everyone, WIDTH, HEIGHT, &vec![1.; MASK_WIDTH * MASK_HEIGHT], &cover_of([0, 0, 0]));
484
assert_eq!(everyone, original);
485
let mut nobody = original;
486
compose_image(&mut nobody, WIDTH, HEIGHT, &vec![0.; MASK_WIDTH * MASK_HEIGHT], &cover_of([0, 0, 0]));
487
assert!(nobody.chunks(CHANNELS).all(|pixel| pixel[..3] == [0, 0, 0] && pixel[3] == 255));
488
}
489
414
490
#[test]
415
491
fn the_model_answers_one_probability_per_mask_pixel() {
416
492
let segmenter = Segmenter::new().expect("model loads");
@@ -423,8 +499,8 @@ mod tests {
423
499
fn the_blur_keeps_a_running_average_and_a_mask() {
424
500
let mut blur = BackgroundBlur::new().expect("model loads");
425
501
let mut frame = checkerboard();
426
blur.apply(&mut frame, WIDTH, HEIGHT);
427
blur.apply(&mut frame, WIDTH, HEIGHT);
502
blur.apply(&mut frame, WIDTH, HEIGHT, None);
503
blur.apply(&mut frame, WIDTH, HEIGHT, None);
428
504
assert!(blur.average_ms() > 0.);
429
505
assert_eq!(blur.mask.len(), MASK_WIDTH * MASK_HEIGHT);
430
506
}
@@ -1,5 +1,5 @@1
use std::io::Cursor;1
use std::io::Cursor;2
use std::sync::Arc;2
use std::sync::{Arc, Mutex};3
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};3
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};4
use std::time::{Duration, Instant};4
use std::time::{Duration, Instant};5
5
@@ -7,6 +7,7 @@ use libwebrtc::native::yuv_helper::i420_to_abgr;7
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};7
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};8
use tract_onnx::prelude::*;8
use tract_onnx::prelude::*;9
9
10
use crate::background::BackgroundPicture;10
use crate::camera::i420_from_rgba;11
use crate::camera::i420_from_rgba;11
use crate::error::{Error, Result};12
use crate::error::{Error, Result};12
13
@@ -196,18 +197,16 @@ impl Composer<'_> {196
}197
}197
}198
}198
199
199
/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.200
fn compose_over(rgba: &mut [u8], width: usize, height: usize, mask: &[f32], background: &[u8], background_width: usize, background_height: usize) {200
pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {201
let (background, small_width, small_height) = blurred_background(rgba, width, height);202
let composer = Composer {201
let composer = Composer {203
background: &background,202
background,204
mask,203
mask,205
width,204
width,206
mask_x: axis(width, MASK_WIDTH),205
mask_x: axis(width, MASK_WIDTH),207
mask_y: axis(height, MASK_HEIGHT),206
mask_y: axis(height, MASK_HEIGHT),208
small_x: axis(width, small_width),207
small_x: axis(width, background_width),209
small_y: axis(height, small_height),208
small_y: axis(height, background_height),210
small_width,209
small_width: background_width,211
};210
};212
let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);211
let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);213
let rows_per_band = height.div_ceil(bands);212
let rows_per_band = height.div_ceil(bands);@@ -219,11 +218,22 @@ pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {219
});218
});220
}219
}221
220
221
/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.222
pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {223
let (background, small_width, small_height) = blurred_background(rgba, width, height);224
compose_over(rgba, width, height, mask, &background, small_width, small_height);225
}226
227
pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, mask: &[f32], covered: &[u8]) {228
compose_over(rgba, width, height, mask, covered, width, height);229
}230
222
/// Shared between the UI command and the camera thread.231
/// Shared between the UI command and the camera thread.223
#[derive(Default)]232
#[derive(Default)]224
pub struct BlurSettings {233
pub struct BlurSettings {225
enabled: AtomicBool,234
enabled: AtomicBool,226
average_micros: AtomicU32,235
average_micros: AtomicU32,236
picture: Mutex<Option<Arc<BackgroundPicture>>>,227
}237
}228
238
229
impl BlurSettings {239
impl BlurSettings {@@ -235,6 +245,14 @@ impl BlurSettings {235
self.enabled.load(Ordering::Relaxed)245
self.enabled.load(Ordering::Relaxed)236
}246
}237
247
248
pub fn set_picture(&self, picture: Option<Arc<BackgroundPicture>>) {249
*self.picture.lock().expect("picture lock") = picture;250
}251
252
fn picture(&self) -> Option<Arc<BackgroundPicture>> {253
self.picture.lock().expect("picture lock").clone()254
}255
238
pub fn average_ms(&self) -> f32 {256
pub fn average_ms(&self) -> f32 {239
self.average_micros.load(Ordering::Relaxed) as f32 / 1000.257
self.average_micros.load(Ordering::Relaxed) as f32 / 1000.240
}258
}@@ -245,11 +263,31 @@ pub struct BlurStage {245
settings: Arc<BlurSettings>,263
settings: Arc<BlurSettings>,246
blur: Option<BackgroundBlur>,264
blur: Option<BackgroundBlur>,247
unavailable: bool,265
unavailable: bool,266
covered: Option<CoveredPicture>,267
}268
269
struct CoveredPicture {270
picture: Arc<BackgroundPicture>,271
width: usize,272
height: usize,273
rgb: Vec<u8>,248
}274
}249
275
250
impl BlurStage {276
impl BlurStage {251
pub fn new(settings: Arc<BlurSettings>) -> Self {277
pub fn new(settings: Arc<BlurSettings>) -> Self {252
BlurStage { settings, blur: None, unavailable: false }278
BlurStage { settings, blur: None, unavailable: false, covered: None }279
}280
281
fn refresh_covered(&mut self, width: usize, height: usize) {282
let Some(picture) = self.settings.picture() else {283
self.covered = None;284
return;285
};286
let fresh = self.covered.as_ref().is_some_and(|covered| Arc::ptr_eq(&covered.picture, &picture) && covered.width == width && covered.height == height);287
if !fresh {288
let rgb = picture.covering(width, height);289
self.covered = Some(CoveredPicture { picture, width, height, rgb });290
}253
}291
}254
292
255
pub fn apply_rgba(&mut self, rgba: &mut [u8], width: usize, height: usize) {293
pub fn apply_rgba(&mut self, rgba: &mut [u8], width: usize, height: usize) {@@ -265,8 +303,9 @@ impl BlurStage {265
}303
}266
}304
}267
}305
}306
self.refresh_covered(width, height);268
if let Some(blur) = self.blur.as_mut() {307
if let Some(blur) = self.blur.as_mut() {269
blur.apply(rgba, width, height);308
blur.apply(rgba, width, height, self.covered.as_ref().map(|covered| covered.rgb.as_slice()));270
self.settings.average_micros.store((blur.average_ms() * 1000.) as u32, Ordering::Relaxed);309
self.settings.average_micros.store((blur.average_ms() * 1000.) as u32, Ordering::Relaxed);271
}310
}272
}311
}@@ -300,13 +339,16 @@ impl BackgroundBlur {300
Ok(BackgroundBlur { segmenter: Segmenter::new()?, mask: Vec::new(), frames: 0, stride: 1, average_ms: 0., processed: 0 })339
Ok(BackgroundBlur { segmenter: Segmenter::new()?, mask: Vec::new(), frames: 0, stride: 1, average_ms: 0., processed: 0 })301
}340
}302
341
303
pub fn apply(&mut self, rgba: &mut [u8], width: usize, height: usize) {342
pub fn apply(&mut self, rgba: &mut [u8], width: usize, height: usize, covered: Option<&[u8]>) {304
let started = Instant::now();343
let started = Instant::now();305
if self.frames.is_multiple_of(self.stride) || self.mask.is_empty() {344
if self.frames.is_multiple_of(self.stride) || self.mask.is_empty() {306
self.segment(rgba, width, height, started);345
self.segment(rgba, width, height, started);307
}346
}308
self.frames += 1;347
self.frames += 1;309
compose(rgba, width, height, &self.mask);348
match covered {349
Some(covered) => compose_image(rgba, width, height, &self.mask, covered),350
None => compose(rgba, width, height, &self.mask),351
}310
let elapsed = started.elapsed().as_secs_f64() * 1000.;352
let elapsed = started.elapsed().as_secs_f64() * 1000.;311
self.average_ms = if self.processed == 0 { elapsed } else { self.average_ms * (1. - AVERAGE_WEIGHT) + elapsed * AVERAGE_WEIGHT };353
self.average_ms = if self.processed == 0 { elapsed } else { self.average_ms * (1. - AVERAGE_WEIGHT) + elapsed * AVERAGE_WEIGHT };312
self.processed += 1;354
self.processed += 1;@@ -411,6 +453,40 @@ mod tests {411
assert!(blurred.chunks(CHANNELS).all(|pixel| pixel[3] == 255));453
assert!(blurred.chunks(CHANNELS).all(|pixel| pixel[3] == 255));412
}454
}413
455
456
fn cover_of(color: [u8; 3]) -> Vec<u8> {457
BackgroundPicture::from_rgb(color.repeat(4 * 4), 4, 4).unwrap().covering(WIDTH, HEIGHT)458
}459
460
#[test]461
fn the_person_stays_and_the_picture_replaces_everything_else() {462
let original = checkerboard();463
let mut replaced = original.clone();464
compose_image(&mut replaced, WIDTH, HEIGHT, &oval_mask(), &cover_of([10, 120, 200]));465
let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);466
assert_eq!(pixel(&replaced, center_x, center_y), pixel(&original, center_x, center_y));467
for (x, y) in [(2, 2), (WIDTH - 3, HEIGHT - 3), (2, HEIGHT - 3)] {468
assert_eq!(&replaced[(y * WIDTH + x) * CHANNELS..][..4], &[10, 120, 200, 255]);469
}470
}471
472
#[test]473
fn the_picture_edge_is_feathered_like_the_blur_edge() {474
let original = checkerboard();475
let mut replaced = original.clone();476
compose_image(&mut replaced, WIDTH, HEIGHT, &oval_mask(), &cover_of([0, 0, 0]));477
let edge_row = HEIGHT / 2;478
let switches = (0..WIDTH - 1)479
.filter(|&x| pixel(&replaced, x, edge_row) != pixel(&original, x, edge_row) && pixel(&replaced, x + 1, edge_row) == pixel(&original, x + 1, edge_row))480
.count();481
assert!(switches <= 2);482
let mut everyone = original.clone();483
compose_image(&mut everyone, WIDTH, HEIGHT, &vec![1.; MASK_WIDTH * MASK_HEIGHT], &cover_of([0, 0, 0]));484
assert_eq!(everyone, original);485
let mut nobody = original;486
compose_image(&mut nobody, WIDTH, HEIGHT, &vec![0.; MASK_WIDTH * MASK_HEIGHT], &cover_of([0, 0, 0]));487
assert!(nobody.chunks(CHANNELS).all(|pixel| pixel[..3] == [0, 0, 0] && pixel[3] == 255));488
}489
414
#[test]490
#[test]415
fn the_model_answers_one_probability_per_mask_pixel() {491
fn the_model_answers_one_probability_per_mask_pixel() {416
let segmenter = Segmenter::new().expect("model loads");492
let segmenter = Segmenter::new().expect("model loads");@@ -423,8 +499,8 @@ mod tests {423
fn the_blur_keeps_a_running_average_and_a_mask() {499
fn the_blur_keeps_a_running_average_and_a_mask() {424
let mut blur = BackgroundBlur::new().expect("model loads");500
let mut blur = BackgroundBlur::new().expect("model loads");425
let mut frame = checkerboard();501
let mut frame = checkerboard();426
blur.apply(&mut frame, WIDTH, HEIGHT);502
blur.apply(&mut frame, WIDTH, HEIGHT, None);427
blur.apply(&mut frame, WIDTH, HEIGHT);503
blur.apply(&mut frame, WIDTH, HEIGHT, None);428
assert!(blur.average_ms() > 0.);504
assert!(blur.average_ms() > 0.);429
assert_eq!(blur.mask.len(), MASK_WIDTH * MASK_HEIGHT);505
assert_eq!(blur.mask.len(), MASK_WIDTH * MASK_HEIGHT);430
}506
}@@ -0,0 +1,247 @@
1
use serde_json::Value;
2
3
use crate::signaling::MeetingTarget;
4
use crate::trouter_events::find_key;
5
6
const MEETUP_PATH: &str = "/l/meetup-join/";
7
8
#[derive(Debug, Clone, PartialEq)]
9
pub struct BreakoutMove {
10
pub room_name: String,
11
pub target: MeetingTarget,
12
pub returning: bool,
13
}
14
15
#[derive(Debug, Clone, PartialEq, Eq)]
16
pub struct RoomAssignment {
17
pub name: String,
18
pub open: bool,
19
pub join_url: String,
20
pub version: u64,
21
}
22
23
fn percent_decoded(text: &str) -> String {
24
let bytes = text.as_bytes();
25
let mut decoded = Vec::with_capacity(bytes.len());
26
let mut index = 0;
27
while index < bytes.len() {
28
let hex = bytes.get(index + 1..index + 3).and_then(|pair| std::str::from_utf8(pair).ok()).and_then(|pair| u8::from_str_radix(pair, 16).ok());
29
match (bytes[index], hex) {
30
(b'%', Some(byte)) => {
31
decoded.push(byte);
32
index += 3;
33
}
34
(byte, _) => {
35
decoded.push(byte);
36
index += 1;
37
}
38
}
39
}
40
String::from_utf8_lossy(&decoded).into_owned()
41
}
42
43
fn context_of(decoded_url: &str) -> Option<Value> {
44
let start = decoded_url.find('{')?;
45
let mut depth = 0usize;
46
for (offset, letter) in decoded_url[start..].char_indices() {
47
match letter {
48
'{' => depth += 1,
49
'}' => {
50
depth -= 1;
51
if depth == 0 {
52
return serde_json::from_str(&decoded_url[start..=start + offset]).ok();
53
}
54
}
55
_ => {}
56
}
57
}
58
None
59
}
60
61
/// `https://<host>/l/meetup-join/<thread>/<messageId>?context={"Tid":..,"Oid":..}`; the host does not matter.
62
pub fn target_from_join_url(url: &str) -> Option<MeetingTarget> {
63
let decoded = percent_decoded(url);
64
let after = &decoded[decoded.find(MEETUP_PATH)? + MEETUP_PATH.len()..];
65
let thread_id = after.split(['/', '?']).next().filter(|thread| thread.starts_with("19:"))?.to_owned();
66
let context = context_of(after)?;
67
Some(MeetingTarget {
68
thread_id,
69
tenant_id: context["Tid"].as_str()?.to_owned(),
70
organizer_id: context["Oid"].as_str()?.to_owned(),
71
meeting_data: None,
72
})
73
}
74
75
/// `<tenantId>/<organizerId>/<threadId with the first ":" written as "_">/<messageId>`.
76
pub fn target_from_coordinates(coordinates: &str) -> Option<MeetingTarget> {
77
let mut parts = coordinates.split('/');
78
let (tenant_id, organizer_id, thread) = (parts.next()?, parts.next()?, parts.next()?);
79
if tenant_id.is_empty() || organizer_id.is_empty() {
80
return None;
81
}
82
let thread_id = thread.replacen('_', ":", 1);
83
thread_id.starts_with("19:").then(|| MeetingTarget {
84
thread_id,
85
tenant_id: tenant_id.to_owned(),
86
organizer_id: organizer_id.to_owned(),
87
meeting_data: None,
88
})
89
}
90
91
pub fn room_assignment(body: &Value) -> Option<RoomAssignment> {
92
let properties = find_key(body, "mainMeetingProperties")?;
93
let room = properties["assignedBreakoutRooms"].as_array()?.first()?;
94
Some(RoomAssignment {
95
name: room["name"].as_str().unwrap_or("a breakout room").to_owned(),
96
open: room["isOpen"].as_bool().unwrap_or(false),
97
join_url: room["meetingJoinUrl"].as_str()?.to_owned(),
98
version: properties["breakoutRoomVersion"].as_u64().unwrap_or_default(),
99
})
100
}
101
102
pub fn main_meeting_target(conversation_update: &Value) -> Option<MeetingTarget> {
103
let properties = find_key(conversation_update, "breakoutRoomProperties")?;
104
target_from_join_url(properties["mainMeetingJoinUrl"].as_str()?)
105
}
106
107
/// Mode 1: the server rings the client with a "replaces" call that names the room or the main meeting.
108
pub fn invite_move(body: &Value) -> Option<BreakoutMove> {
109
let data = find_key(body, "breakoutRoomData")?;
110
let returning = data["isMainMeetingInvite"].as_bool().unwrap_or(false);
111
if !returning && !data["isRoomInvite"].as_bool().unwrap_or(false) {
112
return None;
113
}
114
let target = target_from_coordinates(data["relatedMeetingCoords"].as_str()?)?;
115
let room_name = data["meetingName"].as_str().filter(|name| !name.is_empty()).map_or_else(
116
|| if returning { "the main meeting".to_owned() } else { "a breakout room".to_owned() },
117
str::to_owned,
118
);
119
Some(BreakoutMove { room_name, target, returning })
120
}
121
122
/// Mode 2: no invite, the room simply opens; moves once per room opening.
123
#[derive(Debug, Default)]
124
pub struct RoomWatcher {
125
version: u64,
126
joined: Option<String>,
127
}
128
129
impl RoomWatcher {
130
pub fn apply(&mut self, assignment: Option<RoomAssignment>) -> Option<BreakoutMove> {
131
let assignment = assignment?;
132
if assignment.version < self.version {
133
return None;
134
}
135
self.version = assignment.version;
136
if !assignment.open {
137
self.joined = None;
138
return None;
139
}
140
if self.joined.as_deref() == Some(assignment.join_url.as_str()) {
141
return None;
142
}
143
let target = target_from_join_url(&assignment.join_url)?;
144
self.joined = Some(assignment.join_url);
145
Some(BreakoutMove { room_name: assignment.name, target, returning: false })
146
}
147
148
pub fn entered(&mut self, join_url: &str) {
149
self.joined = Some(join_url.to_owned());
150
}
151
}
152
153
#[cfg(test)]
154
mod tests {
155
use serde_json::json;
156
157
use super::*;
158
159
const ROOM_URL: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_Room1abc%40thread.v2/0?context=%7b%22Tid%22%3a%22tenant-1%22%2c%22Oid%22%3a%22org-1%22%7d";
160
161
fn room_update(open: bool, version: u64) -> Value {
162
json!({"breakoutDetails": {"mainMeetingProperties": {
163
"breakoutRoomVersion": version,
164
"breakoutRoomManagers": [],
165
"allBreakoutRooms": [{"name": "Room 1", "isOpen": open, "meetingJoinUrl": ROOM_URL, "invitees": []}],
166
"assignedBreakoutRooms": [{"name": "Room 1", "isOpen": open, "meetingJoinUrl": ROOM_URL, "invitees": [{"id": "8:orgid:me"}], "eTag": "1", "moveJitter": 3}],
167
}}})
168
}
169
170
#[test]
171
fn a_meetup_join_link_becomes_a_meeting_target() {
172
let target = target_from_join_url(ROOM_URL).unwrap();
173
assert_eq!(target.thread_id, "19:meeting_Room1abc@thread.v2");
174
assert_eq!(target.tenant_id, "tenant-1");
175
assert_eq!(target.organizer_id, "org-1");
176
let plain = "https://teams.cloud.microsoft/l/meetup-join/19:meeting_x@thread.v2/0?context={\"Tid\":\"t\",\"Oid\":\"o\"}";
177
assert_eq!(target_from_join_url(plain).unwrap().organizer_id, "o");
178
assert!(target_from_join_url("https://example.com/other").is_none());
179
assert!(target_from_join_url("https://teams.microsoft.com/l/meetup-join/19:x@thread.v2/0").is_none());
180
}
181
182
#[test]
183
fn coordinates_name_the_meeting_with_the_first_colon_replaced() {
184
let target = target_from_coordinates("tenant-1/org-1/19_meeting_Room1abc@thread.v2/0").unwrap();
185
assert_eq!(target.thread_id, "19:meeting_Room1abc@thread.v2");
186
assert_eq!((target.tenant_id.as_str(), target.organizer_id.as_str()), ("tenant-1", "org-1"));
187
assert!(target_from_coordinates("tenant-1/org-1").is_none());
188
assert!(target_from_coordinates("t/o/nonsense/0").is_none());
189
}
190
191
#[test]
192
fn the_assigned_room_is_read_from_the_participant_update() {
193
let assignment = room_assignment(&room_update(true, 5)).unwrap();
194
assert_eq!(assignment, RoomAssignment { name: "Room 1".into(), open: true, join_url: ROOM_URL.into(), version: 5 });
195
assert!(room_assignment(&json!({"breakoutDetails": {"mainMeetingProperties": {"assignedBreakoutRooms": []}}})).is_none());
196
assert!(room_assignment(&json!({"other": 1})).is_none());
197
}
198
199
#[test]
200
fn an_opening_room_moves_you_once() {
201
let mut watcher = RoomWatcher::default();
202
assert!(watcher.apply(room_assignment(&room_update(false, 1))).is_none());
203
let moved = watcher.apply(room_assignment(&room_update(true, 2))).unwrap();
204
assert_eq!(moved.room_name, "Room 1");
205
assert_eq!(moved.target.thread_id, "19:meeting_Room1abc@thread.v2");
206
assert!(!moved.returning);
207
assert!(watcher.apply(room_assignment(&room_update(true, 3))).is_none());
208
assert!(watcher.apply(room_assignment(&room_update(false, 4))).is_none());
209
assert!(watcher.apply(room_assignment(&room_update(true, 5))).is_some());
210
}
211
212
#[test]
213
fn old_versions_and_the_room_you_are_already_in_do_not_move_you() {
214
let mut watcher = RoomWatcher::default();
215
assert!(watcher.apply(room_assignment(&room_update(true, 9))).is_some());
216
assert!(watcher.apply(room_assignment(&room_update(false, 4))).is_none());
217
let mut inside = RoomWatcher::default();
218
inside.entered(ROOM_URL);
219
assert!(inside.apply(room_assignment(&room_update(true, 1))).is_none());
220
}
221
222
fn invite(room: bool, main: bool) -> Value {
223
json!({"callNotification": {"callType": "replaces", "invitationData": {"breakoutRoomData": {
224
"isRoomInvite": room, "isMainMeetingInvite": main, "meetingName": "Room 2",
225
"relatedMeetingCoords": "tenant-1/org-1/19_meeting_Room2@thread.v2/0", "shouldAutoAcceptInvite": true, "correlationId": "c"}},
226
"meetingInfo": {"tenantId": "tenant-1", "organizerId": "org-1"}}})
227
}
228
229
#[test]
230
fn a_room_invite_names_the_room_and_a_main_invite_sends_you_back() {
231
let moved = invite_move(&invite(true, false)).unwrap();
232
assert_eq!(moved.room_name, "Room 2");
233
assert_eq!(moved.target.thread_id, "19:meeting_Room2@thread.v2");
234
assert!(!moved.returning);
235
let back = invite_move(&invite(false, true)).unwrap();
236
assert!(back.returning);
237
assert!(invite_move(&invite(false, false)).is_none());
238
assert!(invite_move(&json!({"callNotification": {}})).is_none());
239
}
240
241
#[test]
242
fn the_room_properties_carry_the_way_back() {
243
let update = json!({"meetingDetails": {"breakoutDetails": {"breakoutRoomProperties": {"mainMeetingJoinUrl": ROOM_URL, "remainingRoomDuration": 600}}}});
244
assert_eq!(main_meeting_target(&update).unwrap().tenant_id, "tenant-1");
245
assert!(main_meeting_target(&json!({"meetingDetails": {}})).is_none());
246
}
247
}
@@ -0,0 +1,247 @@1
use serde_json::Value;2
3
use crate::signaling::MeetingTarget;4
use crate::trouter_events::find_key;5
6
const MEETUP_PATH: &str = "/l/meetup-join/";7
8
#[derive(Debug, Clone, PartialEq)]9
pub struct BreakoutMove {10
pub room_name: String,11
pub target: MeetingTarget,12
pub returning: bool,13
}14
15
#[derive(Debug, Clone, PartialEq, Eq)]16
pub struct RoomAssignment {17
pub name: String,18
pub open: bool,19
pub join_url: String,20
pub version: u64,21
}22
23
fn percent_decoded(text: &str) -> String {24
let bytes = text.as_bytes();25
let mut decoded = Vec::with_capacity(bytes.len());26
let mut index = 0;27
while index < bytes.len() {28
let hex = bytes.get(index + 1..index + 3).and_then(|pair| std::str::from_utf8(pair).ok()).and_then(|pair| u8::from_str_radix(pair, 16).ok());29
match (bytes[index], hex) {30
(b'%', Some(byte)) => {31
decoded.push(byte);32
index += 3;33
}34
(byte, _) => {35
decoded.push(byte);36
index += 1;37
}38
}39
}40
String::from_utf8_lossy(&decoded).into_owned()41
}42
43
fn context_of(decoded_url: &str) -> Option<Value> {44
let start = decoded_url.find('{')?;45
let mut depth = 0usize;46
for (offset, letter) in decoded_url[start..].char_indices() {47
match letter {48
'{' => depth += 1,49
'}' => {50
depth -= 1;51
if depth == 0 {52
return serde_json::from_str(&decoded_url[start..=start + offset]).ok();53
}54
}55
_ => {}56
}57
}58
None59
}60
61
/// `https://<host>/l/meetup-join/<thread>/<messageId>?context={"Tid":..,"Oid":..}`; the host does not matter.62
pub fn target_from_join_url(url: &str) -> Option<MeetingTarget> {63
let decoded = percent_decoded(url);64
let after = &decoded[decoded.find(MEETUP_PATH)? + MEETUP_PATH.len()..];65
let thread_id = after.split(['/', '?']).next().filter(|thread| thread.starts_with("19:"))?.to_owned();66
let context = context_of(after)?;67
Some(MeetingTarget {68
thread_id,69
tenant_id: context["Tid"].as_str()?.to_owned(),70
organizer_id: context["Oid"].as_str()?.to_owned(),71
meeting_data: None,72
})73
}74
75
/// `<tenantId>/<organizerId>/<threadId with the first ":" written as "_">/<messageId>`.76
pub fn target_from_coordinates(coordinates: &str) -> Option<MeetingTarget> {77
let mut parts = coordinates.split('/');78
let (tenant_id, organizer_id, thread) = (parts.next()?, parts.next()?, parts.next()?);79
if tenant_id.is_empty() || organizer_id.is_empty() {80
return None;81
}82
let thread_id = thread.replacen('_', ":", 1);83
thread_id.starts_with("19:").then(|| MeetingTarget {84
thread_id,85
tenant_id: tenant_id.to_owned(),86
organizer_id: organizer_id.to_owned(),87
meeting_data: None,88
})89
}90
91
pub fn room_assignment(body: &Value) -> Option<RoomAssignment> {92
let properties = find_key(body, "mainMeetingProperties")?;93
let room = properties["assignedBreakoutRooms"].as_array()?.first()?;94
Some(RoomAssignment {95
name: room["name"].as_str().unwrap_or("a breakout room").to_owned(),96
open: room["isOpen"].as_bool().unwrap_or(false),97
join_url: room["meetingJoinUrl"].as_str()?.to_owned(),98
version: properties["breakoutRoomVersion"].as_u64().unwrap_or_default(),99
})100
}101
102
pub fn main_meeting_target(conversation_update: &Value) -> Option<MeetingTarget> {103
let properties = find_key(conversation_update, "breakoutRoomProperties")?;104
target_from_join_url(properties["mainMeetingJoinUrl"].as_str()?)105
}106
107
/// Mode 1: the server rings the client with a "replaces" call that names the room or the main meeting.108
pub fn invite_move(body: &Value) -> Option<BreakoutMove> {109
let data = find_key(body, "breakoutRoomData")?;110
let returning = data["isMainMeetingInvite"].as_bool().unwrap_or(false);111
if !returning && !data["isRoomInvite"].as_bool().unwrap_or(false) {112
return None;113
}114
let target = target_from_coordinates(data["relatedMeetingCoords"].as_str()?)?;115
let room_name = data["meetingName"].as_str().filter(|name| !name.is_empty()).map_or_else(116
|| if returning { "the main meeting".to_owned() } else { "a breakout room".to_owned() },117
str::to_owned,118
);119
Some(BreakoutMove { room_name, target, returning })120
}121
122
/// Mode 2: no invite, the room simply opens; moves once per room opening.123
#[derive(Debug, Default)]124
pub struct RoomWatcher {125
version: u64,126
joined: Option<String>,127
}128
129
impl RoomWatcher {130
pub fn apply(&mut self, assignment: Option<RoomAssignment>) -> Option<BreakoutMove> {131
let assignment = assignment?;132
if assignment.version < self.version {133
return None;134
}135
self.version = assignment.version;136
if !assignment.open {137
self.joined = None;138
return None;139
}140
if self.joined.as_deref() == Some(assignment.join_url.as_str()) {141
return None;142
}143
let target = target_from_join_url(&assignment.join_url)?;144
self.joined = Some(assignment.join_url);145
Some(BreakoutMove { room_name: assignment.name, target, returning: false })146
}147
148
pub fn entered(&mut self, join_url: &str) {149
self.joined = Some(join_url.to_owned());150
}151
}152
153
#[cfg(test)]154
mod tests {155
use serde_json::json;156
157
use super::*;158
159
const ROOM_URL: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_Room1abc%40thread.v2/0?context=%7b%22Tid%22%3a%22tenant-1%22%2c%22Oid%22%3a%22org-1%22%7d";160
161
fn room_update(open: bool, version: u64) -> Value {162
json!({"breakoutDetails": {"mainMeetingProperties": {163
"breakoutRoomVersion": version,164
"breakoutRoomManagers": [],165
"allBreakoutRooms": [{"name": "Room 1", "isOpen": open, "meetingJoinUrl": ROOM_URL, "invitees": []}],166
"assignedBreakoutRooms": [{"name": "Room 1", "isOpen": open, "meetingJoinUrl": ROOM_URL, "invitees": [{"id": "8:orgid:me"}], "eTag": "1", "moveJitter": 3}],167
}}})168
}169
170
#[test]171
fn a_meetup_join_link_becomes_a_meeting_target() {172
let target = target_from_join_url(ROOM_URL).unwrap();173
assert_eq!(target.thread_id, "19:meeting_Room1abc@thread.v2");174
assert_eq!(target.tenant_id, "tenant-1");175
assert_eq!(target.organizer_id, "org-1");176
let plain = "https://teams.cloud.microsoft/l/meetup-join/19:meeting_x@thread.v2/0?context={\"Tid\":\"t\",\"Oid\":\"o\"}";177
assert_eq!(target_from_join_url(plain).unwrap().organizer_id, "o");178
assert!(target_from_join_url("https://example.com/other").is_none());179
assert!(target_from_join_url("https://teams.microsoft.com/l/meetup-join/19:x@thread.v2/0").is_none());180
}181
182
#[test]183
fn coordinates_name_the_meeting_with_the_first_colon_replaced() {184
let target = target_from_coordinates("tenant-1/org-1/19_meeting_Room1abc@thread.v2/0").unwrap();185
assert_eq!(target.thread_id, "19:meeting_Room1abc@thread.v2");186
assert_eq!((target.tenant_id.as_str(), target.organizer_id.as_str()), ("tenant-1", "org-1"));187
assert!(target_from_coordinates("tenant-1/org-1").is_none());188
assert!(target_from_coordinates("t/o/nonsense/0").is_none());189
}190
191
#[test]192
fn the_assigned_room_is_read_from_the_participant_update() {193
let assignment = room_assignment(&room_update(true, 5)).unwrap();194
assert_eq!(assignment, RoomAssignment { name: "Room 1".into(), open: true, join_url: ROOM_URL.into(), version: 5 });195
assert!(room_assignment(&json!({"breakoutDetails": {"mainMeetingProperties": {"assignedBreakoutRooms": []}}})).is_none());196
assert!(room_assignment(&json!({"other": 1})).is_none());197
}198
199
#[test]200
fn an_opening_room_moves_you_once() {201
let mut watcher = RoomWatcher::default();202
assert!(watcher.apply(room_assignment(&room_update(false, 1))).is_none());203
let moved = watcher.apply(room_assignment(&room_update(true, 2))).unwrap();204
assert_eq!(moved.room_name, "Room 1");205
assert_eq!(moved.target.thread_id, "19:meeting_Room1abc@thread.v2");206
assert!(!moved.returning);207
assert!(watcher.apply(room_assignment(&room_update(true, 3))).is_none());208
assert!(watcher.apply(room_assignment(&room_update(false, 4))).is_none());209
assert!(watcher.apply(room_assignment(&room_update(true, 5))).is_some());210
}211
212
#[test]213
fn old_versions_and_the_room_you_are_already_in_do_not_move_you() {214
let mut watcher = RoomWatcher::default();215
assert!(watcher.apply(room_assignment(&room_update(true, 9))).is_some());216
assert!(watcher.apply(room_assignment(&room_update(false, 4))).is_none());217
let mut inside = RoomWatcher::default();218
inside.entered(ROOM_URL);219
assert!(inside.apply(room_assignment(&room_update(true, 1))).is_none());220
}221
222
fn invite(room: bool, main: bool) -> Value {223
json!({"callNotification": {"callType": "replaces", "invitationData": {"breakoutRoomData": {224
"isRoomInvite": room, "isMainMeetingInvite": main, "meetingName": "Room 2",225
"relatedMeetingCoords": "tenant-1/org-1/19_meeting_Room2@thread.v2/0", "shouldAutoAcceptInvite": true, "correlationId": "c"}},226
"meetingInfo": {"tenantId": "tenant-1", "organizerId": "org-1"}}})227
}228
229
#[test]230
fn a_room_invite_names_the_room_and_a_main_invite_sends_you_back() {231
let moved = invite_move(&invite(true, false)).unwrap();232
assert_eq!(moved.room_name, "Room 2");233
assert_eq!(moved.target.thread_id, "19:meeting_Room2@thread.v2");234
assert!(!moved.returning);235
let back = invite_move(&invite(false, true)).unwrap();236
assert!(back.returning);237
assert!(invite_move(&invite(false, false)).is_none());238
assert!(invite_move(&json!({"callNotification": {}})).is_none());239
}240
241
#[test]242
fn the_room_properties_carry_the_way_back() {243
let update = json!({"meetingDetails": {"breakoutDetails": {"breakoutRoomProperties": {"mainMeetingJoinUrl": ROOM_URL, "remainingRoomDuration": 600}}}});244
assert_eq!(main_meeting_target(&update).unwrap().tenant_id, "tenant-1");245
assert!(main_meeting_target(&json!({"meetingDetails": {}})).is_none());246
}247
}@@ -9,7 +9,7 @@ use futures_util::StreamExt;
9
9
use libwebrtc::audio_stream::native::NativeAudioStream;
10
10
use libwebrtc::data_channel::{DataChannel, DataChannelInit};
11
11
use libwebrtc::prelude::*;
12
use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};
12
use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit};
13
13
use libwebrtc::session_description::{SdpType, SessionDescription};
14
14
use libwebrtc::stats::RtcStats;
15
15
use session::Session;
@@ -19,6 +19,8 @@ use tokio::time::{Instant, interval, sleep_until, timeout};
19
19
20
20
use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};
21
21
use crate::audio_io::{AudioMode, AudioSetup};
22
use crate::background::{BackgroundChoice, BackgroundPicture};
23
use crate::breakout::{self, RoomWatcher};
22
24
use crate::captions::{CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep, BotAction, parse_caption_message};
23
25
use crate::data_channel::Depacketizer;
24
26
use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
@@ -26,21 +28,27 @@ use crate::devices::{self, DeviceChoice};
26
28
use crate::end::EndKind;
27
29
use crate::engine::{CallEngine, EngineConfig, Inner};
28
30
use crate::error::{Error, Result};
31
use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, rewrite_directions};
29
32
use crate::mute::{MuteCommand, MuteEffect};
30
33
use crate::push::CallNotification;
31
34
use crate::share_audio::ShareAudio;
32
35
use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
33
use crate::renegotiation::{MediaAction, MediaNegotiator};
36
use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath};
34
37
use crate::organizer::Target;
38
use crate::recording::{Consent, RecordingStatus};
35
39
use crate::roster::Roster;
36
use crate::sdp::{RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
40
use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
37
41
use crate::signaling::{
38
42
Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling,
39
43
TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
40
44
};
41
45
use crate::state::{CallSignal, CallState};
42
46
use crate::timeline::{Timeline, TimelineEntry};
43
use crate::video_layout::{MediaDescription, SlotTable, VideoLines, VideoRouter, add_video_lines, offer_plan};
47
use crate::transfer::{TransferEvent, TransferTarget};
48
use crate::video_frame::VideoKey;
49
use crate::video_layout::{
50
CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, offer_plan, one_to_one_plan,
51
};
44
52
use crate::video_send::{LocalVideo, VideoMode};
45
53
use crate::camera::{CameraDevice, list_cameras};
46
54
use crate::screen::{ShareKind, ShareSource, list_share_sources};
@@ -48,6 +56,7 @@ use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoR
48
56
use crate::trouter_events::{
49
57
CallEnd, CallEvent, CallbackLinks, ProgressStatus, acceptance_acknowledgement, classify, decode_body,
50
58
};
59
use crate::whiteboard;
51
60
52
61
const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
53
62
const STATS_PERIOD: Duration = Duration::from_millis(200);
@@ -64,6 +73,10 @@ pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL";
64
73
const CAPTION_START_LIMIT: Duration = Duration::from_secs(40);
65
74
const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
66
75
const BOT_PREFIX: &str = "28:";
76
const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
77
const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(15);
78
const CAMERA_STREAM: &str = "camera";
79
const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
67
80
68
81
#[derive(Debug, Clone)]
69
82
pub struct CallOptions {
@@ -83,6 +96,7 @@ pub struct CallOptions {
83
96
pub sdp_dump_dir: Option<PathBuf>,
84
97
pub trace: bool,
85
98
pub data_channel: bool,
99
pub concurrent: bool,
86
100
}
87
101
88
102
impl Default for CallOptions {
@@ -104,6 +118,7 @@ impl Default for CallOptions {
104
118
sdp_dump_dir: None,
105
119
trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(),
106
120
data_channel: data_channel_from_env(),
121
concurrent: false,
107
122
}
108
123
}
109
124
}
@@ -184,6 +199,7 @@ impl CallSpec {
184
199
}
185
200
186
201
pub(crate) struct IncomingCall {
202
pub accept: AcceptMode,
187
203
pub notification: CallNotification,
188
204
pub attached: Attached,
189
205
pub links: CallbackLinks,
@@ -235,6 +251,39 @@ struct OfferedMedia {
235
251
browser_offer: String,
236
252
signaled: SignaledOffer,
237
253
video: VideoLines,
254
plan: OfferPlan,
255
modalities: Vec<String>,
256
}
257
258
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
259
enum Layout {
260
Conference,
261
OneToOne,
262
}
263
264
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
265
pub enum AcceptMode {
266
Audio,
267
Video,
268
}
269
270
#[derive(Clone, Copy)]
271
enum AnswerVideo<'a> {
272
Reject,
273
Receive,
274
Send(&'a RtcVideoTrack),
275
}
276
277
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278
enum Change {
279
Hold(bool),
280
Camera(bool),
281
}
282
283
struct SamePeerOffer {
284
browser_offer: String,
285
signaled: SignaledOffer,
286
change: Change,
238
287
}
239
288
240
289
struct NextPeer {
@@ -242,11 +291,6 @@ struct NextPeer {
242
291
offered: Option<OfferedMedia>,
243
292
}
244
293
245
struct AnsweredMedia {
246
remote: RemoteOffer,
247
answer_sdp: String,
248
}
249
250
294
#[derive(Clone)]
251
295
struct RemoteCall {
252
296
signaling: Arc<Signaling>,
@@ -306,7 +350,7 @@ pub async fn run_test_call(
306
350
impl CallEngine {
307
351
pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
308
352
let inner = self.inner.as_ref();
309
let _one_call_at_a_time = inner.gate.lock().await;
353
let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };
310
354
let timeline = Timeline::new(options.trace);
311
355
let mut report = CallReport::default();
312
356
let mut state = CallState::Idle;
@@ -389,7 +433,23 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv
389
433
Ok(channel)
390
434
}
391
435
392
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack) -> Result<OfferedMedia> {
436
fn one_to_one_directions(camera: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> {
437
move |line| match (line.kind, line.mid) {
438
("video", CAMERA_MID) => Some(if camera { "sendrecv" } else { INACTIVE }),
439
("video", ONE_TO_ONE_SHARE_MID) => Some(INACTIVE),
440
_ => None,
441
}
442
}
443
444
fn directions_for(layout: Layout, hold: bool, camera: bool, text: &str) -> String {
445
match (hold, layout) {
446
(true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
447
(false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera)),
448
(false, Layout::Conference) => text.to_owned(),
449
}
450
}
451
452
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout) -> Result<OfferedMedia> {
393
453
let transceiver_init = RtpTransceiverInit {
394
454
direction: RtpTransceiverDirection::SendRecv,
395
455
stream_ids: vec![MIC_STREAM.into()],
@@ -397,7 +457,10 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
397
457
};
398
458
peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init)
399
459
.map_err(|error| Error::Webrtc(error.to_string()))?;
400
let video = add_video_lines(peer, factory)?;
460
let (video, plan) = match layout {
461
Layout::Conference => (add_video_lines(peer, factory)?, offer_plan()),
462
Layout::OneToOne => (add_one_to_one_lines(peer, factory)?, one_to_one_plan()),
463
};
401
464
let offer = peer
402
465
.create_offer(OfferOptions {
403
466
offer_to_receive_audio: true,
@@ -406,20 +469,31 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
406
469
})
407
470
.await
408
471
.map_err(|error| Error::Webrtc(error.to_string()))?;
409
peer.set_local_description(offer.clone())
472
let browser_offer = directions_for(layout, false, false, &offer.to_string());
473
let description = SessionDescription::parse(&browser_offer, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;
474
peer.set_local_description(description)
410
475
.await
411
476
.map_err(|error| Error::Webrtc(error.to_string()))?;
412
let browser_offer = offer.to_string();
413
477
let mut numbers = random_u32;
414
let signaled = to_teams_offer(&browser_offer, &offer_plan(), &mut numbers)?;
415
Ok(OfferedMedia { browser_offer, signaled, video })
478
let signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
479
Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })
480
}
481
482
struct AnsweredMedia {
483
remote: RemoteOffer,
484
answer_sdp: String,
485
camera_mid: Option<String>,
486
}
487
488
fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
489
remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
416
490
}
417
491
418
/// Video lines of a Teams offer are stopped so the answer rejects them; audio is all this client does.
419
492
async fn answer_offer(
420
493
peer: &PeerConnection,
421
494
track: Option<&RtcAudioTrack>,
422
495
teams_offer: &str,
496
video: AnswerVideo<'_>,
423
497
) -> Result<AnsweredMedia> {
424
498
let remote = from_teams_offer(teams_offer)?;
425
499
let description =
@@ -427,8 +501,10 @@ async fn answer_offer(
427
501
peer.set_remote_description(description)
428
502
.await
429
503
.map_err(|error| Error::Webrtc(error.to_string()))?;
504
let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
430
505
for transceiver in peer.transceivers() {
431
if matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_))) {
506
let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
507
if is_video && transceiver.mid() != camera_mid {
432
508
let _ = transceiver.stop();
433
509
}
434
510
}
@@ -436,6 +512,10 @@ async fn answer_offer(
436
512
peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
437
513
.map_err(|error| Error::Webrtc(error.to_string()))?;
438
514
}
515
if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {
516
peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM])
517
.map_err(|error| Error::Webrtc(error.to_string()))?;
518
}
439
519
let answer = peer
440
520
.create_answer(AnswerOptions::default())
441
521
.await
@@ -448,6 +528,7 @@ async fn answer_offer(
448
528
Ok(AnsweredMedia {
449
529
remote,
450
530
answer_sdp: signaled.sdp,
531
camera_mid,
451
532
})
452
533
}
453
534
@@ -480,8 +561,10 @@ async fn drive(
480
561
Plan::Outgoing(spec) => (Some(spec), None),
481
562
Plan::Incoming(incoming) => (None, Some(*incoming)),
482
563
};
564
let accept_mode = incoming.as_ref().map_or(AcceptMode::Audio, |incoming| incoming.accept);
483
565
let (links, participant, mut callbacks, incoming_media) = match incoming {
484
566
Some(IncomingCall {
567
accept: _,
485
568
notification,
486
569
attached,
487
570
links,
@@ -544,10 +627,30 @@ async fn drive(
544
627
let mut outgoing_deadline: Option<Instant> = None;
545
628
let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
546
629
let is_echo = matches!(spec, Some(CallSpec::Echo));
630
let meeting_target = match &spec {
631
Some(CallSpec::Meeting(target)) => Some(target.clone()),
632
_ => None,
633
};
634
let mut layout = match &spec {
635
Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne,
636
_ => Layout::Conference,
637
};
638
let peer_mri = match &spec {
639
Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Some(callees[0].mri.clone()),
640
_ => incoming_media.as_ref().map(|(notification, _)| notification.caller.mri.clone()),
641
};
642
let mut layout_plan: OfferPlan;
643
let mut direct_video_mid: Option<String> = None;
644
let mut sending_camera = false;
645
let mut media_links: BTreeMap<String, String> = BTreeMap::new();
547
646
548
647
let conversation = match (spec, incoming_media) {
549
648
(Some(spec), None) => {
550
let media = create_offer(¤t.peer, &factory, &track).await?;
649
let media = create_offer(¤t.peer, &factory, &track, layout).await?;
650
layout_plan = media.plan.clone();
651
if layout == Layout::OneToOne {
652
direct_video_mid = Some(CAMERA_MID.to_owned());
653
}
551
654
timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
552
655
dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
553
656
dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
@@ -558,6 +661,7 @@ async fn drive(
558
661
media_leg_id: &media_leg_id,
559
662
callbacks: &links,
560
663
target: &target,
664
modalities: &media.modalities,
561
665
};
562
666
let conversation = match &target {
563
667
InviteTarget::Meeting(meeting) => {
@@ -583,7 +687,7 @@ async fn drive(
583
687
});
584
688
conversation
585
689
}
586
(None, Some((_notification, attached))) => {
690
(None, Some((notification, attached))) => {
587
691
let teams_offer = attached
588
692
.offer_sdp
589
693
.clone()
@@ -597,7 +701,17 @@ async fn drive(
597
701
conversation: conversation.clone(),
598
702
participant: participant.clone(),
599
703
});
600
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer).await?;
704
let one_to_one = !attached.from_mixer && !notification.is_multi_party;
705
layout = if one_to_one { Layout::OneToOne } else { Layout::Conference };
706
let camera_track = local_video.camera_track();
707
let video_answer = match accept_mode {
708
_ if !one_to_one => AnswerVideo::Reject,
709
AcceptMode::Video if local_video.is_available() => AnswerVideo::Send(&camera_track),
710
_ => AnswerVideo::Receive,
711
};
712
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer, video_answer).await?;
713
layout_plan = answered.remote.plan();
714
direct_video_mid = answered.camera_mid.clone();
601
715
timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
602
716
dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
603
717
dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
@@ -605,7 +719,7 @@ async fn drive(
605
719
.links
606
720
.get("acceptance")
607
721
.ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
608
let modalities = vec!["Audio".to_owned()];
722
let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some());
609
723
signaling
610
724
.accept(
611
725
acceptance_url,
@@ -620,6 +734,18 @@ async fn drive(
620
734
.await?;
621
735
negotiator.answered_incoming(attached.from_mixer);
622
736
remote_set = true;
737
media_links.extend(attached.links.clone());
738
if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
739
let camera = peer_transceiver(¤t.peer, mid);
740
match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) {
741
Some(Ok(())) => match local_video.start_camera(&camera_choice) {
742
Ok(()) => sending_camera = true,
743
Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
744
},
745
Some(Err(error)) => timeline.record("video lines not attached", error.to_string()),
746
None => timeline.record("video lines not attached", "no transceiver for the camera line"),
747
}
748
}
623
749
keep_alive_link = attached.links.get("callLeg").cloned();
624
750
keep_alive_at = Some(Instant::now() + keep_alive_period(None));
625
751
conversation
@@ -657,7 +783,12 @@ async fn drive(
657
783
let mut second = 0u32;
658
784
let echo_thread = thread_id;
659
785
let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());
660
let mut media_links: BTreeMap<String, String> = BTreeMap::new();
786
if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) {
787
video.router().set(mid, Some(VideoKey::Person(mri.clone())));
788
}
789
if sending_camera {
790
control.send(CallUpdate::Camera(true));
791
}
661
792
let mut share_audio: Option<ShareAudio> = None;
662
793
let mut share_sound_wanted = false;
663
794
let mut remote_audio: Option<RtcAudioTrack> = None;
@@ -665,6 +796,18 @@ async fn drive(
665
796
let mut depacketizer = Depacketizer::default();
666
797
let mut caption_flow = CaptionFlow::default();
667
798
let mut caption_deadline: Option<Instant> = None;
799
let mut recording_flow = CaptionFlow::default();
800
let mut recording_deadline: Option<Instant> = None;
801
let mut recording_title = String::new();
802
let mut recording_status = RecordingStatus::default();
803
let mut bot_pending = false;
804
let mut consent_pending = false;
805
let mut room_watcher = RoomWatcher::default();
806
let mut main_meeting_sent = false;
807
let mut local_hold = false;
808
let mut remote_hold = false;
809
let mut same_peer: Option<SamePeerOffer> = None;
810
let mut same_peer_deadline: Option<Instant> = None;
668
811
let mut meeting_chat = conversation.chat_thread.clone();
669
812
if let Some(thread) = &meeting_chat {
670
813
control.send(CallUpdate::MeetingChat(thread.clone()));
@@ -688,7 +831,12 @@ async fn drive(
688
831
.inspect_err(|error| timeline.record("answer rejected", error.to_string()))?;
689
832
remote_set = true;
690
833
media_links.extend(acceptance.links.clone());
691
negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster);
834
if layout == Layout::Conference {
835
negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster);
836
}
837
if let Some(link) = acceptance.links.get("replacement") {
838
control.send(CallUpdate::ReplacementLink(link.clone()));
839
}
692
840
outgoing_deadline = None;
693
841
let directions: Vec<String> = current
694
842
.peer
@@ -732,7 +880,32 @@ async fn drive(
732
880
}
733
881
Ok(CallEvent::MediaAnswer(answer)) => {
734
882
replier.reply(request_id, 200, "");
735
if negotiator.on_media_answer() == MediaAction::ApplyOnNewPeer {
883
let action = negotiator.on_media_answer();
884
if action == MediaAction::ApplyOnSamePeer
885
&& let Some(pending) = same_peer.take()
886
{
887
same_peer_deadline = None;
888
let applied = apply_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await;
889
match applied {
890
Ok(()) => {
891
if let Some(url) = answer.links.get("mediaAcknowledgement") {
892
let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
893
}
894
match pending.change {
895
Change::Hold(hold) => {
896
local_hold = hold;
897
control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
898
}
899
Change::Camera(on) => control.send(CallUpdate::Camera(on)),
900
}
901
}
902
Err(error) => {
903
timeline.record("same-peer answer rejected", error.to_string());
904
undo_change(pending.change, &mut local_video, control);
905
}
906
}
907
}
908
if action == MediaAction::ApplyOnNewPeer {
736
909
let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) {
737
910
Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await,
738
911
None => Err(Error::Webrtc("no pending peer connection for the answer".into())),
@@ -771,8 +944,17 @@ async fn drive(
771
944
}
772
945
}
773
946
MediaAction::AnswerOnSamePeer => {
774
match answer_offer(¤t.peer, None, &renegotiation.sdp).await {
775
Ok(answered) => send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await,
947
let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
948
match answer_offer(¤t.peer, None, &renegotiation.sdp, video_answer).await {
949
Ok(answered) => {
950
let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
951
let held = is_hold(&renegotiation.sdp).unwrap_or(false);
952
if held != remote_hold {
953
remote_hold = held;
954
control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
955
}
956
sent
957
}
776
958
Err(error) => Err(error),
777
959
}
778
960
}
@@ -800,16 +982,29 @@ async fn drive(
800
982
lobby = in_lobby;
801
983
control.send(CallUpdate::Lobby(lobby));
802
984
}
985
if roster.caption_bot().is_some() {
986
bot_pending = false;
987
}
803
988
if caption_flow.wanted() {
804
run_caption_steps(&mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), control, timeline).await;
989
run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), "", &mut bot_pending, control, timeline).await;
805
990
if caption_flow.on() {
806
991
caption_deadline = None;
807
992
}
808
993
}
994
if recording_flow.wanted() {
995
run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_title, &mut bot_pending, control, timeline).await;
996
}
809
997
}
810
998
}
811
999
Ok(CallEvent::AddParticipantFailure(_)) => {
812
1000
replier.reply(request_id, 200, "");
1001
bot_pending = false;
1002
if recording_flow.wanted() && roster.caption_bot().is_none() {
1003
timeline.record("recorder bot failed", "addParticipantFailure");
1004
recording_flow.failed();
1005
recording_deadline = None;
1006
control.send(CallUpdate::Notice("The recording service could not join".into()));
1007
}
813
1008
if caption_flow.wanted() && roster.caption_bot().is_none() {
814
1009
timeline.record("caption bot failed", "addParticipantFailure");
815
1010
caption_flow.failed();
@@ -825,6 +1020,64 @@ async fn drive(
825
1020
control.send(CallUpdate::MeetingChat(thread.clone()));
826
1021
meeting_chat = Some(thread);
827
1022
}
1023
let change = recording_status.apply(&body);
1024
if let Some(on) = change.recording {
1025
control.send(CallUpdate::Recording(on));
1026
if on {
1027
recording_deadline = None;
1028
}
1029
}
1030
if let Some(required) = change.consent_required {
1031
consent_pending = required;
1032
control.send(CallUpdate::ConsentRequired(required));
1033
if required {
1034
withhold_media(&mut muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, &mut local_video, control);
1035
}
1036
}
1037
if !main_meeting_sent
1038
&& let Some(main) = breakout::main_meeting_target(&body)
1039
{
1040
main_meeting_sent = true;
1041
control.send(CallUpdate::BreakoutRoom { main });
1042
}
1043
}
1044
Ok(CallEvent::LocalParticipantUpdate(body)) => {
1045
replier.reply(request_id, 200, "");
1046
let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1047
if let Some(moved) = moved {
1048
timeline.record("breakout", format!("moved to {}", moved.room_name));
1049
control.send(CallUpdate::BreakoutMove(moved));
1050
}
1051
}
1052
Ok(CallEvent::Replacement(body)) => {
1053
replier.reply(request_id, 200, "");
1054
let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1055
if let Some(moved) = invited {
1056
timeline.record("breakout", format!("invited to {}", moved.room_name));
1057
control.send(CallUpdate::BreakoutMove(moved));
1058
}
1059
}
1060
Ok(CallEvent::ContentShareUpdate(body)) => {
1061
replier.reply(request_id, 200, "");
1062
if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) {
1063
control.send(CallUpdate::Whiteboard(Some(share)));
1064
}
1065
}
1066
Ok(CallEvent::ContentShareEnd(_)) => {
1067
replier.reply(request_id, 200, "");
1068
control.send(CallUpdate::Whiteboard(None));
1069
}
1070
Ok(CallEvent::Transfer(event)) => {
1071
replier.reply(request_id, 200, "");
1072
match event {
1073
TransferEvent::Accepted => timeline.record("transfer", "accepted by the target"),
1074
completed if completed.succeeded() => {
1075
control.send(CallUpdate::Notice("Call transferred".into()));
1076
advance(state, CallSignal::LocalLeave, control);
1077
break;
1078
}
1079
_ => control.send(CallUpdate::Notice("The transfer did not go through".into())),
1080
}
828
1081
}
829
1082
Ok(CallEvent::Reactions(events)) => {
830
1083
replier.reply(request_id, 200, "");
@@ -930,10 +1183,15 @@ async fn drive(
930
1183
timeline.record("computer sound not carried over", error.to_string());
931
1184
}
932
1185
offered = pending.offered;
933
if let Some(media) = &offered
934
&& let Err(error) = local_video.set_lines(media.video.clone())
935
{
936
timeline.record("video lines not attached", error.to_string());
1186
if let Some(mid) = direct_video_mid.take() {
1187
video.router().set(&mid, None);
1188
}
1189
if let Some(media) = &offered {
1190
layout = Layout::Conference;
1191
layout_plan = media.plan.clone();
1192
if let Err(error) = local_video.set_lines(media.video.clone()) {
1193
timeline.record("video lines not attached", error.to_string());
1194
}
937
1195
}
938
1196
remote_set = true;
939
1197
}
@@ -953,7 +1211,11 @@ async fn drive(
953
1211
},
954
1212
command = control.recv() => match command {
955
1213
Some(CallCommand::Mute(mute)) => {
956
muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control);
1214
if consent_pending && !mute.target(muted) {
1215
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
1216
} else {
1217
muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control);
1218
}
957
1219
}
958
1220
Some(CallCommand::SelectInput(choice)) => {
959
1221
if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
@@ -973,16 +1235,46 @@ async fn drive(
973
1235
control.send(CallUpdate::Devices(devices::list_devices(&factory)));
974
1236
}
975
1237
Some(CallCommand::SetCamera(on)) => {
1238
let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
976
1239
if !remote_set {
977
1240
control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1241
} else if on && consent_pending {
1242
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
1243
} else if local_hold {
1244
control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
978
1245
} else if on {
979
match local_video.start_camera(&camera_choice) {
1246
let started = start_camera_line(&mut local_video, ¤t.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
1247
match started {
1248
Ok(()) if direct => {
1249
match offer_same_peer(¤t.peer, &layout_plan, layout, false, true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1250
Ok((browser_offer, signaled)) => {
1251
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true) });
1252
same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1253
}
1254
Err(error) => {
1255
timeline.record("camera offer failed", error.to_string());
1256
undo_change(Change::Camera(true), &mut local_video, control);
1257
}
1258
}
1259
}
980
1260
Ok(()) => {
981
1261
control.send(CallUpdate::Camera(true));
982
1262
tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
983
1263
}
984
1264
Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
985
1265
}
1266
} else if direct {
1267
local_video.stop_camera();
1268
match offer_same_peer(¤t.peer, &layout_plan, layout, false, false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1269
Ok((browser_offer, signaled)) => {
1270
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false) });
1271
same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1272
}
1273
Err(error) => {
1274
timeline.record("camera offer failed", error.to_string());
1275
control.send(CallUpdate::Camera(false));
1276
}
1277
}
986
1278
} else {
987
1279
local_video.stop_camera();
988
1280
control.send(CallUpdate::Camera(false));
@@ -1114,12 +1406,81 @@ async fn drive(
1114
1406
caption_deadline = None;
1115
1407
control.send(CallUpdate::Captions(CaptionState::Off));
1116
1408
}
1117
run_caption_steps(&mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), control, timeline).await;
1409
run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), "", &mut bot_pending, control, timeline).await;
1118
1410
if caption_flow.on() {
1119
1411
caption_deadline = None;
1120
1412
}
1121
1413
}
1122
Some(CallCommand::SetBlur(on)) => local_video.set_blur(on),
1414
Some(CallCommand::SetRecording { on, title }) => {
1415
if is_meeting {
1416
recording_title = title;
1417
recording_flow.want(on);
1418
recording_deadline = on.then(|| Instant::now() + RECORDING_START_LIMIT);
1419
run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_title, &mut bot_pending, control, timeline).await;
1420
}
1421
}
1422
Some(CallCommand::ConsentToRecording) => {
1423
match remote.signaling.consent_to_recording(&remote.conversation, &remote.participant, Consent::Give).await {
1424
Ok(_) => {
1425
consent_pending = false;
1426
control.send(CallUpdate::ConsentRequired(false));
1427
}
1428
Err(error) => {
1429
timeline.record("recording consent failed", error.to_string());
1430
control.send(CallUpdate::Notice("Could not confirm the recording notice".into()));
1431
}
1432
}
1433
}
1434
Some(CallCommand::Hold(hold)) => {
1435
if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() {
1436
continue;
1437
}
1438
if hold && local_video.camera_on() {
1439
local_video.stop_camera();
1440
control.send(CallUpdate::Camera(false));
1441
}
1442
let camera = !hold && local_video.camera_on();
1443
match offer_same_peer(¤t.peer, &layout_plan, layout, hold, camera, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1444
Ok((browser_offer, signaled)) => {
1445
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold) });
1446
same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1447
}
1448
Err(error) => {
1449
timeline.record("hold failed", error.to_string());
1450
control.send(CallUpdate::Notice(if hold { "Could not put the call on hold".into() } else { "Could not resume the call".into() }));
1451
}
1452
}
1453
}
1454
Some(CallCommand::Transfer { target, replaces }) => {
1455
let Some(url) = media_links.get("transfer").cloned() else {
1456
control.send(CallUpdate::Notice("This call cannot be transferred".into()));
1457
continue;
1458
};
1459
let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_deref() };
1460
match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {
1461
Ok(()) => control.send(CallUpdate::Notice(format!("Transferring to {}...", target.display_name))),
1462
Err(error) => {
1463
timeline.record("transfer failed", error.to_string());
1464
control.send(CallUpdate::Notice("Could not transfer the call".into()));
1465
}
1466
}
1467
}
1468
Some(CallCommand::OpenWhiteboard { title }) => {
1469
let Some(target) = meeting_target.clone() else {
1470
control.send(CallUpdate::Notice("Whiteboards belong to meetings".into()));
1471
continue;
1472
};
1473
let session = inner.session.clone();
1474
let updates = control.updates();
1475
tokio::spawn(async move {
1476
let update = match whiteboard::fetch_board(&session, &target, &title).await {
1477
Ok(url) => CallUpdate::WhiteboardUrl(url),
1478
Err(_) => CallUpdate::Notice("The whiteboard could not be opened".into()),
1479
};
1480
let _ = updates.send(update);
1481
});
1482
}
1483
Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,
1123
1484
Some(CallCommand::SendReaction(reaction)) => {
1124
1485
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1125
1486
timeline.record("reaction failed", error.to_string());
@@ -1153,6 +1514,12 @@ async fn drive(
1153
1514
timeline.record("captions", "did not start in time");
1154
1515
control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into())));
1155
1516
}
1517
if recording_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
1518
recording_deadline = None;
1519
recording_flow.failed();
1520
timeline.record("recording", "did not start in time");
1521
control.send(CallUpdate::Notice("The recording did not start".into()));
1522
}
1156
1523
if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)
1157
1524
&& let Some(average_ms) = local_video.blur_average_ms()
1158
1525
{
@@ -1216,6 +1583,15 @@ async fn drive(
1216
1583
advance(state, CallSignal::LocalLeave, control);
1217
1584
break;
1218
1585
}
1586
_ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
1587
same_peer_deadline = None;
1588
if let Some(pending) = same_peer.take() {
1589
timeline.record("same-peer offer", "no answer in time");
1590
negotiator.same_peer_offer_failed();
1591
rollback_offer(¤t.peer).await;
1592
undo_change(pending.change, &mut local_video, control);
1593
}
1594
}
1219
1595
_ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => {
1220
1596
timeline.record("no answer", "outgoing call timed out");
1221
1597
live.cancel_leave = true;
@@ -1255,8 +1631,8 @@ async fn start_escalation(
1255
1631
.get("mediaRenegotiation")
1256
1632
.ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
1257
1633
let session = open_peer(factory, grant, &options.relay_host, false)?;
1258
let media = create_offer(&session.peer, factory, track).await?;
1259
let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id);
1634
let media = create_offer(&session.peer, factory, track, Layout::Conference).await?;
1635
let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true);
1260
1636
remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
1261
1637
Ok(NextPeer {
1262
1638
session,
@@ -1272,7 +1648,7 @@ async fn answer_on_new_peer(
1272
1648
teams_offer: &str,
1273
1649
) -> Result<(PeerSession, AnsweredMedia)> {
1274
1650
let session = open_peer(factory, grant, &options.relay_host, false)?;
1275
let answered = answer_offer(&session.peer, Some(track), teams_offer).await?;
1651
let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject).await?;
1276
1652
Ok((session, answered))
1277
1653
}
1278
1654
@@ -1328,6 +1704,7 @@ fn negotiate_video(
1328
1704
}
1329
1705
1330
1706
const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";
1707
const ON_HOLD_NOTICE: &str = "Resume the call first";
1331
1708
1332
1709
async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
1333
1710
match mode {
@@ -1374,6 +1751,127 @@ fn tell_media_descriptions(
1374
1751
});
1375
1752
}
1376
1753
1754
fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
1755
own.is_some_and(|own| own.thread_id == target.thread_id)
1756
}
1757
1758
fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
1759
peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid))
1760
}
1761
1762
fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct_mid: Option<&str>, choice: &DeviceChoice) -> Result<()> {
1763
if !local_video.has_lines() {
1764
let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
1765
let camera = peer_transceiver(peer, mid).ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
1766
if !matches!(camera.direction(), RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly) {
1767
peer.add_track(MediaStreamTrack::Video(local_video.camera_track()), &[CAMERA_STREAM])
1768
.map_err(|error| Error::Webrtc(error.to_string()))?;
1769
}
1770
local_video.set_lines(VideoLines { camera, share: None })?;
1771
}
1772
local_video.start_camera(choice)
1773
}
1774
1775
#[allow(clippy::too_many_arguments)]
1776
async fn offer_same_peer(
1777
peer: &PeerConnection,
1778
plan: &OfferPlan,
1779
layout: Layout,
1780
hold: bool,
1781
camera: bool,
1782
remote: &RemoteCall,
1783
links: &CallbackLinks,
1784
media_leg_id: &str,
1785
media_links: &BTreeMap<String, String>,
1786
negotiator: &mut MediaNegotiator,
1787
) -> Result<(String, SignaledOffer)> {
1788
let url = media_links
1789
.get("mediaRenegotiation")
1790
.cloned()
1791
.ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
1792
if !negotiator.begin_same_peer_offer() {
1793
return Err(Error::Signaling("another media negotiation is running".into()));
1794
}
1795
let offered = build_same_peer_offer(peer, plan, layout, hold, camera).await;
1796
let (text, signaled) = match offered {
1797
Ok(offered) => offered,
1798
Err(error) => {
1799
negotiator.same_peer_offer_failed();
1800
return Err(error);
1801
}
1802
};
1803
let modalities = accepted_modalities(layout == Layout::OneToOne && camera && !hold);
1804
let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false);
1805
if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
1806
negotiator.same_peer_offer_failed();
1807
rollback_offer(peer).await;
1808
return Err(error);
1809
}
1810
Ok((text, signaled))
1811
}
1812
1813
async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool) -> Result<(String, SignaledOffer)> {
1814
let offer = peer
1815
.create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
1816
.await
1817
.map_err(|error| Error::Webrtc(error.to_string()))?;
1818
let text = directions_for(layout, hold, camera, &offer.to_string());
1819
let description = SessionDescription::parse(&text, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;
1820
peer.set_local_description(description)
1821
.await
1822
.map_err(|error| Error::Webrtc(error.to_string()))?;
1823
let mut numbers = random_u32;
1824
let signaled = to_teams_offer(&text, plan, &mut numbers)?;
1825
Ok((text, signaled))
1826
}
1827
1828
async fn rollback_offer(peer: &PeerConnection) {
1829
if let Ok(rollback) = SessionDescription::parse("", SdpType::Rollback) {
1830
let _ = peer.set_local_description(rollback).await;
1831
}
1832
}
1833
1834
fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {
1835
match change {
1836
Change::Camera(true) => {
1837
local_video.stop_camera();
1838
control.send(CallUpdate::Camera(false));
1839
}
1840
Change::Camera(false) => control.send(CallUpdate::Camera(false)),
1841
Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())),
1842
}
1843
}
1844
1845
fn withhold_media(
1846
muted: &mut bool,
1847
audio: &AudioSetup,
1848
share_audio: Option<&ShareAudio>,
1849
remote: &RemoteCall,
1850
local_video: &mut LocalVideo,
1851
control: &CallControl,
1852
) {
1853
*muted = apply_mute(MuteCommand::Mute, *muted, audio, share_audio, remote, control);
1854
if local_video.camera_on() {
1855
local_video.stop_camera();
1856
control.send(CallUpdate::Camera(false));
1857
}
1858
}
1859
1860
async fn apply_background(choice: BackgroundChoice, local_video: &LocalVideo, control: &CallControl, timeline: &Timeline) {
1861
match choice {
1862
BackgroundChoice::None => local_video.set_background(false, None),
1863
BackgroundChoice::Blur => local_video.set_background(true, None),
1864
BackgroundChoice::Image(path) => match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
1865
Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
1866
Ok(Err(error)) => {
1867
timeline.record("background image failed", error.to_string());
1868
control.send(CallUpdate::Notice("That background image could not be used".into()));
1869
}
1870
Err(_) => {}
1871
},
1872
}
1873
}
1874
1377
1875
fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
1378
1876
let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());
1379
1877
Target { mri, display_name }
@@ -1394,53 +1892,105 @@ fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
1394
1892
entry
1395
1893
}
1396
1894
1895
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1896
enum BotJob {
1897
Captions,
1898
Recording,
1899
}
1900
1397
1901
#[allow(clippy::too_many_arguments)]
1398
async fn run_caption_steps(
1902
async fn run_bot_steps(
1903
job: BotJob,
1399
1904
flow: &mut CaptionFlow,
1400
1905
roster: &Roster,
1401
1906
remote: &RemoteCall,
1402
1907
links: &CallbackLinks,
1403
1908
meeting_chat: Option<&str>,
1909
title: &str,
1910
bot_pending: &mut bool,
1404
1911
control: &CallControl,
1405
1912
timeline: &Timeline,
1406
1913
) {
1914
let is_active: fn(&crate::roster::CaptionBot) -> bool = match job {
1915
BotJob::Captions => |bot| bot.active,
1916
BotJob::Recording => |bot| bot.recording,
1917
};
1407
1918
let fail = |flow: &mut CaptionFlow, reason: &str| {
1408
1919
flow.failed();
1409
control.send(CallUpdate::Captions(CaptionState::Failed(reason.to_owned())));
1920
control.send(match job {
1921
BotJob::Captions => CallUpdate::Captions(CaptionState::Failed(reason.to_owned())),
1922
BotJob::Recording => CallUpdate::Notice(reason.to_owned()),
1923
});
1924
};
1925
let (join_failure, start_failure) = match job {
1926
BotJob::Captions => ("The captions service could not join", "Captions could not start"),
1927
BotJob::Recording => ("The recording service could not join", "The recording could not start"),
1410
1928
};
1411
1929
loop {
1412
match flow.next(roster.caption_bot()) {
1930
match flow.next_for(roster.caption_bot(), is_active) {
1413
1931
CaptionStep::Wait => return,
1414
1932
CaptionStep::AddBot => {
1933
if *bot_pending {
1934
continue;
1935
}
1415
1936
let Some(thread) = meeting_chat else {
1416
return fail(flow, "This meeting has no chat for captions");
1937
return fail(flow, "This meeting has no chat for the captions and the recording");
1417
1938
};
1418
if let Err(error) = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links).await {
1419
timeline.record("caption bot failed", error.to_string());
1420
return fail(flow, "The captions service could not join");
1939
*bot_pending = true;
1940
let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links).await;
1941
if job == BotJob::Recording {
1942
report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline);
1943
}
1944
if let Err(error) = added {
1945
timeline.record("bot invitation failed", error.to_string());
1946
*bot_pending = false;
1947
return fail(flow, join_failure);
1421
1948
}
1422
1949
}
1423
1950
CaptionStep::Start => {
1424
1951
let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return };
1425
if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {
1426
timeline.record("caption start failed", error.to_string());
1427
return fail(flow, "Captions could not start");
1428
}
1429
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {
1430
timeline.record("caption preference failed", error.to_string());
1952
match job {
1953
BotJob::Captions => {
1954
if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {
1955
timeline.record("caption start failed", error.to_string());
1956
return fail(flow, start_failure);
1957
}
1958
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {
1959
timeline.record("caption preference failed", error.to_string());
1960
}
1961
}
1962
BotJob::Recording => {
1963
let started = remote.signaling.recording_command(&url, BotAction::Start, &remote.participant, title).await;
1964
let failed = started.is_err();
1965
report_organizer_result(started, "recording start", start_failure, control, timeline);
1966
if failed {
1967
return fail(flow, start_failure);
1968
}
1969
}
1431
1970
}
1432
1971
}
1433
1972
CaptionStep::Stop => {
1434
if let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone())
1435
&& let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await
1436
{
1437
timeline.record("caption stop failed", error.to_string());
1973
let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { continue };
1974
match job {
1975
BotJob::Captions => {
1976
if let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await {
1977
timeline.record("caption stop failed", error.to_string());
1978
}
1979
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {
1980
timeline.record("caption preference failed", error.to_string());
1981
}
1982
}
1983
BotJob::Recording => {
1984
let stopped = remote.signaling.recording_command(&url, BotAction::Stop, &remote.participant, title).await;
1985
report_organizer_result(stopped, "recording stop", "The recording could not be stopped", control, timeline);
1986
}
1438
1987
}
1439
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {
1440
timeline.record("caption preference failed", error.to_string());
1988
}
1989
CaptionStep::ReportOn => {
1990
if job == BotJob::Captions {
1991
control.send(CallUpdate::Captions(CaptionState::On));
1441
1992
}
1442
1993
}
1443
CaptionStep::ReportOn => control.send(CallUpdate::Captions(CaptionState::On)),
1444
1994
}
1445
1995
}
1446
1996
}
@@ -1773,6 +2323,40 @@ mod tests {
1773
2323
assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54));
1774
2324
}
1775
2325
2326
const BROWSER_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:1\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:2\r\na=recvonly\r\n";
2327
2328
fn directions(sdp: &str) -> Vec<String> {
2329
crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()
2330
}
2331
2332
#[test]
2333
fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
2334
assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
2335
assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
2336
}
2337
2338
#[test]
2339
fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
2340
for layout in [Layout::OneToOne, Layout::Conference] {
2341
assert_eq!(directions(&directions_for(layout, true, true, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
2342
}
2343
assert_eq!(directions_for(Layout::Conference, false, true, BROWSER_OFFER), BROWSER_OFFER);
2344
}
2345
2346
#[test]
2347
fn a_move_into_the_meeting_you_are_already_in_is_ignored() {
2348
let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None };
2349
assert!(is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_a@thread.v2")));
2350
assert!(!is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_b@thread.v2")));
2351
assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2")));
2352
}
2353
2354
#[test]
2355
fn a_video_call_names_the_video_modality_only_when_the_camera_sends() {
2356
assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]);
2357
assert_eq!(accepted_modalities(true), vec!["Audio".to_owned(), "Video".to_owned()]);
2358
}
2359
1776
2360
#[test]
1777
2361
fn specs_map_to_invitation_targets() {
1778
2362
assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
@@ -9,7 +9,7 @@ use futures_util::StreamExt;9
use libwebrtc::audio_stream::native::NativeAudioStream;9
use libwebrtc::audio_stream::native::NativeAudioStream;10
use libwebrtc::data_channel::{DataChannel, DataChannelInit};10
use libwebrtc::data_channel::{DataChannel, DataChannelInit};11
use libwebrtc::prelude::*;11
use libwebrtc::prelude::*;12
use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};12
use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit};13
use libwebrtc::session_description::{SdpType, SessionDescription};13
use libwebrtc::session_description::{SdpType, SessionDescription};14
use libwebrtc::stats::RtcStats;14
use libwebrtc::stats::RtcStats;15
use session::Session;15
use session::Session;@@ -19,6 +19,8 @@ use tokio::time::{Instant, interval, sleep_until, timeout};19
19
20
use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};20
use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};21
use crate::audio_io::{AudioMode, AudioSetup};21
use crate::audio_io::{AudioMode, AudioSetup};22
use crate::background::{BackgroundChoice, BackgroundPicture};23
use crate::breakout::{self, RoomWatcher};22
use crate::captions::{CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep, BotAction, parse_caption_message};24
use crate::captions::{CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep, BotAction, parse_caption_message};23
use crate::data_channel::Depacketizer;25
use crate::data_channel::Depacketizer;24
use crate::control::{CallCommand, CallControl, CallUpdate, Progress};26
use crate::control::{CallCommand, CallControl, CallUpdate, Progress};@@ -26,21 +28,27 @@ use crate::devices::{self, DeviceChoice};26
use crate::end::EndKind;28
use crate::end::EndKind;27
use crate::engine::{CallEngine, EngineConfig, Inner};29
use crate::engine::{CallEngine, EngineConfig, Inner};28
use crate::error::{Error, Result};30
use crate::error::{Error, Result};31
use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, rewrite_directions};29
use crate::mute::{MuteCommand, MuteEffect};32
use crate::mute::{MuteCommand, MuteEffect};30
use crate::push::CallNotification;33
use crate::push::CallNotification;31
use crate::share_audio::ShareAudio;34
use crate::share_audio::ShareAudio;32
use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};35
use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};33
use crate::renegotiation::{MediaAction, MediaNegotiator};36
use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath};34
use crate::organizer::Target;37
use crate::organizer::Target;38
use crate::recording::{Consent, RecordingStatus};35
use crate::roster::Roster;39
use crate::roster::Roster;36
use crate::sdp::{RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};40
use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};37
use crate::signaling::{41
use crate::signaling::{38
Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling,42
Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling,39
TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,43
TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,40
};44
};41
use crate::state::{CallSignal, CallState};45
use crate::state::{CallSignal, CallState};42
use crate::timeline::{Timeline, TimelineEntry};46
use crate::timeline::{Timeline, TimelineEntry};43
use crate::video_layout::{MediaDescription, SlotTable, VideoLines, VideoRouter, add_video_lines, offer_plan};47
use crate::transfer::{TransferEvent, TransferTarget};48
use crate::video_frame::VideoKey;49
use crate::video_layout::{50
CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, offer_plan, one_to_one_plan,51
};44
use crate::video_send::{LocalVideo, VideoMode};52
use crate::video_send::{LocalVideo, VideoMode};45
use crate::camera::{CameraDevice, list_cameras};53
use crate::camera::{CameraDevice, list_cameras};46
use crate::screen::{ShareKind, ShareSource, list_share_sources};54
use crate::screen::{ShareKind, ShareSource, list_share_sources};@@ -48,6 +56,7 @@ use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoR48
use crate::trouter_events::{56
use crate::trouter_events::{49
CallEnd, CallEvent, CallbackLinks, ProgressStatus, acceptance_acknowledgement, classify, decode_body,57
CallEnd, CallEvent, CallbackLinks, ProgressStatus, acceptance_acknowledgement, classify, decode_body,50
};58
};59
use crate::whiteboard;51
60
52
const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);61
const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);53
const STATS_PERIOD: Duration = Duration::from_millis(200);62
const STATS_PERIOD: Duration = Duration::from_millis(200);@@ -64,6 +73,10 @@ pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL";64
const CAPTION_START_LIMIT: Duration = Duration::from_secs(40);73
const CAPTION_START_LIMIT: Duration = Duration::from_secs(40);65
const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;74
const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;66
const BOT_PREFIX: &str = "28:";75
const BOT_PREFIX: &str = "28:";76
const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);77
const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(15);78
const CAMERA_STREAM: &str = "camera";79
const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";67
80
68
#[derive(Debug, Clone)]81
#[derive(Debug, Clone)]69
pub struct CallOptions {82
pub struct CallOptions {@@ -83,6 +96,7 @@ pub struct CallOptions {83
pub sdp_dump_dir: Option<PathBuf>,96
pub sdp_dump_dir: Option<PathBuf>,84
pub trace: bool,97
pub trace: bool,85
pub data_channel: bool,98
pub data_channel: bool,99
pub concurrent: bool,86
}100
}87
101
88
impl Default for CallOptions {102
impl Default for CallOptions {@@ -104,6 +118,7 @@ impl Default for CallOptions {104
sdp_dump_dir: None,118
sdp_dump_dir: None,105
trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(),119
trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(),106
data_channel: data_channel_from_env(),120
data_channel: data_channel_from_env(),121
concurrent: false,107
}122
}108
}123
}109
}124
}@@ -184,6 +199,7 @@ impl CallSpec {184
}199
}185
200
186
pub(crate) struct IncomingCall {201
pub(crate) struct IncomingCall {202
pub accept: AcceptMode,187
pub notification: CallNotification,203
pub notification: CallNotification,188
pub attached: Attached,204
pub attached: Attached,189
pub links: CallbackLinks,205
pub links: CallbackLinks,@@ -235,6 +251,39 @@ struct OfferedMedia {235
browser_offer: String,251
browser_offer: String,236
signaled: SignaledOffer,252
signaled: SignaledOffer,237
video: VideoLines,253
video: VideoLines,254
plan: OfferPlan,255
modalities: Vec<String>,256
}257
258
#[derive(Debug, Clone, Copy, PartialEq, Eq)]259
enum Layout {260
Conference,261
OneToOne,262
}263
264
#[derive(Debug, Clone, Copy, PartialEq, Eq)]265
pub enum AcceptMode {266
Audio,267
Video,268
}269
270
#[derive(Clone, Copy)]271
enum AnswerVideo<'a> {272
Reject,273
Receive,274
Send(&'a RtcVideoTrack),275
}276
277
#[derive(Debug, Clone, Copy, PartialEq, Eq)]278
enum Change {279
Hold(bool),280
Camera(bool),281
}282
283
struct SamePeerOffer {284
browser_offer: String,285
signaled: SignaledOffer,286
change: Change,238
}287
}239
288
240
struct NextPeer {289
struct NextPeer {@@ -242,11 +291,6 @@ struct NextPeer {242
offered: Option<OfferedMedia>,291
offered: Option<OfferedMedia>,243
}292
}244
293
245
struct AnsweredMedia {246
remote: RemoteOffer,247
answer_sdp: String,248
}249
250
#[derive(Clone)]294
#[derive(Clone)]251
struct RemoteCall {295
struct RemoteCall {252
signaling: Arc<Signaling>,296
signaling: Arc<Signaling>,@@ -306,7 +350,7 @@ pub async fn run_test_call(306
impl CallEngine {350
impl CallEngine {307
pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {351
pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {308
let inner = self.inner.as_ref();352
let inner = self.inner.as_ref();309
let _one_call_at_a_time = inner.gate.lock().await;353
let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };310
let timeline = Timeline::new(options.trace);354
let timeline = Timeline::new(options.trace);311
let mut report = CallReport::default();355
let mut report = CallReport::default();312
let mut state = CallState::Idle;356
let mut state = CallState::Idle;@@ -389,7 +433,23 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv389
Ok(channel)433
Ok(channel)390
}434
}391
435
392
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack) -> Result<OfferedMedia> {436
fn one_to_one_directions(camera: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> {437
move |line| match (line.kind, line.mid) {438
("video", CAMERA_MID) => Some(if camera { "sendrecv" } else { INACTIVE }),439
("video", ONE_TO_ONE_SHARE_MID) => Some(INACTIVE),440
_ => None,441
}442
}443
444
fn directions_for(layout: Layout, hold: bool, camera: bool, text: &str) -> String {445
match (hold, layout) {446
(true, _) => rewrite_directions(text, |_| Some(INACTIVE)),447
(false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera)),448
(false, Layout::Conference) => text.to_owned(),449
}450
}451
452
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout) -> Result<OfferedMedia> {393
let transceiver_init = RtpTransceiverInit {453
let transceiver_init = RtpTransceiverInit {394
direction: RtpTransceiverDirection::SendRecv,454
direction: RtpTransceiverDirection::SendRecv,395
stream_ids: vec![MIC_STREAM.into()],455
stream_ids: vec![MIC_STREAM.into()],@@ -397,7 +457,10 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr397
};457
};398
peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init)458
peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init)399
.map_err(|error| Error::Webrtc(error.to_string()))?;459
.map_err(|error| Error::Webrtc(error.to_string()))?;400
let video = add_video_lines(peer, factory)?;460
let (video, plan) = match layout {461
Layout::Conference => (add_video_lines(peer, factory)?, offer_plan()),462
Layout::OneToOne => (add_one_to_one_lines(peer, factory)?, one_to_one_plan()),463
};401
let offer = peer464
let offer = peer402
.create_offer(OfferOptions {465
.create_offer(OfferOptions {403
offer_to_receive_audio: true,466
offer_to_receive_audio: true,@@ -406,20 +469,31 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr406
})469
})407
.await470
.await408
.map_err(|error| Error::Webrtc(error.to_string()))?;471
.map_err(|error| Error::Webrtc(error.to_string()))?;409
peer.set_local_description(offer.clone())472
let browser_offer = directions_for(layout, false, false, &offer.to_string());473
let description = SessionDescription::parse(&browser_offer, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;474
peer.set_local_description(description)410
.await475
.await411
.map_err(|error| Error::Webrtc(error.to_string()))?;476
.map_err(|error| Error::Webrtc(error.to_string()))?;412
let browser_offer = offer.to_string();413
let mut numbers = random_u32;477
let mut numbers = random_u32;414
let signaled = to_teams_offer(&browser_offer, &offer_plan(), &mut numbers)?;478
let signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;415
Ok(OfferedMedia { browser_offer, signaled, video })479
Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })480
}481
482
struct AnsweredMedia {483
remote: RemoteOffer,484
answer_sdp: String,485
camera_mid: Option<String>,486
}487
488
fn main_video_mid(remote: &RemoteOffer) -> Option<String> {489
remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())416
}490
}417
491
418
/// Video lines of a Teams offer are stopped so the answer rejects them; audio is all this client does.419
async fn answer_offer(492
async fn answer_offer(420
peer: &PeerConnection,493
peer: &PeerConnection,421
track: Option<&RtcAudioTrack>,494
track: Option<&RtcAudioTrack>,422
teams_offer: &str,495
teams_offer: &str,496
video: AnswerVideo<'_>,423
) -> Result<AnsweredMedia> {497
) -> Result<AnsweredMedia> {424
let remote = from_teams_offer(teams_offer)?;498
let remote = from_teams_offer(teams_offer)?;425
let description =499
let description =@@ -427,8 +501,10 @@ async fn answer_offer(427
peer.set_remote_description(description)501
peer.set_remote_description(description)428
.await502
.await429
.map_err(|error| Error::Webrtc(error.to_string()))?;503
.map_err(|error| Error::Webrtc(error.to_string()))?;504
let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));430
for transceiver in peer.transceivers() {505
for transceiver in peer.transceivers() {431
if matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_))) {506
let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));507
if is_video && transceiver.mid() != camera_mid {432
let _ = transceiver.stop();508
let _ = transceiver.stop();433
}509
}434
}510
}@@ -436,6 +512,10 @@ async fn answer_offer(436
peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])512
peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])437
.map_err(|error| Error::Webrtc(error.to_string()))?;513
.map_err(|error| Error::Webrtc(error.to_string()))?;438
}514
}515
if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {516
peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM])517
.map_err(|error| Error::Webrtc(error.to_string()))?;518
}439
let answer = peer519
let answer = peer440
.create_answer(AnswerOptions::default())520
.create_answer(AnswerOptions::default())441
.await521
.await@@ -448,6 +528,7 @@ async fn answer_offer(448
Ok(AnsweredMedia {528
Ok(AnsweredMedia {449
remote,529
remote,450
answer_sdp: signaled.sdp,530
answer_sdp: signaled.sdp,531
camera_mid,451
})532
})452
}533
}453
534
@@ -480,8 +561,10 @@ async fn drive(480
Plan::Outgoing(spec) => (Some(spec), None),561
Plan::Outgoing(spec) => (Some(spec), None),481
Plan::Incoming(incoming) => (None, Some(*incoming)),562
Plan::Incoming(incoming) => (None, Some(*incoming)),482
};563
};564
let accept_mode = incoming.as_ref().map_or(AcceptMode::Audio, |incoming| incoming.accept);483
let (links, participant, mut callbacks, incoming_media) = match incoming {565
let (links, participant, mut callbacks, incoming_media) = match incoming {484
Some(IncomingCall {566
Some(IncomingCall {567
accept: _,485
notification,568
notification,486
attached,569
attached,487
links,570
links,@@ -544,10 +627,30 @@ async fn drive(544
let mut outgoing_deadline: Option<Instant> = None;627
let mut outgoing_deadline: Option<Instant> = None;545
let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);628
let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);546
let is_echo = matches!(spec, Some(CallSpec::Echo));629
let is_echo = matches!(spec, Some(CallSpec::Echo));630
let meeting_target = match &spec {631
Some(CallSpec::Meeting(target)) => Some(target.clone()),632
_ => None,633
};634
let mut layout = match &spec {635
Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne,636
_ => Layout::Conference,637
};638
let peer_mri = match &spec {639
Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Some(callees[0].mri.clone()),640
_ => incoming_media.as_ref().map(|(notification, _)| notification.caller.mri.clone()),641
};642
let mut layout_plan: OfferPlan;643
let mut direct_video_mid: Option<String> = None;644
let mut sending_camera = false;645
let mut media_links: BTreeMap<String, String> = BTreeMap::new();547
646
548
let conversation = match (spec, incoming_media) {647
let conversation = match (spec, incoming_media) {549
(Some(spec), None) => {648
(Some(spec), None) => {550
let media = create_offer(¤t.peer, &factory, &track).await?;649
let media = create_offer(¤t.peer, &factory, &track, layout).await?;650
layout_plan = media.plan.clone();651
if layout == Layout::OneToOne {652
direct_video_mid = Some(CAMERA_MID.to_owned());653
}551
timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));654
timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));552
dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);655
dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);553
dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);656
dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);@@ -558,6 +661,7 @@ async fn drive(558
media_leg_id: &media_leg_id,661
media_leg_id: &media_leg_id,559
callbacks: &links,662
callbacks: &links,560
target: &target,663
target: &target,664
modalities: &media.modalities,561
};665
};562
let conversation = match &target {666
let conversation = match &target {563
InviteTarget::Meeting(meeting) => {667
InviteTarget::Meeting(meeting) => {@@ -583,7 +687,7 @@ async fn drive(583
});687
});584
conversation688
conversation585
}689
}586
(None, Some((_notification, attached))) => {690
(None, Some((notification, attached))) => {587
let teams_offer = attached691
let teams_offer = attached588
.offer_sdp692
.offer_sdp589
.clone()693
.clone()@@ -597,7 +701,17 @@ async fn drive(597
conversation: conversation.clone(),701
conversation: conversation.clone(),598
participant: participant.clone(),702
participant: participant.clone(),599
});703
});600
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer).await?;704
let one_to_one = !attached.from_mixer && !notification.is_multi_party;705
layout = if one_to_one { Layout::OneToOne } else { Layout::Conference };706
let camera_track = local_video.camera_track();707
let video_answer = match accept_mode {708
_ if !one_to_one => AnswerVideo::Reject,709
AcceptMode::Video if local_video.is_available() => AnswerVideo::Send(&camera_track),710
_ => AnswerVideo::Receive,711
};712
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer, video_answer).await?;713
layout_plan = answered.remote.plan();714
direct_video_mid = answered.camera_mid.clone();601
timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));715
timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));602
dump_sdp(options, "3-teams-offer.sdp", &teams_offer);716
dump_sdp(options, "3-teams-offer.sdp", &teams_offer);603
dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);717
dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);@@ -605,7 +719,7 @@ async fn drive(605
.links719
.links606
.get("acceptance")720
.get("acceptance")607
.ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;721
.ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;608
let modalities = vec!["Audio".to_owned()];722
let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some());609
signaling723
signaling610
.accept(724
.accept(611
acceptance_url,725
acceptance_url,@@ -620,6 +734,18 @@ async fn drive(620
.await?;734
.await?;621
negotiator.answered_incoming(attached.from_mixer);735
negotiator.answered_incoming(attached.from_mixer);622
remote_set = true;736
remote_set = true;737
media_links.extend(attached.links.clone());738
if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {739
let camera = peer_transceiver(¤t.peer, mid);740
match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) {741
Some(Ok(())) => match local_video.start_camera(&camera_choice) {742
Ok(()) => sending_camera = true,743
Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),744
},745
Some(Err(error)) => timeline.record("video lines not attached", error.to_string()),746
None => timeline.record("video lines not attached", "no transceiver for the camera line"),747
}748
}623
keep_alive_link = attached.links.get("callLeg").cloned();749
keep_alive_link = attached.links.get("callLeg").cloned();624
keep_alive_at = Some(Instant::now() + keep_alive_period(None));750
keep_alive_at = Some(Instant::now() + keep_alive_period(None));625
conversation751
conversation@@ -657,7 +783,12 @@ async fn drive(657
let mut second = 0u32;783
let mut second = 0u32;658
let echo_thread = thread_id;784
let echo_thread = thread_id;659
let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());785
let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());660
let mut media_links: BTreeMap<String, String> = BTreeMap::new();786
if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) {787
video.router().set(mid, Some(VideoKey::Person(mri.clone())));788
}789
if sending_camera {790
control.send(CallUpdate::Camera(true));791
}661
let mut share_audio: Option<ShareAudio> = None;792
let mut share_audio: Option<ShareAudio> = None;662
let mut share_sound_wanted = false;793
let mut share_sound_wanted = false;663
let mut remote_audio: Option<RtcAudioTrack> = None;794
let mut remote_audio: Option<RtcAudioTrack> = None;@@ -665,6 +796,18 @@ async fn drive(665
let mut depacketizer = Depacketizer::default();796
let mut depacketizer = Depacketizer::default();666
let mut caption_flow = CaptionFlow::default();797
let mut caption_flow = CaptionFlow::default();667
let mut caption_deadline: Option<Instant> = None;798
let mut caption_deadline: Option<Instant> = None;799
let mut recording_flow = CaptionFlow::default();800
let mut recording_deadline: Option<Instant> = None;801
let mut recording_title = String::new();802
let mut recording_status = RecordingStatus::default();803
let mut bot_pending = false;804
let mut consent_pending = false;805
let mut room_watcher = RoomWatcher::default();806
let mut main_meeting_sent = false;807
let mut local_hold = false;808
let mut remote_hold = false;809
let mut same_peer: Option<SamePeerOffer> = None;810
let mut same_peer_deadline: Option<Instant> = None;668
let mut meeting_chat = conversation.chat_thread.clone();811
let mut meeting_chat = conversation.chat_thread.clone();669
if let Some(thread) = &meeting_chat {812
if let Some(thread) = &meeting_chat {670
control.send(CallUpdate::MeetingChat(thread.clone()));813
control.send(CallUpdate::MeetingChat(thread.clone()));@@ -688,7 +831,12 @@ async fn drive(688
.inspect_err(|error| timeline.record("answer rejected", error.to_string()))?;831
.inspect_err(|error| timeline.record("answer rejected", error.to_string()))?;689
remote_set = true;832
remote_set = true;690
media_links.extend(acceptance.links.clone());833
media_links.extend(acceptance.links.clone());691
negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster);834
if layout == Layout::Conference {835
negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster);836
}837
if let Some(link) = acceptance.links.get("replacement") {838
control.send(CallUpdate::ReplacementLink(link.clone()));839
}692
outgoing_deadline = None;840
outgoing_deadline = None;693
let directions: Vec<String> = current841
let directions: Vec<String> = current694
.peer842
.peer@@ -732,7 +880,32 @@ async fn drive(732
}880
}733
Ok(CallEvent::MediaAnswer(answer)) => {881
Ok(CallEvent::MediaAnswer(answer)) => {734
replier.reply(request_id, 200, "");882
replier.reply(request_id, 200, "");735
if negotiator.on_media_answer() == MediaAction::ApplyOnNewPeer {883
let action = negotiator.on_media_answer();884
if action == MediaAction::ApplyOnSamePeer885
&& let Some(pending) = same_peer.take()886
{887
same_peer_deadline = None;888
let applied = apply_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await;889
match applied {890
Ok(()) => {891
if let Some(url) = answer.links.get("mediaAcknowledgement") {892
let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;893
}894
match pending.change {895
Change::Hold(hold) => {896
local_hold = hold;897
control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));898
}899
Change::Camera(on) => control.send(CallUpdate::Camera(on)),900
}901
}902
Err(error) => {903
timeline.record("same-peer answer rejected", error.to_string());904
undo_change(pending.change, &mut local_video, control);905
}906
}907
}908
if action == MediaAction::ApplyOnNewPeer {736
let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) {909
let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) {737
Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await,910
Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await,738
None => Err(Error::Webrtc("no pending peer connection for the answer".into())),911
None => Err(Error::Webrtc("no pending peer connection for the answer".into())),@@ -771,8 +944,17 @@ async fn drive(771
}944
}772
}945
}773
MediaAction::AnswerOnSamePeer => {946
MediaAction::AnswerOnSamePeer => {774
match answer_offer(¤t.peer, None, &renegotiation.sdp).await {947
let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };775
Ok(answered) => send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await,948
match answer_offer(¤t.peer, None, &renegotiation.sdp, video_answer).await {949
Ok(answered) => {950
let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;951
let held = is_hold(&renegotiation.sdp).unwrap_or(false);952
if held != remote_hold {953
remote_hold = held;954
control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));955
}956
sent957
}776
Err(error) => Err(error),958
Err(error) => Err(error),777
}959
}778
}960
}@@ -800,16 +982,29 @@ async fn drive(800
lobby = in_lobby;982
lobby = in_lobby;801
control.send(CallUpdate::Lobby(lobby));983
control.send(CallUpdate::Lobby(lobby));802
}984
}985
if roster.caption_bot().is_some() {986
bot_pending = false;987
}803
if caption_flow.wanted() {988
if caption_flow.wanted() {804
run_caption_steps(&mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), control, timeline).await;989
run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), "", &mut bot_pending, control, timeline).await;805
if caption_flow.on() {990
if caption_flow.on() {806
caption_deadline = None;991
caption_deadline = None;807
}992
}808
}993
}994
if recording_flow.wanted() {995
run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_title, &mut bot_pending, control, timeline).await;996
}809
}997
}810
}998
}811
Ok(CallEvent::AddParticipantFailure(_)) => {999
Ok(CallEvent::AddParticipantFailure(_)) => {812
replier.reply(request_id, 200, "");1000
replier.reply(request_id, 200, "");1001
bot_pending = false;1002
if recording_flow.wanted() && roster.caption_bot().is_none() {1003
timeline.record("recorder bot failed", "addParticipantFailure");1004
recording_flow.failed();1005
recording_deadline = None;1006
control.send(CallUpdate::Notice("The recording service could not join".into()));1007
}813
if caption_flow.wanted() && roster.caption_bot().is_none() {1008
if caption_flow.wanted() && roster.caption_bot().is_none() {814
timeline.record("caption bot failed", "addParticipantFailure");1009
timeline.record("caption bot failed", "addParticipantFailure");815
caption_flow.failed();1010
caption_flow.failed();@@ -825,6 +1020,64 @@ async fn drive(825
control.send(CallUpdate::MeetingChat(thread.clone()));1020
control.send(CallUpdate::MeetingChat(thread.clone()));826
meeting_chat = Some(thread);1021
meeting_chat = Some(thread);827
}1022
}1023
let change = recording_status.apply(&body);1024
if let Some(on) = change.recording {1025
control.send(CallUpdate::Recording(on));1026
if on {1027
recording_deadline = None;1028
}1029
}1030
if let Some(required) = change.consent_required {1031
consent_pending = required;1032
control.send(CallUpdate::ConsentRequired(required));1033
if required {1034
withhold_media(&mut muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, &mut local_video, control);1035
}1036
}1037
if !main_meeting_sent1038
&& let Some(main) = breakout::main_meeting_target(&body)1039
{1040
main_meeting_sent = true;1041
control.send(CallUpdate::BreakoutRoom { main });1042
}1043
}1044
Ok(CallEvent::LocalParticipantUpdate(body)) => {1045
replier.reply(request_id, 200, "");1046
let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));1047
if let Some(moved) = moved {1048
timeline.record("breakout", format!("moved to {}", moved.room_name));1049
control.send(CallUpdate::BreakoutMove(moved));1050
}1051
}1052
Ok(CallEvent::Replacement(body)) => {1053
replier.reply(request_id, 200, "");1054
let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));1055
if let Some(moved) = invited {1056
timeline.record("breakout", format!("invited to {}", moved.room_name));1057
control.send(CallUpdate::BreakoutMove(moved));1058
}1059
}1060
Ok(CallEvent::ContentShareUpdate(body)) => {1061
replier.reply(request_id, 200, "");1062
if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) {1063
control.send(CallUpdate::Whiteboard(Some(share)));1064
}1065
}1066
Ok(CallEvent::ContentShareEnd(_)) => {1067
replier.reply(request_id, 200, "");1068
control.send(CallUpdate::Whiteboard(None));1069
}1070
Ok(CallEvent::Transfer(event)) => {1071
replier.reply(request_id, 200, "");1072
match event {1073
TransferEvent::Accepted => timeline.record("transfer", "accepted by the target"),1074
completed if completed.succeeded() => {1075
control.send(CallUpdate::Notice("Call transferred".into()));1076
advance(state, CallSignal::LocalLeave, control);1077
break;1078
}1079
_ => control.send(CallUpdate::Notice("The transfer did not go through".into())),1080
}828
}1081
}829
Ok(CallEvent::Reactions(events)) => {1082
Ok(CallEvent::Reactions(events)) => {830
replier.reply(request_id, 200, "");1083
replier.reply(request_id, 200, "");@@ -930,10 +1183,15 @@ async fn drive(930
timeline.record("computer sound not carried over", error.to_string());1183
timeline.record("computer sound not carried over", error.to_string());931
}1184
}932
offered = pending.offered;1185
offered = pending.offered;933
if let Some(media) = &offered1186
if let Some(mid) = direct_video_mid.take() {934
&& let Err(error) = local_video.set_lines(media.video.clone())1187
video.router().set(&mid, None);935
{1188
}936
timeline.record("video lines not attached", error.to_string());1189
if let Some(media) = &offered {1190
layout = Layout::Conference;1191
layout_plan = media.plan.clone();1192
if let Err(error) = local_video.set_lines(media.video.clone()) {1193
timeline.record("video lines not attached", error.to_string());1194
}937
}1195
}938
remote_set = true;1196
remote_set = true;939
}1197
}@@ -953,7 +1211,11 @@ async fn drive(953
},1211
},954
command = control.recv() => match command {1212
command = control.recv() => match command {955
Some(CallCommand::Mute(mute)) => {1213
Some(CallCommand::Mute(mute)) => {956
muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control);1214
if consent_pending && !mute.target(muted) {1215
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));1216
} else {1217
muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control);1218
}957
}1219
}958
Some(CallCommand::SelectInput(choice)) => {1220
Some(CallCommand::SelectInput(choice)) => {959
if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {1221
if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {@@ -973,16 +1235,46 @@ async fn drive(973
control.send(CallUpdate::Devices(devices::list_devices(&factory)));1235
control.send(CallUpdate::Devices(devices::list_devices(&factory)));974
}1236
}975
Some(CallCommand::SetCamera(on)) => {1237
Some(CallCommand::SetCamera(on)) => {1238
let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;976
if !remote_set {1239
if !remote_set {977
control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));1240
control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));1241
} else if on && consent_pending {1242
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));1243
} else if local_hold {1244
control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));978
} else if on {1245
} else if on {979
match local_video.start_camera(&camera_choice) {1246
let started = start_camera_line(&mut local_video, ¤t.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);1247
match started {1248
Ok(()) if direct => {1249
match offer_same_peer(¤t.peer, &layout_plan, layout, false, true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {1250
Ok((browser_offer, signaled)) => {1251
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true) });1252
same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);1253
}1254
Err(error) => {1255
timeline.record("camera offer failed", error.to_string());1256
undo_change(Change::Camera(true), &mut local_video, control);1257
}1258
}1259
}980
Ok(()) => {1260
Ok(()) => {981
control.send(CallUpdate::Camera(true));1261
control.send(CallUpdate::Camera(true));982
tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);1262
tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);983
}1263
}984
Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),1264
Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),985
}1265
}1266
} else if direct {1267
local_video.stop_camera();1268
match offer_same_peer(¤t.peer, &layout_plan, layout, false, false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {1269
Ok((browser_offer, signaled)) => {1270
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false) });1271
same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);1272
}1273
Err(error) => {1274
timeline.record("camera offer failed", error.to_string());1275
control.send(CallUpdate::Camera(false));1276
}1277
}986
} else {1278
} else {987
local_video.stop_camera();1279
local_video.stop_camera();988
control.send(CallUpdate::Camera(false));1280
control.send(CallUpdate::Camera(false));@@ -1114,12 +1406,81 @@ async fn drive(1114
caption_deadline = None;1406
caption_deadline = None;1115
control.send(CallUpdate::Captions(CaptionState::Off));1407
control.send(CallUpdate::Captions(CaptionState::Off));1116
}1408
}1117
run_caption_steps(&mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), control, timeline).await;1409
run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), "", &mut bot_pending, control, timeline).await;1118
if caption_flow.on() {1410
if caption_flow.on() {1119
caption_deadline = None;1411
caption_deadline = None;1120
}1412
}1121
}1413
}1122
Some(CallCommand::SetBlur(on)) => local_video.set_blur(on),1414
Some(CallCommand::SetRecording { on, title }) => {1415
if is_meeting {1416
recording_title = title;1417
recording_flow.want(on);1418
recording_deadline = on.then(|| Instant::now() + RECORDING_START_LIMIT);1419
run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_title, &mut bot_pending, control, timeline).await;1420
}1421
}1422
Some(CallCommand::ConsentToRecording) => {1423
match remote.signaling.consent_to_recording(&remote.conversation, &remote.participant, Consent::Give).await {1424
Ok(_) => {1425
consent_pending = false;1426
control.send(CallUpdate::ConsentRequired(false));1427
}1428
Err(error) => {1429
timeline.record("recording consent failed", error.to_string());1430
control.send(CallUpdate::Notice("Could not confirm the recording notice".into()));1431
}1432
}1433
}1434
Some(CallCommand::Hold(hold)) => {1435
if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() {1436
continue;1437
}1438
if hold && local_video.camera_on() {1439
local_video.stop_camera();1440
control.send(CallUpdate::Camera(false));1441
}1442
let camera = !hold && local_video.camera_on();1443
match offer_same_peer(¤t.peer, &layout_plan, layout, hold, camera, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {1444
Ok((browser_offer, signaled)) => {1445
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold) });1446
same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);1447
}1448
Err(error) => {1449
timeline.record("hold failed", error.to_string());1450
control.send(CallUpdate::Notice(if hold { "Could not put the call on hold".into() } else { "Could not resume the call".into() }));1451
}1452
}1453
}1454
Some(CallCommand::Transfer { target, replaces }) => {1455
let Some(url) = media_links.get("transfer").cloned() else {1456
control.send(CallUpdate::Notice("This call cannot be transferred".into()));1457
continue;1458
};1459
let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_deref() };1460
match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {1461
Ok(()) => control.send(CallUpdate::Notice(format!("Transferring to {}...", target.display_name))),1462
Err(error) => {1463
timeline.record("transfer failed", error.to_string());1464
control.send(CallUpdate::Notice("Could not transfer the call".into()));1465
}1466
}1467
}1468
Some(CallCommand::OpenWhiteboard { title }) => {1469
let Some(target) = meeting_target.clone() else {1470
control.send(CallUpdate::Notice("Whiteboards belong to meetings".into()));1471
continue;1472
};1473
let session = inner.session.clone();1474
let updates = control.updates();1475
tokio::spawn(async move {1476
let update = match whiteboard::fetch_board(&session, &target, &title).await {1477
Ok(url) => CallUpdate::WhiteboardUrl(url),1478
Err(_) => CallUpdate::Notice("The whiteboard could not be opened".into()),1479
};1480
let _ = updates.send(update);1481
});1482
}1483
Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,1123
Some(CallCommand::SendReaction(reaction)) => {1484
Some(CallCommand::SendReaction(reaction)) => {1124
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {1485
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {1125
timeline.record("reaction failed", error.to_string());1486
timeline.record("reaction failed", error.to_string());@@ -1153,6 +1514,12 @@ async fn drive(1153
timeline.record("captions", "did not start in time");1514
timeline.record("captions", "did not start in time");1154
control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into())));1515
control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into())));1155
}1516
}1517
if recording_deadline.is_some_and(|deadline| Instant::now() >= deadline) {1518
recording_deadline = None;1519
recording_flow.failed();1520
timeline.record("recording", "did not start in time");1521
control.send(CallUpdate::Notice("The recording did not start".into()));1522
}1156
if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)1523
if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)1157
&& let Some(average_ms) = local_video.blur_average_ms()1524
&& let Some(average_ms) = local_video.blur_average_ms()1158
{1525
{@@ -1216,6 +1583,15 @@ async fn drive(1216
advance(state, CallSignal::LocalLeave, control);1583
advance(state, CallSignal::LocalLeave, control);1217
break;1584
break;1218
}1585
}1586
_ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {1587
same_peer_deadline = None;1588
if let Some(pending) = same_peer.take() {1589
timeline.record("same-peer offer", "no answer in time");1590
negotiator.same_peer_offer_failed();1591
rollback_offer(¤t.peer).await;1592
undo_change(pending.change, &mut local_video, control);1593
}1594
}1219
_ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => {1595
_ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => {1220
timeline.record("no answer", "outgoing call timed out");1596
timeline.record("no answer", "outgoing call timed out");1221
live.cancel_leave = true;1597
live.cancel_leave = true;@@ -1255,8 +1631,8 @@ async fn start_escalation(1255
.get("mediaRenegotiation")1631
.get("mediaRenegotiation")1256
.ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;1632
.ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;1257
let session = open_peer(factory, grant, &options.relay_host, false)?;1633
let session = open_peer(factory, grant, &options.relay_host, false)?;1258
let media = create_offer(&session.peer, factory, track).await?;1634
let media = create_offer(&session.peer, factory, track, Layout::Conference).await?;1259
let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id);1635
let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true);1260
remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;1636
remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;1261
Ok(NextPeer {1637
Ok(NextPeer {1262
session,1638
session,@@ -1272,7 +1648,7 @@ async fn answer_on_new_peer(1272
teams_offer: &str,1648
teams_offer: &str,1273
) -> Result<(PeerSession, AnsweredMedia)> {1649
) -> Result<(PeerSession, AnsweredMedia)> {1274
let session = open_peer(factory, grant, &options.relay_host, false)?;1650
let session = open_peer(factory, grant, &options.relay_host, false)?;1275
let answered = answer_offer(&session.peer, Some(track), teams_offer).await?;1651
let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject).await?;1276
Ok((session, answered))1652
Ok((session, answered))1277
}1653
}1278
1654
@@ -1328,6 +1704,7 @@ fn negotiate_video(1328
}1704
}1329
1705
1330
const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";1706
const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";1707
const ON_HOLD_NOTICE: &str = "Resume the call first";1331
1708
1332
async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {1709
async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {1333
match mode {1710
match mode {@@ -1374,6 +1751,127 @@ fn tell_media_descriptions(1374
});1751
});1375
}1752
}1376
1753
1754
fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {1755
own.is_some_and(|own| own.thread_id == target.thread_id)1756
}1757
1758
fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {1759
peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid))1760
}1761
1762
fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct_mid: Option<&str>, choice: &DeviceChoice) -> Result<()> {1763
if !local_video.has_lines() {1764
let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;1765
let camera = peer_transceiver(peer, mid).ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;1766
if !matches!(camera.direction(), RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly) {1767
peer.add_track(MediaStreamTrack::Video(local_video.camera_track()), &[CAMERA_STREAM])1768
.map_err(|error| Error::Webrtc(error.to_string()))?;1769
}1770
local_video.set_lines(VideoLines { camera, share: None })?;1771
}1772
local_video.start_camera(choice)1773
}1774
1775
#[allow(clippy::too_many_arguments)]1776
async fn offer_same_peer(1777
peer: &PeerConnection,1778
plan: &OfferPlan,1779
layout: Layout,1780
hold: bool,1781
camera: bool,1782
remote: &RemoteCall,1783
links: &CallbackLinks,1784
media_leg_id: &str,1785
media_links: &BTreeMap<String, String>,1786
negotiator: &mut MediaNegotiator,1787
) -> Result<(String, SignaledOffer)> {1788
let url = media_links1789
.get("mediaRenegotiation")1790
.cloned()1791
.ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;1792
if !negotiator.begin_same_peer_offer() {1793
return Err(Error::Signaling("another media negotiation is running".into()));1794
}1795
let offered = build_same_peer_offer(peer, plan, layout, hold, camera).await;1796
let (text, signaled) = match offered {1797
Ok(offered) => offered,1798
Err(error) => {1799
negotiator.same_peer_offer_failed();1800
return Err(error);1801
}1802
};1803
let modalities = accepted_modalities(layout == Layout::OneToOne && camera && !hold);1804
let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false);1805
if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {1806
negotiator.same_peer_offer_failed();1807
rollback_offer(peer).await;1808
return Err(error);1809
}1810
Ok((text, signaled))1811
}1812
1813
async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool) -> Result<(String, SignaledOffer)> {1814
let offer = peer1815
.create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })1816
.await1817
.map_err(|error| Error::Webrtc(error.to_string()))?;1818
let text = directions_for(layout, hold, camera, &offer.to_string());1819
let description = SessionDescription::parse(&text, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;1820
peer.set_local_description(description)1821
.await1822
.map_err(|error| Error::Webrtc(error.to_string()))?;1823
let mut numbers = random_u32;1824
let signaled = to_teams_offer(&text, plan, &mut numbers)?;1825
Ok((text, signaled))1826
}1827
1828
async fn rollback_offer(peer: &PeerConnection) {1829
if let Ok(rollback) = SessionDescription::parse("", SdpType::Rollback) {1830
let _ = peer.set_local_description(rollback).await;1831
}1832
}1833
1834
fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {1835
match change {1836
Change::Camera(true) => {1837
local_video.stop_camera();1838
control.send(CallUpdate::Camera(false));1839
}1840
Change::Camera(false) => control.send(CallUpdate::Camera(false)),1841
Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())),1842
}1843
}1844
1845
fn withhold_media(1846
muted: &mut bool,1847
audio: &AudioSetup,1848
share_audio: Option<&ShareAudio>,1849
remote: &RemoteCall,1850
local_video: &mut LocalVideo,1851
control: &CallControl,1852
) {1853
*muted = apply_mute(MuteCommand::Mute, *muted, audio, share_audio, remote, control);1854
if local_video.camera_on() {1855
local_video.stop_camera();1856
control.send(CallUpdate::Camera(false));1857
}1858
}1859
1860
async fn apply_background(choice: BackgroundChoice, local_video: &LocalVideo, control: &CallControl, timeline: &Timeline) {1861
match choice {1862
BackgroundChoice::None => local_video.set_background(false, None),1863
BackgroundChoice::Blur => local_video.set_background(true, None),1864
BackgroundChoice::Image(path) => match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {1865
Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),1866
Ok(Err(error)) => {1867
timeline.record("background image failed", error.to_string());1868
control.send(CallUpdate::Notice("That background image could not be used".into()));1869
}1870
Err(_) => {}1871
},1872
}1873
}1874
1377
fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {1875
fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {1378
let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());1876
let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());1379
Target { mri, display_name }1877
Target { mri, display_name }@@ -1394,53 +1892,105 @@ fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {1394
entry1892
entry1395
}1893
}1396
1894
1895
#[derive(Debug, Clone, Copy, PartialEq, Eq)]1896
enum BotJob {1897
Captions,1898
Recording,1899
}1900
1397
#[allow(clippy::too_many_arguments)]1901
#[allow(clippy::too_many_arguments)]1398
async fn run_caption_steps(1902
async fn run_bot_steps(1903
job: BotJob,1399
flow: &mut CaptionFlow,1904
flow: &mut CaptionFlow,1400
roster: &Roster,1905
roster: &Roster,1401
remote: &RemoteCall,1906
remote: &RemoteCall,1402
links: &CallbackLinks,1907
links: &CallbackLinks,1403
meeting_chat: Option<&str>,1908
meeting_chat: Option<&str>,1909
title: &str,1910
bot_pending: &mut bool,1404
control: &CallControl,1911
control: &CallControl,1405
timeline: &Timeline,1912
timeline: &Timeline,1406
) {1913
) {1914
let is_active: fn(&crate::roster::CaptionBot) -> bool = match job {1915
BotJob::Captions => |bot| bot.active,1916
BotJob::Recording => |bot| bot.recording,1917
};1407
let fail = |flow: &mut CaptionFlow, reason: &str| {1918
let fail = |flow: &mut CaptionFlow, reason: &str| {1408
flow.failed();1919
flow.failed();1409
control.send(CallUpdate::Captions(CaptionState::Failed(reason.to_owned())));1920
control.send(match job {1921
BotJob::Captions => CallUpdate::Captions(CaptionState::Failed(reason.to_owned())),1922
BotJob::Recording => CallUpdate::Notice(reason.to_owned()),1923
});1924
};1925
let (join_failure, start_failure) = match job {1926
BotJob::Captions => ("The captions service could not join", "Captions could not start"),1927
BotJob::Recording => ("The recording service could not join", "The recording could not start"),1410
};1928
};1411
loop {1929
loop {1412
match flow.next(roster.caption_bot()) {1930
match flow.next_for(roster.caption_bot(), is_active) {1413
CaptionStep::Wait => return,1931
CaptionStep::Wait => return,1414
CaptionStep::AddBot => {1932
CaptionStep::AddBot => {1933
if *bot_pending {1934
continue;1935
}1415
let Some(thread) = meeting_chat else {1936
let Some(thread) = meeting_chat else {1416
return fail(flow, "This meeting has no chat for captions");1937
return fail(flow, "This meeting has no chat for the captions and the recording");1417
};1938
};1418
if let Err(error) = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links).await {1939
*bot_pending = true;1419
timeline.record("caption bot failed", error.to_string());1940
let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links).await;1420
return fail(flow, "The captions service could not join");1941
if job == BotJob::Recording {1942
report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline);1943
}1944
if let Err(error) = added {1945
timeline.record("bot invitation failed", error.to_string());1946
*bot_pending = false;1947
return fail(flow, join_failure);1421
}1948
}1422
}1949
}1423
CaptionStep::Start => {1950
CaptionStep::Start => {1424
let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return };1951
let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return };1425
if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {1952
match job {1426
timeline.record("caption start failed", error.to_string());1953
BotJob::Captions => {1427
return fail(flow, "Captions could not start");1954
if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {1428
}1955
timeline.record("caption start failed", error.to_string());1429
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {1956
return fail(flow, start_failure);1430
timeline.record("caption preference failed", error.to_string());1957
}1958
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {1959
timeline.record("caption preference failed", error.to_string());1960
}1961
}1962
BotJob::Recording => {1963
let started = remote.signaling.recording_command(&url, BotAction::Start, &remote.participant, title).await;1964
let failed = started.is_err();1965
report_organizer_result(started, "recording start", start_failure, control, timeline);1966
if failed {1967
return fail(flow, start_failure);1968
}1969
}1431
}1970
}1432
}1971
}1433
CaptionStep::Stop => {1972
CaptionStep::Stop => {1434
if let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone())1973
let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { continue };1435
&& let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await1974
match job {1436
{1975
BotJob::Captions => {1437
timeline.record("caption stop failed", error.to_string());1976
if let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await {1977
timeline.record("caption stop failed", error.to_string());1978
}1979
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {1980
timeline.record("caption preference failed", error.to_string());1981
}1982
}1983
BotJob::Recording => {1984
let stopped = remote.signaling.recording_command(&url, BotAction::Stop, &remote.participant, title).await;1985
report_organizer_result(stopped, "recording stop", "The recording could not be stopped", control, timeline);1986
}1438
}1987
}1439
if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {1988
}1440
timeline.record("caption preference failed", error.to_string());1989
CaptionStep::ReportOn => {1990
if job == BotJob::Captions {1991
control.send(CallUpdate::Captions(CaptionState::On));1441
}1992
}1442
}1993
}1443
CaptionStep::ReportOn => control.send(CallUpdate::Captions(CaptionState::On)),1444
}1994
}1445
}1995
}1446
}1996
}@@ -1773,6 +2323,40 @@ mod tests {1773
assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54));2323
assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54));1774
}2324
}1775
2325
2326
const BROWSER_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:1\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:2\r\na=recvonly\r\n";2327
2328
fn directions(sdp: &str) -> Vec<String> {2329
crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()2330
}2331
2332
#[test]2333
fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {2334
assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);2335
assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);2336
}2337
2338
#[test]2339
fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {2340
for layout in [Layout::OneToOne, Layout::Conference] {2341
assert_eq!(directions(&directions_for(layout, true, true, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);2342
}2343
assert_eq!(directions_for(Layout::Conference, false, true, BROWSER_OFFER), BROWSER_OFFER);2344
}2345
2346
#[test]2347
fn a_move_into_the_meeting_you_are_already_in_is_ignored() {2348
let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None };2349
assert!(is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_a@thread.v2")));2350
assert!(!is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_b@thread.v2")));2351
assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2")));2352
}2353
2354
#[test]2355
fn a_video_call_names_the_video_modality_only_when_the_camera_sends() {2356
assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]);2357
assert_eq!(accepted_modalities(true), vec!["Audio".to_owned(), "Video".to_owned()]);2358
}2359
1776
#[test]2360
#[test]1777
fn specs_map_to_invitation_targets() {2361
fn specs_map_to_invitation_targets() {1778
assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);2362
assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);@@ -60,6 +60,18 @@ fn entry_from(item: &Value) -> Option<CaptionEntry> {
60
60
})
61
61
}
62
62
63
pub fn recorder_features() -> Value {
64
json!({
65
"enablePPTSharing": true,
66
"intermediateLiveCaptions": false,
67
"actionItemsEnabled": false,
68
"enableEmailAndMeetingLanguageModel": true,
69
"ceoSummit": false,
70
"useUnmixedAudio": true,
71
"enableTranscriptMeetingChaptering": false,
72
})
73
}
74
63
75
pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks) -> Value {
64
76
json!({
65
77
"disableUnmute": false,
@@ -72,15 +84,7 @@ pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name:
72
84
"clientInfo": "Teams-R4",
73
85
"callId": call_id,
74
86
"threadId": thread_id,
75
"recorderFeatures": {
76
"enablePPTSharing": true,
77
"intermediateLiveCaptions": false,
78
"actionItemsEnabled": false,
79
"enableEmailAndMeetingLanguageModel": true,
80
"ceoSummit": false,
81
"useUnmixedAudio": true,
82
"enableTranscriptMeetingChaptering": false,
83
},
87
"recorderFeatures": recorder_features(),
84
88
"mode": BOT_MODE,
85
89
"iCalUid": null,
86
90
"consumerType": "Teams",
@@ -172,6 +176,10 @@ impl CaptionFlow {
172
176
}
173
177
174
178
pub fn next(&mut self, bot: Option<&CaptionBot>) -> CaptionStep {
179
self.next_for(bot, |bot| bot.active)
180
}
181
182
pub fn next_for(&mut self, bot: Option<&CaptionBot>, is_active: fn(&CaptionBot) -> bool) -> CaptionStep {
175
183
if !self.wanted {
176
184
return if std::mem::take(&mut self.started) { CaptionStep::Stop } else { CaptionStep::Wait };
177
185
}
@@ -181,7 +189,7 @@ impl CaptionFlow {
181
189
if bot.command_url.is_some() && !std::mem::replace(&mut self.started, true) {
182
190
return CaptionStep::Start;
183
191
}
184
if self.started && bot.active && !std::mem::replace(&mut self.reported, true) {
192
if self.started && is_active(bot) && !std::mem::replace(&mut self.reported, true) {
185
193
return CaptionStep::ReportOn;
186
194
}
187
195
CaptionStep::Wait
@@ -193,7 +201,7 @@ mod tests {
193
201
use super::*;
194
202
195
203
fn bot(command_url: bool, active: bool) -> CaptionBot {
196
CaptionBot { mri: RECORDING_BOT_MRI.into(), command_url: command_url.then(|| "https://x/v2/oncommand/1".into()), active }
204
CaptionBot { mri: RECORDING_BOT_MRI.into(), command_url: command_url.then(|| "https://x/v2/oncommand/1".into()), active, recording: false }
197
205
}
198
206
199
207
#[test]
@@ -60,6 +60,18 @@ fn entry_from(item: &Value) -> Option<CaptionEntry> {60
})60
})61
}61
}62
62
63
pub fn recorder_features() -> Value {64
json!({65
"enablePPTSharing": true,66
"intermediateLiveCaptions": false,67
"actionItemsEnabled": false,68
"enableEmailAndMeetingLanguageModel": true,69
"ceoSummit": false,70
"useUnmixedAudio": true,71
"enableTranscriptMeetingChaptering": false,72
})73
}74
63
pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks) -> Value {75
pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks) -> Value {64
json!({76
json!({65
"disableUnmute": false,77
"disableUnmute": false,@@ -72,15 +84,7 @@ pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name:72
"clientInfo": "Teams-R4",84
"clientInfo": "Teams-R4",73
"callId": call_id,85
"callId": call_id,74
"threadId": thread_id,86
"threadId": thread_id,75
"recorderFeatures": {87
"recorderFeatures": recorder_features(),76
"enablePPTSharing": true,77
"intermediateLiveCaptions": false,78
"actionItemsEnabled": false,79
"enableEmailAndMeetingLanguageModel": true,80
"ceoSummit": false,81
"useUnmixedAudio": true,82
"enableTranscriptMeetingChaptering": false,83
},84
"mode": BOT_MODE,88
"mode": BOT_MODE,85
"iCalUid": null,89
"iCalUid": null,86
"consumerType": "Teams",90
"consumerType": "Teams",@@ -172,6 +176,10 @@ impl CaptionFlow {172
}176
}173
177
174
pub fn next(&mut self, bot: Option<&CaptionBot>) -> CaptionStep {178
pub fn next(&mut self, bot: Option<&CaptionBot>) -> CaptionStep {179
self.next_for(bot, |bot| bot.active)180
}181
182
pub fn next_for(&mut self, bot: Option<&CaptionBot>, is_active: fn(&CaptionBot) -> bool) -> CaptionStep {175
if !self.wanted {183
if !self.wanted {176
return if std::mem::take(&mut self.started) { CaptionStep::Stop } else { CaptionStep::Wait };184
return if std::mem::take(&mut self.started) { CaptionStep::Stop } else { CaptionStep::Wait };177
}185
}@@ -181,7 +189,7 @@ impl CaptionFlow {181
if bot.command_url.is_some() && !std::mem::replace(&mut self.started, true) {189
if bot.command_url.is_some() && !std::mem::replace(&mut self.started, true) {182
return CaptionStep::Start;190
return CaptionStep::Start;183
}191
}184
if self.started && bot.active && !std::mem::replace(&mut self.reported, true) {192
if self.started && is_active(bot) && !std::mem::replace(&mut self.reported, true) {185
return CaptionStep::ReportOn;193
return CaptionStep::ReportOn;186
}194
}187
CaptionStep::Wait195
CaptionStep::Wait@@ -193,7 +201,7 @@ mod tests {193
use super::*;201
use super::*;194
202
195
fn bot(command_url: bool, active: bool) -> CaptionBot {203
fn bot(command_url: bool, active: bool) -> CaptionBot {196
CaptionBot { mri: RECORDING_BOT_MRI.into(), command_url: command_url.then(|| "https://x/v2/oncommand/1".into()), active }204
CaptionBot { mri: RECORDING_BOT_MRI.into(), command_url: command_url.then(|| "https://x/v2/oncommand/1".into()), active, recording: false }197
}205
}198
206
199
#[test]207
#[test]@@ -3,16 +3,21 @@ use std::sync::Arc;
3
3
4
4
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
5
5
6
use crate::background::BackgroundChoice;
7
use crate::breakout::BreakoutMove;
6
8
use crate::captions::{CaptionEntry, CaptionState};
7
9
use crate::devices::{DeviceChoice, DeviceLists};
8
10
use crate::error::{Error, Result};
11
use crate::hold::HoldState;
9
12
use crate::mute::MuteCommand;
10
13
use crate::reaction::Reaction;
11
14
use crate::roster::RosterEntry;
12
15
use crate::camera::CameraDevice;
13
16
use crate::screen::ShareSource;
17
use crate::signaling::{Callee, MeetingTarget};
14
18
use crate::state::CallState;
15
19
use crate::video_frame::VideoHub;
20
use crate::whiteboard::ContentShare;
16
21
17
22
#[derive(Debug, Clone, PartialEq, Eq)]
18
23
pub enum CallCommand {
@@ -38,8 +43,13 @@ pub enum CallCommand {
38
43
StopSpotlight { mri: String },
39
44
RemoveParticipant { mri: String },
40
45
SetCaptions(bool),
41
SetBlur(bool),
46
SetBackground(BackgroundChoice),
42
47
SendReaction(Reaction),
48
SetRecording { on: bool, title: String },
49
ConsentToRecording,
50
Hold(bool),
51
Transfer { target: Callee, replaces: Option<String> },
52
OpenWhiteboard { title: String },
43
53
Hangup,
44
54
EndMeeting,
45
55
}
@@ -75,6 +85,14 @@ pub enum CallUpdate {
75
85
Captions(CaptionState),
76
86
Caption(CaptionEntry),
77
87
BlurTiming(f32),
88
Recording(bool),
89
ConsentRequired(bool),
90
Hold(HoldState),
91
Whiteboard(Option<ContentShare>),
92
WhiteboardUrl(String),
93
BreakoutMove(BreakoutMove),
94
BreakoutRoom { main: MeetingTarget },
95
ReplacementLink(String),
78
96
Organizer { action: String, outcome: std::result::Result<u16, String> },
79
97
MeetingChat(String),
80
98
Notice(String),
@@ -3,16 +3,21 @@ use std::sync::Arc;3
3
4
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};4
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};5
5
6
use crate::background::BackgroundChoice;7
use crate::breakout::BreakoutMove;6
use crate::captions::{CaptionEntry, CaptionState};8
use crate::captions::{CaptionEntry, CaptionState};7
use crate::devices::{DeviceChoice, DeviceLists};9
use crate::devices::{DeviceChoice, DeviceLists};8
use crate::error::{Error, Result};10
use crate::error::{Error, Result};11
use crate::hold::HoldState;9
use crate::mute::MuteCommand;12
use crate::mute::MuteCommand;10
use crate::reaction::Reaction;13
use crate::reaction::Reaction;11
use crate::roster::RosterEntry;14
use crate::roster::RosterEntry;12
use crate::camera::CameraDevice;15
use crate::camera::CameraDevice;13
use crate::screen::ShareSource;16
use crate::screen::ShareSource;17
use crate::signaling::{Callee, MeetingTarget};14
use crate::state::CallState;18
use crate::state::CallState;15
use crate::video_frame::VideoHub;19
use crate::video_frame::VideoHub;20
use crate::whiteboard::ContentShare;16
21
17
#[derive(Debug, Clone, PartialEq, Eq)]22
#[derive(Debug, Clone, PartialEq, Eq)]18
pub enum CallCommand {23
pub enum CallCommand {@@ -38,8 +43,13 @@ pub enum CallCommand {38
StopSpotlight { mri: String },43
StopSpotlight { mri: String },39
RemoveParticipant { mri: String },44
RemoveParticipant { mri: String },40
SetCaptions(bool),45
SetCaptions(bool),41
SetBlur(bool),46
SetBackground(BackgroundChoice),42
SendReaction(Reaction),47
SendReaction(Reaction),48
SetRecording { on: bool, title: String },49
ConsentToRecording,50
Hold(bool),51
Transfer { target: Callee, replaces: Option<String> },52
OpenWhiteboard { title: String },43
Hangup,53
Hangup,44
EndMeeting,54
EndMeeting,45
}55
}@@ -75,6 +85,14 @@ pub enum CallUpdate {75
Captions(CaptionState),85
Captions(CaptionState),76
Caption(CaptionEntry),86
Caption(CaptionEntry),77
BlurTiming(f32),87
BlurTiming(f32),88
Recording(bool),89
ConsentRequired(bool),90
Hold(HoldState),91
Whiteboard(Option<ContentShare>),92
WhiteboardUrl(String),93
BreakoutMove(BreakoutMove),94
BreakoutRoom { main: MeetingTarget },95
ReplacementLink(String),78
Organizer { action: String, outcome: std::result::Result<u16, String> },96
Organizer { action: String, outcome: std::result::Result<u16, String> },79
MeetingChat(String),97
MeetingChat(String),80
Notice(String),98
Notice(String),@@ -8,13 +8,18 @@ pub enum EndKind {
8
8
AnsweredElsewhere,
9
9
Forwarded,
10
10
MediaError,
11
RoomClosed,
11
12
Other,
12
13
}
13
14
14
15
const SUB_CODE_DECLINED: i64 = 10603;
15
16
const SUB_CODES_NO_ANSWER: [i64; 2] = [10408, 10486];
17
const SUB_CODES_ROOM_CLOSED: [i64; 2] = [4097, 5030];
16
18
17
19
pub fn classify_end(code: i64, sub_code: i64) -> EndKind {
20
if SUB_CODES_ROOM_CLOSED.contains(&sub_code) {
21
return EndKind::RoomClosed;
22
}
18
23
match code {
19
24
0 => EndKind::Normal,
20
25
487 => EndKind::Cancelled,
@@ -47,6 +52,13 @@ mod tests {
47
52
assert_eq!(classify_end(410, 0), EndKind::MediaError);
48
53
}
49
54
55
#[test]
56
fn a_closed_breakout_room_ends_with_its_own_sub_codes() {
57
assert_eq!(classify_end(0, 4097), EndKind::RoomClosed);
58
assert_eq!(classify_end(0, 5030), EndKind::RoomClosed);
59
assert_eq!(classify_end(0, 5001), EndKind::Normal);
60
}
61
50
62
#[test]
51
63
fn unknown_codes_fall_back_to_the_sub_code() {
52
64
assert_eq!(classify_end(500, 10603), EndKind::Declined);
@@ -8,13 +8,18 @@ pub enum EndKind {8
AnsweredElsewhere,8
AnsweredElsewhere,9
Forwarded,9
Forwarded,10
MediaError,10
MediaError,11
RoomClosed,11
Other,12
Other,12
}13
}13
14
14
const SUB_CODE_DECLINED: i64 = 10603;15
const SUB_CODE_DECLINED: i64 = 10603;15
const SUB_CODES_NO_ANSWER: [i64; 2] = [10408, 10486];16
const SUB_CODES_NO_ANSWER: [i64; 2] = [10408, 10486];17
const SUB_CODES_ROOM_CLOSED: [i64; 2] = [4097, 5030];16
18
17
pub fn classify_end(code: i64, sub_code: i64) -> EndKind {19
pub fn classify_end(code: i64, sub_code: i64) -> EndKind {20
if SUB_CODES_ROOM_CLOSED.contains(&sub_code) {21
return EndKind::RoomClosed;22
}18
match code {23
match code {19
0 => EndKind::Normal,24
0 => EndKind::Normal,20
487 => EndKind::Cancelled,25
487 => EndKind::Cancelled,@@ -47,6 +52,13 @@ mod tests {47
assert_eq!(classify_end(410, 0), EndKind::MediaError);52
assert_eq!(classify_end(410, 0), EndKind::MediaError);48
}53
}49
54
55
#[test]56
fn a_closed_breakout_room_ends_with_its_own_sub_codes() {57
assert_eq!(classify_end(0, 4097), EndKind::RoomClosed);58
assert_eq!(classify_end(0, 5030), EndKind::RoomClosed);59
assert_eq!(classify_end(0, 5001), EndKind::Normal);60
}61
50
#[test]62
#[test]51
fn unknown_codes_fall_back_to_the_sub_code() {63
fn unknown_codes_fall_back_to_the_sub_code() {52
assert_eq!(classify_end(500, 10603), EndKind::Declined);64
assert_eq!(classify_end(500, 10603), EndKind::Declined);@@ -9,13 +9,15 @@ use tokio::sync::{mpsc, oneshot};
9
9
use tokio::task::JoinHandle;
10
10
use tokio::time::timeout;
11
11
12
use crate::call::{CallOptions, CallSpec, IncomingCall, Plan};
12
use crate::call::{AcceptMode, CallOptions, CallSpec, IncomingCall, Plan};
13
13
use crate::control::{CallHandle, call_channel};
14
14
use crate::end::EndKind;
15
15
use crate::error::{Error, Result};
16
16
use crate::push::{CallNotification, Caller, PushEvent, decode_push};
17
17
use crate::relay::DEFAULT_RELAY_HOST;
18
use crate::signaling::{AttachRequest, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self};
18
use crate::signaling::{
19
AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self,
20
};
19
21
use crate::timeline::Timeline;
20
22
use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, classify, decode_body};
21
23
@@ -90,7 +92,7 @@ pub enum EngineEvent {
90
92
}
91
93
92
94
enum RingCommand {
93
Accept(oneshot::Sender<Option<CallHandle>>),
95
Accept(AcceptMode, oneshot::Sender<Option<CallHandle>>),
94
96
Decline,
95
97
Drop,
96
98
}
@@ -252,19 +254,27 @@ impl CallEngine {
252
254
}
253
255
254
256
pub fn start_call(&self, spec: CallSpec) -> CallHandle {
257
self.start_call_with(spec, false)
258
}
259
260
pub fn start_consult(&self, spec: CallSpec) -> CallHandle {
261
self.start_call_with(spec, true)
262
}
263
264
fn start_call_with(&self, spec: CallSpec, concurrent: bool) -> CallHandle {
255
265
let (handle, control) = call_channel();
256
266
let engine = self.clone();
257
267
self.inner.runtime.spawn(async move {
258
let options = engine.inner.call_options();
268
let options = CallOptions { concurrent, ..engine.inner.call_options() };
259
269
let _ = engine.run(Plan::Outgoing(spec), options, control).await;
260
270
});
261
271
handle
262
272
}
263
273
264
pub async fn accept_ring(&self, ring_id: u64) -> Option<CallHandle> {
274
pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {
265
275
let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned()?;
266
276
let (answer, handle) = oneshot::channel();
267
commands.send(RingCommand::Accept(answer)).ok()?;
277
commands.send(RingCommand::Accept(mode, answer)).ok()?;
268
278
handle.await.ok().flatten()
269
279
}
270
280
@@ -285,6 +295,16 @@ impl CallEngine {
285
295
}
286
296
}
287
297
298
pub async fn resolve_meeting(&self, meeting_data: &serde_json::Value) -> Result<MeetingTarget> {
299
let signaling = self.inner.signaling(Timeline::new(self.inner.config.trace));
300
let from = self.inner.participant(&uuid::Uuid::new_v4().to_string());
301
let (target, conversation) = signaling
302
.resolve_meeting(&from, &self.inner.callback_links(), meeting_data)
303
.await?;
304
let _ = signaling.leave(&conversation, &from, LeaveReason::Cancel).await;
305
Ok(target)
306
}
307
288
308
pub async fn stop(&self) {
289
309
let stop = self.inner.stop.lock().expect("stop lock").take();
290
310
if let Some(stop) = stop {
@@ -422,9 +442,10 @@ async fn ring_task(
422
442
}
423
443
}
424
444
command = commands.recv() => match command {
425
Some(RingCommand::Accept(answer)) => {
445
Some(RingCommand::Accept(accept, answer)) => {
426
446
let (handle, control) = call_channel();
427
447
let incoming = IncomingCall {
448
accept,
428
449
notification,
429
450
attached,
430
451
links,
@@ -9,13 +9,15 @@ use tokio::sync::{mpsc, oneshot};9
use tokio::task::JoinHandle;9
use tokio::task::JoinHandle;10
use tokio::time::timeout;10
use tokio::time::timeout;11
11
12
use crate::call::{CallOptions, CallSpec, IncomingCall, Plan};12
use crate::call::{AcceptMode, CallOptions, CallSpec, IncomingCall, Plan};13
use crate::control::{CallHandle, call_channel};13
use crate::control::{CallHandle, call_channel};14
use crate::end::EndKind;14
use crate::end::EndKind;15
use crate::error::{Error, Result};15
use crate::error::{Error, Result};16
use crate::push::{CallNotification, Caller, PushEvent, decode_push};16
use crate::push::{CallNotification, Caller, PushEvent, decode_push};17
use crate::relay::DEFAULT_RELAY_HOST;17
use crate::relay::DEFAULT_RELAY_HOST;18
use crate::signaling::{AttachRequest, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self};18
use crate::signaling::{19
AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self,20
};19
use crate::timeline::Timeline;21
use crate::timeline::Timeline;20
use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, classify, decode_body};22
use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, classify, decode_body};21
23
@@ -90,7 +92,7 @@ pub enum EngineEvent {90
}92
}91
93
92
enum RingCommand {94
enum RingCommand {93
Accept(oneshot::Sender<Option<CallHandle>>),95
Accept(AcceptMode, oneshot::Sender<Option<CallHandle>>),94
Decline,96
Decline,95
Drop,97
Drop,96
}98
}@@ -252,19 +254,27 @@ impl CallEngine {252
}254
}253
255
254
pub fn start_call(&self, spec: CallSpec) -> CallHandle {256
pub fn start_call(&self, spec: CallSpec) -> CallHandle {257
self.start_call_with(spec, false)258
}259
260
pub fn start_consult(&self, spec: CallSpec) -> CallHandle {261
self.start_call_with(spec, true)262
}263
264
fn start_call_with(&self, spec: CallSpec, concurrent: bool) -> CallHandle {255
let (handle, control) = call_channel();265
let (handle, control) = call_channel();256
let engine = self.clone();266
let engine = self.clone();257
self.inner.runtime.spawn(async move {267
self.inner.runtime.spawn(async move {258
let options = engine.inner.call_options();268
let options = CallOptions { concurrent, ..engine.inner.call_options() };259
let _ = engine.run(Plan::Outgoing(spec), options, control).await;269
let _ = engine.run(Plan::Outgoing(spec), options, control).await;260
});270
});261
handle271
handle262
}272
}263
273
264
pub async fn accept_ring(&self, ring_id: u64) -> Option<CallHandle> {274
pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> {265
let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned()?;275
let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned()?;266
let (answer, handle) = oneshot::channel();276
let (answer, handle) = oneshot::channel();267
commands.send(RingCommand::Accept(answer)).ok()?;277
commands.send(RingCommand::Accept(mode, answer)).ok()?;268
handle.await.ok().flatten()278
handle.await.ok().flatten()269
}279
}270
280
@@ -285,6 +295,16 @@ impl CallEngine {285
}295
}286
}296
}287
297
298
pub async fn resolve_meeting(&self, meeting_data: &serde_json::Value) -> Result<MeetingTarget> {299
let signaling = self.inner.signaling(Timeline::new(self.inner.config.trace));300
let from = self.inner.participant(&uuid::Uuid::new_v4().to_string());301
let (target, conversation) = signaling302
.resolve_meeting(&from, &self.inner.callback_links(), meeting_data)303
.await?;304
let _ = signaling.leave(&conversation, &from, LeaveReason::Cancel).await;305
Ok(target)306
}307
288
pub async fn stop(&self) {308
pub async fn stop(&self) {289
let stop = self.inner.stop.lock().expect("stop lock").take();309
let stop = self.inner.stop.lock().expect("stop lock").take();290
if let Some(stop) = stop {310
if let Some(stop) = stop {@@ -422,9 +442,10 @@ async fn ring_task(422
}442
}423
}443
}424
command = commands.recv() => match command {444
command = commands.recv() => match command {425
Some(RingCommand::Accept(answer)) => {445
Some(RingCommand::Accept(accept, answer)) => {426
let (handle, control) = call_channel();446
let (handle, control) = call_channel();427
let incoming = IncomingCall {447
let incoming = IncomingCall {448
accept,428
notification,449
notification,429
attached,450
attached,430
links,451
links,@@ -0,0 +1,188 @@
1
use crate::error::Result;
2
use crate::sdp::parse;
3
4
const DIRECTIONS: [&str; 4] = ["sendrecv", "sendonly", "recvonly", "inactive"];
5
pub const INACTIVE: &str = "inactive";
6
const REJECTED_PORT: &str = "0";
7
const DATA_KINDS: [&str; 2] = ["x-data", "application"];
8
const MAIN_VIDEO_LABEL: &str = "main-video";
9
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11
pub enum HoldState {
12
#[default]
13
Active,
14
Local,
15
Remote,
16
}
17
18
impl HoldState {
19
pub fn from_flags(local: bool, remote: bool) -> HoldState {
20
if local {
21
HoldState::Local
22
} else if remote {
23
HoldState::Remote
24
} else {
25
HoldState::Active
26
}
27
}
28
}
29
30
#[derive(Debug, Clone, Copy)]
31
pub struct MediaLine<'a> {
32
pub kind: &'a str,
33
pub mid: &'a str,
34
}
35
36
struct Section {
37
kind: String,
38
mid: String,
39
direction_line: Option<usize>,
40
}
41
42
fn sections(lines: &[String]) -> Vec<Section> {
43
let mut found: Vec<Section> = Vec::new();
44
for (index, line) in lines.iter().enumerate() {
45
if let Some(rest) = line.strip_prefix("m=") {
46
let kind = rest.split(' ').next().unwrap_or_default().to_owned();
47
found.push(Section { kind, mid: String::new(), direction_line: None });
48
} else if let Some(section) = found.last_mut() {
49
if let Some(mid) = line.strip_prefix("a=mid:") {
50
section.mid = mid.to_owned();
51
} else if line.strip_prefix("a=").is_some_and(|name| DIRECTIONS.contains(&name)) {
52
section.direction_line = Some(index);
53
}
54
}
55
}
56
found
57
}
58
59
pub fn rewrite_directions(sdp: &str, pick: impl Fn(MediaLine<'_>) -> Option<&'static str>) -> String {
60
let newline = if sdp.contains("\r\n") { "\r\n" } else { "\n" };
61
let mut lines: Vec<String> = sdp.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();
62
for section in sections(&lines) {
63
let Some(direction_line) = section.direction_line else { continue };
64
if let Some(direction) = pick(MediaLine { kind: §ion.kind, mid: §ion.mid }) {
65
lines[direction_line] = format!("a={direction}");
66
}
67
}
68
lines.join(newline)
69
}
70
71
pub fn all_inactive(sdp: &str) -> String {
72
rewrite_directions(sdp, |_| Some(INACTIVE))
73
}
74
75
pub fn is_hold(teams_sdp: &str) -> Result<bool> {
76
let description = parse(teams_sdp)?;
77
let mut media = description
78
.media
79
.iter()
80
.filter(|line| line.port != REJECTED_PORT && !DATA_KINDS.contains(&line.kind.as_str()))
81
.peekable();
82
if media.peek().is_none() {
83
return Ok(false);
84
}
85
Ok(media.all(|line| line.direction() == Some(INACTIVE)))
86
}
87
88
pub fn offer_sends_video(teams_sdp: &str) -> bool {
89
parse(teams_sdp).is_ok_and(|description| {
90
description.media.iter().any(|line| {
91
line.kind == "video"
92
&& line.port != REJECTED_PORT
93
&& line.value("label").is_none_or(|label| label == MAIN_VIDEO_LABEL)
94
&& matches!(line.direction(), None | Some("sendrecv" | "sendonly"))
95
})
96
})
97
}
98
99
pub fn accepted_modalities(video: bool) -> Vec<String> {
100
let mut modalities = vec!["Audio".to_owned()];
101
if video {
102
modalities.push("Video".to_owned());
103
}
104
modalities
105
}
106
107
#[cfg(test)]
108
mod tests {
109
use super::*;
110
111
const OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=mid:0\r\na=sendrecv\r\na=rtpmap:111 opus/48000/2\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:1\r\na=sendrecv\r\na=rtpmap:102 H264/90000\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:2\r\na=recvonly\r\na=rtpmap:102 H264/90000\r\n";
112
113
fn directions(sdp: &str) -> Vec<String> {
114
parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()
115
}
116
117
#[test]
118
fn holding_puts_every_line_on_inactive_and_nothing_else_changes() {
119
let held = all_inactive(OFFER);
120
assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);
121
assert_eq!(held.lines().count(), OFFER.lines().count());
122
assert!(held.contains("a=mid:2\r\na=inactive\r\n"));
123
assert!(held.ends_with("\r\n"));
124
}
125
126
#[test]
127
fn resuming_keeps_the_offer_as_libwebrtc_wrote_it() {
128
let resumed = rewrite_directions(OFFER, |_| None);
129
assert_eq!(resumed, OFFER);
130
assert_eq!(directions(&resumed), vec!["sendrecv", "sendrecv", "recvonly"]);
131
}
132
133
#[test]
134
fn single_lines_can_be_picked_by_kind_and_mid() {
135
let picked = rewrite_directions(OFFER, |line| match (line.kind, line.mid) {
136
("video", "1") => Some("inactive"),
137
("video", "2") => Some("sendonly"),
138
_ => None,
139
});
140
assert_eq!(directions(&picked), vec!["sendrecv", "inactive", "sendonly"]);
141
}
142
143
#[test]
144
fn plain_line_feeds_survive() {
145
let unix = OFFER.replace("\r\n", "\n");
146
let held = all_inactive(&unix);
147
assert!(!held.contains('\r'));
148
assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);
149
}
150
151
#[test]
152
fn a_hold_is_every_audio_and_video_line_inactive() {
153
assert!(is_hold(&all_inactive(OFFER)).unwrap());
154
assert!(!is_hold(OFFER).unwrap());
155
let sendonly_audio = rewrite_directions(&all_inactive(OFFER), |line| (line.kind == "audio").then_some("sendonly"));
156
assert!(!is_hold(&sendonly_audio).unwrap());
157
}
158
159
#[test]
160
fn rejected_and_data_lines_do_not_stop_a_hold() {
161
let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\na=mid:0\r\na=inactive\r\nm=video 0 RTP/SAVP 102\r\na=mid:1\r\na=inactive\r\nm=x-data 1234 RTP/SAVP 127\r\na=mid:2\r\na=sendrecv\r\n";
162
assert!(is_hold(teams).unwrap());
163
assert!(!is_hold("v=0\r\ns=-\r\nt=0 0\r\n").unwrap());
164
}
165
166
#[test]
167
fn an_offer_with_a_sending_main_video_line_is_a_video_call() {
168
let teams = |direction: &str, label: &str| format!("v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\na=mid:0\r\na=sendrecv\r\nm=video 1234 RTP/SAVP 102\r\na=mid:1\r\na={direction}\r\na=label:{label}\r\n");
169
assert!(offer_sends_video(&teams("sendrecv", "main-video")));
170
assert!(offer_sends_video(&teams("sendonly", "main-video")));
171
assert!(!offer_sends_video(&teams("recvonly", "main-video")));
172
assert!(!offer_sends_video(&teams("inactive", "main-video")));
173
assert!(!offer_sends_video(&teams("sendrecv", "applicationsharing-video")));
174
}
175
176
#[test]
177
fn the_hold_state_prefers_your_own_hold() {
178
assert_eq!(HoldState::from_flags(false, false), HoldState::Active);
179
assert_eq!(HoldState::from_flags(true, true), HoldState::Local);
180
assert_eq!(HoldState::from_flags(false, true), HoldState::Remote);
181
}
182
183
#[test]
184
fn accepting_with_video_adds_the_modality() {
185
assert_eq!(accepted_modalities(false), vec!["Audio"]);
186
assert_eq!(accepted_modalities(true), vec!["Audio", "Video"]);
187
}
188
}
@@ -0,0 +1,188 @@1
use crate::error::Result;2
use crate::sdp::parse;3
4
const DIRECTIONS: [&str; 4] = ["sendrecv", "sendonly", "recvonly", "inactive"];5
pub const INACTIVE: &str = "inactive";6
const REJECTED_PORT: &str = "0";7
const DATA_KINDS: [&str; 2] = ["x-data", "application"];8
const MAIN_VIDEO_LABEL: &str = "main-video";9
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]11
pub enum HoldState {12
#[default]13
Active,14
Local,15
Remote,16
}17
18
impl HoldState {19
pub fn from_flags(local: bool, remote: bool) -> HoldState {20
if local {21
HoldState::Local22
} else if remote {23
HoldState::Remote24
} else {25
HoldState::Active26
}27
}28
}29
30
#[derive(Debug, Clone, Copy)]31
pub struct MediaLine<'a> {32
pub kind: &'a str,33
pub mid: &'a str,34
}35
36
struct Section {37
kind: String,38
mid: String,39
direction_line: Option<usize>,40
}41
42
fn sections(lines: &[String]) -> Vec<Section> {43
let mut found: Vec<Section> = Vec::new();44
for (index, line) in lines.iter().enumerate() {45
if let Some(rest) = line.strip_prefix("m=") {46
let kind = rest.split(' ').next().unwrap_or_default().to_owned();47
found.push(Section { kind, mid: String::new(), direction_line: None });48
} else if let Some(section) = found.last_mut() {49
if let Some(mid) = line.strip_prefix("a=mid:") {50
section.mid = mid.to_owned();51
} else if line.strip_prefix("a=").is_some_and(|name| DIRECTIONS.contains(&name)) {52
section.direction_line = Some(index);53
}54
}55
}56
found57
}58
59
pub fn rewrite_directions(sdp: &str, pick: impl Fn(MediaLine<'_>) -> Option<&'static str>) -> String {60
let newline = if sdp.contains("\r\n") { "\r\n" } else { "\n" };61
let mut lines: Vec<String> = sdp.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();62
for section in sections(&lines) {63
let Some(direction_line) = section.direction_line else { continue };64
if let Some(direction) = pick(MediaLine { kind: §ion.kind, mid: §ion.mid }) {65
lines[direction_line] = format!("a={direction}");66
}67
}68
lines.join(newline)69
}70
71
pub fn all_inactive(sdp: &str) -> String {72
rewrite_directions(sdp, |_| Some(INACTIVE))73
}74
75
pub fn is_hold(teams_sdp: &str) -> Result<bool> {76
let description = parse(teams_sdp)?;77
let mut media = description78
.media79
.iter()80
.filter(|line| line.port != REJECTED_PORT && !DATA_KINDS.contains(&line.kind.as_str()))81
.peekable();82
if media.peek().is_none() {83
return Ok(false);84
}85
Ok(media.all(|line| line.direction() == Some(INACTIVE)))86
}87
88
pub fn offer_sends_video(teams_sdp: &str) -> bool {89
parse(teams_sdp).is_ok_and(|description| {90
description.media.iter().any(|line| {91
line.kind == "video"92
&& line.port != REJECTED_PORT93
&& line.value("label").is_none_or(|label| label == MAIN_VIDEO_LABEL)94
&& matches!(line.direction(), None | Some("sendrecv" | "sendonly"))95
})96
})97
}98
99
pub fn accepted_modalities(video: bool) -> Vec<String> {100
let mut modalities = vec!["Audio".to_owned()];101
if video {102
modalities.push("Video".to_owned());103
}104
modalities105
}106
107
#[cfg(test)]108
mod tests {109
use super::*;110
111
const OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=mid:0\r\na=sendrecv\r\na=rtpmap:111 opus/48000/2\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:1\r\na=sendrecv\r\na=rtpmap:102 H264/90000\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:2\r\na=recvonly\r\na=rtpmap:102 H264/90000\r\n";112
113
fn directions(sdp: &str) -> Vec<String> {114
parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()115
}116
117
#[test]118
fn holding_puts_every_line_on_inactive_and_nothing_else_changes() {119
let held = all_inactive(OFFER);120
assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);121
assert_eq!(held.lines().count(), OFFER.lines().count());122
assert!(held.contains("a=mid:2\r\na=inactive\r\n"));123
assert!(held.ends_with("\r\n"));124
}125
126
#[test]127
fn resuming_keeps_the_offer_as_libwebrtc_wrote_it() {128
let resumed = rewrite_directions(OFFER, |_| None);129
assert_eq!(resumed, OFFER);130
assert_eq!(directions(&resumed), vec!["sendrecv", "sendrecv", "recvonly"]);131
}132
133
#[test]134
fn single_lines_can_be_picked_by_kind_and_mid() {135
let picked = rewrite_directions(OFFER, |line| match (line.kind, line.mid) {136
("video", "1") => Some("inactive"),137
("video", "2") => Some("sendonly"),138
_ => None,139
});140
assert_eq!(directions(&picked), vec!["sendrecv", "inactive", "sendonly"]);141
}142
143
#[test]144
fn plain_line_feeds_survive() {145
let unix = OFFER.replace("\r\n", "\n");146
let held = all_inactive(&unix);147
assert!(!held.contains('\r'));148
assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);149
}150
151
#[test]152
fn a_hold_is_every_audio_and_video_line_inactive() {153
assert!(is_hold(&all_inactive(OFFER)).unwrap());154
assert!(!is_hold(OFFER).unwrap());155
let sendonly_audio = rewrite_directions(&all_inactive(OFFER), |line| (line.kind == "audio").then_some("sendonly"));156
assert!(!is_hold(&sendonly_audio).unwrap());157
}158
159
#[test]160
fn rejected_and_data_lines_do_not_stop_a_hold() {161
let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\na=mid:0\r\na=inactive\r\nm=video 0 RTP/SAVP 102\r\na=mid:1\r\na=inactive\r\nm=x-data 1234 RTP/SAVP 127\r\na=mid:2\r\na=sendrecv\r\n";162
assert!(is_hold(teams).unwrap());163
assert!(!is_hold("v=0\r\ns=-\r\nt=0 0\r\n").unwrap());164
}165
166
#[test]167
fn an_offer_with_a_sending_main_video_line_is_a_video_call() {168
let teams = |direction: &str, label: &str| format!("v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\na=mid:0\r\na=sendrecv\r\nm=video 1234 RTP/SAVP 102\r\na=mid:1\r\na={direction}\r\na=label:{label}\r\n");169
assert!(offer_sends_video(&teams("sendrecv", "main-video")));170
assert!(offer_sends_video(&teams("sendonly", "main-video")));171
assert!(!offer_sends_video(&teams("recvonly", "main-video")));172
assert!(!offer_sends_video(&teams("inactive", "main-video")));173
assert!(!offer_sends_video(&teams("sendrecv", "applicationsharing-video")));174
}175
176
#[test]177
fn the_hold_state_prefers_your_own_hold() {178
assert_eq!(HoldState::from_flags(false, false), HoldState::Active);179
assert_eq!(HoldState::from_flags(true, true), HoldState::Local);180
assert_eq!(HoldState::from_flags(false, true), HoldState::Remote);181
}182
183
#[test]184
fn accepting_with_video_adds_the_modality() {185
assert_eq!(accepted_modalities(false), vec!["Audio"]);186
assert_eq!(accepted_modalities(true), vec!["Audio", "Video"]);187
}188
}@@ -0,0 +1,104 @@
1
use serde_json::{Value, json};
2
3
use crate::error::{Error, Result};
4
use crate::signaling::{MeetingTarget, Participant, chat_thread_id, endpoint_state, subscribe_request};
5
use crate::trouter_events::CallbackLinks;
6
7
const RESURRECT: &str = "resurrect";
8
9
/// Conversation links are required: without them epconv answers 400 with an empty body.
10
pub fn resolve_body(from: &Participant, callbacks: &CallbackLinks, meeting_data: &Value) -> Value {
11
json!({
12
"conversationRequest": subscribe_request(callbacks),
13
"participants": {"from": from.wire()},
14
"groupChat": null,
15
"meetingInfo": null,
16
"meetingData": meeting_data,
17
"meetingPreferences": {"shouldResurrect": RESURRECT},
18
"endpointState": endpoint_state(),
19
})
20
}
21
22
fn answer_text(body: &Value, pointer: &str) -> Option<String> {
23
body.pointer(pointer)?
24
.as_str()
25
.filter(|text| !text.is_empty())
26
.map(str::to_owned)
27
}
28
29
pub fn target_from_answer(body: &Value, meeting_data: &Value) -> Result<MeetingTarget> {
30
let not_found = || Error::Signaling("meeting not found".into());
31
Ok(MeetingTarget {
32
thread_id: chat_thread_id(body).ok_or_else(not_found)?,
33
tenant_id: answer_text(body, "/meetingInfo/tenantId")
34
.or_else(|| answer_text(body, "/tenantId"))
35
.ok_or_else(not_found)?,
36
organizer_id: answer_text(body, "/meetingInfo/organizerId").ok_or_else(not_found)?,
37
meeting_data: Some(meeting_data.clone()),
38
})
39
}
40
41
#[cfg(test)]
42
mod tests {
43
use super::*;
44
45
fn meeting_data() -> Value {
46
json!({"meetingCode": "234567890123", "passcode": "pw", "meetingUrl": "https://teams.microsoft.com/meet/234567890123?p=pw"})
47
}
48
49
fn from() -> Participant {
50
Participant {
51
mri: "8:orgid:me".into(),
52
display_name: "Me".into(),
53
endpoint_id: "endpoint".into(),
54
participant_id: "participant".into(),
55
language_id: "en-gb".into(),
56
}
57
}
58
59
#[test]
60
fn the_resolve_body_is_a_roster_subscription_by_meeting_data() {
61
let callbacks = CallbackLinks::new("https://trouter.example/callAgent", "call-1");
62
let body = resolve_body(&from(), &callbacks, &meeting_data());
63
assert_eq!(body["meetingData"], meeting_data());
64
assert_eq!(body["groupChat"], Value::Null);
65
assert_eq!(body["meetingInfo"], Value::Null);
66
assert_eq!(body["participants"]["from"]["id"], "8:orgid:me");
67
assert_eq!(body["meetingPreferences"]["shouldResurrect"], "resurrect");
68
let links = body["conversationRequest"]["links"].as_object().unwrap();
69
assert!(links.contains_key("conversationUpdate") && links.contains_key("conversationEnd"));
70
assert!(body["conversationRequest"]["roster"]["rosterUpdate"].as_str().unwrap().contains("call-1"));
71
assert!(body.get("callInvitation").is_none());
72
}
73
74
#[test]
75
fn an_answer_with_thread_tenant_and_organizer_gives_a_target() {
76
let body = json!({
77
"activeModalities": {"groupChat": {"threadId": "19:meeting_x@thread.v2", "messageId": "0"}},
78
"meetingInfo": {"tenantId": "tenant-1", "organizerId": "organizer-1"},
79
});
80
let target = target_from_answer(&body, &meeting_data()).unwrap();
81
assert_eq!(target.thread_id, "19:meeting_x@thread.v2");
82
assert_eq!(target.tenant_id, "tenant-1");
83
assert_eq!(target.organizer_id, "organizer-1");
84
assert_eq!(target.meeting_data, Some(meeting_data()));
85
}
86
87
#[test]
88
fn the_top_level_tenant_fills_a_missing_meeting_info_tenant() {
89
let body = json!({
90
"activeModalities": {"groupChat": {"threadId": "19:x"}},
91
"tenantId": "tenant-2",
92
"meetingInfo": {"organizerId": "organizer-1"},
93
});
94
assert_eq!(target_from_answer(&body, &meeting_data()).unwrap().tenant_id, "tenant-2");
95
}
96
97
#[test]
98
fn an_answer_without_a_thread_or_organizer_is_not_found() {
99
let no_thread = json!({"meetingInfo": {"tenantId": "t", "organizerId": "o"}});
100
assert!(target_from_answer(&no_thread, &meeting_data()).is_err());
101
let no_organizer = json!({"activeModalities": {"groupChat": {"threadId": "19:x"}}, "meetingInfo": {"tenantId": "t"}});
102
assert!(target_from_answer(&no_organizer, &meeting_data()).is_err());
103
}
104
}
@@ -0,0 +1,104 @@1
use serde_json::{Value, json};2
3
use crate::error::{Error, Result};4
use crate::signaling::{MeetingTarget, Participant, chat_thread_id, endpoint_state, subscribe_request};5
use crate::trouter_events::CallbackLinks;6
7
const RESURRECT: &str = "resurrect";8
9
/// Conversation links are required: without them epconv answers 400 with an empty body.10
pub fn resolve_body(from: &Participant, callbacks: &CallbackLinks, meeting_data: &Value) -> Value {11
json!({12
"conversationRequest": subscribe_request(callbacks),13
"participants": {"from": from.wire()},14
"groupChat": null,15
"meetingInfo": null,16
"meetingData": meeting_data,17
"meetingPreferences": {"shouldResurrect": RESURRECT},18
"endpointState": endpoint_state(),19
})20
}21
22
fn answer_text(body: &Value, pointer: &str) -> Option<String> {23
body.pointer(pointer)?24
.as_str()25
.filter(|text| !text.is_empty())26
.map(str::to_owned)27
}28
29
pub fn target_from_answer(body: &Value, meeting_data: &Value) -> Result<MeetingTarget> {30
let not_found = || Error::Signaling("meeting not found".into());31
Ok(MeetingTarget {32
thread_id: chat_thread_id(body).ok_or_else(not_found)?,33
tenant_id: answer_text(body, "/meetingInfo/tenantId")34
.or_else(|| answer_text(body, "/tenantId"))35
.ok_or_else(not_found)?,36
organizer_id: answer_text(body, "/meetingInfo/organizerId").ok_or_else(not_found)?,37
meeting_data: Some(meeting_data.clone()),38
})39
}40
41
#[cfg(test)]42
mod tests {43
use super::*;44
45
fn meeting_data() -> Value {46
json!({"meetingCode": "234567890123", "passcode": "pw", "meetingUrl": "https://teams.microsoft.com/meet/234567890123?p=pw"})47
}48
49
fn from() -> Participant {50
Participant {51
mri: "8:orgid:me".into(),52
display_name: "Me".into(),53
endpoint_id: "endpoint".into(),54
participant_id: "participant".into(),55
language_id: "en-gb".into(),56
}57
}58
59
#[test]60
fn the_resolve_body_is_a_roster_subscription_by_meeting_data() {61
let callbacks = CallbackLinks::new("https://trouter.example/callAgent", "call-1");62
let body = resolve_body(&from(), &callbacks, &meeting_data());63
assert_eq!(body["meetingData"], meeting_data());64
assert_eq!(body["groupChat"], Value::Null);65
assert_eq!(body["meetingInfo"], Value::Null);66
assert_eq!(body["participants"]["from"]["id"], "8:orgid:me");67
assert_eq!(body["meetingPreferences"]["shouldResurrect"], "resurrect");68
let links = body["conversationRequest"]["links"].as_object().unwrap();69
assert!(links.contains_key("conversationUpdate") && links.contains_key("conversationEnd"));70
assert!(body["conversationRequest"]["roster"]["rosterUpdate"].as_str().unwrap().contains("call-1"));71
assert!(body.get("callInvitation").is_none());72
}73
74
#[test]75
fn an_answer_with_thread_tenant_and_organizer_gives_a_target() {76
let body = json!({77
"activeModalities": {"groupChat": {"threadId": "19:meeting_x@thread.v2", "messageId": "0"}},78
"meetingInfo": {"tenantId": "tenant-1", "organizerId": "organizer-1"},79
});80
let target = target_from_answer(&body, &meeting_data()).unwrap();81
assert_eq!(target.thread_id, "19:meeting_x@thread.v2");82
assert_eq!(target.tenant_id, "tenant-1");83
assert_eq!(target.organizer_id, "organizer-1");84
assert_eq!(target.meeting_data, Some(meeting_data()));85
}86
87
#[test]88
fn the_top_level_tenant_fills_a_missing_meeting_info_tenant() {89
let body = json!({90
"activeModalities": {"groupChat": {"threadId": "19:x"}},91
"tenantId": "tenant-2",92
"meetingInfo": {"organizerId": "organizer-1"},93
});94
assert_eq!(target_from_answer(&body, &meeting_data()).unwrap().tenant_id, "tenant-2");95
}96
97
#[test]98
fn an_answer_without_a_thread_or_organizer_is_not_found() {99
let no_thread = json!({"meetingInfo": {"tenantId": "t", "organizerId": "o"}});100
assert!(target_from_answer(&no_thread, &meeting_data()).is_err());101
let no_organizer = json!({"activeModalities": {"groupChat": {"threadId": "19:x"}}, "meetingInfo": {"tenantId": "t"}});102
assert!(target_from_answer(&no_organizer, &meeting_data()).is_err());103
}104
}@@ -1,7 +1,9 @@
1
1
pub mod audio;
2
2
pub mod audio_io;
3
pub mod background;
3
4
pub mod call;
4
5
pub mod blur;
6
pub mod breakout;
5
7
pub mod camera;
6
8
pub mod captions;
7
9
pub mod capture;
@@ -11,6 +13,8 @@ pub mod devices;
11
13
pub mod engine;
12
14
pub mod end;
13
15
pub mod error;
16
pub mod hold;
17
pub mod join;
14
18
pub mod level;
15
19
#[cfg(windows)]
16
20
mod loopback_windows;
@@ -21,6 +25,7 @@ pub mod organizer;
21
25
pub mod pcm;
22
26
pub mod push;
23
27
pub mod reaction;
28
pub mod recording;
24
29
pub mod relay;
25
30
pub mod renegotiation;
26
31
pub mod ring;
@@ -32,15 +37,21 @@ pub mod signaling;
32
37
pub mod sound_capture;
33
38
pub mod state;
34
39
pub mod timeline;
40
pub mod transfer;
35
41
pub mod trouter_events;
36
42
pub mod video_frame;
37
43
pub mod video_layout;
38
44
pub mod video_pattern;
39
45
pub mod video_receive;
40
46
pub mod video_send;
47
pub mod whiteboard;
41
48
42
49
pub use audio_io::AudioMode;
43
pub use call::{CallOptions, CallReport, CallSpec, run_test_call};
50
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
51
pub use breakout::BreakoutMove;
52
pub use hold::HoldState;
53
pub use whiteboard::ContentShare;
54
pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
44
55
pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};
45
56
pub use end::EndKind;
46
57
pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
@@ -1,7 +1,9 @@1
pub mod audio;1
pub mod audio;2
pub mod audio_io;2
pub mod audio_io;3
pub mod background;3
pub mod call;4
pub mod call;4
pub mod blur;5
pub mod blur;6
pub mod breakout;5
pub mod camera;7
pub mod camera;6
pub mod captions;8
pub mod captions;7
pub mod capture;9
pub mod capture;@@ -11,6 +13,8 @@ pub mod devices;11
pub mod engine;13
pub mod engine;12
pub mod end;14
pub mod end;13
pub mod error;15
pub mod error;16
pub mod hold;17
pub mod join;14
pub mod level;18
pub mod level;15
#[cfg(windows)]19
#[cfg(windows)]16
mod loopback_windows;20
mod loopback_windows;@@ -21,6 +25,7 @@ pub mod organizer;21
pub mod pcm;25
pub mod pcm;22
pub mod push;26
pub mod push;23
pub mod reaction;27
pub mod reaction;28
pub mod recording;24
pub mod relay;29
pub mod relay;25
pub mod renegotiation;30
pub mod renegotiation;26
pub mod ring;31
pub mod ring;@@ -32,15 +37,21 @@ pub mod signaling;32
pub mod sound_capture;37
pub mod sound_capture;33
pub mod state;38
pub mod state;34
pub mod timeline;39
pub mod timeline;40
pub mod transfer;35
pub mod trouter_events;41
pub mod trouter_events;36
pub mod video_frame;42
pub mod video_frame;37
pub mod video_layout;43
pub mod video_layout;38
pub mod video_pattern;44
pub mod video_pattern;39
pub mod video_receive;45
pub mod video_receive;40
pub mod video_send;46
pub mod video_send;47
pub mod whiteboard;41
48
42
pub use audio_io::AudioMode;49
pub use audio_io::AudioMode;43
pub use call::{CallOptions, CallReport, CallSpec, run_test_call};50
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};51
pub use breakout::BreakoutMove;52
pub use hold::HoldState;53
pub use whiteboard::ContentShare;54
pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};44
pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};55
pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};45
pub use end::EndKind;56
pub use end::EndKind;46
pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};57
pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};@@ -6,6 +6,7 @@ use flate2::read::{DeflateDecoder, GzDecoder, ZlibDecoder};
6
6
use serde_json::Value;
7
7
8
8
use crate::error::{Error, Result};
9
use crate::hold::offer_sends_video;
9
10
10
11
pub const EVT_TEAMS_CALL: i64 = 107;
11
12
pub const EVT_GROUP_VIDEO_CALL: i64 = 109;
@@ -118,6 +119,8 @@ fn notification_from(payload: &Value, evt: i64) -> Result<CallNotification> {
118
119
.as_array()
119
120
.is_some_and(|items| items.iter().any(|item| item.as_str() == Some(VIDEO_MODALITY)));
120
121
let invitation = &payload["conversationInvitation"];
122
let offer_sdp = text_of(¬ification["mediaContent"]["blob"]);
123
let offer_has_video = offer_sdp.as_deref().is_some_and(offer_sends_video);
121
124
Ok(CallNotification {
122
125
call_id,
123
126
participant_id,
@@ -126,13 +129,13 @@ fn notification_from(payload: &Value, evt: i64) -> Result<CallNotification> {
126
129
display_name: notification["from"]["displayName"].as_str().unwrap_or_default().to_owned(),
127
130
},
128
131
links,
129
offer_sdp: text_of(¬ification["mediaContent"]["blob"]),
132
offer_sdp,
130
133
controller_name: text_of(¬ification["controllerName"]),
131
134
conversation_controller: text_of(&invitation["conversationController"]),
132
135
is_multi_party: invitation["isMultiParty"].as_bool().unwrap_or(false),
133
136
subject: text_of(&invitation["subject"]),
134
137
thread_id: text_of(&payload["groupChat"]["threadId"]),
135
video: evt == EVT_GROUP_VIDEO_CALL || modalities_have_video,
138
video: evt == EVT_GROUP_VIDEO_CALL || modalities_have_video || offer_has_video,
136
139
})
137
140
}
138
141
@@ -211,6 +214,16 @@ mod tests {
211
214
assert!(incoming(&gp_body(&with_video)).video);
212
215
}
213
216
217
#[test]
218
fn an_offer_that_sends_video_makes_a_video_call_even_without_the_modality() {
219
let mut with_video = payload();
220
let offer = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\na=mid:0\r\na=sendrecv\r\nm=video 1234 RTP/SAVP 102\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\n";
221
with_video["callNotification"]["mediaContent"] = json!({"blob": offer});
222
assert!(incoming(&gp_body(&with_video)).video);
223
with_video["callNotification"]["mediaContent"] = json!({"blob": offer.replace("a=sendrecv\r\na=label:main-video", "a=inactive\r\na=label:main-video")});
224
assert!(!incoming(&gp_body(&with_video)).video);
225
}
226
214
227
#[test]
215
228
fn an_offer_in_the_push_is_kept() {
216
229
let mut with_offer = payload();
@@ -6,6 +6,7 @@ use flate2::read::{DeflateDecoder, GzDecoder, ZlibDecoder};6
use serde_json::Value;6
use serde_json::Value;7
7
8
use crate::error::{Error, Result};8
use crate::error::{Error, Result};9
use crate::hold::offer_sends_video;9
10
10
pub const EVT_TEAMS_CALL: i64 = 107;11
pub const EVT_TEAMS_CALL: i64 = 107;11
pub const EVT_GROUP_VIDEO_CALL: i64 = 109;12
pub const EVT_GROUP_VIDEO_CALL: i64 = 109;@@ -118,6 +119,8 @@ fn notification_from(payload: &Value, evt: i64) -> Result<CallNotification> {118
.as_array()119
.as_array()119
.is_some_and(|items| items.iter().any(|item| item.as_str() == Some(VIDEO_MODALITY)));120
.is_some_and(|items| items.iter().any(|item| item.as_str() == Some(VIDEO_MODALITY)));120
let invitation = &payload["conversationInvitation"];121
let invitation = &payload["conversationInvitation"];122
let offer_sdp = text_of(¬ification["mediaContent"]["blob"]);123
let offer_has_video = offer_sdp.as_deref().is_some_and(offer_sends_video);121
Ok(CallNotification {124
Ok(CallNotification {122
call_id,125
call_id,123
participant_id,126
participant_id,@@ -126,13 +129,13 @@ fn notification_from(payload: &Value, evt: i64) -> Result<CallNotification> {126
display_name: notification["from"]["displayName"].as_str().unwrap_or_default().to_owned(),129
display_name: notification["from"]["displayName"].as_str().unwrap_or_default().to_owned(),127
},130
},128
links,131
links,129
offer_sdp: text_of(¬ification["mediaContent"]["blob"]),132
offer_sdp,130
controller_name: text_of(¬ification["controllerName"]),133
controller_name: text_of(¬ification["controllerName"]),131
conversation_controller: text_of(&invitation["conversationController"]),134
conversation_controller: text_of(&invitation["conversationController"]),132
is_multi_party: invitation["isMultiParty"].as_bool().unwrap_or(false),135
is_multi_party: invitation["isMultiParty"].as_bool().unwrap_or(false),133
subject: text_of(&invitation["subject"]),136
subject: text_of(&invitation["subject"]),134
thread_id: text_of(&payload["groupChat"]["threadId"]),137
thread_id: text_of(&payload["groupChat"]["threadId"]),135
video: evt == EVT_GROUP_VIDEO_CALL || modalities_have_video,138
video: evt == EVT_GROUP_VIDEO_CALL || modalities_have_video || offer_has_video,136
})139
})137
}140
}138
141
@@ -211,6 +214,16 @@ mod tests {211
assert!(incoming(&gp_body(&with_video)).video);214
assert!(incoming(&gp_body(&with_video)).video);212
}215
}213
216
217
#[test]218
fn an_offer_that_sends_video_makes_a_video_call_even_without_the_modality() {219
let mut with_video = payload();220
let offer = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\na=mid:0\r\na=sendrecv\r\nm=video 1234 RTP/SAVP 102\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\n";221
with_video["callNotification"]["mediaContent"] = json!({"blob": offer});222
assert!(incoming(&gp_body(&with_video)).video);223
with_video["callNotification"]["mediaContent"] = json!({"blob": offer.replace("a=sendrecv\r\na=label:main-video", "a=inactive\r\na=label:main-video")});224
assert!(!incoming(&gp_body(&with_video)).video);225
}226
214
#[test]227
#[test]215
fn an_offer_in_the_push_is_kept() {228
fn an_offer_in_the_push_is_kept() {216
let mut with_offer = payload();229
let mut with_offer = payload();@@ -0,0 +1,256 @@
1
use serde_json::{Value, json};
2
3
use crate::captions::{BotAction, recorder_features};
4
use crate::trouter_events::find_key;
5
6
const CLOUD_RECORDING: &str = "cloudRecording";
7
const CONSENT_DETAILS: &str = "recordingConsentDetails";
8
const ACTIVE: &str = "Active";
9
const PROCESSING_MODES: [&str; 2] = ["recording", "realTimeTranscript"];
10
const STORAGE_TYPE: &str = "OnedriveForBusiness";
11
const STORAGE_LOCATION: &str = "Recordings";
12
const RECORDING_MODE: &str = "Normal";
13
const FILE_SUFFIX: &str = "Meeting Recording";
14
const CONSENT_STATE: &str = "consentToRecording";
15
const DENY_STATE: &str = "denyConsentToRecording";
16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18
pub struct StateChange {
19
pub recording: Option<bool>,
20
pub consent_required: Option<bool>,
21
}
22
23
impl StateChange {
24
pub fn is_empty(&self) -> bool {
25
self.recording.is_none() && self.consent_required.is_none()
26
}
27
}
28
29
#[derive(Debug, Clone, Copy, Default)]
30
pub struct RecordingStatus {
31
active: bool,
32
consent_required: bool,
33
sequence: u64,
34
}
35
36
impl RecordingStatus {
37
pub fn active(&self) -> bool {
38
self.active
39
}
40
41
pub fn consent_required(&self) -> bool {
42
self.consent_required
43
}
44
45
pub fn apply(&mut self, body: &Value) -> StateChange {
46
let mut change = StateChange::default();
47
if let Some(state) = find_key(body, CLOUD_RECORDING) {
48
let sequence = state["sequenceNumber"].as_u64().unwrap_or_default();
49
let current = state["value"]["State"].as_str().map(|name| name == ACTIVE);
50
if let Some(current) = current
51
&& sequence >= self.sequence
52
{
53
self.sequence = sequence;
54
if current != self.active {
55
self.active = current;
56
change.recording = Some(current);
57
}
58
}
59
}
60
if let Some(required) = find_key(body, CONSENT_DETAILS).and_then(|details| details["consentActivelyRequired"].as_bool())
61
&& required != self.consent_required
62
{
63
self.consent_required = required;
64
change.consent_required = Some(required);
65
}
66
change
67
}
68
}
69
70
#[derive(Debug, Clone, Copy)]
71
pub struct StartDetails<'a> {
72
pub own_mri: &'a str,
73
pub participant_leg_id: &'a str,
74
pub timestamp: &'a str,
75
pub file_name: &'a str,
76
pub meeting_title: &'a str,
77
pub organizer_name: &'a str,
78
pub correlation_id: &'a str,
79
}
80
81
/// The skype token is added inside the page, so the body travels without it.
82
pub fn start_body(details: StartDetails<'_>) -> Value {
83
json!({
84
"timestamp": details.timestamp,
85
"participantMri": details.own_mri,
86
"participantLegId": details.participant_leg_id,
87
"action": "start",
88
"processingModes": PROCESSING_MODES,
89
"actionParameters": {
90
"recordingFeatures": recorder_features(),
91
"recordingStorageSettings": [{
92
"StorageType": STORAGE_TYPE,
93
"StorageLocation": STORAGE_LOCATION,
94
"FileName": details.file_name,
95
}],
96
"correlationId": details.correlation_id,
97
"meetingTitle": details.meeting_title,
98
"exchangeId": null,
99
"meetingOrganizer": details.organizer_name,
100
"recordingMode": RECORDING_MODE,
101
"spokenLanguage": "",
102
"type": "start",
103
},
104
})
105
}
106
107
pub fn stop_body(own_mri: &str, participant_leg_id: &str, timestamp: &str) -> Value {
108
json!({
109
"timestamp": timestamp,
110
"participantMri": own_mri,
111
"participantLegId": participant_leg_id,
112
"action": "stop",
113
"processingModes": PROCESSING_MODES,
114
})
115
}
116
117
pub fn command_body(action: BotAction, details: StartDetails<'_>) -> Value {
118
match action {
119
BotAction::Start => start_body(details),
120
BotAction::Stop => stop_body(details.own_mri, details.participant_leg_id, details.timestamp),
121
}
122
}
123
124
pub fn file_name(meeting_title: &str, now: chrono::DateTime<chrono::Utc>) -> String {
125
let title = if meeting_title.trim().is_empty() { "Meeting" } else { meeting_title.trim() };
126
let safe: String = title.chars().map(|letter| if letter.is_alphanumeric() || letter == ' ' || letter == '-' { letter } else { '_' }).collect();
127
format!("{safe}-{}-{FILE_SUFFIX}", now.format("%Y%m%d_%H%M%S"))
128
}
129
130
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131
pub enum Consent {
132
Give,
133
Deny,
134
}
135
136
pub fn consent_body(from: Value, sequence_number: u32, consent: Consent) -> Value {
137
let state_type = match consent {
138
Consent::Give => CONSENT_STATE,
139
Consent::Deny => DENY_STATE,
140
};
141
json!({
142
"from": from,
143
"publishedState": {
144
"stateType": state_type,
145
"level": "user",
146
"content": "{}",
147
"sequenceNumber": sequence_number,
148
},
149
})
150
}
151
152
#[cfg(test)]
153
mod tests {
154
use super::*;
155
156
fn update(state: &str, sequence: u64) -> Value {
157
json!({"meetingStates": {"cloudRecording": {"value": {"State": state}, "sequenceNumber": sequence}, "transcription": {"value": {"State": state}, "sequenceNumber": sequence}}})
158
}
159
160
fn consent(required: bool) -> Value {
161
json!({"meetingDetails": {"recordingConsentDetails": {"explicitRecordingConsentEnabled": true, "consentActivelyRequired": required}}})
162
}
163
164
#[test]
165
fn the_recording_state_follows_the_meeting_state_and_ignores_stale_updates() {
166
let mut status = RecordingStatus::default();
167
assert_eq!(status.apply(&update("Active", 3)), StateChange { recording: Some(true), consent_required: None });
168
assert!(status.active());
169
assert!(status.apply(&update("Active", 3)).is_empty());
170
assert!(status.apply(&update("Inactive", 2)).is_empty());
171
assert!(status.active());
172
assert_eq!(status.apply(&update("Inactive", 4)).recording, Some(false));
173
assert!(!status.active());
174
}
175
176
#[test]
177
fn unrelated_updates_change_nothing() {
178
let mut status = RecordingStatus::default();
179
assert!(status.apply(&json!({"activeModalities": {"groupChat": {"threadId": "19:x"}}})).is_empty());
180
assert!(status.apply(&Value::Null).is_empty());
181
}
182
183
#[test]
184
fn consent_is_required_when_the_meeting_says_so() {
185
let mut status = RecordingStatus::default();
186
assert!(status.apply(&consent(false)).is_empty());
187
assert_eq!(status.apply(&consent(true)), StateChange { recording: None, consent_required: Some(true) });
188
assert!(status.consent_required());
189
assert!(status.apply(&consent(true)).is_empty());
190
assert_eq!(status.apply(&consent(false)).consent_required, Some(false));
191
}
192
193
#[test]
194
fn one_update_can_carry_both_states() {
195
let mut both = update("Active", 1);
196
both["meetingDetails"] = consent(true)["meetingDetails"].clone();
197
let change = RecordingStatus::default().apply(&both);
198
assert_eq!(change, StateChange { recording: Some(true), consent_required: Some(true) });
199
}
200
201
fn details() -> StartDetails<'static> {
202
StartDetails {
203
own_mri: "8:orgid:me",
204
participant_leg_id: "leg-1",
205
timestamp: "2026-10-10T08:44:12.705Z",
206
file_name: "Standup-20261010_084412-Meeting Recording",
207
meeting_title: "Standup",
208
organizer_name: "Me",
209
correlation_id: "corr-1",
210
}
211
}
212
213
#[test]
214
fn the_start_command_records_to_onedrive_without_a_mode_key() {
215
let body = command_body(BotAction::Start, details());
216
assert_eq!(body["action"], "start");
217
assert_eq!(body["processingModes"], json!(["recording", "realTimeTranscript"]));
218
assert!(body.get("mode").is_none());
219
assert!(body.get("participantSkypeToken").is_none());
220
let parameters = &body["actionParameters"];
221
assert_eq!(parameters["type"], "start");
222
assert_eq!(parameters["recordingMode"], "Normal");
223
assert_eq!(parameters["meetingTitle"], "Standup");
224
assert_eq!(parameters["recordingStorageSettings"][0]["StorageType"], "OnedriveForBusiness");
225
assert_eq!(parameters["recordingStorageSettings"][0]["StorageLocation"], "Recordings");
226
assert_eq!(parameters["recordingStorageSettings"][0]["FileName"], "Standup-20261010_084412-Meeting Recording");
227
assert_eq!(body["participantLegId"], "leg-1");
228
}
229
230
#[test]
231
fn the_stop_command_is_short() {
232
let body = command_body(BotAction::Stop, details());
233
assert_eq!(body["action"], "stop");
234
assert_eq!(body["processingModes"], json!(["recording", "realTimeTranscript"]));
235
assert!(body.get("actionParameters").is_none());
236
assert_eq!(body["timestamp"], "2026-10-10T08:44:12.705Z");
237
}
238
239
#[test]
240
fn file_names_are_safe_and_stamped() {
241
let at = chrono::DateTime::parse_from_rfc3339("2026-10-10T08:44:12Z").unwrap().with_timezone(&chrono::Utc);
242
assert_eq!(file_name("Q3 / Plan: v2", at), "Q3 _ Plan_ v2-20261010_084412-Meeting Recording");
243
assert_eq!(file_name(" ", at), "Meeting-20261010_084412-Meeting Recording");
244
}
245
246
#[test]
247
fn consent_and_denial_publish_a_user_state() {
248
let given = consent_body(json!({"id": "8:orgid:me"}), 4, Consent::Give);
249
assert_eq!(given["publishedState"]["stateType"], "consentToRecording");
250
assert_eq!(given["publishedState"]["level"], "user");
251
assert_eq!(given["publishedState"]["content"], "{}");
252
assert_eq!(given["publishedState"]["sequenceNumber"], 4);
253
let denied = consent_body(json!({"id": "8:orgid:me"}), 5, Consent::Deny);
254
assert_eq!(denied["publishedState"]["stateType"], "denyConsentToRecording");
255
}
256
}
@@ -0,0 +1,256 @@1
use serde_json::{Value, json};2
3
use crate::captions::{BotAction, recorder_features};4
use crate::trouter_events::find_key;5
6
const CLOUD_RECORDING: &str = "cloudRecording";7
const CONSENT_DETAILS: &str = "recordingConsentDetails";8
const ACTIVE: &str = "Active";9
const PROCESSING_MODES: [&str; 2] = ["recording", "realTimeTranscript"];10
const STORAGE_TYPE: &str = "OnedriveForBusiness";11
const STORAGE_LOCATION: &str = "Recordings";12
const RECORDING_MODE: &str = "Normal";13
const FILE_SUFFIX: &str = "Meeting Recording";14
const CONSENT_STATE: &str = "consentToRecording";15
const DENY_STATE: &str = "denyConsentToRecording";16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]18
pub struct StateChange {19
pub recording: Option<bool>,20
pub consent_required: Option<bool>,21
}22
23
impl StateChange {24
pub fn is_empty(&self) -> bool {25
self.recording.is_none() && self.consent_required.is_none()26
}27
}28
29
#[derive(Debug, Clone, Copy, Default)]30
pub struct RecordingStatus {31
active: bool,32
consent_required: bool,33
sequence: u64,34
}35
36
impl RecordingStatus {37
pub fn active(&self) -> bool {38
self.active39
}40
41
pub fn consent_required(&self) -> bool {42
self.consent_required43
}44
45
pub fn apply(&mut self, body: &Value) -> StateChange {46
let mut change = StateChange::default();47
if let Some(state) = find_key(body, CLOUD_RECORDING) {48
let sequence = state["sequenceNumber"].as_u64().unwrap_or_default();49
let current = state["value"]["State"].as_str().map(|name| name == ACTIVE);50
if let Some(current) = current51
&& sequence >= self.sequence52
{53
self.sequence = sequence;54
if current != self.active {55
self.active = current;56
change.recording = Some(current);57
}58
}59
}60
if let Some(required) = find_key(body, CONSENT_DETAILS).and_then(|details| details["consentActivelyRequired"].as_bool())61
&& required != self.consent_required62
{63
self.consent_required = required;64
change.consent_required = Some(required);65
}66
change67
}68
}69
70
#[derive(Debug, Clone, Copy)]71
pub struct StartDetails<'a> {72
pub own_mri: &'a str,73
pub participant_leg_id: &'a str,74
pub timestamp: &'a str,75
pub file_name: &'a str,76
pub meeting_title: &'a str,77
pub organizer_name: &'a str,78
pub correlation_id: &'a str,79
}80
81
/// The skype token is added inside the page, so the body travels without it.82
pub fn start_body(details: StartDetails<'_>) -> Value {83
json!({84
"timestamp": details.timestamp,85
"participantMri": details.own_mri,86
"participantLegId": details.participant_leg_id,87
"action": "start",88
"processingModes": PROCESSING_MODES,89
"actionParameters": {90
"recordingFeatures": recorder_features(),91
"recordingStorageSettings": [{92
"StorageType": STORAGE_TYPE,93
"StorageLocation": STORAGE_LOCATION,94
"FileName": details.file_name,95
}],96
"correlationId": details.correlation_id,97
"meetingTitle": details.meeting_title,98
"exchangeId": null,99
"meetingOrganizer": details.organizer_name,100
"recordingMode": RECORDING_MODE,101
"spokenLanguage": "",102
"type": "start",103
},104
})105
}106
107
pub fn stop_body(own_mri: &str, participant_leg_id: &str, timestamp: &str) -> Value {108
json!({109
"timestamp": timestamp,110
"participantMri": own_mri,111
"participantLegId": participant_leg_id,112
"action": "stop",113
"processingModes": PROCESSING_MODES,114
})115
}116
117
pub fn command_body(action: BotAction, details: StartDetails<'_>) -> Value {118
match action {119
BotAction::Start => start_body(details),120
BotAction::Stop => stop_body(details.own_mri, details.participant_leg_id, details.timestamp),121
}122
}123
124
pub fn file_name(meeting_title: &str, now: chrono::DateTime<chrono::Utc>) -> String {125
let title = if meeting_title.trim().is_empty() { "Meeting" } else { meeting_title.trim() };126
let safe: String = title.chars().map(|letter| if letter.is_alphanumeric() || letter == ' ' || letter == '-' { letter } else { '_' }).collect();127
format!("{safe}-{}-{FILE_SUFFIX}", now.format("%Y%m%d_%H%M%S"))128
}129
130
#[derive(Debug, Clone, Copy, PartialEq, Eq)]131
pub enum Consent {132
Give,133
Deny,134
}135
136
pub fn consent_body(from: Value, sequence_number: u32, consent: Consent) -> Value {137
let state_type = match consent {138
Consent::Give => CONSENT_STATE,139
Consent::Deny => DENY_STATE,140
};141
json!({142
"from": from,143
"publishedState": {144
"stateType": state_type,145
"level": "user",146
"content": "{}",147
"sequenceNumber": sequence_number,148
},149
})150
}151
152
#[cfg(test)]153
mod tests {154
use super::*;155
156
fn update(state: &str, sequence: u64) -> Value {157
json!({"meetingStates": {"cloudRecording": {"value": {"State": state}, "sequenceNumber": sequence}, "transcription": {"value": {"State": state}, "sequenceNumber": sequence}}})158
}159
160
fn consent(required: bool) -> Value {161
json!({"meetingDetails": {"recordingConsentDetails": {"explicitRecordingConsentEnabled": true, "consentActivelyRequired": required}}})162
}163
164
#[test]165
fn the_recording_state_follows_the_meeting_state_and_ignores_stale_updates() {166
let mut status = RecordingStatus::default();167
assert_eq!(status.apply(&update("Active", 3)), StateChange { recording: Some(true), consent_required: None });168
assert!(status.active());169
assert!(status.apply(&update("Active", 3)).is_empty());170
assert!(status.apply(&update("Inactive", 2)).is_empty());171
assert!(status.active());172
assert_eq!(status.apply(&update("Inactive", 4)).recording, Some(false));173
assert!(!status.active());174
}175
176
#[test]177
fn unrelated_updates_change_nothing() {178
let mut status = RecordingStatus::default();179
assert!(status.apply(&json!({"activeModalities": {"groupChat": {"threadId": "19:x"}}})).is_empty());180
assert!(status.apply(&Value::Null).is_empty());181
}182
183
#[test]184
fn consent_is_required_when_the_meeting_says_so() {185
let mut status = RecordingStatus::default();186
assert!(status.apply(&consent(false)).is_empty());187
assert_eq!(status.apply(&consent(true)), StateChange { recording: None, consent_required: Some(true) });188
assert!(status.consent_required());189
assert!(status.apply(&consent(true)).is_empty());190
assert_eq!(status.apply(&consent(false)).consent_required, Some(false));191
}192
193
#[test]194
fn one_update_can_carry_both_states() {195
let mut both = update("Active", 1);196
both["meetingDetails"] = consent(true)["meetingDetails"].clone();197
let change = RecordingStatus::default().apply(&both);198
assert_eq!(change, StateChange { recording: Some(true), consent_required: Some(true) });199
}200
201
fn details() -> StartDetails<'static> {202
StartDetails {203
own_mri: "8:orgid:me",204
participant_leg_id: "leg-1",205
timestamp: "2026-10-10T08:44:12.705Z",206
file_name: "Standup-20261010_084412-Meeting Recording",207
meeting_title: "Standup",208
organizer_name: "Me",209
correlation_id: "corr-1",210
}211
}212
213
#[test]214
fn the_start_command_records_to_onedrive_without_a_mode_key() {215
let body = command_body(BotAction::Start, details());216
assert_eq!(body["action"], "start");217
assert_eq!(body["processingModes"], json!(["recording", "realTimeTranscript"]));218
assert!(body.get("mode").is_none());219
assert!(body.get("participantSkypeToken").is_none());220
let parameters = &body["actionParameters"];221
assert_eq!(parameters["type"], "start");222
assert_eq!(parameters["recordingMode"], "Normal");223
assert_eq!(parameters["meetingTitle"], "Standup");224
assert_eq!(parameters["recordingStorageSettings"][0]["StorageType"], "OnedriveForBusiness");225
assert_eq!(parameters["recordingStorageSettings"][0]["StorageLocation"], "Recordings");226
assert_eq!(parameters["recordingStorageSettings"][0]["FileName"], "Standup-20261010_084412-Meeting Recording");227
assert_eq!(body["participantLegId"], "leg-1");228
}229
230
#[test]231
fn the_stop_command_is_short() {232
let body = command_body(BotAction::Stop, details());233
assert_eq!(body["action"], "stop");234
assert_eq!(body["processingModes"], json!(["recording", "realTimeTranscript"]));235
assert!(body.get("actionParameters").is_none());236
assert_eq!(body["timestamp"], "2026-10-10T08:44:12.705Z");237
}238
239
#[test]240
fn file_names_are_safe_and_stamped() {241
let at = chrono::DateTime::parse_from_rfc3339("2026-10-10T08:44:12Z").unwrap().with_timezone(&chrono::Utc);242
assert_eq!(file_name("Q3 / Plan: v2", at), "Q3 _ Plan_ v2-20261010_084412-Meeting Recording");243
assert_eq!(file_name(" ", at), "Meeting-20261010_084412-Meeting Recording");244
}245
246
#[test]247
fn consent_and_denial_publish_a_user_state() {248
let given = consent_body(json!({"id": "8:orgid:me"}), 4, Consent::Give);249
assert_eq!(given["publishedState"]["stateType"], "consentToRecording");250
assert_eq!(given["publishedState"]["level"], "user");251
assert_eq!(given["publishedState"]["content"], "{}");252
assert_eq!(given["publishedState"]["sequenceNumber"], 4);253
let denied = consent_body(json!({"id": "8:orgid:me"}), 5, Consent::Deny);254
assert_eq!(denied["publishedState"]["stateType"], "denyConsentToRecording");255
}256
}@@ -10,6 +10,7 @@ pub enum MediaAction {
10
10
ApplyAnswer,
11
11
Escalate,
12
12
ApplyOnNewPeer,
13
ApplyOnSamePeer,
13
14
AnswerOnNewPeer,
14
15
AnswerOnSamePeer,
15
16
RejectGlare,
@@ -20,6 +21,7 @@ pub enum MediaAction {
20
21
pub struct MediaNegotiator {
21
22
path: MediaPath,
22
23
own_offer_pending: bool,
24
same_peer_offer_pending: bool,
23
25
}
24
26
25
27
impl Default for MediaNegotiator {
@@ -27,6 +29,7 @@ impl Default for MediaNegotiator {
27
29
MediaNegotiator {
28
30
path: MediaPath::Pending,
29
31
own_offer_pending: false,
32
same_peer_offer_pending: false,
30
33
}
31
34
}
32
35
}
@@ -54,7 +57,22 @@ impl MediaNegotiator {
54
57
}
55
58
}
56
59
60
pub fn begin_same_peer_offer(&mut self) -> bool {
61
if self.own_offer_pending || self.same_peer_offer_pending {
62
return false;
63
}
64
self.same_peer_offer_pending = true;
65
true
66
}
67
68
pub fn same_peer_offer_failed(&mut self) {
69
self.same_peer_offer_pending = false;
70
}
71
57
72
pub fn on_media_answer(&mut self) -> MediaAction {
73
if std::mem::take(&mut self.same_peer_offer_pending) {
74
return MediaAction::ApplyOnSamePeer;
75
}
58
76
if !self.own_offer_pending {
59
77
return MediaAction::Ignore;
60
78
}
@@ -64,7 +82,7 @@ impl MediaNegotiator {
64
82
}
65
83
66
84
pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {
67
if self.own_offer_pending {
85
if self.own_offer_pending || self.same_peer_offer_pending {
68
86
return MediaAction::RejectGlare;
69
87
}
70
88
if escalation {
@@ -143,6 +161,20 @@ mod tests {
143
161
assert_eq!(negotiator.path(), MediaPath::Mixer);
144
162
}
145
163
164
#[test]
165
fn an_offer_on_the_same_peer_waits_for_its_answer_and_blocks_other_offers() {
166
let mut negotiator = MediaNegotiator::default();
167
negotiator.on_acceptance(false);
168
assert!(negotiator.begin_same_peer_offer());
169
assert!(!negotiator.begin_same_peer_offer());
170
assert_eq!(negotiator.on_renegotiation(false, false), MediaAction::RejectGlare);
171
assert_eq!(negotiator.on_media_answer(), MediaAction::ApplyOnSamePeer);
172
assert_eq!(negotiator.on_media_answer(), MediaAction::Ignore);
173
assert!(negotiator.begin_same_peer_offer());
174
negotiator.same_peer_offer_failed();
175
assert_eq!(negotiator.on_renegotiation(false, false), MediaAction::AnswerOnSamePeer);
176
}
177
146
178
#[test]
147
179
fn two_offers_at_once_are_glare() {
148
180
let mut negotiator = MediaNegotiator::default();
@@ -10,6 +10,7 @@ pub enum MediaAction {10
ApplyAnswer,10
ApplyAnswer,11
Escalate,11
Escalate,12
ApplyOnNewPeer,12
ApplyOnNewPeer,13
ApplyOnSamePeer,13
AnswerOnNewPeer,14
AnswerOnNewPeer,14
AnswerOnSamePeer,15
AnswerOnSamePeer,15
RejectGlare,16
RejectGlare,@@ -20,6 +21,7 @@ pub enum MediaAction {20
pub struct MediaNegotiator {21
pub struct MediaNegotiator {21
path: MediaPath,22
path: MediaPath,22
own_offer_pending: bool,23
own_offer_pending: bool,24
same_peer_offer_pending: bool,23
}25
}24
26
25
impl Default for MediaNegotiator {27
impl Default for MediaNegotiator {@@ -27,6 +29,7 @@ impl Default for MediaNegotiator {27
MediaNegotiator {29
MediaNegotiator {28
path: MediaPath::Pending,30
path: MediaPath::Pending,29
own_offer_pending: false,31
own_offer_pending: false,32
same_peer_offer_pending: false,30
}33
}31
}34
}32
}35
}@@ -54,7 +57,22 @@ impl MediaNegotiator {54
}57
}55
}58
}56
59
60
pub fn begin_same_peer_offer(&mut self) -> bool {61
if self.own_offer_pending || self.same_peer_offer_pending {62
return false;63
}64
self.same_peer_offer_pending = true;65
true66
}67
68
pub fn same_peer_offer_failed(&mut self) {69
self.same_peer_offer_pending = false;70
}71
57
pub fn on_media_answer(&mut self) -> MediaAction {72
pub fn on_media_answer(&mut self) -> MediaAction {73
if std::mem::take(&mut self.same_peer_offer_pending) {74
return MediaAction::ApplyOnSamePeer;75
}58
if !self.own_offer_pending {76
if !self.own_offer_pending {59
return MediaAction::Ignore;77
return MediaAction::Ignore;60
}78
}@@ -64,7 +82,7 @@ impl MediaNegotiator {64
}82
}65
83
66
pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {84
pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {67
if self.own_offer_pending {85
if self.own_offer_pending || self.same_peer_offer_pending {68
return MediaAction::RejectGlare;86
return MediaAction::RejectGlare;69
}87
}70
if escalation {88
if escalation {@@ -143,6 +161,20 @@ mod tests {143
assert_eq!(negotiator.path(), MediaPath::Mixer);161
assert_eq!(negotiator.path(), MediaPath::Mixer);144
}162
}145
163
164
#[test]165
fn an_offer_on_the_same_peer_waits_for_its_answer_and_blocks_other_offers() {166
let mut negotiator = MediaNegotiator::default();167
negotiator.on_acceptance(false);168
assert!(negotiator.begin_same_peer_offer());169
assert!(!negotiator.begin_same_peer_offer());170
assert_eq!(negotiator.on_renegotiation(false, false), MediaAction::RejectGlare);171
assert_eq!(negotiator.on_media_answer(), MediaAction::ApplyOnSamePeer);172
assert_eq!(negotiator.on_media_answer(), MediaAction::Ignore);173
assert!(negotiator.begin_same_peer_offer());174
negotiator.same_peer_offer_failed();175
assert_eq!(negotiator.on_renegotiation(false, false), MediaAction::AnswerOnSamePeer);176
}177
146
#[test]178
#[test]147
fn two_offers_at_once_are_glare() {179
fn two_offers_at_once_are_glare() {148
let mut negotiator = MediaNegotiator::default();180
let mut negotiator = MediaNegotiator::default();@@ -24,6 +24,7 @@ pub struct CaptionBot {
24
24
pub mri: String,
25
25
pub command_url: Option<String>,
26
26
pub active: bool,
27
pub recording: bool,
27
28
}
28
29
29
30
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -222,7 +223,8 @@ fn caption_bot(mri: &str, endpoints: &[&Value]) -> Option<CaptionBot> {
222
223
let command_url = metadata.iter().find_map(|metadata| metadata["commandUrl"].as_str()).map(str::to_owned);
223
224
let known = command_url.is_some() || metadata.iter().any(|metadata| metadata["processingModes"].is_object());
224
225
let active = metadata.iter().any(|metadata| metadata["processingModes"]["closedCaptions"]["state"].as_str() == Some("Active"));
225
known.then(|| CaptionBot { mri: mri.to_owned(), command_url, active })
226
let recording = metadata.iter().any(|metadata| metadata["processingModes"]["recording"]["state"].as_str() == Some("Active"));
227
known.then(|| CaptionBot { mri: mri.to_owned(), command_url, active, recording })
226
228
}
227
229
228
230
fn published_state(participant: &Value, endpoints: &[&Value], state_type: &str) -> Option<PublishedState> {
@@ -24,6 +24,7 @@ pub struct CaptionBot {24
pub mri: String,24
pub mri: String,25
pub command_url: Option<String>,25
pub command_url: Option<String>,26
pub active: bool,26
pub active: bool,27
pub recording: bool,27
}28
}28
29
29
#[derive(Debug, Clone, PartialEq, Eq)]30
#[derive(Debug, Clone, PartialEq, Eq)]@@ -222,7 +223,8 @@ fn caption_bot(mri: &str, endpoints: &[&Value]) -> Option<CaptionBot> {222
let command_url = metadata.iter().find_map(|metadata| metadata["commandUrl"].as_str()).map(str::to_owned);223
let command_url = metadata.iter().find_map(|metadata| metadata["commandUrl"].as_str()).map(str::to_owned);223
let known = command_url.is_some() || metadata.iter().any(|metadata| metadata["processingModes"].is_object());224
let known = command_url.is_some() || metadata.iter().any(|metadata| metadata["processingModes"].is_object());224
let active = metadata.iter().any(|metadata| metadata["processingModes"]["closedCaptions"]["state"].as_str() == Some("Active"));225
let active = metadata.iter().any(|metadata| metadata["processingModes"]["closedCaptions"]["state"].as_str() == Some("Active"));225
known.then(|| CaptionBot { mri: mri.to_owned(), command_url, active })226
let recording = metadata.iter().any(|metadata| metadata["processingModes"]["recording"]["state"].as_str() == Some("Active"));227
known.then(|| CaptionBot { mri: mri.to_owned(), command_url, active, recording })226
}228
}227
229
228
fn published_state(participant: &Value, endpoints: &[&Value], state_type: &str) -> Option<PublishedState> {230
fn published_state(participant: &Value, endpoints: &[&Value], state_type: &str) -> Option<PublishedState> {@@ -1131,6 +1131,37 @@ mod tests {
1131
1131
assert_eq!(parsed.media[1].direction(), Some("inactive"));
1132
1132
}
1133
1133
1134
const ONE_TO_ONE_VIDEO_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\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\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na=sendrecv\r\na=label:applicationsharing-video\r\n";
1135
1136
fn browser_answer(camera_direction: &str, share_port: &str, share_direction: &str) -> String {
1137
format!("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 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 9 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={camera_direction}\r\na=ssrc:8 cname:x\r\nm=video {share_port} UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na={share_direction}\r\n")
1138
}
1139
1140
#[test]
1141
fn a_one_to_one_offer_keeps_a_camera_line_and_a_sharing_line() {
1142
let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1143
let roles: Vec<LineRole> = remote.lines.iter().map(|line| line.role).collect();
1144
assert_eq!(roles, vec![LineRole::MainAudio, LineRole::MainVideo, LineRole::ScreenShare]);
1145
assert_eq!(remote.plan().screen_share_mids, vec!["2".to_owned()]);
1146
assert!(remote.plan().gallery_mids.is_empty());
1147
assert_eq!(parse(&remote.browser_sdp).unwrap().media.iter().filter(|media| media.kind == "video").count(), 2);
1148
}
1149
1150
#[test]
1151
fn accepting_with_audio_answers_the_video_line_receive_only_and_with_video_sending() {
1152
let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1153
for (camera_direction, expected) in [("recvonly", "recvonly"), ("sendrecv", "sendrecv")] {
1154
let answer = to_teams_answer(&browser_answer(camera_direction, "0", "inactive"), &remote, &mut counter()).unwrap();
1155
let parsed = parse(&answer.sdp).unwrap();
1156
assert_eq!(parsed.media.len(), 3);
1157
assert_eq!(parsed.media[1].port, "1234");
1158
assert_eq!(parsed.media[1].direction(), Some(expected));
1159
assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1160
assert_eq!(parsed.media[2].port, "0");
1161
assert_eq!(parsed.media[2].value("label"), Some("applicationsharing-video"));
1162
}
1163
}
1164
1134
1165
#[test]
1135
1166
fn folded_gallery_lines_expand_below_their_carrier_mid() {
1136
1167
assert_eq!(folded_mids("17", 8), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());
@@ -1131,6 +1131,37 @@ mod tests {1131
assert_eq!(parsed.media[1].direction(), Some("inactive"));1131
assert_eq!(parsed.media[1].direction(), Some("inactive"));1132
}1132
}1133
1133
1134
const ONE_TO_ONE_VIDEO_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\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\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na=sendrecv\r\na=label:applicationsharing-video\r\n";1135
1136
fn browser_answer(camera_direction: &str, share_port: &str, share_direction: &str) -> String {1137
format!("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 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 9 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={camera_direction}\r\na=ssrc:8 cname:x\r\nm=video {share_port} UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na={share_direction}\r\n")1138
}1139
1140
#[test]1141
fn a_one_to_one_offer_keeps_a_camera_line_and_a_sharing_line() {1142
let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();1143
let roles: Vec<LineRole> = remote.lines.iter().map(|line| line.role).collect();1144
assert_eq!(roles, vec![LineRole::MainAudio, LineRole::MainVideo, LineRole::ScreenShare]);1145
assert_eq!(remote.plan().screen_share_mids, vec!["2".to_owned()]);1146
assert!(remote.plan().gallery_mids.is_empty());1147
assert_eq!(parse(&remote.browser_sdp).unwrap().media.iter().filter(|media| media.kind == "video").count(), 2);1148
}1149
1150
#[test]1151
fn accepting_with_audio_answers_the_video_line_receive_only_and_with_video_sending() {1152
let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();1153
for (camera_direction, expected) in [("recvonly", "recvonly"), ("sendrecv", "sendrecv")] {1154
let answer = to_teams_answer(&browser_answer(camera_direction, "0", "inactive"), &remote, &mut counter()).unwrap();1155
let parsed = parse(&answer.sdp).unwrap();1156
assert_eq!(parsed.media.len(), 3);1157
assert_eq!(parsed.media[1].port, "1234");1158
assert_eq!(parsed.media[1].direction(), Some(expected));1159
assert_eq!(parsed.media[1].value("label"), Some("main-video"));1160
assert_eq!(parsed.media[2].port, "0");1161
assert_eq!(parsed.media[2].value("label"), Some("applicationsharing-video"));1162
}1163
}1164
1134
#[test]1165
#[test]1135
fn folded_gallery_lines_expand_below_their_carrier_mid() {1166
fn folded_gallery_lines_expand_below_their_carrier_mid() {1136
assert_eq!(folded_mids("17", 8), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());1167
assert_eq!(folded_mids("17", 8), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());@@ -4,6 +4,8 @@ use serde_json::{Map, Value, json};
4
4
use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};
5
5
6
6
use crate::captions::{self, BotAction};
7
use crate::recording::{self, Consent, StartDetails};
8
use crate::transfer::{self, TransferTarget};
7
9
use crate::error::{Error, Result};
8
10
use crate::organizer::{self, Target};
9
11
use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
@@ -24,7 +26,7 @@ const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".
24
26
const BACKEND_SUFFIX: &str = ".skype.com";
25
27
const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";
26
28
const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
27
const CONVERSATION_LINK_NAMES: [&str; 9] = [
29
const CONVERSATION_LINK_NAMES: [&str; 11] = [
28
30
"conversationEnd",
29
31
"conversationUpdate",
30
32
"localParticipantUpdate",
@@ -34,6 +36,8 @@ const CONVERSATION_LINK_NAMES: [&str; 9] = [
34
36
"addModalityFailure",
35
37
"confirmUnmute",
36
38
"receiveMessage",
39
"contentSharingUpdate",
40
"contentSharingEnd",
37
41
];
38
42
const SUBSCRIBE_LINK_NAMES: [&str; 6] = [
39
43
"conversationEnd",
@@ -192,6 +196,7 @@ pub struct Invitation<'a> {
192
196
pub media_leg_id: &'a str,
193
197
pub callbacks: &'a CallbackLinks,
194
198
pub target: &'a InviteTarget,
199
pub modalities: &'a [String],
195
200
}
196
201
197
202
pub struct Answer<'a> {
@@ -291,6 +296,19 @@ impl Signaling {
291
296
conversation_from(&response.body)
292
297
}
293
298
299
/// Opens a roster-only conversation for the meeting ID; the caller leaves it once the target is read.
300
pub async fn resolve_meeting(
301
&self,
302
from: &Participant,
303
callbacks: &CallbackLinks,
304
meeting_data: &Value,
305
) -> Result<(MeetingTarget, Conversation)> {
306
let body = crate::join::resolve_body(from, callbacks, meeting_data);
307
let response = self.send("POST epconv resolve", Method::Post, EPCONV_URL, Some(body)).await?;
308
let target = crate::join::target_from_answer(&response.body, meeting_data)?;
309
Ok((target, conversation_from(&response.body)?))
310
}
311
294
312
/// Joins with the offer; the answer may restate the conversation links, otherwise the subscribed ones stay.
295
313
pub async fn join_meeting(&self, subscribed: &Conversation, invitation: &Invitation<'_>) -> Result<Conversation> {
296
314
let response = self
@@ -437,17 +455,21 @@ impl Signaling {
437
455
from: &Participant,
438
456
thread_id: &str,
439
457
callbacks: &CallbackLinks,
440
) -> Result<()> {
458
) -> Result<u16> {
441
459
let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks);
442
460
let mut request = self.request(Method::Post, conversation.link("addParticipantAndModality")?, Some(body));
443
461
request = request.with_body_token(captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER);
444
self.exchange(&self.session, "POST add (caption bot)", request).await.map(|_| ())
462
self.exchange(&self.session, "POST add (caption bot)", request).await.map(|response| response.status)
445
463
}
446
464
447
465
pub async fn caption_command(&self, command_url: &str, action: BotAction, from: &Participant) -> Result<()> {
448
466
ensure_teams_url(command_url)?;
449
467
let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
450
468
let body = captions::command_body(action, &from.mri, &from.participant_id, ×tamp);
469
self.bot_command(command_url, body, "caption command").await.map(|_| ())
470
}
471
472
async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {
451
473
let arguments = json!({
452
474
"url": command_url,
453
475
"body": body,
@@ -458,12 +480,40 @@ impl Signaling {
458
480
});
459
481
let answer = self.session.run_with_token(App::Teams, &spaces_scope(), captions::COMMAND_SCRIPT, &arguments, false).await?;
460
482
let status = answer["status"].as_u64().unwrap_or_default();
461
self.timeline.record("POST caption command", format!("HTTP {status}"));
483
self.timeline.record(format!("POST {label}"), format!("HTTP {status}"));
462
484
if (200..300).contains(&status) {
463
return Ok(());
485
return Ok(status as u16);
464
486
}
465
487
let reason = answer["error"].as_str().unwrap_or("no answer");
466
Err(Error::Signaling(format!("caption command answered HTTP {status} {reason}")))
488
Err(Error::Signaling(format!("{label} answered HTTP {status} {reason}")))
489
}
490
491
pub async fn recording_command(&self, command_url: &str, action: BotAction, from: &Participant, title: &str) -> Result<u16> {
492
ensure_teams_url(command_url)?;
493
let now = chrono::Utc::now();
494
let timestamp = now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
495
let file_name = recording::file_name(title, now);
496
let correlation_id = uuid::Uuid::new_v4().to_string();
497
let details = StartDetails {
498
own_mri: &from.mri,
499
participant_leg_id: &from.participant_id,
500
timestamp: ×tamp,
501
file_name: &file_name,
502
meeting_title: title,
503
organizer_name: &from.display_name,
504
correlation_id: &correlation_id,
505
};
506
self.bot_command(command_url, recording::command_body(action, details), "recording command").await
507
}
508
509
pub async fn consent_to_recording(&self, conversation: &Conversation, from: &Participant, consent: Consent) -> Result<u16> {
510
let body = recording::consent_body(from.wire(), self.next_state_sequence(), consent);
511
self.send("POST publishState (recording consent)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
512
}
513
514
pub async fn transfer(&self, transfer_url: &str, from: &Participant, target: TransferTarget<'_>, callbacks: &CallbackLinks) -> Result<()> {
515
let body = transfer::transfer_body(from, target, callbacks);
516
self.post_json("POST transfer", transfer_url, body).await
467
517
}
468
518
469
519
/// One broker long poll; answers the next subscribe URL.
@@ -547,7 +597,7 @@ fn conversation_properties() -> Value {
547
597
})
548
598
}
549
599
550
fn endpoint_state() -> Value {
600
pub(crate) fn endpoint_state() -> Value {
551
601
json!({
552
602
"endpointStateSequenceNumber": 2,
553
603
"endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},
@@ -625,7 +675,7 @@ pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
625
675
"meetingData": meeting_data,
626
676
"endpointState": endpoint_state(),
627
677
"callInvitation": {
628
"callModalities": AUDIO_MODALITIES,
678
"callModalities": invitation.modalities,
629
679
"replaces": null,
630
680
"transferor": null,
631
681
"clientTransferContext": null,
@@ -639,13 +689,17 @@ pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
639
689
})
640
690
}
641
691
692
pub(crate) fn subscribe_request(callbacks: &CallbackLinks) -> Value {
693
json!({
694
"roster": roster_request(callbacks),
695
"properties": conversation_properties(),
696
"links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
697
})
698
}
699
642
700
pub fn subscribe_body(from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget) -> Value {
643
701
json!({
644
"conversationRequest": {
645
"roster": roster_request(callbacks),
646
"properties": conversation_properties(),
647
"links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),
648
},
702
"conversationRequest": subscribe_request(callbacks),
649
703
"participants": {"from": from.wire()},
650
704
"groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID},
651
705
"meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id},
@@ -732,23 +786,25 @@ pub fn renegotiation_body(
732
786
callbacks: &CallbackLinks,
733
787
offer_sdp: &str,
734
788
media_leg_id: &str,
789
modalities: &[String],
790
new_offer: bool,
735
791
) -> Value {
736
792
json!({
737
793
"mediaNegotiation": {
738
"callModalities": AUDIO_MODALITIES,
794
"callModalities": modalities,
739
795
"sender": from.wire(),
740
796
"links": {
741
797
"mediaAnswer": callbacks.call("mediaAnswer"),
742
798
"rejection": callbacks.call("rejection"),
743
799
},
744
"mediaContent": renegotiation_content(offer_sdp, media_leg_id),
800
"mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer),
745
801
},
746
802
})
747
803
}
748
804
749
fn renegotiation_content(sdp: &str, media_leg_id: &str) -> Value {
805
fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool) -> Value {
750
806
let mut content = media_content(sdp, media_leg_id, true);
751
content["newOffer"] = json!(true);
807
content["newOffer"] = json!(new_offer);
752
808
content
753
809
}
754
810
@@ -936,6 +992,7 @@ mod tests {
936
992
media_leg_id: "AB",
937
993
callbacks: &callbacks,
938
994
target,
995
modalities: &["Audio".to_owned()],
939
996
})
940
997
}
941
998
@@ -982,7 +1039,7 @@ mod tests {
982
1039
assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
983
1040
assert_eq!(body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE);
984
1041
assert!(body["callInvitation"]["links"]["acceptance"].as_str().unwrap().ends_with("/call/acceptance/"));
985
assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 9);
1042
assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 11);
986
1043
}
987
1044
988
1045
#[test]
@@ -1137,9 +1194,13 @@ mod tests {
1137
1194
fn renegotiation_messages_name_their_reply_links() {
1138
1195
let from = from();
1139
1196
let callbacks = callbacks();
1140
let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB");
1197
let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned()], true);
1141
1198
let negotiation = &offer["mediaNegotiation"];
1142
1199
assert_eq!(negotiation["mediaContent"]["newOffer"], true);
1200
assert_eq!(negotiation["callModalities"], json!(["Audio"]));
1201
let same_peer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned(), "Video".to_owned()], false);
1202
assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["newOffer"], false);
1203
assert_eq!(same_peer["mediaNegotiation"]["callModalities"], json!(["Audio", "Video"]));
1143
1204
assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));
1144
1205
assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));
1145
1206
let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB");
@@ -1149,6 +1210,16 @@ mod tests {
1149
1210
.ends_with("/call/mediaAcknowledgement/"));
1150
1211
}
1151
1212
1213
#[test]
1214
fn a_video_call_invites_with_audio_and_video() {
1215
let from = from();
1216
let callbacks = callbacks();
1217
let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1218
let modalities = vec!["Audio".to_owned(), "Video".to_owned()];
1219
let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities });
1220
assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio", "Video"]));
1221
}
1222
1152
1223
#[test]
1153
1224
fn ringing_progress_names_the_sender() {
1154
1225
let body = ringing_body(&from());
@@ -4,6 +4,8 @@ use serde_json::{Map, Value, json};4
use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};4
use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};5
5
6
use crate::captions::{self, BotAction};6
use crate::captions::{self, BotAction};7
use crate::recording::{self, Consent, StartDetails};8
use crate::transfer::{self, TransferTarget};7
use crate::error::{Error, Result};9
use crate::error::{Error, Result};8
use crate::organizer::{self, Target};10
use crate::organizer::{self, Target};9
use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};11
use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};@@ -24,7 +26,7 @@ const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".24
const BACKEND_SUFFIX: &str = ".skype.com";26
const BACKEND_SUFFIX: &str = ".skype.com";25
const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";27
const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";26
const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";28
const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";27
const CONVERSATION_LINK_NAMES: [&str; 9] = [29
const CONVERSATION_LINK_NAMES: [&str; 11] = [28
"conversationEnd",30
"conversationEnd",29
"conversationUpdate",31
"conversationUpdate",30
"localParticipantUpdate",32
"localParticipantUpdate",@@ -34,6 +36,8 @@ const CONVERSATION_LINK_NAMES: [&str; 9] = [34
"addModalityFailure",36
"addModalityFailure",35
"confirmUnmute",37
"confirmUnmute",36
"receiveMessage",38
"receiveMessage",39
"contentSharingUpdate",40
"contentSharingEnd",37
];41
];38
const SUBSCRIBE_LINK_NAMES: [&str; 6] = [42
const SUBSCRIBE_LINK_NAMES: [&str; 6] = [39
"conversationEnd",43
"conversationEnd",@@ -192,6 +196,7 @@ pub struct Invitation<'a> {192
pub media_leg_id: &'a str,196
pub media_leg_id: &'a str,193
pub callbacks: &'a CallbackLinks,197
pub callbacks: &'a CallbackLinks,194
pub target: &'a InviteTarget,198
pub target: &'a InviteTarget,199
pub modalities: &'a [String],195
}200
}196
201
197
pub struct Answer<'a> {202
pub struct Answer<'a> {@@ -291,6 +296,19 @@ impl Signaling {291
conversation_from(&response.body)296
conversation_from(&response.body)292
}297
}293
298
299
/// Opens a roster-only conversation for the meeting ID; the caller leaves it once the target is read.300
pub async fn resolve_meeting(301
&self,302
from: &Participant,303
callbacks: &CallbackLinks,304
meeting_data: &Value,305
) -> Result<(MeetingTarget, Conversation)> {306
let body = crate::join::resolve_body(from, callbacks, meeting_data);307
let response = self.send("POST epconv resolve", Method::Post, EPCONV_URL, Some(body)).await?;308
let target = crate::join::target_from_answer(&response.body, meeting_data)?;309
Ok((target, conversation_from(&response.body)?))310
}311
294
/// Joins with the offer; the answer may restate the conversation links, otherwise the subscribed ones stay.312
/// Joins with the offer; the answer may restate the conversation links, otherwise the subscribed ones stay.295
pub async fn join_meeting(&self, subscribed: &Conversation, invitation: &Invitation<'_>) -> Result<Conversation> {313
pub async fn join_meeting(&self, subscribed: &Conversation, invitation: &Invitation<'_>) -> Result<Conversation> {296
let response = self314
let response = self@@ -437,17 +455,21 @@ impl Signaling {437
from: &Participant,455
from: &Participant,438
thread_id: &str,456
thread_id: &str,439
callbacks: &CallbackLinks,457
callbacks: &CallbackLinks,440
) -> Result<()> {458
) -> Result<u16> {441
let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks);459
let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks);442
let mut request = self.request(Method::Post, conversation.link("addParticipantAndModality")?, Some(body));460
let mut request = self.request(Method::Post, conversation.link("addParticipantAndModality")?, Some(body));443
request = request.with_body_token(captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER);461
request = request.with_body_token(captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER);444
self.exchange(&self.session, "POST add (caption bot)", request).await.map(|_| ())462
self.exchange(&self.session, "POST add (caption bot)", request).await.map(|response| response.status)445
}463
}446
464
447
pub async fn caption_command(&self, command_url: &str, action: BotAction, from: &Participant) -> Result<()> {465
pub async fn caption_command(&self, command_url: &str, action: BotAction, from: &Participant) -> Result<()> {448
ensure_teams_url(command_url)?;466
ensure_teams_url(command_url)?;449
let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);467
let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);450
let body = captions::command_body(action, &from.mri, &from.participant_id, ×tamp);468
let body = captions::command_body(action, &from.mri, &from.participant_id, ×tamp);469
self.bot_command(command_url, body, "caption command").await.map(|_| ())470
}471
472
async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {451
let arguments = json!({473
let arguments = json!({452
"url": command_url,474
"url": command_url,453
"body": body,475
"body": body,@@ -458,12 +480,40 @@ impl Signaling {458
});480
});459
let answer = self.session.run_with_token(App::Teams, &spaces_scope(), captions::COMMAND_SCRIPT, &arguments, false).await?;481
let answer = self.session.run_with_token(App::Teams, &spaces_scope(), captions::COMMAND_SCRIPT, &arguments, false).await?;460
let status = answer["status"].as_u64().unwrap_or_default();482
let status = answer["status"].as_u64().unwrap_or_default();461
self.timeline.record("POST caption command", format!("HTTP {status}"));483
self.timeline.record(format!("POST {label}"), format!("HTTP {status}"));462
if (200..300).contains(&status) {484
if (200..300).contains(&status) {463
return Ok(());485
return Ok(status as u16);464
}486
}465
let reason = answer["error"].as_str().unwrap_or("no answer");487
let reason = answer["error"].as_str().unwrap_or("no answer");466
Err(Error::Signaling(format!("caption command answered HTTP {status} {reason}")))488
Err(Error::Signaling(format!("{label} answered HTTP {status} {reason}")))489
}490
491
pub async fn recording_command(&self, command_url: &str, action: BotAction, from: &Participant, title: &str) -> Result<u16> {492
ensure_teams_url(command_url)?;493
let now = chrono::Utc::now();494
let timestamp = now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);495
let file_name = recording::file_name(title, now);496
let correlation_id = uuid::Uuid::new_v4().to_string();497
let details = StartDetails {498
own_mri: &from.mri,499
participant_leg_id: &from.participant_id,500
timestamp: ×tamp,501
file_name: &file_name,502
meeting_title: title,503
organizer_name: &from.display_name,504
correlation_id: &correlation_id,505
};506
self.bot_command(command_url, recording::command_body(action, details), "recording command").await507
}508
509
pub async fn consent_to_recording(&self, conversation: &Conversation, from: &Participant, consent: Consent) -> Result<u16> {510
let body = recording::consent_body(from.wire(), self.next_state_sequence(), consent);511
self.send("POST publishState (recording consent)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)512
}513
514
pub async fn transfer(&self, transfer_url: &str, from: &Participant, target: TransferTarget<'_>, callbacks: &CallbackLinks) -> Result<()> {515
let body = transfer::transfer_body(from, target, callbacks);516
self.post_json("POST transfer", transfer_url, body).await467
}517
}468
518
469
/// One broker long poll; answers the next subscribe URL.519
/// One broker long poll; answers the next subscribe URL.@@ -547,7 +597,7 @@ fn conversation_properties() -> Value {547
})597
})548
}598
}549
599
550
fn endpoint_state() -> Value {600
pub(crate) fn endpoint_state() -> Value {551
json!({601
json!({552
"endpointStateSequenceNumber": 2,602
"endpointStateSequenceNumber": 2,553
"endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},603
"endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}},@@ -625,7 +675,7 @@ pub fn epconv_body(invitation: &Invitation<'_>) -> Value {625
"meetingData": meeting_data,675
"meetingData": meeting_data,626
"endpointState": endpoint_state(),676
"endpointState": endpoint_state(),627
"callInvitation": {677
"callInvitation": {628
"callModalities": AUDIO_MODALITIES,678
"callModalities": invitation.modalities,629
"replaces": null,679
"replaces": null,630
"transferor": null,680
"transferor": null,631
"clientTransferContext": null,681
"clientTransferContext": null,@@ -639,13 +689,17 @@ pub fn epconv_body(invitation: &Invitation<'_>) -> Value {639
})689
})640
}690
}641
691
692
pub(crate) fn subscribe_request(callbacks: &CallbackLinks) -> Value {693
json!({694
"roster": roster_request(callbacks),695
"properties": conversation_properties(),696
"links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),697
})698
}699
642
pub fn subscribe_body(from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget) -> Value {700
pub fn subscribe_body(from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget) -> Value {643
json!({701
json!({644
"conversationRequest": {702
"conversationRequest": subscribe_request(callbacks),645
"roster": roster_request(callbacks),646
"properties": conversation_properties(),647
"links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)),648
},649
"participants": {"from": from.wire()},703
"participants": {"from": from.wire()},650
"groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID},704
"groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID},651
"meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id},705
"meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id},@@ -732,23 +786,25 @@ pub fn renegotiation_body(732
callbacks: &CallbackLinks,786
callbacks: &CallbackLinks,733
offer_sdp: &str,787
offer_sdp: &str,734
media_leg_id: &str,788
media_leg_id: &str,789
modalities: &[String],790
new_offer: bool,735
) -> Value {791
) -> Value {736
json!({792
json!({737
"mediaNegotiation": {793
"mediaNegotiation": {738
"callModalities": AUDIO_MODALITIES,794
"callModalities": modalities,739
"sender": from.wire(),795
"sender": from.wire(),740
"links": {796
"links": {741
"mediaAnswer": callbacks.call("mediaAnswer"),797
"mediaAnswer": callbacks.call("mediaAnswer"),742
"rejection": callbacks.call("rejection"),798
"rejection": callbacks.call("rejection"),743
},799
},744
"mediaContent": renegotiation_content(offer_sdp, media_leg_id),800
"mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer),745
},801
},746
})802
})747
}803
}748
804
749
fn renegotiation_content(sdp: &str, media_leg_id: &str) -> Value {805
fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool) -> Value {750
let mut content = media_content(sdp, media_leg_id, true);806
let mut content = media_content(sdp, media_leg_id, true);751
content["newOffer"] = json!(true);807
content["newOffer"] = json!(new_offer);752
content808
content753
}809
}754
810
@@ -936,6 +992,7 @@ mod tests {936
media_leg_id: "AB",992
media_leg_id: "AB",937
callbacks: &callbacks,993
callbacks: &callbacks,938
target,994
target,995
modalities: &["Audio".to_owned()],939
})996
})940
}997
}941
998
@@ -982,7 +1039,7 @@ mod tests {982
assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));1039
assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));983
assert_eq!(body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE);1040
assert_eq!(body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE);984
assert!(body["callInvitation"]["links"]["acceptance"].as_str().unwrap().ends_with("/call/acceptance/"));1041
assert!(body["callInvitation"]["links"]["acceptance"].as_str().unwrap().ends_with("/call/acceptance/"));985
assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 9);1042
assert_eq!(body["conversationRequest"]["links"].as_object().unwrap().len(), 11);986
}1043
}987
1044
988
#[test]1045
#[test]@@ -1137,9 +1194,13 @@ mod tests {1137
fn renegotiation_messages_name_their_reply_links() {1194
fn renegotiation_messages_name_their_reply_links() {1138
let from = from();1195
let from = from();1139
let callbacks = callbacks();1196
let callbacks = callbacks();1140
let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB");1197
let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned()], true);1141
let negotiation = &offer["mediaNegotiation"];1198
let negotiation = &offer["mediaNegotiation"];1142
assert_eq!(negotiation["mediaContent"]["newOffer"], true);1199
assert_eq!(negotiation["mediaContent"]["newOffer"], true);1200
assert_eq!(negotiation["callModalities"], json!(["Audio"]));1201
let same_peer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned(), "Video".to_owned()], false);1202
assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["newOffer"], false);1203
assert_eq!(same_peer["mediaNegotiation"]["callModalities"], json!(["Audio", "Video"]));1143
assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));1204
assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));1144
assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));1205
assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));1145
let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB");1206
let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB");@@ -1149,6 +1210,16 @@ mod tests {1149
.ends_with("/call/mediaAcknowledgement/"));1210
.ends_with("/call/mediaAcknowledgement/"));1150
}1211
}1151
1212
1213
#[test]1214
fn a_video_call_invites_with_audio_and_video() {1215
let from = from();1216
let callbacks = callbacks();1217
let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };1218
let modalities = vec!["Audio".to_owned(), "Video".to_owned()];1219
let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities });1220
assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio", "Video"]));1221
}1222
1152
#[test]1223
#[test]1153
fn ringing_progress_names_the_sender() {1224
fn ringing_progress_names_the_sender() {1154
let body = ringing_body(&from());1225
let body = ringing_body(&from());@@ -0,0 +1,107 @@
1
use serde_json::{Value, json};
2
3
use crate::signaling::Participant;
4
use crate::trouter_events::CallbackLinks;
5
6
#[derive(Debug, Clone, Copy)]
7
pub struct TransferTarget<'a> {
8
pub mri: &'a str,
9
pub replaces: Option<&'a str>,
10
}
11
12
fn transferor(from: &Participant) -> Value {
13
json!({
14
"details": {
15
"id": from.mri,
16
"endpointId": from.endpoint_id,
17
"participantId": from.participant_id,
18
"languageId": from.language_id,
19
},
20
"authorizationToken": null,
21
})
22
}
23
24
pub fn transfer_body(from: &Participant, target: TransferTarget<'_>, callbacks: &CallbackLinks) -> Value {
25
let replacement = target.replaces.map(|replaces| json!({"replaces": replaces}));
26
json!({
27
"callTransfer": {
28
"target": {"id": target.mri},
29
"transferor": transferor(from),
30
"links": {
31
"transferAcceptance": callbacks.call("transferAcceptance"),
32
"transferCompletion": callbacks.call("transferCompletion"),
33
},
34
"replacementDetails": replacement,
35
"disableForwardingAndUnanswered": false,
36
"transferContext": null,
37
},
38
})
39
}
40
41
#[derive(Debug, Clone, PartialEq, Eq)]
42
pub enum TransferEvent {
43
Accepted,
44
Completed { code: i64, sub_code: i64 },
45
}
46
47
impl TransferEvent {
48
pub fn succeeded(&self) -> bool {
49
matches!(self, TransferEvent::Completed { code, .. } if *code == 0 || (200..300).contains(code))
50
}
51
}
52
53
pub fn completion(body: &Value) -> TransferEvent {
54
let completed = &body["transferCompletion"];
55
TransferEvent::Completed {
56
code: completed["code"].as_i64().unwrap_or_default(),
57
sub_code: completed["subCode"].as_i64().unwrap_or_default(),
58
}
59
}
60
61
#[cfg(test)]
62
mod tests {
63
use super::*;
64
65
fn me() -> Participant {
66
Participant {
67
mri: "8:orgid:me".into(),
68
display_name: "Me".into(),
69
endpoint_id: "ep-1".into(),
70
participant_id: "part-1".into(),
71
language_id: "en-gb".into(),
72
}
73
}
74
75
fn callbacks() -> CallbackLinks {
76
CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1")
77
}
78
79
#[test]
80
fn a_blind_transfer_names_the_target_and_the_transferor() {
81
let body = transfer_body(&me(), TransferTarget { mri: "8:orgid:ana", replaces: None }, &callbacks());
82
let transfer = &body["callTransfer"];
83
assert_eq!(transfer["target"], json!({"id": "8:orgid:ana"}));
84
assert_eq!(transfer["transferor"]["details"], json!({"id": "8:orgid:me", "endpointId": "ep-1", "participantId": "part-1", "languageId": "en-gb"}));
85
assert!(transfer["transferor"]["authorizationToken"].is_null());
86
assert!(transfer["replacementDetails"].is_null());
87
assert!(transfer["links"]["transferAcceptance"].as_str().unwrap().contains("/call/transferAcceptance/"));
88
assert!(transfer["links"]["transferCompletion"].as_str().unwrap().contains("/call/transferCompletion/"));
89
assert_eq!(transfer["disableForwardingAndUnanswered"], false);
90
}
91
92
#[test]
93
fn a_consulted_transfer_replaces_the_consult_call() {
94
let body = transfer_body(&me(), TransferTarget { mri: "8:orgid:ana", replaces: Some("https://cc.skype.com/replacement") }, &callbacks());
95
assert_eq!(body["callTransfer"]["replacementDetails"], json!({"replaces": "https://cc.skype.com/replacement"}));
96
}
97
98
#[test]
99
fn the_completion_callback_tells_success_from_failure() {
100
let done = completion(&json!({"transferCompletion": {"code": 0, "subCode": 0, "resultCategories": ["Success"]}}));
101
assert!(done.succeeded());
102
let failed = completion(&json!({"transferCompletion": {"code": 603, "subCode": 10603}}));
103
assert_eq!(failed, TransferEvent::Completed { code: 603, sub_code: 10603 });
104
assert!(!failed.succeeded());
105
assert!(!TransferEvent::Accepted.succeeded());
106
}
107
}
@@ -0,0 +1,107 @@1
use serde_json::{Value, json};2
3
use crate::signaling::Participant;4
use crate::trouter_events::CallbackLinks;5
6
#[derive(Debug, Clone, Copy)]7
pub struct TransferTarget<'a> {8
pub mri: &'a str,9
pub replaces: Option<&'a str>,10
}11
12
fn transferor(from: &Participant) -> Value {13
json!({14
"details": {15
"id": from.mri,16
"endpointId": from.endpoint_id,17
"participantId": from.participant_id,18
"languageId": from.language_id,19
},20
"authorizationToken": null,21
})22
}23
24
pub fn transfer_body(from: &Participant, target: TransferTarget<'_>, callbacks: &CallbackLinks) -> Value {25
let replacement = target.replaces.map(|replaces| json!({"replaces": replaces}));26
json!({27
"callTransfer": {28
"target": {"id": target.mri},29
"transferor": transferor(from),30
"links": {31
"transferAcceptance": callbacks.call("transferAcceptance"),32
"transferCompletion": callbacks.call("transferCompletion"),33
},34
"replacementDetails": replacement,35
"disableForwardingAndUnanswered": false,36
"transferContext": null,37
},38
})39
}40
41
#[derive(Debug, Clone, PartialEq, Eq)]42
pub enum TransferEvent {43
Accepted,44
Completed { code: i64, sub_code: i64 },45
}46
47
impl TransferEvent {48
pub fn succeeded(&self) -> bool {49
matches!(self, TransferEvent::Completed { code, .. } if *code == 0 || (200..300).contains(code))50
}51
}52
53
pub fn completion(body: &Value) -> TransferEvent {54
let completed = &body["transferCompletion"];55
TransferEvent::Completed {56
code: completed["code"].as_i64().unwrap_or_default(),57
sub_code: completed["subCode"].as_i64().unwrap_or_default(),58
}59
}60
61
#[cfg(test)]62
mod tests {63
use super::*;64
65
fn me() -> Participant {66
Participant {67
mri: "8:orgid:me".into(),68
display_name: "Me".into(),69
endpoint_id: "ep-1".into(),70
participant_id: "part-1".into(),71
language_id: "en-gb".into(),72
}73
}74
75
fn callbacks() -> CallbackLinks {76
CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1")77
}78
79
#[test]80
fn a_blind_transfer_names_the_target_and_the_transferor() {81
let body = transfer_body(&me(), TransferTarget { mri: "8:orgid:ana", replaces: None }, &callbacks());82
let transfer = &body["callTransfer"];83
assert_eq!(transfer["target"], json!({"id": "8:orgid:ana"}));84
assert_eq!(transfer["transferor"]["details"], json!({"id": "8:orgid:me", "endpointId": "ep-1", "participantId": "part-1", "languageId": "en-gb"}));85
assert!(transfer["transferor"]["authorizationToken"].is_null());86
assert!(transfer["replacementDetails"].is_null());87
assert!(transfer["links"]["transferAcceptance"].as_str().unwrap().contains("/call/transferAcceptance/"));88
assert!(transfer["links"]["transferCompletion"].as_str().unwrap().contains("/call/transferCompletion/"));89
assert_eq!(transfer["disableForwardingAndUnanswered"], false);90
}91
92
#[test]93
fn a_consulted_transfer_replaces_the_consult_call() {94
let body = transfer_body(&me(), TransferTarget { mri: "8:orgid:ana", replaces: Some("https://cc.skype.com/replacement") }, &callbacks());95
assert_eq!(body["callTransfer"]["replacementDetails"], json!({"replaces": "https://cc.skype.com/replacement"}));96
}97
98
#[test]99
fn the_completion_callback_tells_success_from_failure() {100
let done = completion(&json!({"transferCompletion": {"code": 0, "subCode": 0, "resultCategories": ["Success"]}}));101
assert!(done.succeeded());102
let failed = completion(&json!({"transferCompletion": {"code": 603, "subCode": 10603}}));103
assert_eq!(failed, TransferEvent::Completed { code: 603, sub_code: 10603 });104
assert!(!failed.succeeded());105
assert!(!TransferEvent::Accepted.succeeded());106
}107
}@@ -9,6 +9,7 @@ use serde_json::{Value, json};
9
9
use crate::end::{EndKind, classify_end};
10
10
use crate::error::{Error, Result};
11
11
use crate::reaction::{ReactionEvent, parse_reactions};
12
use crate::transfer::{TransferEvent, completion};
12
13
13
14
const CALLBACK_ROOT: &str = "callAgent/";
14
15
const GZIP_ENCODING: &str = "gzip";
@@ -24,6 +25,24 @@ const SPEAKER_KEYS: [&str; 7] = [
24
25
];
25
26
const MAX_SPEAKER_DEPTH: usize = 4;
26
27
28
const MAX_FIND_DEPTH: usize = 6;
29
30
/// First value under `key` anywhere in `value`; Teams nests the same field at different depths.
31
pub(crate) fn find_key<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
32
find_key_within(value, key, 0)
33
}
34
35
fn find_key_within<'a>(value: &'a Value, key: &str, depth: usize) -> Option<&'a Value> {
36
if depth > MAX_FIND_DEPTH {
37
return None;
38
}
39
match value {
40
Value::Object(map) => map.get(key).or_else(|| map.values().find_map(|child| find_key_within(child, key, depth + 1))),
41
Value::Array(items) => items.iter().find_map(|item| find_key_within(item, key, depth + 1)),
42
_ => None,
43
}
44
}
45
27
46
pub fn decode_body(callback: &TrouterCallback) -> Result<Value> {
28
47
let text = if callback
29
48
.content_encoding
@@ -116,6 +135,11 @@ pub enum CallEvent {
116
135
AddParticipantSuccess(Value),
117
136
AddParticipantFailure(Value),
118
137
Reactions(Vec<ReactionEvent>),
138
LocalParticipantUpdate(Value),
139
Replacement(Value),
140
ContentShareUpdate(Value),
141
ContentShareEnd(Value),
142
Transfer(TransferEvent),
119
143
End(CallEnd),
120
144
Other { scope: String, event: String },
121
145
}
@@ -133,6 +157,11 @@ impl CallEvent {
133
157
CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
134
158
CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
135
159
CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
160
CallEvent::LocalParticipantUpdate(_) => "conversation/localParticipantUpdate".into(),
161
CallEvent::Replacement(_) => "call/replacement".into(),
162
CallEvent::ContentShareUpdate(_) => "conversation/contentSharingUpdate".into(),
163
CallEvent::ContentShareEnd(_) => "conversation/contentSharingEnd".into(),
164
CallEvent::Transfer(_) => "call/transfer".into(),
136
165
CallEvent::End(_) => "call/end".into(),
137
166
CallEvent::Other { scope, event } => format!("{scope}/{event}"),
138
167
}
@@ -148,6 +177,12 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
148
177
("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
149
178
("conversation", "receiveMessage") => CallEvent::Reactions(parse_reactions(&body)),
150
179
("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
180
("conversation", "localParticipantUpdate") => CallEvent::LocalParticipantUpdate(body),
181
("conversation", "contentSharingUpdate") => CallEvent::ContentShareUpdate(body),
182
("conversation", "contentSharingEnd") => CallEvent::ContentShareEnd(body),
183
("call", "replacement") => CallEvent::Replacement(body),
184
("call", "transferAcceptance") => CallEvent::Transfer(TransferEvent::Accepted),
185
("call", "transferCompletion") => CallEvent::Transfer(completion(&body)),
151
186
("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
152
187
("call", "progress") => CallEvent::Progress(progress(&body)),
153
188
("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),
@@ -406,6 +441,22 @@ mod tests {
406
441
assert_eq!(acceptance.links["callLeg"], "https://cc/leg");
407
442
}
408
443
444
#[test]
445
fn classifies_the_events_of_the_last_features() {
446
let (_, update) = classify("callAgent/abc/1/conversation/localParticipantUpdate/", json!({"breakoutDetails": {}})).unwrap();
447
assert!(matches!(update, CallEvent::LocalParticipantUpdate(_)));
448
let (_, replacement) = classify("callAgent/abc/1/call/replacement/", json!({"callNotification": {}})).unwrap();
449
assert_eq!(replacement.name(), "call/replacement");
450
let (_, share) = classify("callAgent/abc/1/conversation/contentSharingUpdate/", json!({"sessionState": {}})).unwrap();
451
assert!(matches!(share, CallEvent::ContentShareUpdate(_)));
452
let (_, ended) = classify("callAgent/abc/1/conversation/contentSharingEnd/", Value::Null).unwrap();
453
assert!(matches!(ended, CallEvent::ContentShareEnd(_)));
454
let (_, accepted) = classify("callAgent/abc/1/call/transferAcceptance/", Value::Null).unwrap();
455
assert_eq!(accepted, CallEvent::Transfer(TransferEvent::Accepted));
456
let (_, completed) = classify("callAgent/abc/1/call/transferCompletion/", json!({"transferCompletion": {"code": 0}})).unwrap();
457
assert!(matches!(completed, CallEvent::Transfer(event) if event.succeeded()));
458
}
459
409
460
#[test]
410
461
fn classifies_end_and_unknown_events() {
411
462
let (_, end) = classify("callAgent/abc/1/call/end/", json!({"callEnd": {"code": 0, "subCode": 5, "phrase": "x"}})).unwrap();
@@ -9,6 +9,7 @@ use serde_json::{Value, json};9
use crate::end::{EndKind, classify_end};9
use crate::end::{EndKind, classify_end};10
use crate::error::{Error, Result};10
use crate::error::{Error, Result};11
use crate::reaction::{ReactionEvent, parse_reactions};11
use crate::reaction::{ReactionEvent, parse_reactions};12
use crate::transfer::{TransferEvent, completion};12
13
13
const CALLBACK_ROOT: &str = "callAgent/";14
const CALLBACK_ROOT: &str = "callAgent/";14
const GZIP_ENCODING: &str = "gzip";15
const GZIP_ENCODING: &str = "gzip";@@ -24,6 +25,24 @@ const SPEAKER_KEYS: [&str; 7] = [24
];25
];25
const MAX_SPEAKER_DEPTH: usize = 4;26
const MAX_SPEAKER_DEPTH: usize = 4;26
27
28
const MAX_FIND_DEPTH: usize = 6;29
30
/// First value under `key` anywhere in `value`; Teams nests the same field at different depths.31
pub(crate) fn find_key<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {32
find_key_within(value, key, 0)33
}34
35
fn find_key_within<'a>(value: &'a Value, key: &str, depth: usize) -> Option<&'a Value> {36
if depth > MAX_FIND_DEPTH {37
return None;38
}39
match value {40
Value::Object(map) => map.get(key).or_else(|| map.values().find_map(|child| find_key_within(child, key, depth + 1))),41
Value::Array(items) => items.iter().find_map(|item| find_key_within(item, key, depth + 1)),42
_ => None,43
}44
}45
27
pub fn decode_body(callback: &TrouterCallback) -> Result<Value> {46
pub fn decode_body(callback: &TrouterCallback) -> Result<Value> {28
let text = if callback47
let text = if callback29
.content_encoding48
.content_encoding@@ -116,6 +135,11 @@ pub enum CallEvent {116
AddParticipantSuccess(Value),135
AddParticipantSuccess(Value),117
AddParticipantFailure(Value),136
AddParticipantFailure(Value),118
Reactions(Vec<ReactionEvent>),137
Reactions(Vec<ReactionEvent>),138
LocalParticipantUpdate(Value),139
Replacement(Value),140
ContentShareUpdate(Value),141
ContentShareEnd(Value),142
Transfer(TransferEvent),119
End(CallEnd),143
End(CallEnd),120
Other { scope: String, event: String },144
Other { scope: String, event: String },121
}145
}@@ -133,6 +157,11 @@ impl CallEvent {133
CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),157
CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),134
CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),158
CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),135
CallEvent::Reactions(_) => "conversation/receiveMessage".into(),159
CallEvent::Reactions(_) => "conversation/receiveMessage".into(),160
CallEvent::LocalParticipantUpdate(_) => "conversation/localParticipantUpdate".into(),161
CallEvent::Replacement(_) => "call/replacement".into(),162
CallEvent::ContentShareUpdate(_) => "conversation/contentSharingUpdate".into(),163
CallEvent::ContentShareEnd(_) => "conversation/contentSharingEnd".into(),164
CallEvent::Transfer(_) => "call/transfer".into(),136
CallEvent::End(_) => "call/end".into(),165
CallEvent::End(_) => "call/end".into(),137
CallEvent::Other { scope, event } => format!("{scope}/{event}"),166
CallEvent::Other { scope, event } => format!("{scope}/{event}"),138
}167
}@@ -148,6 +177,12 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {148
("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),177
("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),149
("conversation", "receiveMessage") => CallEvent::Reactions(parse_reactions(&body)),178
("conversation", "receiveMessage") => CallEvent::Reactions(parse_reactions(&body)),150
("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),179
("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),180
("conversation", "localParticipantUpdate") => CallEvent::LocalParticipantUpdate(body),181
("conversation", "contentSharingUpdate") => CallEvent::ContentShareUpdate(body),182
("conversation", "contentSharingEnd") => CallEvent::ContentShareEnd(body),183
("call", "replacement") => CallEvent::Replacement(body),184
("call", "transferAcceptance") => CallEvent::Transfer(TransferEvent::Accepted),185
("call", "transferCompletion") => CallEvent::Transfer(completion(&body)),151
("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),186
("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),152
("call", "progress") => CallEvent::Progress(progress(&body)),187
("call", "progress") => CallEvent::Progress(progress(&body)),153
("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),188
("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),@@ -406,6 +441,22 @@ mod tests {406
assert_eq!(acceptance.links["callLeg"], "https://cc/leg");441
assert_eq!(acceptance.links["callLeg"], "https://cc/leg");407
}442
}408
443
444
#[test]445
fn classifies_the_events_of_the_last_features() {446
let (_, update) = classify("callAgent/abc/1/conversation/localParticipantUpdate/", json!({"breakoutDetails": {}})).unwrap();447
assert!(matches!(update, CallEvent::LocalParticipantUpdate(_)));448
let (_, replacement) = classify("callAgent/abc/1/call/replacement/", json!({"callNotification": {}})).unwrap();449
assert_eq!(replacement.name(), "call/replacement");450
let (_, share) = classify("callAgent/abc/1/conversation/contentSharingUpdate/", json!({"sessionState": {}})).unwrap();451
assert!(matches!(share, CallEvent::ContentShareUpdate(_)));452
let (_, ended) = classify("callAgent/abc/1/conversation/contentSharingEnd/", Value::Null).unwrap();453
assert!(matches!(ended, CallEvent::ContentShareEnd(_)));454
let (_, accepted) = classify("callAgent/abc/1/call/transferAcceptance/", Value::Null).unwrap();455
assert_eq!(accepted, CallEvent::Transfer(TransferEvent::Accepted));456
let (_, completed) = classify("callAgent/abc/1/call/transferCompletion/", json!({"transferCompletion": {"code": 0}})).unwrap();457
assert!(matches!(completed, CallEvent::Transfer(event) if event.succeeded()));458
}459
409
#[test]460
#[test]410
fn classifies_end_and_unknown_events() {461
fn classifies_end_and_unknown_events() {411
let (_, end) = classify("callAgent/abc/1/call/end/", json!({"callEnd": {"code": 0, "subCode": 5, "phrase": "x"}})).unwrap();462
let (_, end) = classify("callAgent/abc/1/call/end/", json!({"callEnd": {"code": 0, "subCode": 5, "phrase": "x"}})).unwrap();@@ -15,6 +15,7 @@ use crate::video_frame::VideoKey;
15
15
pub const RECEIVE_SLOTS: usize = 4;
16
16
pub const CAMERA_MID: &str = "1";
17
17
pub const SHARE_MID: &str = "6";
18
pub const ONE_TO_ONE_SHARE_MID: &str = "2";
18
19
const CAMERA_LINE_LABEL: &str = "main-video";
19
20
const SHARE_LINE_LABEL: &str = "applicationsharing-video";
20
21
const CAMERA_STREAM: &str = "camera";
@@ -40,11 +41,18 @@ pub fn offer_plan() -> OfferPlan {
40
41
}
41
42
}
42
43
44
pub fn one_to_one_plan() -> OfferPlan {
45
OfferPlan {
46
screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
47
gallery_mids: Vec::new(),
48
}
49
}
50
43
51
/// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-5, 6).
44
52
#[derive(Clone)]
45
53
pub struct VideoLines {
46
54
pub camera: RtpTransceiver,
47
pub share: RtpTransceiver,
55
pub share: Option<RtpTransceiver>,
48
56
}
49
57
50
58
fn h264_only(capabilities: Vec<RtpCodecCapability>) -> Vec<RtpCodecCapability> {
@@ -85,7 +93,15 @@ pub fn add_video_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -
85
93
add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving.clone())?;
86
94
}
87
95
let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending)?;
88
Ok(VideoLines { camera, share })
96
Ok(VideoLines { camera, share: Some(share) })
97
}
98
99
pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
100
let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
101
let receiving = h264_only(factory.get_rtp_receiver_capabilities(MediaType::Video).codecs);
102
let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending)?;
103
add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving)?;
104
Ok(VideoLines { camera, share: None })
89
105
}
90
106
91
107
/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
@@ -15,6 +15,7 @@ use crate::video_frame::VideoKey;15
pub const RECEIVE_SLOTS: usize = 4;15
pub const RECEIVE_SLOTS: usize = 4;16
pub const CAMERA_MID: &str = "1";16
pub const CAMERA_MID: &str = "1";17
pub const SHARE_MID: &str = "6";17
pub const SHARE_MID: &str = "6";18
pub const ONE_TO_ONE_SHARE_MID: &str = "2";18
const CAMERA_LINE_LABEL: &str = "main-video";19
const CAMERA_LINE_LABEL: &str = "main-video";19
const SHARE_LINE_LABEL: &str = "applicationsharing-video";20
const SHARE_LINE_LABEL: &str = "applicationsharing-video";20
const CAMERA_STREAM: &str = "camera";21
const CAMERA_STREAM: &str = "camera";@@ -40,11 +41,18 @@ pub fn offer_plan() -> OfferPlan {40
}41
}41
}42
}42
43
44
pub fn one_to_one_plan() -> OfferPlan {45
OfferPlan {46
screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],47
gallery_mids: Vec::new(),48
}49
}50
43
/// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-5, 6).51
/// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-5, 6).44
#[derive(Clone)]52
#[derive(Clone)]45
pub struct VideoLines {53
pub struct VideoLines {46
pub camera: RtpTransceiver,54
pub camera: RtpTransceiver,47
pub share: RtpTransceiver,55
pub share: Option<RtpTransceiver>,48
}56
}49
57
50
fn h264_only(capabilities: Vec<RtpCodecCapability>) -> Vec<RtpCodecCapability> {58
fn h264_only(capabilities: Vec<RtpCodecCapability>) -> Vec<RtpCodecCapability> {@@ -85,7 +93,15 @@ pub fn add_video_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -85
add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving.clone())?;93
add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving.clone())?;86
}94
}87
let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending)?;95
let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending)?;88
Ok(VideoLines { camera, share })96
Ok(VideoLines { camera, share: Some(share) })97
}98
99
pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {100
let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);101
let receiving = h264_only(factory.get_rtp_receiver_capabilities(MediaType::Video).codecs);102
let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending)?;103
add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving)?;104
Ok(VideoLines { camera, share: None })89
}105
}90
106
91
/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.107
/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.@@ -11,6 +11,7 @@ use libwebrtc::video_source::native::NativeVideoSource;
11
11
use libwebrtc::video_track::RtcVideoTrack;
12
12
use tokio::sync::mpsc::UnboundedSender;
13
13
14
use crate::background::BackgroundPicture;
14
15
use crate::blur::{BlurSettings, BlurStage};
15
16
use crate::camera::start_camera;
16
17
use crate::capture::Capture;
@@ -116,14 +117,23 @@ impl LocalVideo {
116
117
}
117
118
}
118
119
119
pub fn set_blur(&self, enabled: bool) {
120
pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
121
self.blur.set_picture(picture);
120
122
self.blur.set_enabled(enabled);
121
123
}
122
124
125
pub fn camera_track(&self) -> RtcVideoTrack {
126
self.camera.track.clone()
127
}
128
123
129
pub fn blur_average_ms(&self) -> Option<f32> {
124
130
(self.camera_on() && self.blur.enabled()).then(|| self.blur.average_ms())
125
131
}
126
132
133
pub fn has_lines(&self) -> bool {
134
self.lines.is_some()
135
}
136
127
137
pub fn is_available(&self) -> bool {
128
138
self.mode != VideoMode::Off
129
139
}
@@ -140,8 +150,10 @@ impl LocalVideo {
140
150
if self.camera_on() {
141
151
Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
142
152
}
143
if self.sharing() {
144
Self::begin_sending(&lines.share.sender(), &self.screen.track)?;
153
if self.sharing()
154
&& let Some(share) = &lines.share
155
{
156
Self::begin_sending(&share.sender(), &self.screen.track)?;
145
157
}
146
158
self.lines = Some(lines);
147
159
Ok(())
@@ -199,6 +211,7 @@ impl LocalVideo {
199
211
200
212
pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
201
213
let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
214
let share = lines.share.as_ref().ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
202
215
if !self.is_available() {
203
216
return Err(Error::Webrtc("video is switched off".into()));
204
217
}
@@ -208,15 +221,15 @@ impl LocalVideo {
208
221
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
209
222
_ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
210
223
};
211
Self::begin_sending(&lines.share.sender(), &self.screen.track)?;
224
Self::begin_sending(&share.sender(), &self.screen.track)?;
212
225
self.screen.capture = Some(capture);
213
226
Ok(())
214
227
}
215
228
216
229
pub fn stop_share(&mut self) {
217
230
self.screen.capture = None;
218
if let Some(lines) = &self.lines {
219
let _ = Self::set_active(&lines.share.sender(), false);
231
if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
232
let _ = Self::set_active(&share.sender(), false);
220
233
}
221
234
self.hub.forget(&VideoKey::LocalScreen);
222
235
}
@@ -11,6 +11,7 @@ use libwebrtc::video_source::native::NativeVideoSource;11
use libwebrtc::video_track::RtcVideoTrack;11
use libwebrtc::video_track::RtcVideoTrack;12
use tokio::sync::mpsc::UnboundedSender;12
use tokio::sync::mpsc::UnboundedSender;13
13
14
use crate::background::BackgroundPicture;14
use crate::blur::{BlurSettings, BlurStage};15
use crate::blur::{BlurSettings, BlurStage};15
use crate::camera::start_camera;16
use crate::camera::start_camera;16
use crate::capture::Capture;17
use crate::capture::Capture;@@ -116,14 +117,23 @@ impl LocalVideo {116
}117
}117
}118
}118
119
119
pub fn set_blur(&self, enabled: bool) {120
pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {121
self.blur.set_picture(picture);120
self.blur.set_enabled(enabled);122
self.blur.set_enabled(enabled);121
}123
}122
124
125
pub fn camera_track(&self) -> RtcVideoTrack {126
self.camera.track.clone()127
}128
123
pub fn blur_average_ms(&self) -> Option<f32> {129
pub fn blur_average_ms(&self) -> Option<f32> {124
(self.camera_on() && self.blur.enabled()).then(|| self.blur.average_ms())130
(self.camera_on() && self.blur.enabled()).then(|| self.blur.average_ms())125
}131
}126
132
133
pub fn has_lines(&self) -> bool {134
self.lines.is_some()135
}136
127
pub fn is_available(&self) -> bool {137
pub fn is_available(&self) -> bool {128
self.mode != VideoMode::Off138
self.mode != VideoMode::Off129
}139
}@@ -140,8 +150,10 @@ impl LocalVideo {140
if self.camera_on() {150
if self.camera_on() {141
Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;151
Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;142
}152
}143
if self.sharing() {153
if self.sharing()144
Self::begin_sending(&lines.share.sender(), &self.screen.track)?;154
&& let Some(share) = &lines.share155
{156
Self::begin_sending(&share.sender(), &self.screen.track)?;145
}157
}146
self.lines = Some(lines);158
self.lines = Some(lines);147
Ok(())159
Ok(())@@ -199,6 +211,7 @@ impl LocalVideo {199
211
200
pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {212
pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {201
let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;213
let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;214
let share = lines.share.as_ref().ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;202
if !self.is_available() {215
if !self.is_available() {203
return Err(Error::Webrtc("video is switched off".into()));216
return Err(Error::Webrtc("video is switched off".into()));204
}217
}@@ -208,15 +221,15 @@ impl LocalVideo {208
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),221
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),209
_ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,222
_ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,210
};223
};211
Self::begin_sending(&lines.share.sender(), &self.screen.track)?;224
Self::begin_sending(&share.sender(), &self.screen.track)?;212
self.screen.capture = Some(capture);225
self.screen.capture = Some(capture);213
Ok(())226
Ok(())214
}227
}215
228
216
pub fn stop_share(&mut self) {229
pub fn stop_share(&mut self) {217
self.screen.capture = None;230
self.screen.capture = None;218
if let Some(lines) = &self.lines {231
if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {219
let _ = Self::set_active(&lines.share.sender(), false);232
let _ = Self::set_active(&share.sender(), false);220
}233
}221
self.hub.forget(&VideoKey::LocalScreen);234
self.hub.forget(&VideoKey::LocalScreen);222
}235
}@@ -0,0 +1,128 @@
1
use serde_json::Value;
2
use session::{Method, Request, SPACES, Scope, Session};
3
4
use crate::error::{Error, Result};
5
use crate::signaling::{CHATSVC_REGION, MeetingTarget};
6
use crate::trouter_events::find_key;
7
8
const WHITEBOARD_HOST: &str = "whiteboard.microsoft.com";
9
const BOARD_SCOPE: &str = "user_impersonation";
10
11
#[derive(Debug, Clone, PartialEq, Eq)]
12
pub struct ContentShare {
13
pub session_id: String,
14
pub presenter: Option<String>,
15
pub subject: String,
16
pub url: Option<String>,
17
pub whiteboard: bool,
18
}
19
20
/// A whiteboard share is told apart by the board host in the share URL or by its name.
21
fn is_whiteboard(identifier: &str, subject: &str, url: Option<&str>) -> bool {
22
let named = |text: &str| text.to_ascii_lowercase().contains("whiteboard");
23
url.is_some_and(|url| url.contains(WHITEBOARD_HOST)) || named(identifier) || named(subject)
24
}
25
26
pub fn content_share(body: &Value) -> Option<ContentShare> {
27
let state = find_key(body, "sessionState")?;
28
let text = |key: &str| find_key(body, key).and_then(Value::as_str).unwrap_or_default().to_owned();
29
let url = state["url"].as_str().filter(|url| !url.is_empty()).map(str::to_owned);
30
let presenter = find_key(body, "presenter").and_then(|presenter| match presenter {
31
Value::String(mri) => Some(mri.clone()),
32
other => other["id"].as_str().or_else(|| other["mri"].as_str()).map(str::to_owned),
33
});
34
let (identifier, subject) = (text("identifier"), text("subject"));
35
Some(ContentShare {
36
session_id: text("sessionId"),
37
presenter,
38
whiteboard: is_whiteboard(&identifier, &subject, url.as_deref()),
39
subject,
40
url,
41
})
42
}
43
44
fn encoded(component: &str) -> String {
45
component
46
.bytes()
47
.map(|byte| match byte {
48
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (byte as char).to_string(),
49
other => format!("%{other:02X}"),
50
})
51
.collect()
52
}
53
54
pub fn board_url(target: &MeetingTarget, meeting_title: &str) -> String {
55
format!(
56
"https://teams.cloud.microsoft/api/mt/{CHATSVC_REGION}/beta/meetings/fluidboard?threadId={}&messageId=0&organizerId={}&tenantId={}&meetingTitle={}",
57
encoded(&target.thread_id),
58
encoded(&target.organizer_id),
59
encoded(&target.tenant_id),
60
encoded(meeting_title),
61
)
62
}
63
64
pub async fn fetch_board(session: &Session, target: &MeetingTarget, meeting_title: &str) -> Result<String> {
65
let request = Request { method: Method::Get, ..Request::get(board_url(target, meeting_title)) };
66
let response = session.send(request, &Scope::new(SPACES, BOARD_SCOPE)).await?;
67
if !response.is_success() {
68
return Err(Error::Signaling(format!("whiteboard answered HTTP {}", response.status)));
69
}
70
response.body["url"]
71
.as_str()
72
.or_else(|| response.body["shareUrl"].as_str())
73
.map(str::to_owned)
74
.ok_or_else(|| Error::Signaling("whiteboard answer without a url".into()))
75
}
76
77
#[cfg(test)]
78
mod tests {
79
use serde_json::json;
80
81
use super::*;
82
83
fn share(url: &str, subject: &str) -> Value {
84
json!({"contentSharingUpdate": {
85
"sessionId": "s-1",
86
"identifier": "app-id",
87
"presenter": {"id": "8:orgid:ana", "displayName": "Ana"},
88
"subject": subject,
89
"sequenceNumber": 2,
90
"sessionState": {"url": url, "passThrough": "x"},
91
"links": {"contentSharingController": "https://css.skype.com/contentshare/1"},
92
}})
93
}
94
95
#[test]
96
fn a_board_url_marks_the_share_as_a_whiteboard() {
97
let parsed = content_share(&share("https://app.whiteboard.microsoft.com/me/whiteboards/x?encodedShareLink=1", "Meeting")).unwrap();
98
assert!(parsed.whiteboard);
99
assert_eq!(parsed.presenter.as_deref(), Some("8:orgid:ana"));
100
assert_eq!(parsed.session_id, "s-1");
101
assert!(parsed.url.as_deref().unwrap().contains("encodedShareLink"));
102
}
103
104
#[test]
105
fn the_name_marks_a_whiteboard_when_the_url_does_not() {
106
assert!(content_share(&share("https://example.com/board", "Microsoft Whiteboard")).unwrap().whiteboard);
107
assert!(!content_share(&share("https://example.com/deck", "Quarterly slides")).unwrap().whiteboard);
108
}
109
110
#[test]
111
fn a_string_presenter_and_a_missing_url_still_parse() {
112
let body = json!({"sessionId": "s", "presenter": "8:orgid:bo", "identifier": "whiteboard", "sessionState": {}});
113
let parsed = content_share(&body).unwrap();
114
assert_eq!(parsed.presenter.as_deref(), Some("8:orgid:bo"));
115
assert!(parsed.url.is_none());
116
assert!(parsed.whiteboard);
117
assert!(content_share(&json!({"sessionId": "s"})).is_none());
118
}
119
120
#[test]
121
fn the_board_request_names_the_meeting() {
122
let target = MeetingTarget { thread_id: "19:meeting_x@thread.v2".into(), tenant_id: "t-1".into(), organizer_id: "o-1".into(), meeting_data: None };
123
let url = board_url(&target, "Q3 plan");
124
assert!(url.starts_with("https://teams.cloud.microsoft/api/mt/emea/beta/meetings/fluidboard?"));
125
assert!(url.contains("threadId=19%3Ameeting_x%40thread.v2"));
126
assert!(url.contains("messageId=0&organizerId=o-1&tenantId=t-1&meetingTitle=Q3%20plan"));
127
}
128
}
@@ -0,0 +1,128 @@1
use serde_json::Value;2
use session::{Method, Request, SPACES, Scope, Session};3
4
use crate::error::{Error, Result};5
use crate::signaling::{CHATSVC_REGION, MeetingTarget};6
use crate::trouter_events::find_key;7
8
const WHITEBOARD_HOST: &str = "whiteboard.microsoft.com";9
const BOARD_SCOPE: &str = "user_impersonation";10
11
#[derive(Debug, Clone, PartialEq, Eq)]12
pub struct ContentShare {13
pub session_id: String,14
pub presenter: Option<String>,15
pub subject: String,16
pub url: Option<String>,17
pub whiteboard: bool,18
}19
20
/// A whiteboard share is told apart by the board host in the share URL or by its name.21
fn is_whiteboard(identifier: &str, subject: &str, url: Option<&str>) -> bool {22
let named = |text: &str| text.to_ascii_lowercase().contains("whiteboard");23
url.is_some_and(|url| url.contains(WHITEBOARD_HOST)) || named(identifier) || named(subject)24
}25
26
pub fn content_share(body: &Value) -> Option<ContentShare> {27
let state = find_key(body, "sessionState")?;28
let text = |key: &str| find_key(body, key).and_then(Value::as_str).unwrap_or_default().to_owned();29
let url = state["url"].as_str().filter(|url| !url.is_empty()).map(str::to_owned);30
let presenter = find_key(body, "presenter").and_then(|presenter| match presenter {31
Value::String(mri) => Some(mri.clone()),32
other => other["id"].as_str().or_else(|| other["mri"].as_str()).map(str::to_owned),33
});34
let (identifier, subject) = (text("identifier"), text("subject"));35
Some(ContentShare {36
session_id: text("sessionId"),37
presenter,38
whiteboard: is_whiteboard(&identifier, &subject, url.as_deref()),39
subject,40
url,41
})42
}43
44
fn encoded(component: &str) -> String {45
component46
.bytes()47
.map(|byte| match byte {48
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (byte as char).to_string(),49
other => format!("%{other:02X}"),50
})51
.collect()52
}53
54
pub fn board_url(target: &MeetingTarget, meeting_title: &str) -> String {55
format!(56
"https://teams.cloud.microsoft/api/mt/{CHATSVC_REGION}/beta/meetings/fluidboard?threadId={}&messageId=0&organizerId={}&tenantId={}&meetingTitle={}",57
encoded(&target.thread_id),58
encoded(&target.organizer_id),59
encoded(&target.tenant_id),60
encoded(meeting_title),61
)62
}63
64
pub async fn fetch_board(session: &Session, target: &MeetingTarget, meeting_title: &str) -> Result<String> {65
let request = Request { method: Method::Get, ..Request::get(board_url(target, meeting_title)) };66
let response = session.send(request, &Scope::new(SPACES, BOARD_SCOPE)).await?;67
if !response.is_success() {68
return Err(Error::Signaling(format!("whiteboard answered HTTP {}", response.status)));69
}70
response.body["url"]71
.as_str()72
.or_else(|| response.body["shareUrl"].as_str())73
.map(str::to_owned)74
.ok_or_else(|| Error::Signaling("whiteboard answer without a url".into()))75
}76
77
#[cfg(test)]78
mod tests {79
use serde_json::json;80
81
use super::*;82
83
fn share(url: &str, subject: &str) -> Value {84
json!({"contentSharingUpdate": {85
"sessionId": "s-1",86
"identifier": "app-id",87
"presenter": {"id": "8:orgid:ana", "displayName": "Ana"},88
"subject": subject,89
"sequenceNumber": 2,90
"sessionState": {"url": url, "passThrough": "x"},91
"links": {"contentSharingController": "https://css.skype.com/contentshare/1"},92
}})93
}94
95
#[test]96
fn a_board_url_marks_the_share_as_a_whiteboard() {97
let parsed = content_share(&share("https://app.whiteboard.microsoft.com/me/whiteboards/x?encodedShareLink=1", "Meeting")).unwrap();98
assert!(parsed.whiteboard);99
assert_eq!(parsed.presenter.as_deref(), Some("8:orgid:ana"));100
assert_eq!(parsed.session_id, "s-1");101
assert!(parsed.url.as_deref().unwrap().contains("encodedShareLink"));102
}103
104
#[test]105
fn the_name_marks_a_whiteboard_when_the_url_does_not() {106
assert!(content_share(&share("https://example.com/board", "Microsoft Whiteboard")).unwrap().whiteboard);107
assert!(!content_share(&share("https://example.com/deck", "Quarterly slides")).unwrap().whiteboard);108
}109
110
#[test]111
fn a_string_presenter_and_a_missing_url_still_parse() {112
let body = json!({"sessionId": "s", "presenter": "8:orgid:bo", "identifier": "whiteboard", "sessionState": {}});113
let parsed = content_share(&body).unwrap();114
assert_eq!(parsed.presenter.as_deref(), Some("8:orgid:bo"));115
assert!(parsed.url.is_none());116
assert!(parsed.whiteboard);117
assert!(content_share(&json!({"sessionId": "s"})).is_none());118
}119
120
#[test]121
fn the_board_request_names_the_meeting() {122
let target = MeetingTarget { thread_id: "19:meeting_x@thread.v2".into(), tenant_id: "t-1".into(), organizer_id: "o-1".into(), meeting_data: None };123
let url = board_url(&target, "Q3 plan");124
assert!(url.starts_with("https://teams.cloud.microsoft/api/mt/emea/beta/meetings/fluidboard?"));125
assert!(url.contains("threadId=19%3Ameeting_x%40thread.v2"));126
assert!(url.contains("messageId=0&organizerId=o-1&tenantId=t-1&meetingTitle=Q3%20plan"));127
}128
}@@ -0,0 +1,332 @@
1
use std::cmp::Reverse;
2
use std::collections::HashSet;
3
4
use chrono::{DateTime, Utc};
5
use serde_json::Value;
6
use session::Request;
7
8
use crate::error::{Error, Result};
9
use crate::messages::{MessageTransport, Messages, encode, ensure_success};
10
11
const CALL_LOG_CONVERSATION: &str = "48:calllogs";
12
const LIST_QUERY: &str = "view=msnp24Equivalent&pageSize=200";
13
const MULTI_PARTY: &str = "multiParty";
14
const VOICEMAIL_TYPE: &str = "voicemail";
15
16
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17
pub enum CallDirection {
18
Incoming,
19
Outgoing,
20
}
21
22
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23
pub enum CallOutcome {
24
Accepted,
25
Missed,
26
Declined,
27
}
28
29
#[derive(Debug, Clone, PartialEq, Eq)]
30
pub struct CallLogEntry {
31
pub call_id: String,
32
pub started_at: DateTime<Utc>,
33
pub duration_seconds: Option<i64>,
34
pub direction: CallDirection,
35
pub outcome: CallOutcome,
36
pub is_meeting: bool,
37
pub peer_id: Option<String>,
38
pub peer_name: Option<String>,
39
pub thread_id: Option<String>,
40
}
41
42
impl CallLogEntry {
43
pub fn missed(&self) -> bool {
44
self.direction == CallDirection::Incoming && self.outcome == CallOutcome::Missed
45
}
46
}
47
48
fn text(value: &Value, key: &str) -> Option<String> {
49
value
50
.get(key)?
51
.as_str()
52
.filter(|text| !text.is_empty())
53
.map(str::to_owned)
54
}
55
56
fn time(value: &Value, key: &str) -> Option<DateTime<Utc>> {
57
DateTime::parse_from_rfc3339(value.get(key)?.as_str()?)
58
.ok()
59
.map(|time| time.with_timezone(&Utc))
60
}
61
62
fn log_of(message: &Value) -> Option<Value> {
63
match message.pointer("/properties/call-log")? {
64
Value::String(text) => serde_json::from_str(text).ok(),
65
object @ Value::Object(_) => Some(object.clone()),
66
_ => None,
67
}
68
}
69
70
fn direction_of(log: &Value) -> Option<CallDirection> {
71
match log.get("callDirection")?.as_str()? {
72
"incoming" => Some(CallDirection::Incoming),
73
"outgoing" => Some(CallDirection::Outgoing),
74
_ => None,
75
}
76
}
77
78
fn outcome_of(log: &Value, connected: bool) -> CallOutcome {
79
match log.get("callState").and_then(Value::as_str) {
80
Some("accepted") => CallOutcome::Accepted,
81
Some("declined") => CallOutcome::Declined,
82
Some("missed") => CallOutcome::Missed,
83
_ if connected => CallOutcome::Accepted,
84
_ => CallOutcome::Missed,
85
}
86
}
87
88
fn peer_of(log: &Value, direction: CallDirection) -> (Option<String>, Option<String>) {
89
let (participant_key, id_key) = match direction {
90
CallDirection::Incoming => ("originatorParticipant", "originator"),
91
CallDirection::Outgoing => ("targetParticipant", "target"),
92
};
93
let participant = log.get(participant_key).unwrap_or(&Value::Null);
94
if participant.get("type").and_then(Value::as_str) == Some(VOICEMAIL_TYPE) {
95
return (None, None);
96
}
97
let peer_id = text(participant, "id").or_else(|| text(log, id_key));
98
(peer_id, text(participant, "displayName"))
99
}
100
101
fn call_log_entry(message: &Value) -> Option<CallLogEntry> {
102
let log = log_of(message)?;
103
let direction = direction_of(&log)?;
104
let started_at = time(&log, "startTime")?;
105
let connected_at = time(&log, "connectTime");
106
let duration_seconds = connected_at
107
.zip(time(&log, "endTime"))
108
.map(|(connected, ended)| (ended - connected).num_seconds().max(0));
109
let (peer_id, peer_name) = peer_of(&log, direction);
110
Some(CallLogEntry {
111
call_id: text(&log, "callId").or_else(|| text(message, "id"))?,
112
started_at,
113
duration_seconds,
114
direction,
115
outcome: outcome_of(&log, connected_at.is_some()),
116
is_meeting: log.get("callType").and_then(Value::as_str) == Some(MULTI_PARTY),
117
peer_id,
118
peer_name,
119
thread_id: text(&log, "threadId"),
120
})
121
}
122
123
pub fn parse_call_logs(body: &Value) -> Result<Vec<CallLogEntry>> {
124
let messages = body
125
.get("messages")
126
.and_then(Value::as_array)
127
.ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?;
128
let mut seen = HashSet::new();
129
let mut entries: Vec<CallLogEntry> = messages
130
.iter()
131
.filter_map(call_log_entry)
132
.filter(|entry| seen.insert(entry.call_id.clone()))
133
.collect();
134
entries.sort_by_key(|entry| Reverse(entry.started_at));
135
Ok(entries)
136
}
137
138
impl<T: MessageTransport> Messages<T> {
139
pub fn call_logs_url(&self) -> String {
140
format!(
141
"{}/{}/messages?{LIST_QUERY}",
142
self.base_url,
143
encode(CALL_LOG_CONVERSATION)
144
)
145
}
146
147
pub async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
148
let answer = self
149
.transport
150
.send(Request::get(self.call_logs_url()))
151
.await?;
152
ensure_success(&answer)?;
153
parse_call_logs(&answer.body)
154
}
155
}
156
157
#[cfg(test)]
158
mod tests {
159
use std::sync::Mutex;
160
161
use serde_json::json;
162
use session::{ApiResponse, Method};
163
164
use super::*;
165
166
struct Canned {
167
body: Value,
168
requests: Mutex<Vec<Request>>,
169
}
170
171
impl MessageTransport for Canned {
172
async fn send(&self, request: Request) -> Result<ApiResponse> {
173
self.requests.lock().unwrap().push(request);
174
Ok(ApiResponse {
175
status: 200,
176
body: self.body.clone(),
177
retry_after: None,
178
})
179
}
180
}
181
182
fn message(log: Value) -> Value {
183
json!({"messagetype": "Text", "properties": {"call-log": log.to_string()}})
184
}
185
186
fn log(direction: &str, state: &str, connect: Option<&str>, end: &str) -> Value {
187
json!({
188
"callId": format!("{direction}-{state}-{end}"),
189
"startTime": "2026-10-09T08:00:00.000Z",
190
"connectTime": connect,
191
"endTime": end,
192
"callDirection": direction,
193
"callType": "twoParty",
194
"callState": state,
195
"originator": "8:orgid:caller",
196
"target": "8:orgid:callee",
197
"originatorParticipant": {"id": "8:orgid:caller", "displayName": "Ada", "type": "user"},
198
"targetParticipant": {"id": "8:orgid:callee", "displayName": null, "type": "user"},
199
})
200
}
201
202
fn parse(logs: Vec<Value>) -> Vec<CallLogEntry> {
203
let messages: Vec<Value> = logs.into_iter().map(message).collect();
204
parse_call_logs(&json!({"messages": messages})).unwrap()
205
}
206
207
#[test]
208
fn an_accepted_incoming_call_has_the_caller_and_a_duration() {
209
let entries = parse(vec![log(
210
"incoming",
211
"accepted",
212
Some("2026-10-09T08:00:05.000Z"),
213
"2026-10-09T08:12:05.000Z",
214
)]);
215
let entry = &entries[0];
216
assert_eq!(entry.direction, CallDirection::Incoming);
217
assert_eq!(entry.outcome, CallOutcome::Accepted);
218
assert_eq!(entry.duration_seconds, Some(720));
219
assert_eq!(entry.peer_id.as_deref(), Some("8:orgid:caller"));
220
assert_eq!(entry.peer_name.as_deref(), Some("Ada"));
221
assert!(!entry.missed());
222
assert!(!entry.is_meeting);
223
}
224
225
#[test]
226
fn an_outgoing_call_names_the_target_even_without_a_display_name() {
227
let entries = parse(vec![log(
228
"outgoing",
229
"accepted",
230
Some("2026-10-09T08:00:05.000Z"),
231
"2026-10-09T08:04:17.000Z",
232
)]);
233
assert_eq!(entries[0].direction, CallDirection::Outgoing);
234
assert_eq!(entries[0].duration_seconds, Some(252));
235
assert_eq!(entries[0].peer_id.as_deref(), Some("8:orgid:callee"));
236
assert_eq!(entries[0].peer_name, None);
237
}
238
239
#[test]
240
fn a_missed_incoming_call_has_no_connect_time_and_no_duration() {
241
let entries = parse(vec![log(
242
"incoming",
243
"missed",
244
None,
245
"2026-10-09T08:00:30.000Z",
246
)]);
247
assert!(entries[0].missed());
248
assert_eq!(entries[0].duration_seconds, None);
249
}
250
251
#[test]
252
fn a_declined_call_and_an_unanswered_outgoing_call_are_not_missed_calls() {
253
let entries = parse(vec![
254
log("incoming", "declined", None, "2026-10-09T08:00:10.000Z"),
255
log("outgoing", "missed", None, "2026-10-09T08:00:40.000Z"),
256
]);
257
assert!(entries.iter().all(|entry| !entry.missed()));
258
assert_eq!(entries[0].outcome, CallOutcome::Declined);
259
}
260
261
#[test]
262
fn a_multi_party_call_is_a_meeting_with_its_thread() {
263
let mut meeting = log(
264
"incoming",
265
"accepted",
266
Some("2026-10-09T08:00:05.000Z"),
267
"2026-10-09T08:38:05.000Z",
268
);
269
meeting["callType"] = json!("multiParty");
270
meeting["threadId"] = json!("19:meeting_x@thread.v2");
271
let entries = parse(vec![meeting]);
272
assert!(entries[0].is_meeting);
273
assert_eq!(
274
entries[0].thread_id.as_deref(),
275
Some("19:meeting_x@thread.v2")
276
);
277
assert_eq!(entries[0].duration_seconds, Some(2280));
278
}
279
280
#[test]
281
fn a_voicemail_target_is_no_peer() {
282
let mut forwarded = log("outgoing", "missed", None, "2026-10-09T08:00:40.000Z");
283
forwarded["targetParticipant"]["type"] = json!("voicemail");
284
let entries = parse(vec![forwarded]);
285
assert_eq!(entries[0].peer_id, None);
286
}
287
288
#[test]
289
fn entries_sort_newest_first_and_skip_other_messages_and_duplicates() {
290
let mut older = log("incoming", "missed", None, "2026-10-08T08:00:30.000Z");
291
older["callId"] = json!("older");
292
older["startTime"] = json!("2026-10-08T08:00:00.000Z");
293
let newer = log("incoming", "missed", None, "2026-10-09T08:00:30.000Z");
294
let body = json!({"messages": [
295
message(older),
296
message(newer.clone()),
297
message(newer),
298
{"messagetype": "RichText/Media_CallLogRecording", "properties": {}},
299
{"messagetype": "Text", "properties": {"call-log": "not json"}},
300
]});
301
let entries = parse_call_logs(&body).unwrap();
302
assert_eq!(entries.len(), 2);
303
assert_eq!(entries[1].call_id, "older");
304
assert!(entries[0].started_at > entries[1].started_at);
305
}
306
307
#[test]
308
fn a_body_without_messages_is_unexpected() {
309
assert!(matches!(
310
parse_call_logs(&json!({})),
311
Err(Error::UnexpectedAnswer(_))
312
));
313
}
314
315
#[tokio::test]
316
async fn the_list_reads_the_calllogs_conversation() {
317
let messages = Messages::with_transport(
318
Canned {
319
body: json!({"messages": []}),
320
requests: Mutex::new(Vec::new()),
321
},
322
"emea",
323
);
324
assert!(messages.list_call_logs().await.unwrap().is_empty());
325
let requests = messages.transport.requests.lock().unwrap();
326
assert_eq!(requests[0].method, Method::Get);
327
assert_eq!(
328
requests[0].url,
329
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/48%3Acalllogs/messages?view=msnp24Equivalent&pageSize=200"
330
);
331
}
332
}
@@ -0,0 +1,332 @@1
use std::cmp::Reverse;2
use std::collections::HashSet;3
4
use chrono::{DateTime, Utc};5
use serde_json::Value;6
use session::Request;7
8
use crate::error::{Error, Result};9
use crate::messages::{MessageTransport, Messages, encode, ensure_success};10
11
const CALL_LOG_CONVERSATION: &str = "48:calllogs";12
const LIST_QUERY: &str = "view=msnp24Equivalent&pageSize=200";13
const MULTI_PARTY: &str = "multiParty";14
const VOICEMAIL_TYPE: &str = "voicemail";15
16
#[derive(Debug, Clone, Copy, PartialEq, Eq)]17
pub enum CallDirection {18
Incoming,19
Outgoing,20
}21
22
#[derive(Debug, Clone, Copy, PartialEq, Eq)]23
pub enum CallOutcome {24
Accepted,25
Missed,26
Declined,27
}28
29
#[derive(Debug, Clone, PartialEq, Eq)]30
pub struct CallLogEntry {31
pub call_id: String,32
pub started_at: DateTime<Utc>,33
pub duration_seconds: Option<i64>,34
pub direction: CallDirection,35
pub outcome: CallOutcome,36
pub is_meeting: bool,37
pub peer_id: Option<String>,38
pub peer_name: Option<String>,39
pub thread_id: Option<String>,40
}41
42
impl CallLogEntry {43
pub fn missed(&self) -> bool {44
self.direction == CallDirection::Incoming && self.outcome == CallOutcome::Missed45
}46
}47
48
fn text(value: &Value, key: &str) -> Option<String> {49
value50
.get(key)?51
.as_str()52
.filter(|text| !text.is_empty())53
.map(str::to_owned)54
}55
56
fn time(value: &Value, key: &str) -> Option<DateTime<Utc>> {57
DateTime::parse_from_rfc3339(value.get(key)?.as_str()?)58
.ok()59
.map(|time| time.with_timezone(&Utc))60
}61
62
fn log_of(message: &Value) -> Option<Value> {63
match message.pointer("/properties/call-log")? {64
Value::String(text) => serde_json::from_str(text).ok(),65
object @ Value::Object(_) => Some(object.clone()),66
_ => None,67
}68
}69
70
fn direction_of(log: &Value) -> Option<CallDirection> {71
match log.get("callDirection")?.as_str()? {72
"incoming" => Some(CallDirection::Incoming),73
"outgoing" => Some(CallDirection::Outgoing),74
_ => None,75
}76
}77
78
fn outcome_of(log: &Value, connected: bool) -> CallOutcome {79
match log.get("callState").and_then(Value::as_str) {80
Some("accepted") => CallOutcome::Accepted,81
Some("declined") => CallOutcome::Declined,82
Some("missed") => CallOutcome::Missed,83
_ if connected => CallOutcome::Accepted,84
_ => CallOutcome::Missed,85
}86
}87
88
fn peer_of(log: &Value, direction: CallDirection) -> (Option<String>, Option<String>) {89
let (participant_key, id_key) = match direction {90
CallDirection::Incoming => ("originatorParticipant", "originator"),91
CallDirection::Outgoing => ("targetParticipant", "target"),92
};93
let participant = log.get(participant_key).unwrap_or(&Value::Null);94
if participant.get("type").and_then(Value::as_str) == Some(VOICEMAIL_TYPE) {95
return (None, None);96
}97
let peer_id = text(participant, "id").or_else(|| text(log, id_key));98
(peer_id, text(participant, "displayName"))99
}100
101
fn call_log_entry(message: &Value) -> Option<CallLogEntry> {102
let log = log_of(message)?;103
let direction = direction_of(&log)?;104
let started_at = time(&log, "startTime")?;105
let connected_at = time(&log, "connectTime");106
let duration_seconds = connected_at107
.zip(time(&log, "endTime"))108
.map(|(connected, ended)| (ended - connected).num_seconds().max(0));109
let (peer_id, peer_name) = peer_of(&log, direction);110
Some(CallLogEntry {111
call_id: text(&log, "callId").or_else(|| text(message, "id"))?,112
started_at,113
duration_seconds,114
direction,115
outcome: outcome_of(&log, connected_at.is_some()),116
is_meeting: log.get("callType").and_then(Value::as_str) == Some(MULTI_PARTY),117
peer_id,118
peer_name,119
thread_id: text(&log, "threadId"),120
})121
}122
123
pub fn parse_call_logs(body: &Value) -> Result<Vec<CallLogEntry>> {124
let messages = body125
.get("messages")126
.and_then(Value::as_array)127
.ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?;128
let mut seen = HashSet::new();129
let mut entries: Vec<CallLogEntry> = messages130
.iter()131
.filter_map(call_log_entry)132
.filter(|entry| seen.insert(entry.call_id.clone()))133
.collect();134
entries.sort_by_key(|entry| Reverse(entry.started_at));135
Ok(entries)136
}137
138
impl<T: MessageTransport> Messages<T> {139
pub fn call_logs_url(&self) -> String {140
format!(141
"{}/{}/messages?{LIST_QUERY}",142
self.base_url,143
encode(CALL_LOG_CONVERSATION)144
)145
}146
147
pub async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {148
let answer = self149
.transport150
.send(Request::get(self.call_logs_url()))151
.await?;152
ensure_success(&answer)?;153
parse_call_logs(&answer.body)154
}155
}156
157
#[cfg(test)]158
mod tests {159
use std::sync::Mutex;160
161
use serde_json::json;162
use session::{ApiResponse, Method};163
164
use super::*;165
166
struct Canned {167
body: Value,168
requests: Mutex<Vec<Request>>,169
}170
171
impl MessageTransport for Canned {172
async fn send(&self, request: Request) -> Result<ApiResponse> {173
self.requests.lock().unwrap().push(request);174
Ok(ApiResponse {175
status: 200,176
body: self.body.clone(),177
retry_after: None,178
})179
}180
}181
182
fn message(log: Value) -> Value {183
json!({"messagetype": "Text", "properties": {"call-log": log.to_string()}})184
}185
186
fn log(direction: &str, state: &str, connect: Option<&str>, end: &str) -> Value {187
json!({188
"callId": format!("{direction}-{state}-{end}"),189
"startTime": "2026-10-09T08:00:00.000Z",190
"connectTime": connect,191
"endTime": end,192
"callDirection": direction,193
"callType": "twoParty",194
"callState": state,195
"originator": "8:orgid:caller",196
"target": "8:orgid:callee",197
"originatorParticipant": {"id": "8:orgid:caller", "displayName": "Ada", "type": "user"},198
"targetParticipant": {"id": "8:orgid:callee", "displayName": null, "type": "user"},199
})200
}201
202
fn parse(logs: Vec<Value>) -> Vec<CallLogEntry> {203
let messages: Vec<Value> = logs.into_iter().map(message).collect();204
parse_call_logs(&json!({"messages": messages})).unwrap()205
}206
207
#[test]208
fn an_accepted_incoming_call_has_the_caller_and_a_duration() {209
let entries = parse(vec![log(210
"incoming",211
"accepted",212
Some("2026-10-09T08:00:05.000Z"),213
"2026-10-09T08:12:05.000Z",214
)]);215
let entry = &entries[0];216
assert_eq!(entry.direction, CallDirection::Incoming);217
assert_eq!(entry.outcome, CallOutcome::Accepted);218
assert_eq!(entry.duration_seconds, Some(720));219
assert_eq!(entry.peer_id.as_deref(), Some("8:orgid:caller"));220
assert_eq!(entry.peer_name.as_deref(), Some("Ada"));221
assert!(!entry.missed());222
assert!(!entry.is_meeting);223
}224
225
#[test]226
fn an_outgoing_call_names_the_target_even_without_a_display_name() {227
let entries = parse(vec![log(228
"outgoing",229
"accepted",230
Some("2026-10-09T08:00:05.000Z"),231
"2026-10-09T08:04:17.000Z",232
)]);233
assert_eq!(entries[0].direction, CallDirection::Outgoing);234
assert_eq!(entries[0].duration_seconds, Some(252));235
assert_eq!(entries[0].peer_id.as_deref(), Some("8:orgid:callee"));236
assert_eq!(entries[0].peer_name, None);237
}238
239
#[test]240
fn a_missed_incoming_call_has_no_connect_time_and_no_duration() {241
let entries = parse(vec![log(242
"incoming",243
"missed",244
None,245
"2026-10-09T08:00:30.000Z",246
)]);247
assert!(entries[0].missed());248
assert_eq!(entries[0].duration_seconds, None);249
}250
251
#[test]252
fn a_declined_call_and_an_unanswered_outgoing_call_are_not_missed_calls() {253
let entries = parse(vec![254
log("incoming", "declined", None, "2026-10-09T08:00:10.000Z"),255
log("outgoing", "missed", None, "2026-10-09T08:00:40.000Z"),256
]);257
assert!(entries.iter().all(|entry| !entry.missed()));258
assert_eq!(entries[0].outcome, CallOutcome::Declined);259
}260
261
#[test]262
fn a_multi_party_call_is_a_meeting_with_its_thread() {263
let mut meeting = log(264
"incoming",265
"accepted",266
Some("2026-10-09T08:00:05.000Z"),267
"2026-10-09T08:38:05.000Z",268
);269
meeting["callType"] = json!("multiParty");270
meeting["threadId"] = json!("19:meeting_x@thread.v2");271
let entries = parse(vec![meeting]);272
assert!(entries[0].is_meeting);273
assert_eq!(274
entries[0].thread_id.as_deref(),275
Some("19:meeting_x@thread.v2")276
);277
assert_eq!(entries[0].duration_seconds, Some(2280));278
}279
280
#[test]281
fn a_voicemail_target_is_no_peer() {282
let mut forwarded = log("outgoing", "missed", None, "2026-10-09T08:00:40.000Z");283
forwarded["targetParticipant"]["type"] = json!("voicemail");284
let entries = parse(vec![forwarded]);285
assert_eq!(entries[0].peer_id, None);286
}287
288
#[test]289
fn entries_sort_newest_first_and_skip_other_messages_and_duplicates() {290
let mut older = log("incoming", "missed", None, "2026-10-08T08:00:30.000Z");291
older["callId"] = json!("older");292
older["startTime"] = json!("2026-10-08T08:00:00.000Z");293
let newer = log("incoming", "missed", None, "2026-10-09T08:00:30.000Z");294
let body = json!({"messages": [295
message(older),296
message(newer.clone()),297
message(newer),298
{"messagetype": "RichText/Media_CallLogRecording", "properties": {}},299
{"messagetype": "Text", "properties": {"call-log": "not json"}},300
]});301
let entries = parse_call_logs(&body).unwrap();302
assert_eq!(entries.len(), 2);303
assert_eq!(entries[1].call_id, "older");304
assert!(entries[0].started_at > entries[1].started_at);305
}306
307
#[test]308
fn a_body_without_messages_is_unexpected() {309
assert!(matches!(310
parse_call_logs(&json!({})),311
Err(Error::UnexpectedAnswer(_))312
));313
}314
315
#[tokio::test]316
async fn the_list_reads_the_calllogs_conversation() {317
let messages = Messages::with_transport(318
Canned {319
body: json!({"messages": []}),320
requests: Mutex::new(Vec::new()),321
},322
"emea",323
);324
assert!(messages.list_call_logs().await.unwrap().is_empty());325
let requests = messages.transport.requests.lock().unwrap();326
assert_eq!(requests[0].method, Method::Get);327
assert_eq!(328
requests[0].url,329
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/48%3Acalllogs/messages?view=msnp24Equivalent&pageSize=200"330
);331
}332
}@@ -1,3 +1,4 @@
1
pub mod calllog;
1
2
pub mod cards;
2
3
pub mod channel_notifications;
3
4
pub mod conversations;
@@ -18,6 +19,7 @@ pub mod saved;
18
19
pub mod settings;
19
20
pub mod translate;
20
21
22
pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
21
23
pub use cards::{
22
24
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
23
25
};
@@ -1,3 +1,4 @@1
pub mod calllog;1
pub mod cards;2
pub mod cards;2
pub mod channel_notifications;3
pub mod channel_notifications;3
pub mod conversations;4
pub mod conversations;@@ -18,6 +19,7 @@ pub mod saved;18
pub mod settings;19
pub mod settings;19
pub mod translate;20
pub mod translate;20
21
22
pub use calllog::{CallDirection, CallLogEntry, CallOutcome};21
pub use cards::{23
pub use cards::{22
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,24
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,23
};25
};@@ -28,6 +28,7 @@ mod mapping;
28
28
mod markdown;
29
29
mod mentions;
30
30
mod message_actions;
31
mod meeting_join;
31
32
mod message_link;
32
33
mod people;
33
34
mod presence;
@@ -75,7 +76,7 @@ pub use card_widgets::{
75
76
};
76
77
pub use card_width::{TargetWidth, WidthClass};
77
78
pub use chatsvc::{
78
ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,
79
CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,
79
80
SavedMessage, ScheduledDraft, StatusNote, WorkLocation, WorkLocationKind, WorkLocationSource,
80
81
};
81
82
pub use chatsvc::{ChatSection, ChatSectionSettings};
@@ -101,6 +102,10 @@ pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, pu
101
102
pub use mapping::{chat_record, message_record};
102
103
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
103
104
pub use mentions::MentionInput;
105
pub use meeting_join::{
106
MeetingCode, MeetingLink, ThreadMeeting, find_meeting_link, meeting_code_from_id,
107
meeting_link_in_html, parse_meeting_link,
108
};
104
109
pub use message_link::{
105
110
ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,
106
111
};
@@ -28,6 +28,7 @@ mod mapping;28
mod markdown;28
mod markdown;29
mod mentions;29
mod mentions;30
mod message_actions;30
mod message_actions;31
mod meeting_join;31
mod message_link;32
mod message_link;32
mod people;33
mod people;33
mod presence;34
mod presence;@@ -75,7 +76,7 @@ pub use card_widgets::{75
};76
};76
pub use card_width::{TargetWidth, WidthClass};77
pub use card_width::{TargetWidth, WidthClass};77
pub use chatsvc::{78
pub use chatsvc::{78
ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,79
CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,79
SavedMessage, ScheduledDraft, StatusNote, WorkLocation, WorkLocationKind, WorkLocationSource,80
SavedMessage, ScheduledDraft, StatusNote, WorkLocation, WorkLocationKind, WorkLocationSource,80
};81
};81
pub use chatsvc::{ChatSection, ChatSectionSettings};82
pub use chatsvc::{ChatSection, ChatSectionSettings};@@ -101,6 +102,10 @@ pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, pu101
pub use mapping::{chat_record, message_record};102
pub use mapping::{chat_record, message_record};102
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};103
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};103
pub use mentions::MentionInput;104
pub use mentions::MentionInput;105
pub use meeting_join::{106
MeetingCode, MeetingLink, ThreadMeeting, find_meeting_link, meeting_code_from_id,107
meeting_link_in_html, parse_meeting_link,108
};104
pub use message_link::{109
pub use message_link::{105
ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,110
ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,106
};111
};@@ -0,0 +1,292 @@
1
use std::sync::LazyLock;
2
3
use percent_encoding::percent_decode_str;
4
use regex::Regex;
5
use scraper::{Html, Selector};
6
use serde_json::{Value, json};
7
use url::Url;
8
9
const MEETING_HOSTS: [&str; 3] = [
10
"teams.microsoft.com",
11
"teams.cloud.microsoft",
12
"teams.live.com",
13
];
14
const WORK_DOMAIN: &str = "teams.microsoft.com";
15
const LIVE_DOMAIN: &str = "teams.live.com";
16
const MEETUP_SEGMENT: &str = "meetup-join";
17
const MEET_SEGMENT: &str = "meet";
18
const THREAD_PREFIX: &str = "19:";
19
const PASSCODE_KEY: &str = "p";
20
const CONTEXT_KEY: &str = "context";
21
22
static URL_PATTERN: LazyLock<Regex> =
23
LazyLock::new(|| Regex::new(r#"https://[^\s<>"'\])]+"#).expect("url pattern"));
24
25
#[derive(Debug, Clone, PartialEq, Eq)]
26
pub struct ThreadMeeting {
27
pub thread_id: String,
28
pub tenant_id: String,
29
pub organizer_id: String,
30
}
31
32
#[derive(Debug, Clone, PartialEq, Eq)]
33
pub struct MeetingCode {
34
pub code: String,
35
pub passcode: Option<String>,
36
pub url: String,
37
}
38
39
#[derive(Debug, Clone, PartialEq, Eq)]
40
pub enum MeetingLink {
41
Thread(ThreadMeeting),
42
Code(MeetingCode),
43
}
44
45
impl MeetingCode {
46
pub fn meeting_data(&self) -> Value {
47
json!({
48
"meetingCode": self.code,
49
"passcode": self.passcode,
50
"meetingUrl": self.url,
51
})
52
}
53
}
54
55
fn thread_meeting(url: &Url, segments: &[&str]) -> Option<ThreadMeeting> {
56
let thread_id = percent_decode_str(segments.get(2)?).decode_utf8().ok()?;
57
if !thread_id.starts_with(THREAD_PREFIX) {
58
return None;
59
}
60
let context = url.query_pairs().find(|(key, _)| key == CONTEXT_KEY)?.1;
61
let context: Value = serde_json::from_str(&context).ok()?;
62
let text = |key: &str| {
63
context
64
.get(key)?
65
.as_str()
66
.filter(|value| !value.is_empty())
67
.map(str::to_owned)
68
};
69
Some(ThreadMeeting {
70
thread_id: thread_id.into_owned(),
71
tenant_id: text("Tid")?,
72
organizer_id: text("Oid")?,
73
})
74
}
75
76
fn meeting_code(url: &Url, segments: &[&str]) -> Option<MeetingCode> {
77
let code = *segments.get(1)?;
78
if code.is_empty() || !code.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
79
return None;
80
}
81
let passcode = url
82
.query_pairs()
83
.find(|(key, _)| key == PASSCODE_KEY)
84
.map(|(_, value)| value.into_owned())
85
.filter(|value| !value.is_empty());
86
Some(MeetingCode {
87
code: code.to_owned(),
88
passcode,
89
url: url.to_string(),
90
})
91
}
92
93
pub fn parse_meeting_link(text: &str) -> Option<MeetingLink> {
94
let url = Url::parse(text.trim()).ok()?;
95
if url.scheme() != "https" || !MEETING_HOSTS.contains(&url.host_str()?) {
96
return None;
97
}
98
let segments: Vec<&str> = url.path_segments()?.collect();
99
match segments.as_slice() {
100
["l", MEETUP_SEGMENT, ..] => thread_meeting(&url, &segments).map(MeetingLink::Thread),
101
[MEET_SEGMENT, ..] => meeting_code(&url, &segments).map(MeetingLink::Code),
102
_ => None,
103
}
104
}
105
106
pub fn find_meeting_link(text: &str) -> Option<(String, MeetingLink)> {
107
URL_PATTERN.find_iter(text).find_map(|candidate| {
108
let url = candidate
109
.as_str()
110
.trim_end_matches(['.', ',', ';', ':', '!', '?']);
111
parse_meeting_link(url).map(|link| (url.to_owned(), link))
112
})
113
}
114
115
pub fn meeting_link_in_html(html: &str) -> Option<String> {
116
let anchors = Selector::parse("a[href]").ok()?;
117
let fragment = Html::parse_fragment(html);
118
let linked = fragment
119
.select(&anchors)
120
.filter_map(|anchor| anchor.value().attr("href"))
121
.find(|href| parse_meeting_link(href).is_some());
122
match linked {
123
Some(href) => Some(href.to_owned()),
124
None => {
125
let text = fragment.root_element().text().collect::<Vec<_>>().join(" ");
126
find_meeting_link(&text).map(|(url, _)| url)
127
}
128
}
129
}
130
131
pub fn meeting_code_from_id(meeting_id: &str, passcode: &str) -> Option<MeetingCode> {
132
let digits: String = meeting_id
133
.chars()
134
.filter(|c| !c.is_whitespace() && *c != '-')
135
.collect();
136
if digits.len() < 2 || !digits.chars().all(|c| c.is_ascii_digit()) {
137
return None;
138
}
139
let domain = match (
140
digits[..1].parse::<u8>().ok()?,
141
digits[..2].parse::<u8>().ok()?,
142
) {
143
(2..=4, _) | (_, 90..=92) => WORK_DOMAIN,
144
(_, 93..=95) => LIVE_DOMAIN,
145
_ => return None,
146
};
147
let passcode: String = passcode.chars().filter(|c| !c.is_whitespace()).collect();
148
let mut url = Url::parse(&format!("https://{domain}/{MEET_SEGMENT}/{digits}")).ok()?;
149
if !passcode.is_empty() {
150
url.query_pairs_mut().append_pair(PASSCODE_KEY, &passcode);
151
}
152
Some(MeetingCode {
153
code: digits,
154
passcode: (!passcode.is_empty()).then_some(passcode),
155
url: url.to_string(),
156
})
157
}
158
159
#[cfg(test)]
160
mod tests {
161
use super::*;
162
163
const THREAD: &str = "19:meeting_ZDk5@thread.v2";
164
const JOIN_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZDk5%40thread.v2/0?context=%7b%22Tid%22%3a%22tenant-1%22%2c%22Oid%22%3a%22organizer-1%22%7d";
165
166
fn thread(link: Option<MeetingLink>) -> ThreadMeeting {
167
match link {
168
Some(MeetingLink::Thread(meeting)) => meeting,
169
other => panic!("not a thread link: {other:?}"),
170
}
171
}
172
173
#[test]
174
fn a_meetup_join_link_gives_thread_tenant_and_organizer() {
175
let meeting = thread(parse_meeting_link(JOIN_LINK));
176
assert_eq!(meeting.thread_id, THREAD);
177
assert_eq!(meeting.tenant_id, "tenant-1");
178
assert_eq!(meeting.organizer_id, "organizer-1");
179
}
180
181
#[test]
182
fn a_meetup_join_link_on_the_new_host_parses_too() {
183
let link = JOIN_LINK.replace("teams.microsoft.com", "teams.cloud.microsoft");
184
assert_eq!(thread(parse_meeting_link(&link)).thread_id, THREAD);
185
}
186
187
#[test]
188
fn a_meetup_join_link_without_a_usable_context_is_invalid() {
189
let bare = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZDk5%40thread.v2/0";
190
assert_eq!(parse_meeting_link(bare), None);
191
let broken = format!("{bare}?context=not-json");
192
assert_eq!(parse_meeting_link(&broken), None);
193
let no_organizer = format!("{bare}?context=%7b%22Tid%22%3a%22t%22%7d");
194
assert_eq!(parse_meeting_link(&no_organizer), None);
195
let not_a_thread = JOIN_LINK.replace("19%3ameeting", "20%3ameeting");
196
assert_eq!(parse_meeting_link(¬_a_thread), None);
197
}
198
199
#[test]
200
fn a_meet_link_gives_code_and_passcode() {
201
let link = parse_meeting_link("https://teams.cloud.microsoft/meet/123456789012?p=AbC12xyz");
202
let Some(MeetingLink::Code(code)) = link else {
203
panic!("not a code link");
204
};
205
assert_eq!(code.code, "123456789012");
206
assert_eq!(code.passcode.as_deref(), Some("AbC12xyz"));
207
let without = parse_meeting_link("https://teams.microsoft.com/meet/9876543210");
208
let Some(MeetingLink::Code(code)) = without else {
209
panic!("not a code link");
210
};
211
assert_eq!(code.passcode, None);
212
}
213
214
#[test]
215
fn other_links_are_no_meeting_links() {
216
for text in [
217
"",
218
"hello",
219
"https://example.com/meet/123456789012?p=x",
220
"https://teams.microsoft.com/l/message/19:abc/1",
221
"https://teams.microsoft.com/meet/",
222
"https://teams.microsoft.com/meet/bad id",
223
"http://teams.microsoft.com/meet/123456789012",
224
] {
225
assert_eq!(parse_meeting_link(text), None, "{text}");
226
}
227
}
228
229
#[test]
230
fn a_link_is_found_inside_a_sentence_and_inside_markdown() {
231
let sentence = format!("Join here {JOIN_LINK}, see you.");
232
let (url, link) = find_meeting_link(&sentence).unwrap();
233
assert_eq!(url, JOIN_LINK);
234
assert!(matches!(link, MeetingLink::Thread(_)));
235
let markdown = "[our call](https://teams.microsoft.com/meet/123456789012?p=abc)";
236
let (url, _) = find_meeting_link(markdown).unwrap();
237
assert_eq!(url, "https://teams.microsoft.com/meet/123456789012?p=abc");
238
assert_eq!(find_meeting_link("see https://example.com/x"), None);
239
}
240
241
#[test]
242
fn a_meeting_link_is_found_in_an_anchor_or_in_plain_html_text() {
243
let anchor = format!("<p>Join: <a href=\"{JOIN_LINK}\">Click here</a></p>");
244
assert_eq!(meeting_link_in_html(&anchor).as_deref(), Some(JOIN_LINK));
245
let plain = format!("<p>Join {JOIN_LINK}</p>");
246
assert_eq!(meeting_link_in_html(&plain).as_deref(), Some(JOIN_LINK));
247
assert_eq!(
248
meeting_link_in_html("<p>see <a href=\"https://example.com\">x</a></p>"),
249
None
250
);
251
}
252
253
#[test]
254
fn a_meeting_id_with_spaces_and_a_passcode_becomes_a_meet_link() {
255
let code = meeting_code_from_id("234 567 890 123", " Ab Cd12 ").unwrap();
256
assert_eq!(code.code, "234567890123");
257
assert_eq!(code.passcode.as_deref(), Some("AbCd12"));
258
assert_eq!(
259
code.url,
260
"https://teams.microsoft.com/meet/234567890123?p=AbCd12"
261
);
262
assert_eq!(
263
meeting_code_from_id("93-456-789-012", "").unwrap().url,
264
"https://teams.live.com/meet/93456789012"
265
);
266
assert_eq!(
267
meeting_code_from_id("91 234 567 890", "x").unwrap().code,
268
"91234567890"
269
);
270
}
271
272
#[test]
273
fn a_meeting_id_needs_digits_from_a_known_cloud() {
274
assert_eq!(meeting_code_from_id("", "x"), None);
275
assert_eq!(meeting_code_from_id("12abc", "x"), None);
276
assert_eq!(meeting_code_from_id("1234567890", "x"), None);
277
assert_eq!(meeting_code_from_id("96 1234 5678", "x"), None);
278
}
279
280
#[test]
281
fn the_request_body_carries_code_passcode_and_url() {
282
let code = meeting_code_from_id("234567890123", "pw").unwrap();
283
assert_eq!(
284
code.meeting_data(),
285
json!({
286
"meetingCode": "234567890123",
287
"passcode": "pw",
288
"meetingUrl": "https://teams.microsoft.com/meet/234567890123?p=pw",
289
})
290
);
291
}
292
}
@@ -0,0 +1,292 @@1
use std::sync::LazyLock;2
3
use percent_encoding::percent_decode_str;4
use regex::Regex;5
use scraper::{Html, Selector};6
use serde_json::{Value, json};7
use url::Url;8
9
const MEETING_HOSTS: [&str; 3] = [10
"teams.microsoft.com",11
"teams.cloud.microsoft",12
"teams.live.com",13
];14
const WORK_DOMAIN: &str = "teams.microsoft.com";15
const LIVE_DOMAIN: &str = "teams.live.com";16
const MEETUP_SEGMENT: &str = "meetup-join";17
const MEET_SEGMENT: &str = "meet";18
const THREAD_PREFIX: &str = "19:";19
const PASSCODE_KEY: &str = "p";20
const CONTEXT_KEY: &str = "context";21
22
static URL_PATTERN: LazyLock<Regex> =23
LazyLock::new(|| Regex::new(r#"https://[^\s<>"'\])]+"#).expect("url pattern"));24
25
#[derive(Debug, Clone, PartialEq, Eq)]26
pub struct ThreadMeeting {27
pub thread_id: String,28
pub tenant_id: String,29
pub organizer_id: String,30
}31
32
#[derive(Debug, Clone, PartialEq, Eq)]33
pub struct MeetingCode {34
pub code: String,35
pub passcode: Option<String>,36
pub url: String,37
}38
39
#[derive(Debug, Clone, PartialEq, Eq)]40
pub enum MeetingLink {41
Thread(ThreadMeeting),42
Code(MeetingCode),43
}44
45
impl MeetingCode {46
pub fn meeting_data(&self) -> Value {47
json!({48
"meetingCode": self.code,49
"passcode": self.passcode,50
"meetingUrl": self.url,51
})52
}53
}54
55
fn thread_meeting(url: &Url, segments: &[&str]) -> Option<ThreadMeeting> {56
let thread_id = percent_decode_str(segments.get(2)?).decode_utf8().ok()?;57
if !thread_id.starts_with(THREAD_PREFIX) {58
return None;59
}60
let context = url.query_pairs().find(|(key, _)| key == CONTEXT_KEY)?.1;61
let context: Value = serde_json::from_str(&context).ok()?;62
let text = |key: &str| {63
context64
.get(key)?65
.as_str()66
.filter(|value| !value.is_empty())67
.map(str::to_owned)68
};69
Some(ThreadMeeting {70
thread_id: thread_id.into_owned(),71
tenant_id: text("Tid")?,72
organizer_id: text("Oid")?,73
})74
}75
76
fn meeting_code(url: &Url, segments: &[&str]) -> Option<MeetingCode> {77
let code = *segments.get(1)?;78
if code.is_empty() || !code.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {79
return None;80
}81
let passcode = url82
.query_pairs()83
.find(|(key, _)| key == PASSCODE_KEY)84
.map(|(_, value)| value.into_owned())85
.filter(|value| !value.is_empty());86
Some(MeetingCode {87
code: code.to_owned(),88
passcode,89
url: url.to_string(),90
})91
}92
93
pub fn parse_meeting_link(text: &str) -> Option<MeetingLink> {94
let url = Url::parse(text.trim()).ok()?;95
if url.scheme() != "https" || !MEETING_HOSTS.contains(&url.host_str()?) {96
return None;97
}98
let segments: Vec<&str> = url.path_segments()?.collect();99
match segments.as_slice() {100
["l", MEETUP_SEGMENT, ..] => thread_meeting(&url, &segments).map(MeetingLink::Thread),101
[MEET_SEGMENT, ..] => meeting_code(&url, &segments).map(MeetingLink::Code),102
_ => None,103
}104
}105
106
pub fn find_meeting_link(text: &str) -> Option<(String, MeetingLink)> {107
URL_PATTERN.find_iter(text).find_map(|candidate| {108
let url = candidate109
.as_str()110
.trim_end_matches(['.', ',', ';', ':', '!', '?']);111
parse_meeting_link(url).map(|link| (url.to_owned(), link))112
})113
}114
115
pub fn meeting_link_in_html(html: &str) -> Option<String> {116
let anchors = Selector::parse("a[href]").ok()?;117
let fragment = Html::parse_fragment(html);118
let linked = fragment119
.select(&anchors)120
.filter_map(|anchor| anchor.value().attr("href"))121
.find(|href| parse_meeting_link(href).is_some());122
match linked {123
Some(href) => Some(href.to_owned()),124
None => {125
let text = fragment.root_element().text().collect::<Vec<_>>().join(" ");126
find_meeting_link(&text).map(|(url, _)| url)127
}128
}129
}130
131
pub fn meeting_code_from_id(meeting_id: &str, passcode: &str) -> Option<MeetingCode> {132
let digits: String = meeting_id133
.chars()134
.filter(|c| !c.is_whitespace() && *c != '-')135
.collect();136
if digits.len() < 2 || !digits.chars().all(|c| c.is_ascii_digit()) {137
return None;138
}139
let domain = match (140
digits[..1].parse::<u8>().ok()?,141
digits[..2].parse::<u8>().ok()?,142
) {143
(2..=4, _) | (_, 90..=92) => WORK_DOMAIN,144
(_, 93..=95) => LIVE_DOMAIN,145
_ => return None,146
};147
let passcode: String = passcode.chars().filter(|c| !c.is_whitespace()).collect();148
let mut url = Url::parse(&format!("https://{domain}/{MEET_SEGMENT}/{digits}")).ok()?;149
if !passcode.is_empty() {150
url.query_pairs_mut().append_pair(PASSCODE_KEY, &passcode);151
}152
Some(MeetingCode {153
code: digits,154
passcode: (!passcode.is_empty()).then_some(passcode),155
url: url.to_string(),156
})157
}158
159
#[cfg(test)]160
mod tests {161
use super::*;162
163
const THREAD: &str = "19:meeting_ZDk5@thread.v2";164
const JOIN_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZDk5%40thread.v2/0?context=%7b%22Tid%22%3a%22tenant-1%22%2c%22Oid%22%3a%22organizer-1%22%7d";165
166
fn thread(link: Option<MeetingLink>) -> ThreadMeeting {167
match link {168
Some(MeetingLink::Thread(meeting)) => meeting,169
other => panic!("not a thread link: {other:?}"),170
}171
}172
173
#[test]174
fn a_meetup_join_link_gives_thread_tenant_and_organizer() {175
let meeting = thread(parse_meeting_link(JOIN_LINK));176
assert_eq!(meeting.thread_id, THREAD);177
assert_eq!(meeting.tenant_id, "tenant-1");178
assert_eq!(meeting.organizer_id, "organizer-1");179
}180
181
#[test]182
fn a_meetup_join_link_on_the_new_host_parses_too() {183
let link = JOIN_LINK.replace("teams.microsoft.com", "teams.cloud.microsoft");184
assert_eq!(thread(parse_meeting_link(&link)).thread_id, THREAD);185
}186
187
#[test]188
fn a_meetup_join_link_without_a_usable_context_is_invalid() {189
let bare = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZDk5%40thread.v2/0";190
assert_eq!(parse_meeting_link(bare), None);191
let broken = format!("{bare}?context=not-json");192
assert_eq!(parse_meeting_link(&broken), None);193
let no_organizer = format!("{bare}?context=%7b%22Tid%22%3a%22t%22%7d");194
assert_eq!(parse_meeting_link(&no_organizer), None);195
let not_a_thread = JOIN_LINK.replace("19%3ameeting", "20%3ameeting");196
assert_eq!(parse_meeting_link(¬_a_thread), None);197
}198
199
#[test]200
fn a_meet_link_gives_code_and_passcode() {201
let link = parse_meeting_link("https://teams.cloud.microsoft/meet/123456789012?p=AbC12xyz");202
let Some(MeetingLink::Code(code)) = link else {203
panic!("not a code link");204
};205
assert_eq!(code.code, "123456789012");206
assert_eq!(code.passcode.as_deref(), Some("AbC12xyz"));207
let without = parse_meeting_link("https://teams.microsoft.com/meet/9876543210");208
let Some(MeetingLink::Code(code)) = without else {209
panic!("not a code link");210
};211
assert_eq!(code.passcode, None);212
}213
214
#[test]215
fn other_links_are_no_meeting_links() {216
for text in [217
"",218
"hello",219
"https://example.com/meet/123456789012?p=x",220
"https://teams.microsoft.com/l/message/19:abc/1",221
"https://teams.microsoft.com/meet/",222
"https://teams.microsoft.com/meet/bad id",223
"http://teams.microsoft.com/meet/123456789012",224
] {225
assert_eq!(parse_meeting_link(text), None, "{text}");226
}227
}228
229
#[test]230
fn a_link_is_found_inside_a_sentence_and_inside_markdown() {231
let sentence = format!("Join here {JOIN_LINK}, see you.");232
let (url, link) = find_meeting_link(&sentence).unwrap();233
assert_eq!(url, JOIN_LINK);234
assert!(matches!(link, MeetingLink::Thread(_)));235
let markdown = "[our call](https://teams.microsoft.com/meet/123456789012?p=abc)";236
let (url, _) = find_meeting_link(markdown).unwrap();237
assert_eq!(url, "https://teams.microsoft.com/meet/123456789012?p=abc");238
assert_eq!(find_meeting_link("see https://example.com/x"), None);239
}240
241
#[test]242
fn a_meeting_link_is_found_in_an_anchor_or_in_plain_html_text() {243
let anchor = format!("<p>Join: <a href=\"{JOIN_LINK}\">Click here</a></p>");244
assert_eq!(meeting_link_in_html(&anchor).as_deref(), Some(JOIN_LINK));245
let plain = format!("<p>Join {JOIN_LINK}</p>");246
assert_eq!(meeting_link_in_html(&plain).as_deref(), Some(JOIN_LINK));247
assert_eq!(248
meeting_link_in_html("<p>see <a href=\"https://example.com\">x</a></p>"),249
None250
);251
}252
253
#[test]254
fn a_meeting_id_with_spaces_and_a_passcode_becomes_a_meet_link() {255
let code = meeting_code_from_id("234 567 890 123", " Ab Cd12 ").unwrap();256
assert_eq!(code.code, "234567890123");257
assert_eq!(code.passcode.as_deref(), Some("AbCd12"));258
assert_eq!(259
code.url,260
"https://teams.microsoft.com/meet/234567890123?p=AbCd12"261
);262
assert_eq!(263
meeting_code_from_id("93-456-789-012", "").unwrap().url,264
"https://teams.live.com/meet/93456789012"265
);266
assert_eq!(267
meeting_code_from_id("91 234 567 890", "x").unwrap().code,268
"91234567890"269
);270
}271
272
#[test]273
fn a_meeting_id_needs_digits_from_a_known_cloud() {274
assert_eq!(meeting_code_from_id("", "x"), None);275
assert_eq!(meeting_code_from_id("12abc", "x"), None);276
assert_eq!(meeting_code_from_id("1234567890", "x"), None);277
assert_eq!(meeting_code_from_id("96 1234 5678", "x"), None);278
}279
280
#[test]281
fn the_request_body_carries_code_passcode_and_url() {282
let code = meeting_code_from_id("234567890123", "pw").unwrap();283
assert_eq!(284
code.meeting_data(),285
json!({286
"meetingCode": "234567890123",287
"passcode": "pw",288
"meetingUrl": "https://teams.microsoft.com/meet/234567890123?p=pw",289
})290
);291
}292
}@@ -1,4 +1,4 @@
1
use chatsvc::{EventKind, ForwardResult, MessageEvent, PinnedMessage, SavedMessage};
1
use chatsvc::{CallLogEntry, EventKind, ForwardResult, MessageEvent, PinnedMessage, SavedMessage};
2
2
3
3
use crate::engine::{Conversation, SyncEngine};
4
4
use crate::error::{Error, Result};
@@ -64,6 +64,10 @@ impl<R: Remote> SyncEngine<R> {
64
64
self.remote.list_saved().await
65
65
}
66
66
67
pub async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
68
self.remote.list_call_logs().await
69
}
70
67
71
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
68
72
self.ensure_chat(chat_id)?;
69
73
self.remote.chat_pins(chat_id).await
@@ -1,4 +1,4 @@1
use chatsvc::{EventKind, ForwardResult, MessageEvent, PinnedMessage, SavedMessage};1
use chatsvc::{CallLogEntry, EventKind, ForwardResult, MessageEvent, PinnedMessage, SavedMessage};2
2
3
use crate::engine::{Conversation, SyncEngine};3
use crate::engine::{Conversation, SyncEngine};4
use crate::error::{Error, Result};4
use crate::error::{Error, Result};@@ -64,6 +64,10 @@ impl<R: Remote> SyncEngine<R> {64
self.remote.list_saved().await64
self.remote.list_saved().await65
}65
}66
66
67
pub async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {68
self.remote.list_call_logs().await69
}70
67
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {71
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {68
self.ensure_chat(chat_id)?;72
self.ensure_chat(chat_id)?;69
self.remote.chat_pins(chat_id).await73
self.remote.chat_pins(chat_id).await@@ -1,5 +1,5 @@
1
1
use chatsvc::{
2
CardActions, ChatApp, ConversationRef, Conversations, ForcedAvailability, ForwardResult, Gif,
2
CallLogEntry, CardActions, ChatApp, ConversationRef, Conversations, ForcedAvailability, ForwardResult, Gif,
3
3
Gifs, InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient,
4
4
LinkInfo, MemberHorizon, MessageLanguage, MessageLinks, Messages, PinnedMessage, Pins,
5
5
PresenceService, PresenceStatus, Receipts, SavedMessage, ScheduledDraft, ScheduledDrafts,
@@ -295,6 +295,10 @@ pub trait Remote {
295
295
Err(Error::Unsupported("saved messages"))
296
296
}
297
297
298
async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
299
Err(Error::Unsupported("call history"))
300
}
301
298
302
async fn chat_pins(&self, _chat_id: &str) -> Result<Vec<PinnedMessage>> {
299
303
Err(Error::Unsupported("pinned messages"))
300
304
}
@@ -862,6 +866,10 @@ impl Remote for Graph {
862
866
Ok(Messages::new(self.session()).list_saved().await?)
863
867
}
864
868
869
async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {
870
Ok(Messages::new(self.session()).list_call_logs().await?)
871
}
872
865
873
async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
866
874
Ok(Pins::new(self.session()).chat_pins(chat_id).await?)
867
875
}
@@ -1,5 +1,5 @@1
use chatsvc::{1
use chatsvc::{2
CardActions, ChatApp, ConversationRef, Conversations, ForcedAvailability, ForwardResult, Gif,2
CallLogEntry, CardActions, ChatApp, ConversationRef, Conversations, ForcedAvailability, ForwardResult, Gif,3
Gifs, InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient,3
Gifs, InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient,4
LinkInfo, MemberHorizon, MessageLanguage, MessageLinks, Messages, PinnedMessage, Pins,4
LinkInfo, MemberHorizon, MessageLanguage, MessageLinks, Messages, PinnedMessage, Pins,5
PresenceService, PresenceStatus, Receipts, SavedMessage, ScheduledDraft, ScheduledDrafts,5
PresenceService, PresenceStatus, Receipts, SavedMessage, ScheduledDraft, ScheduledDrafts,@@ -295,6 +295,10 @@ pub trait Remote {295
Err(Error::Unsupported("saved messages"))295
Err(Error::Unsupported("saved messages"))296
}296
}297
297
298
async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {299
Err(Error::Unsupported("call history"))300
}301
298
async fn chat_pins(&self, _chat_id: &str) -> Result<Vec<PinnedMessage>> {302
async fn chat_pins(&self, _chat_id: &str) -> Result<Vec<PinnedMessage>> {299
Err(Error::Unsupported("pinned messages"))303
Err(Error::Unsupported("pinned messages"))300
}304
}@@ -862,6 +866,10 @@ impl Remote for Graph {862
Ok(Messages::new(self.session()).list_saved().await?)866
Ok(Messages::new(self.session()).list_saved().await?)863
}867
}864
868
869
async fn list_call_logs(&self) -> Result<Vec<CallLogEntry>> {870
Ok(Messages::new(self.session()).list_call_logs().await?)871
}872
865
async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {873
async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {866
Ok(Pins::new(self.session()).chat_pins(chat_id).await?)874
Ok(Pins::new(self.session()).chat_pins(chat_id).await?)867
}875
}