BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / organizer.rs

organizer.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
organizer.rs 22.7 KiB Download Raw
1use serde_json::{Value, json};
2
3use crate::roster::{AttendeeLimits, MeetingRole};
4use crate::signaling::{Callee, MEETING_MESSAGE_ID, MeetingTarget};
5use crate::trouter_events::{CallbackLinks, find_key};
6
7const SPOTLIGHT: &str = "spotlight";
8const AUDIO: &str = "audio";
9const SPECIFIED: &str = "specified";
10const PRESENTER: &str = "presenter";
11const DISABLE_AUDIO: &str = "DisableAudio";
12const DISABLE_VIDEO: &str = "DisableVideo";
13const DISABLE_AUDIO_AND_VIDEO: &str = "DisableAv";
14const UNRESTRICTED: &str = "UnRestricted";
15const RECORDER_NONE: &str = "None";
16const RECORDER_ORGANIZERS: &str = "OrganizerAndCoOrganizersOnly";
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
19pub enum RecorderOption {
20 #[default]
21 OrganizersAndPresenters,
22 OrganizersOnly,
23 Nobody,
24}
25
26impl RecorderOption {
27 fn parse(text: &str) -> Self {
28 match text {
29 RECORDER_NONE => RecorderOption::Nobody,
30 RECORDER_ORGANIZERS => RecorderOption::OrganizersOnly,
31 _ => RecorderOption::OrganizersAndPresenters,
32 }
33 }
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub struct MeetingCapability {
38 pub locked: bool,
39 pub attendee_mic_off: bool,
40 pub attendee_camera_off: bool,
41 pub recorder_option: RecorderOption,
42 pub allow_cloud_recording: Option<bool>,
43 pub allow_transcription: Option<bool>,
44}
45
46impl MeetingCapability {
47 pub fn apply(&mut self, body: &Value) -> bool {
48 let Some(capability) = find_key(body, "meetingCapability") else {
49 return false;
50 };
51 let before = *self;
52 if let Some(locked) = capability["lockMeeting"].as_bool() {
53 self.locked = locked;
54 }
55 if let Some(restrictions) = capability["attendeeRestrictions"].as_str() {
56 let both = restrictions.contains(DISABLE_AUDIO_AND_VIDEO);
57 self.attendee_mic_off = both || restrictions.contains(DISABLE_AUDIO);
58 self.attendee_camera_off = both || restrictions.contains(DISABLE_VIDEO);
59 }
60 if let Some(option) = capability["recorderOption"].as_str() {
61 self.recorder_option = RecorderOption::parse(option);
62 }
63 if let Some(allowed) = capability["allowCloudRecording"].as_bool() {
64 self.allow_cloud_recording = Some(allowed);
65 }
66 if let Some(allowed) = capability["allowTranscription"].as_bool() {
67 self.allow_transcription = Some(allowed);
68 }
69 *self != before
70 }
71}
72
73pub fn restrictions_value(mic_off: bool, camera_off: bool) -> String {
74 let flags: Vec<&str> = [(mic_off, DISABLE_AUDIO), (camera_off, DISABLE_VIDEO)]
75 .into_iter()
76 .filter_map(|(on, flag)| on.then_some(flag))
77 .collect();
78 if flags.is_empty() {
79 UNRESTRICTED.to_owned()
80 } else {
81 flags.join(",")
82 }
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum Modality {
87 Mic,
88 Camera,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum StateStep {
93 Publish(&'static str),
94 Remove(String),
95}
96
97impl Modality {
98 fn blocked_type(self) -> &'static str {
99 match self {
100 Modality::Mic => "attendeeAudioRestricted",
101 Modality::Camera => "attendeeVideoRestricted",
102 }
103 }
104
105 fn released_type(self) -> &'static str {
106 match self {
107 Modality::Mic => "attendeeModalitiesUnrestricted",
108 Modality::Camera => "attendeeVideoUnrestricted",
109 }
110 }
111
112 fn attendees_off(self, capability: MeetingCapability) -> bool {
113 match self {
114 Modality::Mic => capability.attendee_mic_off,
115 Modality::Camera => capability.attendee_camera_off,
116 }
117 }
118
119 fn states(self, limits: &AttendeeLimits) -> (Option<&str>, Option<&str>) {
120 let (blocked, released) = match self {
121 Modality::Mic => (&limits.mic_blocked, &limits.mic_released),
122 Modality::Camera => (&limits.camera_blocked, &limits.camera_released),
123 };
124 (
125 blocked.as_ref().map(|state| state.state_id.as_str()),
126 released.as_ref().map(|state| state.state_id.as_str()),
127 )
128 }
129}
130
131pub fn modality_allowed(
132 modality: Modality,
133 capability: MeetingCapability,
134 limits: &AttendeeLimits,
135) -> bool {
136 let (blocked, released) = modality.states(limits);
137 if blocked.is_some() {
138 return false;
139 }
140 !modality.attendees_off(capability) || released.is_some()
141}
142
143pub fn modality_steps(
144 modality: Modality,
145 allowed: bool,
146 capability: MeetingCapability,
147 limits: &AttendeeLimits,
148) -> Vec<StateStep> {
149 let (blocked, released) = modality.states(limits);
150 let attendees_off = modality.attendees_off(capability);
151 let mut steps = Vec::new();
152 if allowed {
153 if let Some(state_id) = blocked {
154 steps.push(StateStep::Remove(state_id.to_owned()));
155 }
156 if attendees_off && released.is_none() {
157 steps.push(StateStep::Publish(modality.released_type()));
158 }
159 } else {
160 if let Some(state_id) = released {
161 steps.push(StateStep::Remove(state_id.to_owned()));
162 }
163 if !attendees_off && blocked.is_none() {
164 steps.push(StateStep::Publish(modality.blocked_type()));
165 }
166 }
167 steps
168}
169
170#[derive(Debug, Clone, Copy)]
171pub struct Target<'a> {
172 pub mri: &'a str,
173 pub display_name: &'a str,
174}
175
176impl Target<'_> {
177 fn wire(&self) -> Value {
178 json!({"id": self.mri, "displayName": self.display_name})
179 }
180}
181
182pub fn admit_body(
183 from: Value,
184 target: Target<'_>,
185 callbacks: &CallbackLinks,
186 cause_id: &str,
187) -> Value {
188 json!({
189 "participants": {"from": from, "to": [target.wire()]},
190 "links": {
191 "admitFailure": callbacks.conversation("admitParticipantFailure"),
192 "admitSuccess": callbacks.conversation("admitParticipantSuccess"),
193 },
194 "debugContent": {"causeId": cause_id},
195 })
196}
197
198pub fn remove_participant_body(
199 from: Value,
200 target: Target<'_>,
201 callbacks: &CallbackLinks,
202) -> Value {
203 json!({
204 "participants": {"from": from, "to": [target.wire()]},
205 "links": {
206 "removeParticipantSuccess": callbacks.conversation("removeParticipantSuccess"),
207 "removeParticipantFailure": callbacks.conversation("removeParticipantFailure"),
208 },
209 })
210}
211
212pub fn mute_participants_body(from: Value, mris: &[String]) -> Value {
213 mute_body(from, SPECIFIED, mris)
214}
215
216/// Scope `all` answers 202 but mutes nobody live; `specified` with everyone listed works.
217pub fn mute_everyone_body(from: Value, others: &[String]) -> Value {
218 mute_body(from, SPECIFIED, others)
219}
220
221fn mute_body(from: Value, scope: &str, mris: &[String]) -> Value {
222 json!({
223 "from": from,
224 "scope": scope,
225 "muteParticipants": mris.iter().map(|mri| json!({"id": mri})).collect::<Vec<_>>(),
226 "mediaTypes": [AUDIO],
227 })
228}
229
230pub fn spotlight_body(from: Value, sequence_number: u32, mri: &str, own_mri: &str) -> Value {
231 let mut body = json!({
232 "from": from,
233 "publishedState": {
234 "stateType": SPOTLIGHT,
235 "level": "user",
236 "content": {},
237 "sequenceNumber": sequence_number,
238 },
239 });
240 if mri != own_mri {
241 body["scope"] = json!(SPECIFIED);
242 body["to"] = json!([{"id": mri}]);
243 }
244 body
245}
246
247pub fn lock_body(from: Value, locked: bool, sequence_number: u32) -> Value {
248 json!({"from": from, "meetingSettings": {"lockMeeting": locked}, "sequenceNumber": sequence_number})
249}
250
251pub fn role_body(from: Value, mri: &str, role: MeetingRole) -> Value {
252 json!({
253 "from": from,
254 "scope": SPECIFIED,
255 "to": [{"id": mri, "meetingRole": role.wire()}],
256 })
257}
258
259pub fn attendee_state_body(
260 from: Value,
261 state_type: &str,
262 sequence_number: u32,
263 mri: &str,
264) -> Value {
265 json!({
266 "from": from,
267 "publishedState": {
268 "stateType": state_type,
269 "level": "user",
270 "content": {},
271 "sequenceNumber": sequence_number,
272 },
273 "scope": SPECIFIED,
274 "to": [{"id": mri}],
275 })
276}
277
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct Invitee {
280 pub callee: Callee,
281 pub participant_id: String,
282}
283
284pub fn group_chat_for(thread_id: &str, meeting: bool) -> Value {
285 json!({"threadId": thread_id, "messageId": if meeting { json!(MEETING_MESSAGE_ID) } else { Value::Null }})
286}
287
288pub fn add_link_name(has_thread: bool) -> &'static str {
289 if has_thread {
290 "addParticipantAndModality"
291 } else {
292 "addParticipant"
293 }
294}
295
296pub fn add_participants_body(
297 from: Value,
298 invitees: &[Invitee],
299 group_chat: Value,
300 meeting: Option<&MeetingTarget>,
301 callbacks: &CallbackLinks,
302) -> Value {
303 let to: Vec<Value> = invitees
304 .iter()
305 .map(|invitee| {
306 let mut person = json!({
307 "id": invitee.callee.mri,
308 "displayName": invitee.callee.display_name,
309 "participantId": invitee.participant_id,
310 });
311 if meeting.is_some() {
312 person["invitationPreferences"] = json!({"requestedMeetingRoles": [PRESENTER]});
313 }
314 person
315 })
316 .collect();
317 let invitation_data = match meeting {
318 Some(meeting) => {
319 json!({"invitationData": {"meetingInfo": {"organizerId": meeting.organizer_id, "tenantId": meeting.tenant_id}}})
320 }
321 None => json!({}),
322 };
323 json!({
324 "disableUnmute": false,
325 "participants": {"from": from, "to": to},
326 "participantInvitationData": invitation_data,
327 "replacementDetails": null,
328 "groupContext": null,
329 "groupChat": group_chat,
330 "links": {
331 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
332 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
333 },
334 })
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340
341 fn callbacks() -> CallbackLinks {
342 CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1")
343 }
344
345 fn from() -> Value {
346 json!({"id": "8:orgid:me"})
347 }
348
349 fn ana() -> Target<'static> {
350 Target {
351 mri: "8:orgid:ana",
352 display_name: "Ana",
353 }
354 }
355
356 #[test]
357 fn admitting_one_names_the_person_and_both_callbacks() {
358 let body = admit_body(from(), ana(), &callbacks(), "cause-1");
359 assert_eq!(body["participants"]["from"]["id"], "8:orgid:me");
360 assert_eq!(
361 body["participants"]["to"],
362 json!([{"id": "8:orgid:ana", "displayName": "Ana"}])
363 );
364 assert!(
365 body["links"]["admitSuccess"]
366 .as_str()
367 .unwrap()
368 .contains("/conversation/admitParticipantSuccess/")
369 );
370 assert!(
371 body["links"]["admitFailure"]
372 .as_str()
373 .unwrap()
374 .contains("/conversation/admitParticipantFailure/")
375 );
376 assert_eq!(body["debugContent"]["causeId"], "cause-1");
377 }
378
379 #[test]
380 fn denying_and_removing_use_the_remove_body() {
381 let body = remove_participant_body(from(), ana(), &callbacks());
382 assert_eq!(body["participants"]["to"][0]["id"], "8:orgid:ana");
383 assert!(
384 body["links"]["removeParticipantSuccess"]
385 .as_str()
386 .unwrap()
387 .contains("/conversation/removeParticipantSuccess/")
388 );
389 assert!(
390 body["links"]["removeParticipantFailure"]
391 .as_str()
392 .unwrap()
393 .contains("/conversation/removeParticipantFailure/")
394 );
395 }
396
397 #[test]
398 fn muting_one_or_all_names_everyone_as_specified() {
399 let one = mute_participants_body(from(), &["8:orgid:ana".to_owned()]);
400 assert_eq!(one["scope"], "specified");
401 assert_eq!(one["muteParticipants"], json!([{"id": "8:orgid:ana"}]));
402 assert_eq!(one["mediaTypes"], json!(["audio"]));
403 let everyone =
404 mute_everyone_body(from(), &["8:orgid:ana".to_owned(), "8:orgid:bo".to_owned()]);
405 assert_eq!(everyone["scope"], "specified");
406 assert_eq!(everyone["muteParticipants"].as_array().unwrap().len(), 2);
407 }
408
409 #[test]
410 fn spotlighting_someone_else_is_targeted_and_self_is_not() {
411 let other = spotlight_body(from(), 4, "8:orgid:ana", "8:orgid:me");
412 assert_eq!(other["publishedState"]["stateType"], "spotlight");
413 assert_eq!(other["publishedState"]["level"], "user");
414 assert_eq!(other["publishedState"]["sequenceNumber"], 4);
415 assert_eq!(other["scope"], "specified");
416 assert_eq!(other["to"], json!([{"id": "8:orgid:ana"}]));
417 let own = spotlight_body(from(), 5, "8:orgid:me", "8:orgid:me");
418 assert!(own.get("scope").is_none());
419 assert!(own.get("to").is_none());
420 }
421
422 fn capability(mic_off: bool, camera_off: bool) -> MeetingCapability {
423 MeetingCapability {
424 attendee_mic_off: mic_off,
425 attendee_camera_off: camera_off,
426 ..MeetingCapability::default()
427 }
428 }
429
430 fn limits_with(mic_blocked: bool, mic_released: bool) -> AttendeeLimits {
431 let state = |id: &str| crate::roster::PublishedState {
432 state_id: id.to_owned(),
433 rank: 1,
434 };
435 AttendeeLimits {
436 mic_blocked: mic_blocked.then(|| state("blocked-1")),
437 mic_released: mic_released.then(|| state("released-1")),
438 ..AttendeeLimits::default()
439 }
440 }
441
442 #[test]
443 fn locking_names_the_setting_and_the_sequence_number() {
444 let body = lock_body(from(), true, 1);
445 assert_eq!(body["meetingSettings"], json!({"lockMeeting": true}));
446 assert_eq!(body["sequenceNumber"], 1);
447 assert_eq!(body["from"]["id"], "8:orgid:me");
448 assert_eq!(
449 lock_body(from(), false, 2)["meetingSettings"]["lockMeeting"],
450 false
451 );
452 }
453
454 #[test]
455 fn a_role_change_targets_one_person_with_the_wire_role() {
456 let body = role_body(from(), "8:orgid:ana", MeetingRole::Presenter);
457 assert_eq!(body["scope"], "specified");
458 assert_eq!(
459 body["to"],
460 json!([{"id": "8:orgid:ana", "meetingRole": "presenter"}])
461 );
462 assert_eq!(
463 role_body(from(), "8:orgid:ana", MeetingRole::Attendee)["to"][0]["meetingRole"],
464 "attendee"
465 );
466 }
467
468 #[test]
469 fn restricting_one_attendee_publishes_a_user_state_for_that_person() {
470 let body = attendee_state_body(from(), "attendeeAudioRestricted", 7, "8:orgid:ana");
471 assert_eq!(
472 body["publishedState"]["stateType"],
473 "attendeeAudioRestricted"
474 );
475 assert_eq!(body["publishedState"]["level"], "user");
476 assert_eq!(body["publishedState"]["sequenceNumber"], 7);
477 assert_eq!(body["scope"], "specified");
478 assert_eq!(body["to"], json!([{"id": "8:orgid:ana"}]));
479 }
480
481 #[test]
482 fn inviting_into_a_meeting_names_the_organizer_and_asks_for_the_presenter_role() {
483 let meeting = MeetingTarget {
484 thread_id: "19:meeting_x@thread.v2".into(),
485 tenant_id: "tenant-1".into(),
486 organizer_id: "organizer-1".into(),
487 meeting_data: None,
488 };
489 let invitees = [Invitee {
490 callee: Callee {
491 mri: "8:orgid:ana".into(),
492 display_name: "Ana".into(),
493 },
494 participant_id: "p-1".into(),
495 }];
496 let body = add_participants_body(
497 from(),
498 &invitees,
499 group_chat_for(&meeting.thread_id, true),
500 Some(&meeting),
501 &callbacks(),
502 );
503 assert_eq!(body["participants"]["to"][0]["id"], "8:orgid:ana");
504 assert_eq!(body["participants"]["to"][0]["participantId"], "p-1");
505 assert_eq!(
506 body["participants"]["to"][0]["invitationPreferences"]["requestedMeetingRoles"],
507 json!(["presenter"])
508 );
509 assert_eq!(
510 body["participantInvitationData"]["invitationData"]["meetingInfo"],
511 json!({"organizerId": "organizer-1", "tenantId": "tenant-1"})
512 );
513 assert_eq!(
514 body["groupChat"],
515 json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"})
516 );
517 assert!(
518 body["links"]["addParticipantSuccess"]
519 .as_str()
520 .unwrap()
521 .contains("/conversation/addParticipantSuccess/")
522 );
523 assert!(
524 body["links"]["addParticipantFailure"]
525 .as_str()
526 .unwrap()
527 .contains("/conversation/addParticipantFailure/")
528 );
529 }
530
531 #[test]
532 fn inviting_into_a_group_call_has_no_meeting_data_and_a_null_message() {
533 let invitees = [Invitee {
534 callee: Callee {
535 mri: "8:orgid:bo".into(),
536 display_name: "Bo".into(),
537 },
538 participant_id: "p-2".into(),
539 }];
540 let body = add_participants_body(
541 from(),
542 &invitees,
543 group_chat_for("19:group@thread.v2", false),
544 None,
545 &callbacks(),
546 );
547 assert_eq!(body["participantInvitationData"], json!({}));
548 assert!(
549 body["participants"]["to"][0]
550 .get("invitationPreferences")
551 .is_none()
552 );
553 assert_eq!(
554 body["groupChat"],
555 json!({"threadId": "19:group@thread.v2", "messageId": null})
556 );
557 assert_eq!(add_link_name(true), "addParticipantAndModality");
558 assert_eq!(add_link_name(false), "addParticipant");
559 }
560
561 #[test]
562 fn the_restriction_option_combines_both_flags() {
563 assert_eq!(restrictions_value(false, false), "UnRestricted");
564 assert_eq!(restrictions_value(true, false), "DisableAudio");
565 assert_eq!(restrictions_value(false, true), "DisableVideo");
566 assert_eq!(restrictions_value(true, true), "DisableAudio,DisableVideo");
567 }
568
569 #[test]
570 fn the_capability_follows_a_conversation_update() {
571 let mut state = MeetingCapability::default();
572 let update = json!({"meetingDetails": {"meetingCapability": {"lockMeeting": true, "attendeeRestrictions": "DisableAudio,DisableVideo"}}});
573 assert!(state.apply(&update));
574 assert_eq!(
575 state,
576 MeetingCapability {
577 locked: true,
578 attendee_mic_off: true,
579 attendee_camera_off: true,
580 ..MeetingCapability::default()
581 }
582 );
583 assert!(!state.apply(&update));
584 assert!(!state.apply(&json!({"other": 1})));
585 assert!(state.apply(&json!({"meetingCapability": {"lockMeeting": false, "attendeeRestrictions": "UnRestricted"}})));
586 assert_eq!(state, MeetingCapability::default());
587 }
588
589 #[test]
590 fn the_capability_reads_the_recording_and_transcription_rights() {
591 let mut state = MeetingCapability::default();
592 assert_eq!(
593 state.recorder_option,
594 RecorderOption::OrganizersAndPresenters
595 );
596 assert_eq!(
597 (state.allow_cloud_recording, state.allow_transcription),
598 (None, None)
599 );
600 let update = json!({"meetingDetails": {"meetingCapability": {"recorderOption": "OrganizerAndCoOrganizersOnly", "allowCloudRecording": false, "allowTranscription": true}}});
601 assert!(state.apply(&update));
602 assert_eq!(state.recorder_option, RecorderOption::OrganizersOnly);
603 assert_eq!(
604 (state.allow_cloud_recording, state.allow_transcription),
605 (Some(false), Some(true))
606 );
607 assert!(state.apply(&json!({"meetingCapability": {"recorderOption": "None"}})));
608 assert_eq!(state.recorder_option, RecorderOption::Nobody);
609 assert_eq!(state.allow_cloud_recording, Some(false));
610 assert!(state.apply(
611 &json!({"meetingCapability": {"recorderOption": "OrganizersAndPresentersOnly"}})
612 ));
613 assert_eq!(
614 state.recorder_option,
615 RecorderOption::OrganizersAndPresenters
616 );
617 }
618
619 #[test]
620 fn the_live_service_reports_mic_and_camera_off_as_one_value() {
621 let mut state = MeetingCapability::default();
622 assert!(state.apply(&json!({"meetingCapability": {"attendeeRestrictions": "DisableAv"}})));
623 assert!(state.attendee_mic_off && state.attendee_camera_off);
624 }
625
626 #[test]
627 fn a_mic_is_allowed_unless_blocked_or_the_meeting_blocks_everyone() {
628 let none = AttendeeLimits::default();
629 assert!(modality_allowed(
630 Modality::Mic,
631 capability(false, false),
632 &none
633 ));
634 assert!(!modality_allowed(
635 Modality::Mic,
636 capability(true, false),
637 &none
638 ));
639 assert!(modality_allowed(
640 Modality::Mic,
641 capability(true, false),
642 &limits_with(false, true)
643 ));
644 assert!(!modality_allowed(
645 Modality::Mic,
646 capability(false, false),
647 &limits_with(true, false)
648 ));
649 assert!(modality_allowed(
650 Modality::Camera,
651 capability(true, false),
652 &none
653 ));
654 }
655
656 #[test]
657 fn disabling_one_mic_publishes_a_restriction_or_drops_the_release() {
658 let open = capability(false, false);
659 assert_eq!(
660 modality_steps(Modality::Mic, false, open, &AttendeeLimits::default()),
661 vec![StateStep::Publish("attendeeAudioRestricted")]
662 );
663 let closed = capability(true, false);
664 assert_eq!(
665 modality_steps(Modality::Mic, false, closed, &limits_with(false, true)),
666 vec![StateStep::Remove("released-1".into())]
667 );
668 assert!(
669 modality_steps(Modality::Mic, false, closed, &AttendeeLimits::default()).is_empty()
670 );
671 assert!(modality_steps(Modality::Mic, false, open, &limits_with(true, false)).is_empty());
672 }
673
674 #[test]
675 fn allowing_one_mic_removes_the_restriction_or_publishes_a_release() {
676 let open = capability(false, false);
677 assert_eq!(
678 modality_steps(Modality::Mic, true, open, &limits_with(true, false)),
679 vec![StateStep::Remove("blocked-1".into())]
680 );
681 let closed = capability(true, false);
682 assert_eq!(
683 modality_steps(Modality::Mic, true, closed, &AttendeeLimits::default()),
684 vec![StateStep::Publish("attendeeModalitiesUnrestricted")]
685 );
686 assert_eq!(
687 modality_steps(
688 Modality::Camera,
689 true,
690 capability(false, true),
691 &AttendeeLimits::default()
692 ),
693 vec![StateStep::Publish("attendeeVideoUnrestricted")]
694 );
695 assert!(modality_steps(Modality::Mic, true, open, &AttendeeLimits::default()).is_empty());
696 }
697}