BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / call / model.rs

model.rs

model.rs 57.7 KiB Download Raw
1use std::sync::Arc;
2use std::time::{Duration, Instant};
3
4use calling::{
5 CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
6 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingTarget, Progress, Reaction,
7 RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
8};
9use tokio::sync::mpsc::UnboundedSender;
10
11use super::background::BackgroundPick;
12use super::health::{HealthBanner, HealthState};
13use super::pictures::CallPictures;
14
15pub const TEST_CALL_TITLE: &str = "Test call";
16pub const ECHO_NAME: &str = "Teams echo";
17pub const ECHO_MRI: &str = calling::signaling::ECHO_BOT_MRI;
18pub const MAX_TILES: usize = 9;
19const ORGID_PREFIX: &str = "8:orgid:";
20const WIDE_TILES: usize = 2;
21const MEDIUM_TILES: usize = 4;
22pub const REACTION_SHOWN: Duration = Duration::from_secs(3);
23const OWN_ECHO_WINDOW: Duration = Duration::from_secs(2);
24pub const CHAT_OPEN_TILES: usize = 6;
25pub const CAPTION_SHOWN: Duration = Duration::from_secs(4);
26const CAPTION_LINES: usize = 2;
27
28pub struct ActiveCall {
29 pub id: u64,
30 pub model: CallModel,
31 pub commands: UnboundedSender<CallCommand>,
32 pub viewing: bool,
33 pub conversation_id: Option<String>,
34 pub video: Arc<VideoHub>,
35 pub pictures: CallPictures,
36 pub stage_fullscreen: bool,
37 pub chat_open: bool,
38 pub meeting_target: Option<MeetingTarget>,
39 pub pending_move: Option<PendingMove>,
40 pub consult: Option<ConsultCall>,
41}
42
43#[derive(Debug, Clone, PartialEq)]
44pub struct PendingMove {
45 pub target: MeetingTarget,
46 pub title: String,
47 pub breakout: Option<BreakoutState>,
48}
49
50pub struct ConsultCall {
51 pub id: u64,
52 pub target: (String, String),
53 pub commands: UnboundedSender<CallCommand>,
54 pub state: CallState,
55 pub replacement: Option<String>,
56 pub transferring: bool,
57}
58
59impl ConsultCall {
60 pub fn connected(&self) -> bool {
61 matches!(self.state, CallState::Connected { .. })
62 }
63
64 pub fn ready_to_transfer(&self) -> bool {
65 self.connected() && self.replacement.is_some()
66 }
67
68 pub fn status_text(&self) -> String {
69 let name = &self.target.1;
70 match &self.state {
71 CallState::Connected { .. } => format!("Consulting {name}"),
72 _ => format!("Calling {name}..."),
73 }
74 }
75}
76
77impl ActiveCall {
78 pub fn new(
79 id: u64,
80 model: CallModel,
81 commands: UnboundedSender<CallCommand>,
82 conversation_id: Option<String>,
83 video: Arc<VideoHub>,
84 ) -> Self {
85 ActiveCall {
86 id,
87 model,
88 commands,
89 viewing: true,
90 conversation_id,
91 video,
92 pictures: CallPictures::default(),
93 stage_fullscreen: false,
94 chat_open: false,
95 meeting_target: None,
96 pending_move: None,
97 consult: None,
98 }
99 }
100
101 pub fn chat_thread(&self) -> Option<&str> {
102 chat_thread(
103 self.model.kind,
104 self.model.meeting_chat.as_deref(),
105 self.conversation_id.as_deref(),
106 )
107 }
108}
109
110pub fn chat_thread<'a>(
111 kind: CallKind,
112 meeting_chat: Option<&'a str>,
113 conversation_id: Option<&'a str>,
114) -> Option<&'a str> {
115 match kind {
116 CallKind::Meeting => meeting_chat.or(conversation_id),
117 CallKind::Test | CallKind::Direct | CallKind::Group => conversation_id,
118 }
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum CallKind {
123 Test,
124 Direct,
125 Group,
126 Meeting,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum TileState {
131 Invited,
132 Present,
133 InLobby,
134 Left,
135}
136
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct Tile {
139 pub mri: String,
140 pub user_id: Option<String>,
141 pub name: String,
142 pub muted: bool,
143 pub state: TileState,
144 pub invited: bool,
145 pub has_video: bool,
146 pub hand: Option<u64>,
147 pub spotlight: Option<u64>,
148}
149
150impl Tile {
151 pub fn invited(mri: &str, name: &str) -> Tile {
152 Tile {
153 mri: mri.to_owned(),
154 user_id: mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
155 name: name.to_owned(),
156 muted: false,
157 state: TileState::Invited,
158 invited: true,
159 has_video: false,
160 hand: None,
161 spotlight: None,
162 }
163 }
164}
165
166#[derive(Debug, Clone, PartialEq)]
167pub struct BreakoutState {
168 pub room_name: String,
169 pub main: Option<MeetingTarget>,
170 pub main_title: String,
171}
172
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub struct Focus {
175 pub mri: String,
176 pub own: bool,
177 pub spotlight: bool,
178 pub pinned: bool,
179}
180
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct CaptionLine {
183 pub id: String,
184 pub speaker: String,
185 pub text: String,
186 pub at: Instant,
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub struct GridLayout {
191 pub shown_others: usize,
192 pub hidden: usize,
193}
194
195pub fn grid_layout(others: usize, max_tiles: usize) -> GridLayout {
196 let total = others + 1;
197 if total <= max_tiles {
198 return GridLayout {
199 shown_others: others,
200 hidden: 0,
201 };
202 }
203 let shown_others = max_tiles - 2;
204 GridLayout {
205 shown_others,
206 hidden: others - shown_others,
207 }
208}
209
210#[derive(Debug, Clone, Copy, PartialEq)]
211pub struct TileSize {
212 pub width: f32,
213 pub height: f32,
214 pub avatar: f32,
215}
216
217pub fn tile_size(cells: usize) -> TileSize {
218 if cells <= WIDE_TILES {
219 TileSize {
220 width: 260.,
221 height: 210.,
222 avatar: 96.,
223 }
224 } else if cells <= MEDIUM_TILES {
225 TileSize {
226 width: 220.,
227 height: 180.,
228 avatar: 72.,
229 }
230 } else {
231 TileSize {
232 width: 190.,
233 height: 150.,
234 avatar: 56.,
235 }
236 }
237}
238
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct ReactionChip {
241 pub mri: String,
242 pub reaction: Reaction,
243 pub since: Instant,
244 pub serial: u64,
245}
246
247#[derive(Debug, Clone)]
248pub struct CallModel {
249 pub title: String,
250 pub kind: CallKind,
251 pub peer_name: String,
252 pub state: CallState,
253 pub progress: Option<Progress>,
254 pub muted: bool,
255 pub listen_only: bool,
256 pub lobby: bool,
257 pub can_end_meeting: bool,
258 pub incoming: bool,
259 pub input: DeviceChoice,
260 pub output: DeviceChoice,
261 pub devices: DeviceLists,
262 pub local_speaking: bool,
263 pub remote_speaking: bool,
264 pub speaking_mris: Vec<String>,
265 pub connected_since: Option<Instant>,
266 pub own_mri: Option<String>,
267 pub tiles: Vec<Tile>,
268 pub screen_sharer: Option<String>,
269 pub camera_on: bool,
270 pub cameras: Vec<CameraDevice>,
271 pub camera: DeviceChoice,
272 pub local_share: Option<String>,
273 pub share_sources: Vec<ShareSource>,
274 pub share_sound: bool,
275 pub own_hand: Option<u64>,
276 pub own_spotlight: Option<u64>,
277 pub organizer: bool,
278 pub pinned: Option<String>,
279 pub captions: CaptionState,
280 pub caption_lines: Vec<CaptionLine>,
281 pub background: BackgroundPick,
282 pub recording: bool,
283 pub consent_required: bool,
284 pub hold: HoldState,
285 pub health: HealthState,
286 pub whiteboard: Option<ContentShare>,
287 pub breakout: Option<BreakoutState>,
288 pub main_meeting: Option<MeetingTarget>,
289 pub reactions: Vec<ReactionChip>,
290 reaction_serial: u64,
291 pub meeting_chat: Option<String>,
292 local_detector: SpeakingDetector,
293 remote_detector: SpeakingDetector,
294}
295
296impl CallModel {
297 fn base(kind: CallKind, title: &str, peer_name: &str, tiles: Vec<Tile>) -> Self {
298 CallModel {
299 title: title.to_owned(),
300 kind,
301 peer_name: peer_name.to_owned(),
302 state: CallState::Connecting,
303 progress: None,
304 muted: false,
305 listen_only: false,
306 lobby: false,
307 can_end_meeting: false,
308 incoming: false,
309 input: DeviceChoice::SystemDefault,
310 output: DeviceChoice::SystemDefault,
311 devices: DeviceLists::default(),
312 local_speaking: false,
313 remote_speaking: false,
314 speaking_mris: Vec::new(),
315 connected_since: None,
316 own_mri: None,
317 tiles,
318 screen_sharer: None,
319 camera_on: false,
320 cameras: Vec::new(),
321 camera: DeviceChoice::SystemDefault,
322 local_share: None,
323 share_sources: Vec::new(),
324 share_sound: false,
325 own_hand: None,
326 own_spotlight: None,
327 organizer: false,
328 pinned: None,
329 captions: CaptionState::Off,
330 caption_lines: Vec::new(),
331 background: BackgroundPick::None,
332 recording: false,
333 consent_required: false,
334 hold: HoldState::Active,
335 health: HealthState::default(),
336 whiteboard: None,
337 breakout: None,
338 main_meeting: None,
339 reactions: Vec::new(),
340 reaction_serial: 0,
341 meeting_chat: None,
342 local_detector: SpeakingDetector::default(),
343 remote_detector: SpeakingDetector::default(),
344 }
345 }
346
347 pub fn test() -> Self {
348 Self::base(
349 CallKind::Test,
350 TEST_CALL_TITLE,
351 ECHO_NAME,
352 vec![Tile::invited(ECHO_MRI, ECHO_NAME)],
353 )
354 }
355
356 pub fn people(title: &str, callees: &[(String, String)]) -> Self {
357 let kind = if callees.len() == 1 {
358 CallKind::Direct
359 } else {
360 CallKind::Group
361 };
362 let peer_name = match callees {
363 [(_, name)] => name.clone(),
364 _ => title.to_owned(),
365 };
366 let tiles = callees
367 .iter()
368 .map(|(mri, name)| Tile::invited(mri, name))
369 .collect();
370 Self::base(kind, title, &peer_name, tiles)
371 }
372
373 pub fn meeting(title: &str, can_end_meeting: bool) -> Self {
374 let mut model = Self::base(CallKind::Meeting, title, title, Vec::new());
375 model.can_end_meeting = can_end_meeting;
376 model
377 }
378
379 pub fn incoming(title: &str, caller_mri: &str, caller_name: &str) -> Self {
380 let mut model = Self::base(
381 CallKind::Direct,
382 title,
383 caller_name,
384 vec![Tile {
385 state: TileState::Present,
386 ..Tile::invited(caller_mri, caller_name)
387 }],
388 );
389 model.incoming = true;
390 model
391 }
392
393 pub fn apply(&mut self, update: CallUpdate) {
394 match update {
395 CallUpdate::State(state) => {
396 if let Some(since) = state.started_at() {
397 self.connected_since = Some(since);
398 }
399 if !matches!(state, CallState::Connected { .. }) {
400 self.silence();
401 }
402 self.state = state;
403 }
404 CallUpdate::Muted(muted) => {
405 self.muted = muted;
406 if muted {
407 self.local_speaking = false;
408 self.local_detector.reset();
409 }
410 }
411 CallUpdate::Levels { local, remote } => {
412 self.local_speaking = !self.muted && self.local_detector.update(local);
413 self.remote_speaking = self.remote_detector.update(remote);
414 }
415 CallUpdate::Devices(devices) => self.devices = devices,
416 CallUpdate::Selected { input, output } => {
417 self.input = input;
418 self.output = output;
419 }
420 CallUpdate::ListenOnly(listen_only) => self.listen_only = listen_only,
421 CallUpdate::Stats { .. } => {}
422 CallUpdate::Progress(progress) => self.progress = Some(progress),
423 CallUpdate::Roster(entries) => self.apply_roster(&entries),
424 CallUpdate::Speakers(mris) => self.speaking_mris = mris,
425 CallUpdate::Lobby(lobby) => self.lobby = lobby,
426 CallUpdate::OwnIdentity { mri } => self.own_mri = Some(mri),
427 CallUpdate::ScreenShare(sharer) => self.screen_sharer = sharer,
428 CallUpdate::VideoReady | CallUpdate::Notice(_) => {}
429 CallUpdate::Camera(on) => self.camera_on = on,
430 CallUpdate::Cameras(cameras) => self.cameras = cameras,
431 CallUpdate::LocalShare(label) => {
432 if label.is_none() {
433 self.share_sound = false;
434 }
435 self.local_share = label;
436 }
437 CallUpdate::ShareSources(sources) => self.share_sources = sources,
438 CallUpdate::ShareSound(active) => self.share_sound = active,
439 CallUpdate::OwnHand(rank) => self.own_hand = rank,
440 CallUpdate::Reaction { mri, reaction } => {
441 self.note_reaction(mri, reaction, Instant::now())
442 }
443 CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),
444 CallUpdate::Captions(state) => {
445 if state != CaptionState::On {
446 self.caption_lines.clear();
447 }
448 self.captions = state;
449 }
450 CallUpdate::Caption(entry) => self.note_caption(entry, Instant::now()),
451 CallUpdate::Recording(on) => self.recording = on,
452 CallUpdate::ConsentRequired(required) => self.consent_required = required,
453 CallUpdate::Hold(hold) => self.hold = hold,
454 CallUpdate::Health(health) => self.health.apply(health),
455 CallUpdate::IncomingVideo(enabled) => self.health.incoming_video = enabled,
456 CallUpdate::Whiteboard(share) => self.whiteboard = share,
457 CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
458 CallUpdate::BlurTiming(_)
459 | CallUpdate::Organizer { .. }
460 | CallUpdate::WhiteboardUrl(_)
461 | CallUpdate::BreakoutMove(_)
462 | CallUpdate::ReplacementLink(_) => {}
463 }
464 }
465
466 pub fn note_caption(&mut self, entry: CaptionEntry, at: Instant) {
467 if self.captions == CaptionState::Off {
468 return;
469 }
470 let speaker = if entry.display_name.is_empty() {
471 "Someone".to_owned()
472 } else {
473 entry.display_name
474 };
475 let line = CaptionLine {
476 id: entry.id,
477 speaker,
478 text: entry.text,
479 at,
480 };
481 match self.caption_lines.last_mut() {
482 Some(last) if last.id == line.id => *last = line,
483 _ => self.caption_lines.push(line),
484 }
485 let surplus = self.caption_lines.len().saturating_sub(CAPTION_LINES);
486 self.caption_lines.drain(..surplus);
487 }
488
489 pub fn visible_captions(&self, now: Instant) -> Vec<&CaptionLine> {
490 self.caption_lines
491 .iter()
492 .filter(|line| now.saturating_duration_since(line.at) < CAPTION_SHOWN)
493 .collect()
494 }
495
496 pub fn captions_on(&self) -> bool {
497 matches!(self.captions, CaptionState::Starting | CaptionState::On)
498 }
499
500 fn silence(&mut self) {
501 self.local_speaking = false;
502 self.remote_speaking = false;
503 self.speaking_mris.clear();
504 self.local_detector.reset();
505 self.remote_detector.reset();
506 }
507
508 pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {
509 let own_echo = Some(&mri) == self.own_mri.as_ref()
510 && self.reactions.iter().any(|chip| {
511 chip.mri == mri
512 && chip.reaction == reaction
513 && at.saturating_duration_since(chip.since) < OWN_ECHO_WINDOW
514 });
515 if own_echo {
516 return;
517 }
518 self.reactions.retain(|chip| {
519 chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN
520 });
521 self.reaction_serial += 1;
522 self.reactions.push(ReactionChip {
523 mri,
524 reaction,
525 since: at,
526 serial: self.reaction_serial,
527 });
528 }
529
530 pub fn chip_of(&self, mri: &str, now: Instant) -> Option<&ReactionChip> {
531 self.reactions.iter().find(|chip| {
532 chip.mri == mri && now.saturating_duration_since(chip.since) < REACTION_SHOWN
533 })
534 }
535
536 pub fn own_chip(&self, now: Instant) -> Option<&ReactionChip> {
537 self.chip_of(self.own_mri.as_deref()?, now)
538 }
539
540 pub fn hand_position(&self, rank: u64) -> usize {
541 let raised = self
542 .tiles
543 .iter()
544 .filter_map(|tile| tile.hand)
545 .chain(self.own_hand);
546 1 + raised.filter(|other| *other < rank).count()
547 }
548
549 pub fn can_manage(&self) -> bool {
550 self.can_end_meeting || self.organizer
551 }
552
553 pub fn organizes_meeting(&self) -> bool {
554 self.kind == CallKind::Meeting && self.can_manage()
555 }
556
557 pub fn can_lower_hands(&self) -> bool {
558 self.can_manage()
559 }
560
561 pub fn lobby_guests(&self) -> Vec<&Tile> {
562 self.tiles
563 .iter()
564 .filter(|tile| tile.state == TileState::InLobby)
565 .collect()
566 }
567
568 pub fn can_admit(&self) -> bool {
569 self.can_manage() && self.is_live() && !self.lobby
570 }
571
572 pub fn is_pinned(&self, mri: &str) -> bool {
573 self.pinned.as_deref() == Some(mri)
574 }
575
576 pub fn toggle_pin(&mut self, mri: &str) {
577 self.pinned = if self.is_pinned(mri) {
578 None
579 } else {
580 Some(mri.to_owned())
581 };
582 }
583
584 pub fn is_spotlighted(&self, mri: &str) -> bool {
585 self.own_mri.as_deref() == Some(mri) && self.own_spotlight.is_some()
586 || self
587 .tiles
588 .iter()
589 .any(|tile| tile.mri == mri && tile.spotlight.is_some())
590 }
591
592 pub fn focus(&self) -> Option<Focus> {
593 let own = |mri: &str| self.own_mri.as_deref() == Some(mri);
594 let on_stage = |mri: &str| {
595 own(mri)
596 || self
597 .visible_tiles()
598 .iter()
599 .any(|tile| tile.mri == mri && tile.state == TileState::Present)
600 };
601 if let Some(pinned) = self.pinned.as_deref().filter(|mri| on_stage(mri)) {
602 return Some(Focus {
603 mri: pinned.to_owned(),
604 own: own(pinned),
605 spotlight: self.is_spotlighted(pinned),
606 pinned: true,
607 });
608 }
609 let remote = self
610 .tiles
611 .iter()
612 .filter(|tile| tile.state == TileState::Present)
613 .filter_map(|tile| Some((tile.spotlight?, tile.mri.as_str())));
614 let (_, mri) = remote
615 .chain(self.own_spotlight.zip(self.own_mri.as_deref()))
616 .min_by_key(|(rank, _)| *rank)?;
617 Some(Focus {
618 mri: mri.to_owned(),
619 own: own(mri),
620 spotlight: true,
621 pinned: false,
622 })
623 }
624
625 pub fn any_hand_raised(&self) -> bool {
626 self.own_hand.is_some() || self.tiles.iter().any(|tile| tile.hand.is_some())
627 }
628
629 pub fn own_cell_index(&self, remote_cells: usize) -> usize {
630 let Some(own) = self.own_hand else {
631 return remote_cells;
632 };
633 let ahead = self
634 .visible_tiles()
635 .iter()
636 .filter(|tile| tile.hand.is_some_and(|rank| rank < own))
637 .count();
638 ahead.min(remote_cells)
639 }
640
641 fn apply_roster(&mut self, entries: &[RosterEntry]) {
642 let own_entry = entries
643 .iter()
644 .find(|entry| Some(&entry.mri) == self.own_mri.as_ref());
645 if let Some(entry) = own_entry {
646 self.own_hand = entry.hand.as_ref().map(|hand| hand.rank);
647 }
648 self.own_spotlight =
649 own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
650 if let Some(entry) = own_entry {
651 self.organizer = entry.organizer;
652 }
653 for entry in entries
654 .iter()
655 .filter(|entry| Some(&entry.mri) != self.own_mri.as_ref())
656 {
657 let state = if entry.in_lobby {
658 TileState::InLobby
659 } else {
660 TileState::Present
661 };
662 match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
663 Some(tile) => {
664 tile.state = state;
665 tile.muted = entry.muted;
666 tile.has_video = entry.has_video;
667 tile.hand = entry.hand.as_ref().map(|hand| hand.rank);
668 tile.spotlight = entry.spotlight.as_ref().map(|spotlight| spotlight.rank);
669 if tile.name.is_empty() {
670 tile.name = entry.display_name.clone();
671 }
672 }
673 None => self.tiles.push(Tile {
674 mri: entry.mri.clone(),
675 user_id: entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
676 name: entry.display_name.clone(),
677 muted: entry.muted,
678 state,
679 invited: false,
680 has_video: entry.has_video,
681 hand: entry.hand.as_ref().map(|hand| hand.rank),
682 spotlight: entry.spotlight.as_ref().map(|spotlight| spotlight.rank),
683 }),
684 }
685 }
686 let own_mri = self.own_mri.clone();
687 let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
688 if self
689 .pinned
690 .as_deref()
691 .is_some_and(|mri| !listed(mri) && Some(mri) != own_mri.as_deref())
692 {
693 self.pinned = None;
694 }
695 self.tiles.retain_mut(|tile| {
696 if listed(&tile.mri) || Some(&tile.mri) == own_mri.as_ref() {
697 return true;
698 }
699 match (tile.invited, tile.state) {
700 (true, TileState::Invited) => true,
701 (true, _) => {
702 tile.state = TileState::Left;
703 true
704 }
705 (false, _) => false,
706 }
707 });
708 }
709
710 pub fn visible_tiles(&self) -> Vec<&Tile> {
711 let mut tiles: Vec<&Tile> = self
712 .tiles
713 .iter()
714 .filter(|tile| tile.state != TileState::InLobby)
715 .collect();
716 tiles.sort_by_key(|tile| {
717 let state = match tile.state {
718 TileState::Present => 0,
719 TileState::Invited => 1,
720 _ => 2,
721 };
722 (
723 !self.is_pinned(&tile.mri),
724 tile.hand.is_none(),
725 tile.hand.unwrap_or(0),
726 state,
727 )
728 });
729 tiles
730 }
731
732 pub fn strip_tiles(&self) -> Vec<&Tile> {
733 let mut tiles = self.visible_tiles();
734 tiles.sort_by_key(|tile| {
735 (
736 !self.is_pinned(&tile.mri),
737 tile.hand.is_none(),
738 tile.hand.unwrap_or(0),
739 !self.tile_speaking(tile),
740 )
741 });
742 tiles
743 }
744
745 pub fn sharing_label(&self) -> Option<String> {
746 let sharer = self.screen_sharer.as_ref()?;
747 let name = self
748 .tiles
749 .iter()
750 .find(|tile| &tile.mri == sharer)
751 .map(|tile| tile.name.as_str())
752 .filter(|name| !name.is_empty())
753 .unwrap_or("Someone");
754 Some(format!("{name} is sharing"))
755 }
756
757 pub fn whiteboard_label(&self) -> Option<String> {
758 let share = self.whiteboard.as_ref()?;
759 let name = share
760 .presenter
761 .as_deref()
762 .and_then(|presenter| self.tiles.iter().find(|tile| tile.mri == presenter))
763 .map(|tile| tile.name.as_str())
764 .filter(|name| !name.is_empty())
765 .unwrap_or("Someone");
766 Some(format!("{name} is sharing a whiteboard"))
767 }
768
769 pub fn whiteboard_url(&self) -> Option<&str> {
770 self.whiteboard.as_ref()?.url.as_deref()
771 }
772
773 pub fn health_banner(&self) -> Option<HealthBanner> {
774 self.health.banner(self.background != BackgroundPick::None)
775 }
776
777 pub fn is_one_to_one(&self) -> bool {
778 self.kind == CallKind::Direct
779 }
780
781 pub fn can_hold(&self) -> bool {
782 self.is_one_to_one() && self.is_live() && self.hold != HoldState::Remote
783 }
784
785 pub fn can_transfer(&self) -> bool {
786 self.is_one_to_one() && self.is_live() && self.hold == HoldState::Active
787 }
788
789 pub fn can_record(&self) -> bool {
790 self.organizes_meeting() && self.is_live() && !self.lobby
791 }
792
793 pub fn can_open_whiteboard(&self) -> bool {
794 self.kind == CallKind::Meeting && self.is_live() && !self.lobby
795 }
796
797 pub fn tile_speaking(&self, tile: &Tile) -> bool {
798 if self.speaking_mris.contains(&tile.mri) {
799 return true;
800 }
801 let only_remote = self.tiles.len() == 1;
802 only_remote && tile.state != TileState::Left && self.remote_speaking
803 }
804
805 pub fn tile_caption(&self, tile: &Tile) -> Option<&'static str> {
806 match tile.state {
807 TileState::Invited => Some(match self.progress {
808 Some(Progress::Ringing) => "Ringing",
809 _ => "Calling...",
810 }),
811 TileState::Left => Some("Left"),
812 TileState::Present | TileState::InLobby => None,
813 }
814 }
815
816 pub fn elapsed(&self, now: Instant) -> Option<Duration> {
817 self.connected_since
818 .map(|since| now.saturating_duration_since(since))
819 }
820
821 pub fn connecting_text(&self) -> &'static str {
822 match (self.kind, self.progress) {
823 (CallKind::Meeting, _) => "Joining...",
824 (_, _) if self.incoming => "Connecting...",
825 (_, Some(Progress::Ringing)) => "Ringing",
826 _ => "Calling...",
827 }
828 }
829
830 pub fn is_active(&self) -> bool {
831 matches!(
832 self.state,
833 CallState::Connecting | CallState::Connected { .. } | CallState::Reconnecting { .. }
834 )
835 }
836
837 pub fn is_connecting(&self) -> bool {
838 matches!(self.state, CallState::Connecting)
839 }
840
841 pub fn is_reconnecting(&self) -> bool {
842 matches!(self.state, CallState::Reconnecting { .. })
843 }
844
845 pub fn ended_reason(&self) -> Option<&EndReason> {
846 match &self.state {
847 CallState::Ended { reason } => Some(reason),
848 _ => None,
849 }
850 }
851
852 pub fn timer_text(&self, now: Instant) -> String {
853 self.elapsed(now).map(format_elapsed).unwrap_or_default()
854 }
855
856 pub fn has_reaction_controls(&self) -> bool {
857 matches!(self.kind, CallKind::Group | CallKind::Meeting)
858 }
859
860 pub fn can_react(&self) -> bool {
861 self.is_live() && !self.lobby
862 }
863
864 pub fn can_use_camera(&self) -> bool {
865 !self.cameras.is_empty()
866 }
867
868 pub fn can_share(&self) -> bool {
869 !self.share_sources.is_empty() && self.is_live()
870 }
871
872 fn is_live(&self) -> bool {
873 matches!(
874 self.state,
875 CallState::Connected { .. } | CallState::Reconnecting { .. }
876 )
877 }
878
879 pub fn screens(&self) -> Vec<&ShareSource> {
880 self.share_sources
881 .iter()
882 .filter(|source| source.kind == ShareKind::Screen)
883 .collect()
884 }
885
886 pub fn windows(&self) -> Vec<&ShareSource> {
887 self.share_sources
888 .iter()
889 .filter(|source| source.kind == ShareKind::Window)
890 .collect()
891 }
892
893 pub fn can_unmute(&self) -> bool {
894 !self.listen_only
895 }
896}
897
898pub fn format_elapsed(elapsed: Duration) -> String {
899 let seconds = elapsed.as_secs();
900 let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
901 if hours > 0 {
902 format!("{hours}:{minutes:02}:{seconds:02}")
903 } else {
904 format!("{minutes:02}:{seconds:02}")
905 }
906}
907
908pub fn ended_notice(reason: &EndReason, elapsed: Option<Duration>, peer_name: &str) -> String {
909 let ended = || match elapsed {
910 Some(elapsed) => format!("Call ended {}", format_elapsed(elapsed)),
911 None => "Call ended".to_owned(),
912 };
913 match reason {
914 EndReason::Cancelled => "Call cancelled".to_owned(),
915 EndReason::Dropped => "Call dropped".to_owned(),
916 EndReason::Failed(message) => format!("Call failed: {message}"),
917 EndReason::LocalHangup => ended(),
918 EndReason::Remote(EndKind::Declined) => format!("{peer_name} declined"),
919 EndReason::Remote(EndKind::NoAnswer) => "No answer".to_owned(),
920 EndReason::Remote(EndKind::Unavailable) => format!("{peer_name} is not available"),
921 EndReason::Remote(_) => ended(),
922 }
923}
924
925#[cfg(test)]
926mod tests {
927 use super::*;
928
929 fn connected_model() -> CallModel {
930 let mut model = CallModel::test();
931 model.apply(CallUpdate::State(CallState::Connected {
932 since: Instant::now(),
933 }));
934 model
935 }
936
937 fn entry(mri: &str, name: &str, muted: bool, in_lobby: bool) -> RosterEntry {
938 RosterEntry {
939 mri: mri.into(),
940 display_name: name.into(),
941 muted,
942 in_lobby,
943 has_video: false,
944 sharing: false,
945 hand: None,
946 spotlight: None,
947 organizer: false,
948 }
949 }
950
951 fn spotlit(mri: &str, name: &str, rank: u64) -> RosterEntry {
952 RosterEntry {
953 spotlight: Some(calling::Spotlight {
954 state_id: format!("sp-{rank}"),
955 rank,
956 }),
957 ..entry(mri, name, false, false)
958 }
959 }
960
961 fn organizer_entry(mri: &str) -> RosterEntry {
962 RosterEntry {
963 organizer: true,
964 ..entry(mri, "Me", false, false)
965 }
966 }
967
968 fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {
969 RosterEntry {
970 hand: Some(calling::RaisedHand {
971 state_id: format!("s-{rank}"),
972 rank,
973 }),
974 ..entry(mri, name, false, false)
975 }
976 }
977
978 fn meeting_with_me() -> CallModel {
979 let mut model = CallModel::meeting("Standup", false);
980 model.apply(CallUpdate::OwnIdentity {
981 mri: "8:orgid:me".into(),
982 });
983 model
984 }
985
986 #[test]
987 fn elapsed_text_is_minutes_and_seconds() {
988 assert_eq!(format_elapsed(Duration::from_secs(42)), "00:42");
989 assert_eq!(format_elapsed(Duration::from_secs(61)), "01:01");
990 assert_eq!(format_elapsed(Duration::from_secs(3725)), "1:02:05");
991 }
992
993 #[test]
994 fn levels_drive_the_speaking_rings() {
995 let mut model = connected_model();
996 model.apply(CallUpdate::Levels {
997 local: 0.0,
998 remote: 0.4,
999 });
1000 assert!(model.remote_speaking);
1001 assert!(!model.local_speaking);
1002 model.apply(CallUpdate::Levels {
1003 local: 0.4,
1004 remote: 0.0,
1005 });
1006 assert!(model.local_speaking);
1007 }
1008
1009 #[test]
1010 fn muting_switches_the_local_ring_off_at_once() {
1011 let mut model = connected_model();
1012 model.apply(CallUpdate::Levels {
1013 local: 0.5,
1014 remote: 0.0,
1015 });
1016 assert!(model.local_speaking);
1017 model.apply(CallUpdate::Muted(true));
1018 assert!(!model.local_speaking);
1019 model.apply(CallUpdate::Levels {
1020 local: 0.5,
1021 remote: 0.0,
1022 });
1023 assert!(!model.local_speaking);
1024 }
1025
1026 #[test]
1027 fn reconnecting_keeps_the_timer_and_clears_the_rings() {
1028 let mut model = connected_model();
1029 let since = model.connected_since.unwrap();
1030 model.apply(CallUpdate::Levels {
1031 local: 0.5,
1032 remote: 0.5,
1033 });
1034 model.apply(CallUpdate::State(CallState::Reconnecting { since }));
1035 assert!(model.is_reconnecting());
1036 assert_eq!(model.connected_since, Some(since));
1037 assert!(!model.remote_speaking && !model.local_speaking);
1038 }
1039
1040 #[test]
1041 fn notices_for_every_end_reason() {
1042 let elapsed = Some(Duration::from_secs(42));
1043 let notice = |reason: EndReason, elapsed| ended_notice(&reason, elapsed, "Bea");
1044 assert_eq!(notice(EndReason::LocalHangup, elapsed), "Call ended 00:42");
1045 assert_eq!(
1046 notice(EndReason::Remote(EndKind::Normal), elapsed),
1047 "Call ended 00:42"
1048 );
1049 assert_eq!(
1050 notice(EndReason::Remote(EndKind::Normal), None),
1051 "Call ended"
1052 );
1053 assert_eq!(notice(EndReason::Cancelled, None), "Call cancelled");
1054 assert_eq!(notice(EndReason::Dropped, elapsed), "Call dropped");
1055 assert_eq!(
1056 notice(EndReason::Failed("no route".into()), None),
1057 "Call failed: no route"
1058 );
1059 assert_eq!(
1060 notice(EndReason::Remote(EndKind::Declined), None),
1061 "Bea declined"
1062 );
1063 assert_eq!(
1064 notice(EndReason::Remote(EndKind::NoAnswer), None),
1065 "No answer"
1066 );
1067 assert_eq!(
1068 notice(EndReason::Remote(EndKind::Unavailable), None),
1069 "Bea is not available"
1070 );
1071 assert_eq!(
1072 notice(EndReason::Remote(EndKind::Cancelled), None),
1073 "Call ended"
1074 );
1075 assert_eq!(
1076 notice(EndReason::Remote(EndKind::Other), None),
1077 "Call ended"
1078 );
1079 assert_eq!(
1080 notice(EndReason::Remote(EndKind::AnsweredElsewhere), None),
1081 "Call ended"
1082 );
1083 }
1084
1085 #[test]
1086 fn the_connecting_text_follows_the_kind_of_call() {
1087 let mut direct = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1088 assert_eq!(direct.connecting_text(), "Calling...");
1089 direct.apply(CallUpdate::Progress(Progress::Ringing));
1090 assert_eq!(direct.connecting_text(), "Ringing");
1091 assert_eq!(
1092 CallModel::meeting("Standup", false).connecting_text(),
1093 "Joining..."
1094 );
1095 assert_eq!(
1096 CallModel::incoming("Bea", "8:orgid:b", "Bea").connecting_text(),
1097 "Connecting..."
1098 );
1099 assert_eq!(CallModel::test().connecting_text(), "Calling...");
1100 }
1101
1102 #[test]
1103 fn listen_only_blocks_unmuting() {
1104 let mut model = connected_model();
1105 assert!(model.can_unmute());
1106 model.apply(CallUpdate::ListenOnly(true));
1107 assert!(!model.can_unmute());
1108 }
1109
1110 #[test]
1111 fn callees_start_invited_and_follow_the_progress() {
1112 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1113 assert_eq!(model.kind, CallKind::Direct);
1114 assert_eq!(model.peer_name, "Bea");
1115 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Calling..."));
1116 model.apply(CallUpdate::Progress(Progress::Ringing));
1117 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Ringing"));
1118 model.apply(CallUpdate::Roster(vec![entry(
1119 "8:orgid:b",
1120 "Bea",
1121 false,
1122 false,
1123 )]));
1124 assert_eq!(model.tiles[0].state, TileState::Present);
1125 assert_eq!(model.tile_caption(&model.tiles[0]), None);
1126 }
1127
1128 #[test]
1129 fn several_callees_make_a_group_call_named_after_the_chat() {
1130 let model = CallModel::people(
1131 "Retro team",
1132 &[
1133 ("8:orgid:b".into(), "Bea".into()),
1134 ("8:orgid:c".into(), "Cy".into()),
1135 ],
1136 );
1137 assert_eq!(model.kind, CallKind::Group);
1138 assert_eq!(model.peer_name, "Retro team");
1139 assert_eq!(model.tiles.len(), 2);
1140 }
1141
1142 #[test]
1143 fn roster_adds_guests_updates_mute_and_drops_leavers() {
1144 let mut model = meeting_with_me();
1145 model.apply(CallUpdate::Roster(vec![
1146 entry("8:orgid:me", "Me", false, false),
1147 entry("8:orgid:a", "Ana", true, false),
1148 entry("8:orgid:b", "Bo", false, false),
1149 ]));
1150 assert_eq!(model.tiles.len(), 2);
1151 assert!(
1152 model
1153 .tiles
1154 .iter()
1155 .find(|tile| tile.name == "Ana")
1156 .unwrap()
1157 .muted
1158 );
1159 model.apply(CallUpdate::Roster(vec![
1160 entry("8:orgid:me", "Me", false, false),
1161 entry("8:orgid:b", "Bo", false, false),
1162 ]));
1163 assert_eq!(model.tiles.len(), 1);
1164 assert_eq!(model.tiles[0].name, "Bo");
1165 }
1166
1167 #[test]
1168 fn an_invited_callee_who_leaves_stays_as_left() {
1169 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1170 model.apply(CallUpdate::Roster(vec![entry(
1171 "8:orgid:b",
1172 "Bea",
1173 false,
1174 false,
1175 )]));
1176 model.apply(CallUpdate::Roster(Vec::new()));
1177 assert_eq!(model.tiles[0].state, TileState::Left);
1178 assert_eq!(model.tile_caption(&model.tiles[0]), Some("Left"));
1179 }
1180
1181 #[test]
1182 fn lobby_guests_get_no_tile() {
1183 let mut model = meeting_with_me();
1184 model.apply(CallUpdate::Roster(vec![
1185 entry("8:orgid:a", "Ana", false, false),
1186 entry("8:orgid:g", "Guest", false, true),
1187 ]));
1188 let names: Vec<&str> = model
1189 .visible_tiles()
1190 .iter()
1191 .map(|tile| tile.name.as_str())
1192 .collect();
1193 assert_eq!(names, vec!["Ana"]);
1194 }
1195
1196 #[test]
1197 fn the_lobby_flag_follows_the_call() {
1198 let mut model = meeting_with_me();
1199 model.apply(CallUpdate::Lobby(true));
1200 assert!(model.lobby);
1201 model.apply(CallUpdate::Lobby(false));
1202 assert!(!model.lobby);
1203 }
1204
1205 #[test]
1206 fn speakers_light_their_own_tile_and_a_lone_remote_follows_the_level() {
1207 let mut model = meeting_with_me();
1208 model.apply(CallUpdate::Roster(vec![
1209 entry("8:orgid:a", "Ana", false, false),
1210 entry("8:orgid:b", "Bo", false, false),
1211 ]));
1212 model.apply(CallUpdate::State(CallState::Connected {
1213 since: Instant::now(),
1214 }));
1215 model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
1216 let tiles: Vec<Tile> = model.tiles.clone();
1217 assert!(!model.tile_speaking(&tiles[0]));
1218 assert!(model.tile_speaking(&tiles[1]));
1219 let mut lone = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1220 lone.apply(CallUpdate::State(CallState::Connected {
1221 since: Instant::now(),
1222 }));
1223 lone.apply(CallUpdate::Levels {
1224 local: 0.0,
1225 remote: 0.5,
1226 });
1227 assert!(lone.tile_speaking(&lone.tiles[0].clone()));
1228 }
1229
1230 #[test]
1231 fn more_than_nine_cells_collapse_into_a_plus_n_tile() {
1232 assert_eq!(
1233 grid_layout(0, MAX_TILES),
1234 GridLayout {
1235 shown_others: 0,
1236 hidden: 0
1237 }
1238 );
1239 assert_eq!(
1240 grid_layout(8, MAX_TILES),
1241 GridLayout {
1242 shown_others: 8,
1243 hidden: 0
1244 }
1245 );
1246 assert_eq!(
1247 grid_layout(9, MAX_TILES),
1248 GridLayout {
1249 shown_others: 7,
1250 hidden: 2
1251 }
1252 );
1253 assert_eq!(
1254 grid_layout(30, MAX_TILES),
1255 GridLayout {
1256 shown_others: 7,
1257 hidden: 23
1258 }
1259 );
1260 }
1261
1262 #[test]
1263 fn an_open_chat_panel_leaves_room_for_fewer_tiles() {
1264 assert_eq!(
1265 grid_layout(5, CHAT_OPEN_TILES),
1266 GridLayout {
1267 shown_others: 5,
1268 hidden: 0
1269 }
1270 );
1271 assert_eq!(
1272 grid_layout(6, CHAT_OPEN_TILES),
1273 GridLayout {
1274 shown_others: 4,
1275 hidden: 2
1276 }
1277 );
1278 }
1279
1280 #[test]
1281 fn crowded_calls_get_smaller_tiles() {
1282 assert_eq!(tile_size(2).avatar, 96.);
1283 assert_eq!(tile_size(4).avatar, 72.);
1284 assert_eq!(tile_size(9).avatar, 56.);
1285 }
1286
1287 #[test]
1288 fn the_stage_label_names_the_sharer_and_the_strip_puts_the_speaker_first() {
1289 let mut model = meeting_with_me();
1290 model.apply(CallUpdate::Roster(vec![
1291 entry("8:orgid:a", "Ana", false, false),
1292 entry("8:orgid:b", "Bo", false, false),
1293 ]));
1294 assert_eq!(model.sharing_label(), None);
1295 model.apply(CallUpdate::ScreenShare(Some("8:orgid:b".into())));
1296 assert_eq!(model.sharing_label().as_deref(), Some("Bo is sharing"));
1297 model.apply(CallUpdate::State(CallState::Connected {
1298 since: Instant::now(),
1299 }));
1300 model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
1301 let names: Vec<&str> = model
1302 .strip_tiles()
1303 .iter()
1304 .map(|tile| tile.name.as_str())
1305 .collect();
1306 assert_eq!(names, vec!["Bo", "Ana"]);
1307 model.apply(CallUpdate::ScreenShare(None));
1308 assert_eq!(model.sharing_label(), None);
1309 }
1310
1311 #[test]
1312 fn roster_entries_carry_the_camera_flag_to_the_tile() {
1313 let mut model = meeting_with_me();
1314 let mut with_camera = entry("8:orgid:a", "Ana", false, false);
1315 with_camera.has_video = true;
1316 model.apply(CallUpdate::Roster(vec![with_camera]));
1317 assert!(model.tiles[0].has_video);
1318 model.apply(CallUpdate::Roster(vec![entry(
1319 "8:orgid:a",
1320 "Ana",
1321 false,
1322 false,
1323 )]));
1324 assert!(!model.tiles[0].has_video);
1325 }
1326
1327 #[test]
1328 fn present_guests_sort_before_waiting_ones() {
1329 let mut model = CallModel::people(
1330 "Group",
1331 &[
1332 ("8:orgid:b".into(), "Bea".into()),
1333 ("8:orgid:c".into(), "Cy".into()),
1334 ],
1335 );
1336 model.apply(CallUpdate::Roster(vec![entry(
1337 "8:orgid:c",
1338 "Cy",
1339 false,
1340 false,
1341 )]));
1342 let names: Vec<&str> = model
1343 .visible_tiles()
1344 .iter()
1345 .map(|tile| tile.name.as_str())
1346 .collect();
1347 assert_eq!(names, vec!["Cy", "Bea"]);
1348 }
1349
1350 #[test]
1351 fn raised_hands_get_queue_positions_by_raise_time_and_sort_first() {
1352 let mut model = meeting_with_me();
1353 model.apply(CallUpdate::Roster(vec![
1354 entry("8:orgid:a", "Ana", false, false),
1355 raised("8:orgid:b", "Bo", 9),
1356 raised("8:orgid:c", "Cy", 4),
1357 raised("8:orgid:me", "Me", 6),
1358 ]));
1359 assert_eq!(model.own_hand, Some(6));
1360 assert!(model.any_hand_raised());
1361 let names: Vec<&str> = model
1362 .visible_tiles()
1363 .iter()
1364 .map(|tile| tile.name.as_str())
1365 .collect();
1366 assert_eq!(names, vec!["Cy", "Bo", "Ana"]);
1367 let positions: Vec<usize> = [4, 6, 9]
1368 .into_iter()
1369 .map(|rank| model.hand_position(rank))
1370 .collect();
1371 assert_eq!(positions, vec![1, 2, 3]);
1372 assert_eq!(model.own_cell_index(3), 1);
1373 let strip: Vec<&str> = model
1374 .strip_tiles()
1375 .iter()
1376 .map(|tile| tile.name.as_str())
1377 .collect();
1378 assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);
1379 }
1380
1381 #[test]
1382 fn a_roster_without_the_own_entry_keeps_the_own_hand() {
1383 let mut model = meeting_with_me();
1384 model.apply(CallUpdate::OwnHand(Some(5)));
1385 model.apply(CallUpdate::Roster(vec![entry(
1386 "8:orgid:a",
1387 "Ana",
1388 false,
1389 false,
1390 )]));
1391 assert_eq!(model.own_hand, Some(5));
1392 model.apply(CallUpdate::Roster(vec![entry(
1393 "8:orgid:me",
1394 "Me",
1395 false,
1396 false,
1397 )]));
1398 assert_eq!(model.own_hand, None);
1399 }
1400
1401 #[test]
1402 fn reaction_controls_show_in_group_calls_and_meetings_only() {
1403 let mut model = CallModel::test();
1404 for (kind, expected) in [
1405 (CallKind::Test, false),
1406 (CallKind::Direct, false),
1407 (CallKind::Group, true),
1408 (CallKind::Meeting, true),
1409 ] {
1410 model.kind = kind;
1411 assert_eq!(model.has_reaction_controls(), expected);
1412 }
1413 }
1414
1415 #[test]
1416 fn the_server_echo_of_an_own_reaction_does_not_restart_the_chip() {
1417 let mut model = meeting_with_me();
1418 let start = Instant::now();
1419 model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
1420 let serial = model.reactions[0].serial;
1421 model.note_reaction(
1422 "8:orgid:me".into(),
1423 Reaction::Like,
1424 start + Duration::from_millis(1500),
1425 );
1426 assert_eq!(model.reactions.len(), 1);
1427 assert_eq!(model.reactions[0].serial, serial);
1428 model.note_reaction(
1429 "8:orgid:me".into(),
1430 Reaction::Heart,
1431 start + Duration::from_millis(1600),
1432 );
1433 assert_eq!(model.reactions[0].reaction, Reaction::Heart);
1434 model.note_reaction(
1435 "8:orgid:me".into(),
1436 Reaction::Heart,
1437 start + Duration::from_secs(4),
1438 );
1439 assert_ne!(model.reactions[0].serial, serial);
1440 }
1441
1442 #[test]
1443 fn another_persons_repeated_reaction_restarts_the_chip() {
1444 let mut model = meeting_with_me();
1445 let start = Instant::now();
1446 model.note_reaction("8:orgid:a".into(), Reaction::Like, start);
1447 let serial = model.reactions[0].serial;
1448 model.note_reaction(
1449 "8:orgid:a".into(),
1450 Reaction::Like,
1451 start + Duration::from_secs(1),
1452 );
1453 assert_ne!(model.reactions[0].serial, serial);
1454 }
1455
1456 #[test]
1457 fn lowering_clears_the_hand_everywhere() {
1458 let mut model = meeting_with_me();
1459 model.apply(CallUpdate::Roster(vec![
1460 raised("8:orgid:a", "Ana", 1),
1461 raised("8:orgid:me", "Me", 2),
1462 ]));
1463 model.apply(CallUpdate::Roster(vec![
1464 entry("8:orgid:a", "Ana", false, false),
1465 entry("8:orgid:me", "Me", false, false),
1466 ]));
1467 assert!(!model.any_hand_raised());
1468 assert_eq!(model.own_cell_index(1), 1);
1469 }
1470
1471 #[test]
1472 fn only_organizers_may_lower_hands() {
1473 assert!(!CallModel::meeting("Standup", false).can_lower_hands());
1474 assert!(CallModel::meeting("Standup", true).can_lower_hands());
1475 }
1476
1477 #[test]
1478 fn a_reaction_shows_for_three_seconds_on_its_sender_and_the_latest_wins() {
1479 let mut model = meeting_with_me();
1480 let start = Instant::now();
1481 model.note_reaction("8:orgid:a".into(), Reaction::Heart, start);
1482 model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
1483 let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {
1484 model
1485 .chip_of(mri, start + Duration::from_secs(seconds))
1486 .map(|chip| chip.reaction)
1487 };
1488 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));
1489 assert_eq!(
1490 model
1491 .own_chip(start + Duration::from_secs(2))
1492 .map(|chip| chip.reaction),
1493 Some(Reaction::Like)
1494 );
1495 assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);
1496 model.note_reaction(
1497 "8:orgid:a".into(),
1498 Reaction::Laugh,
1499 start + Duration::from_secs(1),
1500 );
1501 assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Laugh));
1502 assert_eq!(model.reactions.len(), 2);
1503 }
1504
1505 #[test]
1506 fn the_chat_panel_picks_the_meeting_thread_or_the_call_chat() {
1507 assert_eq!(
1508 chat_thread(CallKind::Meeting, Some("19:meeting_x"), Some("19:list")),
1509 Some("19:meeting_x")
1510 );
1511 assert_eq!(
1512 chat_thread(CallKind::Meeting, None, Some("19:list")),
1513 Some("19:list")
1514 );
1515 assert_eq!(
1516 chat_thread(CallKind::Direct, Some("19:meeting_x"), Some("19:dm")),
1517 Some("19:dm")
1518 );
1519 assert_eq!(
1520 chat_thread(CallKind::Group, None, Some("19:group")),
1521 Some("19:group")
1522 );
1523 assert_eq!(chat_thread(CallKind::Test, None, None), None);
1524 }
1525
1526 #[test]
1527 fn computer_sound_follows_the_share() {
1528 let mut model = connected_model();
1529 model.apply(CallUpdate::LocalShare(Some("Screen".into())));
1530 model.apply(CallUpdate::ShareSound(true));
1531 assert!(model.share_sound);
1532 model.apply(CallUpdate::LocalShare(None));
1533 assert!(!model.share_sound);
1534 }
1535
1536 #[test]
1537 fn lobby_guests_are_listed_for_organizers_who_may_admit() {
1538 let mut model = meeting_with_me();
1539 model.apply(CallUpdate::State(CallState::Connected {
1540 since: Instant::now(),
1541 }));
1542 model.apply(CallUpdate::Roster(vec![
1543 entry("8:orgid:a", "Ana", false, false),
1544 entry("8:orgid:g1", "Gast Eins", false, true),
1545 entry("8:orgid:g2", "Gast Zwei", false, true),
1546 ]));
1547 let waiting: Vec<&str> = model
1548 .lobby_guests()
1549 .iter()
1550 .map(|tile| tile.name.as_str())
1551 .collect();
1552 assert_eq!(waiting, vec!["Gast Eins", "Gast Zwei"]);
1553 assert!(!model.can_admit());
1554 model.apply(CallUpdate::Roster(vec![
1555 organizer_entry("8:orgid:me"),
1556 entry("8:orgid:g1", "Gast Eins", false, true),
1557 ]));
1558 assert!(model.organizer && model.can_admit() && model.organizes_meeting());
1559 let mut owner = CallModel::meeting("Standup", true);
1560 owner.apply(CallUpdate::State(CallState::Connected {
1561 since: Instant::now(),
1562 }));
1563 assert!(owner.can_admit());
1564 owner.apply(CallUpdate::Lobby(true));
1565 assert!(!owner.can_admit());
1566 }
1567
1568 #[test]
1569 fn a_spotlight_takes_the_stage_and_the_lowest_rank_wins() {
1570 let mut model = meeting_with_me();
1571 model.apply(CallUpdate::Roster(vec![
1572 entry("8:orgid:a", "Ana", false, false),
1573 spotlit("8:orgid:b", "Bo", 4),
1574 spotlit("8:orgid:c", "Cy", 2),
1575 ]));
1576 assert_eq!(
1577 model.focus(),
1578 Some(Focus {
1579 mri: "8:orgid:c".into(),
1580 own: false,
1581 spotlight: true,
1582 pinned: false
1583 })
1584 );
1585 assert!(model.is_spotlighted("8:orgid:b") && !model.is_spotlighted("8:orgid:a"));
1586 model.apply(CallUpdate::Roster(vec![
1587 entry("8:orgid:a", "Ana", false, false),
1588 spotlit("8:orgid:b", "Bo", 4),
1589 entry("8:orgid:c", "Cy", false, false),
1590 ]));
1591 assert_eq!(
1592 model.focus().map(|focus| focus.mri),
1593 Some("8:orgid:b".to_owned())
1594 );
1595 model.apply(CallUpdate::Roster(vec![entry(
1596 "8:orgid:a",
1597 "Ana",
1598 false,
1599 false,
1600 )]));
1601 assert_eq!(model.focus(), None);
1602 }
1603
1604 #[test]
1605 fn spotlighting_yourself_puts_your_own_tile_on_the_stage() {
1606 let mut model = meeting_with_me();
1607 model.apply(CallUpdate::Roster(vec![
1608 entry("8:orgid:a", "Ana", false, false),
1609 spotlit("8:orgid:me", "Me", 1),
1610 ]));
1611 assert_eq!(
1612 model.focus(),
1613 Some(Focus {
1614 mri: "8:orgid:me".into(),
1615 own: true,
1616 spotlight: true,
1617 pinned: false
1618 })
1619 );
1620 }
1621
1622 #[test]
1623 fn a_pin_is_local_beats_the_spotlight_and_ends_when_the_person_leaves() {
1624 let mut model = meeting_with_me();
1625 model.apply(CallUpdate::State(CallState::Connected {
1626 since: Instant::now(),
1627 }));
1628 model.apply(CallUpdate::Roster(vec![
1629 entry("8:orgid:a", "Ana", false, false),
1630 spotlit("8:orgid:b", "Bo", 1),
1631 ]));
1632 model.toggle_pin("8:orgid:a");
1633 assert_eq!(
1634 model.focus(),
1635 Some(Focus {
1636 mri: "8:orgid:a".into(),
1637 own: false,
1638 spotlight: false,
1639 pinned: true
1640 })
1641 );
1642 let names: Vec<&str> = model
1643 .strip_tiles()
1644 .iter()
1645 .map(|tile| tile.name.as_str())
1646 .collect();
1647 assert_eq!(names[0], "Ana");
1648 model.toggle_pin("8:orgid:b");
1649 assert_eq!(
1650 model
1651 .focus()
1652 .map(|focus| (focus.mri, focus.spotlight, focus.pinned)),
1653 Some(("8:orgid:b".to_owned(), true, true))
1654 );
1655 model.toggle_pin("8:orgid:b");
1656 assert_eq!(model.pinned, None);
1657 model.toggle_pin("8:orgid:a");
1658 model.apply(CallUpdate::Roster(vec![spotlit("8:orgid:b", "Bo", 1)]));
1659 assert_eq!(model.pinned, None);
1660 }
1661
1662 fn caption(id: &str, speaker: &str, text: &str, is_final: bool) -> CaptionEntry {
1663 CaptionEntry {
1664 id: id.into(),
1665 user_id: "u".into(),
1666 display_name: speaker.into(),
1667 text: text.into(),
1668 is_final,
1669 }
1670 }
1671
1672 #[test]
1673 fn captions_keep_two_lines_update_partials_and_fade_after_four_seconds() {
1674 let mut model = meeting_with_me();
1675 let start = Instant::now();
1676 model.note_caption(caption("1", "Ana", "ignored while off", false), start);
1677 assert!(model.caption_lines.is_empty());
1678 model.apply(CallUpdate::Captions(CaptionState::On));
1679 model.note_caption(caption("1", "Ana", "Hello", false), start);
1680 model.note_caption(caption("1", "Ana", "Hello there", true), start);
1681 assert_eq!(model.caption_lines.len(), 1);
1682 assert_eq!(model.caption_lines[0].text, "Hello there");
1683 model.note_caption(
1684 caption("2", "", "Next", false),
1685 start + Duration::from_secs(1),
1686 );
1687 model.note_caption(
1688 caption("3", "Bo", "Third", false),
1689 start + Duration::from_secs(2),
1690 );
1691 let texts: Vec<&str> = model
1692 .caption_lines
1693 .iter()
1694 .map(|line| line.text.as_str())
1695 .collect();
1696 assert_eq!(texts, vec!["Next", "Third"]);
1697 assert_eq!(model.caption_lines[0].speaker, "Someone");
1698 assert_eq!(
1699 model.visible_captions(start + Duration::from_secs(3)).len(),
1700 2
1701 );
1702 assert_eq!(
1703 model
1704 .visible_captions(start + Duration::from_millis(5500))
1705 .len(),
1706 1
1707 );
1708 assert!(
1709 model
1710 .visible_captions(start + Duration::from_secs(7))
1711 .is_empty()
1712 );
1713 model.apply(CallUpdate::Captions(CaptionState::Off));
1714 assert!(model.caption_lines.is_empty() && !model.captions_on());
1715 }
1716
1717 fn one_to_one() -> CallModel {
1718 let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
1719 model.apply(CallUpdate::State(CallState::Connected {
1720 since: Instant::now(),
1721 }));
1722 model
1723 }
1724
1725 #[test]
1726 fn hold_and_transfer_belong_to_one_to_one_calls_and_follow_the_hold_state() {
1727 let mut model = one_to_one();
1728 assert!(model.can_hold() && model.can_transfer());
1729 model.apply(CallUpdate::Hold(HoldState::Local));
1730 assert!(model.can_hold() && !model.can_transfer());
1731 model.apply(CallUpdate::Hold(HoldState::Remote));
1732 assert!(!model.can_hold() && !model.can_transfer());
1733 let meeting = meeting_with_me();
1734 assert!(!meeting.can_hold() && !meeting.can_transfer());
1735 assert!(
1736 !CallModel::people(
1737 "Group",
1738 &[
1739 ("8:orgid:a".into(), "A".into()),
1740 ("8:orgid:b".into(), "B".into())
1741 ]
1742 )
1743 .can_hold()
1744 );
1745 }
1746
1747 #[test]
1748 fn recording_and_consent_follow_the_call_updates_and_only_organizers_may_record() {
1749 let mut model = meeting_with_me();
1750 model.apply(CallUpdate::State(CallState::Connected {
1751 since: Instant::now(),
1752 }));
1753 assert!(!model.can_record());
1754 model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me")]));
1755 assert!(model.can_record());
1756 model.apply(CallUpdate::Recording(true));
1757 model.apply(CallUpdate::ConsentRequired(true));
1758 assert!(model.recording && model.consent_required);
1759 model.apply(CallUpdate::ConsentRequired(false));
1760 assert!(model.recording && !model.consent_required);
1761 model.apply(CallUpdate::Recording(false));
1762 assert!(!model.recording);
1763 }
1764
1765 #[test]
1766 fn a_whiteboard_share_names_the_presenter_and_offers_the_browser_only_with_a_link() {
1767 let mut model = meeting_with_me();
1768 model.apply(CallUpdate::Roster(vec![entry(
1769 "8:orgid:ana",
1770 "Ana",
1771 false,
1772 false,
1773 )]));
1774 assert_eq!(model.whiteboard_label(), None);
1775 let share = |presenter: &str, url: Option<&str>| calling::ContentShare {
1776 session_id: "s".into(),
1777 presenter: Some(presenter.into()),
1778 subject: "Whiteboard".into(),
1779 url: url.map(str::to_owned),
1780 whiteboard: true,
1781 };
1782 model.apply(CallUpdate::Whiteboard(Some(share(
1783 "8:orgid:ana",
1784 Some("https://app.whiteboard.microsoft.com/x"),
1785 ))));
1786 assert_eq!(
1787 model.whiteboard_label().as_deref(),
1788 Some("Ana is sharing a whiteboard")
1789 );
1790 assert_eq!(
1791 model.whiteboard_url(),
1792 Some("https://app.whiteboard.microsoft.com/x")
1793 );
1794 model.apply(CallUpdate::Whiteboard(Some(share(
1795 "8:orgid:stranger",
1796 None,
1797 ))));
1798 assert_eq!(
1799 model.whiteboard_label().as_deref(),
1800 Some("Someone is sharing a whiteboard")
1801 );
1802 assert_eq!(model.whiteboard_url(), None);
1803 model.apply(CallUpdate::Whiteboard(None));
1804 assert_eq!(model.whiteboard_label(), None);
1805 }
1806
1807 #[test]
1808 fn a_consultation_can_transfer_once_connected_with_a_replacement_link() {
1809 let (handle, _control) = calling::call_channel();
1810 let mut consult = ConsultCall {
1811 id: 3,
1812 target: ("8:orgid:ana".into(), "Ana".into()),
1813 commands: handle.commands,
1814 state: CallState::Connecting,
1815 replacement: None,
1816 transferring: false,
1817 };
1818 assert_eq!(consult.status_text(), "Calling Ana...");
1819 assert!(!consult.ready_to_transfer());
1820 consult.state = CallState::Connected {
1821 since: Instant::now(),
1822 };
1823 assert_eq!(consult.status_text(), "Consulting Ana");
1824 assert!(!consult.ready_to_transfer());
1825 consult.replacement = Some("https://cc/replacement".into());
1826 assert!(consult.ready_to_transfer());
1827 }
1828}