BlueGit

ict rusty-teams

feat(calls): people panel, roles, lock, attendee mic and camera, invite, meeting options

- People button opens a 320 px panel (closes the chat): lobby, raised hands, role groups, row menu
- Lock meeting (updateMeetingSettings), role change (updateParticipantRole), per-attendee mic and camera (publishState / removeState)
- Attendee mic and camera for everyone and meeting options dialog through the meetings/v1/options service
- Invite into a meeting or group call (addParticipantAndModality); 1:1 creates a group chat and reuses the existing escalation
- Roster carries meeting role and attendee limits; meetingCapability feeds the Locked chip
- Demo gallery scene: roles, blocked mic, lobby, hands; layout guard covers the open panel
- Unit tests for every new request body, panel grouping, options dialog and commands

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 7 weeks ago

Hash
7020c0e4c891f13c4693e69b8870536208815821
Parent
1136fb3e
23 files changed +2503 −45
ROADMAP.md +2 −0
@@ -170,6 +170,8 @@ Feature parity with the Microsoft Teams desktop client.
170 170 | 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 |
171 171 | 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 |
172 172 | 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 |
173 | People panel, roles, lock, invite | Partial | People button before chat opens a 320 px panel (closes the chat): "People (N)" with Invite and "...", lobby with Admit / Deny / Admit all, raised hands in queue order, groups Organizers / Presenters / Attendees (flat "In this call" in 1:1 and group calls), row "..." with Pin, Spotlight, Mute, Disable / Allow mic and camera, Make presenter / attendee, Remove. "..." menu: Mute all, Lock / Unlock meeting ("Locked" chip, banner for organizers), mic and camera off for attendees, Add people (1:1). Invite adds a person to the running meeting or group call; in a 1:1 call it creates a group chat and escalates. Request bodies from the Teams code and unit tested; demo checked, nothing sent to the live service |
174 | Meeting options | Partial | Organizer "..." > Meeting options: lobby bypass, who can present, attendee mic and camera, meeting chat (On / In-meeting only / Off), reactions, record automatically. Reads and writes the `meetings/v1/options` service from the captured shapes, one request per changed option, errors inline. Not yet read or written live |
173 175 | 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 |
174 176 | 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 |
175 177 | Camera effects | Partial | Camera menu "Effects" and Settings > Devices: Mirror my video (self view and camera test only, default on), Auto framing, Adjust brightness, Soft focus (Low / Medium / High in Settings). Framing, brightness and soft focus run on the send path, so others see them; one segmentation mask per frame is shared with the background. Crop planner, gamma and blend are unit tested; not yet checked on a real camera |
@@ -170,6 +170,8 @@ Feature parity with the Microsoft Teams desktop client.
170| 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| 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 |
171| 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| 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 |
172| 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| 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 |
173| People panel, roles, lock, invite | Partial | People button before chat opens a 320 px panel (closes the chat): "People (N)" with Invite and "...", lobby with Admit / Deny / Admit all, raised hands in queue order, groups Organizers / Presenters / Attendees (flat "In this call" in 1:1 and group calls), row "..." with Pin, Spotlight, Mute, Disable / Allow mic and camera, Make presenter / attendee, Remove. "..." menu: Mute all, Lock / Unlock meeting ("Locked" chip, banner for organizers), mic and camera off for attendees, Add people (1:1). Invite adds a person to the running meeting or group call; in a 1:1 call it creates a group chat and escalates. Request bodies from the Teams code and unit tested; demo checked, nothing sent to the live service |
174| Meeting options | Partial | Organizer "..." > Meeting options: lobby bypass, who can present, attendee mic and camera, meeting chat (On / In-meeting only / Off), reactions, record automatically. Reads and writes the `meetings/v1/options` service from the captured shapes, one request per changed option, errors inline. Not yet read or written live |
173| 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 |
175| 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 |
174| 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 |
176| 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 |
175| Camera effects | Partial | Camera menu "Effects" and Settings > Devices: Mirror my video (self view and camera test only, default on), Auto framing, Adjust brightness, Soft focus (Low / Medium / High in Settings). Framing, brightness and soft focus run on the send path, so others see them; one segmentation mask per frame is shared with the background. Crop planner, gamma and blend are unit tested; not yet checked on a real camera |
177| Camera effects | Partial | Camera menu "Effects" and Settings > Devices: Mirror my video (self view and camera test only, default on), Auto framing, Adjust brightness, Soft focus (Low / Medium / High in Settings). Framing, brightness and soft focus run on the send path, so others see them; one segmentation mask per frame is shared with the background. Crop planner, gamma and blend are unit tested; not yet checked on a real camera |
crates/app/src/call/actions.rs +19 −0
@@ -339,6 +339,20 @@ impl AppState {
339 339 self.begin_breakout_move(moved, cx);
340 340 return;
341 341 }
342 CallUpdate::MeetingOptions(result) => {
343 if let Some(dialog) = call.options_dialog.as_mut() {
344 dialog.loaded(result);
345 }
346 cx.notify();
347 return;
348 }
349 CallUpdate::MeetingOptionsSaved(result) => {
350 if call.options_dialog.as_mut().is_some_and(|dialog| dialog.saved(result)) {
351 call.options_dialog = None;
352 }
353 cx.notify();
354 return;
355 }
342 356 _ => {}
343 357 }
344 358 if let (CallUpdate::Caption(entry), Some(thread)) = (&update, call.chat_thread()) {
@@ -516,6 +530,9 @@ impl AppState {
516 530 return;
517 531 };
518 532 call.chat_open = !call.chat_open;
533 if call.chat_open {
534 call.people_open = false;
535 }
519 536 cx.emit(AppEvent::Call);
520 537 cx.notify();
521 538 }
@@ -1339,6 +1356,7 @@ mod tests {
1339 1356 }),
1340 1357 spotlight: None,
1341 1358 organizer: false,
1359 ..Default::default()
1342 1360 }]),
1343 1361 cx,
1344 1362 );
@@ -1372,6 +1390,7 @@ mod tests {
1372 1390 rank: 1,
1373 1391 }),
1374 1392 organizer: false,
1393 ..Default::default()
1375 1394 }
1376 1395 }
1377 1396
@@ -339,6 +339,20 @@ impl AppState {
339 self.begin_breakout_move(moved, cx);
339 self.begin_breakout_move(moved, cx);
340 return;
340 return;
341 }
341 }
342 CallUpdate::MeetingOptions(result) => {
343 if let Some(dialog) = call.options_dialog.as_mut() {
344 dialog.loaded(result);
345 }
346 cx.notify();
347 return;
348 }
349 CallUpdate::MeetingOptionsSaved(result) => {
350 if call.options_dialog.as_mut().is_some_and(|dialog| dialog.saved(result)) {
351 call.options_dialog = None;
352 }
353 cx.notify();
354 return;
355 }
342 _ => {}
356 _ => {}
343 }
357 }
344 if let (CallUpdate::Caption(entry), Some(thread)) = (&update, call.chat_thread()) {
358 if let (CallUpdate::Caption(entry), Some(thread)) = (&update, call.chat_thread()) {
@@ -516,6 +530,9 @@ impl AppState {
516 return;
530 return;
517 };
531 };
518 call.chat_open = !call.chat_open;
532 call.chat_open = !call.chat_open;
533 if call.chat_open {
534 call.people_open = false;
535 }
519 cx.emit(AppEvent::Call);
536 cx.emit(AppEvent::Call);
520 cx.notify();
537 cx.notify();
521 }
538 }
@@ -1339,6 +1356,7 @@ mod tests {
1339 }),
1356 }),
1340 spotlight: None,
1357 spotlight: None,
1341 organizer: false,
1358 organizer: false,
1359 ..Default::default()
1342 }]),
1360 }]),
1343 cx,
1361 cx,
1344 );
1362 );
@@ -1372,6 +1390,7 @@ mod tests {
1372 rank: 1,
1390 rank: 1,
1373 }),
1391 }),
1374 organizer: false,
1392 organizer: false,
1393 ..Default::default()
1375 }
1394 }
1376 }
1395 }
1377
1396
crates/app/src/call/demo.rs +73 −2
@@ -4,10 +4,10 @@ use calling::CameraDevice;
4 4 use calling::video_frame::bgra_from_i420;
5 5 use calling::video_pattern::{PatternKind, pattern_frame};
6 6 use calling::{
7 AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallHealth,
7 AttendeeLimits, AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallHealth,
8 8 CallState, CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice,
9 9 DeviceLists, EndReason, HealthSample, HoldState, IncomingRing, Limitation, MediaPath,
10 MeetingTarget, NetworkLevel, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,
10 MeetingCapability, MeetingOptions, MeetingRole, MeetingTarget, Modality, NetworkLevel, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,
11 11 ShareKind, ShareSource, TransportDetails, VideoKey, call_channel,
12 12 };
13 13
@@ -255,6 +255,8 @@ fn roster_of(people: &[Person], cameras: usize) -> Vec<RosterEntry> {
255 255 sharing: false,
256 256 hand: None,
257 257 spotlight: None,
258 role: Some(demo_role(index)),
259 limits: demo_limits(index),
258 260 organizer: false,
259 261 })
260 262 .collect()
@@ -473,6 +475,7 @@ async fn speak_until_hangup(
473 475 let mut output = DeviceChoice::SystemDefault;
474 476 let mut ticks = 0u32;
475 477 let mut share_sound = false;
478 let mut capability = MeetingCapability::default();
476 479 let mut tick = interval(LEVEL_PERIOD);
477 480 loop {
478 481 tokio::select! {
@@ -574,6 +577,38 @@ async fn speak_until_hangup(
574 577 roster.iter_mut().filter(|entry| entry.mri != DEMO_OWN_MRI).for_each(|entry| entry.muted = true);
575 578 control.send(CallUpdate::Roster(roster.clone()));
576 579 }
580 Some(CallCommand::SetLock(locked)) => {
581 capability.locked = locked;
582 control.send(CallUpdate::Capability(capability));
583 }
584 Some(CallCommand::SetRole { mri, role }) => {
585 roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.role = Some(role));
586 control.send(CallUpdate::Roster(roster.clone()));
587 }
588 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
589 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
590 let (blocked, released) = match modality {
591 Modality::Mic => (&mut entry.limits.mic_blocked, &mut entry.limits.mic_released),
592 Modality::Camera => (&mut entry.limits.camera_blocked, &mut entry.limits.camera_released),
593 };
594 *blocked = (!allowed).then(|| demo_state("demo-blocked", 1));
595 *released = None;
596 }
597 control.send(CallUpdate::Roster(roster.clone()));
598 }
599 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
600 capability.attendee_mic_off = mic_off;
601 capability.attendee_camera_off = camera_off;
602 control.send(CallUpdate::Capability(capability));
603 }
604 Some(CallCommand::Invite { callees, .. }) => {
605 for callee in callees {
606 roster.push(RosterEntry { mri: callee.mri, display_name: callee.display_name, role: Some(MeetingRole::Attendee), ..RosterEntry::default() });
607 }
608 control.send(CallUpdate::Roster(roster.clone()));
609 }
610 Some(CallCommand::LoadMeetingOptions) => control.send(CallUpdate::MeetingOptions(Ok(demo_options()))),
611 Some(CallCommand::SaveMeetingOptions(_)) => control.send(CallUpdate::MeetingOptionsSaved(Ok(demo_options()))),
577 612 Some(CallCommand::Spotlight { mri }) => {
578 613 let rank = roster.iter().filter_map(|entry| entry.spotlight.as_ref().map(|state| state.rank)).max().unwrap_or(0) + 1;
579 614 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
@@ -616,6 +651,38 @@ async fn speak_until_hangup(
616 651 }
617 652 }
618 653
654 fn demo_role(index: usize) -> MeetingRole {
655 match index {
656 3 => MeetingRole::Organizer,
657 0 | 1 => MeetingRole::Presenter,
658 _ => MeetingRole::Attendee,
659 }
660 }
661
662 fn demo_limits(index: usize) -> AttendeeLimits {
663 AttendeeLimits {
664 mic_blocked: (index == 5).then(|| demo_state("demo-blocked-5", 1)),
665 ..AttendeeLimits::default()
666 }
667 }
668
669 fn demo_state(id: &str, rank: u64) -> PublishedState {
670 PublishedState { state_id: id.to_owned(), rank }
671 }
672
673 fn demo_options() -> MeetingOptions {
674 let option = |name: &str, value: serde_json::Value| serde_json::json!({"name": name, "currentValue": value});
675 MeetingOptions::from_response(&serde_json::json!({"options": [
676 option("AutoAdmittedUsers", serde_json::json!("EveryoneInCompany")),
677 option("PresenterOption", serde_json::json!("Everyone")),
678 option("AttendeeRestrictions", serde_json::json!("UnRestricted")),
679 option("AllowMeetingChat", serde_json::json!("Enabled")),
680 option("AllowTeamsMeetingReactions", serde_json::json!(true)),
681 option("AutoRecordAndTranscribeMode", serde_json::json!("Off")),
682 ]}))
683 .expect("the demo options are complete")
684 }
685
619 686 fn demo_organizer() -> RosterEntry {
620 687 RosterEntry {
621 688 mri: DEMO_OWN_MRI.to_owned(),
@@ -627,6 +694,8 @@ fn demo_organizer() -> RosterEntry {
627 694 hand: None,
628 695 spotlight: None,
629 696 organizer: true,
697 role: Some(MeetingRole::Organizer),
698 ..Default::default()
630 699 }
631 700 }
632 701
@@ -641,6 +710,7 @@ fn demo_waiting(index: usize, name: &str) -> RosterEntry {
641 710 hand: None,
642 711 spotlight: None,
643 712 organizer: false,
713 ..Default::default()
644 714 }
645 715 }
646 716
@@ -700,6 +770,7 @@ fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {
700 770 hand: Some(demo_hand(next_rank)),
701 771 spotlight: None,
702 772 organizer: false,
773 ..Default::default()
703 774 }),
704 775 }
705 776 }
@@ -4,10 +4,10 @@ use calling::CameraDevice;
4use calling::video_frame::bgra_from_i420;
4use calling::video_frame::bgra_from_i420;
5use calling::video_pattern::{PatternKind, pattern_frame};
5use calling::video_pattern::{PatternKind, pattern_frame};
6use calling::{
6use calling::{
7 AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallHealth,
7 AttendeeLimits, AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallHealth,
8 CallState, CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice,
8 CallState, CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice,
9 DeviceLists, EndReason, HealthSample, HoldState, IncomingRing, Limitation, MediaPath,
9 DeviceLists, EndReason, HealthSample, HoldState, IncomingRing, Limitation, MediaPath,
10 MeetingTarget, NetworkLevel, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,
10 MeetingCapability, MeetingOptions, MeetingRole, MeetingTarget, Modality, NetworkLevel, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,
11 ShareKind, ShareSource, TransportDetails, VideoKey, call_channel,
11 ShareKind, ShareSource, TransportDetails, VideoKey, call_channel,
12};
12};
13
13
@@ -255,6 +255,8 @@ fn roster_of(people: &[Person], cameras: usize) -> Vec<RosterEntry> {
255 sharing: false,
255 sharing: false,
256 hand: None,
256 hand: None,
257 spotlight: None,
257 spotlight: None,
258 role: Some(demo_role(index)),
259 limits: demo_limits(index),
258 organizer: false,
260 organizer: false,
259 })
261 })
260 .collect()
262 .collect()
@@ -473,6 +475,7 @@ async fn speak_until_hangup(
473 let mut output = DeviceChoice::SystemDefault;
475 let mut output = DeviceChoice::SystemDefault;
474 let mut ticks = 0u32;
476 let mut ticks = 0u32;
475 let mut share_sound = false;
477 let mut share_sound = false;
478 let mut capability = MeetingCapability::default();
476 let mut tick = interval(LEVEL_PERIOD);
479 let mut tick = interval(LEVEL_PERIOD);
477 loop {
480 loop {
478 tokio::select! {
481 tokio::select! {
@@ -574,6 +577,38 @@ async fn speak_until_hangup(
574 roster.iter_mut().filter(|entry| entry.mri != DEMO_OWN_MRI).for_each(|entry| entry.muted = true);
577 roster.iter_mut().filter(|entry| entry.mri != DEMO_OWN_MRI).for_each(|entry| entry.muted = true);
575 control.send(CallUpdate::Roster(roster.clone()));
578 control.send(CallUpdate::Roster(roster.clone()));
576 }
579 }
580 Some(CallCommand::SetLock(locked)) => {
581 capability.locked = locked;
582 control.send(CallUpdate::Capability(capability));
583 }
584 Some(CallCommand::SetRole { mri, role }) => {
585 roster.iter_mut().filter(|entry| entry.mri == mri).for_each(|entry| entry.role = Some(role));
586 control.send(CallUpdate::Roster(roster.clone()));
587 }
588 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
589 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
590 let (blocked, released) = match modality {
591 Modality::Mic => (&mut entry.limits.mic_blocked, &mut entry.limits.mic_released),
592 Modality::Camera => (&mut entry.limits.camera_blocked, &mut entry.limits.camera_released),
593 };
594 *blocked = (!allowed).then(|| demo_state("demo-blocked", 1));
595 *released = None;
596 }
597 control.send(CallUpdate::Roster(roster.clone()));
598 }
599 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
600 capability.attendee_mic_off = mic_off;
601 capability.attendee_camera_off = camera_off;
602 control.send(CallUpdate::Capability(capability));
603 }
604 Some(CallCommand::Invite { callees, .. }) => {
605 for callee in callees {
606 roster.push(RosterEntry { mri: callee.mri, display_name: callee.display_name, role: Some(MeetingRole::Attendee), ..RosterEntry::default() });
607 }
608 control.send(CallUpdate::Roster(roster.clone()));
609 }
610 Some(CallCommand::LoadMeetingOptions) => control.send(CallUpdate::MeetingOptions(Ok(demo_options()))),
611 Some(CallCommand::SaveMeetingOptions(_)) => control.send(CallUpdate::MeetingOptionsSaved(Ok(demo_options()))),
577 Some(CallCommand::Spotlight { mri }) => {
612 Some(CallCommand::Spotlight { mri }) => {
578 let rank = roster.iter().filter_map(|entry| entry.spotlight.as_ref().map(|state| state.rank)).max().unwrap_or(0) + 1;
613 let rank = roster.iter().filter_map(|entry| entry.spotlight.as_ref().map(|state| state.rank)).max().unwrap_or(0) + 1;
579 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
614 if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
@@ -616,6 +651,38 @@ async fn speak_until_hangup(
616 }
651 }
617}
652}
618
653
654fn demo_role(index: usize) -> MeetingRole {
655 match index {
656 3 => MeetingRole::Organizer,
657 0 | 1 => MeetingRole::Presenter,
658 _ => MeetingRole::Attendee,
659 }
660}
661
662fn demo_limits(index: usize) -> AttendeeLimits {
663 AttendeeLimits {
664 mic_blocked: (index == 5).then(|| demo_state("demo-blocked-5", 1)),
665 ..AttendeeLimits::default()
666 }
667}
668
669fn demo_state(id: &str, rank: u64) -> PublishedState {
670 PublishedState { state_id: id.to_owned(), rank }
671}
672
673fn demo_options() -> MeetingOptions {
674 let option = |name: &str, value: serde_json::Value| serde_json::json!({"name": name, "currentValue": value});
675 MeetingOptions::from_response(&serde_json::json!({"options": [
676 option("AutoAdmittedUsers", serde_json::json!("EveryoneInCompany")),
677 option("PresenterOption", serde_json::json!("Everyone")),
678 option("AttendeeRestrictions", serde_json::json!("UnRestricted")),
679 option("AllowMeetingChat", serde_json::json!("Enabled")),
680 option("AllowTeamsMeetingReactions", serde_json::json!(true)),
681 option("AutoRecordAndTranscribeMode", serde_json::json!("Off")),
682 ]}))
683 .expect("the demo options are complete")
684}
685
619fn demo_organizer() -> RosterEntry {
686fn demo_organizer() -> RosterEntry {
620 RosterEntry {
687 RosterEntry {
621 mri: DEMO_OWN_MRI.to_owned(),
688 mri: DEMO_OWN_MRI.to_owned(),
@@ -627,6 +694,8 @@ fn demo_organizer() -> RosterEntry {
627 hand: None,
694 hand: None,
628 spotlight: None,
695 spotlight: None,
629 organizer: true,
696 organizer: true,
697 role: Some(MeetingRole::Organizer),
698 ..Default::default()
630 }
699 }
631}
700}
632
701
@@ -641,6 +710,7 @@ fn demo_waiting(index: usize, name: &str) -> RosterEntry {
641 hand: None,
710 hand: None,
642 spotlight: None,
711 spotlight: None,
643 organizer: false,
712 organizer: false,
713 ..Default::default()
644 }
714 }
645}
715}
646
716
@@ -700,6 +770,7 @@ fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {
700 hand: Some(demo_hand(next_rank)),
770 hand: Some(demo_hand(next_rank)),
701 spotlight: None,
771 spotlight: None,
702 organizer: false,
772 organizer: false,
773 ..Default::default()
703 }),
774 }),
704 }
775 }
705}
776}
crates/app/src/call/mod.rs +5 −0
@@ -15,8 +15,11 @@ mod list;
15 15 mod media;
16 16 mod mic;
17 17 mod model;
18 mod options_dialog;
18 19 mod overlay;
19 20 mod overlay_layout;
21 mod people;
22 mod people_actions;
20 23 mod pictures;
21 24 mod preview;
22 25 mod push_to_talk;
@@ -48,7 +51,9 @@ pub use model::{
48 51 ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
49 52 TileState,
50 53 };
54 pub use options_dialog::OptionsDialog;
51 55 pub use overlay::CallWindows;
56 pub use people::{PeopleSections, PersonRow, people_sections};
52 57 pub use preview::{CameraPreview, preview_backgrounds};
53 58 pub use ring::{MissedCall, RingEntry, Rings};
54 59 pub use stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, filmstrip, gallery_grid, split_overflow};
@@ -15,8 +15,11 @@ mod list;
15mod media;
15mod media;
16mod mic;
16mod mic;
17mod model;
17mod model;
18mod options_dialog;
18mod overlay;
19mod overlay;
19mod overlay_layout;
20mod overlay_layout;
21mod people;
22mod people_actions;
20mod pictures;
23mod pictures;
21mod preview;
24mod preview;
22mod push_to_talk;
25mod push_to_talk;
@@ -48,7 +51,9 @@ pub use model::{
48 ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
51 ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
49 TileState,
52 TileState,
50};
53};
54pub use options_dialog::OptionsDialog;
51pub use overlay::CallWindows;
55pub use overlay::CallWindows;
56pub use people::{PeopleSections, PersonRow, people_sections};
52pub use preview::{CameraPreview, preview_backgrounds};
57pub use preview::{CameraPreview, preview_backgrounds};
53pub use ring::{MissedCall, RingEntry, Rings};
58pub use ring::{MissedCall, RingEntry, Rings};
54pub use stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, filmstrip, gallery_grid, split_overflow};
59pub use stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, filmstrip, gallery_grid, split_overflow};
crates/app/src/call/model.rs +67 −3
@@ -4,9 +4,9 @@ use std::sync::Arc;
4 4 use std::time::{Duration, Instant};
5 5
6 6 use calling::{
7 CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
8 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingTarget, Progress, Reaction,
9 RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
7 AttendeeLimits, CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
8 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingCapability, MeetingRole,
9 MeetingTarget, Progress, Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
10 10 };
11 11 use tokio::sync::mpsc::UnboundedSender;
12 12
@@ -17,6 +17,7 @@ use super::fullscreen::FullscreenState;
17 17 use super::pictures::CallPictures;
18 18 use super::stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, RECENT_SPEAKER, SPEAKER_HOLD, VisibleRotation, split_overflow};
19 19 use super::view_settings::{CallLayout, ViewSettings};
20 use super::options_dialog::OptionsDialog;
20 21 use super::push_to_talk::PushToTalk;
21 22
22 23 pub const TEST_CALL_TITLE: &str = "Test call";
@@ -46,6 +47,8 @@ pub struct ActiveCall {
46 47 pub share_menu_open: bool,
47 48 pub lobby_list_open: bool,
48 49 pub chat_open: bool,
50 pub people_open: bool,
51 pub options_dialog: Option<OptionsDialog>,
49 52 pub meeting_target: Option<MeetingTarget>,
50 53 pub pending_move: Option<PendingMove>,
51 54 pub consult: Option<ConsultCall>,
@@ -109,6 +112,8 @@ impl ActiveCall {
109 112 share_menu_open: false,
110 113 lobby_list_open: false,
111 114 chat_open: false,
115 people_open: false,
116 options_dialog: None,
112 117 meeting_target: None,
113 118 pending_move: None,
114 119 consult: None,
@@ -163,6 +168,8 @@ pub struct Tile {
163 168 pub has_video: bool,
164 169 pub hand: Option<u64>,
165 170 pub spotlight: Option<u64>,
171 pub role: Option<MeetingRole>,
172 pub limits: AttendeeLimits,
166 173 }
167 174
168 175 impl Tile {
@@ -177,6 +184,8 @@ impl Tile {
177 184 has_video: false,
178 185 hand: None,
179 186 spotlight: None,
187 role: None,
188 limits: AttendeeLimits::default(),
180 189 }
181 190 }
182 191 }
@@ -261,6 +270,8 @@ pub struct CallModel {
261 270 pub own_hand: Option<u64>,
262 271 pub own_spotlight: Option<u64>,
263 272 pub organizer: bool,
273 pub own_role: Option<MeetingRole>,
274 pub capability: MeetingCapability,
264 275 pub pinned: Option<String>,
265 276 pub captions: CaptionState,
266 277 pub caption_lines: Vec<CaptionLine>,
@@ -315,6 +326,8 @@ impl CallModel {
315 326 own_hand: None,
316 327 own_spotlight: None,
317 328 organizer: false,
329 own_role: None,
330 capability: MeetingCapability::default(),
318 331 pinned: None,
319 332 captions: CaptionState::Off,
320 333 caption_lines: Vec::new(),
@@ -454,9 +467,12 @@ impl CallModel {
454 467 CallUpdate::Health(health) => self.health.apply(health),
455 468 CallUpdate::IncomingVideo(enabled) => self.health.incoming_video = enabled,
456 469 CallUpdate::Whiteboard(share) => self.whiteboard = share,
470 CallUpdate::Capability(capability) => self.capability = capability,
457 471 CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
458 472 CallUpdate::BlurTiming(_)
459 473 | CallUpdate::Organizer { .. }
474 | CallUpdate::MeetingOptions(_)
475 | CallUpdate::MeetingOptionsSaved(_)
460 476 | CallUpdate::WhiteboardUrl(_)
461 477 | CallUpdate::BreakoutMove(_)
462 478 | CallUpdate::ReplacementLink(_) => {}
@@ -554,6 +570,39 @@ impl CallModel {
554 570 self.kind == CallKind::Meeting && self.can_manage()
555 571 }
556 572
573 pub fn present_others(&self) -> usize {
574 self.tiles
575 .iter()
576 .filter(|tile| tile.state == TileState::Present)
577 .count()
578 }
579
580 pub fn can_invite(&self) -> bool {
581 let open_to_everyone = matches!(self.kind, CallKind::Direct | CallKind::Group);
582 self.is_live() && !self.lobby && (open_to_everyone || self.organizes_meeting())
583 }
584
585 pub fn tile_role(&self, mri: &str) -> Option<MeetingRole> {
586 self.tiles
587 .iter()
588 .find(|tile| tile.mri == mri)
589 .and_then(|tile| tile.role)
590 }
591
592 pub fn can_change_roles(&self, mri: &str) -> bool {
593 self.organizes_meeting() && self.tile_role(mri) != Some(MeetingRole::Organizer)
594 }
595
596 pub fn attendee_allowed(&self, mri: &str, modality: calling::Modality) -> bool {
597 let limits = self
598 .tiles
599 .iter()
600 .find(|tile| tile.mri == mri)
601 .map(|tile| tile.limits.clone())
602 .unwrap_or_default();
603 calling::modality_allowed(modality, self.capability, &limits)
604 }
605
557 606 pub fn can_lower_hands(&self) -> bool {
558 607 self.can_manage()
559 608 }
@@ -623,6 +672,11 @@ impl CallModel {
623 672 })
624 673 }
625 674
675 pub fn raised_hands(&self) -> usize {
676 self.tiles.iter().filter(|tile| tile.hand.is_some()).count()
677 + usize::from(self.own_hand.is_some())
678 }
679
626 680 pub fn any_hand_raised(&self) -> bool {
627 681 self.own_hand.is_some() || self.tiles.iter().any(|tile| tile.hand.is_some())
628 682 }
@@ -650,6 +704,7 @@ impl CallModel {
650 704 own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
651 705 if let Some(entry) = own_entry {
652 706 self.organizer = entry.organizer;
707 self.own_role = entry.role;
653 708 }
654 709 for entry in entries
655 710 .iter()
@@ -667,6 +722,8 @@ impl CallModel {
667 722 tile.has_video = entry.has_video;
668 723 tile.hand = entry.hand.as_ref().map(|hand| hand.rank);
669 724 tile.spotlight = entry.spotlight.as_ref().map(|spotlight| spotlight.rank);
725 tile.role = entry.role;
726 tile.limits = entry.limits.clone();
670 727 if tile.name.is_empty() {
671 728 tile.name = entry.display_name.clone();
672 729 }
@@ -681,9 +738,14 @@ impl CallModel {
681 738 has_video: entry.has_video,
682 739 hand: entry.hand.as_ref().map(|hand| hand.rank),
683 740 spotlight: entry.spotlight.as_ref().map(|spotlight| spotlight.rank),
741 role: entry.role,
742 limits: entry.limits.clone(),
684 743 }),
685 744 }
686 745 }
746 if self.kind == CallKind::Direct && self.present_others() > 1 {
747 self.kind = CallKind::Group;
748 }
687 749 let own_mri = self.own_mri.clone();
688 750 let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
689 751 if self
@@ -1094,6 +1156,8 @@ mod tests {
1094 1156 hand: None,
1095 1157 spotlight: None,
1096 1158 organizer: false,
1159 role: None,
1160 limits: AttendeeLimits::default(),
1097 1161 }
1098 1162 }
1099 1163
@@ -4,9 +4,9 @@ use std::sync::Arc;
4use std::time::{Duration, Instant};
4use std::time::{Duration, Instant};
5
5
6use calling::{
6use calling::{
7 CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
7 AttendeeLimits, CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
8 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingTarget, Progress, Reaction,
8 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingCapability, MeetingRole,
9 RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
9 MeetingTarget, Progress, Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
10};
10};
11use tokio::sync::mpsc::UnboundedSender;
11use tokio::sync::mpsc::UnboundedSender;
12
12
@@ -17,6 +17,7 @@ use super::fullscreen::FullscreenState;
17use super::pictures::CallPictures;
17use super::pictures::CallPictures;
18use super::stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, RECENT_SPEAKER, SPEAKER_HOLD, VisibleRotation, split_overflow};
18use super::stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, RECENT_SPEAKER, SPEAKER_HOLD, VisibleRotation, split_overflow};
19use super::view_settings::{CallLayout, ViewSettings};
19use super::view_settings::{CallLayout, ViewSettings};
20use super::options_dialog::OptionsDialog;
20use super::push_to_talk::PushToTalk;
21use super::push_to_talk::PushToTalk;
21
22
22pub const TEST_CALL_TITLE: &str = "Test call";
23pub const TEST_CALL_TITLE: &str = "Test call";
@@ -46,6 +47,8 @@ pub struct ActiveCall {
46 pub share_menu_open: bool,
47 pub share_menu_open: bool,
47 pub lobby_list_open: bool,
48 pub lobby_list_open: bool,
48 pub chat_open: bool,
49 pub chat_open: bool,
50 pub people_open: bool,
51 pub options_dialog: Option<OptionsDialog>,
49 pub meeting_target: Option<MeetingTarget>,
52 pub meeting_target: Option<MeetingTarget>,
50 pub pending_move: Option<PendingMove>,
53 pub pending_move: Option<PendingMove>,
51 pub consult: Option<ConsultCall>,
54 pub consult: Option<ConsultCall>,
@@ -109,6 +112,8 @@ impl ActiveCall {
109 share_menu_open: false,
112 share_menu_open: false,
110 lobby_list_open: false,
113 lobby_list_open: false,
111 chat_open: false,
114 chat_open: false,
115 people_open: false,
116 options_dialog: None,
112 meeting_target: None,
117 meeting_target: None,
113 pending_move: None,
118 pending_move: None,
114 consult: None,
119 consult: None,
@@ -163,6 +168,8 @@ pub struct Tile {
163 pub has_video: bool,
168 pub has_video: bool,
164 pub hand: Option<u64>,
169 pub hand: Option<u64>,
165 pub spotlight: Option<u64>,
170 pub spotlight: Option<u64>,
171 pub role: Option<MeetingRole>,
172 pub limits: AttendeeLimits,
166}
173}
167
174
168impl Tile {
175impl Tile {
@@ -177,6 +184,8 @@ impl Tile {
177 has_video: false,
184 has_video: false,
178 hand: None,
185 hand: None,
179 spotlight: None,
186 spotlight: None,
187 role: None,
188 limits: AttendeeLimits::default(),
180 }
189 }
181 }
190 }
182}
191}
@@ -261,6 +270,8 @@ pub struct CallModel {
261 pub own_hand: Option<u64>,
270 pub own_hand: Option<u64>,
262 pub own_spotlight: Option<u64>,
271 pub own_spotlight: Option<u64>,
263 pub organizer: bool,
272 pub organizer: bool,
273 pub own_role: Option<MeetingRole>,
274 pub capability: MeetingCapability,
264 pub pinned: Option<String>,
275 pub pinned: Option<String>,
265 pub captions: CaptionState,
276 pub captions: CaptionState,
266 pub caption_lines: Vec<CaptionLine>,
277 pub caption_lines: Vec<CaptionLine>,
@@ -315,6 +326,8 @@ impl CallModel {
315 own_hand: None,
326 own_hand: None,
316 own_spotlight: None,
327 own_spotlight: None,
317 organizer: false,
328 organizer: false,
329 own_role: None,
330 capability: MeetingCapability::default(),
318 pinned: None,
331 pinned: None,
319 captions: CaptionState::Off,
332 captions: CaptionState::Off,
320 caption_lines: Vec::new(),
333 caption_lines: Vec::new(),
@@ -454,9 +467,12 @@ impl CallModel {
454 CallUpdate::Health(health) => self.health.apply(health),
467 CallUpdate::Health(health) => self.health.apply(health),
455 CallUpdate::IncomingVideo(enabled) => self.health.incoming_video = enabled,
468 CallUpdate::IncomingVideo(enabled) => self.health.incoming_video = enabled,
456 CallUpdate::Whiteboard(share) => self.whiteboard = share,
469 CallUpdate::Whiteboard(share) => self.whiteboard = share,
470 CallUpdate::Capability(capability) => self.capability = capability,
457 CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
471 CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
458 CallUpdate::BlurTiming(_)
472 CallUpdate::BlurTiming(_)
459 | CallUpdate::Organizer { .. }
473 | CallUpdate::Organizer { .. }
474 | CallUpdate::MeetingOptions(_)
475 | CallUpdate::MeetingOptionsSaved(_)
460 | CallUpdate::WhiteboardUrl(_)
476 | CallUpdate::WhiteboardUrl(_)
461 | CallUpdate::BreakoutMove(_)
477 | CallUpdate::BreakoutMove(_)
462 | CallUpdate::ReplacementLink(_) => {}
478 | CallUpdate::ReplacementLink(_) => {}
@@ -554,6 +570,39 @@ impl CallModel {
554 self.kind == CallKind::Meeting && self.can_manage()
570 self.kind == CallKind::Meeting && self.can_manage()
555 }
571 }
556
572
573 pub fn present_others(&self) -> usize {
574 self.tiles
575 .iter()
576 .filter(|tile| tile.state == TileState::Present)
577 .count()
578 }
579
580 pub fn can_invite(&self) -> bool {
581 let open_to_everyone = matches!(self.kind, CallKind::Direct | CallKind::Group);
582 self.is_live() && !self.lobby && (open_to_everyone || self.organizes_meeting())
583 }
584
585 pub fn tile_role(&self, mri: &str) -> Option<MeetingRole> {
586 self.tiles
587 .iter()
588 .find(|tile| tile.mri == mri)
589 .and_then(|tile| tile.role)
590 }
591
592 pub fn can_change_roles(&self, mri: &str) -> bool {
593 self.organizes_meeting() && self.tile_role(mri) != Some(MeetingRole::Organizer)
594 }
595
596 pub fn attendee_allowed(&self, mri: &str, modality: calling::Modality) -> bool {
597 let limits = self
598 .tiles
599 .iter()
600 .find(|tile| tile.mri == mri)
601 .map(|tile| tile.limits.clone())
602 .unwrap_or_default();
603 calling::modality_allowed(modality, self.capability, &limits)
604 }
605
557 pub fn can_lower_hands(&self) -> bool {
606 pub fn can_lower_hands(&self) -> bool {
558 self.can_manage()
607 self.can_manage()
559 }
608 }
@@ -623,6 +672,11 @@ impl CallModel {
623 })
672 })
624 }
673 }
625
674
675 pub fn raised_hands(&self) -> usize {
676 self.tiles.iter().filter(|tile| tile.hand.is_some()).count()
677 + usize::from(self.own_hand.is_some())
678 }
679
626 pub fn any_hand_raised(&self) -> bool {
680 pub fn any_hand_raised(&self) -> bool {
627 self.own_hand.is_some() || self.tiles.iter().any(|tile| tile.hand.is_some())
681 self.own_hand.is_some() || self.tiles.iter().any(|tile| tile.hand.is_some())
628 }
682 }
@@ -650,6 +704,7 @@ impl CallModel {
650 own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
704 own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
651 if let Some(entry) = own_entry {
705 if let Some(entry) = own_entry {
652 self.organizer = entry.organizer;
706 self.organizer = entry.organizer;
707 self.own_role = entry.role;
653 }
708 }
654 for entry in entries
709 for entry in entries
655 .iter()
710 .iter()
@@ -667,6 +722,8 @@ impl CallModel {
667 tile.has_video = entry.has_video;
722 tile.has_video = entry.has_video;
668 tile.hand = entry.hand.as_ref().map(|hand| hand.rank);
723 tile.hand = entry.hand.as_ref().map(|hand| hand.rank);
669 tile.spotlight = entry.spotlight.as_ref().map(|spotlight| spotlight.rank);
724 tile.spotlight = entry.spotlight.as_ref().map(|spotlight| spotlight.rank);
725 tile.role = entry.role;
726 tile.limits = entry.limits.clone();
670 if tile.name.is_empty() {
727 if tile.name.is_empty() {
671 tile.name = entry.display_name.clone();
728 tile.name = entry.display_name.clone();
672 }
729 }
@@ -681,9 +738,14 @@ impl CallModel {
681 has_video: entry.has_video,
738 has_video: entry.has_video,
682 hand: entry.hand.as_ref().map(|hand| hand.rank),
739 hand: entry.hand.as_ref().map(|hand| hand.rank),
683 spotlight: entry.spotlight.as_ref().map(|spotlight| spotlight.rank),
740 spotlight: entry.spotlight.as_ref().map(|spotlight| spotlight.rank),
741 role: entry.role,
742 limits: entry.limits.clone(),
684 }),
743 }),
685 }
744 }
686 }
745 }
746 if self.kind == CallKind::Direct && self.present_others() > 1 {
747 self.kind = CallKind::Group;
748 }
687 let own_mri = self.own_mri.clone();
749 let own_mri = self.own_mri.clone();
688 let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
750 let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
689 if self
751 if self
@@ -1094,6 +1156,8 @@ mod tests {
1094 hand: None,
1156 hand: None,
1095 spotlight: None,
1157 spotlight: None,
1096 organizer: false,
1158 organizer: false,
1159 role: None,
1160 limits: AttendeeLimits::default(),
1097 }
1161 }
1098 }
1162 }
1099
1163
crates/app/src/call/options_dialog.rs added +115 −0
@@ -0,0 +1,115 @@
1 use calling::{MeetingOptions, OptionWrite};
2
3 #[derive(Debug, Clone, PartialEq)]
4 pub struct OptionsDialog {
5 pub original: Option<MeetingOptions>,
6 pub draft: Option<MeetingOptions>,
7 pub saving: bool,
8 pub error: Option<String>,
9 }
10
11 impl OptionsDialog {
12 pub fn loading() -> Self {
13 OptionsDialog { original: None, draft: None, saving: false, error: None }
14 }
15
16 pub fn loaded(&mut self, result: Result<MeetingOptions, String>) {
17 match result {
18 Ok(options) => {
19 self.original = Some(options.clone());
20 self.draft = Some(options);
21 self.error = None;
22 }
23 Err(error) => self.error = Some(error),
24 }
25 }
26
27 pub fn is_loading(&self) -> bool {
28 self.draft.is_none() && self.error.is_none()
29 }
30
31 pub fn changes(&self) -> Vec<OptionWrite> {
32 match (&self.original, &self.draft) {
33 (Some(original), Some(draft)) => original.changes(draft),
34 _ => Vec::new(),
35 }
36 }
37
38 pub fn can_save(&self) -> bool {
39 !self.saving && !self.changes().is_empty()
40 }
41
42 pub fn begin_save(&mut self) -> Option<Vec<OptionWrite>> {
43 if !self.can_save() {
44 return None;
45 }
46 self.saving = true;
47 self.error = None;
48 Some(self.changes())
49 }
50
51 pub fn saved(&mut self, result: Result<MeetingOptions, String>) -> bool {
52 self.saving = false;
53 match result {
54 Ok(_) => true,
55 Err(error) => {
56 self.error = Some(error);
57 false
58 }
59 }
60 }
61 }
62
63 #[cfg(test)]
64 mod tests {
65 use serde_json::json;
66
67 use super::*;
68
69 fn options() -> MeetingOptions {
70 let option = |name: &str, value: serde_json::Value| json!({"name": name, "currentValue": value});
71 MeetingOptions::from_response(&json!({"options": [
72 option("AutoAdmittedUsers", json!("EveryoneInCompany")),
73 option("PresenterOption", json!("Everyone")),
74 option("AttendeeRestrictions", json!("UnRestricted")),
75 option("AllowMeetingChat", json!("Enabled")),
76 option("AllowTeamsMeetingReactions", json!(true)),
77 option("AutoRecordAndTranscribeMode", json!("Off")),
78 ]}))
79 .unwrap()
80 }
81
82 #[test]
83 fn a_dialog_loads_then_saves_only_what_changed() {
84 let mut dialog = OptionsDialog::loading();
85 assert!(dialog.is_loading());
86 assert!(dialog.begin_save().is_none());
87 dialog.loaded(Ok(options()));
88 assert!(!dialog.is_loading());
89 assert!(!dialog.can_save());
90 dialog.draft.as_mut().unwrap().reactions = false;
91 let writes = dialog.begin_save().expect("a change to save");
92 assert_eq!(writes.len(), 1);
93 assert_eq!(writes[0].name, "AllowTeamsMeetingReactions");
94 assert!(dialog.saving);
95 assert!(dialog.begin_save().is_none());
96 }
97
98 #[test]
99 fn errors_stay_inline_and_a_failed_save_can_be_retried() {
100 let mut dialog = OptionsDialog::loading();
101 dialog.loaded(Err("The options could not be read".into()));
102 assert!(!dialog.is_loading());
103 assert_eq!(dialog.error.as_deref(), Some("The options could not be read"));
104 dialog.loaded(Ok(options()));
105 assert_eq!(dialog.error, None);
106 dialog.draft.as_mut().unwrap().meeting_chat = "Disabled".into();
107 dialog.begin_save();
108 assert!(!dialog.saved(Err("the service refused AllowMeetingChat".into())));
109 assert!(!dialog.saving);
110 assert_eq!(dialog.error.as_deref(), Some("the service refused AllowMeetingChat"));
111 assert!(dialog.can_save());
112 dialog.begin_save();
113 assert!(dialog.saved(Ok(options())));
114 }
115 }
@@ -0,0 +1,115 @@
1use calling::{MeetingOptions, OptionWrite};
2
3#[derive(Debug, Clone, PartialEq)]
4pub struct OptionsDialog {
5 pub original: Option<MeetingOptions>,
6 pub draft: Option<MeetingOptions>,
7 pub saving: bool,
8 pub error: Option<String>,
9}
10
11impl OptionsDialog {
12 pub fn loading() -> Self {
13 OptionsDialog { original: None, draft: None, saving: false, error: None }
14 }
15
16 pub fn loaded(&mut self, result: Result<MeetingOptions, String>) {
17 match result {
18 Ok(options) => {
19 self.original = Some(options.clone());
20 self.draft = Some(options);
21 self.error = None;
22 }
23 Err(error) => self.error = Some(error),
24 }
25 }
26
27 pub fn is_loading(&self) -> bool {
28 self.draft.is_none() && self.error.is_none()
29 }
30
31 pub fn changes(&self) -> Vec<OptionWrite> {
32 match (&self.original, &self.draft) {
33 (Some(original), Some(draft)) => original.changes(draft),
34 _ => Vec::new(),
35 }
36 }
37
38 pub fn can_save(&self) -> bool {
39 !self.saving && !self.changes().is_empty()
40 }
41
42 pub fn begin_save(&mut self) -> Option<Vec<OptionWrite>> {
43 if !self.can_save() {
44 return None;
45 }
46 self.saving = true;
47 self.error = None;
48 Some(self.changes())
49 }
50
51 pub fn saved(&mut self, result: Result<MeetingOptions, String>) -> bool {
52 self.saving = false;
53 match result {
54 Ok(_) => true,
55 Err(error) => {
56 self.error = Some(error);
57 false
58 }
59 }
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use serde_json::json;
66
67 use super::*;
68
69 fn options() -> MeetingOptions {
70 let option = |name: &str, value: serde_json::Value| json!({"name": name, "currentValue": value});
71 MeetingOptions::from_response(&json!({"options": [
72 option("AutoAdmittedUsers", json!("EveryoneInCompany")),
73 option("PresenterOption", json!("Everyone")),
74 option("AttendeeRestrictions", json!("UnRestricted")),
75 option("AllowMeetingChat", json!("Enabled")),
76 option("AllowTeamsMeetingReactions", json!(true)),
77 option("AutoRecordAndTranscribeMode", json!("Off")),
78 ]}))
79 .unwrap()
80 }
81
82 #[test]
83 fn a_dialog_loads_then_saves_only_what_changed() {
84 let mut dialog = OptionsDialog::loading();
85 assert!(dialog.is_loading());
86 assert!(dialog.begin_save().is_none());
87 dialog.loaded(Ok(options()));
88 assert!(!dialog.is_loading());
89 assert!(!dialog.can_save());
90 dialog.draft.as_mut().unwrap().reactions = false;
91 let writes = dialog.begin_save().expect("a change to save");
92 assert_eq!(writes.len(), 1);
93 assert_eq!(writes[0].name, "AllowTeamsMeetingReactions");
94 assert!(dialog.saving);
95 assert!(dialog.begin_save().is_none());
96 }
97
98 #[test]
99 fn errors_stay_inline_and_a_failed_save_can_be_retried() {
100 let mut dialog = OptionsDialog::loading();
101 dialog.loaded(Err("The options could not be read".into()));
102 assert!(!dialog.is_loading());
103 assert_eq!(dialog.error.as_deref(), Some("The options could not be read"));
104 dialog.loaded(Ok(options()));
105 assert_eq!(dialog.error, None);
106 dialog.draft.as_mut().unwrap().meeting_chat = "Disabled".into();
107 dialog.begin_save();
108 assert!(!dialog.saved(Err("the service refused AllowMeetingChat".into())));
109 assert!(!dialog.saving);
110 assert_eq!(dialog.error.as_deref(), Some("the service refused AllowMeetingChat"));
111 assert!(dialog.can_save());
112 dialog.begin_save();
113 assert!(dialog.saved(Ok(options())));
114 }
115}
crates/app/src/call/people.rs added +271 −0
@@ -0,0 +1,271 @@
1 use calling::{MeetingRole, Modality};
2
3 use super::model::{CallKind, CallModel, Tile, TileState};
4
5 const BOT_PREFIX: &str = "28:";
6 const FLAT_TITLE: &str = "In this call";
7 const OWN_NAME: &str = "You";
8
9 #[derive(Debug, Clone, PartialEq, Eq)]
10 pub struct PersonRow {
11 pub mri: String,
12 pub name: String,
13 pub user_id: Option<String>,
14 pub own: bool,
15 pub label: Option<&'static str>,
16 pub muted: bool,
17 pub mic_blocked: bool,
18 pub camera_on: bool,
19 pub camera_blocked: bool,
20 pub hand: Option<usize>,
21 pub ringing: bool,
22 }
23
24 #[derive(Debug, Clone, PartialEq, Eq)]
25 pub struct LobbyRow {
26 pub mri: String,
27 pub name: String,
28 pub user_id: Option<String>,
29 }
30
31 #[derive(Debug, Clone, PartialEq, Eq)]
32 pub struct PeopleGroup {
33 pub title: &'static str,
34 pub rows: Vec<PersonRow>,
35 }
36
37 #[derive(Debug, Clone, PartialEq, Eq, Default)]
38 pub struct PeopleSections {
39 pub count: usize,
40 pub lobby: Vec<LobbyRow>,
41 pub hands: Vec<PersonRow>,
42 pub groups: Vec<PeopleGroup>,
43 }
44
45 pub fn role_label(role: MeetingRole) -> &'static str {
46 match role {
47 MeetingRole::Organizer => "Organizer",
48 MeetingRole::Presenter => "Presenter",
49 MeetingRole::Attendee => "Attendee",
50 }
51 }
52
53 fn group_title(role: MeetingRole) -> &'static str {
54 match role {
55 MeetingRole::Organizer => "Organizers",
56 MeetingRole::Presenter => "Presenters",
57 MeetingRole::Attendee => "Attendees",
58 }
59 }
60
61 fn tile_row(model: &CallModel, tile: &Tile, role: Option<MeetingRole>) -> PersonRow {
62 let attendee = role != Some(MeetingRole::Organizer) && role != Some(MeetingRole::Presenter);
63 PersonRow {
64 mri: tile.mri.clone(),
65 name: tile.name.clone(),
66 user_id: tile.user_id.clone(),
67 own: false,
68 label: role.map(role_label),
69 muted: tile.muted,
70 mic_blocked: attendee && !model.attendee_allowed(&tile.mri, Modality::Mic),
71 camera_on: tile.has_video,
72 camera_blocked: attendee && !model.attendee_allowed(&tile.mri, Modality::Camera),
73 hand: tile.hand.map(|rank| model.hand_position(rank)),
74 ringing: tile.state == TileState::Invited,
75 }
76 }
77
78 fn own_row(model: &CallModel, role: Option<MeetingRole>) -> Option<PersonRow> {
79 let mri = model.own_mri.clone()?;
80 Some(PersonRow {
81 mri,
82 name: OWN_NAME.to_owned(),
83 user_id: None,
84 own: true,
85 label: role.map(role_label),
86 muted: model.muted,
87 mic_blocked: false,
88 camera_on: model.camera_on,
89 camera_blocked: false,
90 hand: model.own_hand.map(|rank| model.hand_position(rank)),
91 ringing: false,
92 })
93 }
94
95 fn by_name(rows: &mut [PersonRow]) {
96 rows.sort_by_key(|row| (!row.own, row.name.to_lowercase()));
97 }
98
99 pub fn people_sections(model: &CallModel) -> PeopleSections {
100 let in_meeting = model.kind == CallKind::Meeting;
101 let own_role = in_meeting.then(|| {
102 model
103 .own_role
104 .or_else(|| model.can_manage().then_some(MeetingRole::Organizer))
105 .unwrap_or(MeetingRole::Attendee)
106 });
107 let mut rows: Vec<(MeetingRole, PersonRow)> = Vec::new();
108 let mut lobby = Vec::new();
109 for tile in model.tiles.iter().filter(|tile| !tile.mri.starts_with(BOT_PREFIX)) {
110 match tile.state {
111 TileState::InLobby => lobby.push(LobbyRow {
112 mri: tile.mri.clone(),
113 name: tile.name.clone(),
114 user_id: tile.user_id.clone(),
115 }),
116 TileState::Present | TileState::Invited => {
117 let role = in_meeting.then(|| tile.role.unwrap_or(MeetingRole::Attendee));
118 rows.push((role.unwrap_or(MeetingRole::Attendee), tile_row(model, tile, role)));
119 }
120 TileState::Left => {}
121 }
122 }
123 if let Some(own) = own_row(model, own_role) {
124 rows.push((own_role.unwrap_or(MeetingRole::Attendee), own));
125 }
126 let count = rows.len();
127 let mut hands: Vec<PersonRow> = rows
128 .iter()
129 .filter(|(_, row)| row.hand.is_some())
130 .map(|(_, row)| row.clone())
131 .collect();
132 hands.sort_by_key(|row| row.hand);
133 let groups = if in_meeting {
134 [MeetingRole::Organizer, MeetingRole::Presenter, MeetingRole::Attendee]
135 .into_iter()
136 .filter_map(|role| {
137 let mut group: Vec<PersonRow> = rows
138 .iter()
139 .filter(|(row_role, _)| *row_role == role)
140 .map(|(_, row)| row.clone())
141 .collect();
142 by_name(&mut group);
143 (!group.is_empty()).then_some(PeopleGroup { title: group_title(role), rows: group })
144 })
145 .collect()
146 } else {
147 let mut flat: Vec<PersonRow> = rows.into_iter().map(|(_, row)| row).collect();
148 by_name(&mut flat);
149 vec![PeopleGroup { title: FLAT_TITLE, rows: flat }]
150 };
151 PeopleSections { count, lobby, hands, groups }
152 }
153
154 #[cfg(test)]
155 mod tests {
156 use std::time::Instant;
157
158 use calling::{AttendeeLimits, CallState, CallUpdate, MeetingCapability, PublishedState, RaisedHand, RosterEntry};
159
160 use super::*;
161
162 fn entry(mri: &str, name: &str, role: Option<MeetingRole>) -> RosterEntry {
163 RosterEntry { mri: mri.into(), display_name: name.into(), role, ..RosterEntry::default() }
164 }
165
166 fn raised(mut entry: RosterEntry, rank: u64) -> RosterEntry {
167 entry.hand = Some(RaisedHand { state_id: format!("s-{rank}"), rank });
168 entry
169 }
170
171 fn meeting(entries: Vec<RosterEntry>) -> CallModel {
172 let mut model = CallModel::meeting("Standup", true);
173 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
174 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
175 model.apply(CallUpdate::Roster(entries));
176 model
177 }
178
179 fn titles(sections: &PeopleSections) -> Vec<&'static str> {
180 sections.groups.iter().map(|group| group.title).collect()
181 }
182
183 fn names(group: &PeopleGroup) -> Vec<&str> {
184 group.rows.iter().map(|row| row.name.as_str()).collect()
185 }
186
187 #[test]
188 fn a_meeting_groups_by_role_and_keeps_only_the_groups_that_exist() {
189 let model = meeting(vec![
190 entry("8:orgid:me", "Me", Some(MeetingRole::Organizer)),
191 entry("8:orgid:a", "Ana", Some(MeetingRole::Attendee)),
192 entry("8:orgid:b", "bo", Some(MeetingRole::Attendee)),
193 entry("8:orgid:c", "Cy", None),
194 ]);
195 let sections = people_sections(&model);
196 assert_eq!(titles(&sections), vec!["Organizers", "Attendees"]);
197 assert_eq!(names(&sections.groups[0]), vec!["You"]);
198 assert_eq!(names(&sections.groups[1]), vec!["Ana", "bo", "Cy"]);
199 assert_eq!(sections.count, 4);
200 let presenter = meeting(vec![entry("8:orgid:p", "Pia", Some(MeetingRole::Presenter))]);
201 assert_eq!(titles(&people_sections(&presenter)), vec!["Organizers", "Presenters"]);
202 }
203
204 #[test]
205 fn direct_and_group_calls_show_one_flat_list_without_role_labels() {
206 let mut model = CallModel::people("Team", &[("8:orgid:a".into(), "Ana".into()), ("8:orgid:b".into(), "Bo".into())]);
207 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
208 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
209 let sections = people_sections(&model);
210 assert_eq!(titles(&sections), vec!["In this call"]);
211 assert_eq!(names(&sections.groups[0]), vec!["You", "Ana", "Bo"]);
212 assert!(sections.groups[0].rows.iter().all(|row| row.label.is_none()));
213 assert!(sections.groups[0].rows[1].ringing);
214 }
215
216 #[test]
217 fn raised_hands_queue_in_raise_order_and_the_lobby_stays_out_of_the_groups() {
218 let mut waiting = entry("8:orgid:w", "Wen", None);
219 waiting.in_lobby = true;
220 let model = meeting(vec![
221 entry("8:orgid:me", "Me", Some(MeetingRole::Organizer)),
222 raised(entry("8:orgid:a", "Ana", None), 7),
223 raised(entry("8:orgid:b", "Bo", None), 3),
224 waiting,
225 ]);
226 let sections = people_sections(&model);
227 let queue: Vec<(&str, Option<usize>)> = sections.hands.iter().map(|row| (row.name.as_str(), row.hand)).collect();
228 assert_eq!(queue, vec![("Bo", Some(1)), ("Ana", Some(2))]);
229 assert_eq!(sections.lobby.len(), 1);
230 assert_eq!(sections.lobby[0].name, "Wen");
231 assert_eq!(sections.count, 3);
232 }
233
234 #[test]
235 fn bots_stay_out_and_the_own_role_falls_back_to_the_organizer_flag() {
236 let model = meeting(vec![entry("28:recorder", "Recorder", Some(MeetingRole::Presenter))]);
237 let sections = people_sections(&model);
238 assert_eq!(sections.count, 1);
239 assert_eq!(sections.groups[0].title, "Organizers");
240 assert_eq!(sections.groups[0].rows[0].label, Some("Organizer"));
241 }
242
243 #[test]
244 fn only_attendees_show_blocked_microphones() {
245 let blocked = AttendeeLimits {
246 mic_blocked: Some(PublishedState { state_id: "x".into(), rank: 1 }),
247 ..AttendeeLimits::default()
248 };
249 let mut limited = entry("8:orgid:a", "Ana", Some(MeetingRole::Attendee));
250 limited.limits = blocked.clone();
251 let mut presenter = entry("8:orgid:p", "Pia", Some(MeetingRole::Presenter));
252 presenter.limits = blocked;
253 let mut model = meeting(vec![limited, presenter, entry("8:orgid:b", "Bo", Some(MeetingRole::Attendee))]);
254 model.apply(CallUpdate::Capability(MeetingCapability { attendee_camera_off: true, ..MeetingCapability::default() }));
255 let sections = people_sections(&model);
256 let attendees = sections.groups.iter().find(|group| group.title == "Attendees").unwrap();
257 assert!(attendees.rows[0].mic_blocked && !attendees.rows[1].mic_blocked);
258 assert!(attendees.rows.iter().all(|row| row.camera_blocked));
259 let presenters = sections.groups.iter().find(|group| group.title == "Presenters").unwrap();
260 assert!(!presenters.rows[0].mic_blocked && !presenters.rows[0].camera_blocked);
261 }
262
263 #[test]
264 fn a_one_to_one_call_turns_into_a_group_when_a_third_person_joins() {
265 let mut model = CallModel::people("Ana", &[("8:orgid:a".into(), "Ana".into())]);
266 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", None)]));
267 assert_eq!(model.kind, CallKind::Direct);
268 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", None), entry("8:orgid:b", "Bo", None)]));
269 assert_eq!(model.kind, CallKind::Group);
270 }
271 }
@@ -0,0 +1,271 @@
1use calling::{MeetingRole, Modality};
2
3use super::model::{CallKind, CallModel, Tile, TileState};
4
5const BOT_PREFIX: &str = "28:";
6const FLAT_TITLE: &str = "In this call";
7const OWN_NAME: &str = "You";
8
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct PersonRow {
11 pub mri: String,
12 pub name: String,
13 pub user_id: Option<String>,
14 pub own: bool,
15 pub label: Option<&'static str>,
16 pub muted: bool,
17 pub mic_blocked: bool,
18 pub camera_on: bool,
19 pub camera_blocked: bool,
20 pub hand: Option<usize>,
21 pub ringing: bool,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct LobbyRow {
26 pub mri: String,
27 pub name: String,
28 pub user_id: Option<String>,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct PeopleGroup {
33 pub title: &'static str,
34 pub rows: Vec<PersonRow>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Default)]
38pub struct PeopleSections {
39 pub count: usize,
40 pub lobby: Vec<LobbyRow>,
41 pub hands: Vec<PersonRow>,
42 pub groups: Vec<PeopleGroup>,
43}
44
45pub fn role_label(role: MeetingRole) -> &'static str {
46 match role {
47 MeetingRole::Organizer => "Organizer",
48 MeetingRole::Presenter => "Presenter",
49 MeetingRole::Attendee => "Attendee",
50 }
51}
52
53fn group_title(role: MeetingRole) -> &'static str {
54 match role {
55 MeetingRole::Organizer => "Organizers",
56 MeetingRole::Presenter => "Presenters",
57 MeetingRole::Attendee => "Attendees",
58 }
59}
60
61fn tile_row(model: &CallModel, tile: &Tile, role: Option<MeetingRole>) -> PersonRow {
62 let attendee = role != Some(MeetingRole::Organizer) && role != Some(MeetingRole::Presenter);
63 PersonRow {
64 mri: tile.mri.clone(),
65 name: tile.name.clone(),
66 user_id: tile.user_id.clone(),
67 own: false,
68 label: role.map(role_label),
69 muted: tile.muted,
70 mic_blocked: attendee && !model.attendee_allowed(&tile.mri, Modality::Mic),
71 camera_on: tile.has_video,
72 camera_blocked: attendee && !model.attendee_allowed(&tile.mri, Modality::Camera),
73 hand: tile.hand.map(|rank| model.hand_position(rank)),
74 ringing: tile.state == TileState::Invited,
75 }
76}
77
78fn own_row(model: &CallModel, role: Option<MeetingRole>) -> Option<PersonRow> {
79 let mri = model.own_mri.clone()?;
80 Some(PersonRow {
81 mri,
82 name: OWN_NAME.to_owned(),
83 user_id: None,
84 own: true,
85 label: role.map(role_label),
86 muted: model.muted,
87 mic_blocked: false,
88 camera_on: model.camera_on,
89 camera_blocked: false,
90 hand: model.own_hand.map(|rank| model.hand_position(rank)),
91 ringing: false,
92 })
93}
94
95fn by_name(rows: &mut [PersonRow]) {
96 rows.sort_by_key(|row| (!row.own, row.name.to_lowercase()));
97}
98
99pub fn people_sections(model: &CallModel) -> PeopleSections {
100 let in_meeting = model.kind == CallKind::Meeting;
101 let own_role = in_meeting.then(|| {
102 model
103 .own_role
104 .or_else(|| model.can_manage().then_some(MeetingRole::Organizer))
105 .unwrap_or(MeetingRole::Attendee)
106 });
107 let mut rows: Vec<(MeetingRole, PersonRow)> = Vec::new();
108 let mut lobby = Vec::new();
109 for tile in model.tiles.iter().filter(|tile| !tile.mri.starts_with(BOT_PREFIX)) {
110 match tile.state {
111 TileState::InLobby => lobby.push(LobbyRow {
112 mri: tile.mri.clone(),
113 name: tile.name.clone(),
114 user_id: tile.user_id.clone(),
115 }),
116 TileState::Present | TileState::Invited => {
117 let role = in_meeting.then(|| tile.role.unwrap_or(MeetingRole::Attendee));
118 rows.push((role.unwrap_or(MeetingRole::Attendee), tile_row(model, tile, role)));
119 }
120 TileState::Left => {}
121 }
122 }
123 if let Some(own) = own_row(model, own_role) {
124 rows.push((own_role.unwrap_or(MeetingRole::Attendee), own));
125 }
126 let count = rows.len();
127 let mut hands: Vec<PersonRow> = rows
128 .iter()
129 .filter(|(_, row)| row.hand.is_some())
130 .map(|(_, row)| row.clone())
131 .collect();
132 hands.sort_by_key(|row| row.hand);
133 let groups = if in_meeting {
134 [MeetingRole::Organizer, MeetingRole::Presenter, MeetingRole::Attendee]
135 .into_iter()
136 .filter_map(|role| {
137 let mut group: Vec<PersonRow> = rows
138 .iter()
139 .filter(|(row_role, _)| *row_role == role)
140 .map(|(_, row)| row.clone())
141 .collect();
142 by_name(&mut group);
143 (!group.is_empty()).then_some(PeopleGroup { title: group_title(role), rows: group })
144 })
145 .collect()
146 } else {
147 let mut flat: Vec<PersonRow> = rows.into_iter().map(|(_, row)| row).collect();
148 by_name(&mut flat);
149 vec![PeopleGroup { title: FLAT_TITLE, rows: flat }]
150 };
151 PeopleSections { count, lobby, hands, groups }
152}
153
154#[cfg(test)]
155mod tests {
156 use std::time::Instant;
157
158 use calling::{AttendeeLimits, CallState, CallUpdate, MeetingCapability, PublishedState, RaisedHand, RosterEntry};
159
160 use super::*;
161
162 fn entry(mri: &str, name: &str, role: Option<MeetingRole>) -> RosterEntry {
163 RosterEntry { mri: mri.into(), display_name: name.into(), role, ..RosterEntry::default() }
164 }
165
166 fn raised(mut entry: RosterEntry, rank: u64) -> RosterEntry {
167 entry.hand = Some(RaisedHand { state_id: format!("s-{rank}"), rank });
168 entry
169 }
170
171 fn meeting(entries: Vec<RosterEntry>) -> CallModel {
172 let mut model = CallModel::meeting("Standup", true);
173 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
174 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
175 model.apply(CallUpdate::Roster(entries));
176 model
177 }
178
179 fn titles(sections: &PeopleSections) -> Vec<&'static str> {
180 sections.groups.iter().map(|group| group.title).collect()
181 }
182
183 fn names(group: &PeopleGroup) -> Vec<&str> {
184 group.rows.iter().map(|row| row.name.as_str()).collect()
185 }
186
187 #[test]
188 fn a_meeting_groups_by_role_and_keeps_only_the_groups_that_exist() {
189 let model = meeting(vec![
190 entry("8:orgid:me", "Me", Some(MeetingRole::Organizer)),
191 entry("8:orgid:a", "Ana", Some(MeetingRole::Attendee)),
192 entry("8:orgid:b", "bo", Some(MeetingRole::Attendee)),
193 entry("8:orgid:c", "Cy", None),
194 ]);
195 let sections = people_sections(&model);
196 assert_eq!(titles(&sections), vec!["Organizers", "Attendees"]);
197 assert_eq!(names(&sections.groups[0]), vec!["You"]);
198 assert_eq!(names(&sections.groups[1]), vec!["Ana", "bo", "Cy"]);
199 assert_eq!(sections.count, 4);
200 let presenter = meeting(vec![entry("8:orgid:p", "Pia", Some(MeetingRole::Presenter))]);
201 assert_eq!(titles(&people_sections(&presenter)), vec!["Organizers", "Presenters"]);
202 }
203
204 #[test]
205 fn direct_and_group_calls_show_one_flat_list_without_role_labels() {
206 let mut model = CallModel::people("Team", &[("8:orgid:a".into(), "Ana".into()), ("8:orgid:b".into(), "Bo".into())]);
207 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
208 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
209 let sections = people_sections(&model);
210 assert_eq!(titles(&sections), vec!["In this call"]);
211 assert_eq!(names(&sections.groups[0]), vec!["You", "Ana", "Bo"]);
212 assert!(sections.groups[0].rows.iter().all(|row| row.label.is_none()));
213 assert!(sections.groups[0].rows[1].ringing);
214 }
215
216 #[test]
217 fn raised_hands_queue_in_raise_order_and_the_lobby_stays_out_of_the_groups() {
218 let mut waiting = entry("8:orgid:w", "Wen", None);
219 waiting.in_lobby = true;
220 let model = meeting(vec![
221 entry("8:orgid:me", "Me", Some(MeetingRole::Organizer)),
222 raised(entry("8:orgid:a", "Ana", None), 7),
223 raised(entry("8:orgid:b", "Bo", None), 3),
224 waiting,
225 ]);
226 let sections = people_sections(&model);
227 let queue: Vec<(&str, Option<usize>)> = sections.hands.iter().map(|row| (row.name.as_str(), row.hand)).collect();
228 assert_eq!(queue, vec![("Bo", Some(1)), ("Ana", Some(2))]);
229 assert_eq!(sections.lobby.len(), 1);
230 assert_eq!(sections.lobby[0].name, "Wen");
231 assert_eq!(sections.count, 3);
232 }
233
234 #[test]
235 fn bots_stay_out_and_the_own_role_falls_back_to_the_organizer_flag() {
236 let model = meeting(vec![entry("28:recorder", "Recorder", Some(MeetingRole::Presenter))]);
237 let sections = people_sections(&model);
238 assert_eq!(sections.count, 1);
239 assert_eq!(sections.groups[0].title, "Organizers");
240 assert_eq!(sections.groups[0].rows[0].label, Some("Organizer"));
241 }
242
243 #[test]
244 fn only_attendees_show_blocked_microphones() {
245 let blocked = AttendeeLimits {
246 mic_blocked: Some(PublishedState { state_id: "x".into(), rank: 1 }),
247 ..AttendeeLimits::default()
248 };
249 let mut limited = entry("8:orgid:a", "Ana", Some(MeetingRole::Attendee));
250 limited.limits = blocked.clone();
251 let mut presenter = entry("8:orgid:p", "Pia", Some(MeetingRole::Presenter));
252 presenter.limits = blocked;
253 let mut model = meeting(vec![limited, presenter, entry("8:orgid:b", "Bo", Some(MeetingRole::Attendee))]);
254 model.apply(CallUpdate::Capability(MeetingCapability { attendee_camera_off: true, ..MeetingCapability::default() }));
255 let sections = people_sections(&model);
256 let attendees = sections.groups.iter().find(|group| group.title == "Attendees").unwrap();
257 assert!(attendees.rows[0].mic_blocked && !attendees.rows[1].mic_blocked);
258 assert!(attendees.rows.iter().all(|row| row.camera_blocked));
259 let presenters = sections.groups.iter().find(|group| group.title == "Presenters").unwrap();
260 assert!(!presenters.rows[0].mic_blocked && !presenters.rows[0].camera_blocked);
261 }
262
263 #[test]
264 fn a_one_to_one_call_turns_into_a_group_when_a_third_person_joins() {
265 let mut model = CallModel::people("Ana", &[("8:orgid:a".into(), "Ana".into())]);
266 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", None)]));
267 assert_eq!(model.kind, CallKind::Direct);
268 model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", None), entry("8:orgid:b", "Bo", None)]));
269 assert_eq!(model.kind, CallKind::Group);
270 }
271}
crates/app/src/call/people_actions.rs added +367 −0
@@ -0,0 +1,367 @@
1 use calling::{CallCommand, Callee, MeetingOptions, MeetingRole, Modality};
2 use gpui_kit::*;
3
4 use super::actions::NOT_CONNECTED_NOTICE;
5 use super::features::TransferCandidate;
6 use super::model::{CallKind, Tile};
7 use super::options_dialog::OptionsDialog;
8 use crate::app_state::{AppEvent, AppState};
9 use crate::runtime;
10
11 const INVITE_FAILED_NOTICE: &str = "Could not add that person";
12 const NO_PEER_NOTICE: &str = "This call cannot be extended";
13
14 impl AppState {
15 pub fn toggle_call_people(&mut self, cx: &mut Context<Self>) {
16 let Some(call) = self.call.as_mut() else {
17 return;
18 };
19 call.people_open = !call.people_open;
20 if call.people_open {
21 call.chat_open = false;
22 }
23 cx.emit(AppEvent::Call);
24 cx.notify();
25 }
26
27 pub fn set_call_lock(&mut self, locked: bool, _cx: &mut Context<Self>) {
28 if self.call.as_ref().is_some_and(|call| call.model.organizes_meeting()) {
29 self.send_call_command(CallCommand::SetLock(locked));
30 }
31 }
32
33 pub fn set_call_role(&mut self, mri: String, role: MeetingRole, _cx: &mut Context<Self>) {
34 let allowed = self.call.as_ref().is_some_and(|call| {
35 call.model.can_change_roles(&mri) && role != MeetingRole::Organizer
36 });
37 if allowed {
38 self.send_call_command(CallCommand::SetRole { mri, role });
39 }
40 }
41
42 pub fn set_call_attendee_modality(
43 &mut self,
44 mri: String,
45 modality: Modality,
46 allowed: bool,
47 _cx: &mut Context<Self>,
48 ) {
49 if self.call.as_ref().is_some_and(|call| call.model.can_change_roles(&mri)) {
50 self.send_call_command(CallCommand::SetAttendeeModality { mri, modality, allowed });
51 }
52 }
53
54 pub fn set_call_attendee_restrictions(&mut self, mic_off: bool, camera_off: bool, _cx: &mut Context<Self>) {
55 if self.call.as_ref().is_some_and(|call| call.model.organizes_meeting()) {
56 self.send_call_command(CallCommand::SetAttendeeRestrictions { mic_off, camera_off });
57 }
58 }
59
60 pub fn open_meeting_options(&mut self, cx: &mut Context<Self>) {
61 let Some(call) = self.call.as_mut().filter(|call| call.model.organizes_meeting()) else {
62 return;
63 };
64 call.options_dialog = Some(OptionsDialog::loading());
65 self.send_call_command(CallCommand::LoadMeetingOptions);
66 cx.notify();
67 }
68
69 pub fn close_meeting_options(&mut self, cx: &mut Context<Self>) {
70 if let Some(call) = self.call.as_mut().filter(|call| call.options_dialog.is_some()) {
71 call.options_dialog = None;
72 cx.notify();
73 }
74 }
75
76 pub fn edit_meeting_options(&mut self, edit: impl FnOnce(&mut MeetingOptions), cx: &mut Context<Self>) {
77 let Some(draft) = self
78 .call
79 .as_mut()
80 .and_then(|call| call.options_dialog.as_mut())
81 .and_then(|dialog| dialog.draft.as_mut())
82 else {
83 return;
84 };
85 edit(draft);
86 cx.notify();
87 }
88
89 pub fn save_meeting_options(&mut self, cx: &mut Context<Self>) {
90 let writes = self
91 .call
92 .as_mut()
93 .and_then(|call| call.options_dialog.as_mut())
94 .and_then(OptionsDialog::begin_save);
95 if let Some(writes) = writes {
96 self.send_call_command(CallCommand::SaveMeetingOptions(writes));
97 cx.notify();
98 }
99 }
100
101 pub fn invite_candidates(&self) -> Vec<TransferCandidate> {
102 let present: Vec<&str> = self
103 .call
104 .as_ref()
105 .map(|call| call.model.tiles.iter().map(|tile| tile.mri.as_str()).collect())
106 .unwrap_or_default();
107 self.transfer_candidates()
108 .into_iter()
109 .filter(|candidate| !present.contains(&candidate.mri.as_str()))
110 .collect()
111 }
112
113 pub fn open_invite_picker(
114 &mut self,
115 picker: Entity<crate::views::transfer_picker::TransferPicker>,
116 cx: &mut Context<Self>,
117 ) {
118 if self.call.as_ref().is_some_and(|call| call.model.can_invite()) {
119 self.transfer_picker = Some(picker);
120 cx.notify();
121 }
122 }
123
124 pub fn invite_call_person(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {
125 self.close_transfer_picker(cx);
126 let Some(call) = self.call.as_mut().filter(|call| call.model.can_invite()) else {
127 return;
128 };
129 let callee = Callee { mri: target.mri.clone(), display_name: target.name.clone() };
130 if !call.model.tiles.iter().any(|tile| tile.mri == callee.mri) {
131 call.model.tiles.push(Tile::invited(&callee.mri, &callee.display_name));
132 }
133 let one_to_one = call.model.kind == CallKind::Direct;
134 let peer_user_id = call
135 .model
136 .tiles
137 .iter()
138 .find(|tile| tile.mri != callee.mri)
139 .and_then(|tile| tile.user_id.clone());
140 let call_id = call.id;
141 cx.emit(AppEvent::Call);
142 cx.notify();
143 if !one_to_one || self.mode.demo {
144 self.send_call_command(CallCommand::Invite { callees: vec![callee], group_thread: None });
145 return;
146 }
147 let (Some(engine), Some(peer_user_id), Some(invited_user_id)) =
148 (self.engine.clone(), peer_user_id, target.user_id.clone())
149 else {
150 let notice = if self.engine.is_none() { NOT_CONNECTED_NOTICE } else { NO_PEER_NOTICE };
151 self.raise_notice(notice.to_owned(), None, cx);
152 return;
153 };
154 let receiver = runtime::spawn(async move {
155 engine.create_group(&[peer_user_id, invited_user_id], None).await
156 });
157 cx.spawn(async move |this, cx| {
158 let created = receiver.await.ok().and_then(Result::ok);
159 this.update(cx, |state, cx| match created {
160 Some(thread_id) if state.call.as_ref().is_some_and(|call| call.id == call_id) => {
161 state.send_call_command(CallCommand::Invite {
162 callees: vec![callee],
163 group_thread: Some(thread_id),
164 });
165 }
166 _ => state.raise_notice(INVITE_FAILED_NOTICE.to_owned(), None, cx),
167 })
168 .ok();
169 })
170 .detach();
171 }
172 }
173
174 #[cfg(test)]
175 mod tests {
176 use std::sync::Arc;
177 use std::time::Instant;
178
179 use calling::{
180 CallCommand, CallControl, CallState, CallUpdate, MeetingCapability, MeetingOptions, MeetingRole,
181 Modality, RosterEntry, call_channel,
182 };
183 use gpui_kit::{AppContext as _, Entity, TestAppContext};
184 use serde_json::json;
185 use store::Store;
186
187 use crate::app_state::{AppState, Mode};
188 use crate::call::{ActiveCall, CallModel, TransferCandidate};
189
190 fn app_with_meeting(cx: &mut TestAppContext, organizer: bool) -> (Entity<AppState>, CallControl) {
191 cx.update(gpui_kit::init);
192 let store = Arc::new(Store::open_in_memory().unwrap());
193 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
194 let (handle, control) = call_channel();
195 let mut model = CallModel::meeting("Standup", organizer);
196 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
197 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
198 model.apply(CallUpdate::Roster(vec![RosterEntry {
199 mri: "8:orgid:a".into(),
200 display_name: "Ana".into(),
201 role: Some(MeetingRole::Attendee),
202 ..RosterEntry::default()
203 }]));
204 cx.update(|cx| {
205 app.update(cx, |state, _| {
206 state.call = Some(ActiveCall::new(
207 7,
208 model,
209 handle.commands,
210 Some("19:meeting_x@thread.v2".into()),
211 handle.video,
212 ));
213 })
214 });
215 (app, control)
216 }
217
218 fn options() -> MeetingOptions {
219 let option = |name: &str, value: serde_json::Value| json!({"name": name, "currentValue": value});
220 MeetingOptions::from_response(&json!({"options": [
221 option("AutoAdmittedUsers", json!("EveryoneInCompany")),
222 option("PresenterOption", json!("Everyone")),
223 option("AttendeeRestrictions", json!("UnRestricted")),
224 option("AllowMeetingChat", json!("Enabled")),
225 option("AllowTeamsMeetingReactions", json!(true)),
226 option("AutoRecordAndTranscribeMode", json!("Off")),
227 ]}))
228 .unwrap()
229 }
230
231 #[gpui_kit::test]
232 fn the_people_panel_and_the_chat_panel_exclude_each_other(cx: &mut TestAppContext) {
233 let (app, _control) = app_with_meeting(cx, true);
234 let open = |app: &Entity<AppState>, cx: &mut TestAppContext| {
235 cx.update(|cx| {
236 let call = app.read(cx).call.as_ref().unwrap();
237 (call.people_open, call.chat_open)
238 })
239 };
240 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)));
241 assert_eq!(open(&app, cx), (false, true));
242 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_people(cx)));
243 assert_eq!(open(&app, cx), (true, false));
244 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)));
245 assert_eq!(open(&app, cx), (false, true));
246 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_people(cx)));
247 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_people(cx)));
248 assert_eq!(open(&app, cx), (false, false));
249 }
250
251 #[gpui_kit::test]
252 fn organizer_actions_become_commands_and_attendees_send_nothing(cx: &mut TestAppContext) {
253 let (attendee, mut attendee_control) = app_with_meeting(cx, false);
254 cx.update(|cx| {
255 attendee.update(cx, |state, cx| {
256 state.set_call_lock(true, cx);
257 state.set_call_role("8:orgid:a".into(), MeetingRole::Presenter, cx);
258 state.set_call_attendee_modality("8:orgid:a".into(), Modality::Mic, false, cx);
259 state.set_call_attendee_restrictions(true, false, cx);
260 state.open_meeting_options(cx);
261 })
262 });
263 assert_eq!(attendee_control.try_recv_command(), None);
264 let (organizer, mut control) = app_with_meeting(cx, true);
265 cx.update(|cx| {
266 organizer.update(cx, |state, cx| {
267 state.set_call_lock(true, cx);
268 state.set_call_role("8:orgid:a".into(), MeetingRole::Presenter, cx);
269 state.set_call_role("8:orgid:a".into(), MeetingRole::Organizer, cx);
270 state.set_call_attendee_modality("8:orgid:a".into(), Modality::Camera, false, cx);
271 state.set_call_attendee_restrictions(true, true, cx);
272 })
273 });
274 assert_eq!(control.try_recv_command(), Some(CallCommand::SetLock(true)));
275 assert_eq!(
276 control.try_recv_command(),
277 Some(CallCommand::SetRole { mri: "8:orgid:a".into(), role: MeetingRole::Presenter })
278 );
279 assert_eq!(
280 control.try_recv_command(),
281 Some(CallCommand::SetAttendeeModality { mri: "8:orgid:a".into(), modality: Modality::Camera, allowed: false })
282 );
283 assert_eq!(
284 control.try_recv_command(),
285 Some(CallCommand::SetAttendeeRestrictions { mic_off: true, camera_off: true })
286 );
287 assert_eq!(control.try_recv_command(), None);
288 }
289
290 #[gpui_kit::test]
291 fn the_capability_update_marks_the_meeting_as_locked(cx: &mut TestAppContext) {
292 let (app, _control) = app_with_meeting(cx, true);
293 cx.update(|cx| {
294 app.update(cx, |state, cx| {
295 state.apply_call_update(
296 7,
297 CallUpdate::Capability(MeetingCapability { locked: true, ..MeetingCapability::default() }),
298 cx,
299 )
300 })
301 });
302 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.capability.locked));
303 }
304
305 #[gpui_kit::test]
306 fn the_options_dialog_loads_saves_only_changes_and_keeps_errors_inline(cx: &mut TestAppContext) {
307 let (app, mut control) = app_with_meeting(cx, true);
308 cx.update(|cx| app.update(cx, |state, cx| state.open_meeting_options(cx)));
309 assert_eq!(control.try_recv_command(), Some(CallCommand::LoadMeetingOptions));
310 cx.update(|cx| {
311 app.update(cx, |state, cx| {
312 state.apply_call_update(7, CallUpdate::MeetingOptions(Err("The options could not be read".into())), cx)
313 })
314 });
315 let error = cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.as_ref().unwrap().error.clone());
316 assert_eq!(error.as_deref(), Some("The options could not be read"));
317 cx.update(|cx| {
318 app.update(cx, |state, cx| {
319 state.apply_call_update(7, CallUpdate::MeetingOptions(Ok(options())), cx);
320 state.save_meeting_options(cx);
321 state.edit_meeting_options(|draft| draft.meeting_chat = "InMeeting".into(), cx);
322 state.save_meeting_options(cx);
323 })
324 });
325 let Some(CallCommand::SaveMeetingOptions(writes)) = control.try_recv_command() else {
326 panic!("a save command");
327 };
328 assert_eq!(writes.len(), 1);
329 assert_eq!(writes[0].name, "AllowMeetingChat");
330 assert_eq!(control.try_recv_command(), None);
331 cx.update(|cx| {
332 app.update(cx, |state, cx| {
333 state.apply_call_update(7, CallUpdate::MeetingOptionsSaved(Err("the service refused AllowMeetingChat".into())), cx)
334 })
335 });
336 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.is_some()));
337 cx.update(|cx| {
338 app.update(cx, |state, cx| {
339 state.apply_call_update(7, CallUpdate::MeetingOptionsSaved(Ok(options())), cx)
340 })
341 });
342 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.is_none()));
343 }
344
345 #[gpui_kit::test]
346 fn inviting_into_a_meeting_sends_the_person_and_shows_them_as_ringing(cx: &mut TestAppContext) {
347 let (app, mut control) = app_with_meeting(cx, true);
348 let candidate = TransferCandidate {
349 mri: "8:orgid:bo".into(),
350 name: "Bo".into(),
351 user_id: Some("bo".into()),
352 chat_id: "19:bo".into(),
353 };
354 cx.update(|cx| app.update(cx, |state, cx| state.invite_call_person(candidate, cx)));
355 let Some(CallCommand::Invite { callees, group_thread }) = control.try_recv_command() else {
356 panic!("an invite command");
357 };
358 assert_eq!(callees.len(), 1);
359 assert_eq!(callees[0].mri, "8:orgid:bo");
360 assert_eq!(group_thread, None);
361 let ringing = cx.update(|cx| {
362 let tiles = &app.read(cx).call.as_ref().unwrap().model.tiles;
363 tiles.iter().any(|tile| tile.mri == "8:orgid:bo" && tile.invited)
364 });
365 assert!(ringing);
366 }
367 }
@@ -0,0 +1,367 @@
1use calling::{CallCommand, Callee, MeetingOptions, MeetingRole, Modality};
2use gpui_kit::*;
3
4use super::actions::NOT_CONNECTED_NOTICE;
5use super::features::TransferCandidate;
6use super::model::{CallKind, Tile};
7use super::options_dialog::OptionsDialog;
8use crate::app_state::{AppEvent, AppState};
9use crate::runtime;
10
11const INVITE_FAILED_NOTICE: &str = "Could not add that person";
12const NO_PEER_NOTICE: &str = "This call cannot be extended";
13
14impl AppState {
15 pub fn toggle_call_people(&mut self, cx: &mut Context<Self>) {
16 let Some(call) = self.call.as_mut() else {
17 return;
18 };
19 call.people_open = !call.people_open;
20 if call.people_open {
21 call.chat_open = false;
22 }
23 cx.emit(AppEvent::Call);
24 cx.notify();
25 }
26
27 pub fn set_call_lock(&mut self, locked: bool, _cx: &mut Context<Self>) {
28 if self.call.as_ref().is_some_and(|call| call.model.organizes_meeting()) {
29 self.send_call_command(CallCommand::SetLock(locked));
30 }
31 }
32
33 pub fn set_call_role(&mut self, mri: String, role: MeetingRole, _cx: &mut Context<Self>) {
34 let allowed = self.call.as_ref().is_some_and(|call| {
35 call.model.can_change_roles(&mri) && role != MeetingRole::Organizer
36 });
37 if allowed {
38 self.send_call_command(CallCommand::SetRole { mri, role });
39 }
40 }
41
42 pub fn set_call_attendee_modality(
43 &mut self,
44 mri: String,
45 modality: Modality,
46 allowed: bool,
47 _cx: &mut Context<Self>,
48 ) {
49 if self.call.as_ref().is_some_and(|call| call.model.can_change_roles(&mri)) {
50 self.send_call_command(CallCommand::SetAttendeeModality { mri, modality, allowed });
51 }
52 }
53
54 pub fn set_call_attendee_restrictions(&mut self, mic_off: bool, camera_off: bool, _cx: &mut Context<Self>) {
55 if self.call.as_ref().is_some_and(|call| call.model.organizes_meeting()) {
56 self.send_call_command(CallCommand::SetAttendeeRestrictions { mic_off, camera_off });
57 }
58 }
59
60 pub fn open_meeting_options(&mut self, cx: &mut Context<Self>) {
61 let Some(call) = self.call.as_mut().filter(|call| call.model.organizes_meeting()) else {
62 return;
63 };
64 call.options_dialog = Some(OptionsDialog::loading());
65 self.send_call_command(CallCommand::LoadMeetingOptions);
66 cx.notify();
67 }
68
69 pub fn close_meeting_options(&mut self, cx: &mut Context<Self>) {
70 if let Some(call) = self.call.as_mut().filter(|call| call.options_dialog.is_some()) {
71 call.options_dialog = None;
72 cx.notify();
73 }
74 }
75
76 pub fn edit_meeting_options(&mut self, edit: impl FnOnce(&mut MeetingOptions), cx: &mut Context<Self>) {
77 let Some(draft) = self
78 .call
79 .as_mut()
80 .and_then(|call| call.options_dialog.as_mut())
81 .and_then(|dialog| dialog.draft.as_mut())
82 else {
83 return;
84 };
85 edit(draft);
86 cx.notify();
87 }
88
89 pub fn save_meeting_options(&mut self, cx: &mut Context<Self>) {
90 let writes = self
91 .call
92 .as_mut()
93 .and_then(|call| call.options_dialog.as_mut())
94 .and_then(OptionsDialog::begin_save);
95 if let Some(writes) = writes {
96 self.send_call_command(CallCommand::SaveMeetingOptions(writes));
97 cx.notify();
98 }
99 }
100
101 pub fn invite_candidates(&self) -> Vec<TransferCandidate> {
102 let present: Vec<&str> = self
103 .call
104 .as_ref()
105 .map(|call| call.model.tiles.iter().map(|tile| tile.mri.as_str()).collect())
106 .unwrap_or_default();
107 self.transfer_candidates()
108 .into_iter()
109 .filter(|candidate| !present.contains(&candidate.mri.as_str()))
110 .collect()
111 }
112
113 pub fn open_invite_picker(
114 &mut self,
115 picker: Entity<crate::views::transfer_picker::TransferPicker>,
116 cx: &mut Context<Self>,
117 ) {
118 if self.call.as_ref().is_some_and(|call| call.model.can_invite()) {
119 self.transfer_picker = Some(picker);
120 cx.notify();
121 }
122 }
123
124 pub fn invite_call_person(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {
125 self.close_transfer_picker(cx);
126 let Some(call) = self.call.as_mut().filter(|call| call.model.can_invite()) else {
127 return;
128 };
129 let callee = Callee { mri: target.mri.clone(), display_name: target.name.clone() };
130 if !call.model.tiles.iter().any(|tile| tile.mri == callee.mri) {
131 call.model.tiles.push(Tile::invited(&callee.mri, &callee.display_name));
132 }
133 let one_to_one = call.model.kind == CallKind::Direct;
134 let peer_user_id = call
135 .model
136 .tiles
137 .iter()
138 .find(|tile| tile.mri != callee.mri)
139 .and_then(|tile| tile.user_id.clone());
140 let call_id = call.id;
141 cx.emit(AppEvent::Call);
142 cx.notify();
143 if !one_to_one || self.mode.demo {
144 self.send_call_command(CallCommand::Invite { callees: vec![callee], group_thread: None });
145 return;
146 }
147 let (Some(engine), Some(peer_user_id), Some(invited_user_id)) =
148 (self.engine.clone(), peer_user_id, target.user_id.clone())
149 else {
150 let notice = if self.engine.is_none() { NOT_CONNECTED_NOTICE } else { NO_PEER_NOTICE };
151 self.raise_notice(notice.to_owned(), None, cx);
152 return;
153 };
154 let receiver = runtime::spawn(async move {
155 engine.create_group(&[peer_user_id, invited_user_id], None).await
156 });
157 cx.spawn(async move |this, cx| {
158 let created = receiver.await.ok().and_then(Result::ok);
159 this.update(cx, |state, cx| match created {
160 Some(thread_id) if state.call.as_ref().is_some_and(|call| call.id == call_id) => {
161 state.send_call_command(CallCommand::Invite {
162 callees: vec![callee],
163 group_thread: Some(thread_id),
164 });
165 }
166 _ => state.raise_notice(INVITE_FAILED_NOTICE.to_owned(), None, cx),
167 })
168 .ok();
169 })
170 .detach();
171 }
172}
173
174#[cfg(test)]
175mod tests {
176 use std::sync::Arc;
177 use std::time::Instant;
178
179 use calling::{
180 CallCommand, CallControl, CallState, CallUpdate, MeetingCapability, MeetingOptions, MeetingRole,
181 Modality, RosterEntry, call_channel,
182 };
183 use gpui_kit::{AppContext as _, Entity, TestAppContext};
184 use serde_json::json;
185 use store::Store;
186
187 use crate::app_state::{AppState, Mode};
188 use crate::call::{ActiveCall, CallModel, TransferCandidate};
189
190 fn app_with_meeting(cx: &mut TestAppContext, organizer: bool) -> (Entity<AppState>, CallControl) {
191 cx.update(gpui_kit::init);
192 let store = Arc::new(Store::open_in_memory().unwrap());
193 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
194 let (handle, control) = call_channel();
195 let mut model = CallModel::meeting("Standup", organizer);
196 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
197 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
198 model.apply(CallUpdate::Roster(vec![RosterEntry {
199 mri: "8:orgid:a".into(),
200 display_name: "Ana".into(),
201 role: Some(MeetingRole::Attendee),
202 ..RosterEntry::default()
203 }]));
204 cx.update(|cx| {
205 app.update(cx, |state, _| {
206 state.call = Some(ActiveCall::new(
207 7,
208 model,
209 handle.commands,
210 Some("19:meeting_x@thread.v2".into()),
211 handle.video,
212 ));
213 })
214 });
215 (app, control)
216 }
217
218 fn options() -> MeetingOptions {
219 let option = |name: &str, value: serde_json::Value| json!({"name": name, "currentValue": value});
220 MeetingOptions::from_response(&json!({"options": [
221 option("AutoAdmittedUsers", json!("EveryoneInCompany")),
222 option("PresenterOption", json!("Everyone")),
223 option("AttendeeRestrictions", json!("UnRestricted")),
224 option("AllowMeetingChat", json!("Enabled")),
225 option("AllowTeamsMeetingReactions", json!(true)),
226 option("AutoRecordAndTranscribeMode", json!("Off")),
227 ]}))
228 .unwrap()
229 }
230
231 #[gpui_kit::test]
232 fn the_people_panel_and_the_chat_panel_exclude_each_other(cx: &mut TestAppContext) {
233 let (app, _control) = app_with_meeting(cx, true);
234 let open = |app: &Entity<AppState>, cx: &mut TestAppContext| {
235 cx.update(|cx| {
236 let call = app.read(cx).call.as_ref().unwrap();
237 (call.people_open, call.chat_open)
238 })
239 };
240 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)));
241 assert_eq!(open(&app, cx), (false, true));
242 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_people(cx)));
243 assert_eq!(open(&app, cx), (true, false));
244 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)));
245 assert_eq!(open(&app, cx), (false, true));
246 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_people(cx)));
247 cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_people(cx)));
248 assert_eq!(open(&app, cx), (false, false));
249 }
250
251 #[gpui_kit::test]
252 fn organizer_actions_become_commands_and_attendees_send_nothing(cx: &mut TestAppContext) {
253 let (attendee, mut attendee_control) = app_with_meeting(cx, false);
254 cx.update(|cx| {
255 attendee.update(cx, |state, cx| {
256 state.set_call_lock(true, cx);
257 state.set_call_role("8:orgid:a".into(), MeetingRole::Presenter, cx);
258 state.set_call_attendee_modality("8:orgid:a".into(), Modality::Mic, false, cx);
259 state.set_call_attendee_restrictions(true, false, cx);
260 state.open_meeting_options(cx);
261 })
262 });
263 assert_eq!(attendee_control.try_recv_command(), None);
264 let (organizer, mut control) = app_with_meeting(cx, true);
265 cx.update(|cx| {
266 organizer.update(cx, |state, cx| {
267 state.set_call_lock(true, cx);
268 state.set_call_role("8:orgid:a".into(), MeetingRole::Presenter, cx);
269 state.set_call_role("8:orgid:a".into(), MeetingRole::Organizer, cx);
270 state.set_call_attendee_modality("8:orgid:a".into(), Modality::Camera, false, cx);
271 state.set_call_attendee_restrictions(true, true, cx);
272 })
273 });
274 assert_eq!(control.try_recv_command(), Some(CallCommand::SetLock(true)));
275 assert_eq!(
276 control.try_recv_command(),
277 Some(CallCommand::SetRole { mri: "8:orgid:a".into(), role: MeetingRole::Presenter })
278 );
279 assert_eq!(
280 control.try_recv_command(),
281 Some(CallCommand::SetAttendeeModality { mri: "8:orgid:a".into(), modality: Modality::Camera, allowed: false })
282 );
283 assert_eq!(
284 control.try_recv_command(),
285 Some(CallCommand::SetAttendeeRestrictions { mic_off: true, camera_off: true })
286 );
287 assert_eq!(control.try_recv_command(), None);
288 }
289
290 #[gpui_kit::test]
291 fn the_capability_update_marks_the_meeting_as_locked(cx: &mut TestAppContext) {
292 let (app, _control) = app_with_meeting(cx, true);
293 cx.update(|cx| {
294 app.update(cx, |state, cx| {
295 state.apply_call_update(
296 7,
297 CallUpdate::Capability(MeetingCapability { locked: true, ..MeetingCapability::default() }),
298 cx,
299 )
300 })
301 });
302 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.capability.locked));
303 }
304
305 #[gpui_kit::test]
306 fn the_options_dialog_loads_saves_only_changes_and_keeps_errors_inline(cx: &mut TestAppContext) {
307 let (app, mut control) = app_with_meeting(cx, true);
308 cx.update(|cx| app.update(cx, |state, cx| state.open_meeting_options(cx)));
309 assert_eq!(control.try_recv_command(), Some(CallCommand::LoadMeetingOptions));
310 cx.update(|cx| {
311 app.update(cx, |state, cx| {
312 state.apply_call_update(7, CallUpdate::MeetingOptions(Err("The options could not be read".into())), cx)
313 })
314 });
315 let error = cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.as_ref().unwrap().error.clone());
316 assert_eq!(error.as_deref(), Some("The options could not be read"));
317 cx.update(|cx| {
318 app.update(cx, |state, cx| {
319 state.apply_call_update(7, CallUpdate::MeetingOptions(Ok(options())), cx);
320 state.save_meeting_options(cx);
321 state.edit_meeting_options(|draft| draft.meeting_chat = "InMeeting".into(), cx);
322 state.save_meeting_options(cx);
323 })
324 });
325 let Some(CallCommand::SaveMeetingOptions(writes)) = control.try_recv_command() else {
326 panic!("a save command");
327 };
328 assert_eq!(writes.len(), 1);
329 assert_eq!(writes[0].name, "AllowMeetingChat");
330 assert_eq!(control.try_recv_command(), None);
331 cx.update(|cx| {
332 app.update(cx, |state, cx| {
333 state.apply_call_update(7, CallUpdate::MeetingOptionsSaved(Err("the service refused AllowMeetingChat".into())), cx)
334 })
335 });
336 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.is_some()));
337 cx.update(|cx| {
338 app.update(cx, |state, cx| {
339 state.apply_call_update(7, CallUpdate::MeetingOptionsSaved(Ok(options())), cx)
340 })
341 });
342 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.is_none()));
343 }
344
345 #[gpui_kit::test]
346 fn inviting_into_a_meeting_sends_the_person_and_shows_them_as_ringing(cx: &mut TestAppContext) {
347 let (app, mut control) = app_with_meeting(cx, true);
348 let candidate = TransferCandidate {
349 mri: "8:orgid:bo".into(),
350 name: "Bo".into(),
351 user_id: Some("bo".into()),
352 chat_id: "19:bo".into(),
353 };
354 cx.update(|cx| app.update(cx, |state, cx| state.invite_call_person(candidate, cx)));
355 let Some(CallCommand::Invite { callees, group_thread }) = control.try_recv_command() else {
356 panic!("an invite command");
357 };
358 assert_eq!(callees.len(), 1);
359 assert_eq!(callees[0].mri, "8:orgid:bo");
360 assert_eq!(group_thread, None);
361 let ringing = cx.update(|cx| {
362 let tiles = &app.read(cx).call.as_ref().unwrap().model.tiles;
363 tiles.iter().any(|tile| tile.mri == "8:orgid:bo" && tile.invited)
364 });
365 assert!(ringing);
366 }
367}
crates/app/src/layout_guard.rs +17 −6
@@ -150,6 +150,7 @@ mod frames {
150 150 "shell/islands/main/call-stage",
151 151 "shell/islands/main/call-controls",
152 152 ];
153 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
153 154 const MENU: &str = "popup-menu";
154 155 const OWN_STATUS: &str = "shell/title-bar/own-status";
155 156 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
@@ -164,6 +165,7 @@ mod frames {
164 165 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
165 166 StatusMenu,
166 167 Call,
168 CallPeople,
167 169 }
168 170
169 171 fn parent_of(path: &str) -> Option<&str> {
@@ -279,7 +281,7 @@ mod frames {
279 281 GUARDED
280 282 .iter()
281 283 .chain(CALL_GUARDED)
282 .chain([&MENU, &RECAP_TAB, &RECAP_REGION])
284 .chain([&MENU, &RECAP_TAB, &RECAP_REGION, &PEOPLE_PANEL])
283 285 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
284 286 .collect()
285 287 }
@@ -302,6 +304,7 @@ mod frames {
302 304 hand: None,
303 305 spotlight: None,
304 306 organizer: false,
307 ..Default::default()
305 308 })
306 309 .collect(),
307 310 ));
@@ -395,6 +398,7 @@ mod frames {
395 398 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
396 399 Screen::StatusMenu,
397 400 Screen::Call,
401 Screen::CallPeople,
398 402 ];
399 403 for screen in screens {
400 404 let (screen_name, status_menu) = match screen {
@@ -404,14 +408,17 @@ mod frames {
404 408 }
405 409 (name, false)
406 410 }
407 Screen::Call => {
411 Screen::Call | Screen::CallPeople => {
412 let people_open = matches!(screen, Screen::CallPeople);
408 413 visual.update(|_, cx| {
409 414 app.update(cx, |state, cx| {
410 state.call = Some(gallery_call());
415 let mut call = gallery_call();
416 call.people_open = people_open;
417 state.call = Some(call);
411 418 cx.notify();
412 419 })
413 420 });
414 ("call", false)
421 (if people_open { "call-people" } else { "call" }, false)
415 422 }
416 423 Screen::StatusMenu => {
417 424 let tags = collect(&mut visual, None);
@@ -424,11 +431,15 @@ mod frames {
424 431 ("status-menu", true)
425 432 }
426 433 };
434 let is_call = matches!(screen_name, "call" | "call-people");
427 435 let tags = collect(&mut visual, status_menu.then_some(MENU));
428 436 let mut expected = GUARDED.to_vec();
429 if screen_name == "call" {
437 if is_call {
430 438 expected.extend(CALL_GUARDED);
431 439 }
440 if screen_name == "call-people" {
441 expected.push(PEOPLE_PANEL);
442 }
432 443 if status_menu {
433 444 expected.push(MENU);
434 445 }
@@ -457,7 +468,7 @@ mod frames {
457 468 visual.simulate_keystrokes("escape");
458 469 visual.run_until_parked();
459 470 }
460 if screen_name == "call" {
471 if is_call {
461 472 visual.update(|_, cx| {
462 473 app.update(cx, |state, cx| {
463 474 state.call = None;
@@ -150,6 +150,7 @@ mod frames {
150 "shell/islands/main/call-stage",
150 "shell/islands/main/call-stage",
151 "shell/islands/main/call-controls",
151 "shell/islands/main/call-controls",
152 ];
152 ];
153 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
153 const MENU: &str = "popup-menu";
154 const MENU: &str = "popup-menu";
154 const OWN_STATUS: &str = "shell/title-bar/own-status";
155 const OWN_STATUS: &str = "shell/title-bar/own-status";
155 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
156 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
@@ -164,6 +165,7 @@ mod frames {
164 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
165 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
165 StatusMenu,
166 StatusMenu,
166 Call,
167 Call,
168 CallPeople,
167 }
169 }
168
170
169 fn parent_of(path: &str) -> Option<&str> {
171 fn parent_of(path: &str) -> Option<&str> {
@@ -279,7 +281,7 @@ mod frames {
279 GUARDED
281 GUARDED
280 .iter()
282 .iter()
281 .chain(CALL_GUARDED)
283 .chain(CALL_GUARDED)
282 .chain([&MENU, &RECAP_TAB, &RECAP_REGION])
284 .chain([&MENU, &RECAP_TAB, &RECAP_REGION, &PEOPLE_PANEL])
283 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
285 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
284 .collect()
286 .collect()
285 }
287 }
@@ -302,6 +304,7 @@ mod frames {
302 hand: None,
304 hand: None,
303 spotlight: None,
305 spotlight: None,
304 organizer: false,
306 organizer: false,
307 ..Default::default()
305 })
308 })
306 .collect(),
309 .collect(),
307 ));
310 ));
@@ -395,6 +398,7 @@ mod frames {
395 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
398 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
396 Screen::StatusMenu,
399 Screen::StatusMenu,
397 Screen::Call,
400 Screen::Call,
401 Screen::CallPeople,
398 ];
402 ];
399 for screen in screens {
403 for screen in screens {
400 let (screen_name, status_menu) = match screen {
404 let (screen_name, status_menu) = match screen {
@@ -404,14 +408,17 @@ mod frames {
404 }
408 }
405 (name, false)
409 (name, false)
406 }
410 }
407 Screen::Call => {
411 Screen::Call | Screen::CallPeople => {
412 let people_open = matches!(screen, Screen::CallPeople);
408 visual.update(|_, cx| {
413 visual.update(|_, cx| {
409 app.update(cx, |state, cx| {
414 app.update(cx, |state, cx| {
410 state.call = Some(gallery_call());
415 let mut call = gallery_call();
416 call.people_open = people_open;
417 state.call = Some(call);
411 cx.notify();
418 cx.notify();
412 })
419 })
413 });
420 });
414 ("call", false)
421 (if people_open { "call-people" } else { "call" }, false)
415 }
422 }
416 Screen::StatusMenu => {
423 Screen::StatusMenu => {
417 let tags = collect(&mut visual, None);
424 let tags = collect(&mut visual, None);
@@ -424,11 +431,15 @@ mod frames {
424 ("status-menu", true)
431 ("status-menu", true)
425 }
432 }
426 };
433 };
434 let is_call = matches!(screen_name, "call" | "call-people");
427 let tags = collect(&mut visual, status_menu.then_some(MENU));
435 let tags = collect(&mut visual, status_menu.then_some(MENU));
428 let mut expected = GUARDED.to_vec();
436 let mut expected = GUARDED.to_vec();
429 if screen_name == "call" {
437 if is_call {
430 expected.extend(CALL_GUARDED);
438 expected.extend(CALL_GUARDED);
431 }
439 }
440 if screen_name == "call-people" {
441 expected.push(PEOPLE_PANEL);
442 }
432 if status_menu {
443 if status_menu {
433 expected.push(MENU);
444 expected.push(MENU);
434 }
445 }
@@ -457,7 +468,7 @@ mod frames {
457 visual.simulate_keystrokes("escape");
468 visual.simulate_keystrokes("escape");
458 visual.run_until_parked();
469 visual.run_until_parked();
459 }
470 }
460 if screen_name == "call" {
471 if is_call {
461 visual.update(|_, cx| {
472 visual.update(|_, cx| {
462 app.update(cx, |state, cx| {
473 app.update(cx, |state, cx| {
463 state.call = None;
474 state.call = None;
crates/app/src/views/call_extras.rs +9 −2
@@ -12,7 +12,7 @@ use gpui_kit::*;
12 12
13 13 use super::call_organizer::pill;
14 14 use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
15 use super::transfer_picker::TransferPicker;
15 use super::transfer_picker::{PickerMode, TransferPicker};
16 16 use super::widgets::icon;
17 17 use crate::app_state::AppState;
18 18 use crate::call::{BackgroundPick, CallModel};
@@ -284,10 +284,17 @@ pub fn confirm_stop_recording(app: &Entity<AppState>, window: &mut Window, cx: &
284 284 pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
285 285 let candidates = app.read(cx).transfer_candidates();
286 286 let picker_app = app.clone();
287 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, window, cx));
287 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Transfer, window, cx));
288 288 app.update(cx, |state, cx| state.open_transfer_picker(picker, cx));
289 289 }
290 290
291 pub fn open_invite_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
292 let candidates = app.read(cx).invite_candidates();
293 let picker_app = app.clone();
294 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Invite, window, cx));
295 app.update(cx, |state, cx| state.open_invite_picker(picker, cx));
296 }
297
291 298 #[derive(Clone)]
292 299 pub struct CameraMenu {
293 300 pub pick: BackgroundPick,
@@ -12,7 +12,7 @@ use gpui_kit::*;
12
12
13use super::call_organizer::pill;
13use super::call_organizer::pill;
14use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
14use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
15use super::transfer_picker::TransferPicker;
15use super::transfer_picker::{PickerMode, TransferPicker};
16use super::widgets::icon;
16use super::widgets::icon;
17use crate::app_state::AppState;
17use crate::app_state::AppState;
18use crate::call::{BackgroundPick, CallModel};
18use crate::call::{BackgroundPick, CallModel};
@@ -284,10 +284,17 @@ pub fn confirm_stop_recording(app: &Entity<AppState>, window: &mut Window, cx: &
284pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
284pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
285 let candidates = app.read(cx).transfer_candidates();
285 let candidates = app.read(cx).transfer_candidates();
286 let picker_app = app.clone();
286 let picker_app = app.clone();
287 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, window, cx));
287 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Transfer, window, cx));
288 app.update(cx, |state, cx| state.open_transfer_picker(picker, cx));
288 app.update(cx, |state, cx| state.open_transfer_picker(picker, cx));
289}
289}
290
290
291pub fn open_invite_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
292 let candidates = app.read(cx).invite_candidates();
293 let picker_app = app.clone();
294 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Invite, window, cx));
295 app.update(cx, |state, cx| state.open_invite_picker(picker, cx));
296}
297
291#[derive(Clone)]
298#[derive(Clone)]
292pub struct CameraMenu {
299pub struct CameraMenu {
293 pub pick: BackgroundPick,
300 pub pick: BackgroundPick,
crates/app/src/views/call_organizer.rs +47 −1
@@ -1,7 +1,7 @@
1 1 use std::sync::Arc;
2 2 use std::time::Instant;
3 3
4 use calling::{CaptionState, HoldState, VideoKey};
4 use calling::{CaptionState, HoldState, MeetingRole, Modality, 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;
@@ -15,6 +15,7 @@ use super::avatar::person_avatar;
15 15 use super::call_extras::{
16 16 CameraMenu, background_items, confirm_stop_recording, effect_items, open_transfer_picker,
17 17 };
18 use super::call_people::add_people_item;
18 19 use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};
19 20 use super::widgets::icon;
20 21 use crate::app_state::AppState;
@@ -274,6 +275,9 @@ pub fn tile_menu(
274 275 }),
275 276 );
276 277 }
278 if model.can_change_roles(mri) {
279 popup = restriction_items(popup, app, model, mri);
280 }
277 281 if organizes && raised {
278 282 let (hand_app, hand_mri) = (app.clone(), mri.to_owned());
279 283 popup = popup.item(PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| {
@@ -293,6 +297,47 @@ pub fn tile_menu(
293 297 popup
294 298 }
295 299
300 fn modality_item(
301 app: &Entity<AppState>,
302 mri: &str,
303 modality: Modality,
304 allowed: bool,
305 ) -> PopupMenuItem {
306 let (app, mri) = (app.clone(), mri.to_owned());
307 let (label, glyph) = match (modality, allowed) {
308 (Modality::Mic, true) => ("Disable mic", IconName::MicOff),
309 (Modality::Mic, false) => ("Allow mic", IconName::Mic),
310 (Modality::Camera, true) => ("Disable camera", IconName::VideoOff),
311 (Modality::Camera, false) => ("Allow camera", IconName::Video),
312 };
313 PopupMenuItem::new(label).icon(glyph).on_click(move |_, _, cx| {
314 app.update(cx, |state, cx| {
315 state.set_call_attendee_modality(mri.clone(), modality, !allowed, cx)
316 })
317 })
318 }
319
320 fn restriction_items(
321 popup: PopupMenu,
322 app: &Entity<AppState>,
323 model: &CallModel,
324 mri: &str,
325 ) -> PopupMenu {
326 let presenter = model.tile_role(mri) == Some(MeetingRole::Presenter);
327 let (role_app, role_mri) = (app.clone(), mri.to_owned());
328 popup
329 .item(modality_item(app, mri, Modality::Mic, model.attendee_allowed(mri, Modality::Mic)))
330 .item(modality_item(app, mri, Modality::Camera, model.attendee_allowed(mri, Modality::Camera)))
331 .item(
332 PopupMenuItem::new(if presenter { "Make attendee" } else { "Make presenter" })
333 .icon(IconName::Users)
334 .on_click(move |_, _, cx| {
335 let role = if presenter { MeetingRole::Attendee } else { MeetingRole::Presenter };
336 role_app.update(cx, |state, cx| state.set_call_role(role_mri.clone(), role, cx))
337 }),
338 )
339 }
340
296 341 fn more_overlay(
297 342 app: &Entity<AppState>,
298 343 model: &CallModel,
@@ -428,6 +473,7 @@ fn one_to_one_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallMo
428 473 .on_click(move |_, _, cx| hold_app.update(cx, |state, cx| state.toggle_call_hold(cx))),
429 474 );
430 475 let can_transfer = model.can_transfer();
476 popup = popup.item(add_people_item(app, model));
431 477 popup.item(
432 478 PopupMenuItem::new("Transfer...")
433 479 .icon(IconName::Forward)
@@ -1,7 +1,7 @@
1use std::sync::Arc;
1use std::sync::Arc;
2use std::time::Instant;
2use std::time::Instant;
3
3
4use calling::{CaptionState, HoldState, VideoKey};
4use calling::{CaptionState, HoldState, MeetingRole, Modality, VideoKey};
5use gpui_kit::assets::IconName;
5use gpui_kit::assets::IconName;
6use gpui_kit::component::button::{Button, ButtonVariants as _};
6use gpui_kit::component::button::{Button, ButtonVariants as _};
7use gpui_kit::component::dialog::DialogFooter;
7use gpui_kit::component::dialog::DialogFooter;
@@ -15,6 +15,7 @@ use super::avatar::person_avatar;
15use super::call_extras::{
15use super::call_extras::{
16 CameraMenu, background_items, confirm_stop_recording, effect_items, open_transfer_picker,
16 CameraMenu, background_items, confirm_stop_recording, effect_items, open_transfer_picker,
17};
17};
18use super::call_people::add_people_item;
18use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};
19use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};
19use super::widgets::icon;
20use super::widgets::icon;
20use crate::app_state::AppState;
21use crate::app_state::AppState;
@@ -274,6 +275,9 @@ pub fn tile_menu(
274 }),
275 }),
275 );
276 );
276 }
277 }
278 if model.can_change_roles(mri) {
279 popup = restriction_items(popup, app, model, mri);
280 }
277 if organizes && raised {
281 if organizes && raised {
278 let (hand_app, hand_mri) = (app.clone(), mri.to_owned());
282 let (hand_app, hand_mri) = (app.clone(), mri.to_owned());
279 popup = popup.item(PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| {
283 popup = popup.item(PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| {
@@ -293,6 +297,47 @@ pub fn tile_menu(
293 popup
297 popup
294}
298}
295
299
300fn modality_item(
301 app: &Entity<AppState>,
302 mri: &str,
303 modality: Modality,
304 allowed: bool,
305) -> PopupMenuItem {
306 let (app, mri) = (app.clone(), mri.to_owned());
307 let (label, glyph) = match (modality, allowed) {
308 (Modality::Mic, true) => ("Disable mic", IconName::MicOff),
309 (Modality::Mic, false) => ("Allow mic", IconName::Mic),
310 (Modality::Camera, true) => ("Disable camera", IconName::VideoOff),
311 (Modality::Camera, false) => ("Allow camera", IconName::Video),
312 };
313 PopupMenuItem::new(label).icon(glyph).on_click(move |_, _, cx| {
314 app.update(cx, |state, cx| {
315 state.set_call_attendee_modality(mri.clone(), modality, !allowed, cx)
316 })
317 })
318}
319
320fn restriction_items(
321 popup: PopupMenu,
322 app: &Entity<AppState>,
323 model: &CallModel,
324 mri: &str,
325) -> PopupMenu {
326 let presenter = model.tile_role(mri) == Some(MeetingRole::Presenter);
327 let (role_app, role_mri) = (app.clone(), mri.to_owned());
328 popup
329 .item(modality_item(app, mri, Modality::Mic, model.attendee_allowed(mri, Modality::Mic)))
330 .item(modality_item(app, mri, Modality::Camera, model.attendee_allowed(mri, Modality::Camera)))
331 .item(
332 PopupMenuItem::new(if presenter { "Make attendee" } else { "Make presenter" })
333 .icon(IconName::Users)
334 .on_click(move |_, _, cx| {
335 let role = if presenter { MeetingRole::Attendee } else { MeetingRole::Presenter };
336 role_app.update(cx, |state, cx| state.set_call_role(role_mri.clone(), role, cx))
337 }),
338 )
339}
340
296fn more_overlay(
341fn more_overlay(
297 app: &Entity<AppState>,
342 app: &Entity<AppState>,
298 model: &CallModel,
343 model: &CallModel,
@@ -428,6 +473,7 @@ fn one_to_one_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallMo
428 .on_click(move |_, _, cx| hold_app.update(cx, |state, cx| state.toggle_call_hold(cx))),
473 .on_click(move |_, _, cx| hold_app.update(cx, |state, cx| state.toggle_call_hold(cx))),
429 );
474 );
430 let can_transfer = model.can_transfer();
475 let can_transfer = model.can_transfer();
476 popup = popup.item(add_people_item(app, model));
431 popup.item(
477 popup.item(
432 PopupMenuItem::new("Transfer...")
478 PopupMenuItem::new("Transfer...")
433 .icon(IconName::Forward)
479 .icon(IconName::Forward)
crates/app/src/views/call_people.rs added +697 −0
@@ -0,0 +1,697 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::{
3 Sizable as _,
4 button::{Button, ButtonVariants as _},
5 h_flex,
6 menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},
7 switch::Switch,
8 tooltip::Tooltip,
9 v_flex,
10 };
11 use gpui_kit::prelude::FluentBuilder as _;
12 use gpui_kit::*;
13
14 use super::avatar::person_avatar;
15 use super::call_extras::open_invite_picker;
16 use super::call_organizer::{pill, tile_menu};
17 use super::call_view::{BANNER_HEIGHT, CHAT_PANEL_WIDTH, MENU_WIDTH, round_control};
18 use super::widgets::{Corner, corner_badge, count_badge, icon};
19 use crate::app_state::AppState;
20 use crate::call::{
21 ActiveCall, CallKind, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,
22 };
23 use crate::notice::truncated;
24 use crate::theme;
25 use calling::MeetingOptions;
26
27 const HEADER_HEIGHT: f32 = 48.;
28 const ROW_HEIGHT: f32 = 44.;
29 const AVATAR_SIZE: f32 = 28.;
30 const MORE_SIZE: f32 = 24.;
31 const SECTION_HEIGHT: f32 = 32.;
32 const NAME_LIMIT: usize = 26;
33 const STATE_ICON: f32 = 15.;
34 const DIALOG_WIDTH: f32 = 460.;
35 const DIALOG_BACKDROP: f32 = 0.55;
36 const FIELD_HEIGHT: f32 = 36.;
37 const DROPDOWN_WIDTH: f32 = 210.;
38
39 fn dark_text() -> Hsla {
40 hsla(0., 0., 0.08, 1.)
41 }
42
43 pub fn people_button(app: &Entity<AppState>, open: bool, raised_hands: usize) -> Stateful<Div> {
44 let app = app.clone();
45 let (background, foreground) = if open {
46 (theme::accent(), theme::on_accent())
47 } else {
48 (theme::surface_raised(), theme::text())
49 };
50 round_control("call-people", IconName::Users, background, foreground)
51 .relative()
52 .tooltip(move |window, cx| {
53 Tooltip::new(if open { "Close the people list" } else { "Show people" }).build(window, cx)
54 })
55 .when(raised_hands > 0, |button| {
56 button.child(
57 corner_badge(Corner::TopRight, 4.).child(count_badge(raised_hands as u32, false)),
58 )
59 })
60 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_people(cx)))
61 }
62
63 pub fn lock_chip(model: &CallModel) -> Option<AnyElement> {
64 model.capability.locked.then(|| {
65 h_flex()
66 .id("call-lock-chip")
67 .h(px(24.))
68 .px(px(8.))
69 .gap(px(4.))
70 .flex_none()
71 .items_center()
72 .rounded_full()
73 .bg(theme::amber())
74 .text_color(dark_text())
75 .text_size(px(12.))
76 .font_weight(FontWeight::SEMIBOLD)
77 .child(icon(IconName::Lock, 13., dark_text()))
78 .child("Locked")
79 .into_any_element()
80 })
81 }
82
83 pub fn lock_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
84 if !model.capability.locked || !model.organizes_meeting() {
85 return None;
86 }
87 let app = app.clone();
88 Some(
89 h_flex()
90 .id("call-lock-banner")
91 .w_full()
92 .h(px(BANNER_HEIGHT))
93 .flex_none()
94 .px(px(20.))
95 .gap(px(12.))
96 .items_center()
97 .justify_center()
98 .bg(theme::surface_raised())
99 .text_color(theme::text())
100 .text_size(px(13.))
101 .font_weight(FontWeight::SEMIBOLD)
102 .child("The meeting is locked. Nobody new can join.")
103 .child(
104 pill("call-lock-unlock", "Unlock", false)
105 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_lock(false, cx))),
106 )
107 .into_any_element(),
108 )
109 }
110
111 fn people_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
112 let mut popup = popup.min_w(px(MENU_WIDTH));
113 if model.kind == CallKind::Direct {
114 popup = popup.item(add_people_item(app, model));
115 }
116 if !model.organizes_meeting() {
117 return popup;
118 }
119 let capability = model.capability;
120 let (mute_app, lock_app, mic_app, camera_app, options_app) =
121 (app.clone(), app.clone(), app.clone(), app.clone(), app.clone());
122 popup
123 .item(
124 PopupMenuItem::new("Mute all")
125 .icon(IconName::MicOff)
126 .on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
127 )
128 .item(
129 PopupMenuItem::new(if capability.locked { "Unlock meeting" } else { "Lock meeting" })
130 .icon(if capability.locked { IconName::LockOpen } else { IconName::Lock })
131 .on_click(move |_, _, cx| {
132 lock_app.update(cx, |state, cx| state.set_call_lock(!capability.locked, cx))
133 }),
134 )
135 .item(
136 PopupMenuItem::new(if capability.attendee_mic_off {
137 "Allow mic for attendees"
138 } else {
139 "Disable mic for attendees"
140 })
141 .icon(IconName::MicOff)
142 .on_click(move |_, _, cx| {
143 mic_app.update(cx, |state, cx| {
144 state.set_call_attendee_restrictions(
145 !capability.attendee_mic_off,
146 capability.attendee_camera_off,
147 cx,
148 )
149 })
150 }),
151 )
152 .item(
153 PopupMenuItem::new(if capability.attendee_camera_off {
154 "Allow camera for attendees"
155 } else {
156 "Disable camera for attendees"
157 })
158 .icon(IconName::VideoOff)
159 .on_click(move |_, _, cx| {
160 camera_app.update(cx, |state, cx| {
161 state.set_call_attendee_restrictions(
162 capability.attendee_mic_off,
163 !capability.attendee_camera_off,
164 cx,
165 )
166 })
167 }),
168 )
169 .separator()
170 .item(
171 PopupMenuItem::new("Meeting options...")
172 .icon(IconName::Settings)
173 .on_click(move |_, _, cx| {
174 options_app.update(cx, |state, cx| state.open_meeting_options(cx))
175 }),
176 )
177 }
178
179 pub fn add_people_item(app: &Entity<AppState>, model: &CallModel) -> PopupMenuItem {
180 let app = app.clone();
181 PopupMenuItem::new("Add people")
182 .icon(IconName::UserPlus)
183 .disabled(!model.can_invite())
184 .on_click(move |_, window, cx| open_invite_picker(&app, window, cx))
185 }
186
187 fn has_people_menu(model: &CallModel) -> bool {
188 model.kind == CallKind::Direct || model.organizes_meeting()
189 }
190
191 fn panel_header(app: &Entity<AppState>, model: &CallModel, count: usize) -> Div {
192 let (invite_app, menu_app, close_app) = (app.clone(), app.clone(), app.clone());
193 let menu_model = model.clone();
194 h_flex()
195 .w_full()
196 .h(px(HEADER_HEIGHT))
197 .flex_none()
198 .pl(px(20.))
199 .pr(px(12.))
200 .gap(px(8.))
201 .items_center()
202 .child(
203 div()
204 .flex_1()
205 .min_w_0()
206 .truncate()
207 .text_size(px(15.))
208 .font_weight(FontWeight::SEMIBOLD)
209 .child(format!("People ({count})")),
210 )
211 .when(model.can_invite(), |header| {
212 header.child(
213 Button::new("call-people-invite")
214 .label("Invite")
215 .icon(IconName::UserPlus)
216 .xsmall()
217 .on_click(move |_, window, cx| open_invite_picker(&invite_app, window, cx)),
218 )
219 })
220 .when(has_people_menu(model), |header| {
221 header.child(
222 Button::new("call-people-more")
223 .icon(IconName::Ellipsis)
224 .ghost()
225 .xsmall()
226 .tooltip("More")
227 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
228 people_menu(popup, &menu_app, &menu_model)
229 }),
230 )
231 })
232 .child(
233 div()
234 .id("call-people-close")
235 .size(px(28.))
236 .flex()
237 .flex_none()
238 .items_center()
239 .justify_center()
240 .rounded(px(7.))
241 .cursor_pointer()
242 .hover(|button| button.bg(theme::row_hover()))
243 .tooltip(|window, cx| Tooltip::new("Close the people list").build(window, cx))
244 .child(icon(IconName::Close, 14., theme::text_muted()))
245 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.toggle_call_people(cx))),
246 )
247 }
248
249 fn section_header(title: String, action: Option<AnyElement>) -> Div {
250 h_flex()
251 .w_full()
252 .h(px(SECTION_HEIGHT))
253 .flex_none()
254 .px(px(20.))
255 .items_center()
256 .justify_between()
257 .text_size(px(12.))
258 .font_weight(FontWeight::SEMIBOLD)
259 .text_color(theme::text_muted())
260 .child(title)
261 .children(action)
262 }
263
264 fn hand_badge(position: usize) -> Div {
265 h_flex()
266 .h(px(20.))
267 .px(px(6.))
268 .gap(px(3.))
269 .flex_none()
270 .items_center()
271 .rounded_full()
272 .bg(theme::amber())
273 .text_color(dark_text())
274 .text_size(px(11.))
275 .font_weight(FontWeight::SEMIBOLD)
276 .child(icon(IconName::Hand, 11., dark_text()))
277 .child(position.to_string())
278 }
279
280 fn mic_icon(row: &PersonRow) -> impl IntoElement {
281 if row.mic_blocked {
282 icon(IconName::MicOff, STATE_ICON, theme::red())
283 } else if row.muted {
284 icon(IconName::MicOff, STATE_ICON, theme::text_muted())
285 } else {
286 icon(IconName::Mic, STATE_ICON, theme::text())
287 }
288 }
289
290 fn camera_icon(row: &PersonRow) -> impl IntoElement {
291 if row.camera_blocked {
292 icon(IconName::VideoOff, STATE_ICON, theme::red())
293 } else if row.camera_on {
294 icon(IconName::Video, STATE_ICON, theme::text())
295 } else {
296 icon(IconName::VideoOff, STATE_ICON, theme::text_muted())
297 }
298 }
299
300 fn person_row(
301 app: &Entity<AppState>,
302 state: &AppState,
303 model: &CallModel,
304 section: &'static str,
305 row: &PersonRow,
306 ) -> AnyElement {
307 let group = SharedString::from(format!("call-people-{section}-{}", row.mri));
308 let user_id = row
309 .user_id
310 .clone()
311 .or_else(|| {
312 row.own
313 .then(|| state.directory.me.as_ref().map(|me| me.user_id.clone()))
314 .flatten()
315 });
316 let subtitle = if row.ringing { Some("Ringing") } else { row.label };
317 let (more_app, more_model, more_mri, more_name) =
318 (app.clone(), model.clone(), row.mri.clone(), row.name.clone());
319 h_flex()
320 .id(SharedString::from(format!("call-people-row-{section}-{}", row.mri)))
321 .group(group.clone())
322 .w_full()
323 .h(px(ROW_HEIGHT))
324 .flex_none()
325 .px(px(20.))
326 .gap(px(8.))
327 .items_center()
328 .hover(|row| row.bg(theme::row_hover()))
329 .child(person_avatar(&state.directory, user_id.as_deref(), &row.name, AVATAR_SIZE))
330 .child(
331 v_flex()
332 .flex_1()
333 .min_w_0()
334 .child(
335 div()
336 .truncate()
337 .text_size(px(13.))
338 .font_weight(FontWeight::SEMIBOLD)
339 .child(truncated(&row.name, NAME_LIMIT)),
340 )
341 .children(subtitle.map(|text| {
342 div()
343 .truncate()
344 .text_size(px(11.))
345 .text_color(theme::text_muted())
346 .child(text)
347 })),
348 )
349 .children(row.hand.map(hand_badge))
350 .child(mic_icon(row))
351 .child(camera_icon(row))
352 .child(
353 div()
354 .size(px(MORE_SIZE))
355 .flex_none()
356 .when(!row.own, |slot| {
357 slot.opacity(0.)
358 .group_hover(group, |slot| slot.opacity(1.))
359 .child(
360 Button::new(SharedString::from(format!(
361 "call-people-more-{section}-{}",
362 row.mri
363 )))
364 .icon(IconName::Ellipsis)
365 .ghost()
366 .xsmall()
367 .size(px(MORE_SIZE))
368 .tooltip("More")
369 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
370 tile_menu(popup, &more_app, &more_model, &more_mri, &more_name, false)
371 }),
372 )
373 }),
374 )
375 .into_any_element()
376 }
377
378 fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSections) -> Option<Div> {
379 if sections.lobby.is_empty() {
380 return None;
381 }
382 let admit_all_app = app.clone();
383 let action = Button::new("call-people-admit-all")
384 .label("Admit all")
385 .ghost()
386 .xsmall()
387 .on_click(move |_, _, cx| admit_all_app.update(cx, |state, cx| state.admit_all_call_guests(cx)))
388 .into_any_element();
389 Some(
390 v_flex()
391 .w_full()
392 .child(section_header(format!("Waiting in lobby ({})", sections.lobby.len()), Some(action)))
393 .children(sections.lobby.iter().map(|guest| {
394 let (admit_app, deny_app) = (app.clone(), app.clone());
395 let (admit_mri, deny_mri) = (guest.mri.clone(), guest.mri.clone());
396 h_flex()
397 .id(SharedString::from(format!("call-people-lobby-{}", guest.mri)))
398 .w_full()
399 .h(px(ROW_HEIGHT))
400 .flex_none()
401 .px(px(20.))
402 .gap(px(8.))
403 .items_center()
404 .child(person_avatar(&state.directory, guest.user_id.as_deref(), &guest.name, AVATAR_SIZE))
405 .child(
406 div()
407 .flex_1()
408 .min_w_0()
409 .truncate()
410 .text_size(px(13.))
411 .font_weight(FontWeight::SEMIBOLD)
412 .child(truncated(&guest.name, NAME_LIMIT)),
413 )
414 .child(
415 Button::new(SharedString::from(format!("call-people-admit-{}", guest.mri)))
416 .label("Admit")
417 .xsmall()
418 .on_click(move |_, _, cx| {
419 admit_app.update(cx, |state, cx| state.admit_call_guest(admit_mri.clone(), cx))
420 }),
421 )
422 .child(
423 Button::new(SharedString::from(format!("call-people-deny-{}", guest.mri)))
424 .label("Deny")
425 .ghost()
426 .xsmall()
427 .on_click(move |_, _, cx| {
428 deny_app.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
429 }),
430 )
431 })),
432 )
433 }
434
435 pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
436 call.people_open.then_some(())?;
437 let model = &call.model;
438 let sections = people_sections(model);
439 let lower_all = model.can_lower_hands().then(|| {
440 let app = app.clone();
441 Button::new("call-people-lower-all")
442 .label("Lower all")
443 .ghost()
444 .xsmall()
445 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.lower_all_call_hands(cx)))
446 .into_any_element()
447 });
448 let body = v_flex()
449 .id("call-people-list")
450 .flex_1()
451 .min_h_0()
452 .w_full()
453 .overflow_y_scroll()
454 .pb(px(12.))
455 .children(model.can_admit().then(|| lobby_section(app, state, &sections)).flatten())
456 .when(!sections.hands.is_empty(), |list| {
457 list.child(section_header(format!("Raised hands ({})", sections.hands.len()), lower_all))
458 .children(
459 sections
460 .hands
461 .iter()
462 .map(|row| person_row(app, state, model, "hands", row)),
463 )
464 })
465 .children(sections.groups.iter().map(|group| {
466 v_flex()
467 .w_full()
468 .child(section_header(format!("{} ({})", group.title, group.rows.len()), None))
469 .children(group.rows.iter().map(|row| person_row(app, state, model, "group", row)))
470 }));
471 Some(
472 v_flex()
473 .id("call-people-panel")
474 .debug_selector(|| "shell/islands/main/call-people".into())
475 .w(px(CHAT_PANEL_WIDTH))
476 .h_full()
477 .flex_shrink(1.)
478 .min_w_0()
479 .rounded(px(10.))
480 .overflow_hidden()
481 .bg(theme::surface())
482 .child(panel_header(app, model, sections.count))
483 .child(body)
484 .into_any_element(),
485 )
486 }
487
488 fn choice_label(choices: &[(&str, &str)], value: &str) -> String {
489 choices
490 .iter()
491 .find(|(wire, _)| *wire == value)
492 .map_or_else(|| value.to_owned(), |(_, label)| (*label).to_owned())
493 }
494
495 fn choice_dropdown(
496 id: &'static str,
497 app: &Entity<AppState>,
498 choices: &'static [(&'static str, &'static str)],
499 current: &str,
500 edit: fn(&mut MeetingOptions, &str),
501 ) -> AnyElement {
502 let app = app.clone();
503 let current = current.to_owned();
504 Button::new(id)
505 .label(choice_label(choices, &current))
506 .icon(IconName::ChevronDown)
507 .ghost()
508 .h(px(FIELD_HEIGHT))
509 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
510 let mut popup = popup.min_w(px(DROPDOWN_WIDTH));
511 if !choices.iter().any(|(wire, _)| *wire == current) {
512 popup = popup.item(PopupMenuItem::new(current.clone()).checked(true));
513 }
514 for (wire, label) in choices {
515 let app = app.clone();
516 popup = popup.item(PopupMenuItem::new(*label).checked(*wire == current).on_click(
517 move |_, _, cx| {
518 app.update(cx, |state, cx| {
519 state.edit_meeting_options(|options| edit(options, wire), cx)
520 })
521 },
522 ));
523 }
524 popup
525 })
526 .into_any_element()
527 }
528
529 fn switch_field(
530 id: &'static str,
531 app: &Entity<AppState>,
532 on: bool,
533 edit: fn(&mut MeetingOptions, bool),
534 ) -> AnyElement {
535 let app = app.clone();
536 Switch::new(id)
537 .checked(on)
538 .on_click(move |checked, _, cx| {
539 let checked = *checked;
540 app.update(cx, |state, cx| {
541 state.edit_meeting_options(|options| edit(options, checked), cx)
542 })
543 })
544 .into_any_element()
545 }
546
547 fn option_row(label: &'static str, control: AnyElement) -> Div {
548 h_flex()
549 .w_full()
550 .min_h(px(FIELD_HEIGHT))
551 .gap(px(12.))
552 .items_center()
553 .justify_between()
554 .child(div().flex_1().min_w_0().text_size(px(14.)).child(label))
555 .child(control)
556 }
557
558 fn options_fields(app: &Entity<AppState>, options: &MeetingOptions) -> Div {
559 use calling::meeting_options::{BYPASS_CHOICES, CHAT_CHOICES, PRESENTER_CHOICES};
560 v_flex()
561 .w_full()
562 .gap(px(6.))
563 .child(option_row(
564 "Who can bypass the lobby",
565 choice_dropdown("options-bypass", app, &BYPASS_CHOICES, &options.bypass_lobby, |options, value| {
566 options.bypass_lobby = value.to_owned()
567 }),
568 ))
569 .child(option_row(
570 "Who can present",
571 choice_dropdown("options-present", app, &PRESENTER_CHOICES, &options.presenters, |options, value| {
572 options.presenters = value.to_owned()
573 }),
574 ))
575 .child(option_row(
576 "Allow mic for attendees",
577 switch_field("options-mic", app, options.attendee_mic, |options, on| options.attendee_mic = on),
578 ))
579 .child(option_row(
580 "Allow camera for attendees",
581 switch_field("options-camera", app, options.attendee_camera, |options, on| {
582 options.attendee_camera = on
583 }),
584 ))
585 .child(option_row(
586 "Meeting chat",
587 choice_dropdown("options-chat", app, &CHAT_CHOICES, &options.meeting_chat, |options, value| {
588 options.meeting_chat = value.to_owned()
589 }),
590 ))
591 .child(option_row(
592 "Allow reactions",
593 switch_field("options-reactions", app, options.reactions, |options, on| options.reactions = on),
594 ))
595 .child(option_row(
596 "Record automatically",
597 switch_field("options-record", app, options.record_automatically, |options, on| {
598 options.record_automatically = on
599 }),
600 ))
601 }
602
603 fn dialog_body(app: &Entity<AppState>, dialog: &OptionsDialog) -> Div {
604 let body = v_flex().w_full().gap(px(12.));
605 let body = match &dialog.draft {
606 Some(draft) => body.child(options_fields(app, draft)),
607 None if dialog.is_loading() => body.child(
608 div()
609 .text_size(px(13.))
610 .text_color(theme::text_muted())
611 .child("Loading the meeting options..."),
612 ),
613 None => body,
614 };
615 body.children(dialog.error.as_ref().map(|error| {
616 div()
617 .id("options-error")
618 .w_full()
619 .text_size(px(13.))
620 .text_color(theme::red())
621 .child(error.clone())
622 }))
623 }
624
625 pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyElement> {
626 let dialog = call.options_dialog.as_ref()?;
627 let (close_app, cancel_app, save_app) = (app.clone(), app.clone(), app.clone());
628 let can_save = dialog.can_save();
629 let save = Button::new("options-save")
630 .label(if dialog.saving { "Saving..." } else { "Save" })
631 .when(!can_save, |button| button.opacity(0.4))
632 .on_click(move |_, _, cx| {
633 if can_save {
634 save_app.update(cx, |state, cx| state.save_meeting_options(cx))
635 }
636 });
637 Some(
638 div()
639 .id("options-layer")
640 .absolute()
641 .top_0()
642 .left_0()
643 .size_full()
644 .flex()
645 .items_center()
646 .justify_center()
647 .child(
648 div()
649 .id("options-backdrop")
650 .absolute()
651 .top_0()
652 .left_0()
653 .size_full()
654 .bg(black().opacity(DIALOG_BACKDROP))
655 .occlude()
656 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.close_meeting_options(cx))),
657 )
658 .child(
659 v_flex()
660 .id("options-card")
661 .w(px(DIALOG_WIDTH))
662 .max_w(relative(1.))
663 .p(px(16.))
664 .gap(px(12.))
665 .rounded(px(12.))
666 .bg(theme::background())
667 .border_1()
668 .border_color(theme::border_strong())
669 .text_color(theme::text())
670 .shadow_lg()
671 .occlude()
672 .child(
673 div()
674 .text_size(px(15.))
675 .font_weight(FontWeight::SEMIBOLD)
676 .child("Meeting options"),
677 )
678 .child(dialog_body(app, dialog))
679 .child(
680 h_flex()
681 .w_full()
682 .justify_end()
683 .gap(px(8.))
684 .child(
685 Button::new("options-cancel")
686 .label("Cancel")
687 .ghost()
688 .on_click(move |_, _, cx| {
689 cancel_app.update(cx, |state, cx| state.close_meeting_options(cx))
690 }),
691 )
692 .child(save),
693 ),
694 )
695 .into_any_element(),
696 )
697 }
@@ -0,0 +1,697 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::component::{
3 Sizable as _,
4 button::{Button, ButtonVariants as _},
5 h_flex,
6 menu::{DropdownMenu as _, PopupMenu, PopupMenuItem},
7 switch::Switch,
8 tooltip::Tooltip,
9 v_flex,
10};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13
14use super::avatar::person_avatar;
15use super::call_extras::open_invite_picker;
16use super::call_organizer::{pill, tile_menu};
17use super::call_view::{BANNER_HEIGHT, CHAT_PANEL_WIDTH, MENU_WIDTH, round_control};
18use super::widgets::{Corner, corner_badge, count_badge, icon};
19use crate::app_state::AppState;
20use crate::call::{
21 ActiveCall, CallKind, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,
22};
23use crate::notice::truncated;
24use crate::theme;
25use calling::MeetingOptions;
26
27const HEADER_HEIGHT: f32 = 48.;
28const ROW_HEIGHT: f32 = 44.;
29const AVATAR_SIZE: f32 = 28.;
30const MORE_SIZE: f32 = 24.;
31const SECTION_HEIGHT: f32 = 32.;
32const NAME_LIMIT: usize = 26;
33const STATE_ICON: f32 = 15.;
34const DIALOG_WIDTH: f32 = 460.;
35const DIALOG_BACKDROP: f32 = 0.55;
36const FIELD_HEIGHT: f32 = 36.;
37const DROPDOWN_WIDTH: f32 = 210.;
38
39fn dark_text() -> Hsla {
40 hsla(0., 0., 0.08, 1.)
41}
42
43pub fn people_button(app: &Entity<AppState>, open: bool, raised_hands: usize) -> Stateful<Div> {
44 let app = app.clone();
45 let (background, foreground) = if open {
46 (theme::accent(), theme::on_accent())
47 } else {
48 (theme::surface_raised(), theme::text())
49 };
50 round_control("call-people", IconName::Users, background, foreground)
51 .relative()
52 .tooltip(move |window, cx| {
53 Tooltip::new(if open { "Close the people list" } else { "Show people" }).build(window, cx)
54 })
55 .when(raised_hands > 0, |button| {
56 button.child(
57 corner_badge(Corner::TopRight, 4.).child(count_badge(raised_hands as u32, false)),
58 )
59 })
60 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_people(cx)))
61}
62
63pub fn lock_chip(model: &CallModel) -> Option<AnyElement> {
64 model.capability.locked.then(|| {
65 h_flex()
66 .id("call-lock-chip")
67 .h(px(24.))
68 .px(px(8.))
69 .gap(px(4.))
70 .flex_none()
71 .items_center()
72 .rounded_full()
73 .bg(theme::amber())
74 .text_color(dark_text())
75 .text_size(px(12.))
76 .font_weight(FontWeight::SEMIBOLD)
77 .child(icon(IconName::Lock, 13., dark_text()))
78 .child("Locked")
79 .into_any_element()
80 })
81}
82
83pub fn lock_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
84 if !model.capability.locked || !model.organizes_meeting() {
85 return None;
86 }
87 let app = app.clone();
88 Some(
89 h_flex()
90 .id("call-lock-banner")
91 .w_full()
92 .h(px(BANNER_HEIGHT))
93 .flex_none()
94 .px(px(20.))
95 .gap(px(12.))
96 .items_center()
97 .justify_center()
98 .bg(theme::surface_raised())
99 .text_color(theme::text())
100 .text_size(px(13.))
101 .font_weight(FontWeight::SEMIBOLD)
102 .child("The meeting is locked. Nobody new can join.")
103 .child(
104 pill("call-lock-unlock", "Unlock", false)
105 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_lock(false, cx))),
106 )
107 .into_any_element(),
108 )
109}
110
111fn people_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
112 let mut popup = popup.min_w(px(MENU_WIDTH));
113 if model.kind == CallKind::Direct {
114 popup = popup.item(add_people_item(app, model));
115 }
116 if !model.organizes_meeting() {
117 return popup;
118 }
119 let capability = model.capability;
120 let (mute_app, lock_app, mic_app, camera_app, options_app) =
121 (app.clone(), app.clone(), app.clone(), app.clone(), app.clone());
122 popup
123 .item(
124 PopupMenuItem::new("Mute all")
125 .icon(IconName::MicOff)
126 .on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
127 )
128 .item(
129 PopupMenuItem::new(if capability.locked { "Unlock meeting" } else { "Lock meeting" })
130 .icon(if capability.locked { IconName::LockOpen } else { IconName::Lock })
131 .on_click(move |_, _, cx| {
132 lock_app.update(cx, |state, cx| state.set_call_lock(!capability.locked, cx))
133 }),
134 )
135 .item(
136 PopupMenuItem::new(if capability.attendee_mic_off {
137 "Allow mic for attendees"
138 } else {
139 "Disable mic for attendees"
140 })
141 .icon(IconName::MicOff)
142 .on_click(move |_, _, cx| {
143 mic_app.update(cx, |state, cx| {
144 state.set_call_attendee_restrictions(
145 !capability.attendee_mic_off,
146 capability.attendee_camera_off,
147 cx,
148 )
149 })
150 }),
151 )
152 .item(
153 PopupMenuItem::new(if capability.attendee_camera_off {
154 "Allow camera for attendees"
155 } else {
156 "Disable camera for attendees"
157 })
158 .icon(IconName::VideoOff)
159 .on_click(move |_, _, cx| {
160 camera_app.update(cx, |state, cx| {
161 state.set_call_attendee_restrictions(
162 capability.attendee_mic_off,
163 !capability.attendee_camera_off,
164 cx,
165 )
166 })
167 }),
168 )
169 .separator()
170 .item(
171 PopupMenuItem::new("Meeting options...")
172 .icon(IconName::Settings)
173 .on_click(move |_, _, cx| {
174 options_app.update(cx, |state, cx| state.open_meeting_options(cx))
175 }),
176 )
177}
178
179pub fn add_people_item(app: &Entity<AppState>, model: &CallModel) -> PopupMenuItem {
180 let app = app.clone();
181 PopupMenuItem::new("Add people")
182 .icon(IconName::UserPlus)
183 .disabled(!model.can_invite())
184 .on_click(move |_, window, cx| open_invite_picker(&app, window, cx))
185}
186
187fn has_people_menu(model: &CallModel) -> bool {
188 model.kind == CallKind::Direct || model.organizes_meeting()
189}
190
191fn panel_header(app: &Entity<AppState>, model: &CallModel, count: usize) -> Div {
192 let (invite_app, menu_app, close_app) = (app.clone(), app.clone(), app.clone());
193 let menu_model = model.clone();
194 h_flex()
195 .w_full()
196 .h(px(HEADER_HEIGHT))
197 .flex_none()
198 .pl(px(20.))
199 .pr(px(12.))
200 .gap(px(8.))
201 .items_center()
202 .child(
203 div()
204 .flex_1()
205 .min_w_0()
206 .truncate()
207 .text_size(px(15.))
208 .font_weight(FontWeight::SEMIBOLD)
209 .child(format!("People ({count})")),
210 )
211 .when(model.can_invite(), |header| {
212 header.child(
213 Button::new("call-people-invite")
214 .label("Invite")
215 .icon(IconName::UserPlus)
216 .xsmall()
217 .on_click(move |_, window, cx| open_invite_picker(&invite_app, window, cx)),
218 )
219 })
220 .when(has_people_menu(model), |header| {
221 header.child(
222 Button::new("call-people-more")
223 .icon(IconName::Ellipsis)
224 .ghost()
225 .xsmall()
226 .tooltip("More")
227 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
228 people_menu(popup, &menu_app, &menu_model)
229 }),
230 )
231 })
232 .child(
233 div()
234 .id("call-people-close")
235 .size(px(28.))
236 .flex()
237 .flex_none()
238 .items_center()
239 .justify_center()
240 .rounded(px(7.))
241 .cursor_pointer()
242 .hover(|button| button.bg(theme::row_hover()))
243 .tooltip(|window, cx| Tooltip::new("Close the people list").build(window, cx))
244 .child(icon(IconName::Close, 14., theme::text_muted()))
245 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.toggle_call_people(cx))),
246 )
247}
248
249fn section_header(title: String, action: Option<AnyElement>) -> Div {
250 h_flex()
251 .w_full()
252 .h(px(SECTION_HEIGHT))
253 .flex_none()
254 .px(px(20.))
255 .items_center()
256 .justify_between()
257 .text_size(px(12.))
258 .font_weight(FontWeight::SEMIBOLD)
259 .text_color(theme::text_muted())
260 .child(title)
261 .children(action)
262}
263
264fn hand_badge(position: usize) -> Div {
265 h_flex()
266 .h(px(20.))
267 .px(px(6.))
268 .gap(px(3.))
269 .flex_none()
270 .items_center()
271 .rounded_full()
272 .bg(theme::amber())
273 .text_color(dark_text())
274 .text_size(px(11.))
275 .font_weight(FontWeight::SEMIBOLD)
276 .child(icon(IconName::Hand, 11., dark_text()))
277 .child(position.to_string())
278}
279
280fn mic_icon(row: &PersonRow) -> impl IntoElement {
281 if row.mic_blocked {
282 icon(IconName::MicOff, STATE_ICON, theme::red())
283 } else if row.muted {
284 icon(IconName::MicOff, STATE_ICON, theme::text_muted())
285 } else {
286 icon(IconName::Mic, STATE_ICON, theme::text())
287 }
288}
289
290fn camera_icon(row: &PersonRow) -> impl IntoElement {
291 if row.camera_blocked {
292 icon(IconName::VideoOff, STATE_ICON, theme::red())
293 } else if row.camera_on {
294 icon(IconName::Video, STATE_ICON, theme::text())
295 } else {
296 icon(IconName::VideoOff, STATE_ICON, theme::text_muted())
297 }
298}
299
300fn person_row(
301 app: &Entity<AppState>,
302 state: &AppState,
303 model: &CallModel,
304 section: &'static str,
305 row: &PersonRow,
306) -> AnyElement {
307 let group = SharedString::from(format!("call-people-{section}-{}", row.mri));
308 let user_id = row
309 .user_id
310 .clone()
311 .or_else(|| {
312 row.own
313 .then(|| state.directory.me.as_ref().map(|me| me.user_id.clone()))
314 .flatten()
315 });
316 let subtitle = if row.ringing { Some("Ringing") } else { row.label };
317 let (more_app, more_model, more_mri, more_name) =
318 (app.clone(), model.clone(), row.mri.clone(), row.name.clone());
319 h_flex()
320 .id(SharedString::from(format!("call-people-row-{section}-{}", row.mri)))
321 .group(group.clone())
322 .w_full()
323 .h(px(ROW_HEIGHT))
324 .flex_none()
325 .px(px(20.))
326 .gap(px(8.))
327 .items_center()
328 .hover(|row| row.bg(theme::row_hover()))
329 .child(person_avatar(&state.directory, user_id.as_deref(), &row.name, AVATAR_SIZE))
330 .child(
331 v_flex()
332 .flex_1()
333 .min_w_0()
334 .child(
335 div()
336 .truncate()
337 .text_size(px(13.))
338 .font_weight(FontWeight::SEMIBOLD)
339 .child(truncated(&row.name, NAME_LIMIT)),
340 )
341 .children(subtitle.map(|text| {
342 div()
343 .truncate()
344 .text_size(px(11.))
345 .text_color(theme::text_muted())
346 .child(text)
347 })),
348 )
349 .children(row.hand.map(hand_badge))
350 .child(mic_icon(row))
351 .child(camera_icon(row))
352 .child(
353 div()
354 .size(px(MORE_SIZE))
355 .flex_none()
356 .when(!row.own, |slot| {
357 slot.opacity(0.)
358 .group_hover(group, |slot| slot.opacity(1.))
359 .child(
360 Button::new(SharedString::from(format!(
361 "call-people-more-{section}-{}",
362 row.mri
363 )))
364 .icon(IconName::Ellipsis)
365 .ghost()
366 .xsmall()
367 .size(px(MORE_SIZE))
368 .tooltip("More")
369 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
370 tile_menu(popup, &more_app, &more_model, &more_mri, &more_name, false)
371 }),
372 )
373 }),
374 )
375 .into_any_element()
376}
377
378fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSections) -> Option<Div> {
379 if sections.lobby.is_empty() {
380 return None;
381 }
382 let admit_all_app = app.clone();
383 let action = Button::new("call-people-admit-all")
384 .label("Admit all")
385 .ghost()
386 .xsmall()
387 .on_click(move |_, _, cx| admit_all_app.update(cx, |state, cx| state.admit_all_call_guests(cx)))
388 .into_any_element();
389 Some(
390 v_flex()
391 .w_full()
392 .child(section_header(format!("Waiting in lobby ({})", sections.lobby.len()), Some(action)))
393 .children(sections.lobby.iter().map(|guest| {
394 let (admit_app, deny_app) = (app.clone(), app.clone());
395 let (admit_mri, deny_mri) = (guest.mri.clone(), guest.mri.clone());
396 h_flex()
397 .id(SharedString::from(format!("call-people-lobby-{}", guest.mri)))
398 .w_full()
399 .h(px(ROW_HEIGHT))
400 .flex_none()
401 .px(px(20.))
402 .gap(px(8.))
403 .items_center()
404 .child(person_avatar(&state.directory, guest.user_id.as_deref(), &guest.name, AVATAR_SIZE))
405 .child(
406 div()
407 .flex_1()
408 .min_w_0()
409 .truncate()
410 .text_size(px(13.))
411 .font_weight(FontWeight::SEMIBOLD)
412 .child(truncated(&guest.name, NAME_LIMIT)),
413 )
414 .child(
415 Button::new(SharedString::from(format!("call-people-admit-{}", guest.mri)))
416 .label("Admit")
417 .xsmall()
418 .on_click(move |_, _, cx| {
419 admit_app.update(cx, |state, cx| state.admit_call_guest(admit_mri.clone(), cx))
420 }),
421 )
422 .child(
423 Button::new(SharedString::from(format!("call-people-deny-{}", guest.mri)))
424 .label("Deny")
425 .ghost()
426 .xsmall()
427 .on_click(move |_, _, cx| {
428 deny_app.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
429 }),
430 )
431 })),
432 )
433}
434
435pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
436 call.people_open.then_some(())?;
437 let model = &call.model;
438 let sections = people_sections(model);
439 let lower_all = model.can_lower_hands().then(|| {
440 let app = app.clone();
441 Button::new("call-people-lower-all")
442 .label("Lower all")
443 .ghost()
444 .xsmall()
445 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.lower_all_call_hands(cx)))
446 .into_any_element()
447 });
448 let body = v_flex()
449 .id("call-people-list")
450 .flex_1()
451 .min_h_0()
452 .w_full()
453 .overflow_y_scroll()
454 .pb(px(12.))
455 .children(model.can_admit().then(|| lobby_section(app, state, &sections)).flatten())
456 .when(!sections.hands.is_empty(), |list| {
457 list.child(section_header(format!("Raised hands ({})", sections.hands.len()), lower_all))
458 .children(
459 sections
460 .hands
461 .iter()
462 .map(|row| person_row(app, state, model, "hands", row)),
463 )
464 })
465 .children(sections.groups.iter().map(|group| {
466 v_flex()
467 .w_full()
468 .child(section_header(format!("{} ({})", group.title, group.rows.len()), None))
469 .children(group.rows.iter().map(|row| person_row(app, state, model, "group", row)))
470 }));
471 Some(
472 v_flex()
473 .id("call-people-panel")
474 .debug_selector(|| "shell/islands/main/call-people".into())
475 .w(px(CHAT_PANEL_WIDTH))
476 .h_full()
477 .flex_shrink(1.)
478 .min_w_0()
479 .rounded(px(10.))
480 .overflow_hidden()
481 .bg(theme::surface())
482 .child(panel_header(app, model, sections.count))
483 .child(body)
484 .into_any_element(),
485 )
486}
487
488fn choice_label(choices: &[(&str, &str)], value: &str) -> String {
489 choices
490 .iter()
491 .find(|(wire, _)| *wire == value)
492 .map_or_else(|| value.to_owned(), |(_, label)| (*label).to_owned())
493}
494
495fn choice_dropdown(
496 id: &'static str,
497 app: &Entity<AppState>,
498 choices: &'static [(&'static str, &'static str)],
499 current: &str,
500 edit: fn(&mut MeetingOptions, &str),
501) -> AnyElement {
502 let app = app.clone();
503 let current = current.to_owned();
504 Button::new(id)
505 .label(choice_label(choices, &current))
506 .icon(IconName::ChevronDown)
507 .ghost()
508 .h(px(FIELD_HEIGHT))
509 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
510 let mut popup = popup.min_w(px(DROPDOWN_WIDTH));
511 if !choices.iter().any(|(wire, _)| *wire == current) {
512 popup = popup.item(PopupMenuItem::new(current.clone()).checked(true));
513 }
514 for (wire, label) in choices {
515 let app = app.clone();
516 popup = popup.item(PopupMenuItem::new(*label).checked(*wire == current).on_click(
517 move |_, _, cx| {
518 app.update(cx, |state, cx| {
519 state.edit_meeting_options(|options| edit(options, wire), cx)
520 })
521 },
522 ));
523 }
524 popup
525 })
526 .into_any_element()
527}
528
529fn switch_field(
530 id: &'static str,
531 app: &Entity<AppState>,
532 on: bool,
533 edit: fn(&mut MeetingOptions, bool),
534) -> AnyElement {
535 let app = app.clone();
536 Switch::new(id)
537 .checked(on)
538 .on_click(move |checked, _, cx| {
539 let checked = *checked;
540 app.update(cx, |state, cx| {
541 state.edit_meeting_options(|options| edit(options, checked), cx)
542 })
543 })
544 .into_any_element()
545}
546
547fn option_row(label: &'static str, control: AnyElement) -> Div {
548 h_flex()
549 .w_full()
550 .min_h(px(FIELD_HEIGHT))
551 .gap(px(12.))
552 .items_center()
553 .justify_between()
554 .child(div().flex_1().min_w_0().text_size(px(14.)).child(label))
555 .child(control)
556}
557
558fn options_fields(app: &Entity<AppState>, options: &MeetingOptions) -> Div {
559 use calling::meeting_options::{BYPASS_CHOICES, CHAT_CHOICES, PRESENTER_CHOICES};
560 v_flex()
561 .w_full()
562 .gap(px(6.))
563 .child(option_row(
564 "Who can bypass the lobby",
565 choice_dropdown("options-bypass", app, &BYPASS_CHOICES, &options.bypass_lobby, |options, value| {
566 options.bypass_lobby = value.to_owned()
567 }),
568 ))
569 .child(option_row(
570 "Who can present",
571 choice_dropdown("options-present", app, &PRESENTER_CHOICES, &options.presenters, |options, value| {
572 options.presenters = value.to_owned()
573 }),
574 ))
575 .child(option_row(
576 "Allow mic for attendees",
577 switch_field("options-mic", app, options.attendee_mic, |options, on| options.attendee_mic = on),
578 ))
579 .child(option_row(
580 "Allow camera for attendees",
581 switch_field("options-camera", app, options.attendee_camera, |options, on| {
582 options.attendee_camera = on
583 }),
584 ))
585 .child(option_row(
586 "Meeting chat",
587 choice_dropdown("options-chat", app, &CHAT_CHOICES, &options.meeting_chat, |options, value| {
588 options.meeting_chat = value.to_owned()
589 }),
590 ))
591 .child(option_row(
592 "Allow reactions",
593 switch_field("options-reactions", app, options.reactions, |options, on| options.reactions = on),
594 ))
595 .child(option_row(
596 "Record automatically",
597 switch_field("options-record", app, options.record_automatically, |options, on| {
598 options.record_automatically = on
599 }),
600 ))
601}
602
603fn dialog_body(app: &Entity<AppState>, dialog: &OptionsDialog) -> Div {
604 let body = v_flex().w_full().gap(px(12.));
605 let body = match &dialog.draft {
606 Some(draft) => body.child(options_fields(app, draft)),
607 None if dialog.is_loading() => body.child(
608 div()
609 .text_size(px(13.))
610 .text_color(theme::text_muted())
611 .child("Loading the meeting options..."),
612 ),
613 None => body,
614 };
615 body.children(dialog.error.as_ref().map(|error| {
616 div()
617 .id("options-error")
618 .w_full()
619 .text_size(px(13.))
620 .text_color(theme::red())
621 .child(error.clone())
622 }))
623}
624
625pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyElement> {
626 let dialog = call.options_dialog.as_ref()?;
627 let (close_app, cancel_app, save_app) = (app.clone(), app.clone(), app.clone());
628 let can_save = dialog.can_save();
629 let save = Button::new("options-save")
630 .label(if dialog.saving { "Saving..." } else { "Save" })
631 .when(!can_save, |button| button.opacity(0.4))
632 .on_click(move |_, _, cx| {
633 if can_save {
634 save_app.update(cx, |state, cx| state.save_meeting_options(cx))
635 }
636 });
637 Some(
638 div()
639 .id("options-layer")
640 .absolute()
641 .top_0()
642 .left_0()
643 .size_full()
644 .flex()
645 .items_center()
646 .justify_center()
647 .child(
648 div()
649 .id("options-backdrop")
650 .absolute()
651 .top_0()
652 .left_0()
653 .size_full()
654 .bg(black().opacity(DIALOG_BACKDROP))
655 .occlude()
656 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.close_meeting_options(cx))),
657 )
658 .child(
659 v_flex()
660 .id("options-card")
661 .w(px(DIALOG_WIDTH))
662 .max_w(relative(1.))
663 .p(px(16.))
664 .gap(px(12.))
665 .rounded(px(12.))
666 .bg(theme::background())
667 .border_1()
668 .border_color(theme::border_strong())
669 .text_color(theme::text())
670 .shadow_lg()
671 .occlude()
672 .child(
673 div()
674 .text_size(px(15.))
675 .font_weight(FontWeight::SEMIBOLD)
676 .child("Meeting options"),
677 )
678 .child(dialog_body(app, dialog))
679 .child(
680 h_flex()
681 .w_full()
682 .justify_end()
683 .gap(px(8.))
684 .child(
685 Button::new("options-cancel")
686 .label("Cancel")
687 .ghost()
688 .on_click(move |_, _, cx| {
689 cancel_app.update(cx, |state, cx| state.close_meeting_options(cx))
690 }),
691 )
692 .child(save),
693 ),
694 )
695 .into_any_element(),
696 )
697}
crates/app/src/views/call_view.rs +9 −1
@@ -26,6 +26,7 @@ use super::call_organizer::{
26 26 camera_menu_button, captions_hint_chip, captions_overlay, chevron_button, lobby_banner,
27 27 more_button, pin_chip, spotlight_chip, with_tile_menu,
28 28 };
29 use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
29 30 use super::call_stage::render_stage;
30 31 use super::call_view_menu::view_button;
31 32 use super::conversation::ConversationView;
@@ -66,7 +67,7 @@ pub const NO_WINDOWS_HINT: &str = "No windows found";
66 67 pub(super) const BANNER_HEIGHT: f32 = 40.;
67 68 const MAX_WINDOW_ITEMS: usize = 12;
68 69 pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
69 pub const CHAT_PANEL_WIDTH: f32 = 320.;
70 pub(super) const CHAT_PANEL_WIDTH: f32 = 320.;
70 71 const CHAT_HEADER_HEIGHT: f32 = 48.;
71 72 const REACTION_RISE: f32 = 24.;
72 73 const REACTION_FADE_FROM: f32 = 0.75;
@@ -1065,6 +1066,7 @@ pub fn render_call_view(
1065 1066 )
1066 1067 .children(health_indicator(model))
1067 1068 .children(recording_chip(model))
1069 .children(lock_chip(model))
1068 1070 .children(room_chip(model))
1069 1071 .child(div().flex_1())
1070 1072 .children(return_button(app, model));
@@ -1110,6 +1112,9 @@ pub fn render_call_view(
1110 1112 })
1111 1113 .child(view_button(app, model, fullscreen))
1112 1114 .children(more_button(app, model))
1115 .when(model.kind != CallKind::Test, |row| {
1116 row.child(people_button(app, call.people_open, model.raised_hands()))
1117 })
1113 1118 .when(call.chat_thread().is_some(), |row| {
1114 1119 row.child(chat_button(app, call.chat_open, state.call_chat_unread()))
1115 1120 })
@@ -1123,6 +1128,7 @@ pub fn render_call_view(
1123 1128 .flex_none()
1124 1129 .child(header)
1125 1130 .children(lobby_banner(app, model, call.lobby_list_open))
1131 .children(lock_banner(app, model))
1126 1132 .children(health_banner(app, model))
1127 1133 .children(sharing_banner(app, model, state.call_share_sound))
1128 1134 .children(consult_banner(app, state));
@@ -1159,6 +1165,7 @@ pub fn render_call_view(
1159 1165 .children(captions_hint_chip(model))
1160 1166 .children(push_to_talk_chip(call))
1161 1167 .children(state.transfer_picker.clone())
1168 .children(options_dialog(app, call))
1162 1169 .children(consent_overlay(app, model));
1163 1170 Some(
1164 1171 h_flex()
@@ -1171,6 +1178,7 @@ pub fn render_call_view(
1171 1178 .gap(px(ISLAND_GAP))
1172 1179 .child(column)
1173 1180 .children(chat.map(|chat| chat_panel(app, chat)))
1181 .children(people_panel(app, state, call))
1174 1182 .into_any_element(),
1175 1183 )
1176 1184 }
@@ -26,6 +26,7 @@ use super::call_organizer::{
26 camera_menu_button, captions_hint_chip, captions_overlay, chevron_button, lobby_banner,
26 camera_menu_button, captions_hint_chip, captions_overlay, chevron_button, lobby_banner,
27 more_button, pin_chip, spotlight_chip, with_tile_menu,
27 more_button, pin_chip, spotlight_chip, with_tile_menu,
28};
28};
29use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
29use super::call_stage::render_stage;
30use super::call_stage::render_stage;
30use super::call_view_menu::view_button;
31use super::call_view_menu::view_button;
31use super::conversation::ConversationView;
32use super::conversation::ConversationView;
@@ -66,7 +67,7 @@ pub const NO_WINDOWS_HINT: &str = "No windows found";
66pub(super) const BANNER_HEIGHT: f32 = 40.;
67pub(super) const BANNER_HEIGHT: f32 = 40.;
67const MAX_WINDOW_ITEMS: usize = 12;
68const MAX_WINDOW_ITEMS: usize = 12;
68pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
69pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
69pub const CHAT_PANEL_WIDTH: f32 = 320.;
70pub(super) const CHAT_PANEL_WIDTH: f32 = 320.;
70const CHAT_HEADER_HEIGHT: f32 = 48.;
71const CHAT_HEADER_HEIGHT: f32 = 48.;
71const REACTION_RISE: f32 = 24.;
72const REACTION_RISE: f32 = 24.;
72const REACTION_FADE_FROM: f32 = 0.75;
73const REACTION_FADE_FROM: f32 = 0.75;
@@ -1065,6 +1066,7 @@ pub fn render_call_view(
1065 )
1066 )
1066 .children(health_indicator(model))
1067 .children(health_indicator(model))
1067 .children(recording_chip(model))
1068 .children(recording_chip(model))
1069 .children(lock_chip(model))
1068 .children(room_chip(model))
1070 .children(room_chip(model))
1069 .child(div().flex_1())
1071 .child(div().flex_1())
1070 .children(return_button(app, model));
1072 .children(return_button(app, model));
@@ -1110,6 +1112,9 @@ pub fn render_call_view(
1110 })
1112 })
1111 .child(view_button(app, model, fullscreen))
1113 .child(view_button(app, model, fullscreen))
1112 .children(more_button(app, model))
1114 .children(more_button(app, model))
1115 .when(model.kind != CallKind::Test, |row| {
1116 row.child(people_button(app, call.people_open, model.raised_hands()))
1117 })
1113 .when(call.chat_thread().is_some(), |row| {
1118 .when(call.chat_thread().is_some(), |row| {
1114 row.child(chat_button(app, call.chat_open, state.call_chat_unread()))
1119 row.child(chat_button(app, call.chat_open, state.call_chat_unread()))
1115 })
1120 })
@@ -1123,6 +1128,7 @@ pub fn render_call_view(
1123 .flex_none()
1128 .flex_none()
1124 .child(header)
1129 .child(header)
1125 .children(lobby_banner(app, model, call.lobby_list_open))
1130 .children(lobby_banner(app, model, call.lobby_list_open))
1131 .children(lock_banner(app, model))
1126 .children(health_banner(app, model))
1132 .children(health_banner(app, model))
1127 .children(sharing_banner(app, model, state.call_share_sound))
1133 .children(sharing_banner(app, model, state.call_share_sound))
1128 .children(consult_banner(app, state));
1134 .children(consult_banner(app, state));
@@ -1159,6 +1165,7 @@ pub fn render_call_view(
1159 .children(captions_hint_chip(model))
1165 .children(captions_hint_chip(model))
1160 .children(push_to_talk_chip(call))
1166 .children(push_to_talk_chip(call))
1161 .children(state.transfer_picker.clone())
1167 .children(state.transfer_picker.clone())
1168 .children(options_dialog(app, call))
1162 .children(consent_overlay(app, model));
1169 .children(consent_overlay(app, model));
1163 Some(
1170 Some(
1164 h_flex()
1171 h_flex()
@@ -1171,6 +1178,7 @@ pub fn render_call_view(
1171 .gap(px(ISLAND_GAP))
1178 .gap(px(ISLAND_GAP))
1172 .child(column)
1179 .child(column)
1173 .children(chat.map(|chat| chat_panel(app, chat)))
1180 .children(chat.map(|chat| chat_panel(app, chat)))
1181 .children(people_panel(app, state, call))
1174 .into_any_element(),
1182 .into_any_element(),
1175 )
1183 )
1176}
1184}
crates/app/src/views/mod.rs +1 −0
@@ -10,6 +10,7 @@ pub mod call_layouts;
10 10 pub mod call_mini;
11 11 pub mod call_mini_window;
12 12 pub mod call_organizer;
13 pub mod call_people;
13 14 pub mod call_stage;
14 15 pub mod call_view;
15 16 pub mod call_view_menu;
@@ -10,6 +10,7 @@ pub mod call_layouts;
10pub mod call_mini;
10pub mod call_mini;
11pub mod call_mini_window;
11pub mod call_mini_window;
12pub mod call_organizer;
12pub mod call_organizer;
13pub mod call_people;
13pub mod call_stage;
14pub mod call_stage;
14pub mod call_view;
15pub mod call_view;
15pub mod call_view_menu;
16pub mod call_view_menu;
crates/app/src/views/transfer_picker.rs +22 −13
@@ -35,8 +35,15 @@ pub fn visible_candidates(
35 35 fuzzy::rank(query, candidates, MAX_RESULTS)
36 36 }
37 37
38 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
39 pub enum PickerMode {
40 Transfer,
41 Invite,
42 }
43
38 44 pub struct TransferPicker {
39 45 app: Entity<AppState>,
46 mode: PickerMode,
40 47 candidates: Vec<(String, TransferCandidate)>,
41 48 search: Entity<InputState>,
42 49 results: Vec<TransferCandidate>,
@@ -49,6 +56,7 @@ impl TransferPicker {
49 56 pub fn new(
50 57 app: Entity<AppState>,
51 58 candidates: Vec<TransferCandidate>,
59 mode: PickerMode,
52 60 window: &mut Window,
53 61 cx: &mut Context<Self>,
54 62 ) -> Self {
@@ -62,6 +70,7 @@ impl TransferPicker {
62 70 let results = visible_candidates(&candidates, "");
63 71 TransferPicker {
64 72 app,
73 mode,
65 74 candidates,
66 75 search,
67 76 results,
@@ -221,18 +230,15 @@ impl Render for TransferPicker {
221 230 .label("Cancel")
222 231 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
223 232 )
224 .child(self.action(
225 "transfer-consult",
226 "Consult first",
227 false,
228 AppState::start_consult,
229 ))
230 .child(self.action(
231 "transfer-now",
232 "Transfer now",
233 true,
234 AppState::transfer_call_blind,
235 ));
233 .children(match self.mode {
234 PickerMode::Transfer => vec![
235 self.action("transfer-consult", "Consult first", false, AppState::start_consult),
236 self.action("transfer-now", "Transfer now", true, AppState::transfer_call_blind),
237 ],
238 PickerMode::Invite => {
239 vec![self.action("transfer-invite", "Invite", true, AppState::invite_call_person)]
240 }
241 });
236 242 div()
237 243 .id("transfer-layer")
238 244 .absolute()
@@ -278,7 +284,10 @@ impl Render for TransferPicker {
278 284 .flex_1()
279 285 .text_size(px(15.))
280 286 .font_weight(FontWeight::SEMIBOLD)
281 .child("Transfer call"),
287 .child(match self.mode {
288 PickerMode::Transfer => "Transfer call",
289 PickerMode::Invite => "Invite people",
290 }),
282 291 )
283 292 .child(
284 293 div()
@@ -35,8 +35,15 @@ pub fn visible_candidates(
35 fuzzy::rank(query, candidates, MAX_RESULTS)
35 fuzzy::rank(query, candidates, MAX_RESULTS)
36}
36}
37
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum PickerMode {
40 Transfer,
41 Invite,
42}
43
38pub struct TransferPicker {
44pub struct TransferPicker {
39 app: Entity<AppState>,
45 app: Entity<AppState>,
46 mode: PickerMode,
40 candidates: Vec<(String, TransferCandidate)>,
47 candidates: Vec<(String, TransferCandidate)>,
41 search: Entity<InputState>,
48 search: Entity<InputState>,
42 results: Vec<TransferCandidate>,
49 results: Vec<TransferCandidate>,
@@ -49,6 +56,7 @@ impl TransferPicker {
49 pub fn new(
56 pub fn new(
50 app: Entity<AppState>,
57 app: Entity<AppState>,
51 candidates: Vec<TransferCandidate>,
58 candidates: Vec<TransferCandidate>,
59 mode: PickerMode,
52 window: &mut Window,
60 window: &mut Window,
53 cx: &mut Context<Self>,
61 cx: &mut Context<Self>,
54 ) -> Self {
62 ) -> Self {
@@ -62,6 +70,7 @@ impl TransferPicker {
62 let results = visible_candidates(&candidates, "");
70 let results = visible_candidates(&candidates, "");
63 TransferPicker {
71 TransferPicker {
64 app,
72 app,
73 mode,
65 candidates,
74 candidates,
66 search,
75 search,
67 results,
76 results,
@@ -221,18 +230,15 @@ impl Render for TransferPicker {
221 .label("Cancel")
230 .label("Cancel")
222 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
231 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
223 )
232 )
224 .child(self.action(
233 .children(match self.mode {
225 "transfer-consult",
234 PickerMode::Transfer => vec![
226 "Consult first",
235 self.action("transfer-consult", "Consult first", false, AppState::start_consult),
227 false,
236 self.action("transfer-now", "Transfer now", true, AppState::transfer_call_blind),
228 AppState::start_consult,
237 ],
229 ))
238 PickerMode::Invite => {
230 .child(self.action(
239 vec![self.action("transfer-invite", "Invite", true, AppState::invite_call_person)]
231 "transfer-now",
240 }
232 "Transfer now",
241 });
233 true,
234 AppState::transfer_call_blind,
235 ));
236 div()
242 div()
237 .id("transfer-layer")
243 .id("transfer-layer")
238 .absolute()
244 .absolute()
@@ -278,7 +284,10 @@ impl Render for TransferPicker {
278 .flex_1()
284 .flex_1()
279 .text_size(px(15.))
285 .text_size(px(15.))
280 .font_weight(FontWeight::SEMIBOLD)
286 .font_weight(FontWeight::SEMIBOLD)
281 .child("Transfer call"),
287 .child(match self.mode {
288 PickerMode::Transfer => "Transfer call",
289 PickerMode::Invite => "Invite people",
290 }),
282 )
291 )
283 .child(
292 .child(
284 div()
293 div()
crates/calling/src/call.rs +77 −1
@@ -40,7 +40,8 @@ use crate::mute::{MuteCommand, MuteEffect};
40 40 use crate::push::CallNotification;
41 41 use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
42 42 use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath};
43 use crate::organizer::Target;
43 use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
44 use crate::meeting_options::{self, OptionWrite};
44 45 use crate::recording::{Consent, RecordingStatus};
45 46 use crate::roster::Roster;
46 47 use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
@@ -798,6 +799,7 @@ async fn drive(
798 799 let mut next: Option<NextPeer> = None;
799 800 let mut roster = Roster::default();
800 801 let mut lobby = false;
802 let mut capability = MeetingCapability::default();
801 803 let mut previous_packets = 0u64;
802 804 let mut ticks = 0u32;
803 805 let mut health_sampler = HealthSampler::default();
@@ -1055,6 +1057,9 @@ async fn drive(
1055 1057 control.send(CallUpdate::MeetingChat(thread.clone()));
1056 1058 meeting_chat = Some(thread);
1057 1059 }
1060 if capability.apply(&body) {
1061 control.send(CallUpdate::Capability(capability));
1062 }
1058 1063 let change = recording_status.apply(&body);
1059 1064 if let Some(on) = change.recording {
1060 1065 control.send(CallUpdate::Recording(on));
@@ -1430,6 +1435,70 @@ async fn drive(
1430 1435 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
1431 1436 report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline);
1432 1437 }
1438 Some(CallCommand::SetLock(locked)) => {
1439 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
1440 if result.is_ok() {
1441 capability.locked = locked;
1442 control.send(CallUpdate::Capability(capability));
1443 }
1444 report_organizer_result(result, "lock meeting", "Could not change the meeting lock", control, timeline);
1445 }
1446 Some(CallCommand::SetRole { mri, role }) => {
1447 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
1448 report_organizer_result(result, "change role", "Could not change that role", control, timeline);
1449 }
1450 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
1451 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
1452 let mut result = Ok(200);
1453 for step in modality_steps(modality, allowed, capability, &limits) {
1454 result = match step {
1455 StateStep::Publish(state_type) => remote.signaling.publish_attendee_state(&remote.conversation, &remote.participant, state_type, &mri).await,
1456 StateStep::Remove(state_id) => remote.signaling.lower_hands(&remote.conversation, &remote.participant, &[state_id]).await.map(|()| 200),
1457 };
1458 if result.is_err() {
1459 break;
1460 }
1461 }
1462 let notice = if modality == Modality::Mic { "Could not change that microphone setting" } else { "Could not change that camera setting" };
1463 report_organizer_result(result, "attendee modality", notice, control, timeline);
1464 }
1465 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
1466 let result = match &meeting_target {
1467 Some(target) => meeting_options::write(&inner.session, target, &OptionWrite::restrictions(mic_off, camera_off)).await.map(|()| 200),
1468 None => Err(Error::Signaling("no meeting coordinates for the options".into())),
1469 };
1470 if result.is_ok() {
1471 capability.attendee_mic_off = mic_off;
1472 capability.attendee_camera_off = camera_off;
1473 control.send(CallUpdate::Capability(capability));
1474 }
1475 report_organizer_result(result, "attendee restrictions", "Could not change the attendee settings", control, timeline);
1476 }
1477 Some(CallCommand::Invite { callees, group_thread }) => {
1478 let thread = group_thread.or_else(|| meeting_chat.clone());
1479 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
1480 report_organizer_result(result, "invite", "Could not invite that person", control, timeline);
1481 }
1482 Some(CallCommand::LoadMeetingOptions) => {
1483 let update = match &meeting_target {
1484 Some(target) => meeting_options::fetch(&inner.session, target).await.map_err(|error| error.to_string()),
1485 None => Err("This meeting has no options page".to_owned()),
1486 };
1487 control.send(CallUpdate::MeetingOptions(update));
1488 }
1489 Some(CallCommand::SaveMeetingOptions(writes)) => {
1490 let update = match &meeting_target {
1491 Some(target) => save_meeting_options(&inner.session, target, &writes).await,
1492 None => Err("This meeting has no options page".to_owned()),
1493 };
1494 if let Ok(options) = &update {
1495 let (mic_off, camera_off) = options.attendees_off();
1496 capability.attendee_mic_off = mic_off;
1497 capability.attendee_camera_off = camera_off;
1498 control.send(CallUpdate::Capability(capability));
1499 }
1500 control.send(CallUpdate::MeetingOptionsSaved(update));
1501 }
1433 1502 Some(CallCommand::Spotlight { mri }) => {
1434 1503 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
1435 1504 report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline);
@@ -1988,6 +2057,13 @@ async fn apply_background(choice: BackgroundChoice, local_video: &LocalVideo, co
1988 2057 }
1989 2058 }
1990 2059
2060 async fn save_meeting_options(session: &session::Session, target: &MeetingTarget, writes: &[OptionWrite]) -> std::result::Result<meeting_options::MeetingOptions, String> {
2061 for change in writes {
2062 meeting_options::write(session, target, change).await.map_err(|error| error.to_string())?;
2063 }
2064 meeting_options::fetch(session, target).await.map_err(|error| error.to_string())
2065 }
2066
1991 2067 fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
1992 2068 let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());
1993 2069 Target { mri, display_name }
@@ -40,7 +40,8 @@ use crate::mute::{MuteCommand, MuteEffect};
40use crate::push::CallNotification;
40use crate::push::CallNotification;
41use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
41use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
42use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath};
42use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath};
43use crate::organizer::Target;
43use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
44use crate::meeting_options::{self, OptionWrite};
44use crate::recording::{Consent, RecordingStatus};
45use crate::recording::{Consent, RecordingStatus};
45use crate::roster::Roster;
46use crate::roster::Roster;
46use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
47use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
@@ -798,6 +799,7 @@ async fn drive(
798 let mut next: Option<NextPeer> = None;
799 let mut next: Option<NextPeer> = None;
799 let mut roster = Roster::default();
800 let mut roster = Roster::default();
800 let mut lobby = false;
801 let mut lobby = false;
802 let mut capability = MeetingCapability::default();
801 let mut previous_packets = 0u64;
803 let mut previous_packets = 0u64;
802 let mut ticks = 0u32;
804 let mut ticks = 0u32;
803 let mut health_sampler = HealthSampler::default();
805 let mut health_sampler = HealthSampler::default();
@@ -1055,6 +1057,9 @@ async fn drive(
1055 control.send(CallUpdate::MeetingChat(thread.clone()));
1057 control.send(CallUpdate::MeetingChat(thread.clone()));
1056 meeting_chat = Some(thread);
1058 meeting_chat = Some(thread);
1057 }
1059 }
1060 if capability.apply(&body) {
1061 control.send(CallUpdate::Capability(capability));
1062 }
1058 let change = recording_status.apply(&body);
1063 let change = recording_status.apply(&body);
1059 if let Some(on) = change.recording {
1064 if let Some(on) = change.recording {
1060 control.send(CallUpdate::Recording(on));
1065 control.send(CallUpdate::Recording(on));
@@ -1430,6 +1435,70 @@ async fn drive(
1430 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
1435 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
1431 report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline);
1436 report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline);
1432 }
1437 }
1438 Some(CallCommand::SetLock(locked)) => {
1439 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
1440 if result.is_ok() {
1441 capability.locked = locked;
1442 control.send(CallUpdate::Capability(capability));
1443 }
1444 report_organizer_result(result, "lock meeting", "Could not change the meeting lock", control, timeline);
1445 }
1446 Some(CallCommand::SetRole { mri, role }) => {
1447 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
1448 report_organizer_result(result, "change role", "Could not change that role", control, timeline);
1449 }
1450 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
1451 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
1452 let mut result = Ok(200);
1453 for step in modality_steps(modality, allowed, capability, &limits) {
1454 result = match step {
1455 StateStep::Publish(state_type) => remote.signaling.publish_attendee_state(&remote.conversation, &remote.participant, state_type, &mri).await,
1456 StateStep::Remove(state_id) => remote.signaling.lower_hands(&remote.conversation, &remote.participant, &[state_id]).await.map(|()| 200),
1457 };
1458 if result.is_err() {
1459 break;
1460 }
1461 }
1462 let notice = if modality == Modality::Mic { "Could not change that microphone setting" } else { "Could not change that camera setting" };
1463 report_organizer_result(result, "attendee modality", notice, control, timeline);
1464 }
1465 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
1466 let result = match &meeting_target {
1467 Some(target) => meeting_options::write(&inner.session, target, &OptionWrite::restrictions(mic_off, camera_off)).await.map(|()| 200),
1468 None => Err(Error::Signaling("no meeting coordinates for the options".into())),
1469 };
1470 if result.is_ok() {
1471 capability.attendee_mic_off = mic_off;
1472 capability.attendee_camera_off = camera_off;
1473 control.send(CallUpdate::Capability(capability));
1474 }
1475 report_organizer_result(result, "attendee restrictions", "Could not change the attendee settings", control, timeline);
1476 }
1477 Some(CallCommand::Invite { callees, group_thread }) => {
1478 let thread = group_thread.or_else(|| meeting_chat.clone());
1479 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
1480 report_organizer_result(result, "invite", "Could not invite that person", control, timeline);
1481 }
1482 Some(CallCommand::LoadMeetingOptions) => {
1483 let update = match &meeting_target {
1484 Some(target) => meeting_options::fetch(&inner.session, target).await.map_err(|error| error.to_string()),
1485 None => Err("This meeting has no options page".to_owned()),
1486 };
1487 control.send(CallUpdate::MeetingOptions(update));
1488 }
1489 Some(CallCommand::SaveMeetingOptions(writes)) => {
1490 let update = match &meeting_target {
1491 Some(target) => save_meeting_options(&inner.session, target, &writes).await,
1492 None => Err("This meeting has no options page".to_owned()),
1493 };
1494 if let Ok(options) = &update {
1495 let (mic_off, camera_off) = options.attendees_off();
1496 capability.attendee_mic_off = mic_off;
1497 capability.attendee_camera_off = camera_off;
1498 control.send(CallUpdate::Capability(capability));
1499 }
1500 control.send(CallUpdate::MeetingOptionsSaved(update));
1501 }
1433 Some(CallCommand::Spotlight { mri }) => {
1502 Some(CallCommand::Spotlight { mri }) => {
1434 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
1503 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
1435 report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline);
1504 report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline);
@@ -1988,6 +2057,13 @@ async fn apply_background(choice: BackgroundChoice, local_video: &LocalVideo, co
1988 }
2057 }
1989}
2058}
1990
2059
2060async fn save_meeting_options(session: &session::Session, target: &MeetingTarget, writes: &[OptionWrite]) -> std::result::Result<meeting_options::MeetingOptions, String> {
2061 for change in writes {
2062 meeting_options::write(session, target, change).await.map_err(|error| error.to_string())?;
2063 }
2064 meeting_options::fetch(session, target).await.map_err(|error| error.to_string())
2065}
2066
1991fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
2067fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
1992 let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());
2068 let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());
1993 Target { mri, display_name }
2069 Target { mri, display_name }
crates/calling/src/control.rs +13 −1
@@ -12,9 +12,11 @@ use crate::error::{Error, Result};
12 12 use crate::health::CallHealth;
13 13 use crate::hold::HoldState;
14 14 use crate::mic_processing::MicSettings;
15 use crate::meeting_options::{MeetingOptions, OptionWrite};
15 16 use crate::mute::MuteCommand;
17 use crate::organizer::{MeetingCapability, Modality};
16 18 use crate::reaction::Reaction;
17 use crate::roster::RosterEntry;
19 use crate::roster::{MeetingRole, RosterEntry};
18 20 use crate::camera::CameraDevice;
19 21 use crate::screen::ShareSource;
20 22 use crate::signaling::{Callee, MeetingTarget};
@@ -46,6 +48,13 @@ pub enum CallCommand {
46 48 Spotlight { mri: String },
47 49 StopSpotlight { mri: String },
48 50 RemoveParticipant { mri: String },
51 SetLock(bool),
52 SetRole { mri: String, role: MeetingRole },
53 SetAttendeeModality { mri: String, modality: Modality, allowed: bool },
54 SetAttendeeRestrictions { mic_off: bool, camera_off: bool },
55 Invite { callees: Vec<Callee>, group_thread: Option<String> },
56 LoadMeetingOptions,
57 SaveMeetingOptions(Vec<OptionWrite>),
49 58 SetCaptions(bool),
50 59 SetBackground(BackgroundChoice),
51 60 SetIncomingVideo(bool),
@@ -102,6 +111,9 @@ pub enum CallUpdate {
102 111 BreakoutMove(BreakoutMove),
103 112 BreakoutRoom { main: MeetingTarget },
104 113 ReplacementLink(String),
114 Capability(MeetingCapability),
115 MeetingOptions(std::result::Result<MeetingOptions, String>),
116 MeetingOptionsSaved(std::result::Result<MeetingOptions, String>),
105 117 Organizer { action: String, outcome: std::result::Result<u16, String> },
106 118 MeetingChat(String),
107 119 Notice(String),
@@ -12,9 +12,11 @@ use crate::error::{Error, Result};
12use crate::health::CallHealth;
12use crate::health::CallHealth;
13use crate::hold::HoldState;
13use crate::hold::HoldState;
14use crate::mic_processing::MicSettings;
14use crate::mic_processing::MicSettings;
15use crate::meeting_options::{MeetingOptions, OptionWrite};
15use crate::mute::MuteCommand;
16use crate::mute::MuteCommand;
17use crate::organizer::{MeetingCapability, Modality};
16use crate::reaction::Reaction;
18use crate::reaction::Reaction;
17use crate::roster::RosterEntry;
19use crate::roster::{MeetingRole, RosterEntry};
18use crate::camera::CameraDevice;
20use crate::camera::CameraDevice;
19use crate::screen::ShareSource;
21use crate::screen::ShareSource;
20use crate::signaling::{Callee, MeetingTarget};
22use crate::signaling::{Callee, MeetingTarget};
@@ -46,6 +48,13 @@ pub enum CallCommand {
46 Spotlight { mri: String },
48 Spotlight { mri: String },
47 StopSpotlight { mri: String },
49 StopSpotlight { mri: String },
48 RemoveParticipant { mri: String },
50 RemoveParticipant { mri: String },
51 SetLock(bool),
52 SetRole { mri: String, role: MeetingRole },
53 SetAttendeeModality { mri: String, modality: Modality, allowed: bool },
54 SetAttendeeRestrictions { mic_off: bool, camera_off: bool },
55 Invite { callees: Vec<Callee>, group_thread: Option<String> },
56 LoadMeetingOptions,
57 SaveMeetingOptions(Vec<OptionWrite>),
49 SetCaptions(bool),
58 SetCaptions(bool),
50 SetBackground(BackgroundChoice),
59 SetBackground(BackgroundChoice),
51 SetIncomingVideo(bool),
60 SetIncomingVideo(bool),
@@ -102,6 +111,9 @@ pub enum CallUpdate {
102 BreakoutMove(BreakoutMove),
111 BreakoutMove(BreakoutMove),
103 BreakoutRoom { main: MeetingTarget },
112 BreakoutRoom { main: MeetingTarget },
104 ReplacementLink(String),
113 ReplacementLink(String),
114 Capability(MeetingCapability),
115 MeetingOptions(std::result::Result<MeetingOptions, String>),
116 MeetingOptionsSaved(std::result::Result<MeetingOptions, String>),
105 Organizer { action: String, outcome: std::result::Result<u16, String> },
117 Organizer { action: String, outcome: std::result::Result<u16, String> },
106 MeetingChat(String),
118 MeetingChat(String),
107 Notice(String),
119 Notice(String),
crates/calling/src/lib.rs +4 −1
@@ -24,6 +24,7 @@ pub mod luma_effects;
24 24 #[cfg(windows)]
25 25 mod loopback_windows;
26 26 pub mod meeting;
27 pub mod meeting_options;
27 28 pub mod mic_processing;
28 29 pub mod mixer;
29 30 pub mod mute;
@@ -67,7 +68,9 @@ pub use push::Caller;
67 68 pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
68 69 pub use reaction::{Reaction, ReactionEvent};
69 70 pub use captions::{CaptionEntry, CaptionState};
70 pub use roster::{PublishedState, RaisedHand, RosterEntry, Spotlight};
71 pub use meeting_options::{MeetingOptions, OptionWrite};
72 pub use organizer::{MeetingCapability, Modality, modality_allowed};
73 pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, RosterEntry, Spotlight};
71 74 pub use sound_capture::LoopbackKind;
72 75 pub use renegotiation::MediaPath;
73 76 pub use signaling::{Callee, MeetingTarget};
@@ -24,6 +24,7 @@ pub mod luma_effects;
24#[cfg(windows)]
24#[cfg(windows)]
25mod loopback_windows;
25mod loopback_windows;
26pub mod meeting;
26pub mod meeting;
27pub mod meeting_options;
27pub mod mic_processing;
28pub mod mic_processing;
28pub mod mixer;
29pub mod mixer;
29pub mod mute;
30pub mod mute;
@@ -67,7 +68,9 @@ pub use push::Caller;
67pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
68pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
68pub use reaction::{Reaction, ReactionEvent};
69pub use reaction::{Reaction, ReactionEvent};
69pub use captions::{CaptionEntry, CaptionState};
70pub use captions::{CaptionEntry, CaptionState};
70pub use roster::{PublishedState, RaisedHand, RosterEntry, Spotlight};
71pub use meeting_options::{MeetingOptions, OptionWrite};
72pub use organizer::{MeetingCapability, Modality, modality_allowed};
73pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, RosterEntry, Spotlight};
71pub use sound_capture::LoopbackKind;
74pub use sound_capture::LoopbackKind;
72pub use renegotiation::MediaPath;
75pub use renegotiation::MediaPath;
73pub use signaling::{Callee, MeetingTarget};
76pub use signaling::{Callee, MeetingTarget};
crates/calling/src/meeting_options.rs added +261 −0
@@ -0,0 +1,261 @@
1 use serde_json::{Value, json};
2 use session::{Method, Request, SPACES, Scope, Session};
3
4 use crate::error::{Error, Result};
5 use crate::organizer::restrictions_value;
6 use crate::signaling::{CHATSVC_REGION, MeetingTarget};
7 use crate::whiteboard::encoded;
8
9 const OPTIONS_SCOPE: &str = "user_impersonation";
10 const READ_HOST: &str = "https://teams.microsoft.com";
11 const LIVE_HOST: &str = "https://teams.cloud.microsoft";
12 const AUTO_ADMITTED: &str = "AutoAdmittedUsers";
13 const PRESENTER: &str = "PresenterOption";
14 const RESTRICTIONS: &str = "AttendeeRestrictions";
15 const MEETING_CHAT: &str = "AllowMeetingChat";
16 const REACTIONS: &str = "AllowTeamsMeetingReactions";
17 const AUTO_RECORD: &str = "AutoRecordAndTranscribeMode";
18 const RECORD_ON: &str = "AutoRecordingAndTranscription";
19 const RECORD_OFF: &str = "Off";
20 const LIST: &str = "List";
21 const BOOLEAN: &str = "Boolean";
22 const BIT_MASK: &str = "BitMask";
23
24 pub const BYPASS_CHOICES: [(&str, &str); 6] = [
25 ("Everyone", "Everyone"),
26 ("EveryoneInSameAndFederatedCompany", "People in my org and trusted orgs"),
27 ("EveryoneInCompany", "People in my org"),
28 ("EveryoneInCompanyExcludingGuests", "People in my org, no guests"),
29 ("InvitedUsers", "People I invite"),
30 ("OrganizerOnly", "Only me"),
31 ];
32 pub const PRESENTER_CHOICES: [(&str, &str); 3] = [
33 ("Everyone", "Everyone"),
34 ("EveryoneInCompany", "People in my org"),
35 ("OrganizerOnly", "Only me"),
36 ];
37 pub const CHAT_CHOICES: [(&str, &str); 3] = [
38 ("Enabled", "On"),
39 ("InMeeting", "In-meeting only"),
40 ("Disabled", "Off"),
41 ];
42
43 #[derive(Debug, Clone, PartialEq, Eq)]
44 pub struct MeetingOptions {
45 pub bypass_lobby: String,
46 pub presenters: String,
47 pub attendee_mic: bool,
48 pub attendee_camera: bool,
49 pub meeting_chat: String,
50 pub reactions: bool,
51 pub record_automatically: bool,
52 record_mode: String,
53 }
54
55 #[derive(Debug, Clone, PartialEq, Eq)]
56 pub struct OptionWrite {
57 pub name: &'static str,
58 pub kind: &'static str,
59 pub value: Value,
60 }
61
62 impl OptionWrite {
63 pub fn restrictions(mic_off: bool, camera_off: bool) -> OptionWrite {
64 OptionWrite { name: RESTRICTIONS, kind: BIT_MASK, value: json!(restrictions_value(mic_off, camera_off)) }
65 }
66
67 fn body(&self) -> Value {
68 json!({"options": [{"name": self.name, "type": self.kind, "currentValue": self.value, "isRecommended": null}]})
69 }
70 }
71
72 impl MeetingOptions {
73 pub fn from_response(body: &Value) -> Option<MeetingOptions> {
74 let options = body["options"].as_array()?;
75 let current = |name: &str| options.iter().find(|option| option["name"].as_str() == Some(name)).map(|option| &option["currentValue"]);
76 let text = |name: &str| current(name).and_then(Value::as_str).map(str::to_owned);
77 let flag = |name: &str| current(name).and_then(|value| value.as_bool().or_else(|| value.as_str().map(|text| text.eq_ignore_ascii_case("true"))));
78 let restrictions = text(RESTRICTIONS).unwrap_or_default();
79 let record_mode = text(AUTO_RECORD).unwrap_or_else(|| RECORD_OFF.to_owned());
80 Some(MeetingOptions {
81 bypass_lobby: text(AUTO_ADMITTED)?,
82 presenters: text(PRESENTER)?,
83 attendee_mic: !restrictions.contains("DisableAudio"),
84 attendee_camera: !restrictions.contains("DisableVideo"),
85 meeting_chat: text(MEETING_CHAT)?,
86 reactions: flag(REACTIONS).unwrap_or(true),
87 record_automatically: record_mode == RECORD_ON,
88 record_mode,
89 })
90 }
91
92 pub fn changes(&self, edited: &MeetingOptions) -> Vec<OptionWrite> {
93 let mut writes = Vec::new();
94 let mut list = |name: &'static str, before: &str, after: &str| {
95 if before != after {
96 writes.push(OptionWrite { name, kind: LIST, value: json!(after) });
97 }
98 };
99 list(AUTO_ADMITTED, &self.bypass_lobby, &edited.bypass_lobby);
100 list(PRESENTER, &self.presenters, &edited.presenters);
101 list(MEETING_CHAT, &self.meeting_chat, &edited.meeting_chat);
102 if self.record_automatically != edited.record_automatically {
103 let mode = if edited.record_automatically { RECORD_ON } else { RECORD_OFF };
104 writes.push(OptionWrite { name: AUTO_RECORD, kind: LIST, value: json!(mode) });
105 }
106 if self.reactions != edited.reactions {
107 writes.push(OptionWrite { name: REACTIONS, kind: BOOLEAN, value: json!(edited.reactions) });
108 }
109 if (self.attendee_mic, self.attendee_camera) != (edited.attendee_mic, edited.attendee_camera) {
110 writes.push(OptionWrite::restrictions(!edited.attendee_mic, !edited.attendee_camera));
111 }
112 writes
113 }
114
115 pub fn attendees_off(&self) -> (bool, bool) {
116 (!self.attendee_mic, !self.attendee_camera)
117 }
118
119 pub fn record_mode(&self) -> &str {
120 &self.record_mode
121 }
122 }
123
124 fn coordinates(target: &MeetingTarget) -> String {
125 format!("{}/{}/{}", encoded(&target.tenant_id), encoded(&target.organizer_id), encoded(&target.thread_id))
126 }
127
128 pub fn read_url(target: &MeetingTarget) -> String {
129 format!("{READ_HOST}/api/mt/{CHATSVC_REGION}//beta/meetings/v1/options/{}/0?monarch=true", coordinates(target))
130 }
131
132 pub fn write_url(target: &MeetingTarget) -> String {
133 format!("{LIVE_HOST}/api/mt/{CHATSVC_REGION}/beta/meetings/v1/options/{}/0/0?monarch=true", coordinates(target))
134 }
135
136 fn with_headers(mut request: Request, caller: &str) -> Request {
137 request.headers.extend([
138 ("X-Ms-Migration".to_owned(), "True".to_owned()),
139 ("x-ms-client-caller".to_owned(), caller.to_owned()),
140 ("X-MS-Request-Id".to_owned(), uuid::Uuid::new_v4().to_string()),
141 ]);
142 request
143 }
144
145 fn scope() -> Scope {
146 Scope::new(SPACES, OPTIONS_SCOPE)
147 }
148
149 pub async fn fetch(session: &Session, target: &MeetingTarget) -> Result<MeetingOptions> {
150 let request = with_headers(Request::get(read_url(target)), "meeting-options-dialog");
151 let response = session.send(request, &scope()).await?;
152 MeetingOptions::from_response(&response.body).ok_or_else(|| Error::Signaling("meeting options answer without the expected options".into()))
153 }
154
155 pub fn write_failed(body: &Value) -> bool {
156 body["success"].as_bool() == Some(false)
157 || body["options"].as_array().is_some_and(|options| options.iter().any(|option| option["success"].as_bool() == Some(false)))
158 }
159
160 pub async fn write(session: &Session, target: &MeetingTarget, change: &OptionWrite) -> Result<()> {
161 let mut request = with_headers(Request::with_body(Method::Post, write_url(target), change.body()), "meeting-options-dialog");
162 request.headers.push(("x-ms-test-user".to_owned(), "False".to_owned()));
163 let response = session.send(request, &scope()).await?;
164 if write_failed(&response.body) {
165 return Err(Error::Signaling(format!("the service refused {}", change.name)));
166 }
167 Ok(())
168 }
169
170 #[cfg(test)]
171 mod tests {
172 use super::*;
173
174 fn target() -> MeetingTarget {
175 MeetingTarget {
176 thread_id: "19:meeting_abc@thread.v2".into(),
177 tenant_id: "00000000-0000-0000-0000-000000000001".into(),
178 organizer_id: "00000000-0000-0000-0000-000000000002".into(),
179 meeting_data: None,
180 }
181 }
182
183 fn option(name: &str, kind: &str, value: Value) -> Value {
184 json!({"name": name, "type": kind, "currentValue": value, "category": "x", "isDisabled": false})
185 }
186
187 fn response() -> Value {
188 json!({"options": [
189 option("AutoAdmittedUsers", "List", json!("EveryoneInCompany")),
190 option("PresenterOption", "List", json!("Everyone")),
191 option("AttendeeRestrictions", "BitMask", json!("DisableAudio")),
192 option("AllowMeetingChat", "List", json!("InMeeting")),
193 option("AllowTeamsMeetingReactions", "Boolean", json!(true)),
194 option("AutoRecordAndTranscribeMode", "List", json!("AutoTranscriptionOnly")),
195 ], "meetingDetails": {"title": "Standup"}})
196 }
197
198 #[test]
199 fn the_read_url_keeps_the_double_slash_and_the_write_url_adds_a_zero() {
200 assert_eq!(
201 read_url(&target()),
202 "https://teams.microsoft.com/api/mt/emea//beta/meetings/v1/options/00000000-0000-0000-0000-000000000001/00000000-0000-0000-0000-000000000002/19%3Ameeting_abc%40thread.v2/0?monarch=true"
203 );
204 assert_eq!(
205 write_url(&target()),
206 "https://teams.cloud.microsoft/api/mt/emea/beta/meetings/v1/options/00000000-0000-0000-0000-000000000001/00000000-0000-0000-0000-000000000002/19%3Ameeting_abc%40thread.v2/0/0?monarch=true"
207 );
208 }
209
210 #[test]
211 fn the_read_answer_becomes_the_dialog_fields() {
212 let options = MeetingOptions::from_response(&response()).unwrap();
213 assert_eq!(options.bypass_lobby, "EveryoneInCompany");
214 assert_eq!(options.presenters, "Everyone");
215 assert!(!options.attendee_mic);
216 assert!(options.attendee_camera);
217 assert_eq!(options.meeting_chat, "InMeeting");
218 assert!(options.reactions);
219 assert!(!options.record_automatically);
220 assert_eq!(options.record_mode(), "AutoTranscriptionOnly");
221 assert!(MeetingOptions::from_response(&json!({"options": []})).is_none());
222 }
223
224 #[test]
225 fn only_changed_options_are_written() {
226 let before = MeetingOptions::from_response(&response()).unwrap();
227 assert!(before.changes(&before.clone()).is_empty());
228 let edited = MeetingOptions {
229 bypass_lobby: "OrganizerOnly".into(),
230 meeting_chat: "Disabled".into(),
231 record_automatically: true,
232 reactions: false,
233 attendee_mic: true,
234 attendee_camera: false,
235 ..before.clone()
236 };
237 let writes = before.changes(&edited);
238 let names: Vec<&str> = writes.iter().map(|write| write.name).collect();
239 assert_eq!(names, ["AutoAdmittedUsers", "AllowMeetingChat", "AutoRecordAndTranscribeMode", "AllowTeamsMeetingReactions", "AttendeeRestrictions"]);
240 assert_eq!(writes[2].value, json!("AutoRecordingAndTranscription"));
241 assert_eq!(writes[4].value, json!("DisableVideo"));
242 }
243
244 #[test]
245 fn a_write_sends_one_option_in_the_captured_shape() {
246 let write = OptionWrite { name: "AllowMeetingChat", kind: "List", value: json!("Disabled") };
247 assert_eq!(
248 write.body(),
249 json!({"options": [{"name": "AllowMeetingChat", "type": "List", "currentValue": "Disabled", "isRecommended": null}]})
250 );
251 assert_eq!(OptionWrite::restrictions(true, true).body()["options"][0]["currentValue"], "DisableAudio,DisableVideo");
252 assert_eq!(OptionWrite::restrictions(false, false).value, json!("UnRestricted"));
253 }
254
255 #[test]
256 fn a_refused_write_is_told_apart_from_an_accepted_one() {
257 assert!(!write_failed(&json!({"success": true, "options": [{"success": true}]})));
258 assert!(write_failed(&json!({"success": false})));
259 assert!(write_failed(&json!({"success": true, "options": [{"success": false}]})));
260 }
261 }
@@ -0,0 +1,261 @@
1use serde_json::{Value, json};
2use session::{Method, Request, SPACES, Scope, Session};
3
4use crate::error::{Error, Result};
5use crate::organizer::restrictions_value;
6use crate::signaling::{CHATSVC_REGION, MeetingTarget};
7use crate::whiteboard::encoded;
8
9const OPTIONS_SCOPE: &str = "user_impersonation";
10const READ_HOST: &str = "https://teams.microsoft.com";
11const LIVE_HOST: &str = "https://teams.cloud.microsoft";
12const AUTO_ADMITTED: &str = "AutoAdmittedUsers";
13const PRESENTER: &str = "PresenterOption";
14const RESTRICTIONS: &str = "AttendeeRestrictions";
15const MEETING_CHAT: &str = "AllowMeetingChat";
16const REACTIONS: &str = "AllowTeamsMeetingReactions";
17const AUTO_RECORD: &str = "AutoRecordAndTranscribeMode";
18const RECORD_ON: &str = "AutoRecordingAndTranscription";
19const RECORD_OFF: &str = "Off";
20const LIST: &str = "List";
21const BOOLEAN: &str = "Boolean";
22const BIT_MASK: &str = "BitMask";
23
24pub const BYPASS_CHOICES: [(&str, &str); 6] = [
25 ("Everyone", "Everyone"),
26 ("EveryoneInSameAndFederatedCompany", "People in my org and trusted orgs"),
27 ("EveryoneInCompany", "People in my org"),
28 ("EveryoneInCompanyExcludingGuests", "People in my org, no guests"),
29 ("InvitedUsers", "People I invite"),
30 ("OrganizerOnly", "Only me"),
31];
32pub const PRESENTER_CHOICES: [(&str, &str); 3] = [
33 ("Everyone", "Everyone"),
34 ("EveryoneInCompany", "People in my org"),
35 ("OrganizerOnly", "Only me"),
36];
37pub const CHAT_CHOICES: [(&str, &str); 3] = [
38 ("Enabled", "On"),
39 ("InMeeting", "In-meeting only"),
40 ("Disabled", "Off"),
41];
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct MeetingOptions {
45 pub bypass_lobby: String,
46 pub presenters: String,
47 pub attendee_mic: bool,
48 pub attendee_camera: bool,
49 pub meeting_chat: String,
50 pub reactions: bool,
51 pub record_automatically: bool,
52 record_mode: String,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct OptionWrite {
57 pub name: &'static str,
58 pub kind: &'static str,
59 pub value: Value,
60}
61
62impl OptionWrite {
63 pub fn restrictions(mic_off: bool, camera_off: bool) -> OptionWrite {
64 OptionWrite { name: RESTRICTIONS, kind: BIT_MASK, value: json!(restrictions_value(mic_off, camera_off)) }
65 }
66
67 fn body(&self) -> Value {
68 json!({"options": [{"name": self.name, "type": self.kind, "currentValue": self.value, "isRecommended": null}]})
69 }
70}
71
72impl MeetingOptions {
73 pub fn from_response(body: &Value) -> Option<MeetingOptions> {
74 let options = body["options"].as_array()?;
75 let current = |name: &str| options.iter().find(|option| option["name"].as_str() == Some(name)).map(|option| &option["currentValue"]);
76 let text = |name: &str| current(name).and_then(Value::as_str).map(str::to_owned);
77 let flag = |name: &str| current(name).and_then(|value| value.as_bool().or_else(|| value.as_str().map(|text| text.eq_ignore_ascii_case("true"))));
78 let restrictions = text(RESTRICTIONS).unwrap_or_default();
79 let record_mode = text(AUTO_RECORD).unwrap_or_else(|| RECORD_OFF.to_owned());
80 Some(MeetingOptions {
81 bypass_lobby: text(AUTO_ADMITTED)?,
82 presenters: text(PRESENTER)?,
83 attendee_mic: !restrictions.contains("DisableAudio"),
84 attendee_camera: !restrictions.contains("DisableVideo"),
85 meeting_chat: text(MEETING_CHAT)?,
86 reactions: flag(REACTIONS).unwrap_or(true),
87 record_automatically: record_mode == RECORD_ON,
88 record_mode,
89 })
90 }
91
92 pub fn changes(&self, edited: &MeetingOptions) -> Vec<OptionWrite> {
93 let mut writes = Vec::new();
94 let mut list = |name: &'static str, before: &str, after: &str| {
95 if before != after {
96 writes.push(OptionWrite { name, kind: LIST, value: json!(after) });
97 }
98 };
99 list(AUTO_ADMITTED, &self.bypass_lobby, &edited.bypass_lobby);
100 list(PRESENTER, &self.presenters, &edited.presenters);
101 list(MEETING_CHAT, &self.meeting_chat, &edited.meeting_chat);
102 if self.record_automatically != edited.record_automatically {
103 let mode = if edited.record_automatically { RECORD_ON } else { RECORD_OFF };
104 writes.push(OptionWrite { name: AUTO_RECORD, kind: LIST, value: json!(mode) });
105 }
106 if self.reactions != edited.reactions {
107 writes.push(OptionWrite { name: REACTIONS, kind: BOOLEAN, value: json!(edited.reactions) });
108 }
109 if (self.attendee_mic, self.attendee_camera) != (edited.attendee_mic, edited.attendee_camera) {
110 writes.push(OptionWrite::restrictions(!edited.attendee_mic, !edited.attendee_camera));
111 }
112 writes
113 }
114
115 pub fn attendees_off(&self) -> (bool, bool) {
116 (!self.attendee_mic, !self.attendee_camera)
117 }
118
119 pub fn record_mode(&self) -> &str {
120 &self.record_mode
121 }
122}
123
124fn coordinates(target: &MeetingTarget) -> String {
125 format!("{}/{}/{}", encoded(&target.tenant_id), encoded(&target.organizer_id), encoded(&target.thread_id))
126}
127
128pub fn read_url(target: &MeetingTarget) -> String {
129 format!("{READ_HOST}/api/mt/{CHATSVC_REGION}//beta/meetings/v1/options/{}/0?monarch=true", coordinates(target))
130}
131
132pub fn write_url(target: &MeetingTarget) -> String {
133 format!("{LIVE_HOST}/api/mt/{CHATSVC_REGION}/beta/meetings/v1/options/{}/0/0?monarch=true", coordinates(target))
134}
135
136fn with_headers(mut request: Request, caller: &str) -> Request {
137 request.headers.extend([
138 ("X-Ms-Migration".to_owned(), "True".to_owned()),
139 ("x-ms-client-caller".to_owned(), caller.to_owned()),
140 ("X-MS-Request-Id".to_owned(), uuid::Uuid::new_v4().to_string()),
141 ]);
142 request
143}
144
145fn scope() -> Scope {
146 Scope::new(SPACES, OPTIONS_SCOPE)
147}
148
149pub async fn fetch(session: &Session, target: &MeetingTarget) -> Result<MeetingOptions> {
150 let request = with_headers(Request::get(read_url(target)), "meeting-options-dialog");
151 let response = session.send(request, &scope()).await?;
152 MeetingOptions::from_response(&response.body).ok_or_else(|| Error::Signaling("meeting options answer without the expected options".into()))
153}
154
155pub fn write_failed(body: &Value) -> bool {
156 body["success"].as_bool() == Some(false)
157 || body["options"].as_array().is_some_and(|options| options.iter().any(|option| option["success"].as_bool() == Some(false)))
158}
159
160pub async fn write(session: &Session, target: &MeetingTarget, change: &OptionWrite) -> Result<()> {
161 let mut request = with_headers(Request::with_body(Method::Post, write_url(target), change.body()), "meeting-options-dialog");
162 request.headers.push(("x-ms-test-user".to_owned(), "False".to_owned()));
163 let response = session.send(request, &scope()).await?;
164 if write_failed(&response.body) {
165 return Err(Error::Signaling(format!("the service refused {}", change.name)));
166 }
167 Ok(())
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 fn target() -> MeetingTarget {
175 MeetingTarget {
176 thread_id: "19:meeting_abc@thread.v2".into(),
177 tenant_id: "00000000-0000-0000-0000-000000000001".into(),
178 organizer_id: "00000000-0000-0000-0000-000000000002".into(),
179 meeting_data: None,
180 }
181 }
182
183 fn option(name: &str, kind: &str, value: Value) -> Value {
184 json!({"name": name, "type": kind, "currentValue": value, "category": "x", "isDisabled": false})
185 }
186
187 fn response() -> Value {
188 json!({"options": [
189 option("AutoAdmittedUsers", "List", json!("EveryoneInCompany")),
190 option("PresenterOption", "List", json!("Everyone")),
191 option("AttendeeRestrictions", "BitMask", json!("DisableAudio")),
192 option("AllowMeetingChat", "List", json!("InMeeting")),
193 option("AllowTeamsMeetingReactions", "Boolean", json!(true)),
194 option("AutoRecordAndTranscribeMode", "List", json!("AutoTranscriptionOnly")),
195 ], "meetingDetails": {"title": "Standup"}})
196 }
197
198 #[test]
199 fn the_read_url_keeps_the_double_slash_and_the_write_url_adds_a_zero() {
200 assert_eq!(
201 read_url(&target()),
202 "https://teams.microsoft.com/api/mt/emea//beta/meetings/v1/options/00000000-0000-0000-0000-000000000001/00000000-0000-0000-0000-000000000002/19%3Ameeting_abc%40thread.v2/0?monarch=true"
203 );
204 assert_eq!(
205 write_url(&target()),
206 "https://teams.cloud.microsoft/api/mt/emea/beta/meetings/v1/options/00000000-0000-0000-0000-000000000001/00000000-0000-0000-0000-000000000002/19%3Ameeting_abc%40thread.v2/0/0?monarch=true"
207 );
208 }
209
210 #[test]
211 fn the_read_answer_becomes_the_dialog_fields() {
212 let options = MeetingOptions::from_response(&response()).unwrap();
213 assert_eq!(options.bypass_lobby, "EveryoneInCompany");
214 assert_eq!(options.presenters, "Everyone");
215 assert!(!options.attendee_mic);
216 assert!(options.attendee_camera);
217 assert_eq!(options.meeting_chat, "InMeeting");
218 assert!(options.reactions);
219 assert!(!options.record_automatically);
220 assert_eq!(options.record_mode(), "AutoTranscriptionOnly");
221 assert!(MeetingOptions::from_response(&json!({"options": []})).is_none());
222 }
223
224 #[test]
225 fn only_changed_options_are_written() {
226 let before = MeetingOptions::from_response(&response()).unwrap();
227 assert!(before.changes(&before.clone()).is_empty());
228 let edited = MeetingOptions {
229 bypass_lobby: "OrganizerOnly".into(),
230 meeting_chat: "Disabled".into(),
231 record_automatically: true,
232 reactions: false,
233 attendee_mic: true,
234 attendee_camera: false,
235 ..before.clone()
236 };
237 let writes = before.changes(&edited);
238 let names: Vec<&str> = writes.iter().map(|write| write.name).collect();
239 assert_eq!(names, ["AutoAdmittedUsers", "AllowMeetingChat", "AutoRecordAndTranscribeMode", "AllowTeamsMeetingReactions", "AttendeeRestrictions"]);
240 assert_eq!(writes[2].value, json!("AutoRecordingAndTranscription"));
241 assert_eq!(writes[4].value, json!("DisableVideo"));
242 }
243
244 #[test]
245 fn a_write_sends_one_option_in_the_captured_shape() {
246 let write = OptionWrite { name: "AllowMeetingChat", kind: "List", value: json!("Disabled") };
247 assert_eq!(
248 write.body(),
249 json!({"options": [{"name": "AllowMeetingChat", "type": "List", "currentValue": "Disabled", "isRecommended": null}]})
250 );
251 assert_eq!(OptionWrite::restrictions(true, true).body()["options"][0]["currentValue"], "DisableAudio,DisableVideo");
252 assert_eq!(OptionWrite::restrictions(false, false).value, json!("UnRestricted"));
253 }
254
255 #[test]
256 fn a_refused_write_is_told_apart_from_an_accepted_one() {
257 assert!(!write_failed(&json!({"success": true, "options": [{"success": true}]})));
258 assert!(write_failed(&json!({"success": false})));
259 assert!(write_failed(&json!({"success": true, "options": [{"success": false}]})));
260 }
261}
crates/calling/src/organizer.rs +313 −1
@@ -1,11 +1,129 @@
1 1 use serde_json::{Value, json};
2 2
3 use crate::trouter_events::CallbackLinks;
3 use crate::roster::{AttendeeLimits, MeetingRole};
4 use crate::signaling::{Callee, MEETING_MESSAGE_ID, MeetingTarget};
5 use crate::trouter_events::{CallbackLinks, find_key};
4 6
5 7 const SPOTLIGHT: &str = "spotlight";
6 8 const AUDIO: &str = "audio";
7 9 const SPECIFIED: &str = "specified";
8 10 const EVERYONE: &str = "all";
11 const PRESENTER: &str = "presenter";
12 const DISABLE_AUDIO: &str = "DisableAudio";
13 const DISABLE_VIDEO: &str = "DisableVideo";
14 const UNRESTRICTED: &str = "UnRestricted";
15
16 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17 pub struct MeetingCapability {
18 pub locked: bool,
19 pub attendee_mic_off: bool,
20 pub attendee_camera_off: bool,
21 }
22
23 impl MeetingCapability {
24 pub fn apply(&mut self, body: &Value) -> bool {
25 let Some(capability) = find_key(body, "meetingCapability") else {
26 return false;
27 };
28 let before = *self;
29 if let Some(locked) = capability["lockMeeting"].as_bool() {
30 self.locked = locked;
31 }
32 if let Some(restrictions) = capability["attendeeRestrictions"].as_str() {
33 self.attendee_mic_off = restrictions.contains(DISABLE_AUDIO);
34 self.attendee_camera_off = restrictions.contains(DISABLE_VIDEO);
35 }
36 *self != before
37 }
38 }
39
40 pub fn restrictions_value(mic_off: bool, camera_off: bool) -> String {
41 let flags: Vec<&str> = [(mic_off, DISABLE_AUDIO), (camera_off, DISABLE_VIDEO)]
42 .into_iter()
43 .filter_map(|(on, flag)| on.then_some(flag))
44 .collect();
45 if flags.is_empty() {
46 UNRESTRICTED.to_owned()
47 } else {
48 flags.join(",")
49 }
50 }
51
52 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
53 pub enum Modality {
54 Mic,
55 Camera,
56 }
57
58 #[derive(Debug, Clone, PartialEq, Eq)]
59 pub enum StateStep {
60 Publish(&'static str),
61 Remove(String),
62 }
63
64 impl Modality {
65 fn blocked_type(self) -> &'static str {
66 match self {
67 Modality::Mic => "attendeeAudioRestricted",
68 Modality::Camera => "attendeeVideoRestricted",
69 }
70 }
71
72 fn released_type(self) -> &'static str {
73 match self {
74 Modality::Mic => "attendeeModalitiesUnrestricted",
75 Modality::Camera => "attendeeVideoUnrestricted",
76 }
77 }
78
79 fn attendees_off(self, capability: MeetingCapability) -> bool {
80 match self {
81 Modality::Mic => capability.attendee_mic_off,
82 Modality::Camera => capability.attendee_camera_off,
83 }
84 }
85
86 fn states(self, limits: &AttendeeLimits) -> (Option<&str>, Option<&str>) {
87 let (blocked, released) = match self {
88 Modality::Mic => (&limits.mic_blocked, &limits.mic_released),
89 Modality::Camera => (&limits.camera_blocked, &limits.camera_released),
90 };
91 (
92 blocked.as_ref().map(|state| state.state_id.as_str()),
93 released.as_ref().map(|state| state.state_id.as_str()),
94 )
95 }
96 }
97
98 pub fn modality_allowed(modality: Modality, capability: MeetingCapability, limits: &AttendeeLimits) -> bool {
99 let (blocked, released) = modality.states(limits);
100 if blocked.is_some() {
101 return false;
102 }
103 !modality.attendees_off(capability) || released.is_some()
104 }
105
106 pub fn modality_steps(modality: Modality, allowed: bool, capability: MeetingCapability, limits: &AttendeeLimits) -> Vec<StateStep> {
107 let (blocked, released) = modality.states(limits);
108 let attendees_off = modality.attendees_off(capability);
109 let mut steps = Vec::new();
110 if allowed {
111 if let Some(state_id) = blocked {
112 steps.push(StateStep::Remove(state_id.to_owned()));
113 }
114 if attendees_off && released.is_none() {
115 steps.push(StateStep::Publish(modality.released_type()));
116 }
117 } else {
118 if let Some(state_id) = released {
119 steps.push(StateStep::Remove(state_id.to_owned()));
120 }
121 if !attendees_off && blocked.is_none() {
122 steps.push(StateStep::Publish(modality.blocked_type()));
123 }
124 }
125 steps
126 }
9 127
10 128 #[derive(Debug, Clone, Copy)]
11 129 pub struct Target<'a> {
@@ -83,6 +201,85 @@ pub fn spotlight_body(from: Value, sequence_number: u32, mri: &str, own_mri: &st
83 201 body
84 202 }
85 203
204 pub fn lock_body(from: Value, locked: bool, sequence_number: u32) -> Value {
205 json!({"from": from, "meetingSettings": {"lockMeeting": locked}, "sequenceNumber": sequence_number})
206 }
207
208 pub fn role_body(from: Value, mri: &str, role: MeetingRole) -> Value {
209 json!({
210 "from": from,
211 "scope": SPECIFIED,
212 "to": [{"id": mri, "meetingRole": role.wire()}],
213 })
214 }
215
216 pub fn attendee_state_body(from: Value, state_type: &str, sequence_number: u32, mri: &str) -> Value {
217 json!({
218 "from": from,
219 "publishedState": {
220 "stateType": state_type,
221 "level": "user",
222 "content": {},
223 "sequenceNumber": sequence_number,
224 },
225 "scope": SPECIFIED,
226 "to": [{"id": mri}],
227 })
228 }
229
230 #[derive(Debug, Clone, PartialEq, Eq)]
231 pub struct Invitee {
232 pub callee: Callee,
233 pub participant_id: String,
234 }
235
236 pub fn group_chat_for(thread_id: &str, meeting: bool) -> Value {
237 json!({"threadId": thread_id, "messageId": if meeting { json!(MEETING_MESSAGE_ID) } else { Value::Null }})
238 }
239
240 pub fn add_link_name(has_thread: bool) -> &'static str {
241 if has_thread { "addParticipantAndModality" } else { "addParticipant" }
242 }
243
244 pub fn add_participants_body(
245 from: Value,
246 invitees: &[Invitee],
247 group_chat: Value,
248 meeting: Option<&MeetingTarget>,
249 callbacks: &CallbackLinks,
250 ) -> Value {
251 let to: Vec<Value> = invitees
252 .iter()
253 .map(|invitee| {
254 let mut person = json!({
255 "id": invitee.callee.mri,
256 "displayName": invitee.callee.display_name,
257 "participantId": invitee.participant_id,
258 });
259 if meeting.is_some() {
260 person["invitationPreferences"] = json!({"requestedMeetingRoles": [PRESENTER]});
261 }
262 person
263 })
264 .collect();
265 let invitation_data = match meeting {
266 Some(meeting) => json!({"invitationData": {"meetingInfo": {"organizerId": meeting.organizer_id, "tenantId": meeting.tenant_id}}}),
267 None => json!({}),
268 };
269 json!({
270 "disableUnmute": false,
271 "participants": {"from": from, "to": to},
272 "participantInvitationData": invitation_data,
273 "replacementDetails": null,
274 "groupContext": null,
275 "groupChat": group_chat,
276 "links": {
277 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
278 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
279 },
280 })
281 }
282
86 283 #[cfg(test)]
87 284 mod tests {
88 285 use super::*;
@@ -148,4 +345,119 @@ mod tests {
148 345 assert!(own.get("scope").is_none());
149 346 assert!(own.get("to").is_none());
150 347 }
348
349 fn capability(mic_off: bool, camera_off: bool) -> MeetingCapability {
350 MeetingCapability { locked: false, attendee_mic_off: mic_off, attendee_camera_off: camera_off }
351 }
352
353 fn limits_with(mic_blocked: bool, mic_released: bool) -> AttendeeLimits {
354 let state = |id: &str| crate::roster::PublishedState { state_id: id.to_owned(), rank: 1 };
355 AttendeeLimits {
356 mic_blocked: mic_blocked.then(|| state("blocked-1")),
357 mic_released: mic_released.then(|| state("released-1")),
358 ..AttendeeLimits::default()
359 }
360 }
361
362 #[test]
363 fn locking_names_the_setting_and_the_sequence_number() {
364 let body = lock_body(from(), true, 1);
365 assert_eq!(body["meetingSettings"], json!({"lockMeeting": true}));
366 assert_eq!(body["sequenceNumber"], 1);
367 assert_eq!(body["from"]["id"], "8:orgid:me");
368 assert_eq!(lock_body(from(), false, 2)["meetingSettings"]["lockMeeting"], false);
369 }
370
371 #[test]
372 fn a_role_change_targets_one_person_with_the_wire_role() {
373 let body = role_body(from(), "8:orgid:ana", MeetingRole::Presenter);
374 assert_eq!(body["scope"], "specified");
375 assert_eq!(body["to"], json!([{"id": "8:orgid:ana", "meetingRole": "presenter"}]));
376 assert_eq!(role_body(from(), "8:orgid:ana", MeetingRole::Attendee)["to"][0]["meetingRole"], "attendee");
377 }
378
379 #[test]
380 fn restricting_one_attendee_publishes_a_user_state_for_that_person() {
381 let body = attendee_state_body(from(), "attendeeAudioRestricted", 7, "8:orgid:ana");
382 assert_eq!(body["publishedState"]["stateType"], "attendeeAudioRestricted");
383 assert_eq!(body["publishedState"]["level"], "user");
384 assert_eq!(body["publishedState"]["sequenceNumber"], 7);
385 assert_eq!(body["scope"], "specified");
386 assert_eq!(body["to"], json!([{"id": "8:orgid:ana"}]));
387 }
388
389 #[test]
390 fn inviting_into_a_meeting_names_the_organizer_and_asks_for_the_presenter_role() {
391 let meeting = MeetingTarget { thread_id: "19:meeting_x@thread.v2".into(), tenant_id: "tenant-1".into(), organizer_id: "organizer-1".into(), meeting_data: None };
392 let invitees = [Invitee { callee: Callee { mri: "8:orgid:ana".into(), display_name: "Ana".into() }, participant_id: "p-1".into() }];
393 let body = add_participants_body(from(), &invitees, group_chat_for(&meeting.thread_id, true), Some(&meeting), &callbacks());
394 assert_eq!(body["participants"]["to"][0]["id"], "8:orgid:ana");
395 assert_eq!(body["participants"]["to"][0]["participantId"], "p-1");
396 assert_eq!(body["participants"]["to"][0]["invitationPreferences"]["requestedMeetingRoles"], json!(["presenter"]));
397 assert_eq!(body["participantInvitationData"]["invitationData"]["meetingInfo"], json!({"organizerId": "organizer-1", "tenantId": "tenant-1"}));
398 assert_eq!(body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}));
399 assert!(body["links"]["addParticipantSuccess"].as_str().unwrap().contains("/conversation/addParticipantSuccess/"));
400 assert!(body["links"]["addParticipantFailure"].as_str().unwrap().contains("/conversation/addParticipantFailure/"));
401 }
402
403 #[test]
404 fn inviting_into_a_group_call_has_no_meeting_data_and_a_null_message() {
405 let invitees = [Invitee { callee: Callee { mri: "8:orgid:bo".into(), display_name: "Bo".into() }, participant_id: "p-2".into() }];
406 let body = add_participants_body(from(), &invitees, group_chat_for("19:group@thread.v2", false), None, &callbacks());
407 assert_eq!(body["participantInvitationData"], json!({}));
408 assert!(body["participants"]["to"][0].get("invitationPreferences").is_none());
409 assert_eq!(body["groupChat"], json!({"threadId": "19:group@thread.v2", "messageId": null}));
410 assert_eq!(add_link_name(true), "addParticipantAndModality");
411 assert_eq!(add_link_name(false), "addParticipant");
412 }
413
414 #[test]
415 fn the_restriction_option_combines_both_flags() {
416 assert_eq!(restrictions_value(false, false), "UnRestricted");
417 assert_eq!(restrictions_value(true, false), "DisableAudio");
418 assert_eq!(restrictions_value(false, true), "DisableVideo");
419 assert_eq!(restrictions_value(true, true), "DisableAudio,DisableVideo");
420 }
421
422 #[test]
423 fn the_capability_follows_a_conversation_update() {
424 let mut state = MeetingCapability::default();
425 let update = json!({"meetingDetails": {"meetingCapability": {"lockMeeting": true, "attendeeRestrictions": "DisableAudio,DisableVideo"}}});
426 assert!(state.apply(&update));
427 assert_eq!(state, MeetingCapability { locked: true, attendee_mic_off: true, attendee_camera_off: true });
428 assert!(!state.apply(&update));
429 assert!(!state.apply(&json!({"other": 1})));
430 assert!(state.apply(&json!({"meetingCapability": {"lockMeeting": false, "attendeeRestrictions": "UnRestricted"}})));
431 assert_eq!(state, MeetingCapability::default());
432 }
433
434 #[test]
435 fn a_mic_is_allowed_unless_blocked_or_the_meeting_blocks_everyone() {
436 let none = AttendeeLimits::default();
437 assert!(modality_allowed(Modality::Mic, capability(false, false), &none));
438 assert!(!modality_allowed(Modality::Mic, capability(true, false), &none));
439 assert!(modality_allowed(Modality::Mic, capability(true, false), &limits_with(false, true)));
440 assert!(!modality_allowed(Modality::Mic, capability(false, false), &limits_with(true, false)));
441 assert!(modality_allowed(Modality::Camera, capability(true, false), &none));
442 }
443
444 #[test]
445 fn disabling_one_mic_publishes_a_restriction_or_drops_the_release() {
446 let open = capability(false, false);
447 assert_eq!(modality_steps(Modality::Mic, false, open, &AttendeeLimits::default()), vec![StateStep::Publish("attendeeAudioRestricted")]);
448 let closed = capability(true, false);
449 assert_eq!(modality_steps(Modality::Mic, false, closed, &limits_with(false, true)), vec![StateStep::Remove("released-1".into())]);
450 assert!(modality_steps(Modality::Mic, false, closed, &AttendeeLimits::default()).is_empty());
451 assert!(modality_steps(Modality::Mic, false, open, &limits_with(true, false)).is_empty());
452 }
453
454 #[test]
455 fn allowing_one_mic_removes_the_restriction_or_publishes_a_release() {
456 let open = capability(false, false);
457 assert_eq!(modality_steps(Modality::Mic, true, open, &limits_with(true, false)), vec![StateStep::Remove("blocked-1".into())]);
458 let closed = capability(true, false);
459 assert_eq!(modality_steps(Modality::Mic, true, closed, &AttendeeLimits::default()), vec![StateStep::Publish("attendeeModalitiesUnrestricted")]);
460 assert_eq!(modality_steps(Modality::Camera, true, capability(false, true), &AttendeeLimits::default()), vec![StateStep::Publish("attendeeVideoUnrestricted")]);
461 assert!(modality_steps(Modality::Mic, true, open, &AttendeeLimits::default()).is_empty());
462 }
151 463 }
@@ -1,11 +1,129 @@
1use serde_json::{Value, json};
1use serde_json::{Value, json};
2
2
3use crate::trouter_events::CallbackLinks;
3use crate::roster::{AttendeeLimits, MeetingRole};
4use crate::signaling::{Callee, MEETING_MESSAGE_ID, MeetingTarget};
5use crate::trouter_events::{CallbackLinks, find_key};
4
6
5const SPOTLIGHT: &str = "spotlight";
7const SPOTLIGHT: &str = "spotlight";
6const AUDIO: &str = "audio";
8const AUDIO: &str = "audio";
7const SPECIFIED: &str = "specified";
9const SPECIFIED: &str = "specified";
8const EVERYONE: &str = "all";
10const EVERYONE: &str = "all";
11const PRESENTER: &str = "presenter";
12const DISABLE_AUDIO: &str = "DisableAudio";
13const DISABLE_VIDEO: &str = "DisableVideo";
14const UNRESTRICTED: &str = "UnRestricted";
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub struct MeetingCapability {
18 pub locked: bool,
19 pub attendee_mic_off: bool,
20 pub attendee_camera_off: bool,
21}
22
23impl MeetingCapability {
24 pub fn apply(&mut self, body: &Value) -> bool {
25 let Some(capability) = find_key(body, "meetingCapability") else {
26 return false;
27 };
28 let before = *self;
29 if let Some(locked) = capability["lockMeeting"].as_bool() {
30 self.locked = locked;
31 }
32 if let Some(restrictions) = capability["attendeeRestrictions"].as_str() {
33 self.attendee_mic_off = restrictions.contains(DISABLE_AUDIO);
34 self.attendee_camera_off = restrictions.contains(DISABLE_VIDEO);
35 }
36 *self != before
37 }
38}
39
40pub fn restrictions_value(mic_off: bool, camera_off: bool) -> String {
41 let flags: Vec<&str> = [(mic_off, DISABLE_AUDIO), (camera_off, DISABLE_VIDEO)]
42 .into_iter()
43 .filter_map(|(on, flag)| on.then_some(flag))
44 .collect();
45 if flags.is_empty() {
46 UNRESTRICTED.to_owned()
47 } else {
48 flags.join(",")
49 }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Modality {
54 Mic,
55 Camera,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum StateStep {
60 Publish(&'static str),
61 Remove(String),
62}
63
64impl Modality {
65 fn blocked_type(self) -> &'static str {
66 match self {
67 Modality::Mic => "attendeeAudioRestricted",
68 Modality::Camera => "attendeeVideoRestricted",
69 }
70 }
71
72 fn released_type(self) -> &'static str {
73 match self {
74 Modality::Mic => "attendeeModalitiesUnrestricted",
75 Modality::Camera => "attendeeVideoUnrestricted",
76 }
77 }
78
79 fn attendees_off(self, capability: MeetingCapability) -> bool {
80 match self {
81 Modality::Mic => capability.attendee_mic_off,
82 Modality::Camera => capability.attendee_camera_off,
83 }
84 }
85
86 fn states(self, limits: &AttendeeLimits) -> (Option<&str>, Option<&str>) {
87 let (blocked, released) = match self {
88 Modality::Mic => (&limits.mic_blocked, &limits.mic_released),
89 Modality::Camera => (&limits.camera_blocked, &limits.camera_released),
90 };
91 (
92 blocked.as_ref().map(|state| state.state_id.as_str()),
93 released.as_ref().map(|state| state.state_id.as_str()),
94 )
95 }
96}
97
98pub fn modality_allowed(modality: Modality, capability: MeetingCapability, limits: &AttendeeLimits) -> bool {
99 let (blocked, released) = modality.states(limits);
100 if blocked.is_some() {
101 return false;
102 }
103 !modality.attendees_off(capability) || released.is_some()
104}
105
106pub fn modality_steps(modality: Modality, allowed: bool, capability: MeetingCapability, limits: &AttendeeLimits) -> Vec<StateStep> {
107 let (blocked, released) = modality.states(limits);
108 let attendees_off = modality.attendees_off(capability);
109 let mut steps = Vec::new();
110 if allowed {
111 if let Some(state_id) = blocked {
112 steps.push(StateStep::Remove(state_id.to_owned()));
113 }
114 if attendees_off && released.is_none() {
115 steps.push(StateStep::Publish(modality.released_type()));
116 }
117 } else {
118 if let Some(state_id) = released {
119 steps.push(StateStep::Remove(state_id.to_owned()));
120 }
121 if !attendees_off && blocked.is_none() {
122 steps.push(StateStep::Publish(modality.blocked_type()));
123 }
124 }
125 steps
126}
9
127
10#[derive(Debug, Clone, Copy)]
128#[derive(Debug, Clone, Copy)]
11pub struct Target<'a> {
129pub struct Target<'a> {
@@ -83,6 +201,85 @@ pub fn spotlight_body(from: Value, sequence_number: u32, mri: &str, own_mri: &st
83 body
201 body
84}
202}
85
203
204pub fn lock_body(from: Value, locked: bool, sequence_number: u32) -> Value {
205 json!({"from": from, "meetingSettings": {"lockMeeting": locked}, "sequenceNumber": sequence_number})
206}
207
208pub fn role_body(from: Value, mri: &str, role: MeetingRole) -> Value {
209 json!({
210 "from": from,
211 "scope": SPECIFIED,
212 "to": [{"id": mri, "meetingRole": role.wire()}],
213 })
214}
215
216pub fn attendee_state_body(from: Value, state_type: &str, sequence_number: u32, mri: &str) -> Value {
217 json!({
218 "from": from,
219 "publishedState": {
220 "stateType": state_type,
221 "level": "user",
222 "content": {},
223 "sequenceNumber": sequence_number,
224 },
225 "scope": SPECIFIED,
226 "to": [{"id": mri}],
227 })
228}
229
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct Invitee {
232 pub callee: Callee,
233 pub participant_id: String,
234}
235
236pub fn group_chat_for(thread_id: &str, meeting: bool) -> Value {
237 json!({"threadId": thread_id, "messageId": if meeting { json!(MEETING_MESSAGE_ID) } else { Value::Null }})
238}
239
240pub fn add_link_name(has_thread: bool) -> &'static str {
241 if has_thread { "addParticipantAndModality" } else { "addParticipant" }
242}
243
244pub fn add_participants_body(
245 from: Value,
246 invitees: &[Invitee],
247 group_chat: Value,
248 meeting: Option<&MeetingTarget>,
249 callbacks: &CallbackLinks,
250) -> Value {
251 let to: Vec<Value> = invitees
252 .iter()
253 .map(|invitee| {
254 let mut person = json!({
255 "id": invitee.callee.mri,
256 "displayName": invitee.callee.display_name,
257 "participantId": invitee.participant_id,
258 });
259 if meeting.is_some() {
260 person["invitationPreferences"] = json!({"requestedMeetingRoles": [PRESENTER]});
261 }
262 person
263 })
264 .collect();
265 let invitation_data = match meeting {
266 Some(meeting) => json!({"invitationData": {"meetingInfo": {"organizerId": meeting.organizer_id, "tenantId": meeting.tenant_id}}}),
267 None => json!({}),
268 };
269 json!({
270 "disableUnmute": false,
271 "participants": {"from": from, "to": to},
272 "participantInvitationData": invitation_data,
273 "replacementDetails": null,
274 "groupContext": null,
275 "groupChat": group_chat,
276 "links": {
277 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
278 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
279 },
280 })
281}
282
86#[cfg(test)]
283#[cfg(test)]
87mod tests {
284mod tests {
88 use super::*;
285 use super::*;
@@ -148,4 +345,119 @@ mod tests {
148 assert!(own.get("scope").is_none());
345 assert!(own.get("scope").is_none());
149 assert!(own.get("to").is_none());
346 assert!(own.get("to").is_none());
150 }
347 }
348
349 fn capability(mic_off: bool, camera_off: bool) -> MeetingCapability {
350 MeetingCapability { locked: false, attendee_mic_off: mic_off, attendee_camera_off: camera_off }
351 }
352
353 fn limits_with(mic_blocked: bool, mic_released: bool) -> AttendeeLimits {
354 let state = |id: &str| crate::roster::PublishedState { state_id: id.to_owned(), rank: 1 };
355 AttendeeLimits {
356 mic_blocked: mic_blocked.then(|| state("blocked-1")),
357 mic_released: mic_released.then(|| state("released-1")),
358 ..AttendeeLimits::default()
359 }
360 }
361
362 #[test]
363 fn locking_names_the_setting_and_the_sequence_number() {
364 let body = lock_body(from(), true, 1);
365 assert_eq!(body["meetingSettings"], json!({"lockMeeting": true}));
366 assert_eq!(body["sequenceNumber"], 1);
367 assert_eq!(body["from"]["id"], "8:orgid:me");
368 assert_eq!(lock_body(from(), false, 2)["meetingSettings"]["lockMeeting"], false);
369 }
370
371 #[test]
372 fn a_role_change_targets_one_person_with_the_wire_role() {
373 let body = role_body(from(), "8:orgid:ana", MeetingRole::Presenter);
374 assert_eq!(body["scope"], "specified");
375 assert_eq!(body["to"], json!([{"id": "8:orgid:ana", "meetingRole": "presenter"}]));
376 assert_eq!(role_body(from(), "8:orgid:ana", MeetingRole::Attendee)["to"][0]["meetingRole"], "attendee");
377 }
378
379 #[test]
380 fn restricting_one_attendee_publishes_a_user_state_for_that_person() {
381 let body = attendee_state_body(from(), "attendeeAudioRestricted", 7, "8:orgid:ana");
382 assert_eq!(body["publishedState"]["stateType"], "attendeeAudioRestricted");
383 assert_eq!(body["publishedState"]["level"], "user");
384 assert_eq!(body["publishedState"]["sequenceNumber"], 7);
385 assert_eq!(body["scope"], "specified");
386 assert_eq!(body["to"], json!([{"id": "8:orgid:ana"}]));
387 }
388
389 #[test]
390 fn inviting_into_a_meeting_names_the_organizer_and_asks_for_the_presenter_role() {
391 let meeting = MeetingTarget { thread_id: "19:meeting_x@thread.v2".into(), tenant_id: "tenant-1".into(), organizer_id: "organizer-1".into(), meeting_data: None };
392 let invitees = [Invitee { callee: Callee { mri: "8:orgid:ana".into(), display_name: "Ana".into() }, participant_id: "p-1".into() }];
393 let body = add_participants_body(from(), &invitees, group_chat_for(&meeting.thread_id, true), Some(&meeting), &callbacks());
394 assert_eq!(body["participants"]["to"][0]["id"], "8:orgid:ana");
395 assert_eq!(body["participants"]["to"][0]["participantId"], "p-1");
396 assert_eq!(body["participants"]["to"][0]["invitationPreferences"]["requestedMeetingRoles"], json!(["presenter"]));
397 assert_eq!(body["participantInvitationData"]["invitationData"]["meetingInfo"], json!({"organizerId": "organizer-1", "tenantId": "tenant-1"}));
398 assert_eq!(body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}));
399 assert!(body["links"]["addParticipantSuccess"].as_str().unwrap().contains("/conversation/addParticipantSuccess/"));
400 assert!(body["links"]["addParticipantFailure"].as_str().unwrap().contains("/conversation/addParticipantFailure/"));
401 }
402
403 #[test]
404 fn inviting_into_a_group_call_has_no_meeting_data_and_a_null_message() {
405 let invitees = [Invitee { callee: Callee { mri: "8:orgid:bo".into(), display_name: "Bo".into() }, participant_id: "p-2".into() }];
406 let body = add_participants_body(from(), &invitees, group_chat_for("19:group@thread.v2", false), None, &callbacks());
407 assert_eq!(body["participantInvitationData"], json!({}));
408 assert!(body["participants"]["to"][0].get("invitationPreferences").is_none());
409 assert_eq!(body["groupChat"], json!({"threadId": "19:group@thread.v2", "messageId": null}));
410 assert_eq!(add_link_name(true), "addParticipantAndModality");
411 assert_eq!(add_link_name(false), "addParticipant");
412 }
413
414 #[test]
415 fn the_restriction_option_combines_both_flags() {
416 assert_eq!(restrictions_value(false, false), "UnRestricted");
417 assert_eq!(restrictions_value(true, false), "DisableAudio");
418 assert_eq!(restrictions_value(false, true), "DisableVideo");
419 assert_eq!(restrictions_value(true, true), "DisableAudio,DisableVideo");
420 }
421
422 #[test]
423 fn the_capability_follows_a_conversation_update() {
424 let mut state = MeetingCapability::default();
425 let update = json!({"meetingDetails": {"meetingCapability": {"lockMeeting": true, "attendeeRestrictions": "DisableAudio,DisableVideo"}}});
426 assert!(state.apply(&update));
427 assert_eq!(state, MeetingCapability { locked: true, attendee_mic_off: true, attendee_camera_off: true });
428 assert!(!state.apply(&update));
429 assert!(!state.apply(&json!({"other": 1})));
430 assert!(state.apply(&json!({"meetingCapability": {"lockMeeting": false, "attendeeRestrictions": "UnRestricted"}})));
431 assert_eq!(state, MeetingCapability::default());
432 }
433
434 #[test]
435 fn a_mic_is_allowed_unless_blocked_or_the_meeting_blocks_everyone() {
436 let none = AttendeeLimits::default();
437 assert!(modality_allowed(Modality::Mic, capability(false, false), &none));
438 assert!(!modality_allowed(Modality::Mic, capability(true, false), &none));
439 assert!(modality_allowed(Modality::Mic, capability(true, false), &limits_with(false, true)));
440 assert!(!modality_allowed(Modality::Mic, capability(false, false), &limits_with(true, false)));
441 assert!(modality_allowed(Modality::Camera, capability(true, false), &none));
442 }
443
444 #[test]
445 fn disabling_one_mic_publishes_a_restriction_or_drops_the_release() {
446 let open = capability(false, false);
447 assert_eq!(modality_steps(Modality::Mic, false, open, &AttendeeLimits::default()), vec![StateStep::Publish("attendeeAudioRestricted")]);
448 let closed = capability(true, false);
449 assert_eq!(modality_steps(Modality::Mic, false, closed, &limits_with(false, true)), vec![StateStep::Remove("released-1".into())]);
450 assert!(modality_steps(Modality::Mic, false, closed, &AttendeeLimits::default()).is_empty());
451 assert!(modality_steps(Modality::Mic, false, open, &limits_with(true, false)).is_empty());
452 }
453
454 #[test]
455 fn allowing_one_mic_removes_the_restriction_or_publishes_a_release() {
456 let open = capability(false, false);
457 assert_eq!(modality_steps(Modality::Mic, true, open, &limits_with(true, false)), vec![StateStep::Remove("blocked-1".into())]);
458 let closed = capability(true, false);
459 assert_eq!(modality_steps(Modality::Mic, true, closed, &AttendeeLimits::default()), vec![StateStep::Publish("attendeeModalitiesUnrestricted")]);
460 assert_eq!(modality_steps(Modality::Camera, true, capability(false, true), &AttendeeLimits::default()), vec![StateStep::Publish("attendeeVideoUnrestricted")]);
461 assert!(modality_steps(Modality::Mic, true, open, &AttendeeLimits::default()).is_empty());
462 }
151}
463}
crates/calling/src/roster.rs +76 −10
@@ -7,7 +7,11 @@ const SCREEN: &str = "applicationsharing-video";
7 7 const SENDING_DIRECTIONS: [&str; 2] = ["sendonly", "sendrecv"];
8 8 const RAISE_HANDS: &str = "raiseHands";
9 9 const SPOTLIGHT: &str = "spotlight";
10 const ORGANIZER_ROLES: [&str; 2] = ["organizer", "coorganizer"];
10 const ROLE_KEYS: [&str; 2] = ["meetingRole", "role"];
11 const MIC_BLOCKED: &str = "attendeeAudioRestricted";
12 const MIC_RELEASED: &str = "attendeeModalitiesUnrestricted";
13 const CAMERA_BLOCKED: &str = "attendeeVideoRestricted";
14 const CAMERA_RELEASED: &str = "attendeeVideoUnrestricted";
11 15 const BOT_PREFIX: &str = "28:";
12 16
13 17 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -16,6 +20,40 @@ pub struct PublishedState {
16 20 pub rank: u64,
17 21 }
18 22
23 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
24 pub enum MeetingRole {
25 Organizer,
26 Presenter,
27 Attendee,
28 }
29
30 impl MeetingRole {
31 pub fn parse(text: &str) -> Option<MeetingRole> {
32 match text.to_ascii_lowercase().as_str() {
33 "organizer" | "coorganizer" => Some(MeetingRole::Organizer),
34 "presenter" => Some(MeetingRole::Presenter),
35 "attendee" => Some(MeetingRole::Attendee),
36 _ => None,
37 }
38 }
39
40 pub fn wire(self) -> &'static str {
41 match self {
42 MeetingRole::Organizer => "organizer",
43 MeetingRole::Presenter => "presenter",
44 MeetingRole::Attendee => "attendee",
45 }
46 }
47 }
48
49 #[derive(Debug, Clone, Default, PartialEq, Eq)]
50 pub struct AttendeeLimits {
51 pub mic_blocked: Option<PublishedState>,
52 pub mic_released: Option<PublishedState>,
53 pub camera_blocked: Option<PublishedState>,
54 pub camera_released: Option<PublishedState>,
55 }
56
19 57 pub type RaisedHand = PublishedState;
20 58 pub type Spotlight = PublishedState;
21 59
@@ -40,11 +78,13 @@ pub struct Member {
40 78 pub hand: Option<RaisedHand>,
41 79 pub spotlight: Option<Spotlight>,
42 80 pub organizer: bool,
81 pub role: Option<MeetingRole>,
82 pub limits: AttendeeLimits,
43 83 pub captions: Option<CaptionBot>,
44 84 version: u64,
45 85 }
46 86
47 #[derive(Debug, Clone, PartialEq, Eq)]
87 #[derive(Debug, Clone, Default, PartialEq, Eq)]
48 88 pub struct RosterEntry {
49 89 pub mri: String,
50 90 pub display_name: String,
@@ -55,6 +95,8 @@ pub struct RosterEntry {
55 95 pub hand: Option<RaisedHand>,
56 96 pub spotlight: Option<Spotlight>,
57 97 pub organizer: bool,
98 pub role: Option<MeetingRole>,
99 pub limits: AttendeeLimits,
58 100 }
59 101
60 102 #[derive(Debug, Clone, Default, PartialEq, Eq)]
@@ -81,6 +123,8 @@ impl Roster {
81 123 hand: member.hand.clone(),
82 124 spotlight: member.spotlight.clone(),
83 125 organizer: member.organizer,
126 role: member.role,
127 limits: member.limits.clone(),
84 128 })
85 129 .collect()
86 130 }
@@ -194,6 +238,7 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M
194 238 .flat_map(|endpoint| audio_streams(endpoint))
195 239 .filter_map(|stream| source_id(&stream["sourceId"]))
196 240 .collect();
241 let role = ROLE_KEYS.iter().filter_map(|key| participant[*key].as_str()).find_map(MeetingRole::parse);
197 242 Member {
198 243 mri: mri.to_owned(),
199 244 display_name,
@@ -205,19 +250,19 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M
205 250 streams: stream_summaries(&in_call),
206 251 hand: published_state(participant, &endpoints, RAISE_HANDS),
207 252 spotlight: published_state(participant, &endpoints, SPOTLIGHT),
208 organizer: is_organizer_role(participant),
253 organizer: role == Some(MeetingRole::Organizer),
254 role,
255 limits: AttendeeLimits {
256 mic_blocked: published_state(participant, &endpoints, MIC_BLOCKED),
257 mic_released: published_state(participant, &endpoints, MIC_RELEASED),
258 camera_blocked: published_state(participant, &endpoints, CAMERA_BLOCKED),
259 camera_released: published_state(participant, &endpoints, CAMERA_RELEASED),
260 },
209 261 captions: mri.starts_with(BOT_PREFIX).then(|| caption_bot(mri, &endpoints)).flatten(),
210 262 version,
211 263 }
212 264 }
213 265
214 fn is_organizer_role(participant: &Value) -> bool {
215 ["meetingRole", "role"]
216 .iter()
217 .filter_map(|key| participant[*key].as_str())
218 .any(|role| ORGANIZER_ROLES.contains(&role.to_ascii_lowercase().as_str()))
219 }
220
221 266 fn caption_bot(mri: &str, endpoints: &[&Value]) -> Option<CaptionBot> {
222 267 let metadata: Vec<&Value> = endpoints.iter().map(|endpoint| &endpoint["endpointMetadata"]).filter(|metadata| metadata.is_object()).collect();
223 268 let command_url = metadata.iter().find_map(|metadata| metadata["commandUrl"].as_str()).map(str::to_owned);
@@ -517,6 +562,27 @@ mod tests {
517 562 assert!(roster.is_organizer("8:orgid:b"));
518 563 }
519 564
565 #[test]
566 fn roles_and_attendee_limits_reach_the_entries() {
567 let mut roster = Roster::default();
568 let mut presenter = participant("Ana", 1, "active", false, 201);
569 presenter["meetingRole"] = json!("presenter");
570 let mut limited = participant("Bo", 1, "active", false, 301);
571 limited["meetingRole"] = json!("attendee");
572 limited["publishedStates"] = json!([
573 {"stateType": "attendeeAudioRestricted", "stateId": "s-1", "typeRank": 1},
574 {"stateType": "attendeeVideoUnrestricted", "stateId": "s-2", "typeRank": 2},
575 ]);
576 roster.apply(&delta(json!({"8:orgid:a": presenter, "8:orgid:b": limited})));
577 let entries = roster.entries();
578 assert_eq!(entries[0].role, Some(MeetingRole::Presenter));
579 assert_eq!(entries[1].role, Some(MeetingRole::Attendee));
580 assert_eq!(entries[1].limits.mic_blocked.as_ref().map(|state| state.state_id.as_str()), Some("s-1"));
581 assert_eq!(entries[1].limits.camera_released.as_ref().map(|state| state.state_id.as_str()), Some("s-2"));
582 assert_eq!(entries[1].limits.camera_blocked, None);
583 assert_eq!(entries[0].limits, AttendeeLimits::default());
584 }
585
520 586 fn recorder_bot(version: u64, active: bool) -> Value {
521 587 json!({"version": version, "state": "active", "details": {"displayName": "Recorder"}, "meetingRole": "presenter", "endpoints": {"ep": {
522 588 "call": {"mediaStreams": []},
@@ -7,7 +7,11 @@ const SCREEN: &str = "applicationsharing-video";
7const SENDING_DIRECTIONS: [&str; 2] = ["sendonly", "sendrecv"];
7const SENDING_DIRECTIONS: [&str; 2] = ["sendonly", "sendrecv"];
8const RAISE_HANDS: &str = "raiseHands";
8const RAISE_HANDS: &str = "raiseHands";
9const SPOTLIGHT: &str = "spotlight";
9const SPOTLIGHT: &str = "spotlight";
10const ORGANIZER_ROLES: [&str; 2] = ["organizer", "coorganizer"];
10const ROLE_KEYS: [&str; 2] = ["meetingRole", "role"];
11const MIC_BLOCKED: &str = "attendeeAudioRestricted";
12const MIC_RELEASED: &str = "attendeeModalitiesUnrestricted";
13const CAMERA_BLOCKED: &str = "attendeeVideoRestricted";
14const CAMERA_RELEASED: &str = "attendeeVideoUnrestricted";
11const BOT_PREFIX: &str = "28:";
15const BOT_PREFIX: &str = "28:";
12
16
13#[derive(Debug, Clone, PartialEq, Eq)]
17#[derive(Debug, Clone, PartialEq, Eq)]
@@ -16,6 +20,40 @@ pub struct PublishedState {
16 pub rank: u64,
20 pub rank: u64,
17}
21}
18
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum MeetingRole {
25 Organizer,
26 Presenter,
27 Attendee,
28}
29
30impl MeetingRole {
31 pub fn parse(text: &str) -> Option<MeetingRole> {
32 match text.to_ascii_lowercase().as_str() {
33 "organizer" | "coorganizer" => Some(MeetingRole::Organizer),
34 "presenter" => Some(MeetingRole::Presenter),
35 "attendee" => Some(MeetingRole::Attendee),
36 _ => None,
37 }
38 }
39
40 pub fn wire(self) -> &'static str {
41 match self {
42 MeetingRole::Organizer => "organizer",
43 MeetingRole::Presenter => "presenter",
44 MeetingRole::Attendee => "attendee",
45 }
46 }
47}
48
49#[derive(Debug, Clone, Default, PartialEq, Eq)]
50pub struct AttendeeLimits {
51 pub mic_blocked: Option<PublishedState>,
52 pub mic_released: Option<PublishedState>,
53 pub camera_blocked: Option<PublishedState>,
54 pub camera_released: Option<PublishedState>,
55}
56
19pub type RaisedHand = PublishedState;
57pub type RaisedHand = PublishedState;
20pub type Spotlight = PublishedState;
58pub type Spotlight = PublishedState;
21
59
@@ -40,11 +78,13 @@ pub struct Member {
40 pub hand: Option<RaisedHand>,
78 pub hand: Option<RaisedHand>,
41 pub spotlight: Option<Spotlight>,
79 pub spotlight: Option<Spotlight>,
42 pub organizer: bool,
80 pub organizer: bool,
81 pub role: Option<MeetingRole>,
82 pub limits: AttendeeLimits,
43 pub captions: Option<CaptionBot>,
83 pub captions: Option<CaptionBot>,
44 version: u64,
84 version: u64,
45}
85}
46
86
47#[derive(Debug, Clone, PartialEq, Eq)]
87#[derive(Debug, Clone, Default, PartialEq, Eq)]
48pub struct RosterEntry {
88pub struct RosterEntry {
49 pub mri: String,
89 pub mri: String,
50 pub display_name: String,
90 pub display_name: String,
@@ -55,6 +95,8 @@ pub struct RosterEntry {
55 pub hand: Option<RaisedHand>,
95 pub hand: Option<RaisedHand>,
56 pub spotlight: Option<Spotlight>,
96 pub spotlight: Option<Spotlight>,
57 pub organizer: bool,
97 pub organizer: bool,
98 pub role: Option<MeetingRole>,
99 pub limits: AttendeeLimits,
58}
100}
59
101
60#[derive(Debug, Clone, Default, PartialEq, Eq)]
102#[derive(Debug, Clone, Default, PartialEq, Eq)]
@@ -81,6 +123,8 @@ impl Roster {
81 hand: member.hand.clone(),
123 hand: member.hand.clone(),
82 spotlight: member.spotlight.clone(),
124 spotlight: member.spotlight.clone(),
83 organizer: member.organizer,
125 organizer: member.organizer,
126 role: member.role,
127 limits: member.limits.clone(),
84 })
128 })
85 .collect()
129 .collect()
86 }
130 }
@@ -194,6 +238,7 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M
194 .flat_map(|endpoint| audio_streams(endpoint))
238 .flat_map(|endpoint| audio_streams(endpoint))
195 .filter_map(|stream| source_id(&stream["sourceId"]))
239 .filter_map(|stream| source_id(&stream["sourceId"]))
196 .collect();
240 .collect();
241 let role = ROLE_KEYS.iter().filter_map(|key| participant[*key].as_str()).find_map(MeetingRole::parse);
197 Member {
242 Member {
198 mri: mri.to_owned(),
243 mri: mri.to_owned(),
199 display_name,
244 display_name,
@@ -205,19 +250,19 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M
205 streams: stream_summaries(&in_call),
250 streams: stream_summaries(&in_call),
206 hand: published_state(participant, &endpoints, RAISE_HANDS),
251 hand: published_state(participant, &endpoints, RAISE_HANDS),
207 spotlight: published_state(participant, &endpoints, SPOTLIGHT),
252 spotlight: published_state(participant, &endpoints, SPOTLIGHT),
208 organizer: is_organizer_role(participant),
253 organizer: role == Some(MeetingRole::Organizer),
254 role,
255 limits: AttendeeLimits {
256 mic_blocked: published_state(participant, &endpoints, MIC_BLOCKED),
257 mic_released: published_state(participant, &endpoints, MIC_RELEASED),
258 camera_blocked: published_state(participant, &endpoints, CAMERA_BLOCKED),
259 camera_released: published_state(participant, &endpoints, CAMERA_RELEASED),
260 },
209 captions: mri.starts_with(BOT_PREFIX).then(|| caption_bot(mri, &endpoints)).flatten(),
261 captions: mri.starts_with(BOT_PREFIX).then(|| caption_bot(mri, &endpoints)).flatten(),
210 version,
262 version,
211 }
263 }
212}
264}
213
265
214fn is_organizer_role(participant: &Value) -> bool {
215 ["meetingRole", "role"]
216 .iter()
217 .filter_map(|key| participant[*key].as_str())
218 .any(|role| ORGANIZER_ROLES.contains(&role.to_ascii_lowercase().as_str()))
219}
220
221fn caption_bot(mri: &str, endpoints: &[&Value]) -> Option<CaptionBot> {
266fn caption_bot(mri: &str, endpoints: &[&Value]) -> Option<CaptionBot> {
222 let metadata: Vec<&Value> = endpoints.iter().map(|endpoint| &endpoint["endpointMetadata"]).filter(|metadata| metadata.is_object()).collect();
267 let metadata: Vec<&Value> = endpoints.iter().map(|endpoint| &endpoint["endpointMetadata"]).filter(|metadata| metadata.is_object()).collect();
223 let command_url = metadata.iter().find_map(|metadata| metadata["commandUrl"].as_str()).map(str::to_owned);
268 let command_url = metadata.iter().find_map(|metadata| metadata["commandUrl"].as_str()).map(str::to_owned);
@@ -517,6 +562,27 @@ mod tests {
517 assert!(roster.is_organizer("8:orgid:b"));
562 assert!(roster.is_organizer("8:orgid:b"));
518 }
563 }
519
564
565 #[test]
566 fn roles_and_attendee_limits_reach_the_entries() {
567 let mut roster = Roster::default();
568 let mut presenter = participant("Ana", 1, "active", false, 201);
569 presenter["meetingRole"] = json!("presenter");
570 let mut limited = participant("Bo", 1, "active", false, 301);
571 limited["meetingRole"] = json!("attendee");
572 limited["publishedStates"] = json!([
573 {"stateType": "attendeeAudioRestricted", "stateId": "s-1", "typeRank": 1},
574 {"stateType": "attendeeVideoUnrestricted", "stateId": "s-2", "typeRank": 2},
575 ]);
576 roster.apply(&delta(json!({"8:orgid:a": presenter, "8:orgid:b": limited})));
577 let entries = roster.entries();
578 assert_eq!(entries[0].role, Some(MeetingRole::Presenter));
579 assert_eq!(entries[1].role, Some(MeetingRole::Attendee));
580 assert_eq!(entries[1].limits.mic_blocked.as_ref().map(|state| state.state_id.as_str()), Some("s-1"));
581 assert_eq!(entries[1].limits.camera_released.as_ref().map(|state| state.state_id.as_str()), Some("s-2"));
582 assert_eq!(entries[1].limits.camera_blocked, None);
583 assert_eq!(entries[0].limits, AttendeeLimits::default());
584 }
585
520 fn recorder_bot(version: u64, active: bool) -> Value {
586 fn recorder_bot(version: u64, active: bool) -> Value {
521 json!({"version": version, "state": "active", "details": {"displayName": "Recorder"}, "meetingRole": "presenter", "endpoints": {"ep": {
587 json!({"version": version, "state": "active", "details": {"displayName": "Recorder"}, "meetingRole": "presenter", "endpoints": {"ep": {
522 "call": {"mediaStreams": []},
588 "call": {"mediaStreams": []},
crates/calling/src/signaling.rs +37 −2
@@ -7,7 +7,8 @@ use crate::captions::{self, BotAction};
7 7 use crate::recording::{self, Consent, StartDetails};
8 8 use crate::transfer::{self, TransferTarget};
9 9 use crate::error::{Error, Result};
10 use crate::organizer::{self, Target};
10 use crate::organizer::{self, Invitee, Target};
11 use crate::roster::MeetingRole;
11 12 use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
12 13 use crate::relay::ic3_scope;
13 14 use crate::timeline::Timeline;
@@ -49,7 +50,7 @@ const SUBSCRIBE_LINK_NAMES: [&str; 6] = [
49 50 ];
50 51 const CALL_LINK_NAMES: [&str; 5] = ["progress", "mediaAnswer", "acceptance", "redirection", "end"];
51 52 const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
52 const MEETING_MESSAGE_ID: &str = "0";
53 pub(crate) const MEETING_MESSAGE_ID: &str = "0";
53 54 const RAISE_HANDS: &str = "raiseHands";
54 55 const CANCEL_CODE: i64 = 487;
55 56 const DECLINE_CODE: i64 = 603;
@@ -449,6 +450,40 @@ impl Signaling {
449 450 self.send("POST publishState (spotlight)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
450 451 }
451 452
453 pub async fn set_lock(&self, conversation: &Conversation, from: &Participant, locked: bool) -> Result<u16> {
454 let body = organizer::lock_body(from.wire(), locked, self.next_state_sequence());
455 self.send("PUT updateMeetingSettings", Method::Put, conversation.link("updateMeetingSettings")?, Some(body)).await.map(|response| response.status)
456 }
457
458 pub async fn change_role(&self, conversation: &Conversation, from: &Participant, mri: &str, role: MeetingRole) -> Result<u16> {
459 let body = organizer::role_body(from.wire(), mri, role);
460 self.send("POST updateParticipantRole", Method::Post, conversation.link("updateParticipantRole")?, Some(body)).await.map(|response| response.status)
461 }
462
463 pub async fn publish_attendee_state(&self, conversation: &Conversation, from: &Participant, state_type: &str, mri: &str) -> Result<u16> {
464 let body = organizer::attendee_state_body(from.wire(), state_type, self.next_state_sequence(), mri);
465 self.send("POST publishState (attendee)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
466 }
467
468 pub async fn add_participants(
469 &self,
470 conversation: &Conversation,
471 from: &Participant,
472 callees: &[Callee],
473 group_thread: Option<&str>,
474 meeting: Option<&MeetingTarget>,
475 callbacks: &CallbackLinks,
476 ) -> Result<u16> {
477 let invitees: Vec<Invitee> = callees
478 .iter()
479 .map(|callee| Invitee { callee: callee.clone(), participant_id: uuid::Uuid::new_v4().to_string() })
480 .collect();
481 let group_chat = group_thread.map_or(Value::Null, |thread_id| organizer::group_chat_for(thread_id, meeting.is_some()));
482 let body = organizer::add_participants_body(from.wire(), &invitees, group_chat, meeting, callbacks);
483 let url = conversation.link(organizer::add_link_name(group_thread.is_some()))?;
484 self.send("POST add (invite)", Method::Post, url, Some(body)).await.map(|response| response.status)
485 }
486
452 487 pub async fn add_caption_bot(
453 488 &self,
454 489 conversation: &Conversation,
@@ -7,7 +7,8 @@ use crate::captions::{self, BotAction};
7use crate::recording::{self, Consent, StartDetails};
7use crate::recording::{self, Consent, StartDetails};
8use crate::transfer::{self, TransferTarget};
8use crate::transfer::{self, TransferTarget};
9use crate::error::{Error, Result};
9use crate::error::{Error, Result};
10use crate::organizer::{self, Target};
10use crate::organizer::{self, Invitee, Target};
11use crate::roster::MeetingRole;
11use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
12use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
12use crate::relay::ic3_scope;
13use crate::relay::ic3_scope;
13use crate::timeline::Timeline;
14use crate::timeline::Timeline;
@@ -49,7 +50,7 @@ const SUBSCRIBE_LINK_NAMES: [&str; 6] = [
49];
50];
50const CALL_LINK_NAMES: [&str; 5] = ["progress", "mediaAnswer", "acceptance", "redirection", "end"];
51const CALL_LINK_NAMES: [&str; 5] = ["progress", "mediaAnswer", "acceptance", "redirection", "end"];
51const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
52const AUDIO_MODALITIES: [&str; 1] = ["Audio"];
52const MEETING_MESSAGE_ID: &str = "0";
53pub(crate) const MEETING_MESSAGE_ID: &str = "0";
53const RAISE_HANDS: &str = "raiseHands";
54const RAISE_HANDS: &str = "raiseHands";
54const CANCEL_CODE: i64 = 487;
55const CANCEL_CODE: i64 = 487;
55const DECLINE_CODE: i64 = 603;
56const DECLINE_CODE: i64 = 603;
@@ -449,6 +450,40 @@ impl Signaling {
449 self.send("POST publishState (spotlight)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
450 self.send("POST publishState (spotlight)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
450 }
451 }
451
452
453 pub async fn set_lock(&self, conversation: &Conversation, from: &Participant, locked: bool) -> Result<u16> {
454 let body = organizer::lock_body(from.wire(), locked, self.next_state_sequence());
455 self.send("PUT updateMeetingSettings", Method::Put, conversation.link("updateMeetingSettings")?, Some(body)).await.map(|response| response.status)
456 }
457
458 pub async fn change_role(&self, conversation: &Conversation, from: &Participant, mri: &str, role: MeetingRole) -> Result<u16> {
459 let body = organizer::role_body(from.wire(), mri, role);
460 self.send("POST updateParticipantRole", Method::Post, conversation.link("updateParticipantRole")?, Some(body)).await.map(|response| response.status)
461 }
462
463 pub async fn publish_attendee_state(&self, conversation: &Conversation, from: &Participant, state_type: &str, mri: &str) -> Result<u16> {
464 let body = organizer::attendee_state_body(from.wire(), state_type, self.next_state_sequence(), mri);
465 self.send("POST publishState (attendee)", Method::Post, conversation.link("publishState")?, Some(body)).await.map(|response| response.status)
466 }
467
468 pub async fn add_participants(
469 &self,
470 conversation: &Conversation,
471 from: &Participant,
472 callees: &[Callee],
473 group_thread: Option<&str>,
474 meeting: Option<&MeetingTarget>,
475 callbacks: &CallbackLinks,
476 ) -> Result<u16> {
477 let invitees: Vec<Invitee> = callees
478 .iter()
479 .map(|callee| Invitee { callee: callee.clone(), participant_id: uuid::Uuid::new_v4().to_string() })
480 .collect();
481 let group_chat = group_thread.map_or(Value::Null, |thread_id| organizer::group_chat_for(thread_id, meeting.is_some()));
482 let body = organizer::add_participants_body(from.wire(), &invitees, group_chat, meeting, callbacks);
483 let url = conversation.link(organizer::add_link_name(group_thread.is_some()))?;
484 self.send("POST add (invite)", Method::Post, url, Some(body)).await.map(|response| response.status)
485 }
486
452 pub async fn add_caption_bot(
487 pub async fn add_caption_bot(
453 &self,
488 &self,
454 conversation: &Conversation,
489 conversation: &Conversation,
crates/calling/src/whiteboard.rs +1 −1
@@ -41,7 +41,7 @@ pub fn content_share(body: &Value) -> Option<ContentShare> {
41 41 })
42 42 }
43 43
44 fn encoded(component: &str) -> String {
44 pub(crate) fn encoded(component: &str) -> String {
45 45 component
46 46 .bytes()
47 47 .map(|byte| match byte {
@@ -41,7 +41,7 @@ pub fn content_share(body: &Value) -> Option<ContentShare> {
41 })
41 })
42}
42}
43
43
44fn encoded(component: &str) -> String {
44pub(crate) fn encoded(component: &str) -> String {
45 component
45 component
46 .bytes()
46 .bytes()
47 .map(|byte| match byte {
47 .map(|byte| match byte {