BlueGit

ict rusty-teams

Files

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

meet_now.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
meet_now.rs 29.0 KiB Download Raw
1use std::path::PathBuf;
2use std::time::{Duration, Instant};
3
4use calling::meeting::fetch_live_meeting;
5use calling::relay::ic3_scope;
6use calling::signaling::{CHATSVC_REGION, fetch_self};
7use calling::{
8 BackgroundCache, BackgroundChoice, CallCommand, CallEngine, CallSpec, CallState, CallUpdate,
9 CaptionState, EngineConfig, MeetingTarget, MuteCommand, Reaction, RecordingKind, ShareKind,
10 ShareSource, StopScope,
11};
12use chatsvc::InstanceNames;
13use serde_json::{Value, json};
14use session::{DEFAULT_ENDPOINT, Method, Request, SPACES, Scope, Session};
15
16const CREATE_URL: &str = "https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create";
17const SUBJECT: &str = "Native client test";
18const CONNECT_LIMIT: Duration = Duration::from_secs(45);
19const LIVE_STATE_LIMIT: Duration = Duration::from_secs(30);
20const WAIT_FILE_LIMIT: Duration = Duration::from_secs(300);
21const END_LIMIT: Duration = Duration::from_secs(20);
22const GONE_LIMIT: Duration = Duration::from_secs(90);
23const POLL: Duration = Duration::from_secs(2);
24const MEDIA_DELAY: Duration = Duration::from_secs(3);
25const THREAD_PROPERTY_RETRIES: usize = 8;
26const CAPTIONS_HOLD: Duration = Duration::from_secs(10);
27const FEATURE_LIMIT: Duration = Duration::from_secs(90);
28const VIDEO_ENV: &str = "CALLING_VIDEO";
29const RECORD_HOLD: Duration = Duration::from_secs(10);
30const WHITEBOARD_WAIT: Duration = Duration::from_secs(45);
31const BACKGROUND_CACHE: &str = "calling-meet-now-backgrounds";
32
33struct Arguments {
34 resolve_by_id: bool,
35 camera: bool,
36 share: bool,
37 extras: bool,
38 spotlight_self: bool,
39 captions: bool,
40 mute_all: bool,
41 blur: bool,
42 record: bool,
43 audio_only: bool,
44 record_for: Duration,
45 unmute: bool,
46 whiteboard_state: bool,
47 background: bool,
48 stop_media_after: Option<Duration>,
49 hold: Duration,
50 thread_out: Option<PathBuf>,
51 wait_file: Option<PathBuf>,
52}
53
54fn arguments() -> Arguments {
55 let mut parsed = Arguments {
56 resolve_by_id: false,
57 camera: false,
58 share: false,
59 extras: false,
60 spotlight_self: false,
61 captions: false,
62 mute_all: false,
63 blur: false,
64 record: false,
65 audio_only: false,
66 record_for: RECORD_HOLD,
67 unmute: false,
68 whiteboard_state: false,
69 background: false,
70 stop_media_after: None,
71 hold: Duration::from_secs(10),
72 thread_out: None,
73 wait_file: None,
74 };
75 let mut input = std::env::args().skip(1);
76 while let Some(flag) = input.next() {
77 match flag.as_str() {
78 "--camera" => parsed.camera = true,
79 "--share" => parsed.share = true,
80 "--extras" => parsed.extras = true,
81 "--spotlight-self" => parsed.spotlight_self = true,
82 "--captions" => parsed.captions = true,
83 "--mute-all" => parsed.mute_all = true,
84 "--blur" => {
85 parsed.blur = true;
86 parsed.camera = true;
87 }
88 "--record" => parsed.record = true,
89 "--audio-only" => parsed.audio_only = true,
90 "--record-for" => {
91 parsed.record_for = input
92 .next()
93 .and_then(|value| value.parse().ok())
94 .map_or(RECORD_HOLD, Duration::from_secs)
95 }
96 "--unmute" => parsed.unmute = true,
97 "--whiteboard-state" => parsed.whiteboard_state = true,
98 "--resolve-by-id" => parsed.resolve_by_id = true,
99 "--background" => {
100 parsed.background = true;
101 parsed.camera = true;
102 }
103 "--stop-media-after" => {
104 parsed.stop_media_after = input
105 .next()
106 .and_then(|value| value.parse().ok())
107 .map(Duration::from_secs)
108 }
109 "--hold" => {
110 parsed.hold = Duration::from_secs(
111 input
112 .next()
113 .and_then(|value| value.parse().ok())
114 .unwrap_or(10),
115 )
116 }
117 "--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
118 "--wait-file" => parsed.wait_file = input.next().map(PathBuf::from),
119 _ => {}
120 }
121 }
122 parsed
123}
124
125fn as_object(value: &Value) -> Option<Value> {
126 match value {
127 Value::String(text) => serde_json::from_str(text).ok(),
128 Value::Object(_) => Some(value.clone()),
129 _ => None,
130 }
131}
132
133async fn tenant_and_organizer(
134 session: &Session,
135 thread_id: &str,
136) -> (Option<String>, Option<String>) {
137 let url = format!(
138 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
139 thread_id.replace(':', "%3A").replace('@', "%40")
140 );
141 let Ok(response) = session.send(Request::get(url), &ic3_scope()).await else {
142 return (None, None);
143 };
144 let properties = &response.body["properties"];
145 let meeting = as_object(&properties["meeting"]);
146 let text = |value: &Value| {
147 value
148 .as_str()
149 .filter(|text| !text.is_empty())
150 .map(str::to_owned)
151 };
152 let tenant = meeting
153 .as_ref()
154 .and_then(|meeting| text(&meeting["tenantId"]))
155 .or_else(|| text(&properties["addedByTenantId"]));
156 (
157 tenant,
158 meeting
159 .as_ref()
160 .and_then(|meeting| text(&meeting["organizerId"])),
161 )
162}
163
164fn main() {
165 let flags = arguments();
166 if (flags.blur || flags.background) && std::env::var_os(VIDEO_ENV).is_none() {
167 // SAFETY: nothing else runs yet; the runtime below starts after this.
168 unsafe { std::env::set_var(VIDEO_ENV, "pattern") };
169 }
170 tokio::runtime::Runtime::new()
171 .expect("runtime")
172 .block_on(run());
173}
174
175fn http_status(reason: &str) -> String {
176 reason
177 .split("HTTP ")
178 .nth(1)
179 .map(|rest| {
180 rest.chars()
181 .take_while(char::is_ascii_digit)
182 .collect::<String>()
183 })
184 .filter(|digits| !digits.is_empty())
185 .map_or_else(|| "no status".to_owned(), |digits| format!("HTTP {digits}"))
186}
187
188#[derive(Default)]
189struct Features {
190 own_mri: Option<String>,
191 spotlight_seen: bool,
192 spotlight_cleared: bool,
193 captions_requested: bool,
194 captions_active: bool,
195 captions_stop_due: Option<Instant>,
196 captions_stopped: bool,
197 caption_events: usize,
198 blur_reports: usize,
199 blur_total_ms: f64,
200 recording_seen_on: bool,
201 recording_seen_off: bool,
202 recording_stop_due: Option<Instant>,
203 recording_done: bool,
204 whiteboard_url_seen: bool,
205 whiteboard_share_seen: bool,
206 whiteboard_wait_until: Option<Instant>,
207 deadline: Option<Instant>,
208}
209
210impl Features {
211 fn pending(&self, arguments: &Arguments) -> bool {
212 if self
213 .deadline
214 .is_none_or(|deadline| Instant::now() >= deadline)
215 {
216 return false;
217 }
218 (arguments.spotlight_self && !self.spotlight_cleared)
219 || (arguments.captions && !self.captions_stopped)
220 || (arguments.record && !self.recording_done)
221 || (arguments.whiteboard_state
222 && self
223 .whiteboard_wait_until
224 .is_none_or(|until| Instant::now() < until)
225 && !self.whiteboard_share_seen)
226 }
227}
228
229async fn run() {
230 let arguments = arguments();
231 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
232 let session = Session::connect(&endpoint).await.expect("browser");
233 let poll_session = Session::connect(&endpoint).await.expect("browser");
234 let me = fetch_self(&session).await.expect("own identity");
235
236 let started = Instant::now();
237 let reused = std::env::args()
238 .skip_while(|argument| argument != "--thread")
239 .nth(1);
240 let (thread_id, created_meeting) = match reused {
241 Some(thread_id) => (thread_id, None),
242 None => {
243 let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});
244 let created = session
245 .request(
246 Method::Post,
247 CREATE_URL,
248 &Scope::new(SPACES, "user_impersonation"),
249 Some(body),
250 )
251 .await
252 .expect("create meeting");
253 println!(
254 "# create MeetNow: HTTP {} after {:?}",
255 created.status,
256 started.elapsed()
257 );
258 let thread_id = created
259 .body
260 .pointer("/value/groupContext/threadId")
261 .and_then(Value::as_str)
262 .expect("meeting thread")
263 .to_owned();
264 (thread_id, Some(created.body))
265 }
266 };
267 if let Some(path) = &arguments.thread_out {
268 std::fs::write(path, &thread_id).expect("thread file");
269 }
270
271 let (mut tenant_id, mut organizer_id) = tenant_and_organizer(&session, &thread_id).await;
272 for _ in 0..THREAD_PROPERTY_RETRIES {
273 if tenant_id.is_some() {
274 break;
275 }
276 tokio::time::sleep(POLL).await;
277 (tenant_id, organizer_id) = tenant_and_organizer(&session, &thread_id).await;
278 }
279 let organizer_id = organizer_id.unwrap_or_else(|| me.object_id.clone());
280 println!(
281 "# thread: tenant found {}, organizer is me {}",
282 tenant_id.is_some(),
283 organizer_id.eq_ignore_ascii_case(&me.object_id)
284 );
285 let target = MeetingTarget {
286 thread_id: thread_id.clone(),
287 tenant_id: tenant_id.expect("tenant id"),
288 organizer_id,
289 meeting_data: None,
290 };
291
292 let config = EngineConfig {
293 ringable: false,
294 trace: true,
295 instance: InstanceNames {
296 global: "__meetNowTrouter".into(),
297 binding: "__meetNowRealtime".into(),
298 endpoint_storage_key: "__meetNowEpid".into(),
299 },
300 ..EngineConfig::default()
301 };
302 let (engine, _events) = CallEngine::start(session.clone(), poll_session, config)
303 .await
304 .expect("engine");
305 println!("# engine ready after {:?}", started.elapsed());
306 if arguments.resolve_by_id
307 && let Some(created) = &created_meeting
308 {
309 check_resolve_by_id(&engine, created, &thread_id).await;
310 }
311 let join_started = Instant::now();
312 let mut handle = engine.start_call(CallSpec::Meeting(target));
313
314 let mut connected_after = None;
315 let mut roster_count = None;
316 let mut inbound = 0;
317 let mut ended = None;
318 let mut live_detected_after = None;
319 let mut released_at = None;
320 let mut end_sent_at = None;
321 let mut media_due: Option<Instant> = None;
322 let mut media_stop_due: Option<Instant> = None;
323 let mut hand_lower_due: Option<Instant> = None;
324 let mut hands_seen = 0usize;
325 let mut reactions_seen = Vec::new();
326 let mut sharing_local_level: f32 = 0.0;
327 let mut sharing = false;
328 let mut features = Features::default();
329 let deadline = Instant::now()
330 + CONNECT_LIMIT
331 + LIVE_STATE_LIMIT
332 + WAIT_FILE_LIMIT
333 + arguments.hold
334 + END_LIMIT;
335 let mut tick = tokio::time::interval(POLL);
336 while ended.is_none() && Instant::now() < deadline {
337 tokio::select! {
338 update = handle.updates.recv() => match update {
339 Some(CallUpdate::State(CallState::Connected { .. })) => {
340 if connected_after.is_none() {
341 connected_after = Some(join_started.elapsed());
342 media_due = Some(Instant::now() + MEDIA_DELAY);
343 }
344 }
345 Some(CallUpdate::Camera(on)) => println!("# camera update: {on}"),
346 Some(CallUpdate::LocalShare(label)) => {
347 sharing = label.is_some();
348 println!("# local share update: {}", label.is_some());
349 }
350 Some(CallUpdate::Notice(text)) => {
351 println!("# notice: {text}");
352 if arguments.record && text.to_ascii_lowercase().contains("recording") && !features.recording_seen_on {
353 features.recording_done = true;
354 }
355 }
356 Some(CallUpdate::Recording(on)) => {
357 println!("# recording state: {}", if on { "on" } else { "off" });
358 if on {
359 features.recording_seen_on = true;
360 features.recording_stop_due = Some(Instant::now() + arguments.record_for);
361 } else if features.recording_seen_on {
362 features.recording_seen_off = true;
363 features.recording_done = true;
364 }
365 }
366 Some(CallUpdate::Whiteboard(share)) => {
367 println!("# whiteboard share: {}", share.as_ref().map_or_else(|| "ended".to_owned(), |share| format!("presenter {:?}, whiteboard {}, url {}", share.presenter, share.whiteboard, share.url.is_some())));
368 features.whiteboard_share_seen |= share.is_some();
369 }
370 Some(CallUpdate::WhiteboardUrl(url)) => {
371 features.whiteboard_url_seen = true;
372 println!("# whiteboard board url fetched: host {}", url.split('/').nth(2).unwrap_or("?"));
373 }
374 Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),
375 Some(CallUpdate::OwnIdentity { mri }) => features.own_mri = Some(mri),
376 Some(CallUpdate::Captions(state)) => {
377 println!("# captions state: {}", match &state {
378 CaptionState::Off => "off".to_owned(),
379 CaptionState::Starting => "starting".to_owned(),
380 CaptionState::On => "on".to_owned(),
381 CaptionState::Failed(reason) => format!("failed ({reason})"),
382 });
383 if state == CaptionState::On && !features.captions_active {
384 features.captions_active = true;
385 features.captions_stop_due = Some(Instant::now() + CAPTIONS_HOLD);
386 }
387 if matches!(state, CaptionState::Failed(_)) {
388 features.captions_stopped = true;
389 }
390 }
391 Some(CallUpdate::Caption(_)) => features.caption_events += 1,
392 Some(CallUpdate::BlurTiming(average_ms)) => {
393 features.blur_reports += 1;
394 features.blur_total_ms += f64::from(average_ms);
395 }
396 Some(CallUpdate::Organizer { action, outcome }) => match outcome {
397 Ok(status) => println!("# organizer {action}: HTTP {status}"),
398 Err(reason) => println!("# organizer {action}: failed, {}", http_status(&reason)),
399 },
400 Some(CallUpdate::Roster(entries)) => {
401 let own_spotlit = entries.iter().any(|entry| Some(&entry.mri) == features.own_mri.as_ref() && entry.spotlight.is_some());
402 if own_spotlit && !features.spotlight_seen {
403 features.spotlight_seen = true;
404 println!("# own spotlight visible in the roster");
405 if let Some(mri) = features.own_mri.clone() {
406 let _ = handle.commands.send(CallCommand::StopSpotlight { mri });
407 }
408 }
409 if !own_spotlit && features.spotlight_seen && !features.spotlight_cleared {
410 features.spotlight_cleared = true;
411 println!("# own spotlight gone from the roster");
412 }
413 let hands = entries.iter().filter(|entry| entry.hand.is_some()).count();
414 if hands != hands_seen {
415 println!("# roster hands raised: {hands}");
416 hands_seen = hands;
417 }
418 roster_count = Some(entries.len());
419 }
420 Some(CallUpdate::Reaction { reaction, .. }) => {
421 println!("# reaction received: {reaction:?}");
422 reactions_seen.push(reaction);
423 }
424 Some(CallUpdate::MeetingChat(thread)) => {
425 let url = format!(
426 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}/messages?view=msnp24Equivalent&pageSize=5",
427 urlencoding_component(&thread)
428 );
429 let read = session.request(Method::Get, &url, &ic3_scope(), None).await;
430 match read {
431 Ok(answer) => println!(
432 "# meeting chat thread from join: same as meeting {}, read HTTP {}, messages {}",
433 thread == thread_id,
434 answer.status,
435 answer.body.get("messages").and_then(Value::as_array).map_or(0, Vec::len)
436 ),
437 Err(error) => println!("# meeting chat read failed: {error}"),
438 }
439 }
440 Some(CallUpdate::ShareSound(on)) => println!("# share sound: {on}"),
441 Some(CallUpdate::Muted(muted)) => println!("# muted: {muted}"),
442 Some(CallUpdate::Levels { local, .. }) => {
443 if sharing {
444 sharing_local_level = sharing_local_level.max(local);
445 }
446 }
447 Some(CallUpdate::Stats { inbound_packets, .. }) => inbound = inbound_packets,
448 Some(_) => {}
449 None => break,
450 },
451 _ = tick.tick() => {
452 if media_stop_due.is_some_and(|due| Instant::now() >= due) {
453 media_stop_due = None;
454 let _ = handle.commands.send(CallCommand::SetCamera(false));
455 let _ = handle.commands.send(CallCommand::StopShare);
456 }
457 if features.captions_stop_due.is_some_and(|due| Instant::now() >= due) {
458 features.captions_stop_due = None;
459 features.captions_stopped = true;
460 let _ = handle.commands.send(CallCommand::SetCaptions(false));
461 }
462 if features.recording_stop_due.is_some_and(|due| Instant::now() >= due) {
463 features.recording_stop_due = None;
464 let _ = handle.commands.send(CallCommand::StopRecording { scope: StopScope::Both });
465 }
466 if hand_lower_due.is_some_and(|due| Instant::now() >= due) {
467 hand_lower_due = None;
468 let _ = handle.commands.send(CallCommand::SetHand(false));
469 }
470 if media_due.is_some_and(|due| Instant::now() >= due) {
471 media_due = None;
472 media_stop_due = arguments.stop_media_after.map(|after| Instant::now() + after);
473 if arguments.camera {
474 let _ = handle.commands.send(CallCommand::SetCamera(true));
475 }
476 if arguments.unmute {
477 let _ = handle.commands.send(CallCommand::Mute(MuteCommand::Unmute));
478 }
479 if arguments.extras {
480 let _ = handle.commands.send(CallCommand::SetHand(true));
481 for reaction in Reaction::ALL {
482 let _ = handle.commands.send(CallCommand::SendReaction(reaction));
483 }
484 let _ = handle.commands.send(CallCommand::SetShareSound(true));
485 hand_lower_due = Some(Instant::now() + Duration::from_secs(6));
486 }
487 features.deadline = Some(Instant::now() + FEATURE_LIMIT);
488 if arguments.spotlight_self
489 && let Some(mri) = features.own_mri.clone()
490 {
491 let _ = handle.commands.send(CallCommand::Spotlight { mri });
492 }
493 if arguments.mute_all {
494 let _ = handle.commands.send(CallCommand::MuteAll);
495 }
496 if arguments.captions {
497 features.captions_requested = true;
498 let _ = handle.commands.send(CallCommand::SetCaptions(true));
499 }
500 if arguments.blur {
501 let _ = handle.commands.send(CallCommand::SetBackground(BackgroundChoice::Blur));
502 }
503 if arguments.record {
504 let _ = handle.commands.send(CallCommand::StartRecording { kind: if arguments.audio_only { RecordingKind::AudioOnly } else { RecordingKind::Video }, title: SUBJECT.to_owned() });
505 }
506 if arguments.whiteboard_state {
507 features.whiteboard_wait_until = Some(Instant::now() + WHITEBOARD_WAIT);
508 println!("# whiteboard: fetching the board url, then waiting {WHITEBOARD_WAIT:?} for a whiteboard share (start one from Teams web in this meeting)");
509 let _ = handle.commands.send(CallCommand::OpenWhiteboard { title: SUBJECT.to_owned() });
510 }
511 if arguments.background {
512 let image = background_image(&session).await;
513 if let Some(path) = image {
514 let _ = handle.commands.send(CallCommand::SetBackground(BackgroundChoice::Image(path)));
515 }
516 }
517 if arguments.share {
518 let source = ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() };
519 let _ = handle.commands.send(CallCommand::StartShare(source));
520 }
521 }
522 if connected_after.is_none() {
523 if join_started.elapsed() > CONNECT_LIMIT {
524 println!("# not connected within {CONNECT_LIMIT:?}, hanging up");
525 let _ = handle.commands.send(CallCommand::Hangup);
526 }
527 continue;
528 }
529 if live_detected_after.is_none() && end_sent_at.is_none() {
530 if let Ok(Some(meeting)) = fetch_live_meeting(&session, &thread_id).await {
531 live_detected_after = Some(join_started.elapsed());
532 println!("# live state detected, join target complete: {}", meeting.target().is_some());
533 released_at = Some(Instant::now() + arguments.hold);
534 } else if join_started.elapsed() > CONNECT_LIMIT + LIVE_STATE_LIMIT {
535 println!("# live state not seen within {LIVE_STATE_LIMIT:?}");
536 released_at = Some(Instant::now());
537 }
538 }
539 let waiting_for_file = arguments.wait_file.as_ref().is_some_and(|path| !path.exists())
540 && join_started.elapsed() < CONNECT_LIMIT + WAIT_FILE_LIMIT;
541 if end_sent_at.is_none() && released_at.is_some_and(|at| Instant::now() >= at) && !waiting_for_file && !features.pending(&arguments) {
542 println!("# roster before end: {roster_count:?} participant(s), inbound packets {inbound}");
543 let _ = handle.commands.send(CallCommand::EndMeeting);
544 end_sent_at = Some(Instant::now());
545 }
546 }
547 }
548 }
549 println!(
550 "# connected after {connected_after:?}, live state after {live_detected_after:?}, roster {roster_count:?}, inbound packets {inbound}"
551 );
552 println!("# ended: {ended:?}");
553 if arguments.extras {
554 println!(
555 "# extras: reactions echoed {}/{}, max local level while sharing {sharing_local_level:.3}",
556 reactions_seen.len(),
557 Reaction::ALL.len()
558 );
559 }
560 if arguments.spotlight_self {
561 println!(
562 "# spotlight self: shown {}, cleared {}",
563 features.spotlight_seen, features.spotlight_cleared
564 );
565 }
566 if arguments.captions {
567 println!(
568 "# captions: became active {}, caption events {}",
569 features.captions_active, features.caption_events
570 );
571 }
572 if arguments.blur || arguments.background {
573 let average = if features.blur_reports == 0 {
574 0.
575 } else {
576 features.blur_total_ms / features.blur_reports as f64
577 };
578 let label = if arguments.background {
579 "background image"
580 } else {
581 "blur"
582 };
583 println!(
584 "# {label}: average processing {average:.1} ms over {} report(s)",
585 features.blur_reports
586 );
587 }
588 if arguments.record {
589 println!(
590 "# recording: seen on {}, seen off {}",
591 features.recording_seen_on, features.recording_seen_off
592 );
593 }
594 if arguments.whiteboard_state {
595 println!(
596 "# whiteboard: board url fetched {}, share update parsed {}",
597 features.whiteboard_url_seen, features.whiteboard_share_seen
598 );
599 }
600 let gone_started = Instant::now();
601 let mut gone_after = None;
602 while gone_started.elapsed() < GONE_LIMIT {
603 if matches!(fetch_live_meeting(&session, &thread_id).await, Ok(None)) {
604 gone_after = Some(gone_started.elapsed());
605 break;
606 }
607 tokio::time::sleep(POLL).await;
608 }
609 println!("# live state gone after end: {gone_after:?}");
610 engine.stop().await;
611 println!("# engine stopped, total {:?}", started.elapsed());
612}
613
614async fn background_image(session: &Session) -> Option<PathBuf> {
615 let cache = BackgroundCache::new(std::env::temp_dir().join(BACKGROUND_CACHE));
616 let catalog = match cache.refresh_catalog(session).await {
617 Ok(catalog) => catalog,
618 Err(error) => {
619 println!("# background image list failed: {error}");
620 return None;
621 }
622 };
623 println!(
624 "# background image list downloaded: {} entries",
625 catalog.len()
626 );
627 let first = catalog.first()?;
628 match cache.ensure_thumbnail(session, first).await {
629 Ok(path) => println!(
630 "# first thumbnail cached: {} bytes",
631 std::fs::metadata(&path).map_or(0, |meta| meta.len())
632 ),
633 Err(error) => println!("# first thumbnail failed: {error}"),
634 }
635 match cache.ensure_image(session, first).await {
636 Ok(path) => {
637 println!(
638 "# first image {} cached: {} bytes",
639 first.id,
640 std::fs::metadata(&path).map_or(0, |meta| meta.len())
641 );
642 Some(path)
643 }
644 Err(error) => {
645 println!("# first image failed: {error}");
646 None
647 }
648 }
649}
650
651fn urlencoding_component(value: &str) -> String {
652 value
653 .bytes()
654 .map(|byte| match byte {
655 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
656 (byte as char).to_string()
657 }
658 other => format!("%{other:02X}"),
659 })
660 .collect()
661}
662
663fn find_text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
664 match value {
665 Value::Object(map) => {
666 for (key, inner) in map {
667 if keys.iter().any(|wanted| key.eq_ignore_ascii_case(wanted))
668 && let Some(text) = inner.as_str().filter(|text| !text.is_empty())
669 {
670 return Some(text);
671 }
672 if let Some(found) = find_text(inner, keys) {
673 return Some(found);
674 }
675 }
676 None
677 }
678 Value::Array(items) => items.iter().find_map(|item| find_text(item, keys)),
679 _ => None,
680 }
681}
682
683async fn check_resolve_by_id(engine: &CallEngine, created: &Value, thread_id: &str) {
684 let code =
685 find_text(created, &["joinMeetingId", "meetingCode"]).map(|code| code.replace(' ', ""));
686 let passcode = find_text(created, &["passcode"]);
687 println!(
688 "# resolve by id: meeting id found {}, passcode found {}",
689 code.is_some(),
690 passcode.is_some()
691 );
692 let Some(code) = code else {
693 return;
694 };
695 let url = match passcode {
696 Some(passcode) => format!("https://teams.microsoft.com/meet/{code}?p={passcode}"),
697 None => format!("https://teams.microsoft.com/meet/{code}"),
698 };
699 let meeting_data = json!({"meetingCode": code, "passcode": passcode, "meetingUrl": url});
700 match engine.resolve_meeting(&meeting_data).await {
701 Ok(target) => println!(
702 "# resolve by id: found, same thread {}, tenant and organizer present {}",
703 target.thread_id == thread_id,
704 !target.tenant_id.is_empty() && !target.organizer_id.is_empty()
705 ),
706 Err(error) => println!(
707 "# resolve by id: failed: {}",
708 error.to_string().chars().take(160).collect::<String>()
709 ),
710 }
711}