BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / examples / live_matrix.rs

live_matrix.rs

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