BlueGit

ict rusty-teams

Files

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

model.rs

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