BlueGit

ict rusty-teams

Files

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

meeting_options.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
meeting_options.rs 11.9 KiB Download Raw
1use serde_json::{Value, json};
2use session::{Method, Request, SPACES, Scope, Session};
3
4use crate::error::{Error, Result};
5use crate::organizer::restrictions_value;
6use crate::signaling::{CHATSVC_REGION, MeetingTarget};
7use crate::whiteboard::encoded;
8
9const OPTIONS_SCOPE: &str = "user_impersonation";
10const READ_HOST: &str = "https://teams.microsoft.com";
11const LIVE_HOST: &str = "https://teams.cloud.microsoft";
12const AUTO_ADMITTED: &str = "AutoAdmittedUsers";
13const PRESENTER: &str = "PresenterOption";
14const RESTRICTIONS: &str = "AttendeeRestrictions";
15const MEETING_CHAT: &str = "AllowMeetingChat";
16const REACTIONS: &str = "AllowTeamsMeetingReactions";
17const AUTO_RECORD: &str = "AutoRecordAndTranscribeMode";
18const RECORD_ON: &str = "AutoRecordingAndTranscription";
19const RECORD_OFF: &str = "Off";
20const LIST: &str = "List";
21const BOOLEAN: &str = "Boolean";
22const BIT_MASK: &str = "BitMask";
23
24pub const BYPASS_CHOICES: [(&str, &str); 6] = [
25 ("Everyone", "Everyone"),
26 (
27 "EveryoneInSameAndFederatedCompany",
28 "People in my org and trusted orgs",
29 ),
30 ("EveryoneInCompany", "People in my org"),
31 (
32 "EveryoneInCompanyExcludingGuests",
33 "People in my org, no guests",
34 ),
35 ("InvitedUsers", "People I invite"),
36 ("OrganizerOnly", "Only me"),
37];
38pub const PRESENTER_CHOICES: [(&str, &str); 3] = [
39 ("Everyone", "Everyone"),
40 ("EveryoneInCompany", "People in my org"),
41 ("OrganizerOnly", "Only me"),
42];
43pub const CHAT_CHOICES: [(&str, &str); 3] = [
44 ("Enabled", "On"),
45 ("InMeeting", "In-meeting only"),
46 ("Disabled", "Off"),
47];
48
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct MeetingOptions {
51 pub bypass_lobby: String,
52 pub presenters: String,
53 pub attendee_mic: bool,
54 pub attendee_camera: bool,
55 pub meeting_chat: String,
56 pub reactions: bool,
57 pub record_automatically: bool,
58 record_mode: String,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct OptionWrite {
63 pub name: &'static str,
64 pub kind: &'static str,
65 pub value: Value,
66}
67
68impl OptionWrite {
69 pub fn restrictions(mic_off: bool, camera_off: bool) -> OptionWrite {
70 OptionWrite {
71 name: RESTRICTIONS,
72 kind: BIT_MASK,
73 value: json!(restrictions_value(mic_off, camera_off)),
74 }
75 }
76
77 fn body(&self) -> Value {
78 json!({"options": [{"name": self.name, "type": self.kind, "currentValue": self.value, "isRecommended": null}]})
79 }
80}
81
82impl MeetingOptions {
83 pub fn from_response(body: &Value) -> Option<MeetingOptions> {
84 let options = body["options"].as_array()?;
85 let current = |name: &str| {
86 options
87 .iter()
88 .find(|option| option["name"].as_str() == Some(name))
89 .map(|option| &option["currentValue"])
90 };
91 let text = |name: &str| current(name).and_then(Value::as_str).map(str::to_owned);
92 let flag = |name: &str| {
93 current(name).and_then(|value| {
94 value
95 .as_bool()
96 .or_else(|| value.as_str().map(|text| text.eq_ignore_ascii_case("true")))
97 })
98 };
99 let restrictions = text(RESTRICTIONS).unwrap_or_default();
100 let record_mode = text(AUTO_RECORD).unwrap_or_else(|| RECORD_OFF.to_owned());
101 Some(MeetingOptions {
102 bypass_lobby: text(AUTO_ADMITTED)?,
103 presenters: text(PRESENTER)?,
104 attendee_mic: !restrictions.contains("DisableAudio"),
105 attendee_camera: !restrictions.contains("DisableVideo"),
106 meeting_chat: text(MEETING_CHAT)?,
107 reactions: flag(REACTIONS).unwrap_or(true),
108 record_automatically: record_mode == RECORD_ON,
109 record_mode,
110 })
111 }
112
113 pub fn changes(&self, edited: &MeetingOptions) -> Vec<OptionWrite> {
114 let mut writes = Vec::new();
115 let mut list = |name: &'static str, before: &str, after: &str| {
116 if before != after {
117 writes.push(OptionWrite {
118 name,
119 kind: LIST,
120 value: json!(after),
121 });
122 }
123 };
124 list(AUTO_ADMITTED, &self.bypass_lobby, &edited.bypass_lobby);
125 list(PRESENTER, &self.presenters, &edited.presenters);
126 list(MEETING_CHAT, &self.meeting_chat, &edited.meeting_chat);
127 if self.record_automatically != edited.record_automatically {
128 let mode = if edited.record_automatically {
129 RECORD_ON
130 } else {
131 RECORD_OFF
132 };
133 writes.push(OptionWrite {
134 name: AUTO_RECORD,
135 kind: LIST,
136 value: json!(mode),
137 });
138 }
139 if self.reactions != edited.reactions {
140 writes.push(OptionWrite {
141 name: REACTIONS,
142 kind: BOOLEAN,
143 value: json!(edited.reactions),
144 });
145 }
146 if (self.attendee_mic, self.attendee_camera)
147 != (edited.attendee_mic, edited.attendee_camera)
148 {
149 writes.push(OptionWrite::restrictions(
150 !edited.attendee_mic,
151 !edited.attendee_camera,
152 ));
153 }
154 writes
155 }
156
157 pub fn attendees_off(&self) -> (bool, bool) {
158 (!self.attendee_mic, !self.attendee_camera)
159 }
160
161 pub fn record_mode(&self) -> &str {
162 &self.record_mode
163 }
164}
165
166fn coordinates(target: &MeetingTarget) -> String {
167 format!(
168 "{}/{}/{}",
169 encoded(&target.tenant_id),
170 encoded(&target.organizer_id),
171 encoded(&target.thread_id)
172 )
173}
174
175pub fn read_url(target: &MeetingTarget) -> String {
176 format!(
177 "{READ_HOST}/api/mt/{CHATSVC_REGION}//beta/meetings/v1/options/{}/0?monarch=true",
178 coordinates(target)
179 )
180}
181
182pub fn write_url(target: &MeetingTarget) -> String {
183 format!(
184 "{LIVE_HOST}/api/mt/{CHATSVC_REGION}/beta/meetings/v1/options/{}/0/0?monarch=true",
185 coordinates(target)
186 )
187}
188
189fn with_headers(mut request: Request, caller: &str) -> Request {
190 request.headers.extend([
191 ("X-Ms-Migration".to_owned(), "True".to_owned()),
192 ("x-ms-client-caller".to_owned(), caller.to_owned()),
193 (
194 "X-MS-Request-Id".to_owned(),
195 uuid::Uuid::new_v4().to_string(),
196 ),
197 ]);
198 request
199}
200
201fn scope() -> Scope {
202 Scope::new(SPACES, OPTIONS_SCOPE)
203}
204
205pub async fn fetch(session: &Session, target: &MeetingTarget) -> Result<MeetingOptions> {
206 let request = with_headers(Request::get(read_url(target)), "meeting-options-dialog");
207 let response = session.send(request, &scope()).await?;
208 MeetingOptions::from_response(&response.body).ok_or_else(|| {
209 Error::Signaling("meeting options answer without the expected options".into())
210 })
211}
212
213pub fn write_failed(body: &Value) -> bool {
214 body["success"].as_bool() == Some(false)
215 || body["options"].as_array().is_some_and(|options| {
216 options
217 .iter()
218 .any(|option| option["success"].as_bool() == Some(false))
219 })
220}
221
222pub async fn write(session: &Session, target: &MeetingTarget, change: &OptionWrite) -> Result<()> {
223 let mut request = with_headers(
224 Request::with_body(Method::Post, write_url(target), change.body()),
225 "meeting-options-dialog",
226 );
227 request
228 .headers
229 .push(("x-ms-test-user".to_owned(), "False".to_owned()));
230 let response = session.send(request, &scope()).await?;
231 if write_failed(&response.body) {
232 return Err(Error::Signaling(format!(
233 "the service refused {}",
234 change.name
235 )));
236 }
237 Ok(())
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 fn target() -> MeetingTarget {
245 MeetingTarget {
246 thread_id: "19:meeting_abc@thread.v2".into(),
247 tenant_id: "00000000-0000-0000-0000-000000000001".into(),
248 organizer_id: "00000000-0000-0000-0000-000000000002".into(),
249 meeting_data: None,
250 }
251 }
252
253 fn option(name: &str, kind: &str, value: Value) -> Value {
254 json!({"name": name, "type": kind, "currentValue": value, "category": "x", "isDisabled": false})
255 }
256
257 fn response() -> Value {
258 json!({"options": [
259 option("AutoAdmittedUsers", "List", json!("EveryoneInCompany")),
260 option("PresenterOption", "List", json!("Everyone")),
261 option("AttendeeRestrictions", "BitMask", json!("DisableAudio")),
262 option("AllowMeetingChat", "List", json!("InMeeting")),
263 option("AllowTeamsMeetingReactions", "Boolean", json!(true)),
264 option("AutoRecordAndTranscribeMode", "List", json!("AutoTranscriptionOnly")),
265 ], "meetingDetails": {"title": "Standup"}})
266 }
267
268 #[test]
269 fn the_read_url_keeps_the_double_slash_and_the_write_url_adds_a_zero() {
270 assert_eq!(
271 read_url(&target()),
272 "https://teams.microsoft.com/api/mt/emea//beta/meetings/v1/options/00000000-0000-0000-0000-000000000001/00000000-0000-0000-0000-000000000002/19%3Ameeting_abc%40thread.v2/0?monarch=true"
273 );
274 assert_eq!(
275 write_url(&target()),
276 "https://teams.cloud.microsoft/api/mt/emea/beta/meetings/v1/options/00000000-0000-0000-0000-000000000001/00000000-0000-0000-0000-000000000002/19%3Ameeting_abc%40thread.v2/0/0?monarch=true"
277 );
278 }
279
280 #[test]
281 fn the_read_answer_becomes_the_dialog_fields() {
282 let options = MeetingOptions::from_response(&response()).unwrap();
283 assert_eq!(options.bypass_lobby, "EveryoneInCompany");
284 assert_eq!(options.presenters, "Everyone");
285 assert!(!options.attendee_mic);
286 assert!(options.attendee_camera);
287 assert_eq!(options.meeting_chat, "InMeeting");
288 assert!(options.reactions);
289 assert!(!options.record_automatically);
290 assert_eq!(options.record_mode(), "AutoTranscriptionOnly");
291 assert!(MeetingOptions::from_response(&json!({"options": []})).is_none());
292 }
293
294 #[test]
295 fn only_changed_options_are_written() {
296 let before = MeetingOptions::from_response(&response()).unwrap();
297 assert!(before.changes(&before.clone()).is_empty());
298 let edited = MeetingOptions {
299 bypass_lobby: "OrganizerOnly".into(),
300 meeting_chat: "Disabled".into(),
301 record_automatically: true,
302 reactions: false,
303 attendee_mic: true,
304 attendee_camera: false,
305 ..before.clone()
306 };
307 let writes = before.changes(&edited);
308 let names: Vec<&str> = writes.iter().map(|write| write.name).collect();
309 assert_eq!(
310 names,
311 [
312 "AutoAdmittedUsers",
313 "AllowMeetingChat",
314 "AutoRecordAndTranscribeMode",
315 "AllowTeamsMeetingReactions",
316 "AttendeeRestrictions"
317 ]
318 );
319 assert_eq!(writes[2].value, json!("AutoRecordingAndTranscription"));
320 assert_eq!(writes[4].value, json!("DisableVideo"));
321 }
322
323 #[test]
324 fn a_write_sends_one_option_in_the_captured_shape() {
325 let write = OptionWrite {
326 name: "AllowMeetingChat",
327 kind: "List",
328 value: json!("Disabled"),
329 };
330 assert_eq!(
331 write.body(),
332 json!({"options": [{"name": "AllowMeetingChat", "type": "List", "currentValue": "Disabled", "isRecommended": null}]})
333 );
334 assert_eq!(
335 OptionWrite::restrictions(true, true).body()["options"][0]["currentValue"],
336 "DisableAudio,DisableVideo"
337 );
338 assert_eq!(
339 OptionWrite::restrictions(false, false).value,
340 json!("UnRestricted")
341 );
342 }
343
344 #[test]
345 fn a_refused_write_is_told_apart_from_an_accepted_one() {
346 assert!(!write_failed(
347 &json!({"success": true, "options": [{"success": true}]})
348 ));
349 assert!(write_failed(&json!({"success": false})));
350 assert!(write_failed(
351 &json!({"success": true, "options": [{"success": false}]})
352 ));
353 }
354}