BlueGit

ict rusty-teams

Files

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

organizer.rs

organizer.rs 20.5 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(modality: Modality, capability: MeetingCapability, limits: &AttendeeLimits) -> bool {
132 let (blocked, released) = modality.states(limits);
133 if blocked.is_some() {
134 return false;
135 }
136 !modality.attendees_off(capability) || released.is_some()
137}
138
139pub fn modality_steps(modality: Modality, allowed: bool, capability: MeetingCapability, limits: &AttendeeLimits) -> Vec<StateStep> {
140 let (blocked, released) = modality.states(limits);
141 let attendees_off = modality.attendees_off(capability);
142 let mut steps = Vec::new();
143 if allowed {
144 if let Some(state_id) = blocked {
145 steps.push(StateStep::Remove(state_id.to_owned()));
146 }
147 if attendees_off && released.is_none() {
148 steps.push(StateStep::Publish(modality.released_type()));
149 }
150 } else {
151 if let Some(state_id) = released {
152 steps.push(StateStep::Remove(state_id.to_owned()));
153 }
154 if !attendees_off && blocked.is_none() {
155 steps.push(StateStep::Publish(modality.blocked_type()));
156 }
157 }
158 steps
159}
160
161#[derive(Debug, Clone, Copy)]
162pub struct Target<'a> {
163 pub mri: &'a str,
164 pub display_name: &'a str,
165}
166
167impl Target<'_> {
168 fn wire(&self) -> Value {
169 json!({"id": self.mri, "displayName": self.display_name})
170 }
171}
172
173pub fn admit_body(from: Value, target: Target<'_>, callbacks: &CallbackLinks, cause_id: &str) -> Value {
174 json!({
175 "participants": {"from": from, "to": [target.wire()]},
176 "links": {
177 "admitFailure": callbacks.conversation("admitParticipantFailure"),
178 "admitSuccess": callbacks.conversation("admitParticipantSuccess"),
179 },
180 "debugContent": {"causeId": cause_id},
181 })
182}
183
184pub fn remove_participant_body(from: Value, target: Target<'_>, callbacks: &CallbackLinks) -> Value {
185 json!({
186 "participants": {"from": from, "to": [target.wire()]},
187 "links": {
188 "removeParticipantSuccess": callbacks.conversation("removeParticipantSuccess"),
189 "removeParticipantFailure": callbacks.conversation("removeParticipantFailure"),
190 },
191 })
192}
193
194pub fn mute_participants_body(from: Value, mris: &[String]) -> Value {
195 mute_body(from, SPECIFIED, mris)
196}
197
198/// Scope `all` answers 202 but mutes nobody live; `specified` with everyone listed works.
199pub fn mute_everyone_body(from: Value, others: &[String]) -> Value {
200 mute_body(from, SPECIFIED, others)
201}
202
203fn mute_body(from: Value, scope: &str, mris: &[String]) -> Value {
204 json!({
205 "from": from,
206 "scope": scope,
207 "muteParticipants": mris.iter().map(|mri| json!({"id": mri})).collect::<Vec<_>>(),
208 "mediaTypes": [AUDIO],
209 })
210}
211
212pub fn spotlight_body(from: Value, sequence_number: u32, mri: &str, own_mri: &str) -> Value {
213 let mut body = json!({
214 "from": from,
215 "publishedState": {
216 "stateType": SPOTLIGHT,
217 "level": "user",
218 "content": {},
219 "sequenceNumber": sequence_number,
220 },
221 });
222 if mri != own_mri {
223 body["scope"] = json!(SPECIFIED);
224 body["to"] = json!([{"id": mri}]);
225 }
226 body
227}
228
229pub fn lock_body(from: Value, locked: bool, sequence_number: u32) -> Value {
230 json!({"from": from, "meetingSettings": {"lockMeeting": locked}, "sequenceNumber": sequence_number})
231}
232
233pub fn role_body(from: Value, mri: &str, role: MeetingRole) -> Value {
234 json!({
235 "from": from,
236 "scope": SPECIFIED,
237 "to": [{"id": mri, "meetingRole": role.wire()}],
238 })
239}
240
241pub fn attendee_state_body(from: Value, state_type: &str, sequence_number: u32, mri: &str) -> Value {
242 json!({
243 "from": from,
244 "publishedState": {
245 "stateType": state_type,
246 "level": "user",
247 "content": {},
248 "sequenceNumber": sequence_number,
249 },
250 "scope": SPECIFIED,
251 "to": [{"id": mri}],
252 })
253}
254
255#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct Invitee {
257 pub callee: Callee,
258 pub participant_id: String,
259}
260
261pub fn group_chat_for(thread_id: &str, meeting: bool) -> Value {
262 json!({"threadId": thread_id, "messageId": if meeting { json!(MEETING_MESSAGE_ID) } else { Value::Null }})
263}
264
265pub fn add_link_name(has_thread: bool) -> &'static str {
266 if has_thread { "addParticipantAndModality" } else { "addParticipant" }
267}
268
269pub fn add_participants_body(
270 from: Value,
271 invitees: &[Invitee],
272 group_chat: Value,
273 meeting: Option<&MeetingTarget>,
274 callbacks: &CallbackLinks,
275) -> Value {
276 let to: Vec<Value> = invitees
277 .iter()
278 .map(|invitee| {
279 let mut person = json!({
280 "id": invitee.callee.mri,
281 "displayName": invitee.callee.display_name,
282 "participantId": invitee.participant_id,
283 });
284 if meeting.is_some() {
285 person["invitationPreferences"] = json!({"requestedMeetingRoles": [PRESENTER]});
286 }
287 person
288 })
289 .collect();
290 let invitation_data = match meeting {
291 Some(meeting) => json!({"invitationData": {"meetingInfo": {"organizerId": meeting.organizer_id, "tenantId": meeting.tenant_id}}}),
292 None => json!({}),
293 };
294 json!({
295 "disableUnmute": false,
296 "participants": {"from": from, "to": to},
297 "participantInvitationData": invitation_data,
298 "replacementDetails": null,
299 "groupContext": null,
300 "groupChat": group_chat,
301 "links": {
302 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
303 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
304 },
305 })
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 fn callbacks() -> CallbackLinks {
313 CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1")
314 }
315
316 fn from() -> Value {
317 json!({"id": "8:orgid:me"})
318 }
319
320 fn ana() -> Target<'static> {
321 Target { mri: "8:orgid:ana", display_name: "Ana" }
322 }
323
324 #[test]
325 fn admitting_one_names_the_person_and_both_callbacks() {
326 let body = admit_body(from(), ana(), &callbacks(), "cause-1");
327 assert_eq!(body["participants"]["from"]["id"], "8:orgid:me");
328 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:ana", "displayName": "Ana"}]));
329 assert!(body["links"]["admitSuccess"].as_str().unwrap().contains("/conversation/admitParticipantSuccess/"));
330 assert!(body["links"]["admitFailure"].as_str().unwrap().contains("/conversation/admitParticipantFailure/"));
331 assert_eq!(body["debugContent"]["causeId"], "cause-1");
332 }
333
334 #[test]
335 fn denying_and_removing_use_the_remove_body() {
336 let body = remove_participant_body(from(), ana(), &callbacks());
337 assert_eq!(body["participants"]["to"][0]["id"], "8:orgid:ana");
338 assert!(body["links"]["removeParticipantSuccess"].as_str().unwrap().contains("/conversation/removeParticipantSuccess/"));
339 assert!(body["links"]["removeParticipantFailure"].as_str().unwrap().contains("/conversation/removeParticipantFailure/"));
340 }
341
342 #[test]
343 fn muting_one_or_all_names_everyone_as_specified() {
344 let one = mute_participants_body(from(), &["8:orgid:ana".to_owned()]);
345 assert_eq!(one["scope"], "specified");
346 assert_eq!(one["muteParticipants"], json!([{"id": "8:orgid:ana"}]));
347 assert_eq!(one["mediaTypes"], json!(["audio"]));
348 let everyone = mute_everyone_body(from(), &["8:orgid:ana".to_owned(), "8:orgid:bo".to_owned()]);
349 assert_eq!(everyone["scope"], "specified");
350 assert_eq!(everyone["muteParticipants"].as_array().unwrap().len(), 2);
351 }
352
353 #[test]
354 fn spotlighting_someone_else_is_targeted_and_self_is_not() {
355 let other = spotlight_body(from(), 4, "8:orgid:ana", "8:orgid:me");
356 assert_eq!(other["publishedState"]["stateType"], "spotlight");
357 assert_eq!(other["publishedState"]["level"], "user");
358 assert_eq!(other["publishedState"]["sequenceNumber"], 4);
359 assert_eq!(other["scope"], "specified");
360 assert_eq!(other["to"], json!([{"id": "8:orgid:ana"}]));
361 let own = spotlight_body(from(), 5, "8:orgid:me", "8:orgid:me");
362 assert!(own.get("scope").is_none());
363 assert!(own.get("to").is_none());
364 }
365
366 fn capability(mic_off: bool, camera_off: bool) -> MeetingCapability {
367 MeetingCapability { attendee_mic_off: mic_off, attendee_camera_off: camera_off, ..MeetingCapability::default() }
368 }
369
370 fn limits_with(mic_blocked: bool, mic_released: bool) -> AttendeeLimits {
371 let state = |id: &str| crate::roster::PublishedState { state_id: id.to_owned(), rank: 1 };
372 AttendeeLimits {
373 mic_blocked: mic_blocked.then(|| state("blocked-1")),
374 mic_released: mic_released.then(|| state("released-1")),
375 ..AttendeeLimits::default()
376 }
377 }
378
379 #[test]
380 fn locking_names_the_setting_and_the_sequence_number() {
381 let body = lock_body(from(), true, 1);
382 assert_eq!(body["meetingSettings"], json!({"lockMeeting": true}));
383 assert_eq!(body["sequenceNumber"], 1);
384 assert_eq!(body["from"]["id"], "8:orgid:me");
385 assert_eq!(lock_body(from(), false, 2)["meetingSettings"]["lockMeeting"], false);
386 }
387
388 #[test]
389 fn a_role_change_targets_one_person_with_the_wire_role() {
390 let body = role_body(from(), "8:orgid:ana", MeetingRole::Presenter);
391 assert_eq!(body["scope"], "specified");
392 assert_eq!(body["to"], json!([{"id": "8:orgid:ana", "meetingRole": "presenter"}]));
393 assert_eq!(role_body(from(), "8:orgid:ana", MeetingRole::Attendee)["to"][0]["meetingRole"], "attendee");
394 }
395
396 #[test]
397 fn restricting_one_attendee_publishes_a_user_state_for_that_person() {
398 let body = attendee_state_body(from(), "attendeeAudioRestricted", 7, "8:orgid:ana");
399 assert_eq!(body["publishedState"]["stateType"], "attendeeAudioRestricted");
400 assert_eq!(body["publishedState"]["level"], "user");
401 assert_eq!(body["publishedState"]["sequenceNumber"], 7);
402 assert_eq!(body["scope"], "specified");
403 assert_eq!(body["to"], json!([{"id": "8:orgid:ana"}]));
404 }
405
406 #[test]
407 fn inviting_into_a_meeting_names_the_organizer_and_asks_for_the_presenter_role() {
408 let meeting = MeetingTarget { thread_id: "19:meeting_x@thread.v2".into(), tenant_id: "tenant-1".into(), organizer_id: "organizer-1".into(), meeting_data: None };
409 let invitees = [Invitee { callee: Callee { mri: "8:orgid:ana".into(), display_name: "Ana".into() }, participant_id: "p-1".into() }];
410 let body = add_participants_body(from(), &invitees, group_chat_for(&meeting.thread_id, true), Some(&meeting), &callbacks());
411 assert_eq!(body["participants"]["to"][0]["id"], "8:orgid:ana");
412 assert_eq!(body["participants"]["to"][0]["participantId"], "p-1");
413 assert_eq!(body["participants"]["to"][0]["invitationPreferences"]["requestedMeetingRoles"], json!(["presenter"]));
414 assert_eq!(body["participantInvitationData"]["invitationData"]["meetingInfo"], json!({"organizerId": "organizer-1", "tenantId": "tenant-1"}));
415 assert_eq!(body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}));
416 assert!(body["links"]["addParticipantSuccess"].as_str().unwrap().contains("/conversation/addParticipantSuccess/"));
417 assert!(body["links"]["addParticipantFailure"].as_str().unwrap().contains("/conversation/addParticipantFailure/"));
418 }
419
420 #[test]
421 fn inviting_into_a_group_call_has_no_meeting_data_and_a_null_message() {
422 let invitees = [Invitee { callee: Callee { mri: "8:orgid:bo".into(), display_name: "Bo".into() }, participant_id: "p-2".into() }];
423 let body = add_participants_body(from(), &invitees, group_chat_for("19:group@thread.v2", false), None, &callbacks());
424 assert_eq!(body["participantInvitationData"], json!({}));
425 assert!(body["participants"]["to"][0].get("invitationPreferences").is_none());
426 assert_eq!(body["groupChat"], json!({"threadId": "19:group@thread.v2", "messageId": null}));
427 assert_eq!(add_link_name(true), "addParticipantAndModality");
428 assert_eq!(add_link_name(false), "addParticipant");
429 }
430
431 #[test]
432 fn the_restriction_option_combines_both_flags() {
433 assert_eq!(restrictions_value(false, false), "UnRestricted");
434 assert_eq!(restrictions_value(true, false), "DisableAudio");
435 assert_eq!(restrictions_value(false, true), "DisableVideo");
436 assert_eq!(restrictions_value(true, true), "DisableAudio,DisableVideo");
437 }
438
439 #[test]
440 fn the_capability_follows_a_conversation_update() {
441 let mut state = MeetingCapability::default();
442 let update = json!({"meetingDetails": {"meetingCapability": {"lockMeeting": true, "attendeeRestrictions": "DisableAudio,DisableVideo"}}});
443 assert!(state.apply(&update));
444 assert_eq!(state, MeetingCapability { locked: true, attendee_mic_off: true, attendee_camera_off: true, ..MeetingCapability::default() });
445 assert!(!state.apply(&update));
446 assert!(!state.apply(&json!({"other": 1})));
447 assert!(state.apply(&json!({"meetingCapability": {"lockMeeting": false, "attendeeRestrictions": "UnRestricted"}})));
448 assert_eq!(state, MeetingCapability::default());
449 }
450
451 #[test]
452 fn the_capability_reads_the_recording_and_transcription_rights() {
453 let mut state = MeetingCapability::default();
454 assert_eq!(state.recorder_option, RecorderOption::OrganizersAndPresenters);
455 assert_eq!((state.allow_cloud_recording, state.allow_transcription), (None, None));
456 let update = json!({"meetingDetails": {"meetingCapability": {"recorderOption": "OrganizerAndCoOrganizersOnly", "allowCloudRecording": false, "allowTranscription": true}}});
457 assert!(state.apply(&update));
458 assert_eq!(state.recorder_option, RecorderOption::OrganizersOnly);
459 assert_eq!((state.allow_cloud_recording, state.allow_transcription), (Some(false), Some(true)));
460 assert!(state.apply(&json!({"meetingCapability": {"recorderOption": "None"}})));
461 assert_eq!(state.recorder_option, RecorderOption::Nobody);
462 assert_eq!(state.allow_cloud_recording, Some(false));
463 assert!(state.apply(&json!({"meetingCapability": {"recorderOption": "OrganizersAndPresentersOnly"}})));
464 assert_eq!(state.recorder_option, RecorderOption::OrganizersAndPresenters);
465 }
466
467 #[test]
468 fn the_live_service_reports_mic_and_camera_off_as_one_value() {
469 let mut state = MeetingCapability::default();
470 assert!(state.apply(&json!({"meetingCapability": {"attendeeRestrictions": "DisableAv"}})));
471 assert!(state.attendee_mic_off && state.attendee_camera_off);
472 }
473
474 #[test]
475 fn a_mic_is_allowed_unless_blocked_or_the_meeting_blocks_everyone() {
476 let none = AttendeeLimits::default();
477 assert!(modality_allowed(Modality::Mic, capability(false, false), &none));
478 assert!(!modality_allowed(Modality::Mic, capability(true, false), &none));
479 assert!(modality_allowed(Modality::Mic, capability(true, false), &limits_with(false, true)));
480 assert!(!modality_allowed(Modality::Mic, capability(false, false), &limits_with(true, false)));
481 assert!(modality_allowed(Modality::Camera, capability(true, false), &none));
482 }
483
484 #[test]
485 fn disabling_one_mic_publishes_a_restriction_or_drops_the_release() {
486 let open = capability(false, false);
487 assert_eq!(modality_steps(Modality::Mic, false, open, &AttendeeLimits::default()), vec![StateStep::Publish("attendeeAudioRestricted")]);
488 let closed = capability(true, false);
489 assert_eq!(modality_steps(Modality::Mic, false, closed, &limits_with(false, true)), vec![StateStep::Remove("released-1".into())]);
490 assert!(modality_steps(Modality::Mic, false, closed, &AttendeeLimits::default()).is_empty());
491 assert!(modality_steps(Modality::Mic, false, open, &limits_with(true, false)).is_empty());
492 }
493
494 #[test]
495 fn allowing_one_mic_removes_the_restriction_or_publishes_a_release() {
496 let open = capability(false, false);
497 assert_eq!(modality_steps(Modality::Mic, true, open, &limits_with(true, false)), vec![StateStep::Remove("blocked-1".into())]);
498 let closed = capability(true, false);
499 assert_eq!(modality_steps(Modality::Mic, true, closed, &AttendeeLimits::default()), vec![StateStep::Publish("attendeeModalitiesUnrestricted")]);
500 assert_eq!(modality_steps(Modality::Camera, true, capability(false, true), &AttendeeLimits::default()), vec![StateStep::Publish("attendeeVideoUnrestricted")]);
501 assert!(modality_steps(Modality::Mic, true, open, &AttendeeLimits::default()).is_empty());
502 }
503}