BlueGit

ict rusty-teams

Files

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

organizer.rs

organizer.rs 18.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 EVERYONE: &str = "all";
11const PRESENTER: &str = "presenter";
12const DISABLE_AUDIO: &str = "DisableAudio";
13const DISABLE_VIDEO: &str = "DisableVideo";
14const UNRESTRICTED: &str = "UnRestricted";
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub struct MeetingCapability {
18 pub locked: bool,
19 pub attendee_mic_off: bool,
20 pub attendee_camera_off: bool,
21}
22
23impl MeetingCapability {
24 pub fn apply(&mut self, body: &Value) -> bool {
25 let Some(capability) = find_key(body, "meetingCapability") else {
26 return false;
27 };
28 let before = *self;
29 if let Some(locked) = capability["lockMeeting"].as_bool() {
30 self.locked = locked;
31 }
32 if let Some(restrictions) = capability["attendeeRestrictions"].as_str() {
33 self.attendee_mic_off = restrictions.contains(DISABLE_AUDIO);
34 self.attendee_camera_off = restrictions.contains(DISABLE_VIDEO);
35 }
36 *self != before
37 }
38}
39
40pub fn restrictions_value(mic_off: bool, camera_off: bool) -> String {
41 let flags: Vec<&str> = [(mic_off, DISABLE_AUDIO), (camera_off, DISABLE_VIDEO)]
42 .into_iter()
43 .filter_map(|(on, flag)| on.then_some(flag))
44 .collect();
45 if flags.is_empty() {
46 UNRESTRICTED.to_owned()
47 } else {
48 flags.join(",")
49 }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Modality {
54 Mic,
55 Camera,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum StateStep {
60 Publish(&'static str),
61 Remove(String),
62}
63
64impl Modality {
65 fn blocked_type(self) -> &'static str {
66 match self {
67 Modality::Mic => "attendeeAudioRestricted",
68 Modality::Camera => "attendeeVideoRestricted",
69 }
70 }
71
72 fn released_type(self) -> &'static str {
73 match self {
74 Modality::Mic => "attendeeModalitiesUnrestricted",
75 Modality::Camera => "attendeeVideoUnrestricted",
76 }
77 }
78
79 fn attendees_off(self, capability: MeetingCapability) -> bool {
80 match self {
81 Modality::Mic => capability.attendee_mic_off,
82 Modality::Camera => capability.attendee_camera_off,
83 }
84 }
85
86 fn states(self, limits: &AttendeeLimits) -> (Option<&str>, Option<&str>) {
87 let (blocked, released) = match self {
88 Modality::Mic => (&limits.mic_blocked, &limits.mic_released),
89 Modality::Camera => (&limits.camera_blocked, &limits.camera_released),
90 };
91 (
92 blocked.as_ref().map(|state| state.state_id.as_str()),
93 released.as_ref().map(|state| state.state_id.as_str()),
94 )
95 }
96}
97
98pub fn modality_allowed(modality: Modality, capability: MeetingCapability, limits: &AttendeeLimits) -> bool {
99 let (blocked, released) = modality.states(limits);
100 if blocked.is_some() {
101 return false;
102 }
103 !modality.attendees_off(capability) || released.is_some()
104}
105
106pub fn modality_steps(modality: Modality, allowed: bool, capability: MeetingCapability, limits: &AttendeeLimits) -> Vec<StateStep> {
107 let (blocked, released) = modality.states(limits);
108 let attendees_off = modality.attendees_off(capability);
109 let mut steps = Vec::new();
110 if allowed {
111 if let Some(state_id) = blocked {
112 steps.push(StateStep::Remove(state_id.to_owned()));
113 }
114 if attendees_off && released.is_none() {
115 steps.push(StateStep::Publish(modality.released_type()));
116 }
117 } else {
118 if let Some(state_id) = released {
119 steps.push(StateStep::Remove(state_id.to_owned()));
120 }
121 if !attendees_off && blocked.is_none() {
122 steps.push(StateStep::Publish(modality.blocked_type()));
123 }
124 }
125 steps
126}
127
128#[derive(Debug, Clone, Copy)]
129pub struct Target<'a> {
130 pub mri: &'a str,
131 pub display_name: &'a str,
132}
133
134impl Target<'_> {
135 fn wire(&self) -> Value {
136 json!({"id": self.mri, "displayName": self.display_name})
137 }
138}
139
140pub fn admit_body(from: Value, target: Target<'_>, callbacks: &CallbackLinks, cause_id: &str) -> Value {
141 json!({
142 "participants": {"from": from, "to": [target.wire()]},
143 "links": {
144 "admitFailure": callbacks.conversation("admitParticipantFailure"),
145 "admitSuccess": callbacks.conversation("admitParticipantSuccess"),
146 },
147 "debugContent": {"causeId": cause_id},
148 })
149}
150
151pub fn admit_all_body(from: Value, callbacks: &CallbackLinks, operation_id: &str) -> Value {
152 json!({
153 "participants": {"from": from},
154 "links": {"admitAllStatus": callbacks.conversation("admitAllStatus")},
155 "operationId": operation_id,
156 "debugContent": {"causeId": operation_id},
157 })
158}
159
160pub fn remove_participant_body(from: Value, target: Target<'_>, callbacks: &CallbackLinks) -> Value {
161 json!({
162 "participants": {"from": from, "to": [target.wire()]},
163 "links": {
164 "removeParticipantSuccess": callbacks.conversation("removeParticipantSuccess"),
165 "removeParticipantFailure": callbacks.conversation("removeParticipantFailure"),
166 },
167 })
168}
169
170pub fn mute_participants_body(from: Value, mris: &[String]) -> Value {
171 mute_body(from, SPECIFIED, mris)
172}
173
174pub fn mute_everyone_body(from: Value, others: &[String]) -> Value {
175 mute_body(from, EVERYONE, others)
176}
177
178fn mute_body(from: Value, scope: &str, mris: &[String]) -> Value {
179 json!({
180 "from": from,
181 "scope": scope,
182 "muteParticipants": mris.iter().map(|mri| json!({"id": mri})).collect::<Vec<_>>(),
183 "mediaTypes": [AUDIO],
184 })
185}
186
187pub fn spotlight_body(from: Value, sequence_number: u32, mri: &str, own_mri: &str) -> Value {
188 let mut body = json!({
189 "from": from,
190 "publishedState": {
191 "stateType": SPOTLIGHT,
192 "level": "user",
193 "content": {},
194 "sequenceNumber": sequence_number,
195 },
196 });
197 if mri != own_mri {
198 body["scope"] = json!(SPECIFIED);
199 body["to"] = json!([{"id": mri}]);
200 }
201 body
202}
203
204pub fn lock_body(from: Value, locked: bool, sequence_number: u32) -> Value {
205 json!({"from": from, "meetingSettings": {"lockMeeting": locked}, "sequenceNumber": sequence_number})
206}
207
208pub fn role_body(from: Value, mri: &str, role: MeetingRole) -> Value {
209 json!({
210 "from": from,
211 "scope": SPECIFIED,
212 "to": [{"id": mri, "meetingRole": role.wire()}],
213 })
214}
215
216pub fn attendee_state_body(from: Value, state_type: &str, sequence_number: u32, mri: &str) -> Value {
217 json!({
218 "from": from,
219 "publishedState": {
220 "stateType": state_type,
221 "level": "user",
222 "content": {},
223 "sequenceNumber": sequence_number,
224 },
225 "scope": SPECIFIED,
226 "to": [{"id": mri}],
227 })
228}
229
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct Invitee {
232 pub callee: Callee,
233 pub participant_id: String,
234}
235
236pub fn group_chat_for(thread_id: &str, meeting: bool) -> Value {
237 json!({"threadId": thread_id, "messageId": if meeting { json!(MEETING_MESSAGE_ID) } else { Value::Null }})
238}
239
240pub fn add_link_name(has_thread: bool) -> &'static str {
241 if has_thread { "addParticipantAndModality" } else { "addParticipant" }
242}
243
244pub fn add_participants_body(
245 from: Value,
246 invitees: &[Invitee],
247 group_chat: Value,
248 meeting: Option<&MeetingTarget>,
249 callbacks: &CallbackLinks,
250) -> Value {
251 let to: Vec<Value> = invitees
252 .iter()
253 .map(|invitee| {
254 let mut person = json!({
255 "id": invitee.callee.mri,
256 "displayName": invitee.callee.display_name,
257 "participantId": invitee.participant_id,
258 });
259 if meeting.is_some() {
260 person["invitationPreferences"] = json!({"requestedMeetingRoles": [PRESENTER]});
261 }
262 person
263 })
264 .collect();
265 let invitation_data = match meeting {
266 Some(meeting) => json!({"invitationData": {"meetingInfo": {"organizerId": meeting.organizer_id, "tenantId": meeting.tenant_id}}}),
267 None => json!({}),
268 };
269 json!({
270 "disableUnmute": false,
271 "participants": {"from": from, "to": to},
272 "participantInvitationData": invitation_data,
273 "replacementDetails": null,
274 "groupContext": null,
275 "groupChat": group_chat,
276 "links": {
277 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
278 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
279 },
280 })
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 fn callbacks() -> CallbackLinks {
288 CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1")
289 }
290
291 fn from() -> Value {
292 json!({"id": "8:orgid:me"})
293 }
294
295 fn ana() -> Target<'static> {
296 Target { mri: "8:orgid:ana", display_name: "Ana" }
297 }
298
299 #[test]
300 fn admitting_one_names_the_person_and_both_callbacks() {
301 let body = admit_body(from(), ana(), &callbacks(), "cause-1");
302 assert_eq!(body["participants"]["from"]["id"], "8:orgid:me");
303 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:ana", "displayName": "Ana"}]));
304 assert!(body["links"]["admitSuccess"].as_str().unwrap().contains("/conversation/admitParticipantSuccess/"));
305 assert!(body["links"]["admitFailure"].as_str().unwrap().contains("/conversation/admitParticipantFailure/"));
306 assert_eq!(body["debugContent"]["causeId"], "cause-1");
307 }
308
309 #[test]
310 fn admitting_everyone_has_no_recipients() {
311 let body = admit_all_body(from(), &callbacks(), "op-1");
312 assert!(body["participants"].get("to").is_none());
313 assert_eq!(body["operationId"], "op-1");
314 assert!(body["links"]["admitAllStatus"].as_str().unwrap().contains("/conversation/admitAllStatus/"));
315 }
316
317 #[test]
318 fn denying_and_removing_use_the_remove_body() {
319 let body = remove_participant_body(from(), ana(), &callbacks());
320 assert_eq!(body["participants"]["to"][0]["id"], "8:orgid:ana");
321 assert!(body["links"]["removeParticipantSuccess"].as_str().unwrap().contains("/conversation/removeParticipantSuccess/"));
322 assert!(body["links"]["removeParticipantFailure"].as_str().unwrap().contains("/conversation/removeParticipantFailure/"));
323 }
324
325 #[test]
326 fn muting_one_or_all_only_changes_the_scope() {
327 let one = mute_participants_body(from(), &["8:orgid:ana".to_owned()]);
328 assert_eq!(one["scope"], "specified");
329 assert_eq!(one["muteParticipants"], json!([{"id": "8:orgid:ana"}]));
330 assert_eq!(one["mediaTypes"], json!(["audio"]));
331 let everyone = mute_everyone_body(from(), &["8:orgid:ana".to_owned(), "8:orgid:bo".to_owned()]);
332 assert_eq!(everyone["scope"], "all");
333 assert_eq!(everyone["muteParticipants"].as_array().unwrap().len(), 2);
334 }
335
336 #[test]
337 fn spotlighting_someone_else_is_targeted_and_self_is_not() {
338 let other = spotlight_body(from(), 4, "8:orgid:ana", "8:orgid:me");
339 assert_eq!(other["publishedState"]["stateType"], "spotlight");
340 assert_eq!(other["publishedState"]["level"], "user");
341 assert_eq!(other["publishedState"]["sequenceNumber"], 4);
342 assert_eq!(other["scope"], "specified");
343 assert_eq!(other["to"], json!([{"id": "8:orgid:ana"}]));
344 let own = spotlight_body(from(), 5, "8:orgid:me", "8:orgid:me");
345 assert!(own.get("scope").is_none());
346 assert!(own.get("to").is_none());
347 }
348
349 fn capability(mic_off: bool, camera_off: bool) -> MeetingCapability {
350 MeetingCapability { locked: false, attendee_mic_off: mic_off, attendee_camera_off: camera_off }
351 }
352
353 fn limits_with(mic_blocked: bool, mic_released: bool) -> AttendeeLimits {
354 let state = |id: &str| crate::roster::PublishedState { state_id: id.to_owned(), rank: 1 };
355 AttendeeLimits {
356 mic_blocked: mic_blocked.then(|| state("blocked-1")),
357 mic_released: mic_released.then(|| state("released-1")),
358 ..AttendeeLimits::default()
359 }
360 }
361
362 #[test]
363 fn locking_names_the_setting_and_the_sequence_number() {
364 let body = lock_body(from(), true, 1);
365 assert_eq!(body["meetingSettings"], json!({"lockMeeting": true}));
366 assert_eq!(body["sequenceNumber"], 1);
367 assert_eq!(body["from"]["id"], "8:orgid:me");
368 assert_eq!(lock_body(from(), false, 2)["meetingSettings"]["lockMeeting"], false);
369 }
370
371 #[test]
372 fn a_role_change_targets_one_person_with_the_wire_role() {
373 let body = role_body(from(), "8:orgid:ana", MeetingRole::Presenter);
374 assert_eq!(body["scope"], "specified");
375 assert_eq!(body["to"], json!([{"id": "8:orgid:ana", "meetingRole": "presenter"}]));
376 assert_eq!(role_body(from(), "8:orgid:ana", MeetingRole::Attendee)["to"][0]["meetingRole"], "attendee");
377 }
378
379 #[test]
380 fn restricting_one_attendee_publishes_a_user_state_for_that_person() {
381 let body = attendee_state_body(from(), "attendeeAudioRestricted", 7, "8:orgid:ana");
382 assert_eq!(body["publishedState"]["stateType"], "attendeeAudioRestricted");
383 assert_eq!(body["publishedState"]["level"], "user");
384 assert_eq!(body["publishedState"]["sequenceNumber"], 7);
385 assert_eq!(body["scope"], "specified");
386 assert_eq!(body["to"], json!([{"id": "8:orgid:ana"}]));
387 }
388
389 #[test]
390 fn inviting_into_a_meeting_names_the_organizer_and_asks_for_the_presenter_role() {
391 let meeting = MeetingTarget { thread_id: "19:meeting_x@thread.v2".into(), tenant_id: "tenant-1".into(), organizer_id: "organizer-1".into(), meeting_data: None };
392 let invitees = [Invitee { callee: Callee { mri: "8:orgid:ana".into(), display_name: "Ana".into() }, participant_id: "p-1".into() }];
393 let body = add_participants_body(from(), &invitees, group_chat_for(&meeting.thread_id, true), Some(&meeting), &callbacks());
394 assert_eq!(body["participants"]["to"][0]["id"], "8:orgid:ana");
395 assert_eq!(body["participants"]["to"][0]["participantId"], "p-1");
396 assert_eq!(body["participants"]["to"][0]["invitationPreferences"]["requestedMeetingRoles"], json!(["presenter"]));
397 assert_eq!(body["participantInvitationData"]["invitationData"]["meetingInfo"], json!({"organizerId": "organizer-1", "tenantId": "tenant-1"}));
398 assert_eq!(body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}));
399 assert!(body["links"]["addParticipantSuccess"].as_str().unwrap().contains("/conversation/addParticipantSuccess/"));
400 assert!(body["links"]["addParticipantFailure"].as_str().unwrap().contains("/conversation/addParticipantFailure/"));
401 }
402
403 #[test]
404 fn inviting_into_a_group_call_has_no_meeting_data_and_a_null_message() {
405 let invitees = [Invitee { callee: Callee { mri: "8:orgid:bo".into(), display_name: "Bo".into() }, participant_id: "p-2".into() }];
406 let body = add_participants_body(from(), &invitees, group_chat_for("19:group@thread.v2", false), None, &callbacks());
407 assert_eq!(body["participantInvitationData"], json!({}));
408 assert!(body["participants"]["to"][0].get("invitationPreferences").is_none());
409 assert_eq!(body["groupChat"], json!({"threadId": "19:group@thread.v2", "messageId": null}));
410 assert_eq!(add_link_name(true), "addParticipantAndModality");
411 assert_eq!(add_link_name(false), "addParticipant");
412 }
413
414 #[test]
415 fn the_restriction_option_combines_both_flags() {
416 assert_eq!(restrictions_value(false, false), "UnRestricted");
417 assert_eq!(restrictions_value(true, false), "DisableAudio");
418 assert_eq!(restrictions_value(false, true), "DisableVideo");
419 assert_eq!(restrictions_value(true, true), "DisableAudio,DisableVideo");
420 }
421
422 #[test]
423 fn the_capability_follows_a_conversation_update() {
424 let mut state = MeetingCapability::default();
425 let update = json!({"meetingDetails": {"meetingCapability": {"lockMeeting": true, "attendeeRestrictions": "DisableAudio,DisableVideo"}}});
426 assert!(state.apply(&update));
427 assert_eq!(state, MeetingCapability { locked: true, attendee_mic_off: true, attendee_camera_off: true });
428 assert!(!state.apply(&update));
429 assert!(!state.apply(&json!({"other": 1})));
430 assert!(state.apply(&json!({"meetingCapability": {"lockMeeting": false, "attendeeRestrictions": "UnRestricted"}})));
431 assert_eq!(state, MeetingCapability::default());
432 }
433
434 #[test]
435 fn a_mic_is_allowed_unless_blocked_or_the_meeting_blocks_everyone() {
436 let none = AttendeeLimits::default();
437 assert!(modality_allowed(Modality::Mic, capability(false, false), &none));
438 assert!(!modality_allowed(Modality::Mic, capability(true, false), &none));
439 assert!(modality_allowed(Modality::Mic, capability(true, false), &limits_with(false, true)));
440 assert!(!modality_allowed(Modality::Mic, capability(false, false), &limits_with(true, false)));
441 assert!(modality_allowed(Modality::Camera, capability(true, false), &none));
442 }
443
444 #[test]
445 fn disabling_one_mic_publishes_a_restriction_or_drops_the_release() {
446 let open = capability(false, false);
447 assert_eq!(modality_steps(Modality::Mic, false, open, &AttendeeLimits::default()), vec![StateStep::Publish("attendeeAudioRestricted")]);
448 let closed = capability(true, false);
449 assert_eq!(modality_steps(Modality::Mic, false, closed, &limits_with(false, true)), vec![StateStep::Remove("released-1".into())]);
450 assert!(modality_steps(Modality::Mic, false, closed, &AttendeeLimits::default()).is_empty());
451 assert!(modality_steps(Modality::Mic, false, open, &limits_with(true, false)).is_empty());
452 }
453
454 #[test]
455 fn allowing_one_mic_removes_the_restriction_or_publishes_a_release() {
456 let open = capability(false, false);
457 assert_eq!(modality_steps(Modality::Mic, true, open, &limits_with(true, false)), vec![StateStep::Remove("blocked-1".into())]);
458 let closed = capability(true, false);
459 assert_eq!(modality_steps(Modality::Mic, true, closed, &AttendeeLimits::default()), vec![StateStep::Publish("attendeeModalitiesUnrestricted")]);
460 assert_eq!(modality_steps(Modality::Camera, true, capability(false, true), &AttendeeLimits::default()), vec![StateStep::Publish("attendeeVideoUnrestricted")]);
461 assert!(modality_steps(Modality::Mic, true, open, &AttendeeLimits::default()).is_empty());
462 }
463}