| 1 | use std::collections::HashMap; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; |
| 4 | |
| 5 | use futures_util::{SinkExt, StreamExt}; |
| 6 | use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode}; |
| 7 | use serde_json::{Map, Value, json}; |
| 8 | use session::{App, Method, Request, Session}; |
| 9 | use tokio::net::TcpStream; |
| 10 | use tokio::sync::{Notify, mpsc, oneshot, watch}; |
| 11 | use tokio::time::{MissedTickBehavior, interval, sleep, sleep_until, timeout}; |
| 12 | use tokio_tungstenite::tungstenite::Message; |
| 13 | use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, connect_async}; |
| 14 | |
| 15 | use super::RealtimeConfig; |
| 16 | use super::callback::{CallbackReply, decode_callback}; |
| 17 | use super::event::{RealtimeEvent, StatusEvent, StatusKind, decode_payload}; |
| 18 | use super::host::ic3_scope; |
| 19 | use super::runner::CallbackPipes; |
| 20 | |
| 21 | const REGISTRAR: &str = "https://teams.cloud.microsoft/registrar/prod/V2/registrations"; |
| 22 | const UI_VERSION: &str = "1415/26091712213"; |
| 23 | const CLIENT_VERSION: &str = "2026.36.01.1"; |
| 24 | const PING_EVERY: Duration = Duration::from_secs(30); |
| 25 | const SILENCE_LIMIT: Duration = Duration::from_secs(100); |
| 26 | const REREGISTER_AFTER: Duration = Duration::from_secs(40 * 60); |
| 27 | const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); |
| 28 | const MAX_BACKOFF: Duration = Duration::from_secs(30); |
| 29 | const ACTIVITY_DEBOUNCE: Duration = Duration::from_secs(1); |
| 30 | const ACTIVITY_ACK_TIMEOUT: Duration = Duration::from_secs(10); |
| 31 | const CALLBACK_REPLY_TIMEOUT: Duration = Duration::from_secs(5); |
| 32 | const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10); |
| 33 | const CALLBACK_PREFIX: &str = "callAgent/"; |
| 34 | const MAX_PRESENCE_ENTRIES: usize = 1000; |
| 35 | const MAX_PRESENCE_FIELD: usize = 128; |
| 36 | const MAX_SENDER_NAME: usize = 256; |
| 37 | const MAX_RESOURCE_TYPE: usize = 64; |
| 38 | const MAX_LOSS_DETAIL: usize = 200; |
| 39 | const TOKEN_BODY: &str = "return token;"; |
| 40 | |
| 41 | type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>; |
| 42 | |
| 43 | /// One Trouter frame: `type:id:endpoint:data`. |
| 44 | #[derive(Debug, PartialEq, Eq)] |
| 45 | pub(super) struct Frame<'a> { |
| 46 | pub kind: char, |
| 47 | pub data: &'a str, |
| 48 | } |
| 49 | |
| 50 | pub(super) fn parse_frame(text: &str) -> Option<Frame<'_>> { |
| 51 | let mut parts = text.splitn(4, ':'); |
| 52 | let kind = parts.next()?; |
| 53 | let (Some(_id), Some(_endpoint)) = (parts.next(), parts.next()) else { return None }; |
| 54 | let mut chars = kind.chars(); |
| 55 | let kind = chars.next().filter(|kind| kind.is_ascii_digit() && chars.next().is_none())?; |
| 56 | Some(Frame { kind, data: parts.next().unwrap_or("") }) |
| 57 | } |
| 58 | |
| 59 | pub(super) fn socket_url(host: &str, endpoint_id: &str, correlation: &str, now_ms: u128) -> String { |
| 60 | let client_info = json!({"cv": CLIENT_VERSION, "ua": "TeamsCDL", "hr": "", "v": UI_VERSION}).to_string(); |
| 61 | format!( |
| 62 | "wss://{host}/v4/c?tc={}&timeout=40&epid={endpoint_id}&ccid=&cor_id={correlation}&con_num={now_ms}_0", |
| 63 | percent_encode(&client_info) |
| 64 | ) |
| 65 | } |
| 66 | |
| 67 | const URI_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'_').remove(b'.').remove(b'!').remove(b'~').remove(b'*').remove(b'\'').remove(b'(').remove(b')'); |
| 68 | |
| 69 | fn percent_encode(text: &str) -> String { |
| 70 | utf8_percent_encode(text, URI_COMPONENT).to_string() |
| 71 | } |
| 72 | |
| 73 | pub(super) fn registration_body(ringable: bool, endpoint_id: &str, surl: &str) -> Value { |
| 74 | let (app_id, template_key) = if ringable { ("SkypeSpacesWeb", "SkypeSpacesWeb_2.6") } else { ("TeamsCDLWebWorker", "TeamsCDLWebWorker_2.6") }; |
| 75 | let mut description = json!({ |
| 76 | "appId": app_id, "aesKey": "", "languageId": "en-US", "platform": "chrome", |
| 77 | "templateKey": template_key, "platformUIVersion": UI_VERSION, |
| 78 | }); |
| 79 | if ringable { |
| 80 | description["productContext"] = json!(""); |
| 81 | } |
| 82 | json!({ |
| 83 | "clientDescription": description, |
| 84 | "registrationId": endpoint_id, "nodeId": "", |
| 85 | "transports": {"TROUTER": [{"context": "", "path": surl, "ttl": 3600}]}, |
| 86 | }) |
| 87 | } |
| 88 | |
| 89 | fn header_value(headers: &Value, name: &str) -> Option<String> { |
| 90 | let headers = headers.as_object()?; |
| 91 | headers.iter().find(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| match value { |
| 92 | Value::String(text) => text.clone(), |
| 93 | other => other.to_string(), |
| 94 | }) |
| 95 | } |
| 96 | |
| 97 | /// Headers a callback reply echoes back to Trouter. |
| 98 | pub(super) fn echoed_headers(headers: &Value) -> Value { |
| 99 | let mut echoed = Map::new(); |
| 100 | for name in ["X-Microsoft-Skype-Chain-ID", "trouter-request"] { |
| 101 | if let Some(value) = header_value(headers, name) { |
| 102 | echoed.insert(name.to_owned(), Value::String(value)); |
| 103 | } |
| 104 | } |
| 105 | if let Some(correlation) = header_value(headers, "MS-CV") { |
| 106 | echoed.insert("MS-CV".to_owned(), Value::String(format!("{correlation}.0"))); |
| 107 | } |
| 108 | Value::Object(echoed) |
| 109 | } |
| 110 | |
| 111 | fn request_path(url: &str) -> String { |
| 112 | let Some(rest) = url.strip_prefix("/v4/f/") else { return url.to_owned() }; |
| 113 | match rest.split_once('/') { |
| 114 | Some((_, path)) => path.to_owned(), |
| 115 | None => url.to_owned(), |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | fn conversation_of(resource: &Value) -> String { |
| 120 | let link = ["conversationLink", "to", "id"] |
| 121 | .iter() |
| 122 | .find_map(|key| resource.get(key).and_then(Value::as_str).filter(|value| !value.is_empty())) |
| 123 | .unwrap_or(""); |
| 124 | let raw = match link.find("conversations/") { |
| 125 | Some(start) => { |
| 126 | let after = &link[start + "conversations/".len()..]; |
| 127 | after.split([';', '/', '?']).next().unwrap_or("") |
| 128 | } |
| 129 | None => link.split(';').next().unwrap_or(""), |
| 130 | }; |
| 131 | percent_decode(raw).unwrap_or_else(|| raw.to_owned()) |
| 132 | } |
| 133 | |
| 134 | fn percent_decode(text: &str) -> Option<String> { |
| 135 | percent_decode_str(text).decode_utf8().ok().map(|decoded| decoded.into_owned()) |
| 136 | } |
| 137 | |
| 138 | fn classify(resource_type: &str, message_type: &str) -> &'static str { |
| 139 | match resource_type { |
| 140 | "NewMessage" => { |
| 141 | if message_type.starts_with("Control/Typing") || message_type.starts_with("Control/ClearTyping") { |
| 142 | "typing" |
| 143 | } else if message_type == "ThreadActivity/MemberConsumptionHorizonUpdate" { |
| 144 | "read_receipt" |
| 145 | } else if message_type == "ThreadActivity/PinnedItemsUpdate" { |
| 146 | "pins_changed" |
| 147 | } else if message_type.starts_with("ThreadActivity/") { |
| 148 | "thread_activity" |
| 149 | } else if message_type.starts_with("Control/") { |
| 150 | "control" |
| 151 | } else { |
| 152 | "new_message" |
| 153 | } |
| 154 | } |
| 155 | "MessageUpdate" => "message_update", |
| 156 | "ThreadUpdate" => "thread_update", |
| 157 | _ => "other", |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | fn cut(text: &str, limit: usize) -> String { |
| 162 | text.chars().take(limit).collect() |
| 163 | } |
| 164 | |
| 165 | fn typing_sender(from: &str) -> Option<String> { |
| 166 | let lower = from.to_ascii_lowercase(); |
| 167 | let start = lower.rfind("/contacts/8:orgid:")? + "/contacts/8:orgid:".len(); |
| 168 | let id = from[start..].trim_end_matches('/'); |
| 169 | (!id.is_empty() && id.len() <= 64 && id.chars().all(|character| character.is_ascii_hexdigit() || character == '-')).then(|| id.to_owned()) |
| 170 | } |
| 171 | |
| 172 | /// The same message the page worker forwards for a Trouter notification. |
| 173 | pub(super) fn notification_payload(path: &str, body: Option<&Value>, received_at_ms: i64) -> Option<Value> { |
| 174 | if path == "unifiedPresenceService" { |
| 175 | let entries: Vec<Value> = body |
| 176 | .and_then(|body| body.get("presence")) |
| 177 | .and_then(Value::as_array) |
| 178 | .into_iter() |
| 179 | .flatten() |
| 180 | .take(MAX_PRESENCE_ENTRIES) |
| 181 | .filter_map(|entry| { |
| 182 | let text = |pointer: &str| entry.pointer(pointer).and_then(Value::as_str).map(|value| cut(value, MAX_PRESENCE_FIELD)); |
| 183 | let mri = text("/mri")?; |
| 184 | let availability = text("/presence/availability")?; |
| 185 | Some(json!({ |
| 186 | "mri": mri, "availability": availability, "activity": text("/presence/activity"), |
| 187 | "outOfOffice": entry.pointer("/presence/calendarData/isOutOfOffice").and_then(Value::as_bool).unwrap_or(false), |
| 188 | })) |
| 189 | }) |
| 190 | .collect(); |
| 191 | return (!entries.is_empty()).then(|| json!({"channel": "presence", "entries": entries})); |
| 192 | } |
| 193 | let resource = body.and_then(|body| body.get("resource")).filter(|resource| !resource.is_null()); |
| 194 | let resource_type = body |
| 195 | .and_then(|body| body.get("resourceType")) |
| 196 | .and_then(Value::as_str) |
| 197 | .filter(|value| !value.is_empty()) |
| 198 | .unwrap_or(if path.is_empty() { "unknown" } else { path }); |
| 199 | let resource_type = cut(resource_type, MAX_RESOURCE_TYPE); |
| 200 | let message_type = resource.and_then(|resource| resource.get("messagetype")).and_then(Value::as_str).unwrap_or(""); |
| 201 | let event_kind = if path == "messaging" { classify(&resource_type, message_type) } else { "other" }; |
| 202 | let message_like = matches!(event_kind, "new_message" | "message_update"); |
| 203 | let mut payload = json!({ |
| 204 | "channel": "event", "resourceType": resource_type, "eventKind": event_kind, "receivedAt": received_at_ms, |
| 205 | "conversationId": resource.map(conversation_of).filter(|id| !id.is_empty()), |
| 206 | "messageId": resource.filter(|_| message_like).and_then(|resource| resource.get("id")).map(|id| match id { |
| 207 | Value::String(text) => text.clone(), |
| 208 | other => other.to_string(), |
| 209 | }), |
| 210 | }); |
| 211 | if event_kind == "typing" |
| 212 | && let Some(resource) = resource |
| 213 | { |
| 214 | payload["typing"] = json!(if message_type.starts_with("Control/ClearTyping") { "clear" } else { "start" }); |
| 215 | payload["senderId"] = json!(resource.get("from").and_then(Value::as_str).and_then(typing_sender)); |
| 216 | payload["senderName"] = json!(resource.get("imdisplayname").and_then(Value::as_str).map(|name| cut(name, MAX_SENDER_NAME))); |
| 217 | } |
| 218 | Some(payload) |
| 219 | } |
| 220 | |
| 221 | fn now_ms() -> i64 { |
| 222 | SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_millis() as i64) |
| 223 | } |
| 224 | |
| 225 | fn status_payload(kind: &str, detail: &str) -> String { |
| 226 | json!({"channel": "status", "kind": kind, "detail": detail}).to_string() |
| 227 | } |
| 228 | |
| 229 | struct PendingReply { |
| 230 | headers: Value, |
| 231 | deadline: tokio::time::Instant, |
| 232 | } |
| 233 | |
| 234 | enum Ended { |
| 235 | Stopped(Option<oneshot::Sender<()>>), |
| 236 | Lost { was_ready: bool }, |
| 237 | } |
| 238 | |
| 239 | /// Trouter over a websocket of its own; only the token lookup and the registrar calls run in the app tab, which may stay parked. |
| 240 | pub(super) struct NativeTrouter { |
| 241 | pub session: Session, |
| 242 | pub config: RealtimeConfig, |
| 243 | pub host: String, |
| 244 | pub output: mpsc::UnboundedSender<RealtimeEvent>, |
| 245 | pub callbacks: CallbackPipes, |
| 246 | pub activity: watch::Receiver<bool>, |
| 247 | pub resend: Arc<Notify>, |
| 248 | pub endpoint_id: String, |
| 249 | force_refresh: bool, |
| 250 | retry: u32, |
| 251 | ack_counter: u64, |
| 252 | surl: String, |
| 253 | registered_at: Option<Instant>, |
| 254 | } |
| 255 | |
| 256 | struct Connection { |
| 257 | socket: Socket, |
| 258 | token: String, |
| 259 | ready: bool, |
| 260 | last_frame: Instant, |
| 261 | sent_activity: Option<bool>, |
| 262 | activity_ack_id: u64, |
| 263 | activity_due: Option<tokio::time::Instant>, |
| 264 | activity_resend_due: Option<tokio::time::Instant>, |
| 265 | pending: HashMap<i64, PendingReply>, |
| 266 | } |
| 267 | |
| 268 | fn far_future() -> tokio::time::Instant { |
| 269 | tokio::time::Instant::now() + Duration::from_secs(365 * 24 * 3600) |
| 270 | } |
| 271 | |
| 272 | impl NativeTrouter { |
| 273 | pub(super) fn new( |
| 274 | session: Session, |
| 275 | config: RealtimeConfig, |
| 276 | host: String, |
| 277 | output: mpsc::UnboundedSender<RealtimeEvent>, |
| 278 | callbacks: CallbackPipes, |
| 279 | activity: watch::Receiver<bool>, |
| 280 | resend: Arc<Notify>, |
| 281 | ) -> Self { |
| 282 | NativeTrouter { |
| 283 | session, |
| 284 | config, |
| 285 | host, |
| 286 | output, |
| 287 | callbacks, |
| 288 | activity, |
| 289 | resend, |
| 290 | endpoint_id: uuid::Uuid::new_v4().to_string(), |
| 291 | force_refresh: false, |
| 292 | retry: 0, |
| 293 | ack_counter: 0, |
| 294 | surl: String::new(), |
| 295 | registered_at: None, |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | pub(super) async fn token(&mut self) -> session::Result<String> { |
| 300 | let value = self.session.run_with_token(App::Teams, &ic3_scope(), TOKEN_BODY, &json!({}), self.force_refresh).await?; |
| 301 | self.force_refresh = false; |
| 302 | value.as_str().map(str::to_owned).ok_or_else(|| session::Error::Cdp("token lookup gave no text".into())) |
| 303 | } |
| 304 | |
| 305 | pub(super) async fn run(mut self, mut stop: oneshot::Receiver<oneshot::Sender<()>>) { |
| 306 | loop { |
| 307 | let connected = tokio::select! { |
| 308 | connected = self.connect() => connected, |
| 309 | done = &mut stop => Err(done.ok()), |
| 310 | }; |
| 311 | let ended = match connected { |
| 312 | Ok(connection) => self.drive(connection, &mut stop).await, |
| 313 | Err(Some(done)) => Ended::Stopped(Some(done)), |
| 314 | Err(None) => Ended::Lost { was_ready: false }, |
| 315 | }; |
| 316 | match ended { |
| 317 | Ended::Stopped(done) => { |
| 318 | self.unregister().await; |
| 319 | if let Some(done) = done { |
| 320 | let _ = done.send(()); |
| 321 | } |
| 322 | return; |
| 323 | } |
| 324 | Ended::Lost { was_ready } => { |
| 325 | if was_ready { |
| 326 | self.forward(&status_payload("disconnected", "closed")); |
| 327 | } |
| 328 | self.retry += 1; |
| 329 | let delay = Duration::from_secs(1u64 << self.retry.min(5)).min(MAX_BACKOFF); |
| 330 | tokio::select! { |
| 331 | _ = sleep(delay) => {} |
| 332 | done = &mut stop => { |
| 333 | self.unregister().await; |
| 334 | if let Ok(done) = done { |
| 335 | let _ = done.send(()); |
| 336 | } |
| 337 | return; |
| 338 | } |
| 339 | _ = self.output.closed() => return, |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | async fn connect(&mut self) -> Result<Connection, Option<oneshot::Sender<()>>> { |
| 347 | let token = match self.token().await { |
| 348 | Ok(token) => token, |
| 349 | Err(error) => { |
| 350 | self.forward(&status_payload("disconnected", &format!("token_failed: {}", short(&error.to_string())))); |
| 351 | return Err(None); |
| 352 | } |
| 353 | }; |
| 354 | let url = socket_url(&self.host, &self.endpoint_id, &uuid::Uuid::new_v4().to_string(), now_ms() as u128); |
| 355 | let Ok(Ok((socket, _))) = timeout(CONNECT_TIMEOUT, connect_async(url.as_str())).await else { |
| 356 | self.forward(&status_payload("disconnected", "connect_failed")); |
| 357 | return Err(None); |
| 358 | }; |
| 359 | Ok(Connection { |
| 360 | socket, |
| 361 | token, |
| 362 | ready: false, |
| 363 | last_frame: Instant::now(), |
| 364 | sent_activity: None, |
| 365 | activity_ack_id: 0, |
| 366 | activity_due: None, |
| 367 | activity_resend_due: None, |
| 368 | pending: HashMap::new(), |
| 369 | }) |
| 370 | } |
| 371 | |
| 372 | async fn drive(&mut self, mut connection: Connection, stop: &mut oneshot::Receiver<oneshot::Sender<()>>) -> Ended { |
| 373 | let mut ping = interval(PING_EVERY); |
| 374 | ping.set_missed_tick_behavior(MissedTickBehavior::Delay); |
| 375 | ping.tick().await; |
| 376 | let connect_deadline = tokio::time::Instant::now() + CONNECT_TIMEOUT; |
| 377 | loop { |
| 378 | let next_reply = connection.pending.values().map(|pending| pending.deadline).min().unwrap_or_else(far_future); |
| 379 | tokio::select! { |
| 380 | frame = connection.socket.next() => { |
| 381 | let Some(Ok(message)) = frame else { return Ended::Lost { was_ready: connection.ready } }; |
| 382 | let text = match message { |
| 383 | Message::Text(text) => text.to_string(), |
| 384 | Message::Close(_) => return Ended::Lost { was_ready: connection.ready }, |
| 385 | _ => continue, |
| 386 | }; |
| 387 | connection.last_frame = Instant::now(); |
| 388 | if !self.on_frame(&mut connection, &text).await { |
| 389 | let _ = connection.socket.close(None).await; |
| 390 | return Ended::Lost { was_ready: connection.ready }; |
| 391 | } |
| 392 | } |
| 393 | _ = sleep_until(connect_deadline), if !connection.ready => { |
| 394 | let _ = connection.socket.close(None).await; |
| 395 | return Ended::Lost { was_ready: false }; |
| 396 | } |
| 397 | _ = ping.tick() => { |
| 398 | if connection.last_frame.elapsed() > SILENCE_LIMIT { |
| 399 | let _ = connection.socket.close(None).await; |
| 400 | return Ended::Lost { was_ready: connection.ready }; |
| 401 | } |
| 402 | self.send_event(&mut connection, "ping", json!([])).await; |
| 403 | if connection.ready && self.registered_at.is_some_and(|at| at.elapsed() > REREGISTER_AFTER) { |
| 404 | let surl = self.surl.clone(); |
| 405 | if let Err(detail) = self.register(&surl).await { |
| 406 | self.forward(&status_payload("error", &detail)); |
| 407 | } |
| 408 | } |
| 409 | } |
| 410 | changed = self.activity.changed() => { |
| 411 | if changed.is_ok() { |
| 412 | let wanted = *self.activity.borrow_and_update(); |
| 413 | connection.activity_due = (connection.ready && connection.sent_activity != Some(wanted)).then(|| tokio::time::Instant::now() + ACTIVITY_DEBOUNCE); |
| 414 | } |
| 415 | } |
| 416 | _ = sleep_until(connection.activity_due.unwrap_or_else(far_future)), if connection.activity_due.is_some() => { |
| 417 | self.transmit_activity(&mut connection, false).await; |
| 418 | } |
| 419 | _ = sleep_until(connection.activity_resend_due.unwrap_or_else(far_future)), if connection.activity_resend_due.is_some() => { |
| 420 | self.transmit_activity(&mut connection, true).await; |
| 421 | } |
| 422 | _ = self.resend.notified() => self.transmit_activity(&mut connection, false).await, |
| 423 | Some(reply) = self.callbacks.replies.recv() => self.answer(&mut connection, reply).await, |
| 424 | _ = sleep_until(next_reply), if !connection.pending.is_empty() => { |
| 425 | let now = tokio::time::Instant::now(); |
| 426 | let due: Vec<i64> = connection.pending.iter().filter(|(_, pending)| pending.deadline <= now).map(|(id, _)| *id).collect(); |
| 427 | for request_id in due { |
| 428 | self.answer(&mut connection, CallbackReply { request_id, status: 200, body: String::new() }).await; |
| 429 | } |
| 430 | } |
| 431 | done = &mut *stop => { |
| 432 | let _ = connection.socket.close(None).await; |
| 433 | return Ended::Stopped(done.ok()); |
| 434 | } |
| 435 | _ = self.output.closed() => { |
| 436 | let _ = connection.socket.close(None).await; |
| 437 | return Ended::Stopped(None); |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | /// Answers whether the connection should stay open. |
| 444 | async fn on_frame(&mut self, connection: &mut Connection, text: &str) -> bool { |
| 445 | let Some(frame) = parse_frame(text) else { return true }; |
| 446 | match frame.kind { |
| 447 | '1' => { |
| 448 | let authenticate = json!({"name": "user.authenticate", "args": [{"headers": { |
| 449 | "X-Ms-Test-User": "False", "Authorization": format!("Bearer {}", connection.token), "X-MS-Migration": "True", |
| 450 | }}]}); |
| 451 | send(connection, format!("5:::{authenticate}")).await; |
| 452 | } |
| 453 | '2' => send(connection, "2::".to_owned()).await, |
| 454 | '5' => { |
| 455 | let Ok(event) = serde_json::from_str::<Value>(frame.data) else { return true }; |
| 456 | match event.get("name").and_then(Value::as_str) { |
| 457 | Some("trouter.connected") => { |
| 458 | let surl = event.pointer("/args/0/surl").and_then(Value::as_str).unwrap_or_default().to_owned(); |
| 459 | if let Err(detail) = self.register(&surl).await { |
| 460 | self.forward(&status_payload("error", &detail)); |
| 461 | return false; |
| 462 | } |
| 463 | connection.ready = true; |
| 464 | self.retry = 0; |
| 465 | self.transmit_activity(connection, false).await; |
| 466 | let endpoint = json!({"channel": "endpoint", "endpointId": self.endpoint_id, "trouterUri": format!("{}/unifiedPresenceService", self.surl)}); |
| 467 | self.forward(&endpoint.to_string()); |
| 468 | self.forward(&status_payload("connected", "")); |
| 469 | } |
| 470 | Some("trouter.message_loss") => { |
| 471 | let args = event.get("args").cloned().unwrap_or(Value::Null); |
| 472 | let dropped: Vec<String> = args |
| 473 | .pointer("/0/droppedIndicators") |
| 474 | .and_then(Value::as_array) |
| 475 | .into_iter() |
| 476 | .flatten() |
| 477 | .map(|indicator| indicator.get("tag").map(|tag| tag.as_str().map_or_else(|| tag.to_string(), str::to_owned)).unwrap_or_default()) |
| 478 | .collect(); |
| 479 | self.send_event(connection, "trouter.processed_message_loss", args).await; |
| 480 | self.forward(&status_payload("message_loss", &cut(&dropped.join(","), MAX_LOSS_DETAIL))); |
| 481 | } |
| 482 | _ => {} |
| 483 | } |
| 484 | } |
| 485 | '6' => { |
| 486 | if frame.data.split('+').next().and_then(|id| id.parse::<u64>().ok()) == Some(connection.activity_ack_id) { |
| 487 | connection.activity_resend_due = None; |
| 488 | } |
| 489 | } |
| 490 | '3' => { |
| 491 | let Ok(request) = serde_json::from_str::<Value>(frame.data) else { return true }; |
| 492 | let Some(request_id) = request.get("id").and_then(Value::as_i64) else { return true }; |
| 493 | let path = request_path(request.get("url").and_then(Value::as_str).unwrap_or("")); |
| 494 | let raw_body = match request.get("body") { |
| 495 | Some(Value::String(text)) => text.clone(), |
| 496 | Some(Value::Null) | None => "null".to_owned(), |
| 497 | Some(other) => other.to_string(), |
| 498 | }; |
| 499 | let headers = request.get("headers").cloned().unwrap_or(Value::Null); |
| 500 | if self.config.forward_callbacks && path.starts_with(CALLBACK_PREFIX) { |
| 501 | connection.pending.insert(request_id, PendingReply { headers: echoed_headers(&headers), deadline: tokio::time::Instant::now() + CALLBACK_REPLY_TIMEOUT }); |
| 502 | let callback = json!({"channel": "callback", "requestId": request_id, "path": path, |
| 503 | "contentEncoding": header_value(&headers, "X-Microsoft-Skype-Content-Encoding"), "body": raw_body}); |
| 504 | self.forward(&callback.to_string()); |
| 505 | return true; |
| 506 | } |
| 507 | send(connection, format!("3:::{}", json!({"id": request_id, "status": 200, "headers": {}, "body": ""}))).await; |
| 508 | let body = serde_json::from_str::<Value>(&raw_body).ok(); |
| 509 | if self.config.forward_callbacks && body.as_ref().is_some_and(|body| body.get("evt").is_some_and(Value::is_number)) { |
| 510 | let callback = json!({"channel": "callback", "requestId": request_id, "path": "", "contentEncoding": null, "body": raw_body}); |
| 511 | self.forward(&callback.to_string()); |
| 512 | return true; |
| 513 | } |
| 514 | if let Some(payload) = notification_payload(&path, body.as_ref(), now_ms()) { |
| 515 | self.forward(&payload.to_string()); |
| 516 | } |
| 517 | } |
| 518 | _ => {} |
| 519 | } |
| 520 | true |
| 521 | } |
| 522 | |
| 523 | async fn answer(&mut self, connection: &mut Connection, reply: CallbackReply) { |
| 524 | let Some(pending) = connection.pending.remove(&reply.request_id) else { return }; |
| 525 | let frame = json!({"id": reply.request_id, "status": reply.status, "headers": pending.headers, "body": reply.body}); |
| 526 | send(connection, format!("3:::{frame}")).await; |
| 527 | } |
| 528 | |
| 529 | async fn send_event(&mut self, connection: &mut Connection, name: &str, args: Value) { |
| 530 | self.ack_counter += 1; |
| 531 | send(connection, format!("5:{}+::{}", self.ack_counter, json!({"name": name, "args": args}))).await; |
| 532 | } |
| 533 | |
| 534 | async fn transmit_activity(&mut self, connection: &mut Connection, resend: bool) { |
| 535 | connection.activity_due = None; |
| 536 | connection.activity_resend_due = None; |
| 537 | if !connection.ready { |
| 538 | return; |
| 539 | } |
| 540 | let active = *self.activity.borrow(); |
| 541 | let label = if active { "active" } else { "inactive" }; |
| 542 | self.send_event(connection, "user.activity", json!([{"state": label, "cv": uuid::Uuid::new_v4().to_string()}])).await; |
| 543 | connection.sent_activity = Some(active); |
| 544 | connection.activity_ack_id = self.ack_counter; |
| 545 | if !resend { |
| 546 | connection.activity_resend_due = Some(tokio::time::Instant::now() + ACTIVITY_ACK_TIMEOUT); |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | async fn register(&mut self, surl: &str) -> Result<(), String> { |
| 551 | if !surl.is_empty() { |
| 552 | self.surl = surl.to_owned(); |
| 553 | } |
| 554 | let mut request = Request::with_body(Method::Post, REGISTRAR, registration_body(self.config.ringable, &self.endpoint_id, &self.surl)); |
| 555 | request.headers.extend([("X-MS-Migration".to_owned(), "True".to_owned()), ("Accept".to_owned(), "application/json, text/javascript".to_owned())]); |
| 556 | match self.session.send(request, &ic3_scope()).await { |
| 557 | Ok(_) => { |
| 558 | self.registered_at = Some(Instant::now()); |
| 559 | Ok(()) |
| 560 | } |
| 561 | Err(session::Error::Api { status, .. }) => { |
| 562 | if matches!(status, 401 | 403) { |
| 563 | self.force_refresh = true; |
| 564 | } |
| 565 | Err(format!("registrar_http_{status}")) |
| 566 | } |
| 567 | Err(_) => Err("registrar_failed".to_owned()), |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | async fn unregister(&self) { |
| 572 | if self.registered_at.is_none() { |
| 573 | return; |
| 574 | } |
| 575 | let mut request = Request::get(format!("{REGISTRAR}/{}", self.endpoint_id)); |
| 576 | request.method = Method::Delete; |
| 577 | request.headers.push(("X-MS-Migration".to_owned(), "True".to_owned())); |
| 578 | let _ = timeout(STOP_STEP_TIMEOUT, self.session.send(request, &ic3_scope())).await; |
| 579 | } |
| 580 | |
| 581 | fn forward(&mut self, payload: &str) { |
| 582 | if let Some(callback) = decode_callback(payload) { |
| 583 | let _ = self.callbacks.output.send(callback); |
| 584 | return; |
| 585 | } |
| 586 | if let Ok(event) = decode_payload(payload) { |
| 587 | if let RealtimeEvent::Status(StatusEvent { kind: StatusKind::Error, detail }) = &event |
| 588 | && matches!(detail.as_str(), "registrar_http_401" | "registrar_http_403") |
| 589 | { |
| 590 | self.force_refresh = true; |
| 591 | } |
| 592 | let _ = self.output.send(event); |
| 593 | } |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | async fn send(connection: &mut Connection, text: String) { |
| 598 | let _ = connection.socket.send(Message::Text(text.into())).await; |
| 599 | } |
| 600 | |
| 601 | fn short(text: &str) -> String { |
| 602 | text.chars().take(120).collect() |
| 603 | } |
| 604 | |
| 605 | #[cfg(test)] |
| 606 | mod tests { |
| 607 | use super::*; |
| 608 | |
| 609 | #[test] |
| 610 | fn frames_split_into_type_and_data() { |
| 611 | assert_eq!(parse_frame("1::"), Some(Frame { kind: '1', data: "" })); |
| 612 | assert_eq!(parse_frame("5:3+::{\"a\":1}"), Some(Frame { kind: '5', data: "{\"a\":1}" })); |
| 613 | assert_eq!(parse_frame("3:::{\"x\":\"a:b\"}"), Some(Frame { kind: '3', data: "{\"x\":\"a:b\"}" })); |
| 614 | assert_eq!(parse_frame("garbage"), None); |
| 615 | assert_eq!(parse_frame("12::"), None); |
| 616 | } |
| 617 | |
| 618 | #[test] |
| 619 | fn the_socket_url_carries_the_endpoint_and_encoded_client_info() { |
| 620 | let url = socket_url("go-eu.trouter.teams.microsoft.com", "ep-1", "cor-1", 42); |
| 621 | assert!(url.starts_with("wss://go-eu.trouter.teams.microsoft.com/v4/c?tc=%7B%22cv%22"), "{url}"); |
| 622 | assert!(url.ends_with("&timeout=40&epid=ep-1&ccid=&cor_id=cor-1&con_num=42_0"), "{url}"); |
| 623 | } |
| 624 | |
| 625 | #[test] |
| 626 | fn ringable_registration_uses_the_calling_app() { |
| 627 | let calling = registration_body(true, "ep", "https://surl/"); |
| 628 | assert_eq!(calling["clientDescription"]["appId"], "SkypeSpacesWeb"); |
| 629 | assert_eq!(calling["clientDescription"]["productContext"], ""); |
| 630 | let worker = registration_body(false, "ep", "https://surl/"); |
| 631 | assert_eq!(worker["clientDescription"]["templateKey"], "TeamsCDLWebWorker_2.6"); |
| 632 | assert!(worker["clientDescription"].get("productContext").is_none()); |
| 633 | assert_eq!(worker["transports"]["TROUTER"][0]["path"], "https://surl/"); |
| 634 | } |
| 635 | |
| 636 | #[test] |
| 637 | fn callback_replies_echo_chain_request_and_correlation() { |
| 638 | let echoed = echoed_headers(&json!({"x-microsoft-skype-chain-id": "c", "Trouter-Request": "r", "ms-cv": "abc", "Other": "o"})); |
| 639 | assert_eq!(echoed, json!({"X-Microsoft-Skype-Chain-ID": "c", "trouter-request": "r", "MS-CV": "abc.0"})); |
| 640 | } |
| 641 | |
| 642 | #[test] |
| 643 | fn request_paths_drop_the_forwarding_prefix() { |
| 644 | assert_eq!(request_path("/v4/f/abc123/messaging"), "messaging"); |
| 645 | assert_eq!(request_path("/v4/f/abc/callAgent/x/y"), "callAgent/x/y"); |
| 646 | assert_eq!(request_path("messaging"), "messaging"); |
| 647 | } |
| 648 | |
| 649 | #[test] |
| 650 | fn a_message_notification_becomes_the_page_event() { |
| 651 | let body = json!({"resourceType": "NewMessage", "resource": {"messagetype": "RichText/Html", "id": "177", |
| 652 | "conversationLink": "https://emea.ng.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2"}}); |
| 653 | let payload = notification_payload("messaging", Some(&body), 5).unwrap(); |
| 654 | assert_eq!(payload["eventKind"], "new_message"); |
| 655 | assert_eq!(payload["conversationId"], "19:abc@thread.v2"); |
| 656 | assert_eq!(payload["messageId"], "177"); |
| 657 | assert!(matches!(decode_payload(&payload.to_string()), Ok(RealtimeEvent::Message(_)))); |
| 658 | } |
| 659 | |
| 660 | #[test] |
| 661 | fn typing_names_the_sender() { |
| 662 | let body = json!({"resourceType": "NewMessage", "resource": {"messagetype": "Control/Typing", "imdisplayname": "Ada", |
| 663 | "from": "https://x/v1/users/ME/contacts/8:orgid:0a1b2c3d-0000-0000-0000-000000000000", "conversationLink": "conversations/19:t@thread.v2"}}); |
| 664 | let payload = notification_payload("messaging", Some(&body), 5).unwrap(); |
| 665 | assert_eq!(payload["eventKind"], "typing"); |
| 666 | assert_eq!(payload["typing"], "start"); |
| 667 | assert_eq!(payload["senderId"], "0a1b2c3d-0000-0000-0000-000000000000"); |
| 668 | assert_eq!(payload["senderName"], "Ada"); |
| 669 | assert!(payload["messageId"].is_null()); |
| 670 | } |
| 671 | |
| 672 | #[test] |
| 673 | fn presence_keeps_entries_with_an_availability() { |
| 674 | let body = json!({"presence": [{"mri": "8:orgid:a", "presence": {"availability": "Available", "activity": "Available"}}, {"mri": "8:orgid:b"}]}); |
| 675 | let payload = notification_payload("unifiedPresenceService", Some(&body), 5).unwrap(); |
| 676 | assert_eq!(payload["entries"].as_array().unwrap().len(), 1); |
| 677 | assert!(notification_payload("unifiedPresenceService", Some(&json!({"presence": []})), 5).is_none()); |
| 678 | } |
| 679 | } |