BlueGit

ict rusty-teams

Files

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

meet_now.rs

meet_now.rs 8.3 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::{CallCommand, CallEngine, CallSpec, CallState, CallUpdate, EngineConfig, MeetingTarget};
8use chatsvc::InstanceNames;
9use serde_json::{Value, json};
10use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};
11
12const CREATE_URL: &str =
13 "https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create";
14const SUBJECT: &str = "Native client test";
15const CONNECT_LIMIT: Duration = Duration::from_secs(45);
16const LIVE_STATE_LIMIT: Duration = Duration::from_secs(30);
17const WAIT_FILE_LIMIT: Duration = Duration::from_secs(300);
18const END_LIMIT: Duration = Duration::from_secs(20);
19const GONE_LIMIT: Duration = Duration::from_secs(90);
20const POLL: Duration = Duration::from_secs(2);
21
22struct Arguments {
23 hold: Duration,
24 thread_out: Option<PathBuf>,
25 wait_file: Option<PathBuf>,
26}
27
28fn arguments() -> Arguments {
29 let mut parsed = Arguments {
30 hold: Duration::from_secs(10),
31 thread_out: None,
32 wait_file: None,
33 };
34 let mut input = std::env::args().skip(1);
35 while let Some(flag) = input.next() {
36 match flag.as_str() {
37 "--hold" => parsed.hold = Duration::from_secs(input.next().and_then(|value| value.parse().ok()).unwrap_or(10)),
38 "--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
39 "--wait-file" => parsed.wait_file = input.next().map(PathBuf::from),
40 _ => {}
41 }
42 }
43 parsed
44}
45
46fn as_object(value: &Value) -> Option<Value> {
47 match value {
48 Value::String(text) => serde_json::from_str(text).ok(),
49 Value::Object(_) => Some(value.clone()),
50 _ => None,
51 }
52}
53
54async fn tenant_and_organizer(session: &Session, thread_id: &str) -> (Option<String>, Option<String>) {
55 let url = format!(
56 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
57 thread_id.replace(':', "%3A").replace('@', "%40")
58 );
59 let Ok(response) = session.send(Request::get(url), &ic3_scope()).await else {
60 return (None, None);
61 };
62 let properties = &response.body["properties"];
63 let meeting = as_object(&properties["meeting"]);
64 let text = |value: &Value| value.as_str().filter(|text| !text.is_empty()).map(str::to_owned);
65 let tenant = meeting
66 .as_ref()
67 .and_then(|meeting| text(&meeting["tenantId"]))
68 .or_else(|| text(&properties["addedByTenantId"]));
69 (tenant, meeting.as_ref().and_then(|meeting| text(&meeting["organizerId"])))
70}
71
72#[tokio::main]
73async fn main() {
74 let arguments = arguments();
75 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
76 let session = Session::connect(&endpoint).await.expect("browser");
77 let poll_session = Session::connect(&endpoint).await.expect("browser");
78 let me = fetch_self(&session).await.expect("own identity");
79
80 let started = Instant::now();
81 let reused = std::env::args().skip_while(|argument| argument != "--thread").nth(1);
82 let thread_id = match reused {
83 Some(thread_id) => thread_id,
84 None => {
85 let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});
86 let created = session
87 .request(Method::Post, CREATE_URL, &Scope::new(SPACES, "user_impersonation"), Some(body))
88 .await
89 .expect("create meeting");
90 println!("# create MeetNow: HTTP {} after {:?}", created.status, started.elapsed());
91 created.body.pointer("/value/groupContext/threadId").and_then(Value::as_str).expect("meeting thread").to_owned()
92 }
93 };
94 if let Some(path) = &arguments.thread_out {
95 std::fs::write(path, &thread_id).expect("thread file");
96 }
97
98 let (tenant_id, organizer_id) = tenant_and_organizer(&session, &thread_id).await;
99 let organizer_id = organizer_id.unwrap_or_else(|| me.object_id.clone());
100 println!(
101 "# thread: tenant found {}, organizer is me {}",
102 tenant_id.is_some(),
103 organizer_id.eq_ignore_ascii_case(&me.object_id)
104 );
105 let target = MeetingTarget {
106 thread_id: thread_id.clone(),
107 tenant_id: tenant_id.expect("tenant id"),
108 organizer_id,
109 meeting_data: None,
110 };
111
112 let config = EngineConfig {
113 ringable: false,
114 trace: true,
115 instance: InstanceNames {
116 global: "__meetNowTrouter".into(),
117 binding: "__meetNowRealtime".into(),
118 endpoint_storage_key: "__meetNowEpid".into(),
119 },
120 ..EngineConfig::default()
121 };
122 let (engine, _events) = CallEngine::start(session.clone(), poll_session, config).await.expect("engine");
123 println!("# engine ready after {:?}", started.elapsed());
124 let join_started = Instant::now();
125 let mut handle = engine.start_call(CallSpec::Meeting(target));
126
127 let mut connected_after = None;
128 let mut roster_count = None;
129 let mut inbound = 0;
130 let mut ended = None;
131 let mut live_detected_after = None;
132 let mut released_at = None;
133 let mut end_sent_at = None;
134 let deadline = Instant::now() + CONNECT_LIMIT + LIVE_STATE_LIMIT + WAIT_FILE_LIMIT + arguments.hold + END_LIMIT;
135 let mut tick = tokio::time::interval(POLL);
136 while ended.is_none() && Instant::now() < deadline {
137 tokio::select! {
138 update = handle.updates.recv() => match update {
139 Some(CallUpdate::State(CallState::Connected { .. })) => {
140 connected_after.get_or_insert(join_started.elapsed());
141 }
142 Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(reason),
143 Some(CallUpdate::Roster(entries)) => roster_count = Some(entries.len()),
144 Some(CallUpdate::Stats { inbound_packets, .. }) => inbound = inbound_packets,
145 Some(_) => {}
146 None => break,
147 },
148 _ = tick.tick() => {
149 if connected_after.is_none() {
150 if join_started.elapsed() > CONNECT_LIMIT {
151 println!("# not connected within {CONNECT_LIMIT:?}, hanging up");
152 let _ = handle.commands.send(CallCommand::Hangup);
153 }
154 continue;
155 }
156 if live_detected_after.is_none() && end_sent_at.is_none() {
157 if let Ok(Some(meeting)) = fetch_live_meeting(&session, &thread_id).await {
158 live_detected_after = Some(join_started.elapsed());
159 println!("# live state detected, join target complete: {}", meeting.target().is_some());
160 released_at = Some(Instant::now() + arguments.hold);
161 } else if join_started.elapsed() > CONNECT_LIMIT + LIVE_STATE_LIMIT {
162 println!("# live state not seen within {LIVE_STATE_LIMIT:?}");
163 released_at = Some(Instant::now());
164 }
165 }
166 let waiting_for_file = arguments.wait_file.as_ref().is_some_and(|path| !path.exists())
167 && join_started.elapsed() < CONNECT_LIMIT + WAIT_FILE_LIMIT;
168 if end_sent_at.is_none() && released_at.is_some_and(|at| Instant::now() >= at) && !waiting_for_file {
169 println!("# roster before end: {roster_count:?} participant(s), inbound packets {inbound}");
170 let _ = handle.commands.send(CallCommand::EndMeeting);
171 end_sent_at = Some(Instant::now());
172 }
173 }
174 }
175 }
176 println!(
177 "# connected after {connected_after:?}, live state after {live_detected_after:?}, roster {roster_count:?}, inbound packets {inbound}"
178 );
179 println!("# ended: {ended:?}");
180 let gone_started = Instant::now();
181 let mut gone_after = None;
182 while gone_started.elapsed() < GONE_LIMIT {
183 if matches!(fetch_live_meeting(&session, &thread_id).await, Ok(None)) {
184 gone_after = Some(gone_started.elapsed());
185 break;
186 }
187 tokio::time::sleep(POLL).await;
188 }
189 println!("# live state gone after end: {gone_after:?}");
190 engine.stop().await;
191 println!("# engine stopped, total {:?}", started.elapsed());
192}