| 1 | use std::collections::HashMap; |
| 2 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 3 | use std::sync::{Arc, Mutex}; |
| 4 | use std::time::{Duration, Instant}; |
| 5 | |
| 6 | use chatsvc::{CallbackReplier, InstanceNames, Realtime, RealtimeConfig, RealtimeEvent, TrouterCallback, TrouterEndpoint}; |
| 7 | use session::Session; |
| 8 | use tokio::sync::{mpsc, oneshot}; |
| 9 | use tokio::task::JoinHandle; |
| 10 | use tokio::time::timeout; |
| 11 | |
| 12 | use crate::call::{AcceptMode, CallOptions, CallSpec, IncomingCall, Plan}; |
| 13 | use crate::devices::DeviceChoice; |
| 14 | use crate::control::{CallHandle, call_channel}; |
| 15 | use crate::end::EndKind; |
| 16 | use crate::error::{Error, Result}; |
| 17 | use crate::push::{CallNotification, Caller, PushEvent, decode_push}; |
| 18 | use crate::relay::DEFAULT_RELAY_HOST; |
| 19 | use crate::signaling::{ |
| 20 | AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self, |
| 21 | }; |
| 22 | use crate::timeline::Timeline; |
| 23 | use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, classify, decode_body}; |
| 24 | |
| 25 | const ENDPOINT_WAIT: Duration = Duration::from_secs(30); |
| 26 | const PRESENCE_SUFFIX: &str = "unifiedPresenceService"; |
| 27 | const SEEN_WINDOW: Duration = Duration::from_secs(120); |
| 28 | const RING_ID_START: u64 = 1; |
| 29 | pub const TRACE_ENV: &str = "CALLING_TRACE"; |
| 30 | |
| 31 | pub fn calling_instance_names() -> InstanceNames { |
| 32 | InstanceNames { |
| 33 | global: "__callingTrouter".into(), |
| 34 | binding: "__callingRealtime".into(), |
| 35 | endpoint_storage_key: "__callingEpid".into(), |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | pub fn calling_realtime_config(ringable: bool, instance: InstanceNames) -> RealtimeConfig { |
| 40 | RealtimeConfig { |
| 41 | instance, |
| 42 | forward_callbacks: true, |
| 43 | ringable, |
| 44 | ..RealtimeConfig::default() |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | pub(crate) fn callback_base(trouter_uri: &str) -> String { |
| 49 | let trimmed = trouter_uri.strip_suffix(PRESENCE_SUFFIX).unwrap_or(trouter_uri).trim_end_matches('/'); |
| 50 | format!("{trimmed}/") |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, Clone)] |
| 54 | pub struct EngineConfig { |
| 55 | pub ringable: bool, |
| 56 | pub routing: TenantRouting, |
| 57 | pub relay_host: String, |
| 58 | pub trace: bool, |
| 59 | /// Page globals of the Trouter client; a second engine in the same tab needs its own. |
| 60 | pub instance: InstanceNames, |
| 61 | } |
| 62 | |
| 63 | impl Default for EngineConfig { |
| 64 | fn default() -> Self { |
| 65 | EngineConfig { |
| 66 | ringable: true, |
| 67 | routing: TenantRouting::default(), |
| 68 | relay_host: DEFAULT_RELAY_HOST.to_owned(), |
| 69 | trace: std::env::var_os(TRACE_ENV).is_some(), |
| 70 | instance: calling_instance_names(), |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | #[derive(Debug, Clone, PartialEq)] |
| 76 | pub struct IncomingRing { |
| 77 | pub ring_id: u64, |
| 78 | pub caller: Caller, |
| 79 | pub thread_id: Option<String>, |
| 80 | pub video: bool, |
| 81 | pub is_group: bool, |
| 82 | pub subject: Option<String>, |
| 83 | } |
| 84 | |
| 85 | #[derive(Debug, Clone, PartialEq)] |
| 86 | pub enum EngineEvent { |
| 87 | Incoming(IncomingRing), |
| 88 | RingEnded { |
| 89 | ring_id: u64, |
| 90 | kind: EndKind, |
| 91 | answered_by: Option<String>, |
| 92 | }, |
| 93 | } |
| 94 | |
| 95 | enum RingCommand { |
| 96 | Accept(AcceptMode, oneshot::Sender<Option<CallHandle>>), |
| 97 | Decline, |
| 98 | Drop, |
| 99 | } |
| 100 | |
| 101 | pub(crate) struct Inner { |
| 102 | pub(crate) session: Session, |
| 103 | pub(crate) poll_session: Session, |
| 104 | pub(crate) config: EngineConfig, |
| 105 | pub(crate) identity: SelfIdentity, |
| 106 | pub(crate) replier: CallbackReplier, |
| 107 | pub(crate) gate: Arc<tokio::sync::Mutex<()>>, |
| 108 | endpoint: Mutex<TrouterEndpoint>, |
| 109 | routes: Mutex<HashMap<String, mpsc::UnboundedSender<TrouterCallback>>>, |
| 110 | rings: Mutex<HashMap<u64, mpsc::UnboundedSender<RingCommand>>>, |
| 111 | seen: Mutex<HashMap<(String, String), Instant>>, |
| 112 | next_ring_id: AtomicU64, |
| 113 | default_camera: Mutex<DeviceChoice>, |
| 114 | runtime: tokio::runtime::Handle, |
| 115 | events: mpsc::UnboundedSender<EngineEvent>, |
| 116 | stop: Mutex<Option<oneshot::Sender<()>>>, |
| 117 | tasks: Mutex<Vec<JoinHandle<()>>>, |
| 118 | } |
| 119 | |
| 120 | impl Inner { |
| 121 | pub(crate) fn endpoint(&self) -> TrouterEndpoint { |
| 122 | self.endpoint.lock().expect("endpoint lock").clone() |
| 123 | } |
| 124 | |
| 125 | pub(crate) fn register_route(&self, call_id: &str) -> mpsc::UnboundedReceiver<TrouterCallback> { |
| 126 | let (sender, receiver) = mpsc::unbounded_channel(); |
| 127 | self.routes.lock().expect("routes lock").insert(call_id.to_owned(), sender); |
| 128 | receiver |
| 129 | } |
| 130 | |
| 131 | pub(crate) fn unregister_route(&self, call_id: &str) { |
| 132 | self.routes.lock().expect("routes lock").remove(call_id); |
| 133 | } |
| 134 | |
| 135 | pub(crate) fn participant(&self, participant_id: &str) -> Participant { |
| 136 | Participant { |
| 137 | mri: format!("8:orgid:{}", self.identity.object_id), |
| 138 | display_name: self.identity.display_name.clone(), |
| 139 | endpoint_id: self.endpoint().endpoint_id, |
| 140 | participant_id: participant_id.to_owned(), |
| 141 | language_id: "en-gb".into(), |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | pub(crate) fn callback_links(&self) -> CallbackLinks { |
| 146 | CallbackLinks::new(&callback_base(&self.endpoint().trouter_uri), &uuid::Uuid::new_v4().to_string()) |
| 147 | } |
| 148 | |
| 149 | pub(crate) fn signaling(&self, timeline: Timeline) -> Signaling { |
| 150 | Signaling::new(self.session.clone(), self.poll_session.clone(), self.config.routing.clone(), timeline) |
| 151 | } |
| 152 | |
| 153 | pub(crate) fn call_options(&self) -> CallOptions { |
| 154 | CallOptions { |
| 155 | relay_host: self.config.relay_host.clone(), |
| 156 | routing: self.config.routing.clone(), |
| 157 | trace: self.config.trace, |
| 158 | camera: self.default_camera.lock().expect("default camera lock").clone(), |
| 159 | ..CallOptions::default() |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | fn route(&self, callback: TrouterCallback) { |
| 164 | let Some(call_id) = callback_call_id(&callback.path) else { |
| 165 | self.replier.reply(callback.request_id, 200, ""); |
| 166 | return; |
| 167 | }; |
| 168 | let sender = self.routes.lock().expect("routes lock").get(&call_id).cloned(); |
| 169 | match sender { |
| 170 | Some(sender) => { |
| 171 | if let Err(rejected) = sender.send(callback) { |
| 172 | self.replier.reply(rejected.0.request_id, 200, ""); |
| 173 | } |
| 174 | } |
| 175 | None => self.replier.reply(callback.request_id, 200, ""), |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | fn already_seen(&self, notification: &CallNotification) -> bool { |
| 180 | let mut seen = self.seen.lock().expect("seen lock"); |
| 181 | let now = Instant::now(); |
| 182 | seen.retain(|_, at| now.duration_since(*at) < SEEN_WINDOW); |
| 183 | seen.insert(notification.dedupe_key(), now).is_some() |
| 184 | } |
| 185 | |
| 186 | fn emit(&self, event: EngineEvent) { |
| 187 | let _ = self.events.send(event); |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | #[derive(Clone)] |
| 192 | pub struct CallEngine { |
| 193 | pub(crate) inner: Arc<Inner>, |
| 194 | } |
| 195 | |
| 196 | impl CallEngine { |
| 197 | pub async fn start( |
| 198 | session: Session, |
| 199 | poll_session: Session, |
| 200 | config: EngineConfig, |
| 201 | ) -> Result<(CallEngine, mpsc::UnboundedReceiver<EngineEvent>)> { |
| 202 | let mut realtime = Realtime::start_with(&session, calling_realtime_config(config.ringable, config.instance.clone())).await?; |
| 203 | let callbacks = realtime |
| 204 | .take_callbacks() |
| 205 | .ok_or_else(|| Error::Callback("callback stream already taken".into()))?; |
| 206 | let replier = realtime.callback_replier(); |
| 207 | let endpoint = timeout(ENDPOINT_WAIT, async { |
| 208 | while let Some(event) = realtime.recv().await { |
| 209 | if let RealtimeEvent::Endpoint(endpoint) = event { |
| 210 | return Some(endpoint); |
| 211 | } |
| 212 | } |
| 213 | None |
| 214 | }) |
| 215 | .await |
| 216 | .ok() |
| 217 | .flatten(); |
| 218 | let Some(endpoint) = endpoint else { |
| 219 | realtime.stop().await; |
| 220 | return Err(Error::Callback("Trouter socket never announced its endpoint".into())); |
| 221 | }; |
| 222 | let identity = match fetch_self(&session).await { |
| 223 | Ok(identity) => identity, |
| 224 | Err(error) => { |
| 225 | realtime.stop().await; |
| 226 | return Err(error); |
| 227 | } |
| 228 | }; |
| 229 | let (events, event_receiver) = mpsc::unbounded_channel(); |
| 230 | let (stop, stop_receiver) = oneshot::channel(); |
| 231 | let inner = Arc::new(Inner { |
| 232 | session, |
| 233 | poll_session, |
| 234 | config, |
| 235 | identity, |
| 236 | replier, |
| 237 | gate: Arc::new(tokio::sync::Mutex::new(())), |
| 238 | endpoint: Mutex::new(endpoint), |
| 239 | routes: Mutex::default(), |
| 240 | rings: Mutex::default(), |
| 241 | seen: Mutex::default(), |
| 242 | next_ring_id: AtomicU64::new(RING_ID_START), |
| 243 | default_camera: Mutex::new(DeviceChoice::SystemDefault), |
| 244 | runtime: tokio::runtime::Handle::current(), |
| 245 | events, |
| 246 | stop: Mutex::new(Some(stop)), |
| 247 | tasks: Mutex::default(), |
| 248 | }); |
| 249 | let engine = CallEngine { inner: inner.clone() }; |
| 250 | let pump = tokio::spawn(pump_realtime(realtime, inner.clone(), stop_receiver)); |
| 251 | let router = tokio::spawn(route_callbacks(callbacks, engine.clone())); |
| 252 | inner.tasks.lock().expect("tasks lock").extend([pump, router]); |
| 253 | Ok((engine, event_receiver)) |
| 254 | } |
| 255 | |
| 256 | pub fn session(&self) -> Session { |
| 257 | self.inner.session.clone() |
| 258 | } |
| 259 | |
| 260 | pub fn start_call(&self, spec: CallSpec) -> CallHandle { |
| 261 | self.start_call_with(spec, false) |
| 262 | } |
| 263 | |
| 264 | pub fn start_consult(&self, spec: CallSpec) -> CallHandle { |
| 265 | self.start_call_with(spec, true) |
| 266 | } |
| 267 | |
| 268 | fn start_call_with(&self, spec: CallSpec, concurrent: bool) -> CallHandle { |
| 269 | let (handle, control) = call_channel(); |
| 270 | let engine = self.clone(); |
| 271 | self.inner.runtime.spawn(async move { |
| 272 | let options = CallOptions { concurrent, ..engine.inner.call_options() }; |
| 273 | let _ = engine.run(Plan::Outgoing(spec), options, control).await; |
| 274 | }); |
| 275 | handle |
| 276 | } |
| 277 | |
| 278 | pub async fn accept_ring(&self, ring_id: u64, mode: AcceptMode) -> Option<CallHandle> { |
| 279 | let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned()?; |
| 280 | let (answer, handle) = oneshot::channel(); |
| 281 | commands.send(RingCommand::Accept(mode, answer)).ok()?; |
| 282 | handle.await.ok().flatten() |
| 283 | } |
| 284 | |
| 285 | /// Only for a click on Decline: it ends the call for all of the user's devices. |
| 286 | pub fn set_default_camera(&self, camera: DeviceChoice) { |
| 287 | *self.inner.default_camera.lock().expect("default camera lock") = camera; |
| 288 | } |
| 289 | |
| 290 | pub fn decline_ring(&self, ring_id: u64) { |
| 291 | self.send_ring_command(ring_id, RingCommand::Decline); |
| 292 | } |
| 293 | |
| 294 | /// Stops ringing locally without telling Teams; the call keeps ringing elsewhere. |
| 295 | pub fn drop_ring(&self, ring_id: u64) { |
| 296 | self.send_ring_command(ring_id, RingCommand::Drop); |
| 297 | } |
| 298 | |
| 299 | fn send_ring_command(&self, ring_id: u64, command: RingCommand) { |
| 300 | let commands = self.inner.rings.lock().expect("rings lock").get(&ring_id).cloned(); |
| 301 | if let Some(commands) = commands { |
| 302 | let _ = commands.send(command); |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | pub async fn resolve_meeting(&self, meeting_data: &serde_json::Value) -> Result<MeetingTarget> { |
| 307 | let signaling = self.inner.signaling(Timeline::new(self.inner.config.trace)); |
| 308 | let from = self.inner.participant(&uuid::Uuid::new_v4().to_string()); |
| 309 | let (target, conversation) = signaling |
| 310 | .resolve_meeting(&from, &self.inner.callback_links(), meeting_data) |
| 311 | .await?; |
| 312 | let _ = signaling.leave(&conversation, &from, LeaveReason::Cancel).await; |
| 313 | Ok(target) |
| 314 | } |
| 315 | |
| 316 | pub async fn stop(&self) { |
| 317 | let stop = self.inner.stop.lock().expect("stop lock").take(); |
| 318 | if let Some(stop) = stop { |
| 319 | let _ = stop.send(()); |
| 320 | } |
| 321 | let tasks: Vec<JoinHandle<()>> = std::mem::take(&mut *self.inner.tasks.lock().expect("tasks lock")); |
| 322 | for task in tasks { |
| 323 | let _ = task.await; |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | async fn pump_realtime(mut realtime: Realtime, inner: Arc<Inner>, mut stop: oneshot::Receiver<()>) { |
| 329 | let mut last_status = None; |
| 330 | loop { |
| 331 | tokio::select! { |
| 332 | event = realtime.recv() => match event { |
| 333 | Some(RealtimeEvent::Endpoint(endpoint)) => *inner.endpoint.lock().expect("endpoint lock") = endpoint, |
| 334 | Some(RealtimeEvent::Status(status)) => { |
| 335 | if last_status.as_ref() != Some(&status) { |
| 336 | eprintln!("calls: trouter {:?} {}", status.kind, status.detail); |
| 337 | last_status = Some(status); |
| 338 | } |
| 339 | } |
| 340 | Some(_) => {} |
| 341 | None => return, |
| 342 | }, |
| 343 | _ = &mut stop => { |
| 344 | realtime.stop().await; |
| 345 | return; |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | async fn route_callbacks(mut callbacks: mpsc::UnboundedReceiver<TrouterCallback>, engine: CallEngine) { |
| 352 | while let Some(callback) = callbacks.recv().await { |
| 353 | if callback.path.is_empty() { |
| 354 | engine.handle_push(callback); |
| 355 | } else { |
| 356 | engine.inner.route(callback); |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | impl CallEngine { |
| 362 | fn handle_push(&self, callback: TrouterCallback) { |
| 363 | self.inner.replier.reply(callback.request_id, 200, ""); |
| 364 | if !self.inner.config.ringable { |
| 365 | return; |
| 366 | } |
| 367 | let Ok(PushEvent::IncomingCall(notification)) = decode_push(&callback.body) else { |
| 368 | return; |
| 369 | }; |
| 370 | let notification = *notification; |
| 371 | if self.inner.already_seen(¬ification) { |
| 372 | return; |
| 373 | } |
| 374 | let ring_id = self.inner.next_ring_id.fetch_add(1, Ordering::SeqCst); |
| 375 | let (commands, receiver) = mpsc::unbounded_channel(); |
| 376 | self.inner.rings.lock().expect("rings lock").insert(ring_id, commands); |
| 377 | tokio::spawn(ring_task(self.clone(), notification, ring_id, receiver)); |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | async fn ring_task( |
| 382 | engine: CallEngine, |
| 383 | notification: CallNotification, |
| 384 | ring_id: u64, |
| 385 | mut commands: mpsc::UnboundedReceiver<RingCommand>, |
| 386 | ) { |
| 387 | let inner = engine.inner.clone(); |
| 388 | let links = inner.callback_links(); |
| 389 | let route_id = links.call_id().to_owned(); |
| 390 | let mut callbacks = inner.register_route(&route_id); |
| 391 | let timeline = Timeline::new(inner.config.trace); |
| 392 | let signaling = inner.signaling(timeline.clone()); |
| 393 | let participant_id = if notification.participant_id.is_empty() { |
| 394 | uuid::Uuid::new_v4().to_string() |
| 395 | } else { |
| 396 | notification.participant_id.clone() |
| 397 | }; |
| 398 | let participant = inner.participant(&participant_id); |
| 399 | let cleanup = |inner: &Inner| { |
| 400 | inner.unregister_route(&route_id); |
| 401 | inner.rings.lock().expect("rings lock").remove(&ring_id); |
| 402 | }; |
| 403 | let Some(attach_url) = notification.links.get("attach") else { |
| 404 | cleanup(&inner); |
| 405 | return; |
| 406 | }; |
| 407 | let request = AttachRequest { |
| 408 | from: &participant, |
| 409 | callbacks: &links, |
| 410 | controller: notification.conversation_controller.as_deref(), |
| 411 | needs_media: notification.offer_sdp.is_none(), |
| 412 | }; |
| 413 | let mut attached = match signaling.attach(attach_url, &request).await { |
| 414 | Ok(attached) => attached, |
| 415 | Err(error) => { |
| 416 | timeline.record("attach failed", error.to_string()); |
| 417 | cleanup(&inner); |
| 418 | return; |
| 419 | } |
| 420 | }; |
| 421 | if attached.offer_sdp.is_none() { |
| 422 | attached.offer_sdp = notification.offer_sdp.clone(); |
| 423 | } |
| 424 | if let Some(progress) = attached.links.get("progress") |
| 425 | && let Err(error) = signaling.send_ringing(progress, &participant).await |
| 426 | { |
| 427 | timeline.record("ringing progress failed", error.to_string()); |
| 428 | } |
| 429 | inner.emit(EngineEvent::Incoming(IncomingRing { |
| 430 | ring_id, |
| 431 | caller: notification.caller.clone(), |
| 432 | thread_id: notification.thread_id.clone(), |
| 433 | video: notification.video, |
| 434 | is_group: notification.is_multi_party, |
| 435 | subject: notification.subject.clone(), |
| 436 | })); |
| 437 | loop { |
| 438 | tokio::select! { |
| 439 | callback = callbacks.recv() => { |
| 440 | let Some(callback) = callback else { break }; |
| 441 | inner.replier.reply(callback.request_id, 200, ""); |
| 442 | let event = decode_body(&callback).and_then(|body| classify(&callback.path, body)); |
| 443 | if let Ok((_, CallEvent::End(end))) = event { |
| 444 | inner.emit(EngineEvent::RingEnded { |
| 445 | ring_id, |
| 446 | kind: end.kind(), |
| 447 | answered_by: end.accepted_elsewhere_by, |
| 448 | }); |
| 449 | break; |
| 450 | } |
| 451 | } |
| 452 | command = commands.recv() => match command { |
| 453 | Some(RingCommand::Accept(accept, answer)) => { |
| 454 | let (handle, control) = call_channel(); |
| 455 | let incoming = IncomingCall { |
| 456 | accept, |
| 457 | notification, |
| 458 | attached, |
| 459 | links, |
| 460 | participant, |
| 461 | callbacks, |
| 462 | }; |
| 463 | let _ = answer.send(Some(handle)); |
| 464 | inner.rings.lock().expect("rings lock").remove(&ring_id); |
| 465 | let options = inner.call_options(); |
| 466 | tokio::spawn(async move { |
| 467 | let _ = engine.run(Plan::Incoming(Box::new(incoming)), options, control).await; |
| 468 | }); |
| 469 | return; |
| 470 | } |
| 471 | Some(RingCommand::Decline) => { |
| 472 | if let Some(call_leg) = attached.links.get("callLeg") |
| 473 | && let Err(error) = signaling.decline(call_leg).await |
| 474 | { |
| 475 | timeline.record("decline failed", error.to_string()); |
| 476 | } |
| 477 | break; |
| 478 | } |
| 479 | Some(RingCommand::Drop) | None => break, |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | cleanup(&inner); |
| 484 | } |
| 485 | |
| 486 | #[cfg(test)] |
| 487 | mod tests { |
| 488 | use super::*; |
| 489 | |
| 490 | #[test] |
| 491 | fn callback_base_comes_from_the_presence_uri() { |
| 492 | assert_eq!( |
| 493 | callback_base("https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc//unifiedPresenceService"), |
| 494 | "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc/" |
| 495 | ); |
| 496 | assert_eq!(callback_base("https://h/v4/f/abc/unifiedPresenceService"), "https://h/v4/f/abc/"); |
| 497 | } |
| 498 | |
| 499 | #[test] |
| 500 | fn only_the_ringable_engine_registers_for_calls() { |
| 501 | assert!(calling_realtime_config(true, calling_instance_names()).ringable); |
| 502 | assert!(!calling_realtime_config(false, calling_instance_names()).ringable); |
| 503 | assert!(calling_realtime_config(true, calling_instance_names()).forward_callbacks); |
| 504 | } |
| 505 | } |