| 1 | use std::collections::HashMap; |
| 2 | use std::path::PathBuf; |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | use calling::meeting::fetch_live_meeting; |
| 6 | use calling::relay::ic3_scope; |
| 7 | use calling::signaling::{CHATSVC_REGION, fetch_self}; |
| 8 | use calling::{ |
| 9 | CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, |
| 10 | MeetingOptions, MeetingRole, MeetingTarget, Modality, MuteCommand, Reaction, RecordingKind, |
| 11 | RosterEntry, ShareKind, ShareSource, StopScope, TileDetail, VideoKey, VideoWant, |
| 12 | }; |
| 13 | use chatsvc::InstanceNames; |
| 14 | use chatsvc::recap::Recap; |
| 15 | use serde_json::{Value, json}; |
| 16 | use session::{DEFAULT_ENDPOINT, Method, Request, SPACES, Scope, Session}; |
| 17 | |
| 18 | const CREATE_URL: &str = "https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create"; |
| 19 | const SUBJECT: &str = "Native client test"; |
| 20 | const REPORT_EVERY: Duration = Duration::from_secs(2); |
| 21 | const THREAD_PROPERTY_RETRIES: usize = 8; |
| 22 | const GONE_LIMIT: Duration = Duration::from_secs(90); |
| 23 | const GRAPH_CHATS: &str = "https://graph.microsoft.com/v1.0/chats"; |
| 24 | |
| 25 | struct Arguments { |
| 26 | link_out: Option<PathBuf>, |
| 27 | thread_out: Option<PathBuf>, |
| 28 | recap_thread: Option<String>, |
| 29 | join_thread: Option<PathBuf>, |
| 30 | } |
| 31 | |
| 32 | fn arguments() -> Arguments { |
| 33 | let mut parsed = Arguments { |
| 34 | link_out: None, |
| 35 | thread_out: None, |
| 36 | recap_thread: None, |
| 37 | join_thread: None, |
| 38 | }; |
| 39 | let mut input = std::env::args().skip(1); |
| 40 | while let Some(flag) = input.next() { |
| 41 | match flag.as_str() { |
| 42 | "--link-out" => parsed.link_out = input.next().map(PathBuf::from), |
| 43 | "--thread-out" => parsed.thread_out = input.next().map(PathBuf::from), |
| 44 | "--recap" => parsed.recap_thread = input.next(), |
| 45 | "--join-thread" => parsed.join_thread = input.next().map(PathBuf::from), |
| 46 | _ => {} |
| 47 | } |
| 48 | } |
| 49 | parsed |
| 50 | } |
| 51 | |
| 52 | fn emit(value: Value) { |
| 53 | println!("@{value}"); |
| 54 | } |
| 55 | |
| 56 | fn main() { |
| 57 | for (name, value) in [("CALLING_AUDIO", "tone"), ("CALLING_VIDEO", "pattern")] { |
| 58 | if std::env::var_os(name).is_none() { |
| 59 | // SAFETY: nothing else runs yet; the runtime below starts after this. |
| 60 | unsafe { std::env::set_var(name, value) }; |
| 61 | } |
| 62 | } |
| 63 | tokio::runtime::Runtime::new() |
| 64 | .expect("runtime") |
| 65 | .block_on(run()); |
| 66 | } |
| 67 | |
| 68 | fn as_object(value: &Value) -> Option<Value> { |
| 69 | match value { |
| 70 | Value::String(text) => serde_json::from_str(text).ok(), |
| 71 | Value::Object(_) => Some(value.clone()), |
| 72 | _ => None, |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | fn encoded(value: &str) -> String { |
| 77 | value |
| 78 | .bytes() |
| 79 | .map(|byte| match byte { |
| 80 | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { |
| 81 | (byte as char).to_string() |
| 82 | } |
| 83 | other => format!("%{other:02X}"), |
| 84 | }) |
| 85 | .collect() |
| 86 | } |
| 87 | |
| 88 | async fn tenant_and_organizer( |
| 89 | session: &Session, |
| 90 | thread_id: &str, |
| 91 | ) -> (Option<String>, Option<String>) { |
| 92 | let url = format!( |
| 93 | "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent", |
| 94 | encoded(thread_id) |
| 95 | ); |
| 96 | let Ok(response) = session.send(Request::get(url), &ic3_scope()).await else { |
| 97 | return (None, None); |
| 98 | }; |
| 99 | let properties = &response.body["properties"]; |
| 100 | let meeting = as_object(&properties["meeting"]); |
| 101 | let text = |value: &Value| { |
| 102 | value |
| 103 | .as_str() |
| 104 | .filter(|text| !text.is_empty()) |
| 105 | .map(str::to_owned) |
| 106 | }; |
| 107 | let tenant = meeting |
| 108 | .as_ref() |
| 109 | .and_then(|meeting| text(&meeting["tenantId"])) |
| 110 | .or_else(|| text(&properties["addedByTenantId"])); |
| 111 | ( |
| 112 | tenant, |
| 113 | meeting |
| 114 | .as_ref() |
| 115 | .and_then(|meeting| text(&meeting["organizerId"])), |
| 116 | ) |
| 117 | } |
| 118 | |
| 119 | fn find_text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> { |
| 120 | match value { |
| 121 | Value::Object(map) => map.iter().find_map(|(key, inner)| { |
| 122 | let direct = keys |
| 123 | .iter() |
| 124 | .any(|wanted| key.eq_ignore_ascii_case(wanted)) |
| 125 | .then(|| inner.as_str().filter(|text| !text.is_empty())) |
| 126 | .flatten(); |
| 127 | direct.or_else(|| find_text(inner, keys)) |
| 128 | }), |
| 129 | Value::Array(items) => items.iter().find_map(|item| find_text(item, keys)), |
| 130 | _ => None, |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | fn roster_json(entries: &[RosterEntry], own_mri: Option<&str>) -> Value { |
| 135 | Value::Array( |
| 136 | entries |
| 137 | .iter() |
| 138 | .map(|entry| { |
| 139 | json!({ |
| 140 | "name": if Some(entry.mri.as_str()) == own_mri { "(me)" } else { entry.display_name.as_str() }, |
| 141 | "muted": entry.muted, |
| 142 | "lobby": entry.in_lobby, |
| 143 | "video": entry.has_video, |
| 144 | "sharing": entry.sharing, |
| 145 | "hand": entry.hand.is_some(), |
| 146 | "spotlight": entry.spotlight.is_some(), |
| 147 | "organizer": entry.organizer, |
| 148 | "role": entry.role.map(|role| format!("{role:?}")), |
| 149 | "mic_blocked": entry.limits.mic_blocked.is_some(), |
| 150 | "camera_blocked": entry.limits.camera_blocked.is_some(), |
| 151 | "mic_released": entry.limits.mic_released.is_some(), |
| 152 | "camera_released": entry.limits.camera_released.is_some(), |
| 153 | }) |
| 154 | }) |
| 155 | .collect(), |
| 156 | ) |
| 157 | } |
| 158 | |
| 159 | fn options_json(options: &MeetingOptions) -> Value { |
| 160 | json!({ |
| 161 | "bypass_lobby": options.bypass_lobby, |
| 162 | "presenters": options.presenters, |
| 163 | "attendee_mic": options.attendee_mic, |
| 164 | "attendee_camera": options.attendee_camera, |
| 165 | "meeting_chat": options.meeting_chat, |
| 166 | "reactions": options.reactions, |
| 167 | "record_automatically": options.record_automatically, |
| 168 | }) |
| 169 | } |
| 170 | |
| 171 | fn reaction_named(name: &str) -> Option<Reaction> { |
| 172 | Reaction::ALL |
| 173 | .into_iter() |
| 174 | .find(|reaction| format!("{reaction:?}").eq_ignore_ascii_case(name)) |
| 175 | } |
| 176 | |
| 177 | #[derive(Default)] |
| 178 | struct Window { |
| 179 | local_level: f32, |
| 180 | remote_level: f32, |
| 181 | frames: HashMap<VideoKey, (usize, u32, u32)>, |
| 182 | } |
| 183 | |
| 184 | struct Matrix { |
| 185 | session: Session, |
| 186 | thread_id: String, |
| 187 | own_mri: Option<String>, |
| 188 | roster: Vec<RosterEntry>, |
| 189 | options: Option<MeetingOptions>, |
| 190 | original_options: Option<MeetingOptions>, |
| 191 | } |
| 192 | |
| 193 | impl Matrix { |
| 194 | fn mri_of(&self, name: &str) -> Option<String> { |
| 195 | self.roster |
| 196 | .iter() |
| 197 | .find(|entry| entry.display_name.eq_ignore_ascii_case(name)) |
| 198 | .or_else(|| { |
| 199 | self.roster.iter().find(|entry| { |
| 200 | entry |
| 201 | .display_name |
| 202 | .to_lowercase() |
| 203 | .contains(&name.to_lowercase()) |
| 204 | }) |
| 205 | }) |
| 206 | .map(|entry| entry.mri.clone()) |
| 207 | } |
| 208 | |
| 209 | fn name_of(&self, key: &VideoKey) -> String { |
| 210 | match key { |
| 211 | VideoKey::Person(mri) => self |
| 212 | .roster |
| 213 | .iter() |
| 214 | .find(|entry| &entry.mri == mri) |
| 215 | .map_or_else(|| "unknown".to_owned(), |entry| entry.display_name.clone()), |
| 216 | other => format!("{other:?}"), |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | async fn command(&mut self, line: &str) -> Vec<CallCommand> { |
| 221 | let line = line.trim(); |
| 222 | let (verb, rest) = line.split_once(' ').unwrap_or((line, "")); |
| 223 | let rest = rest.trim(); |
| 224 | let person = |matrix: &Matrix, name: &str| { |
| 225 | let found = matrix.mri_of(name); |
| 226 | if found.is_none() { |
| 227 | emit( |
| 228 | json!({"event": "error", "command": verb, "reason": "no such person in the roster"}), |
| 229 | ); |
| 230 | } |
| 231 | found |
| 232 | }; |
| 233 | let on = |text: &str| matches!(text, "on" | "true" | "yes"); |
| 234 | let split_last = |text: &str| { |
| 235 | text.rsplit_once(' ') |
| 236 | .map(|(head, tail)| (head.trim().to_owned(), tail.trim().to_owned())) |
| 237 | }; |
| 238 | match verb { |
| 239 | "admit" => person(self, rest) |
| 240 | .map(|mri| vec![CallCommand::Admit { mri }]) |
| 241 | .unwrap_or_default(), |
| 242 | "deny" => person(self, rest) |
| 243 | .map(|mri| vec![CallCommand::Deny { mri }]) |
| 244 | .unwrap_or_default(), |
| 245 | "admit-all" => vec![CallCommand::AdmitAll], |
| 246 | "mute" => person(self, rest) |
| 247 | .map(|mri| vec![CallCommand::MuteParticipant { mri }]) |
| 248 | .unwrap_or_default(), |
| 249 | "mute-all" => vec![CallCommand::MuteAll], |
| 250 | "spotlight" => person(self, rest) |
| 251 | .map(|mri| vec![CallCommand::Spotlight { mri }]) |
| 252 | .unwrap_or_default(), |
| 253 | "unspotlight" => person(self, rest) |
| 254 | .map(|mri| vec![CallCommand::StopSpotlight { mri }]) |
| 255 | .unwrap_or_default(), |
| 256 | "remove" => person(self, rest) |
| 257 | .map(|mri| vec![CallCommand::RemoveParticipant { mri }]) |
| 258 | .unwrap_or_default(), |
| 259 | "lower" => person(self, rest) |
| 260 | .map(|mri| vec![CallCommand::LowerHand { mri }]) |
| 261 | .unwrap_or_default(), |
| 262 | "lower-all" => vec![CallCommand::LowerAllHands], |
| 263 | "role" => { |
| 264 | let Some((name, role)) = split_last(rest) else { |
| 265 | return Vec::new(); |
| 266 | }; |
| 267 | let role = if role == "presenter" { |
| 268 | MeetingRole::Presenter |
| 269 | } else { |
| 270 | MeetingRole::Attendee |
| 271 | }; |
| 272 | person(self, &name) |
| 273 | .map(|mri| vec![CallCommand::SetRole { mri, role }]) |
| 274 | .unwrap_or_default() |
| 275 | } |
| 276 | "allow-mic" | "allow-camera" | "block-mic" | "block-camera" => { |
| 277 | let modality = if verb.ends_with("mic") { |
| 278 | Modality::Mic |
| 279 | } else { |
| 280 | Modality::Camera |
| 281 | }; |
| 282 | let allowed = verb.starts_with("allow"); |
| 283 | person(self, rest) |
| 284 | .map(|mri| { |
| 285 | vec![CallCommand::SetAttendeeModality { |
| 286 | mri, |
| 287 | modality, |
| 288 | allowed, |
| 289 | }] |
| 290 | }) |
| 291 | .unwrap_or_default() |
| 292 | } |
| 293 | "restrict" => { |
| 294 | let mic_off = rest.contains("mic"); |
| 295 | let camera_off = rest.contains("camera"); |
| 296 | vec![CallCommand::SetAttendeeRestrictions { |
| 297 | mic_off, |
| 298 | camera_off, |
| 299 | }] |
| 300 | } |
| 301 | "lock" => vec![CallCommand::SetLock(on(rest))], |
| 302 | "options" => vec![CallCommand::LoadMeetingOptions], |
| 303 | "option" => { |
| 304 | let (Some(current), Some((name, value))) = (self.options.clone(), split_last(rest)) |
| 305 | else { |
| 306 | emit( |
| 307 | json!({"event": "error", "command": verb, "reason": "load options first"}), |
| 308 | ); |
| 309 | return Vec::new(); |
| 310 | }; |
| 311 | let mut edited = current.clone(); |
| 312 | match name.as_str() { |
| 313 | "reactions" => edited.reactions = on(&value), |
| 314 | "chat" => edited.meeting_chat = value, |
| 315 | "lobby" => edited.bypass_lobby = value, |
| 316 | "presenters" => edited.presenters = value, |
| 317 | "attendee_mic" => edited.attendee_mic = on(&value), |
| 318 | "attendee_camera" => edited.attendee_camera = on(&value), |
| 319 | _ => {} |
| 320 | } |
| 321 | vec![CallCommand::SaveMeetingOptions(current.changes(&edited))] |
| 322 | } |
| 323 | "options-restore" => match (&self.options, &self.original_options) { |
| 324 | (Some(current), Some(original)) => { |
| 325 | vec![CallCommand::SaveMeetingOptions(current.changes(original))] |
| 326 | } |
| 327 | _ => Vec::new(), |
| 328 | }, |
| 329 | "captions" => vec![CallCommand::SetCaptions(on(rest))], |
| 330 | "language" => vec![CallCommand::SetCaptionLanguage(rest.to_owned())], |
| 331 | "record" => { |
| 332 | let kind = match rest { |
| 333 | "audio" => RecordingKind::AudioOnly, |
| 334 | "transcript" => RecordingKind::TranscriptOnly, |
| 335 | _ => RecordingKind::Video, |
| 336 | }; |
| 337 | vec![CallCommand::StartRecording { |
| 338 | kind, |
| 339 | title: SUBJECT.to_owned(), |
| 340 | }] |
| 341 | } |
| 342 | "stop" => { |
| 343 | let scope = match rest { |
| 344 | "recording" => StopScope::RecordingOnly, |
| 345 | "transcription" => StopScope::TranscriptionOnly, |
| 346 | _ => StopScope::Both, |
| 347 | }; |
| 348 | vec![CallCommand::StopRecording { scope }] |
| 349 | } |
| 350 | "camera" => vec![CallCommand::SetCamera(on(rest))], |
| 351 | "share" if on(rest) => vec![CallCommand::StartShare(ShareSource { |
| 352 | id: 0, |
| 353 | kind: ShareKind::Screen, |
| 354 | title: String::new(), |
| 355 | })], |
| 356 | "share" => vec![CallCommand::StopShare], |
| 357 | "self-mute" => vec![CallCommand::Mute(if on(rest) { |
| 358 | MuteCommand::Mute |
| 359 | } else { |
| 360 | MuteCommand::Unmute |
| 361 | })], |
| 362 | "hand" => vec![CallCommand::SetHand(on(rest))], |
| 363 | "react" => reaction_named(rest) |
| 364 | .map(|reaction| vec![CallCommand::SendReaction(reaction)]) |
| 365 | .unwrap_or_default(), |
| 366 | "incoming" => vec![CallCommand::SetIncomingVideo(on(rest))], |
| 367 | "wants" => { |
| 368 | let wants = rest |
| 369 | .split(',') |
| 370 | .filter_map(|item| { |
| 371 | let (detail, name) = item.trim().split_once(':')?; |
| 372 | let detail = if detail == "stage" { |
| 373 | TileDetail::Stage |
| 374 | } else { |
| 375 | TileDetail::Small |
| 376 | }; |
| 377 | Some(VideoWant { |
| 378 | mri: self.mri_of(name)?, |
| 379 | detail, |
| 380 | }) |
| 381 | }) |
| 382 | .collect(); |
| 383 | vec![CallCommand::SetVideoWants(wants)] |
| 384 | } |
| 385 | "chat" => { |
| 386 | self.send_chat(rest).await; |
| 387 | Vec::new() |
| 388 | } |
| 389 | "chat-read" => { |
| 390 | self.read_chat().await; |
| 391 | Vec::new() |
| 392 | } |
| 393 | "end" => vec![CallCommand::EndMeeting], |
| 394 | "hangup" => vec![CallCommand::Hangup], |
| 395 | _ => { |
| 396 | emit(json!({"event": "error", "command": verb, "reason": "unknown command"})); |
| 397 | Vec::new() |
| 398 | } |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | async fn send_chat(&self, text: &str) { |
| 403 | let url = format!("{GRAPH_CHATS}/{}/messages", encoded(&self.thread_id)); |
| 404 | let body = json!({"body": {"contentType": "text", "content": text}}); |
| 405 | let outcome = self |
| 406 | .session |
| 407 | .request( |
| 408 | Method::Post, |
| 409 | &url, |
| 410 | &Scope::graph("Chat.ReadWrite"), |
| 411 | Some(body), |
| 412 | ) |
| 413 | .await; |
| 414 | emit( |
| 415 | json!({"event": "chat_sent", "status": outcome.as_ref().map(|answer| answer.status).ok(), "error": outcome.err().map(|error| error.to_string().chars().take(160).collect::<String>())}), |
| 416 | ); |
| 417 | } |
| 418 | |
| 419 | async fn read_chat(&self) { |
| 420 | let url = format!( |
| 421 | "{GRAPH_CHATS}/{}/messages?$top=20", |
| 422 | encoded(&self.thread_id) |
| 423 | ); |
| 424 | match self |
| 425 | .session |
| 426 | .request(Method::Get, &url, &Scope::graph("Chat.ReadWrite"), None) |
| 427 | .await |
| 428 | { |
| 429 | Ok(answer) => { |
| 430 | let messages: Vec<Value> = answer.body["value"] |
| 431 | .as_array() |
| 432 | .into_iter() |
| 433 | .flatten() |
| 434 | .filter(|message| message["messageType"].as_str() == Some("message")) |
| 435 | .map(|message| { |
| 436 | let sender = message.pointer("/from/user/displayName").and_then(Value::as_str).unwrap_or("?"); |
| 437 | let own = message.pointer("/from/user/id").and_then(Value::as_str).is_some_and(|id| self.own_mri.as_deref().is_some_and(|mri| mri.ends_with(id))); |
| 438 | json!({"from": if own { "(me)" } else { sender }, "text": message.pointer("/body/content").and_then(Value::as_str).unwrap_or_default().chars().take(120).collect::<String>()}) |
| 439 | }) |
| 440 | .collect(); |
| 441 | emit(json!({"event": "chat_read", "status": answer.status, "messages": messages})); |
| 442 | } |
| 443 | Err(error) => emit( |
| 444 | json!({"event": "chat_read", "error": error.to_string().chars().take(160).collect::<String>()}), |
| 445 | ), |
| 446 | } |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | async fn recap(session: &Session, thread_id: &str) { |
| 451 | let recap = Recap::new(session); |
| 452 | let occurrences = match recap.occurrences(thread_id).await { |
| 453 | Ok(occurrences) => occurrences, |
| 454 | Err(error) => { |
| 455 | emit(json!({"event": "recap", "error": format!("{error:?}")})); |
| 456 | return; |
| 457 | } |
| 458 | }; |
| 459 | emit(json!({"event": "recap_occurrences", "count": occurrences.len()})); |
| 460 | for occurrence in &occurrences { |
| 461 | match recap.details(occurrence).await { |
| 462 | Ok(details) => { |
| 463 | emit(json!({ |
| 464 | "event": "recap_recording", |
| 465 | "audio_only": details.audio_only, |
| 466 | "duration_seconds": details.duration_seconds, |
| 467 | "expires_set": details.expires_at.is_some(), |
| 468 | "transcript": details.transcript_id.is_some(), |
| 469 | })); |
| 470 | let deleted = recap.delete_recording(&details).await; |
| 471 | emit( |
| 472 | json!({"event": "recap_deleted", "ok": deleted.is_ok(), "error": deleted.err().map(|error| format!("{error:?}"))}), |
| 473 | ); |
| 474 | } |
| 475 | Err(error) => emit(json!({"event": "recap_recording", "error": format!("{error:?}")})), |
| 476 | } |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | async fn run() { |
| 481 | let arguments = arguments(); |
| 482 | let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned()); |
| 483 | let session = Session::connect(&endpoint).await.expect("browser"); |
| 484 | if let Some(thread_id) = &arguments.recap_thread { |
| 485 | recap(&session, thread_id).await; |
| 486 | return; |
| 487 | } |
| 488 | let poll_session = Session::connect(&endpoint).await.expect("browser"); |
| 489 | let me = fetch_self(&session).await.expect("own identity"); |
| 490 | let started = Instant::now(); |
| 491 | |
| 492 | let late_joiner = arguments.join_thread.is_some(); |
| 493 | let (thread_id, created_body) = match &arguments.join_thread { |
| 494 | Some(path) => ( |
| 495 | std::fs::read_to_string(path) |
| 496 | .expect("thread file") |
| 497 | .trim() |
| 498 | .to_owned(), |
| 499 | Value::Null, |
| 500 | ), |
| 501 | None => { |
| 502 | let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true}); |
| 503 | let created = session |
| 504 | .request( |
| 505 | Method::Post, |
| 506 | CREATE_URL, |
| 507 | &Scope::new(SPACES, "user_impersonation"), |
| 508 | Some(body), |
| 509 | ) |
| 510 | .await |
| 511 | .expect("create meeting"); |
| 512 | let thread_id = created |
| 513 | .body |
| 514 | .pointer("/value/groupContext/threadId") |
| 515 | .and_then(Value::as_str) |
| 516 | .expect("meeting thread") |
| 517 | .to_owned(); |
| 518 | emit(json!({"event": "created", "status": created.status})); |
| 519 | (thread_id, created.body) |
| 520 | } |
| 521 | }; |
| 522 | if let Some(path) = &arguments.thread_out { |
| 523 | std::fs::write(path, &thread_id).expect("thread file"); |
| 524 | } |
| 525 | |
| 526 | let (mut tenant_id, mut organizer_id) = tenant_and_organizer(&session, &thread_id).await; |
| 527 | for _ in 0..THREAD_PROPERTY_RETRIES { |
| 528 | if tenant_id.is_some() { |
| 529 | break; |
| 530 | } |
| 531 | tokio::time::sleep(REPORT_EVERY).await; |
| 532 | (tenant_id, organizer_id) = tenant_and_organizer(&session, &thread_id).await; |
| 533 | } |
| 534 | let target = MeetingTarget { |
| 535 | thread_id: thread_id.clone(), |
| 536 | tenant_id: tenant_id.expect("tenant id"), |
| 537 | organizer_id: organizer_id.unwrap_or_else(|| me.object_id.clone()), |
| 538 | meeting_data: None, |
| 539 | }; |
| 540 | let join_link = find_text(&created_body, &["joinUrl", "meetingJoinUrl", "joinWebUrl"]) |
| 541 | .map_or_else( |
| 542 | || { |
| 543 | let context = |
| 544 | json!({"Tid": target.tenant_id, "Oid": target.organizer_id}).to_string(); |
| 545 | format!( |
| 546 | "https://teams.microsoft.com/l/meetup-join/{}/0?context={}", |
| 547 | encoded(&thread_id), |
| 548 | encoded(&context) |
| 549 | ) |
| 550 | }, |
| 551 | str::to_owned, |
| 552 | ); |
| 553 | if let Some(path) = &arguments.link_out { |
| 554 | std::fs::write(path, &join_link).expect("link file"); |
| 555 | } |
| 556 | let config = EngineConfig { |
| 557 | ringable: false, |
| 558 | trace: std::env::var_os("LIVE_TRACE").is_some(), |
| 559 | instance: if late_joiner { |
| 560 | InstanceNames { |
| 561 | global: "__lateJoinerTrouter".into(), |
| 562 | binding: "__lateJoinerRealtime".into(), |
| 563 | endpoint_storage_key: "__lateJoinerEpid".into(), |
| 564 | } |
| 565 | } else { |
| 566 | InstanceNames { |
| 567 | global: "__liveMatrixTrouter".into(), |
| 568 | binding: "__liveMatrixRealtime".into(), |
| 569 | endpoint_storage_key: "__liveMatrixEpid".into(), |
| 570 | } |
| 571 | }, |
| 572 | ..EngineConfig::default() |
| 573 | }; |
| 574 | let (engine, _events) = CallEngine::start(session.clone(), poll_session, config) |
| 575 | .await |
| 576 | .expect("engine"); |
| 577 | let mut handle = engine.start_call(CallSpec::Meeting(target)); |
| 578 | emit(json!({"event": "joining", "after_ms": started.elapsed().as_millis()})); |
| 579 | |
| 580 | let (line_sender, mut lines) = tokio::sync::mpsc::unbounded_channel::<String>(); |
| 581 | std::thread::spawn(move || { |
| 582 | for line in std::io::stdin().lines().map_while(Result::ok) { |
| 583 | if line_sender.send(line).is_err() { |
| 584 | break; |
| 585 | } |
| 586 | } |
| 587 | }); |
| 588 | |
| 589 | let mut matrix = Matrix { |
| 590 | session: session.clone(), |
| 591 | thread_id: thread_id.clone(), |
| 592 | own_mri: None, |
| 593 | roster: Vec::new(), |
| 594 | options: None, |
| 595 | original_options: None, |
| 596 | }; |
| 597 | let mut window = Window::default(); |
| 598 | let mut last_roster = Value::Null; |
| 599 | let mut last_health = Value::Null; |
| 600 | let mut packets = (0u64, 0u64); |
| 601 | let mut ended = None; |
| 602 | let mut tick = tokio::time::interval(REPORT_EVERY); |
| 603 | while ended.is_none() { |
| 604 | tokio::select! { |
| 605 | update = handle.updates.recv() => match update { |
| 606 | Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(format!("{reason:?}")), |
| 607 | Some(CallUpdate::State(state)) => emit(json!({"event": "state", "state": format!("{state:?}").split([' ', '{', '(']).next().unwrap_or_default()})), |
| 608 | Some(CallUpdate::OwnIdentity { mri }) => matrix.own_mri = Some(mri), |
| 609 | Some(CallUpdate::Roster(entries)) => { |
| 610 | let summary = roster_json(&entries, matrix.own_mri.as_deref()); |
| 611 | if summary != last_roster { |
| 612 | emit(json!({"event": "roster", "entries": summary})); |
| 613 | last_roster = summary; |
| 614 | } |
| 615 | matrix.roster = entries; |
| 616 | } |
| 617 | Some(CallUpdate::Lobby(waiting)) => emit(json!({"event": "lobby_self", "waiting": waiting})), |
| 618 | Some(CallUpdate::Levels { local, remote }) => { |
| 619 | window.local_level = window.local_level.max(local); |
| 620 | window.remote_level = window.remote_level.max(remote); |
| 621 | } |
| 622 | Some(CallUpdate::Stats { inbound_packets, outbound_packets }) => packets = (inbound_packets, outbound_packets), |
| 623 | Some(CallUpdate::VideoReady) => { |
| 624 | for (key, picture) in handle.video.drain() { |
| 625 | let slot = window.frames.entry(key).or_insert((0, 0, 0)); |
| 626 | slot.0 += 1; |
| 627 | slot.1 = picture.width; |
| 628 | slot.2 = picture.height; |
| 629 | } |
| 630 | } |
| 631 | Some(CallUpdate::Speakers(speakers)) => { |
| 632 | let names: Vec<String> = speakers.iter().map(|mri| matrix.name_of(&VideoKey::Person(mri.clone()))).collect(); |
| 633 | emit(json!({"event": "speakers", "names": names})); |
| 634 | } |
| 635 | Some(CallUpdate::ScreenShare(sharer)) => emit(json!({"event": "screen_share", "sharer": sharer.map(|mri| matrix.name_of(&VideoKey::Person(mri)))})), |
| 636 | Some(CallUpdate::LocalShare(label)) => emit(json!({"event": "local_share", "on": label.is_some()})), |
| 637 | Some(CallUpdate::Camera(on)) => emit(json!({"event": "camera", "on": on})), |
| 638 | Some(CallUpdate::Muted(muted)) => emit(json!({"event": "muted", "muted": muted})), |
| 639 | Some(CallUpdate::OwnHand(hand)) => emit(json!({"event": "own_hand", "raised": hand.is_some()})), |
| 640 | Some(CallUpdate::Reaction { mri, reaction }) => emit(json!({"event": "reaction", "from": matrix.name_of(&VideoKey::Person(mri)), "reaction": format!("{reaction:?}")})), |
| 641 | Some(CallUpdate::Captions(state)) => emit(json!({"event": "captions", "state": match state { |
| 642 | CaptionState::Off => "off".to_owned(), |
| 643 | CaptionState::Starting => "starting".to_owned(), |
| 644 | CaptionState::On => "on".to_owned(), |
| 645 | CaptionState::Failed(reason) => format!("failed: {reason}"), |
| 646 | }})), |
| 647 | Some(CallUpdate::Caption(entry)) => { |
| 648 | if entry.is_final { |
| 649 | emit(json!({"event": "caption", "speaker": entry.display_name, "text": entry.text})); |
| 650 | } |
| 651 | } |
| 652 | Some(CallUpdate::Recording(on)) => emit(json!({"event": "recording", "on": on})), |
| 653 | Some(CallUpdate::RecordingAudioOnly(on)) => emit(json!({"event": "recording_audio_only", "on": on})), |
| 654 | Some(CallUpdate::Transcribing(on)) => emit(json!({"event": "transcribing", "on": on})), |
| 655 | Some(CallUpdate::ConsentRequired(on)) => emit(json!({"event": "consent_required", "on": on})), |
| 656 | Some(CallUpdate::Capability(capability)) => emit(json!({"event": "capability", "locked": capability.locked, "attendee_mic_off": capability.attendee_mic_off, "attendee_camera_off": capability.attendee_camera_off})), |
| 657 | Some(CallUpdate::MeetingOptions(result) | CallUpdate::MeetingOptionsSaved(result)) => match result { |
| 658 | Ok(options) => { |
| 659 | emit(json!({"event": "options", "options": options_json(&options)})); |
| 660 | if matrix.original_options.is_none() { |
| 661 | matrix.original_options = Some(options.clone()); |
| 662 | } |
| 663 | matrix.options = Some(options); |
| 664 | } |
| 665 | Err(reason) => emit(json!({"event": "options", "error": reason.chars().take(200).collect::<String>()})), |
| 666 | }, |
| 667 | Some(CallUpdate::Organizer { action, outcome }) => emit(json!({"event": "organizer", "action": action, "status": outcome.as_ref().ok(), "error": outcome.err().map(|reason| reason.chars().take(200).collect::<String>())})), |
| 668 | Some(CallUpdate::Whiteboard(share)) => emit(json!({"event": "whiteboard", "active": share.is_some()})), |
| 669 | Some(CallUpdate::BreakoutMove(_)) => emit(json!({"event": "breakout_move"})), |
| 670 | Some(CallUpdate::BreakoutRoom { .. }) => emit(json!({"event": "breakout_room"})), |
| 671 | Some(CallUpdate::MeetingChat(thread)) => emit(json!({"event": "meeting_chat", "same_thread": thread == thread_id})), |
| 672 | Some(CallUpdate::Health(health)) => { |
| 673 | let summary = json!({"event": "health", "level": format!("{:?}", health.level), "path": format!("{:?}", health.path)}); |
| 674 | if summary != last_health { |
| 675 | emit(summary.clone()); |
| 676 | last_health = summary; |
| 677 | } |
| 678 | } |
| 679 | Some(CallUpdate::Notice(text)) => emit(json!({"event": "notice", "text": text})), |
| 680 | Some(_) => {} |
| 681 | None => break, |
| 682 | }, |
| 683 | line = lines.recv() => { |
| 684 | let Some(line) = line else { continue }; |
| 685 | emit(json!({"event": "command", "line": line})); |
| 686 | for command in matrix.command(&line).await { |
| 687 | let _ = handle.commands.send(command); |
| 688 | } |
| 689 | } |
| 690 | _ = tick.tick() => { |
| 691 | let frames: serde_json::Map<String, Value> = window |
| 692 | .frames |
| 693 | .iter() |
| 694 | .map(|(key, (count, width, height))| (matrix.name_of(key), json!({"frames": count, "size": format!("{width}x{height}")}))) |
| 695 | .collect(); |
| 696 | emit(json!({ |
| 697 | "event": "stats", |
| 698 | "t": started.elapsed().as_secs(), |
| 699 | "local_level": (window.local_level * 1000.0).round() / 1000.0, |
| 700 | "remote_level": (window.remote_level * 1000.0).round() / 1000.0, |
| 701 | "inbound": packets.0, |
| 702 | "outbound": packets.1, |
| 703 | "video": frames, |
| 704 | })); |
| 705 | window = Window::default(); |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 | emit(json!({"event": "ended", "reason": ended})); |
| 710 | let gone_started = Instant::now(); |
| 711 | let mut gone = false; |
| 712 | while !late_joiner && gone_started.elapsed() < GONE_LIMIT { |
| 713 | if matches!(fetch_live_meeting(&session, &thread_id).await, Ok(None)) { |
| 714 | gone = true; |
| 715 | break; |
| 716 | } |
| 717 | tokio::time::sleep(REPORT_EVERY).await; |
| 718 | } |
| 719 | emit( |
| 720 | json!({"event": "live_state_gone", "gone": gone, "after_s": gone_started.elapsed().as_secs()}), |
| 721 | ); |
| 722 | engine.stop().await; |
| 723 | } |