BlueGit

ict rusty-teams

Files

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

organizer.rs

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