BlueGit

ict rusty-teams

Files

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

model.rs

model.rs 57.6 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::pictures::CallPictures;
13
14pub const TEST_CALL_TITLE: &str = "Test call";
15pub const ECHO_NAME: &str = "Teams echo";
16pub const ECHO_MRI: &str = calling::signaling::ECHO_BOT_MRI;
17pub const MAX_TILES: usize = 9;
18const ORGID_PREFIX: &str = "8:orgid:";
19const WIDE_TILES: usize = 2;
20const MEDIUM_TILES: usize = 4;
21pub const REACTION_SHOWN: Duration = Duration::from_secs(3);
22const OWN_ECHO_WINDOW: Duration = Duration::from_secs(2);
23pub const CHAT_OPEN_TILES: usize = 6;
24pub const CAPTION_SHOWN: Duration = Duration::from_secs(4);
25const CAPTION_LINES: usize = 2;
26
27pub struct ActiveCall {
28 pub id: u64,
29 pub model: CallModel,
30 pub commands: UnboundedSender<CallCommand>,
31 pub viewing: bool,
32 pub conversation_id: Option<String>,
33 pub video: Arc<VideoHub>,
34 pub pictures: CallPictures,
35 pub stage_fullscreen: bool,
36 pub chat_open: bool,
37 pub meeting_target: Option<MeetingTarget>,
38 pub pending_move: Option<PendingMove>,
39 pub consult: Option<ConsultCall>,
40}
41
42#[derive(Debug, Clone, PartialEq)]
43pub struct PendingMove {
44 pub target: MeetingTarget,
45 pub title: String,
46 pub breakout: Option<BreakoutState>,
47}
48
49pub struct ConsultCall {
50 pub id: u64,
51 pub target: (String, String),
52 pub commands: UnboundedSender<CallCommand>,
53 pub state: CallState,
54 pub replacement: Option<String>,
55 pub transferring: bool,
56}
57
58impl ConsultCall {
59 pub fn connected(&self) -> bool {
60 matches!(self.state, CallState::Connected { .. })
61 }
62
63 pub fn ready_to_transfer(&self) -> bool {
64 self.connected() && self.replacement.is_some()
65 }
66
67 pub fn status_text(&self) -> String {
68 let name = &self.target.1;
69 match &self.state {
70 CallState::Connected { .. } => format!("Consulting {name}"),
71 _ => format!("Calling {name}..."),
72 }
73 }
74}
75
76impl ActiveCall {
77 pub fn new(
78 id: u64,
79 model: CallModel,
80 commands: UnboundedSender<CallCommand>,
81 conversation_id: Option<String>,
82 video: Arc<VideoHub>,
83 ) -> Self {
84 ActiveCall {
85 id,
86 model,
87 commands,
88 viewing: true,
89 conversation_id,
90 video,
91 pictures: CallPictures::default(),
92 stage_fullscreen: false,
93 chat_open: false,
94 meeting_target: None,
95 pending_move: None,
96 consult: None,
97 }
98 }
99
100 pub fn chat_thread(&self) -> Option<&str> {
101 chat_thread(
102 self.model.kind,
103 self.model.meeting_chat.as_deref(),
104 self.conversation_id.as_deref(),
105 )
106 }
107}
108
109pub fn chat_thread<'a>(
110 kind: CallKind,
111 meeting_chat: Option<&'a str>,
112 conversation_id: Option<&'a str>,
113) -> Option<&'a str> {
114 match kind {
115 CallKind::Meeting => meeting_chat.or(conversation_id),
116 CallKind::Test | CallKind::Direct | CallKind::Group => conversation_id,
117 }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum CallKind {
122 Test,
123 Direct,
124 Group,
125 Meeting,
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum TileState {
130 Invited,
131 Present,
132 InLobby,
133 Left,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Tile {
138 pub mri: String,
139 pub user_id: Option<String>,
140 pub name: String,
141 pub muted: bool,
142 pub state: TileState,
143 pub invited: bool,
144 pub has_video: bool,
145 pub hand: Option<u64>,
146 pub spotlight: Option<u64>,
147}
148
149impl Tile {
150 pub fn invited(mri: &str, name: &str) -> Tile {
151 Tile {
152 mri: mri.to_owned(),
153 user_id: mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
154 name: name.to_owned(),
155 muted: false,
156 state: TileState::Invited,
157 invited: true,
158 has_video: false,
159 hand: None,
160 spotlight: None,
161 }
162 }
163}
164
165#[derive(Debug, Clone, PartialEq)]
166pub struct BreakoutState {
167 pub room_name: String,
168 pub main: Option<MeetingTarget>,
169 pub main_title: String,
170}
171
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct Focus {
174 pub mri: String,
175 pub own: bool,
176 pub spotlight: bool,
177 pub pinned: bool,
178}
179
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub struct CaptionLine {
182 pub id: String,
183 pub speaker: String,
184 pub text: String,
185 pub at: Instant,
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub struct GridLayout {
190 pub shown_others: usize,
191 pub hidden: usize,
192}
193
194pub fn grid_layout(others: usize, max_tiles: usize) -> GridLayout {
195 let total = others + 1;
196 if total <= max_tiles {
197 return GridLayout {
198 shown_others: others,
199 hidden: 0,
200 };
201 }
202 let shown_others = max_tiles - 2;
203 GridLayout {
204 shown_others,
205 hidden: others - shown_others,
206 }
207}
208
209#[derive(Debug, Clone, Copy, PartialEq)]
210pub struct TileSize {
211 pub width: f32,
212 pub height: f32,
213 pub avatar: f32,
214}
215
216pub fn tile_size(cells: usize) -> TileSize {
217 if cells <= WIDE_TILES {
218 TileSize {
219 width: 260.,
220 height: 210.,
221 avatar: 96.,
222 }
223 } else if cells <= MEDIUM_TILES {
224 TileSize {
225 width: 220.,
226 height: 180.,
227 avatar: 72.,
228 }
229 } else {
230 TileSize {
231 width: 190.,
232 height: 150.,
233 avatar: 56.,
234 }
235 }
236}
237
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct ReactionChip {
240 pub mri: String,
241 pub reaction: Reaction,
242 pub since: Instant,
243 pub serial: u64,
244}
245
246#[derive(Debug, Clone)]
247pub struct CallModel {
248 pub title: String,
249 pub kind: CallKind,
250 pub peer_name: String,
251 pub state: CallState,
252 pub progress: Option<Progress>,
253 pub muted: bool,
254 pub listen_only: bool,
255 pub audio_off: 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 whiteboard: Option<ContentShare>,
286 pub breakout: Option<BreakoutState>,
287 pub main_meeting: Option<MeetingTarget>,
288 pub reactions: Vec<ReactionChip>,
289 reaction_serial: u64,
290 pub meeting_chat: Option<String>,
291 local_detector: SpeakingDetector,
292 remote_detector: SpeakingDetector,
293}
294
295impl CallModel {
296 fn base(kind: CallKind, title: &str, peer_name: &str, tiles: Vec<Tile>) -> Self {
297 CallModel {
298 title: title.to_owned(),
299 kind,
300 peer_name: peer_name.to_owned(),
301 state: CallState::Connecting,
302 progress: None,
303 muted: false,
304 listen_only: false,
305 audio_off: 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 whiteboard: None,
336 breakout: None,
337 main_meeting: None,
338 reactions: Vec::new(),
339 reaction_serial: 0,
340 meeting_chat: None,
341 local_detector: SpeakingDetector::default(),
342 remote_detector: SpeakingDetector::default(),
343 }
344 }
345
346 pub fn test() -> Self {
347 Self::base(
348 CallKind::Test,
349 TEST_CALL_TITLE,
350 ECHO_NAME,
351 vec![Tile::invited(ECHO_MRI, ECHO_NAME)],
352 )
353 }
354
355 pub fn people(title: &str, callees: &[(String, String)]) -> Self {
356 let kind = if callees.len() == 1 {
357 CallKind::Direct
358 } else {
359 CallKind::Group
360 };
361 let peer_name = match callees {
362 [(_, name)] => name.clone(),
363 _ => title.to_owned(),
364 };
365 let tiles = callees
366 .iter()
367 .map(|(mri, name)| Tile::invited(mri, name))
368 .collect();
369 Self::base(kind, title, &peer_name, tiles)
370 }
371
372 pub fn meeting(title: &str, can_end_meeting: bool) -> Self {
373 let mut model = Self::base(CallKind::Meeting, title, title, Vec::new());
374 model.can_end_meeting = can_end_meeting;
375 model
376 }
377
378 pub fn incoming(title: &str, caller_mri: &str, caller_name: &str) -> Self {
379 let mut model = Self::base(
380 CallKind::Direct,
381 title,
382 caller_name,
383 vec![Tile {
384 state: TileState::Present,
385 ..Tile::invited(caller_mri, caller_name)
386 }],
387 );
388 model.incoming = true;
389 model
390 }
391
392 pub fn apply(&mut self, update: CallUpdate) {
393 match update {
394 CallUpdate::State(state) => {
395 if let Some(since) = state.started_at() {
396 self.connected_since = Some(since);
397 }
398 if !matches!(state, CallState::Connected { .. }) {
399 self.silence();
400 }
401 self.state = state;
402 }
403 CallUpdate::Muted(muted) => {
404 self.muted = muted;
405 if muted {
406 self.local_speaking = false;
407 self.local_detector.reset();
408 }
409 }
410 CallUpdate::Levels { local, remote } => {
411 self.local_speaking = !self.muted && self.local_detector.update(local);
412 self.remote_speaking = self.remote_detector.update(remote);
413 }
414 CallUpdate::Devices(devices) => self.devices = devices,
415 CallUpdate::Selected { input, output } => {
416 self.input = input;
417 self.output = output;
418 }
419 CallUpdate::ListenOnly(listen_only) => self.listen_only = listen_only,
420 CallUpdate::Stats { .. } => {}
421 CallUpdate::Progress(progress) => self.progress = Some(progress),
422 CallUpdate::Roster(entries) => self.apply_roster(&entries),
423 CallUpdate::Speakers(mris) => self.speaking_mris = mris,
424 CallUpdate::Lobby(lobby) => self.lobby = lobby,
425 CallUpdate::OwnIdentity { mri } => self.own_mri = Some(mri),
426 CallUpdate::ScreenShare(sharer) => self.screen_sharer = sharer,
427 CallUpdate::VideoReady | CallUpdate::Notice(_) => {}
428 CallUpdate::Camera(on) => self.camera_on = on,
429 CallUpdate::Cameras(cameras) => self.cameras = cameras,
430 CallUpdate::LocalShare(label) => {
431 if label.is_none() {
432 self.share_sound = false;
433 }
434 self.local_share = label;
435 }
436 CallUpdate::ShareSources(sources) => self.share_sources = sources,
437 CallUpdate::ShareSound(active) => self.share_sound = active,
438 CallUpdate::OwnHand(rank) => self.own_hand = rank,
439 CallUpdate::Reaction { mri, reaction } => {
440 self.note_reaction(mri, reaction, Instant::now())
441 }
442 CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),
443 CallUpdate::Captions(state) => {
444 if state != CaptionState::On {
445 self.caption_lines.clear();
446 }
447 self.captions = state;
448 }
449 CallUpdate::Caption(entry) => self.note_caption(entry, Instant::now()),
450 CallUpdate::Recording(on) => self.recording = on,
451 CallUpdate::ConsentRequired(required) => self.consent_required = required,
452 CallUpdate::Hold(hold) => self.hold = hold,
453 CallUpdate::Whiteboard(share) => self.whiteboard = share,
454 CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
455 CallUpdate::BlurTiming(_)
456 | CallUpdate::Organizer { .. }
457 | CallUpdate::WhiteboardUrl(_)
458 | CallUpdate::BreakoutMove(_)
459 | CallUpdate::ReplacementLink(_) => {}
460 }
461 }
462
463 pub fn note_caption(&mut self, entry: CaptionEntry, at: Instant) {
464 if self.captions == CaptionState::Off {
465 return;
466 }
467 let speaker = if entry.display_name.is_empty() {
468 "Someone".to_owned()
469 } else {
470 entry.display_name
471 };
472 let line = CaptionLine {
473 id: entry.id,
474 speaker,
475 text: entry.text,
476 at,
477 };
478 match self.caption_lines.last_mut() {
479 Some(last) if last.id == line.id => *last = line,
480 _ => self.caption_lines.push(line),
481 }
482 let surplus = self.caption_lines.len().saturating_sub(CAPTION_LINES);
483 self.caption_lines.drain(..surplus);
484 }
485
486 pub fn visible_captions(&self, now: Instant) -> Vec<&CaptionLine> {
487 self.caption_lines
488 .iter()
489 .filter(|line| now.saturating_duration_since(line.at) < CAPTION_SHOWN)
490 .collect()
491 }
492
493 pub fn captions_on(&self) -> bool {
494 matches!(self.captions, CaptionState::Starting | CaptionState::On)
495 }
496
497 fn silence(&mut self) {
498 self.local_speaking = false;
499 self.remote_speaking = false;
500 self.speaking_mris.clear();
501 self.local_detector.reset();
502 self.remote_detector.reset();
503 }
504
505 pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {
506 let own_echo = Some(&mri) == self.own_mri.as_ref()
507 && self.reactions.iter().any(|chip| {
508 chip.mri == mri
509 && chip.reaction == reaction
510 && at.saturating_duration_since(chip.since) < OWN_ECHO_WINDOW
511 });
512 if own_echo {
513 return;
514 }
515 self.reactions.retain(|chip| {
516 chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN
517 });
518 self.reaction_serial += 1;
519 self.reactions.push(ReactionChip {
520 mri,
521 reaction,
522 since: at,
523 serial: self.reaction_serial,
524 });
525 }
526
527 pub fn chip_of(&self, mri: &str, now: Instant) -> Option<&ReactionChip> {
528 self.reactions.iter().find(|chip| {
529 chip.mri == mri && now.saturating_duration_since(chip.since) < REACTION_SHOWN
530 })
531 }
532
533 pub fn own_chip(&self, now: Instant) -> Option<&ReactionChip> {
534 self.chip_of(self.own_mri.as_deref()?, now)
535 }
536
537 pub fn hand_position(&self, rank: u64) -> usize {
538 let raised = self
539 .tiles
540 .iter()
541 .filter_map(|tile| tile.hand)
542 .chain(self.own_hand);
543 1 + raised.filter(|other| *other < rank).count()
544 }
545
546 pub fn can_manage(&self) -> bool {
547 self.can_end_meeting || self.organizer
548 }
549
550 pub fn organizes_meeting(&self) -> bool {
551 self.kind == CallKind::Meeting && self.can_manage()
552 }
553
554 pub fn can_lower_hands(&self) -> bool {
555 self.can_manage()
556 }
557
558 pub fn lobby_guests(&self) -> Vec<&Tile> {
559 self.tiles
560 .iter()
561 .filter(|tile| tile.state == TileState::InLobby)
562 .collect()
563 }
564
565 pub fn can_admit(&self) -> bool {
566 self.can_manage() && self.is_live() && !self.lobby
567 }
568
569 pub fn is_pinned(&self, mri: &str) -> bool {
570 self.pinned.as_deref() == Some(mri)
571 }
572
573 pub fn toggle_pin(&mut self, mri: &str) {
574 self.pinned = if self.is_pinned(mri) {
575 None
576 } else {
577 Some(mri.to_owned())
578 };
579 }
580
581 pub fn is_spotlighted(&self, mri: &str) -> bool {
582 self.own_mri.as_deref() == Some(mri) && self.own_spotlight.is_some()
583 || self
584 .tiles
585 .iter()
586 .any(|tile| tile.mri == mri && tile.spotlight.is_some())
587 }
588
589 pub fn focus(&self) -> Option<Focus> {
590 let own = |mri: &str| self.own_mri.as_deref() == Some(mri);
591 let on_stage = |mri: &str| {
592 own(mri)
593 || self
594 .visible_tiles()
595 .iter()
596 .any(|tile| tile.mri == mri && tile.state == TileState::Present)
597 };
598 if let Some(pinned) = self.pinned.as_deref().filter(|mri| on_stage(mri)) {
599 return Some(Focus {
600 mri: pinned.to_owned(),
601 own: own(pinned),
602 spotlight: self.is_spotlighted(pinned),
603 pinned: true,
604 });
605 }
606 let remote = self
607 .tiles
608 .iter()
609 .filter(|tile| tile.state == TileState::Present)
610 .filter_map(|tile| Some((tile.spotlight?, tile.mri.as_str())));
611 let (_, mri) = remote
612 .chain(self.own_spotlight.zip(self.own_mri.as_deref()))
613 .min_by_key(|(rank, _)| *rank)?;
614 Some(Focus {
615 mri: mri.to_owned(),
616 own: own(mri),
617 spotlight: true,
618 pinned: false,
619 })
620 }
621
622 pub fn any_hand_raised(&self) -> bool {
623 self.own_hand.is_some() || self.tiles.iter().any(|tile| tile.hand.is_some())
624 }
625
626 pub fn own_cell_index(&self, remote_cells: usize) -> usize {
627 let Some(own) = self.own_hand else {
628 return remote_cells;
629 };
630 let ahead = self
631 .visible_tiles()
632 .iter()
633 .filter(|tile| tile.hand.is_some_and(|rank| rank < own))
634 .count();
635 ahead.min(remote_cells)
636 }
637
638 fn apply_roster(&mut self, entries: &[RosterEntry]) {
639 let own_entry = entries
640 .iter()
641 .find(|entry| Some(&entry.mri) == self.own_mri.as_ref());
642 if let Some(entry) = own_entry {
643 self.own_hand = entry.hand.as_ref().map(|hand| hand.rank);
644 }
645 self.own_spotlight =
646 own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
647 if let Some(entry) = own_entry {
648 self.organizer = entry.organizer;
649 }
650 for entry in entries
651 .iter()
652 .filter(|entry| Some(&entry.mri) != self.own_mri.as_ref())
653 {
654 let state = if entry.in_lobby {
655 TileState::InLobby
656 } else {
657 TileState::Present
658 };
659 match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
660 Some(tile) => {
661 tile.state = state;
662 tile.muted = entry.muted;
663 tile.has_video = entry.has_video;
664 tile.hand = entry.hand.as_ref().map(|hand| hand.rank);
665 tile.spotlight = entry.spotlight.as_ref().map(|spotlight| spotlight.rank);
666 if tile.name.is_empty() {
667 tile.name = entry.display_name.clone();
668 }
669 }
670 None => self.tiles.push(Tile {
671 mri: entry.mri.clone(),
672 user_id: entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned),
673 name: entry.display_name.clone(),
674 muted: entry.muted,
675 state,
676 invited: false,
677 has_video: entry.has_video,
678 hand: entry.hand.as_ref().map(|hand| hand.rank),
679 spotlight: entry.spotlight.as_ref().map(|spotlight| spotlight.rank),
680 }),
681 }
682 }
683 let own_mri = self.own_mri.clone();
684 let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
685 if self
686 .pinned
687 .as_deref()
688 .is_some_and(|mri| !listed(mri) && Some(mri) != own_mri.as_deref())
689 {
690 self.pinned = None;
691 }
692 self.tiles.retain_mut(|tile| {
693 if listed(&tile.mri) || Some(&tile.mri) == own_mri.as_ref() {
694 return true;
695 }
696 match (tile.invited, tile.state) {
697 (true, TileState::Invited) => true,
698 (true, _) => {
699 tile.state = TileState::Left;
700 true
701 }
702 (false, _) => false,
703 }
704 });
705 }
706
707 pub fn visible_tiles(&self) -> Vec<&Tile> {
708 let mut tiles: Vec<&Tile> = self
709 .tiles
710 .iter()
711 .filter(|tile| tile.state != TileState::InLobby)
712 .collect();
713 tiles.sort_by_key(|tile| {
714 let state = match tile.state {
715 TileState::Present => 0,
716 TileState::Invited => 1,
717 _ => 2,
718 };
719 (
720 !self.is_pinned(&tile.mri),
721 tile.hand.is_none(),
722 tile.hand.unwrap_or(0),
723 state,
724 )
725 });
726 tiles
727 }
728
729 pub fn strip_tiles(&self) -> Vec<&Tile> {
730 let mut tiles = self.visible_tiles();
731 tiles.sort_by_key(|tile| {
732 (
733 !self.is_pinned(&tile.mri),
734 tile.hand.is_none(),
735 tile.hand.unwrap_or(0),
736 !self.tile_speaking(tile),
737 )
738 });
739 tiles
740 }
741
742 pub fn sharing_label(&self) -> Option<String> {
743 let sharer = self.screen_sharer.as_ref()?;
744 let name = self
745 .tiles
746 .iter()
747 .find(|tile| &tile.mri == sharer)
748 .map(|tile| tile.name.as_str())
749 .filter(|name| !name.is_empty())
750 .unwrap_or("Someone");
751 Some(format!("{name} is sharing"))
752 }
753
754 pub fn whiteboard_label(&self) -> Option<String> {
755 let share = self.whiteboard.as_ref()?;
756 let name = share
757 .presenter
758 .as_deref()
759 .and_then(|presenter| self.tiles.iter().find(|tile| tile.mri == presenter))
760 .map(|tile| tile.name.as_str())
761 .filter(|name| !name.is_empty())
762 .unwrap_or("Someone");
763 Some(format!("{name} is sharing a whiteboard"))
764 }
765
766 pub fn whiteboard_url(&self) -> Option<&str> {
767 self.whiteboard.as_ref()?.url.as_deref()
768 }
769
770 pub fn is_one_to_one(&self) -> bool {
771 self.kind == CallKind::Direct
772 }
773
774 pub fn can_hold(&self) -> bool {
775 self.is_one_to_one() && self.is_live() && self.hold != HoldState::Remote
776 }
777
778 pub fn can_transfer(&self) -> bool {
779 self.is_one_to_one() && self.is_live() && self.hold == HoldState::Active
780 }
781
782 pub fn can_record(&self) -> bool {
783 self.organizes_meeting() && self.is_live() && !self.lobby
784 }
785
786 pub fn can_open_whiteboard(&self) -> bool {
787 self.kind == CallKind::Meeting && self.is_live() && !self.lobby
788 }
789
790 pub fn tile_speaking(&self, tile: &Tile) -> bool {
791 if self.speaking_mris.contains(&tile.mri) {
792 return true;
793 }
794 let only_remote = self.tiles.len() == 1;
795 only_remote && tile.state != TileState::Left && self.remote_speaking
796 }
797
798 pub fn tile_caption(&self, tile: &Tile) -> Option<&'static str> {
799 match tile.state {
800 TileState::Invited => Some(match self.progress {
801 Some(Progress::Ringing) => "Ringing",
802 _ => "Calling...",
803 }),
804 TileState::Left => Some("Left"),
805 TileState::Present | TileState::InLobby => None,
806 }
807 }
808
809 pub fn elapsed(&self, now: Instant) -> Option<Duration> {
810 self.connected_since
811 .map(|since| now.saturating_duration_since(since))
812 }
813
814 pub fn connecting_text(&self) -> &'static str {
815 match (self.kind, self.progress) {
816 (CallKind::Meeting, _) => "Joining...",
817 (_, _) if self.incoming => "Connecting...",
818 (_, Some(Progress::Ringing)) => "Ringing",
819 _ => "Calling...",
820 }
821 }
822
823 pub fn is_active(&self) -> bool {
824 matches!(
825 self.state,
826 CallState::Connecting | CallState::Connected { .. } | CallState::Reconnecting { .. }
827 )
828 }
829
830 pub fn is_connecting(&self) -> bool {
831 matches!(self.state, CallState::Connecting)
832 }
833
834 pub fn is_reconnecting(&self) -> bool {
835 matches!(self.state, CallState::Reconnecting { .. })
836 }
837
838 pub fn ended_reason(&self) -> Option<&EndReason> {
839 match &self.state {
840 CallState::Ended { reason } => Some(reason),
841 _ => None,
842 }
843 }
844
845 pub fn timer_text(&self, now: Instant) -> String {
846 self.elapsed(now).map(format_elapsed).unwrap_or_default()
847 }
848
849 pub fn has_reaction_controls(&self) -> bool {
850 matches!(self.kind, CallKind::Group | CallKind::Meeting)
851 }
852
853 pub fn can_react(&self) -> bool {
854 self.is_live() && !self.lobby
855 }
856
857 pub fn can_use_camera(&self) -> bool {
858 !self.cameras.is_empty()
859 }
860
861 pub fn can_share(&self) -> bool {
862 !self.share_sources.is_empty() && self.is_live()
863 }
864
865 fn is_live(&self) -> bool {
866 matches!(
867 self.state,
868 CallState::Connected { .. } | CallState::Reconnecting { .. }
869 )
870 }
871
872 pub fn screens(&self) -> Vec<&ShareSource> {
873 self.share_sources
874 .iter()
875 .filter(|source| source.kind == ShareKind::Screen)
876 .collect()
877 }
878
879 pub fn windows(&self) -> Vec<&ShareSource> {
880 self.share_sources
881 .iter()
882 .filter(|source| source.kind == ShareKind::Window)
883 .collect()
884 }
885
886 pub fn can_unmute(&self) -> bool {
887 !self.listen_only && !self.audio_off
888 }
889}
890
891pub fn format_elapsed(elapsed: Duration) -> String {
892 let seconds = elapsed.as_secs();
893 let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
894 if hours > 0 {
895 format!("{hours}:{minutes:02}:{seconds:02}")
896 } else {
897 format!("{minutes:02}:{seconds:02}")
898 }
899}
900
901pub fn ended_notice(reason: &EndReason, elapsed: Option<Duration>, peer_name: &str) -> String {
902 let ended = || match elapsed {
903 Some(elapsed) => format!("Call ended {}", format_elapsed(elapsed)),
904 None => "Call ended".to_owned(),
905 };
906 match reason {
907 EndReason::Cancelled => "Call cancelled".to_owned(),
908 EndReason::Dropped => "Call dropped".to_owned(),
909 EndReason::Failed(message) => format!("Call failed: {message}"),
910 EndReason::LocalHangup => ended(),
911 EndReason::Remote(EndKind::Declined) => format!("{peer_name} declined"),
912 EndReason::Remote(EndKind::NoAnswer) => "No answer".to_owned(),
913 EndReason::Remote(EndKind::Unavailable) => format!("{peer_name} is not available"),
914 EndReason::Remote(_) => ended(),
915 }
916}
917
918#[cfg(test)]
919mod tests {
920 use super::*;
921
922 fn connected_model() -> CallModel {
923 let mut model = CallModel::test();
924 model.apply(CallUpdate::State(CallState::Connected {
925 since: Instant::now(),
926 }));
927 model
928 }
929
930 fn entry(mri: &str, name: &str, muted: bool, in_lobby: bool) -> RosterEntry {
931 RosterEntry {
932 mri: mri.into(),
933 display_name: name.into(),
934 muted,
935 in_lobby,
936 has_video: false,
937 sharing: false,
938 hand: None,
939 spotlight: None,
940 organizer: false,
941 }
942 }
943
944 fn spotlit(mri: &str, name: &str, rank: u64) -> RosterEntry {
945 RosterEntry {
946 spotlight: Some(calling::Spotlight {
947 state_id: format!("sp-{rank}"),
948 rank,
949 }),
950 ..entry(mri, name, false, false)
951 }
952 }
953
954 fn organizer_entry(mri: &str) -> RosterEntry {
955 RosterEntry {
956 organizer: true,
957 ..entry(mri, "Me", false, false)
958 }
959 }
960
961 fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {
962 RosterEntry {
963 hand: Some(calling::RaisedHand {
964 state_id: format!("s-{rank}"),
965 rank,
966 }),
967 ..entry(mri, name, false, false)
968 }
969 }
970
971 fn meeting_with_me() -> CallModel {
972 let mut model = CallModel::meeting("Standup", false);
973 model.apply(CallUpdate::OwnIdentity {
974 mri: "8:orgid:me".into(),
975 });
976 model
977 }
978
979 #[test]
980 fn elapsed_text_is_minutes_and_seconds() {
981 assert_eq!(format_elapsed(Duration::from_secs(42)), "00:42");
982 assert_eq!(format_elapsed(Duration::from_secs(61)), "01:01");
983 assert_eq!(format_elapsed(Duration::from_secs(3725)), "1:02:05");
984 }
985
986 #[test]
987 fn levels_drive_the_speaking_rings() {
988 let mut model = connected_model();
989 model.apply(CallUpdate::Levels {
990 local: 0.0,
991 remote: 0.4,
992 });
993 assert!(model.remote_speaking);
994 assert!(!model.local_speaking);
995 model.apply(CallUpdate::Levels {
996 local: 0.4,
997 remote: 0.0,
998 });
999 assert!(model.local_speaking);
1000 }
1001
1002 #[test]
1003 fn muting_switches_the_local_ring_off_at_once() {
1004 let mut model = connected_model();
1005 model.apply(CallUpdate::Levels {
1006 local: 0.5,
1007 remote: 0.0,
1008 });
1009 assert!(model.local_speaking);
1010 model.apply(CallUpdate::Muted(true));
1011 assert!(!model.local_speaking);
1012 model.apply(CallUpdate::Levels {
1013 local: 0.5,
1014 remote: 0.0,
1015 });
1016 assert!(!model.local_speaking);
1017 }
1018
1019 #[test]
1020 fn reconnecting_keeps_the_timer_and_clears_the_rings() {
1021 let mut model = connected_model();
1022 let since = model.connected_since.unwrap();
1023 model.apply(CallUpdate::Levels {
1024 local: 0.5,
1025 remote: 0.5,
1026 });
1027 model.apply(CallUpdate::State(CallState::Reconnecting { since }));
1028 assert!(model.is_reconnecting());
1029 assert_eq!(model.connected_since, Some(since));
1030 assert!(!model.remote_speaking && !model.local_speaking);
1031 }
1032
1033 #[test]
1034 fn notices_for_every_end_reason() {
1035 let elapsed = Some(Duration::from_secs(42));
1036 let notice = |reason: EndReason, elapsed| ended_notice(&reason, elapsed, "Bea");
1037 assert_eq!(notice(EndReason::LocalHangup, elapsed), "Call ended 00:42");
1038 assert_eq!(
1039 notice(EndReason::Remote(EndKind::Normal), elapsed),
1040 "Call ended 00:42"
1041 );
1042 assert_eq!(
1043 notice(EndReason::Remote(EndKind::Normal), None),
1044 "Call ended"
1045 );
1046 assert_eq!(notice(EndReason::Cancelled, None), "Call cancelled");
1047 assert_eq!(notice(EndReason::Dropped, elapsed), "Call dropped");
1048 assert_eq!(
1049 notice(EndReason::Failed("no route".into()), None),
1050 "Call failed: no route"
1051 );
1052 assert_eq!(
1053 notice(EndReason::Remote(EndKind::Declined), None),
1054 "Bea declined"
1055 );
1056 assert_eq!(
1057 notice(EndReason::Remote(EndKind::NoAnswer), None),
1058 "No answer"
1059 );
1060 assert_eq!(
1061 notice(EndReason::Remote(EndKind::Unavailable), None),
1062 "Bea is not available"
1063 );
1064 assert_eq!(
1065 notice(EndReason::Remote(EndKind::Cancelled), None),
1066 "Call ended"
1067 );
1068 assert_eq!(
1069 notice(EndReason::Remote(EndKind::Other), None),
1070 "Call ended"
1071 );
1072 assert_eq!(
1073 notice(EndReason::Remote(EndKind::AnsweredElsewhere), None),
1074 "Call ended"
1075 );
1076 }
1077
1078 #[test]
1079 fn the_connecting_text_follows_the_kind_of_call() {
1080 let mut direct = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1081 assert_eq!(direct.connecting_text(), "Calling...");
1082 direct.apply(CallUpdate::Progress(Progress::Ringing));
1083 assert_eq!(direct.connecting_text(), "Ringing");
1084 assert_eq!(
1085 CallModel::meeting("Standup", false).connecting_text(),
1086 "Joining..."
1087 );
1088 assert_eq!(
1089 CallModel::incoming("Bea", "8:orgid:b", "Bea").connecting_text(),
1090 "Connecting..."
1091 );
1092 assert_eq!(CallModel::test().connecting_text(), "Calling...");
1093 }
1094
1095 #[test]
1096 fn listen_only_blocks_unmuting() {
1097 let mut model = connected_model();
1098 assert!(model.can_unmute());
1099 model.apply(CallUpdate::ListenOnly(true));
1100 assert!(!model.can_unmute());
1101 }
1102
1103 #[test]
1104 fn a_call_without_audio_blocks_unmuting() {
1105 let mut model = connected_model();
1106 model.audio_off = 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}