BlueGit

ict rusty-teams

Files

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

model.rs

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