| 1 | use std::collections::BTreeMap; |
| 2 | |
| 3 | use serde_json::{Map, Value, json}; |
| 4 | use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session}; |
| 5 | |
| 6 | use crate::captions::{self, BotAction}; |
| 7 | use crate::error::{Error, Result}; |
| 8 | use crate::organizer::{self, Invitee, Target}; |
| 9 | use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message}; |
| 10 | use crate::recording::{self, Consent, RecordingCommand, StartDetails}; |
| 11 | use crate::relay::ic3_scope; |
| 12 | use crate::roster::MeetingRole; |
| 13 | use crate::timeline::Timeline; |
| 14 | use crate::transfer::{self, TransferTarget}; |
| 15 | use crate::trouter_events::{CallbackLinks, acceptance_links, acknowledgement_links}; |
| 16 | use crate::video_layout::MediaDescription; |
| 17 | |
| 18 | pub const EPCONV_URL: &str = "https://api-emea.flightproxy.teams.microsoft.com/api/v2/epconv"; |
| 19 | pub const ECHO_BOT_MRI: &str = "28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0"; |
| 20 | pub const CHATSVC_REGION: &str = "emea"; |
| 21 | const CLIENT_HEADER: &str = "SkypeSpaces/1415/26091712213/os=windows; osVer=NT 10.0; deviceType=computer; browser=chrome; browserVer=155.0.0.0/TsCallingVersion=2026.36.01.5/Ovb=97a9cc3f0dd74681da27f28dfcebcf05da30ef6e"; |
| 22 | const PLATFORM_NAME: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36"; |
| 23 | const SDP_CONTENT_TYPE: &str = "application/sdp-ngc-1.0"; |
| 24 | const ENDPOINT_CAPABILITIES: u64 = 73463; |
| 25 | const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces"; |
| 26 | const DIRECT_REQUIRED_FEATURES: &str = "nonByPass"; |
| 27 | const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826; |
| 28 | const ALLOWED_HOST_SUFFIXES: [&str; 2] = |
| 29 | [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"]; |
| 30 | const BACKEND_SUFFIX: &str = ".skype.com"; |
| 31 | const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite"; |
| 32 | const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep"; |
| 33 | const CONVERSATION_LINK_NAMES: [&str; 11] = [ |
| 34 | "conversationEnd", |
| 35 | "conversationUpdate", |
| 36 | "localParticipantUpdate", |
| 37 | "addParticipantSuccess", |
| 38 | "addParticipantFailure", |
| 39 | "addModalitySuccess", |
| 40 | "addModalityFailure", |
| 41 | "confirmUnmute", |
| 42 | "receiveMessage", |
| 43 | "contentSharingUpdate", |
| 44 | "contentSharingEnd", |
| 45 | ]; |
| 46 | const SUBSCRIBE_LINK_NAMES: [&str; 6] = [ |
| 47 | "conversationEnd", |
| 48 | "conversationUpdate", |
| 49 | "localParticipantUpdate", |
| 50 | "addParticipantSuccess", |
| 51 | "addParticipantFailure", |
| 52 | "receiveMessage", |
| 53 | ]; |
| 54 | const CALL_LINK_NAMES: [&str; 5] = [ |
| 55 | "progress", |
| 56 | "mediaAnswer", |
| 57 | "acceptance", |
| 58 | "redirection", |
| 59 | "end", |
| 60 | ]; |
| 61 | const AUDIO_MODALITIES: [&str; 1] = ["Audio"]; |
| 62 | pub(crate) const MEETING_MESSAGE_ID: &str = "0"; |
| 63 | const RAISE_HANDS: &str = "raiseHands"; |
| 64 | const CANCEL_CODE: i64 = 487; |
| 65 | const DECLINE_CODE: i64 = 603; |
| 66 | |
| 67 | #[derive(Debug, Clone)] |
| 68 | pub struct Participant { |
| 69 | pub mri: String, |
| 70 | pub display_name: String, |
| 71 | pub endpoint_id: String, |
| 72 | pub participant_id: String, |
| 73 | pub language_id: String, |
| 74 | } |
| 75 | |
| 76 | impl Participant { |
| 77 | pub fn wire(&self) -> Value { |
| 78 | json!({ |
| 79 | "id": self.mri, |
| 80 | "displayName": self.display_name, |
| 81 | "endpointId": self.endpoint_id, |
| 82 | "participantId": self.participant_id, |
| 83 | "languageId": self.language_id, |
| 84 | }) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 89 | pub struct Callee { |
| 90 | pub mri: String, |
| 91 | pub display_name: String, |
| 92 | } |
| 93 | |
| 94 | #[derive(Debug, Clone, PartialEq)] |
| 95 | pub struct MeetingTarget { |
| 96 | pub thread_id: String, |
| 97 | pub tenant_id: String, |
| 98 | pub organizer_id: String, |
| 99 | pub meeting_data: Option<Value>, |
| 100 | } |
| 101 | |
| 102 | #[derive(Debug, Clone, PartialEq)] |
| 103 | pub enum InviteTarget { |
| 104 | Echo, |
| 105 | People { |
| 106 | callees: Vec<Callee>, |
| 107 | thread_id: String, |
| 108 | }, |
| 109 | Meeting(MeetingTarget), |
| 110 | } |
| 111 | |
| 112 | #[derive(Debug, Clone)] |
| 113 | pub struct TenantRouting { |
| 114 | pub region: String, |
| 115 | pub partition: String, |
| 116 | pub ring: String, |
| 117 | } |
| 118 | |
| 119 | impl Default for TenantRouting { |
| 120 | fn default() -> Self { |
| 121 | TenantRouting { |
| 122 | region: "de".into(), |
| 123 | partition: "de01".into(), |
| 124 | ring: "general".into(), |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | #[derive(Debug, Clone)] |
| 130 | pub struct Conversation { |
| 131 | pub controller: String, |
| 132 | pub links: BTreeMap<String, String>, |
| 133 | pub chat_thread: Option<String>, |
| 134 | pub roster: Option<Value>, |
| 135 | } |
| 136 | |
| 137 | impl Conversation { |
| 138 | pub fn link(&self, name: &str) -> Result<&str> { |
| 139 | self.links |
| 140 | .get(name) |
| 141 | .map(String::as_str) |
| 142 | .ok_or_else(|| Error::Signaling(format!("conversation has no '{name}' link"))) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | fn host_of(url: &str) -> Result<&str> { |
| 147 | url.strip_prefix("https://") |
| 148 | .and_then(|rest| rest.split(['/', '?']).next()) |
| 149 | .map(|authority| authority.split(':').next().unwrap_or(authority)) |
| 150 | .ok_or_else(|| Error::Signaling("link is not https".into())) |
| 151 | } |
| 152 | |
| 153 | /// Bearer requests only go to Teams hosts; links come from server answers. |
| 154 | pub fn ensure_teams_url(url: &str) -> Result<()> { |
| 155 | let host = host_of(url)?; |
| 156 | if ALLOWED_HOST_SUFFIXES |
| 157 | .iter() |
| 158 | .any(|suffix| host.ends_with(suffix)) |
| 159 | || host == "teams.microsoft.com" |
| 160 | { |
| 161 | Ok(()) |
| 162 | } else { |
| 163 | Err(Error::Signaling(format!("refusing link to host {host}"))) |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | fn is_backend_host(host: &str) -> bool { |
| 168 | host.len() > BACKEND_SUFFIX.len() |
| 169 | && host.ends_with(BACKEND_SUFFIX) |
| 170 | && !host.starts_with('.') |
| 171 | && !host.contains("..") |
| 172 | && host.bytes().all(|byte| { |
| 173 | byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-' |
| 174 | }) |
| 175 | } |
| 176 | |
| 177 | /// Push links may name a backend host directly; the browser always reaches those through flightproxy. |
| 178 | pub fn routed_url(url: &str) -> Result<String> { |
| 179 | let host = host_of(url)?; |
| 180 | if !is_backend_host(host) { |
| 181 | ensure_teams_url(url)?; |
| 182 | return Ok(url.to_owned()); |
| 183 | } |
| 184 | let rest = &url["https://".len()..]; |
| 185 | let path = rest |
| 186 | .find(['/', '?']) |
| 187 | .map_or("", |position| &rest[position..]); |
| 188 | Ok(format!("{FLIGHTPROXY_EP}/{host}{path}")) |
| 189 | } |
| 190 | |
| 191 | const FAILURE_BODY_CHARS: usize = 240; |
| 192 | |
| 193 | /// Status plus a short body excerpt for the timeline and `Error::Signaling`. |
| 194 | pub(crate) fn signaling_failure_detail(status: u16, body: &str) -> String { |
| 195 | let reason: String = body.chars().take(FAILURE_BODY_CHARS).collect(); |
| 196 | format!("HTTP {status} {reason}") |
| 197 | } |
| 198 | |
| 199 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 200 | pub enum LeaveReason { |
| 201 | Hangup, |
| 202 | Cancel, |
| 203 | } |
| 204 | |
| 205 | fn spaces_scope() -> Scope { |
| 206 | Scope::new(SPACES, AUTHZ_SCOPE_NAME) |
| 207 | } |
| 208 | |
| 209 | pub struct Signaling { |
| 210 | session: Session, |
| 211 | poll_session: Session, |
| 212 | chain_id: String, |
| 213 | routing: TenantRouting, |
| 214 | timeline: Timeline, |
| 215 | endpoint_state_sequence: std::sync::atomic::AtomicU32, |
| 216 | state_sequence: std::sync::atomic::AtomicU32, |
| 217 | } |
| 218 | |
| 219 | pub struct Invitation<'a> { |
| 220 | pub from: &'a Participant, |
| 221 | pub offer_sdp: &'a str, |
| 222 | pub media_leg_id: &'a str, |
| 223 | pub callbacks: &'a CallbackLinks, |
| 224 | pub target: &'a InviteTarget, |
| 225 | pub modalities: &'a [String], |
| 226 | pub direct: bool, |
| 227 | } |
| 228 | |
| 229 | impl Invitation<'_> { |
| 230 | pub fn is_direct(&self) -> bool { |
| 231 | self.direct && self.target.is_one_to_one() |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | pub struct Answer<'a> { |
| 236 | pub from: &'a Participant, |
| 237 | pub answer_sdp: &'a str, |
| 238 | pub media_leg_id: &'a str, |
| 239 | pub callbacks: &'a CallbackLinks, |
| 240 | pub modalities: &'a [String], |
| 241 | } |
| 242 | |
| 243 | pub struct AttachRequest<'a> { |
| 244 | pub from: &'a Participant, |
| 245 | pub callbacks: &'a CallbackLinks, |
| 246 | pub controller: Option<&'a str>, |
| 247 | pub needs_media: bool, |
| 248 | } |
| 249 | |
| 250 | #[derive(Debug, Clone)] |
| 251 | pub struct Attached { |
| 252 | pub offer_sdp: Option<String>, |
| 253 | pub from_mixer: bool, |
| 254 | pub modalities: Vec<String>, |
| 255 | pub links: BTreeMap<String, String>, |
| 256 | pub conversation: Option<Conversation>, |
| 257 | } |
| 258 | |
| 259 | impl Signaling { |
| 260 | /// `poll_session` is a second CDP connection so the broker long poll never blocks the call requests. |
| 261 | pub fn new( |
| 262 | session: Session, |
| 263 | poll_session: Session, |
| 264 | routing: TenantRouting, |
| 265 | timeline: Timeline, |
| 266 | ) -> Self { |
| 267 | Signaling { |
| 268 | session, |
| 269 | poll_session, |
| 270 | chain_id: uuid::Uuid::new_v4().to_string(), |
| 271 | routing, |
| 272 | timeline, |
| 273 | endpoint_state_sequence: std::sync::atomic::AtomicU32::new(2), |
| 274 | state_sequence: std::sync::atomic::AtomicU32::new(0), |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | fn request(&self, method: Method, url: &str, body: Option<Value>) -> Request { |
| 279 | let mut request = match body { |
| 280 | Some(body) => Request::with_body(method, url, body), |
| 281 | None => Request { |
| 282 | method, |
| 283 | ..Request::get(url) |
| 284 | }, |
| 285 | }; |
| 286 | request.headers = vec![ |
| 287 | ("X-Microsoft-Skype-Chain-ID".into(), self.chain_id.clone()), |
| 288 | ( |
| 289 | "X-Microsoft-Skype-Message-ID".into(), |
| 290 | uuid::Uuid::new_v4().to_string(), |
| 291 | ), |
| 292 | ("X-Microsoft-Skype-Client".into(), CLIENT_HEADER.into()), |
| 293 | ("MS-Teams-Region".into(), self.routing.region.clone()), |
| 294 | ("MS-Teams-Partition".into(), self.routing.partition.clone()), |
| 295 | ("MS-Teams-Ring".into(), self.routing.ring.clone()), |
| 296 | ("X-MS-Migration".into(), "True".into()), |
| 297 | ("content-type".into(), "application/json".into()), |
| 298 | ]; |
| 299 | request |
| 300 | } |
| 301 | |
| 302 | async fn exchange( |
| 303 | &self, |
| 304 | session: &Session, |
| 305 | label: &str, |
| 306 | mut request: Request, |
| 307 | ) -> Result<ApiResponse> { |
| 308 | request.url = routed_url(&request.url)?; |
| 309 | let response = session.batch(&[request], &ic3_scope()).await?.remove(0); |
| 310 | if response.is_success() { |
| 311 | self.timeline |
| 312 | .record(label, format!("HTTP {}", response.status)); |
| 313 | return Ok(response); |
| 314 | } |
| 315 | let detail = signaling_failure_detail(response.status, &response.body.to_string()); |
| 316 | self.timeline.record(label, detail.clone()); |
| 317 | Err(Error::Signaling(format!("{label} answered {detail}"))) |
| 318 | } |
| 319 | |
| 320 | async fn send( |
| 321 | &self, |
| 322 | label: &str, |
| 323 | method: Method, |
| 324 | url: &str, |
| 325 | body: Option<Value>, |
| 326 | ) -> Result<ApiResponse> { |
| 327 | self.exchange(&self.session, label, self.request(method, url, body)) |
| 328 | .await |
| 329 | } |
| 330 | |
| 331 | pub async fn post_json(&self, label: &str, url: &str, body: Value) -> Result<()> { |
| 332 | self.send(label, Method::Post, url, Some(body)) |
| 333 | .await |
| 334 | .map(|_| ()) |
| 335 | } |
| 336 | |
| 337 | pub async fn post_json_body(&self, label: &str, url: &str, body: Value) -> Result<Value> { |
| 338 | self.send(label, Method::Post, url, Some(body)) |
| 339 | .await |
| 340 | .map(|response| response.body) |
| 341 | } |
| 342 | |
| 343 | pub async fn post_empty(&self, label: &str, url: &str) -> Result<()> { |
| 344 | self.send(label, Method::Post, url, None).await.map(|_| ()) |
| 345 | } |
| 346 | |
| 347 | pub async fn create_conversation(&self, invitation: &Invitation<'_>) -> Result<Conversation> { |
| 348 | let response = self |
| 349 | .send( |
| 350 | "POST epconv", |
| 351 | Method::Post, |
| 352 | EPCONV_URL, |
| 353 | Some(epconv_body(invitation)), |
| 354 | ) |
| 355 | .await?; |
| 356 | conversation_from(&response.body) |
| 357 | } |
| 358 | |
| 359 | pub async fn subscribe_meeting( |
| 360 | &self, |
| 361 | from: &Participant, |
| 362 | callbacks: &CallbackLinks, |
| 363 | meeting: &MeetingTarget, |
| 364 | ) -> Result<Conversation> { |
| 365 | let body = subscribe_body(from, callbacks, meeting); |
| 366 | let response = self |
| 367 | .send( |
| 368 | "POST epconv subscribe", |
| 369 | Method::Post, |
| 370 | EPCONV_URL, |
| 371 | Some(body), |
| 372 | ) |
| 373 | .await?; |
| 374 | conversation_from(&response.body) |
| 375 | } |
| 376 | |
| 377 | /// Opens a roster-only conversation for the meeting ID; the caller leaves it once the target is read. |
| 378 | pub async fn resolve_meeting( |
| 379 | &self, |
| 380 | from: &Participant, |
| 381 | callbacks: &CallbackLinks, |
| 382 | meeting_data: &Value, |
| 383 | ) -> Result<(MeetingTarget, Conversation)> { |
| 384 | let body = crate::join::resolve_body(from, callbacks, meeting_data); |
| 385 | let response = self |
| 386 | .send("POST epconv resolve", Method::Post, EPCONV_URL, Some(body)) |
| 387 | .await?; |
| 388 | let target = crate::join::target_from_answer(&response.body, meeting_data)?; |
| 389 | Ok((target, conversation_from(&response.body)?)) |
| 390 | } |
| 391 | |
| 392 | /// A running meeting answers from the conversation that owns it, so its controller and links replace the subscribed ones. |
| 393 | pub async fn join_meeting( |
| 394 | &self, |
| 395 | subscribed: &Conversation, |
| 396 | invitation: &Invitation<'_>, |
| 397 | ) -> Result<Conversation> { |
| 398 | let response = self |
| 399 | .send( |
| 400 | "POST join", |
| 401 | Method::Post, |
| 402 | &subscribed.controller, |
| 403 | Some(epconv_body(invitation)), |
| 404 | ) |
| 405 | .await?; |
| 406 | Ok(joined_conversation(subscribed, &response.body)) |
| 407 | } |
| 408 | |
| 409 | pub fn next_endpoint_sequence(&self) -> u32 { |
| 410 | self.endpoint_state_sequence |
| 411 | .fetch_add(1, std::sync::atomic::Ordering::SeqCst) |
| 412 | + 1 |
| 413 | } |
| 414 | |
| 415 | pub async fn update_endpoint_state( |
| 416 | &self, |
| 417 | conversation: &Conversation, |
| 418 | from: &Participant, |
| 419 | muted: bool, |
| 420 | ) -> Result<()> { |
| 421 | let body = json!({ |
| 422 | "from": from.wire(), |
| 423 | "endpointState": { |
| 424 | "endpointStateSequenceNumber": self.next_endpoint_sequence(), |
| 425 | "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}}, |
| 426 | "state": {"isMuted": muted}, |
| 427 | }, |
| 428 | }); |
| 429 | let url = conversation.link("updateEndpointState")?; |
| 430 | self.post_json("POST updateEndpointState", url, body).await |
| 431 | } |
| 432 | |
| 433 | fn next_state_sequence(&self) -> u32 { |
| 434 | self.state_sequence |
| 435 | .fetch_add(1, std::sync::atomic::Ordering::SeqCst) |
| 436 | + 1 |
| 437 | } |
| 438 | |
| 439 | pub async fn raise_hand( |
| 440 | &self, |
| 441 | conversation: &Conversation, |
| 442 | from: &Participant, |
| 443 | ) -> Result<HandReceipt> { |
| 444 | let body = raise_hand_body(from.wire(), self.next_state_sequence()); |
| 445 | let response = self |
| 446 | .send( |
| 447 | "POST publishState", |
| 448 | Method::Post, |
| 449 | conversation.link("publishState")?, |
| 450 | Some(body), |
| 451 | ) |
| 452 | .await?; |
| 453 | Ok(hand_receipt_from(&response.body)) |
| 454 | } |
| 455 | |
| 456 | pub async fn lower_hands( |
| 457 | &self, |
| 458 | conversation: &Conversation, |
| 459 | from: &Participant, |
| 460 | state_ids: &[String], |
| 461 | ) -> Result<()> { |
| 462 | let body = remove_states_body(from.wire(), self.next_state_sequence(), state_ids); |
| 463 | self.post_json("POST removeState", conversation.link("removeState")?, body) |
| 464 | .await |
| 465 | } |
| 466 | |
| 467 | pub async fn lower_all_hands( |
| 468 | &self, |
| 469 | conversation: &Conversation, |
| 470 | from: &Participant, |
| 471 | ) -> Result<()> { |
| 472 | let body = remove_all_hands_body(from.wire(), self.next_state_sequence()); |
| 473 | self.post_json("POST removeState", conversation.link("removeState")?, body) |
| 474 | .await |
| 475 | } |
| 476 | |
| 477 | pub async fn send_reaction( |
| 478 | &self, |
| 479 | conversation: &Conversation, |
| 480 | from: &Participant, |
| 481 | reaction: Reaction, |
| 482 | ) -> Result<()> { |
| 483 | let body = reaction_message( |
| 484 | from.wire(), |
| 485 | reaction, |
| 486 | &uuid::Uuid::new_v4().to_string(), |
| 487 | &uuid::Uuid::new_v4().to_string(), |
| 488 | ); |
| 489 | self.post_json("POST sendMessage", conversation.link("sendMessage")?, body) |
| 490 | .await |
| 491 | } |
| 492 | |
| 493 | pub async fn update_media_descriptions( |
| 494 | &self, |
| 495 | url: &str, |
| 496 | descriptions: &[MediaDescription], |
| 497 | request_id: u32, |
| 498 | ) -> Result<()> { |
| 499 | let body = json!({ |
| 500 | "UpdateMediaDescriptions": { |
| 501 | "mediaDescriptions": { |
| 502 | "descriptions": descriptions.iter().map(MediaDescription::wire).collect::<Vec<_>>(), |
| 503 | "requestId": request_id, |
| 504 | }, |
| 505 | }, |
| 506 | }); |
| 507 | self.post_json("POST updateMediaDescriptions", url, body) |
| 508 | .await |
| 509 | } |
| 510 | |
| 511 | pub async fn add_echo_bot( |
| 512 | &self, |
| 513 | conversation: &Conversation, |
| 514 | from: &Participant, |
| 515 | thread_id: Option<&str>, |
| 516 | callbacks: &CallbackLinks, |
| 517 | ) -> Result<()> { |
| 518 | let body = echo_bot_add_body(from, thread_id, callbacks); |
| 519 | let url = conversation.link("addParticipantAndModality")?; |
| 520 | self.post_json("POST add (echo bot)", url, body).await |
| 521 | } |
| 522 | |
| 523 | pub async fn update_endpoint_metadata( |
| 524 | &self, |
| 525 | conversation: &Conversation, |
| 526 | from: &Participant, |
| 527 | ) -> Result<()> { |
| 528 | self.put_endpoint_metadata(conversation, from, json!({"holographicCapabilities": 3})) |
| 529 | .await |
| 530 | } |
| 531 | |
| 532 | pub async fn set_caption_preference( |
| 533 | &self, |
| 534 | conversation: &Conversation, |
| 535 | from: &Participant, |
| 536 | captions: bool, |
| 537 | ) -> Result<()> { |
| 538 | self.put_endpoint_metadata(conversation, from, captions::endpoint_metadata(captions)) |
| 539 | .await |
| 540 | } |
| 541 | |
| 542 | async fn put_endpoint_metadata( |
| 543 | &self, |
| 544 | conversation: &Conversation, |
| 545 | from: &Participant, |
| 546 | metadata: Value, |
| 547 | ) -> Result<()> { |
| 548 | let body = json!({"participants": {"from": from.wire()}, "endpointMetadata": metadata}); |
| 549 | let url = conversation.link("updateEndpointMetadata")?; |
| 550 | self.send("PUT updateEndpointMetadata", Method::Put, url, Some(body)) |
| 551 | .await |
| 552 | .map(|_| ()) |
| 553 | } |
| 554 | |
| 555 | pub async fn admit( |
| 556 | &self, |
| 557 | conversation: &Conversation, |
| 558 | from: &Participant, |
| 559 | target: Target<'_>, |
| 560 | callbacks: &CallbackLinks, |
| 561 | ) -> Result<u16> { |
| 562 | let body = organizer::admit_body( |
| 563 | from.wire(), |
| 564 | target, |
| 565 | callbacks, |
| 566 | &uuid::Uuid::new_v4().to_string(), |
| 567 | ); |
| 568 | self.send( |
| 569 | "POST admit", |
| 570 | Method::Post, |
| 571 | conversation.link("admit")?, |
| 572 | Some(body), |
| 573 | ) |
| 574 | .await |
| 575 | .map(|response| response.status) |
| 576 | } |
| 577 | |
| 578 | pub async fn remove_participant( |
| 579 | &self, |
| 580 | conversation: &Conversation, |
| 581 | from: &Participant, |
| 582 | target: Target<'_>, |
| 583 | callbacks: &CallbackLinks, |
| 584 | ) -> Result<u16> { |
| 585 | let body = organizer::remove_participant_body(from.wire(), target, callbacks); |
| 586 | self.send( |
| 587 | "POST removeParticipant", |
| 588 | Method::Post, |
| 589 | conversation.link("removeParticipant")?, |
| 590 | Some(body), |
| 591 | ) |
| 592 | .await |
| 593 | .map(|response| response.status) |
| 594 | } |
| 595 | |
| 596 | pub async fn mute_participant( |
| 597 | &self, |
| 598 | conversation: &Conversation, |
| 599 | from: &Participant, |
| 600 | mri: &str, |
| 601 | ) -> Result<u16> { |
| 602 | let body = organizer::mute_participants_body(from.wire(), &[mri.to_owned()]); |
| 603 | self.send( |
| 604 | "POST mute", |
| 605 | Method::Post, |
| 606 | conversation.link("mute")?, |
| 607 | Some(body), |
| 608 | ) |
| 609 | .await |
| 610 | .map(|response| response.status) |
| 611 | } |
| 612 | |
| 613 | pub async fn mute_everyone( |
| 614 | &self, |
| 615 | conversation: &Conversation, |
| 616 | from: &Participant, |
| 617 | others: &[String], |
| 618 | ) -> Result<u16> { |
| 619 | let body = organizer::mute_everyone_body(from.wire(), others); |
| 620 | self.send( |
| 621 | "POST mute (all)", |
| 622 | Method::Post, |
| 623 | conversation.link("mute")?, |
| 624 | Some(body), |
| 625 | ) |
| 626 | .await |
| 627 | .map(|response| response.status) |
| 628 | } |
| 629 | |
| 630 | pub async fn spotlight( |
| 631 | &self, |
| 632 | conversation: &Conversation, |
| 633 | from: &Participant, |
| 634 | mri: &str, |
| 635 | ) -> Result<u16> { |
| 636 | let body = |
| 637 | organizer::spotlight_body(from.wire(), self.next_state_sequence(), mri, &from.mri); |
| 638 | self.send( |
| 639 | "POST publishState (spotlight)", |
| 640 | Method::Post, |
| 641 | conversation.link("publishState")?, |
| 642 | Some(body), |
| 643 | ) |
| 644 | .await |
| 645 | .map(|response| response.status) |
| 646 | } |
| 647 | |
| 648 | pub async fn set_lock( |
| 649 | &self, |
| 650 | conversation: &Conversation, |
| 651 | from: &Participant, |
| 652 | locked: bool, |
| 653 | ) -> Result<u16> { |
| 654 | let body = organizer::lock_body(from.wire(), locked, self.next_state_sequence()); |
| 655 | self.send( |
| 656 | "PUT updateMeetingSettings", |
| 657 | Method::Put, |
| 658 | conversation.link("updateMeetingSettings")?, |
| 659 | Some(body), |
| 660 | ) |
| 661 | .await |
| 662 | .map(|response| response.status) |
| 663 | } |
| 664 | |
| 665 | pub async fn change_role( |
| 666 | &self, |
| 667 | conversation: &Conversation, |
| 668 | from: &Participant, |
| 669 | mri: &str, |
| 670 | role: MeetingRole, |
| 671 | ) -> Result<u16> { |
| 672 | let body = organizer::role_body(from.wire(), mri, role); |
| 673 | self.send( |
| 674 | "POST updateParticipantRole", |
| 675 | Method::Post, |
| 676 | conversation.link("updateParticipantRole")?, |
| 677 | Some(body), |
| 678 | ) |
| 679 | .await |
| 680 | .map(|response| response.status) |
| 681 | } |
| 682 | |
| 683 | pub async fn publish_attendee_state( |
| 684 | &self, |
| 685 | conversation: &Conversation, |
| 686 | from: &Participant, |
| 687 | state_type: &str, |
| 688 | mri: &str, |
| 689 | ) -> Result<u16> { |
| 690 | let body = organizer::attendee_state_body( |
| 691 | from.wire(), |
| 692 | state_type, |
| 693 | self.next_state_sequence(), |
| 694 | mri, |
| 695 | ); |
| 696 | self.send( |
| 697 | "POST publishState (attendee)", |
| 698 | Method::Post, |
| 699 | conversation.link("publishState")?, |
| 700 | Some(body), |
| 701 | ) |
| 702 | .await |
| 703 | .map(|response| response.status) |
| 704 | } |
| 705 | |
| 706 | pub async fn add_participants( |
| 707 | &self, |
| 708 | conversation: &Conversation, |
| 709 | from: &Participant, |
| 710 | callees: &[Callee], |
| 711 | group_thread: Option<&str>, |
| 712 | meeting: Option<&MeetingTarget>, |
| 713 | callbacks: &CallbackLinks, |
| 714 | ) -> Result<u16> { |
| 715 | let invitees: Vec<Invitee> = callees |
| 716 | .iter() |
| 717 | .map(|callee| Invitee { |
| 718 | callee: callee.clone(), |
| 719 | participant_id: uuid::Uuid::new_v4().to_string(), |
| 720 | }) |
| 721 | .collect(); |
| 722 | let group_chat = group_thread.map_or(Value::Null, |thread_id| { |
| 723 | organizer::group_chat_for(thread_id, meeting.is_some()) |
| 724 | }); |
| 725 | let body = organizer::add_participants_body( |
| 726 | from.wire(), |
| 727 | &invitees, |
| 728 | group_chat, |
| 729 | meeting, |
| 730 | callbacks, |
| 731 | ); |
| 732 | let url = conversation.link(organizer::add_link_name(group_thread.is_some()))?; |
| 733 | self.send("POST add (invite)", Method::Post, url, Some(body)) |
| 734 | .await |
| 735 | .map(|response| response.status) |
| 736 | } |
| 737 | |
| 738 | pub async fn add_caption_bot( |
| 739 | &self, |
| 740 | conversation: &Conversation, |
| 741 | from: &Participant, |
| 742 | thread_id: &str, |
| 743 | callbacks: &CallbackLinks, |
| 744 | threadless: bool, |
| 745 | ) -> Result<u16> { |
| 746 | let body = captions::add_bot_body( |
| 747 | from.wire(), |
| 748 | thread_id, |
| 749 | callbacks.call_id(), |
| 750 | &from.display_name, |
| 751 | callbacks, |
| 752 | threadless, |
| 753 | ); |
| 754 | let link = if threadless { |
| 755 | "addParticipant" |
| 756 | } else { |
| 757 | "addParticipantAndModality" |
| 758 | }; |
| 759 | let mut request = self.request(Method::Post, conversation.link(link)?, Some(body)); |
| 760 | request = request.with_body_token( |
| 761 | captions::RECORDER_RESOURCE, |
| 762 | captions::RECORDER_SCOPE, |
| 763 | captions::INITIATOR_TOKEN_PLACEHOLDER, |
| 764 | ); |
| 765 | self.exchange(&self.session, "POST add (caption bot)", request) |
| 766 | .await |
| 767 | .map(|response| response.status) |
| 768 | } |
| 769 | |
| 770 | pub async fn caption_command( |
| 771 | &self, |
| 772 | command_url: &str, |
| 773 | action: BotAction, |
| 774 | from: &Participant, |
| 775 | ) -> Result<()> { |
| 776 | ensure_teams_url(command_url)?; |
| 777 | let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); |
| 778 | let body = captions::command_body(action, &from.mri, &from.participant_id, ×tamp); |
| 779 | self.bot_command(command_url, body, "caption command") |
| 780 | .await |
| 781 | .map(|_| ()) |
| 782 | } |
| 783 | |
| 784 | pub async fn caption_language_command( |
| 785 | &self, |
| 786 | command_url: &str, |
| 787 | from: &Participant, |
| 788 | language_tag: &str, |
| 789 | ) -> Result<()> { |
| 790 | ensure_teams_url(command_url)?; |
| 791 | let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); |
| 792 | let body = |
| 793 | captions::language_body(&from.mri, &from.participant_id, ×tamp, language_tag); |
| 794 | self.bot_command(command_url, body, "caption language command") |
| 795 | .await |
| 796 | .map(|_| ()) |
| 797 | } |
| 798 | |
| 799 | async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> { |
| 800 | let arguments = json!({ |
| 801 | "url": command_url, |
| 802 | "body": body, |
| 803 | "recorderResource": captions::RECORDER_RESOURCE, |
| 804 | "recorderScope": captions::RECORDER_SCOPE, |
| 805 | "requestId": uuid::Uuid::new_v4().to_string(), |
| 806 | "chainId": self.chain_id, |
| 807 | }); |
| 808 | let answer = self |
| 809 | .session |
| 810 | .run_with_token( |
| 811 | App::Teams, |
| 812 | &spaces_scope(), |
| 813 | captions::COMMAND_SCRIPT, |
| 814 | &arguments, |
| 815 | false, |
| 816 | ) |
| 817 | .await?; |
| 818 | let status = answer["status"].as_u64().unwrap_or_default(); |
| 819 | self.timeline |
| 820 | .record(format!("POST {label}"), format!("HTTP {status}")); |
| 821 | if (200..300).contains(&status) { |
| 822 | return Ok(status as u16); |
| 823 | } |
| 824 | let reason = answer["error"].as_str().unwrap_or("no answer"); |
| 825 | Err(Error::Signaling(format!( |
| 826 | "{label} answered HTTP {status} {reason}" |
| 827 | ))) |
| 828 | } |
| 829 | |
| 830 | pub async fn recording_command( |
| 831 | &self, |
| 832 | command_url: &str, |
| 833 | command: RecordingCommand, |
| 834 | from: &Participant, |
| 835 | title: &str, |
| 836 | ) -> Result<u16> { |
| 837 | ensure_teams_url(command_url)?; |
| 838 | let now = chrono::Utc::now(); |
| 839 | let timestamp = now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true); |
| 840 | let file_name = recording::file_name(title, now); |
| 841 | let correlation_id = uuid::Uuid::new_v4().to_string(); |
| 842 | let details = StartDetails { |
| 843 | own_mri: &from.mri, |
| 844 | participant_leg_id: &from.participant_id, |
| 845 | timestamp: ×tamp, |
| 846 | file_name: &file_name, |
| 847 | meeting_title: title, |
| 848 | organizer_name: &from.display_name, |
| 849 | correlation_id: &correlation_id, |
| 850 | }; |
| 851 | self.bot_command( |
| 852 | command_url, |
| 853 | recording::command_body(command, details), |
| 854 | "recording command", |
| 855 | ) |
| 856 | .await |
| 857 | } |
| 858 | |
| 859 | pub async fn consent_to_recording( |
| 860 | &self, |
| 861 | conversation: &Conversation, |
| 862 | from: &Participant, |
| 863 | consent: Consent, |
| 864 | ) -> Result<u16> { |
| 865 | let body = recording::consent_body(from.wire(), self.next_state_sequence(), consent); |
| 866 | self.send( |
| 867 | "POST publishState (recording consent)", |
| 868 | Method::Post, |
| 869 | conversation.link("publishState")?, |
| 870 | Some(body), |
| 871 | ) |
| 872 | .await |
| 873 | .map(|response| response.status) |
| 874 | } |
| 875 | |
| 876 | pub async fn transfer( |
| 877 | &self, |
| 878 | transfer_url: &str, |
| 879 | from: &Participant, |
| 880 | target: TransferTarget<'_>, |
| 881 | callbacks: &CallbackLinks, |
| 882 | ) -> Result<()> { |
| 883 | let body = transfer::transfer_body(from, target, callbacks); |
| 884 | self.post_json("POST transfer", transfer_url, body).await |
| 885 | } |
| 886 | |
| 887 | /// One broker long poll; answers the next subscribe URL. |
| 888 | pub async fn poll_broker(&self, url: &str) -> Result<Option<String>> { |
| 889 | let mut request = self.request(Method::Get, url, None); |
| 890 | request.headers.push(("X-UseBatching".into(), "1".into())); |
| 891 | let response = self |
| 892 | .exchange(&self.poll_session, "GET broker subscribe", request) |
| 893 | .await?; |
| 894 | Ok(response.body["nextSubscribeUrl"] |
| 895 | .as_str() |
| 896 | .map(str::to_owned)) |
| 897 | } |
| 898 | |
| 899 | pub async fn leave( |
| 900 | &self, |
| 901 | conversation: &Conversation, |
| 902 | from: &Participant, |
| 903 | reason: LeaveReason, |
| 904 | ) -> Result<()> { |
| 905 | let url = conversation.link("leave")?; |
| 906 | self.post_json("POST leave", url, leave_body(from, reason)) |
| 907 | .await |
| 908 | } |
| 909 | |
| 910 | pub async fn end_for_all(&self, conversation: &Conversation, from: &Participant) -> Result<()> { |
| 911 | self.send( |
| 912 | "DELETE conversation", |
| 913 | Method::Delete, |
| 914 | &conversation.controller, |
| 915 | Some(end_for_all_body(from)), |
| 916 | ) |
| 917 | .await |
| 918 | .map(|_| ()) |
| 919 | } |
| 920 | |
| 921 | pub async fn attach(&self, url: &str, request: &AttachRequest<'_>) -> Result<Attached> { |
| 922 | let response = self |
| 923 | .send("POST attach", Method::Post, url, Some(attach_body(request))) |
| 924 | .await?; |
| 925 | attached_from(&response.body) |
| 926 | } |
| 927 | |
| 928 | pub async fn send_ringing(&self, url: &str, from: &Participant) -> Result<()> { |
| 929 | self.post_json("POST progress", url, ringing_body(from)) |
| 930 | .await |
| 931 | } |
| 932 | |
| 933 | pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<BTreeMap<String, String>> { |
| 934 | let response = self |
| 935 | .send( |
| 936 | "POST acceptance", |
| 937 | Method::Post, |
| 938 | url, |
| 939 | Some(acceptance_body(answer)), |
| 940 | ) |
| 941 | .await?; |
| 942 | Ok(acknowledgement_links(&response.body)) |
| 943 | } |
| 944 | |
| 945 | pub async fn decline(&self, call_leg_url: &str) -> Result<()> { |
| 946 | self.send( |
| 947 | "DELETE callLeg (decline)", |
| 948 | Method::Delete, |
| 949 | call_leg_url, |
| 950 | Some(decline_body()), |
| 951 | ) |
| 952 | .await |
| 953 | .map(|_| ()) |
| 954 | } |
| 955 | |
| 956 | /// Hang up a connected call leg so the mixer drops our participant tile. |
| 957 | pub async fn end_call_leg(&self, call_leg_url: &str) -> Result<()> { |
| 958 | self.send( |
| 959 | "DELETE callLeg (hangup)", |
| 960 | Method::Delete, |
| 961 | call_leg_url, |
| 962 | Some(hangup_call_leg_body()), |
| 963 | ) |
| 964 | .await |
| 965 | .map(|_| ()) |
| 966 | } |
| 967 | |
| 968 | pub async fn reject_renegotiation( |
| 969 | &self, |
| 970 | url: &str, |
| 971 | from: &Participant, |
| 972 | call_id: &str, |
| 973 | failure: NegotiationFailure, |
| 974 | ) -> Result<()> { |
| 975 | self.post_json( |
| 976 | "POST rejection (renegotiation)", |
| 977 | url, |
| 978 | negotiation_failure_body(from, call_id, failure), |
| 979 | ) |
| 980 | .await |
| 981 | } |
| 982 | |
| 983 | pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> { |
| 984 | self.post_json( |
| 985 | "POST callLeg keep-alive", |
| 986 | call_leg_url, |
| 987 | json!({"callParticipantUpdate": {}}), |
| 988 | ) |
| 989 | .await |
| 990 | } |
| 991 | |
| 992 | pub async fn keep_conversation_alive( |
| 993 | &self, |
| 994 | conversation: &Conversation, |
| 995 | from: &Participant, |
| 996 | callbacks: &CallbackLinks, |
| 997 | ) -> Result<()> { |
| 998 | let url = conversation.link("notificationLinks")?; |
| 999 | self.post_json( |
| 1000 | "POST notificationLinks", |
| 1001 | url, |
| 1002 | notification_links_body(from, callbacks), |
| 1003 | ) |
| 1004 | .await |
| 1005 | } |
| 1006 | } |
| 1007 | |
| 1008 | fn link_map(names: &[&str], make: impl Fn(&str) -> String) -> Map<String, Value> { |
| 1009 | names |
| 1010 | .iter() |
| 1011 | .map(|name| ((*name).to_owned(), Value::String(make(name)))) |
| 1012 | .collect() |
| 1013 | } |
| 1014 | |
| 1015 | fn roster_request(callbacks: &CallbackLinks) -> Value { |
| 1016 | json!({"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")}) |
| 1017 | } |
| 1018 | |
| 1019 | fn conversation_properties() -> Value { |
| 1020 | json!({ |
| 1021 | "allowConversationWithoutHost": true, |
| 1022 | "enableGroupCallEventMessages": true, |
| 1023 | "enableGroupCallUpgradeMessage": false, |
| 1024 | "enableGroupCallMeetupGeneration": false, |
| 1025 | }) |
| 1026 | } |
| 1027 | |
| 1028 | pub(crate) fn endpoint_state() -> Value { |
| 1029 | json!({ |
| 1030 | "endpointStateSequenceNumber": 2, |
| 1031 | "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}}, |
| 1032 | }) |
| 1033 | } |
| 1034 | |
| 1035 | fn media_content(sdp: &str, media_leg_id: &str, with_descriptions: bool) -> Value { |
| 1036 | let mut content = json!({ |
| 1037 | "contentType": SDP_CONTENT_TYPE, |
| 1038 | "blob": sdp, |
| 1039 | "clientLocation": "DE", |
| 1040 | "mediaLegId": media_leg_id, |
| 1041 | }); |
| 1042 | if with_descriptions { |
| 1043 | content["mediaDescriptions"] = json!({"descriptions": [], "requestId": 1}); |
| 1044 | } |
| 1045 | content |
| 1046 | } |
| 1047 | |
| 1048 | fn media_controller_links(callbacks: &CallbackLinks) -> Value { |
| 1049 | json!({ |
| 1050 | "controlVideoStreaming": callbacks.call("controlVideoStreaming"), |
| 1051 | "csrcInfo": callbacks.call("csrcInfo"), |
| 1052 | }) |
| 1053 | } |
| 1054 | |
| 1055 | /// The 1:1 chat of two people: both object ids sorted as plain strings. |
| 1056 | pub fn one_to_one_thread(own_object_id: &str, peer_mri: &str) -> Option<String> { |
| 1057 | let peer = peer_mri.strip_prefix("8:orgid:")?; |
| 1058 | let (first, second) = if own_object_id <= peer { |
| 1059 | (own_object_id, peer) |
| 1060 | } else { |
| 1061 | (peer, own_object_id) |
| 1062 | }; |
| 1063 | Some(format!("19:{first}_{second}{ONE_TO_ONE_THREAD_SUFFIX}")) |
| 1064 | } |
| 1065 | |
| 1066 | impl InviteTarget { |
| 1067 | pub fn is_one_to_one(&self) -> bool { |
| 1068 | match self { |
| 1069 | InviteTarget::People { callees, thread_id } => { |
| 1070 | callees.len() == 1 && thread_id.ends_with(ONE_TO_ONE_THREAD_SUFFIX) |
| 1071 | } |
| 1072 | InviteTarget::Echo | InviteTarget::Meeting(_) => false, |
| 1073 | } |
| 1074 | } |
| 1075 | } |
| 1076 | |
| 1077 | fn invitation_media(invitation: &Invitation<'_>) -> Value { |
| 1078 | if !invitation.is_direct() { |
| 1079 | return media_content(invitation.offer_sdp, invitation.media_leg_id, true); |
| 1080 | } |
| 1081 | let mut content = media_content(invitation.offer_sdp, invitation.media_leg_id, false); |
| 1082 | content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES); |
| 1083 | content |
| 1084 | } |
| 1085 | |
| 1086 | fn group_chat(invitation: &Invitation<'_>) -> Value { |
| 1087 | if invitation.is_direct() { |
| 1088 | return Value::Null; |
| 1089 | } |
| 1090 | match invitation.target { |
| 1091 | InviteTarget::Echo => Value::Null, |
| 1092 | InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}), |
| 1093 | InviteTarget::Meeting(meeting) => { |
| 1094 | json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}) |
| 1095 | } |
| 1096 | } |
| 1097 | } |
| 1098 | |
| 1099 | fn callee_wire(callee: &Callee) -> Value { |
| 1100 | json!({"id": callee.mri, "displayName": callee.display_name}) |
| 1101 | } |
| 1102 | |
| 1103 | pub fn epconv_body(invitation: &Invitation<'_>) -> Value { |
| 1104 | let callbacks = invitation.callbacks; |
| 1105 | let target = invitation.target; |
| 1106 | let to: Vec<Value> = match target { |
| 1107 | InviteTarget::People { callees, .. } => callees.iter().map(callee_wire).collect(), |
| 1108 | InviteTarget::Echo | InviteTarget::Meeting(_) => Vec::new(), |
| 1109 | }; |
| 1110 | let mut request = json!({ |
| 1111 | "conversationType": null, |
| 1112 | "subject": null, |
| 1113 | "suppressDialout": to.is_empty(), |
| 1114 | "roster": roster_request(callbacks), |
| 1115 | "properties": conversation_properties(), |
| 1116 | "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)), |
| 1117 | }); |
| 1118 | if matches!(target, InviteTarget::Echo) { |
| 1119 | request["scenario"] = json!("UserInitiatedTestCall"); |
| 1120 | } |
| 1121 | let (meeting_info, meeting_data) = match target { |
| 1122 | InviteTarget::Meeting(meeting) => ( |
| 1123 | json!({"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}), |
| 1124 | meeting.meeting_data.clone().unwrap_or(Value::Null), |
| 1125 | ), |
| 1126 | _ => (Value::Null, Value::Null), |
| 1127 | }; |
| 1128 | json!({ |
| 1129 | "conversationRequest": request, |
| 1130 | "contentSharing": null, |
| 1131 | "participants": {"from": invitation.from.wire(), "to": to}, |
| 1132 | "capabilities": null, |
| 1133 | "endpointCapabilities": ENDPOINT_CAPABILITIES, |
| 1134 | "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES, |
| 1135 | "endpointMetadata": {"holographicCapabilities": 3}, |
| 1136 | "groupContext": null, |
| 1137 | "groupChat": group_chat(invitation), |
| 1138 | "meetingInfo": meeting_info, |
| 1139 | "meetingData": meeting_data, |
| 1140 | "endpointState": endpoint_state(), |
| 1141 | "callInvitation": { |
| 1142 | "callModalities": invitation.modalities, |
| 1143 | "replaces": null, |
| 1144 | "transferor": null, |
| 1145 | "clientTransferContext": null, |
| 1146 | "customContext": null, |
| 1147 | "links": link_map(&CALL_LINK_NAMES, |name| callbacks.call(name)), |
| 1148 | "clientContentForMediaController": media_controller_links(callbacks), |
| 1149 | "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false}, |
| 1150 | "emergencyContent": null, |
| 1151 | "mediaContent": invitation_media(invitation), |
| 1152 | }, |
| 1153 | }) |
| 1154 | } |
| 1155 | |
| 1156 | pub(crate) fn subscribe_request(callbacks: &CallbackLinks) -> Value { |
| 1157 | json!({ |
| 1158 | "roster": roster_request(callbacks), |
| 1159 | "properties": conversation_properties(), |
| 1160 | "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)), |
| 1161 | }) |
| 1162 | } |
| 1163 | |
| 1164 | pub fn subscribe_body( |
| 1165 | from: &Participant, |
| 1166 | callbacks: &CallbackLinks, |
| 1167 | meeting: &MeetingTarget, |
| 1168 | ) -> Value { |
| 1169 | json!({ |
| 1170 | "conversationRequest": subscribe_request(callbacks), |
| 1171 | "participants": {"from": from.wire()}, |
| 1172 | "groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}, |
| 1173 | "meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}, |
| 1174 | "endpointState": endpoint_state(), |
| 1175 | }) |
| 1176 | } |
| 1177 | |
| 1178 | pub fn leave_body(from: &Participant, reason: LeaveReason) -> Value { |
| 1179 | let call_end = match reason { |
| 1180 | LeaveReason::Hangup => { |
| 1181 | json!({"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}) |
| 1182 | } |
| 1183 | LeaveReason::Cancel => { |
| 1184 | json!({"code": CANCEL_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated"}) |
| 1185 | } |
| 1186 | }; |
| 1187 | json!({ |
| 1188 | "participants": {"from": from.wire()}, |
| 1189 | "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"}, |
| 1190 | "callTransactionEnd": call_end, |
| 1191 | }) |
| 1192 | } |
| 1193 | |
| 1194 | pub fn end_for_all_body(from: &Participant) -> Value { |
| 1195 | json!({ |
| 1196 | "participants": {"from": from.wire()}, |
| 1197 | "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndForAllInitiated"}, |
| 1198 | "callTransactionEnd": {"code": 0, "phrase": "CallEndReasonLocalUserInitiated"}, |
| 1199 | }) |
| 1200 | } |
| 1201 | |
| 1202 | pub fn decline_body() -> Value { |
| 1203 | json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}}) |
| 1204 | } |
| 1205 | |
| 1206 | pub fn hangup_call_leg_body() -> Value { |
| 1207 | json!({"callEnd": {"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}}) |
| 1208 | } |
| 1209 | |
| 1210 | pub fn ringing_body(from: &Participant) -> Value { |
| 1211 | json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}}) |
| 1212 | } |
| 1213 | |
| 1214 | pub fn attach_body(request: &AttachRequest<'_>) -> Value { |
| 1215 | let callbacks = request.callbacks; |
| 1216 | let mut body = json!({ |
| 1217 | "attach": { |
| 1218 | "requireMediaContent": request.needs_media, |
| 1219 | "links": {"end": callbacks.call("end")}, |
| 1220 | }, |
| 1221 | "capabilities": null, |
| 1222 | "endpointCapabilities": ENDPOINT_CAPABILITIES, |
| 1223 | }); |
| 1224 | if let Some(controller) = request.controller { |
| 1225 | body["additionalActions"] = json!([{ |
| 1226 | "name": "join", |
| 1227 | "url": controller, |
| 1228 | "waitForResponse": true, |
| 1229 | "input": { |
| 1230 | "conversationRequest": { |
| 1231 | "roster": roster_request(callbacks), |
| 1232 | "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)), |
| 1233 | }, |
| 1234 | "participants": {"from": request.from.wire()}, |
| 1235 | "endpointMetadata": {"holographicCapabilities": 3}, |
| 1236 | "endpointCapabilities": ENDPOINT_CAPABILITIES, |
| 1237 | }, |
| 1238 | }]); |
| 1239 | } |
| 1240 | body |
| 1241 | } |
| 1242 | |
| 1243 | pub fn acceptance_body(answer: &Answer<'_>) -> Value { |
| 1244 | let callbacks = answer.callbacks; |
| 1245 | json!({ |
| 1246 | "callAcceptance": { |
| 1247 | "acceptedBy": answer.from.wire(), |
| 1248 | "acceptedCallModalities": answer.modalities, |
| 1249 | "endpointCapabilities": ENDPOINT_CAPABILITIES, |
| 1250 | "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES, |
| 1251 | "links": acceptance_links(callbacks), |
| 1252 | "clientContentForMediaController": media_controller_links(callbacks), |
| 1253 | "mediaContent": media_content(answer.answer_sdp, answer.media_leg_id, false), |
| 1254 | "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false}, |
| 1255 | "callKeepAliveInterval": null, |
| 1256 | }, |
| 1257 | }) |
| 1258 | } |
| 1259 | |
| 1260 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1261 | pub enum NegotiationFailure { |
| 1262 | InProgress, |
| 1263 | AnswerError, |
| 1264 | } |
| 1265 | |
| 1266 | impl NegotiationFailure { |
| 1267 | fn wire(self) -> (u16, u32, &'static str) { |
| 1268 | match self { |
| 1269 | NegotiationFailure::InProgress => (491, 3118, "NegotiationIsInProgress"), |
| 1270 | NegotiationFailure::AnswerError => (488, 3102, "CallEndReasonMediaAnswerError"), |
| 1271 | } |
| 1272 | } |
| 1273 | } |
| 1274 | |
| 1275 | pub fn negotiation_failure_body( |
| 1276 | from: &Participant, |
| 1277 | call_id: &str, |
| 1278 | failure: NegotiationFailure, |
| 1279 | ) -> Value { |
| 1280 | let (code, sub_code, phrase) = failure.wire(); |
| 1281 | json!({ |
| 1282 | "mediaNegotiationFailure": {"sender": from.wire(), "code": code, "subCode": sub_code, "phrase": phrase}, |
| 1283 | "debugContent": {"callId": call_id, "endpointId": from.endpoint_id}, |
| 1284 | }) |
| 1285 | } |
| 1286 | |
| 1287 | pub fn renegotiation_body( |
| 1288 | from: &Participant, |
| 1289 | callbacks: &CallbackLinks, |
| 1290 | offer_sdp: &str, |
| 1291 | media_leg_id: &str, |
| 1292 | modalities: &[String], |
| 1293 | new_offer: bool, |
| 1294 | direct: bool, |
| 1295 | ) -> Value { |
| 1296 | json!({ |
| 1297 | "mediaNegotiation": { |
| 1298 | "callModalities": modalities, |
| 1299 | "sender": from.wire(), |
| 1300 | "links": { |
| 1301 | "mediaAnswer": callbacks.call("mediaAnswer"), |
| 1302 | "rejection": callbacks.call("rejection"), |
| 1303 | }, |
| 1304 | "mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer, direct), |
| 1305 | }, |
| 1306 | }) |
| 1307 | } |
| 1308 | |
| 1309 | fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool, direct: bool) -> Value { |
| 1310 | let mut content = media_content(sdp, media_leg_id, !direct); |
| 1311 | if direct { |
| 1312 | content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES); |
| 1313 | } |
| 1314 | content["newOffer"] = json!(new_offer); |
| 1315 | content |
| 1316 | } |
| 1317 | |
| 1318 | pub fn escalation_answer_body( |
| 1319 | from: &Participant, |
| 1320 | callbacks: &CallbackLinks, |
| 1321 | answer_sdp: &str, |
| 1322 | media_leg_id: &str, |
| 1323 | ) -> Value { |
| 1324 | json!({ |
| 1325 | "mediaAnswer": { |
| 1326 | "callModalities": AUDIO_MODALITIES, |
| 1327 | "sender": from.wire(), |
| 1328 | "links": {"mediaAcknowledgement": callbacks.call("mediaAcknowledgement")}, |
| 1329 | "clientContentForMediaController": media_controller_links(callbacks), |
| 1330 | "mediaContent": media_content(answer_sdp, media_leg_id, false), |
| 1331 | }, |
| 1332 | }) |
| 1333 | } |
| 1334 | |
| 1335 | pub fn notification_links_body(from: &Participant, callbacks: &CallbackLinks) -> Value { |
| 1336 | json!({ |
| 1337 | "participants": {"from": from.wire()}, |
| 1338 | "roster": roster_request(callbacks), |
| 1339 | "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)), |
| 1340 | }) |
| 1341 | } |
| 1342 | |
| 1343 | fn conversation_from(body: &Value) -> Result<Conversation> { |
| 1344 | let controller = body["conversationController"] |
| 1345 | .as_str() |
| 1346 | .ok_or_else(|| Error::Signaling("answer without conversationController".into()))? |
| 1347 | .to_owned(); |
| 1348 | let links = body["links"] |
| 1349 | .as_object() |
| 1350 | .map(|links| { |
| 1351 | links |
| 1352 | .iter() |
| 1353 | .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned()))) |
| 1354 | .collect() |
| 1355 | }) |
| 1356 | .unwrap_or_default(); |
| 1357 | let roster = Some(&body["roster"]) |
| 1358 | .filter(|roster| roster.is_object()) |
| 1359 | .cloned(); |
| 1360 | Ok(Conversation { |
| 1361 | controller, |
| 1362 | links, |
| 1363 | chat_thread: chat_thread_id(body), |
| 1364 | roster, |
| 1365 | }) |
| 1366 | } |
| 1367 | |
| 1368 | fn joined_conversation(subscribed: &Conversation, answer: &Value) -> Conversation { |
| 1369 | let Ok(joined) = conversation_from(answer) else { |
| 1370 | return subscribed.clone(); |
| 1371 | }; |
| 1372 | let mut links = subscribed.links.clone(); |
| 1373 | links.extend(joined.links); |
| 1374 | Conversation { |
| 1375 | controller: joined.controller, |
| 1376 | links, |
| 1377 | chat_thread: joined |
| 1378 | .chat_thread |
| 1379 | .or_else(|| subscribed.chat_thread.clone()), |
| 1380 | roster: joined.roster.or_else(|| subscribed.roster.clone()), |
| 1381 | } |
| 1382 | } |
| 1383 | |
| 1384 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1385 | pub struct HandReceipt { |
| 1386 | pub state_id: Option<String>, |
| 1387 | pub rank: u64, |
| 1388 | } |
| 1389 | |
| 1390 | pub fn hand_receipt_from(body: &Value) -> HandReceipt { |
| 1391 | let published = &body["publishStateResponse"]; |
| 1392 | HandReceipt { |
| 1393 | state_id: published["stateId"].as_str().map(str::to_owned), |
| 1394 | rank: published["typeRank"].as_u64().unwrap_or(u64::MAX), |
| 1395 | } |
| 1396 | } |
| 1397 | |
| 1398 | pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value { |
| 1399 | json!({ |
| 1400 | "from": from, |
| 1401 | "publishedState": { |
| 1402 | "stateType": RAISE_HANDS, |
| 1403 | "level": "user", |
| 1404 | "content": {"skinTone": DEFAULT_SKIN_TONE}, |
| 1405 | "sequenceNumber": sequence_number, |
| 1406 | }, |
| 1407 | }) |
| 1408 | } |
| 1409 | |
| 1410 | pub fn remove_states_body(from: Value, sequence_number: u32, state_ids: &[String]) -> Value { |
| 1411 | json!({"from": from, "sequenceNumber": sequence_number, "scope": "specified", "stateIds": state_ids}) |
| 1412 | } |
| 1413 | |
| 1414 | pub fn remove_all_hands_body(from: Value, sequence_number: u32) -> Value { |
| 1415 | json!({"from": from, "sequenceNumber": sequence_number, "scope": "all", "stateType": RAISE_HANDS}) |
| 1416 | } |
| 1417 | |
| 1418 | pub fn chat_thread_id(body: &Value) -> Option<String> { |
| 1419 | body["activeModalities"]["groupChat"]["threadId"] |
| 1420 | .as_str() |
| 1421 | .map(str::to_owned) |
| 1422 | } |
| 1423 | |
| 1424 | fn attached_from(body: &Value) -> Result<Attached> { |
| 1425 | let invitation = &body["callInvitation"]; |
| 1426 | if invitation.is_null() { |
| 1427 | return Err(Error::Signaling( |
| 1428 | "attach answer without callInvitation".into(), |
| 1429 | )); |
| 1430 | } |
| 1431 | let links = invitation["links"] |
| 1432 | .as_object() |
| 1433 | .map(|links| { |
| 1434 | links |
| 1435 | .iter() |
| 1436 | .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned()))) |
| 1437 | .collect() |
| 1438 | }) |
| 1439 | .unwrap_or_default(); |
| 1440 | let modalities = invitation["callModalities"] |
| 1441 | .as_array() |
| 1442 | .map(|items| { |
| 1443 | items |
| 1444 | .iter() |
| 1445 | .filter_map(|item| item.as_str().map(str::to_owned)) |
| 1446 | .collect() |
| 1447 | }) |
| 1448 | .unwrap_or_default(); |
| 1449 | Ok(Attached { |
| 1450 | offer_sdp: invitation["mediaContent"]["blob"] |
| 1451 | .as_str() |
| 1452 | .map(str::to_owned), |
| 1453 | from_mixer: invitation["mediaContent"]["fromMixer"] |
| 1454 | .as_bool() |
| 1455 | .unwrap_or(false), |
| 1456 | modalities, |
| 1457 | links, |
| 1458 | conversation: conversation_from(&body["additionalActionResponses"][0]["output"]).ok(), |
| 1459 | }) |
| 1460 | } |
| 1461 | |
| 1462 | #[derive(Debug, Clone)] |
| 1463 | pub struct SelfIdentity { |
| 1464 | pub object_id: String, |
| 1465 | pub display_name: String, |
| 1466 | } |
| 1467 | |
| 1468 | pub async fn fetch_self(session: &Session) -> Result<SelfIdentity> { |
| 1469 | let response = session |
| 1470 | .request( |
| 1471 | Method::Get, |
| 1472 | &format!("{GRAPH}/v1.0/me?$select=id,displayName"), |
| 1473 | &Scope::graph("User.ReadBasic.All"), |
| 1474 | None, |
| 1475 | ) |
| 1476 | .await?; |
| 1477 | Ok(SelfIdentity { |
| 1478 | object_id: response.body["id"] |
| 1479 | .as_str() |
| 1480 | .ok_or_else(|| Error::Signaling("graph /me without id".into()))? |
| 1481 | .to_owned(), |
| 1482 | display_name: response.body["displayName"] |
| 1483 | .as_str() |
| 1484 | .unwrap_or_default() |
| 1485 | .to_owned(), |
| 1486 | }) |
| 1487 | } |
| 1488 | |
| 1489 | pub(crate) fn echo_bot_add_body( |
| 1490 | from: &Participant, |
| 1491 | thread_id: Option<&str>, |
| 1492 | callbacks: &CallbackLinks, |
| 1493 | ) -> Value { |
| 1494 | json!({ |
| 1495 | "disableUnmute": false, |
| 1496 | "participants": { |
| 1497 | "from": from.wire(), |
| 1498 | "to": [{"id": ECHO_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}], |
| 1499 | }, |
| 1500 | "participantInvitationData": {}, |
| 1501 | "replacementDetails": null, |
| 1502 | "groupContext": null, |
| 1503 | "groupChat": thread_id.map(|thread_id| json!({"threadId": thread_id, "messageId": null})), |
| 1504 | "links": { |
| 1505 | "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"), |
| 1506 | "addParticipantFailure": callbacks.conversation("addParticipantFailure"), |
| 1507 | }, |
| 1508 | }) |
| 1509 | } |
| 1510 | |
| 1511 | /// The 1:1 chat with the Echo bot; Teams sends it as `groupChat` when adding the bot. |
| 1512 | pub async fn find_echo_bot_thread( |
| 1513 | session: &Session, |
| 1514 | self_object_id: &str, |
| 1515 | ) -> Result<Option<String>> { |
| 1516 | let bot_id = ECHO_BOT_MRI.trim_start_matches("28:"); |
| 1517 | for thread_id in [ |
| 1518 | format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"), |
| 1519 | format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"), |
| 1520 | ] { |
| 1521 | let url = chatsvc::conversations::thread_url(CHATSVC_REGION, &thread_id); |
| 1522 | let response = session |
| 1523 | .batch(&[Request::get(url)], &ic3_scope()) |
| 1524 | .await? |
| 1525 | .remove(0); |
| 1526 | if response.is_success() { |
| 1527 | return Ok(Some(thread_id)); |
| 1528 | } |
| 1529 | } |
| 1530 | Ok(None) |
| 1531 | } |
| 1532 | |
| 1533 | /// Finds the Echo bot 1:1 chat or creates it so `add_echo_bot` can send `groupChat`. |
| 1534 | pub async fn ensure_echo_bot_thread(session: &Session, self_object_id: &str) -> Result<String> { |
| 1535 | if let Some(thread_id) = find_echo_bot_thread(session, self_object_id).await? { |
| 1536 | return Ok(thread_id); |
| 1537 | } |
| 1538 | let self_mri = format!("8:orgid:{self_object_id}"); |
| 1539 | match chatsvc::ThreadMembers::with_region(session, CHATSVC_REGION) |
| 1540 | .create_one_to_one(&[self_mri, ECHO_BOT_MRI.to_owned()]) |
| 1541 | .await |
| 1542 | { |
| 1543 | Ok(thread_id) => Ok(thread_id), |
| 1544 | Err(error) => { |
| 1545 | // Create may succeed without a parseable id; the unique roster is still findable. |
| 1546 | if let Some(thread_id) = find_echo_bot_thread(session, self_object_id).await? { |
| 1547 | return Ok(thread_id); |
| 1548 | } |
| 1549 | Err(Error::Signaling(format!( |
| 1550 | "echo bot chat create failed: {error}" |
| 1551 | ))) |
| 1552 | } |
| 1553 | } |
| 1554 | } |
| 1555 | |
| 1556 | #[cfg(test)] |
| 1557 | mod tests { |
| 1558 | use super::*; |
| 1559 | |
| 1560 | #[test] |
| 1561 | fn raising_publishes_a_raise_hands_state_and_lowering_names_the_state() { |
| 1562 | let raised = raise_hand_body(json!({"id": "8:orgid:me"}), 4); |
| 1563 | assert_eq!(raised["publishedState"]["stateType"], "raiseHands"); |
| 1564 | assert_eq!(raised["publishedState"]["level"], "user"); |
| 1565 | assert_eq!(raised["publishedState"]["sequenceNumber"], 4); |
| 1566 | let lowered = remove_states_body(json!({"id": "8:orgid:me"}), 5, &["s-1".to_owned()]); |
| 1567 | assert_eq!(lowered["scope"], "specified"); |
| 1568 | assert_eq!(lowered["stateIds"][0], "s-1"); |
| 1569 | let all = remove_all_hands_body(json!({"id": "8:orgid:me"}), 6); |
| 1570 | assert_eq!(all["scope"], "all"); |
| 1571 | assert_eq!(all["stateType"], "raiseHands"); |
| 1572 | } |
| 1573 | |
| 1574 | #[test] |
| 1575 | fn a_raised_hand_reads_state_id_and_rank_from_the_publish_response() { |
| 1576 | let body = json!({"publishStateResponse": {"stateId": "s-9", "typeRank": 3}}); |
| 1577 | assert_eq!( |
| 1578 | hand_receipt_from(&body), |
| 1579 | HandReceipt { |
| 1580 | state_id: Some("s-9".to_owned()), |
| 1581 | rank: 3 |
| 1582 | } |
| 1583 | ); |
| 1584 | assert_eq!( |
| 1585 | hand_receipt_from(&json!({})), |
| 1586 | HandReceipt { |
| 1587 | state_id: None, |
| 1588 | rank: u64::MAX |
| 1589 | } |
| 1590 | ); |
| 1591 | } |
| 1592 | |
| 1593 | #[test] |
| 1594 | fn the_meeting_chat_thread_comes_from_the_group_chat_modality() { |
| 1595 | let body = |
| 1596 | json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}}); |
| 1597 | assert_eq!( |
| 1598 | chat_thread_id(&body).as_deref(), |
| 1599 | Some("19:meeting_abc@thread.v2") |
| 1600 | ); |
| 1601 | assert_eq!(chat_thread_id(&json!({"activeModalities": {}})), None); |
| 1602 | } |
| 1603 | |
| 1604 | fn from() -> Participant { |
| 1605 | Participant { |
| 1606 | mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(), |
| 1607 | display_name: "Test".into(), |
| 1608 | endpoint_id: "e".into(), |
| 1609 | participant_id: "p".into(), |
| 1610 | language_id: "en-gb".into(), |
| 1611 | } |
| 1612 | } |
| 1613 | |
| 1614 | fn callbacks() -> CallbackLinks { |
| 1615 | CallbackLinks::new( |
| 1616 | "https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/", |
| 1617 | "call-1", |
| 1618 | ) |
| 1619 | } |
| 1620 | |
| 1621 | fn body_for(target: &InviteTarget) -> Value { |
| 1622 | let from = from(); |
| 1623 | let callbacks = callbacks(); |
| 1624 | epconv_body(&Invitation { |
| 1625 | from: &from, |
| 1626 | offer_sdp: "v=0\r\n", |
| 1627 | media_leg_id: "AB", |
| 1628 | callbacks: &callbacks, |
| 1629 | target, |
| 1630 | modalities: &["Audio".to_owned()], |
| 1631 | direct: true, |
| 1632 | }) |
| 1633 | } |
| 1634 | |
| 1635 | fn callee(mri: &str, name: &str) -> Callee { |
| 1636 | Callee { |
| 1637 | mri: mri.into(), |
| 1638 | display_name: name.into(), |
| 1639 | } |
| 1640 | } |
| 1641 | |
| 1642 | #[test] |
| 1643 | fn only_teams_hosts_get_the_bearer() { |
| 1644 | assert!( |
| 1645 | ensure_teams_url( |
| 1646 | "https://api.flightproxy.teams.microsoft.com/api/v2/ep/conv-x/conv/1/leave?i=1" |
| 1647 | ) |
| 1648 | .is_ok() |
| 1649 | ); |
| 1650 | assert!(ensure_teams_url(EPCONV_URL).is_ok()); |
| 1651 | assert!(ensure_teams_url("https://teams.microsoft.com/trap/tokens").is_ok()); |
| 1652 | assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err()); |
| 1653 | assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err()); |
| 1654 | assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err()); |
| 1655 | } |
| 1656 | |
| 1657 | #[test] |
| 1658 | fn backend_links_go_through_flightproxy() { |
| 1659 | assert_eq!( |
| 1660 | routed_url("https://cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2") |
| 1661 | .unwrap(), |
| 1662 | "https://api.flightproxy.teams.microsoft.com/api/v2/ep/cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2" |
| 1663 | ); |
| 1664 | assert_eq!( |
| 1665 | routed_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y").unwrap(), |
| 1666 | "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y" |
| 1667 | ); |
| 1668 | assert!(routed_url("https://evil.skype.com.example/x").is_err()); |
| 1669 | assert!(routed_url("https://Evil.skype.com/x").is_err()); |
| 1670 | assert!(routed_url("https://user@cc.skype.com/x").is_err()); |
| 1671 | assert!(routed_url("http://cc.skype.com/x").is_err()); |
| 1672 | assert!(routed_url("https://.skype.com/x").is_err()); |
| 1673 | } |
| 1674 | |
| 1675 | #[test] |
| 1676 | fn signaling_failure_detail_keeps_status_and_a_short_body() { |
| 1677 | let detail = signaling_failure_detail(400, &"x".repeat(300)); |
| 1678 | assert!(detail.starts_with("HTTP 400 ")); |
| 1679 | assert_eq!( |
| 1680 | detail.chars().count(), |
| 1681 | "HTTP 400 ".chars().count() + FAILURE_BODY_CHARS |
| 1682 | ); |
| 1683 | } |
| 1684 | |
| 1685 | #[test] |
| 1686 | fn echo_bot_add_body_carries_the_group_chat_thread() { |
| 1687 | let body = echo_bot_add_body(&from(), Some("19:me_bot@unq.gbl.spaces"), &callbacks()); |
| 1688 | assert_eq!(body["groupChat"]["threadId"], "19:me_bot@unq.gbl.spaces"); |
| 1689 | assert_eq!(body["groupChat"]["messageId"], Value::Null); |
| 1690 | assert_eq!(body["participants"]["to"][0]["id"], ECHO_BOT_MRI); |
| 1691 | assert!(!body["groupChat"].is_null()); |
| 1692 | let without = echo_bot_add_body(&from(), None, &callbacks()); |
| 1693 | assert_eq!(without["groupChat"], Value::Null); |
| 1694 | } |
| 1695 | |
| 1696 | #[test] |
| 1697 | fn echo_body_matches_the_captured_test_call_shape() { |
| 1698 | let body = body_for(&InviteTarget::Echo); |
| 1699 | assert_eq!( |
| 1700 | body["conversationRequest"]["scenario"], |
| 1701 | "UserInitiatedTestCall" |
| 1702 | ); |
| 1703 | assert_eq!(body["participants"]["to"], json!([])); |
| 1704 | assert_eq!(body["groupChat"], Value::Null); |
| 1705 | assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"])); |
| 1706 | assert_eq!( |
| 1707 | body["callInvitation"]["mediaContent"]["contentType"], |
| 1708 | SDP_CONTENT_TYPE |
| 1709 | ); |
| 1710 | assert!( |
| 1711 | body["callInvitation"]["links"]["acceptance"] |
| 1712 | .as_str() |
| 1713 | .unwrap() |
| 1714 | .ends_with("/call/acceptance/") |
| 1715 | ); |
| 1716 | assert_eq!( |
| 1717 | body["conversationRequest"]["links"] |
| 1718 | .as_object() |
| 1719 | .unwrap() |
| 1720 | .len(), |
| 1721 | 11 |
| 1722 | ); |
| 1723 | } |
| 1724 | |
| 1725 | #[test] |
| 1726 | fn one_to_one_body_names_the_callee_without_a_chat_thread() { |
| 1727 | let target = InviteTarget::People { |
| 1728 | callees: vec![callee("8:orgid:b", "Bea")], |
| 1729 | thread_id: "19:a_b@unq.gbl.spaces".into(), |
| 1730 | }; |
| 1731 | let body = body_for(&target); |
| 1732 | assert_eq!( |
| 1733 | body["participants"]["to"], |
| 1734 | json!([{"id": "8:orgid:b", "displayName": "Bea"}]) |
| 1735 | ); |
| 1736 | assert_eq!(body["groupChat"], Value::Null); |
| 1737 | let media = &body["callInvitation"]["mediaContent"]; |
| 1738 | assert_eq!(media["requiredFeatures"], "nonByPass"); |
| 1739 | assert!(media.get("mediaDescriptions").is_none()); |
| 1740 | assert!(body["conversationRequest"].get("scenario").is_none()); |
| 1741 | assert_eq!(body["meetingInfo"], Value::Null); |
| 1742 | assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"])); |
| 1743 | } |
| 1744 | |
| 1745 | #[test] |
| 1746 | fn a_one_to_one_call_that_may_not_go_direct_keeps_the_chat_thread() { |
| 1747 | let from = from(); |
| 1748 | let callbacks = callbacks(); |
| 1749 | let target = InviteTarget::People { |
| 1750 | callees: vec![callee("8:orgid:b", "Bea")], |
| 1751 | thread_id: "19:a_b@unq.gbl.spaces".into(), |
| 1752 | }; |
| 1753 | let modalities = vec!["Audio".to_owned()]; |
| 1754 | let body = epconv_body(&Invitation { |
| 1755 | from: &from, |
| 1756 | offer_sdp: "v=0\r\n", |
| 1757 | media_leg_id: "AB", |
| 1758 | callbacks: &callbacks, |
| 1759 | target: &target, |
| 1760 | modalities: &modalities, |
| 1761 | direct: false, |
| 1762 | }); |
| 1763 | assert_eq!(body["groupChat"]["threadId"], "19:a_b@unq.gbl.spaces"); |
| 1764 | assert!(body["callInvitation"]["mediaContent"]["mediaDescriptions"].is_object()); |
| 1765 | } |
| 1766 | |
| 1767 | #[test] |
| 1768 | fn group_body_invites_every_callee_on_the_group_thread() { |
| 1769 | let target = InviteTarget::People { |
| 1770 | callees: vec![ |
| 1771 | callee("8:orgid:b", "Bea"), |
| 1772 | callee("8:orgid:c", "Cy"), |
| 1773 | callee("8:orgid:d", "Di"), |
| 1774 | ], |
| 1775 | thread_id: "19:group@thread.v2".into(), |
| 1776 | }; |
| 1777 | let body = body_for(&target); |
| 1778 | let to = body["participants"]["to"].as_array().unwrap(); |
| 1779 | assert_eq!(to.len(), 3); |
| 1780 | assert_eq!(to[2]["id"], "8:orgid:d"); |
| 1781 | assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2"); |
| 1782 | assert_eq!(body["groupChat"]["messageId"], Value::Null); |
| 1783 | let media = &body["callInvitation"]["mediaContent"]; |
| 1784 | assert!(media.get("requiredFeatures").is_none()); |
| 1785 | assert!(media["mediaDescriptions"].is_object()); |
| 1786 | } |
| 1787 | |
| 1788 | #[test] |
| 1789 | fn meeting_join_body_carries_thread_and_meeting_info() { |
| 1790 | let target = InviteTarget::Meeting(MeetingTarget { |
| 1791 | thread_id: "19:meeting_x@thread.v2".into(), |
| 1792 | tenant_id: "tenant".into(), |
| 1793 | organizer_id: "organizer".into(), |
| 1794 | meeting_data: Some(json!({"meetingCode": "123"})), |
| 1795 | }); |
| 1796 | let body = body_for(&target); |
| 1797 | assert_eq!( |
| 1798 | body["groupChat"], |
| 1799 | json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}) |
| 1800 | ); |
| 1801 | assert_eq!( |
| 1802 | body["meetingInfo"], |
| 1803 | json!({"tenantId": "tenant", "organizerId": "organizer"}) |
| 1804 | ); |
| 1805 | assert_eq!(body["meetingData"]["meetingCode"], "123"); |
| 1806 | assert_eq!(body["participants"]["to"], json!([])); |
| 1807 | assert!(body["conversationRequest"].get("scenario").is_none()); |
| 1808 | assert!( |
| 1809 | body["endpointState"]["endpointProperties"] |
| 1810 | .get("preheatProperties") |
| 1811 | .is_none() |
| 1812 | ); |
| 1813 | } |
| 1814 | |
| 1815 | #[test] |
| 1816 | fn meeting_subscribe_is_roster_only() { |
| 1817 | let meeting = MeetingTarget { |
| 1818 | thread_id: "19:meeting_x@thread.v2".into(), |
| 1819 | tenant_id: "tenant".into(), |
| 1820 | organizer_id: "organizer".into(), |
| 1821 | meeting_data: None, |
| 1822 | }; |
| 1823 | let body = subscribe_body(&from(), &callbacks(), &meeting); |
| 1824 | assert!(body.get("callInvitation").is_none()); |
| 1825 | assert!(body["participants"].get("to").is_none()); |
| 1826 | assert_eq!( |
| 1827 | body["conversationRequest"]["links"] |
| 1828 | .as_object() |
| 1829 | .unwrap() |
| 1830 | .len(), |
| 1831 | 6 |
| 1832 | ); |
| 1833 | assert_eq!(body["groupChat"]["messageId"], "0"); |
| 1834 | assert_eq!(body["meetingInfo"]["organizerId"], "organizer"); |
| 1835 | } |
| 1836 | |
| 1837 | #[test] |
| 1838 | fn leave_bodies_differ_by_reason() { |
| 1839 | let hangup = leave_body(&from(), LeaveReason::Hangup); |
| 1840 | assert_eq!(hangup["callTransactionEnd"]["code"], 0); |
| 1841 | let cancel = leave_body(&from(), LeaveReason::Cancel); |
| 1842 | assert_eq!(cancel["callTransactionEnd"]["code"], 487); |
| 1843 | assert_eq!( |
| 1844 | cancel["callTransactionEnd"]["phrase"], |
| 1845 | "CallEndReasonLocalUserInitiated" |
| 1846 | ); |
| 1847 | assert_eq!( |
| 1848 | cancel["conversationTransactionEnd"]["phrase"], |
| 1849 | "ConversationEndNoModalityConnected" |
| 1850 | ); |
| 1851 | let end = end_for_all_body(&from()); |
| 1852 | assert_eq!( |
| 1853 | end["conversationTransactionEnd"]["phrase"], |
| 1854 | "ConversationEndForAllInitiated" |
| 1855 | ); |
| 1856 | } |
| 1857 | |
| 1858 | #[test] |
| 1859 | fn decline_uses_603() { |
| 1860 | let body = decline_body(); |
| 1861 | assert_eq!(body["callEnd"]["code"], 603); |
| 1862 | assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"])); |
| 1863 | } |
| 1864 | |
| 1865 | #[test] |
| 1866 | fn hangup_call_leg_uses_success_end() { |
| 1867 | let body = hangup_call_leg_body(); |
| 1868 | assert_eq!(body["callEnd"]["code"], 0); |
| 1869 | assert_eq!(body["callEnd"]["phrase"], "CallEndReasonLocalUserInitiated"); |
| 1870 | } |
| 1871 | |
| 1872 | #[test] |
| 1873 | fn attach_asks_for_media_and_joins_the_conversation() { |
| 1874 | let from = from(); |
| 1875 | let callbacks = callbacks(); |
| 1876 | let body = attach_body(&AttachRequest { |
| 1877 | from: &from, |
| 1878 | callbacks: &callbacks, |
| 1879 | controller: Some("https://conv/controller"), |
| 1880 | needs_media: true, |
| 1881 | }); |
| 1882 | assert_eq!(body["attach"]["requireMediaContent"], true); |
| 1883 | assert!( |
| 1884 | body["attach"]["links"]["end"] |
| 1885 | .as_str() |
| 1886 | .unwrap() |
| 1887 | .ends_with("/call/end/") |
| 1888 | ); |
| 1889 | let action = &body["additionalActions"][0]; |
| 1890 | assert_eq!(action["name"], "join"); |
| 1891 | assert_eq!(action["url"], "https://conv/controller"); |
| 1892 | assert_eq!(action["waitForResponse"], true); |
| 1893 | assert_eq!( |
| 1894 | action["input"]["conversationRequest"]["links"] |
| 1895 | .as_object() |
| 1896 | .unwrap() |
| 1897 | .len(), |
| 1898 | 6 |
| 1899 | ); |
| 1900 | let without = attach_body(&AttachRequest { |
| 1901 | from: &from, |
| 1902 | callbacks: &callbacks, |
| 1903 | controller: None, |
| 1904 | needs_media: false, |
| 1905 | }); |
| 1906 | assert!(without.get("additionalActions").is_none()); |
| 1907 | assert_eq!(without["attach"]["requireMediaContent"], false); |
| 1908 | } |
| 1909 | |
| 1910 | #[test] |
| 1911 | fn attach_answer_yields_offer_links_and_conversation() { |
| 1912 | let body = json!({ |
| 1913 | "callInvitation": { |
| 1914 | "links": {"acceptance": "https://cc/accept", "callLeg": "https://cc/leg", "progress": "https://cc/progress"}, |
| 1915 | "mediaContent": {"blob": "v=0\r\n"}, |
| 1916 | "callModalities": ["Audio"], |
| 1917 | }, |
| 1918 | "additionalActionResponses": [{"output": {"conversationController": "https://conv/c", "links": {"leave": "https://conv/leave"}}}], |
| 1919 | }); |
| 1920 | let attached = attached_from(&body).unwrap(); |
| 1921 | assert_eq!(attached.offer_sdp.as_deref(), Some("v=0\r\n")); |
| 1922 | assert_eq!(attached.links["callLeg"], "https://cc/leg"); |
| 1923 | assert_eq!(attached.modalities, vec!["Audio".to_owned()]); |
| 1924 | let conversation = attached.conversation.unwrap(); |
| 1925 | assert_eq!(conversation.controller, "https://conv/c"); |
| 1926 | assert_eq!(conversation.link("leave").unwrap(), "https://conv/leave"); |
| 1927 | assert!(attached_from(&json!({})).is_err()); |
| 1928 | } |
| 1929 | |
| 1930 | #[test] |
| 1931 | fn a_running_meeting_answers_from_its_owning_conversation_with_the_roster() { |
| 1932 | let subscribed = conversation_from(&json!({ |
| 1933 | "conversationController": "https://conv/subscribed", |
| 1934 | "links": {"leave": "https://conv/subscribed/leave", "mute": "https://conv/subscribed/mute"}, |
| 1935 | })) |
| 1936 | .unwrap(); |
| 1937 | assert_eq!(subscribed.roster, None); |
| 1938 | let answer: Value = |
| 1939 | serde_json::from_str(include_str!("../tests/fixtures/meeting_join_answer.json")) |
| 1940 | .unwrap(); |
| 1941 | let joined = joined_conversation(&subscribed, &answer); |
| 1942 | assert_eq!(joined.controller, "https://conv.example/conv/joined"); |
| 1943 | assert_eq!( |
| 1944 | joined.link("leave").unwrap(), |
| 1945 | "https://conv.example/conv/joined/leave" |
| 1946 | ); |
| 1947 | assert_eq!(joined.link("mute").unwrap(), "https://conv/subscribed/mute"); |
| 1948 | assert_eq!( |
| 1949 | joined.roster.unwrap()["participants"] |
| 1950 | .as_object() |
| 1951 | .unwrap() |
| 1952 | .len(), |
| 1953 | 4 |
| 1954 | ); |
| 1955 | assert_eq!( |
| 1956 | joined_conversation(&subscribed, &json!({})).controller, |
| 1957 | "https://conv/subscribed" |
| 1958 | ); |
| 1959 | } |
| 1960 | |
| 1961 | #[test] |
| 1962 | fn acceptance_carries_the_answer_and_callback_links() { |
| 1963 | let from = from(); |
| 1964 | let callbacks = callbacks(); |
| 1965 | let modalities = vec!["Audio".to_owned()]; |
| 1966 | let body = acceptance_body(&Answer { |
| 1967 | from: &from, |
| 1968 | answer_sdp: "v=0\r\n", |
| 1969 | media_leg_id: "AB", |
| 1970 | callbacks: &callbacks, |
| 1971 | modalities: &modalities, |
| 1972 | }); |
| 1973 | let accepted = &body["callAcceptance"]; |
| 1974 | assert_eq!(accepted["acceptedBy"]["id"], from.mri); |
| 1975 | assert_eq!(accepted["acceptedCallModalities"], json!(["Audio"])); |
| 1976 | assert_eq!(accepted["mediaContent"]["blob"], "v=0\r\n"); |
| 1977 | assert_eq!(accepted["links"].as_object().unwrap().len(), 7); |
| 1978 | assert!( |
| 1979 | accepted["links"]["mediaRenegotiation"] |
| 1980 | .as_str() |
| 1981 | .unwrap() |
| 1982 | .ends_with("/call/mediaRenegotiation/") |
| 1983 | ); |
| 1984 | assert_eq!(accepted["callKeepAliveInterval"], Value::Null); |
| 1985 | } |
| 1986 | |
| 1987 | #[test] |
| 1988 | fn the_one_to_one_chat_sorts_both_ids() { |
| 1989 | assert_eq!( |
| 1990 | one_to_one_thread("f74e", "8:orgid:a1b2").as_deref(), |
| 1991 | Some("19:a1b2_f74e@unq.gbl.spaces") |
| 1992 | ); |
| 1993 | assert_eq!( |
| 1994 | one_to_one_thread("a1b2", "8:orgid:f74e").as_deref(), |
| 1995 | Some("19:a1b2_f74e@unq.gbl.spaces") |
| 1996 | ); |
| 1997 | assert_eq!(one_to_one_thread("a1b2", "28:bot"), None); |
| 1998 | } |
| 1999 | |
| 2000 | #[test] |
| 2001 | fn a_refused_offer_says_why() { |
| 2002 | let body = negotiation_failure_body(&from(), "call-1", NegotiationFailure::InProgress); |
| 2003 | assert_eq!(body["mediaNegotiationFailure"]["code"], 491); |
| 2004 | assert_eq!(body["mediaNegotiationFailure"]["subCode"], 3118); |
| 2005 | assert_eq!( |
| 2006 | body["mediaNegotiationFailure"]["phrase"], |
| 2007 | "NegotiationIsInProgress" |
| 2008 | ); |
| 2009 | assert_eq!(body["debugContent"]["callId"], "call-1"); |
| 2010 | assert_eq!( |
| 2011 | negotiation_failure_body(&from(), "c", NegotiationFailure::AnswerError)["mediaNegotiationFailure"] |
| 2012 | ["code"], |
| 2013 | 488 |
| 2014 | ); |
| 2015 | } |
| 2016 | |
| 2017 | #[test] |
| 2018 | fn renegotiation_messages_name_their_reply_links() { |
| 2019 | let from = from(); |
| 2020 | let callbacks = callbacks(); |
| 2021 | let offer = renegotiation_body( |
| 2022 | &from, |
| 2023 | &callbacks, |
| 2024 | "v=0\r\n", |
| 2025 | "AB", |
| 2026 | &["Audio".to_owned()], |
| 2027 | true, |
| 2028 | false, |
| 2029 | ); |
| 2030 | let negotiation = &offer["mediaNegotiation"]; |
| 2031 | assert_eq!(negotiation["mediaContent"]["newOffer"], true); |
| 2032 | assert_eq!(negotiation["callModalities"], json!(["Audio"])); |
| 2033 | let same_peer = renegotiation_body( |
| 2034 | &from, |
| 2035 | &callbacks, |
| 2036 | "v=0\r\n", |
| 2037 | "AB", |
| 2038 | &["Audio".to_owned(), "Video".to_owned()], |
| 2039 | false, |
| 2040 | true, |
| 2041 | ); |
| 2042 | assert_eq!( |
| 2043 | same_peer["mediaNegotiation"]["mediaContent"]["newOffer"], |
| 2044 | false |
| 2045 | ); |
| 2046 | assert_eq!( |
| 2047 | same_peer["mediaNegotiation"]["mediaContent"]["requiredFeatures"], |
| 2048 | "nonByPass" |
| 2049 | ); |
| 2050 | assert!( |
| 2051 | same_peer["mediaNegotiation"]["mediaContent"] |
| 2052 | .get("mediaDescriptions") |
| 2053 | .is_none() |
| 2054 | ); |
| 2055 | assert!(negotiation["mediaContent"]["mediaDescriptions"].is_object()); |
| 2056 | assert_eq!( |
| 2057 | same_peer["mediaNegotiation"]["callModalities"], |
| 2058 | json!(["Audio", "Video"]) |
| 2059 | ); |
| 2060 | assert!( |
| 2061 | negotiation["links"]["mediaAnswer"] |
| 2062 | .as_str() |
| 2063 | .unwrap() |
| 2064 | .ends_with("/call/mediaAnswer/") |
| 2065 | ); |
| 2066 | assert!( |
| 2067 | negotiation["links"]["rejection"] |
| 2068 | .as_str() |
| 2069 | .unwrap() |
| 2070 | .ends_with("/call/rejection/") |
| 2071 | ); |
| 2072 | let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB"); |
| 2073 | assert!( |
| 2074 | answer["mediaAnswer"]["links"]["mediaAcknowledgement"] |
| 2075 | .as_str() |
| 2076 | .unwrap() |
| 2077 | .ends_with("/call/mediaAcknowledgement/") |
| 2078 | ); |
| 2079 | } |
| 2080 | |
| 2081 | #[test] |
| 2082 | fn a_video_call_invites_with_audio_and_video() { |
| 2083 | let from = from(); |
| 2084 | let callbacks = callbacks(); |
| 2085 | let target = InviteTarget::People { |
| 2086 | callees: vec![callee("8:orgid:b", "Bea")], |
| 2087 | thread_id: "19:a_b@unq.gbl.spaces".into(), |
| 2088 | }; |
| 2089 | let modalities = vec!["Audio".to_owned(), "Video".to_owned()]; |
| 2090 | let body = epconv_body(&Invitation { |
| 2091 | from: &from, |
| 2092 | offer_sdp: "v=0\r\n", |
| 2093 | media_leg_id: "AB", |
| 2094 | callbacks: &callbacks, |
| 2095 | target: &target, |
| 2096 | modalities: &modalities, |
| 2097 | direct: true, |
| 2098 | }); |
| 2099 | assert_eq!( |
| 2100 | body["callInvitation"]["callModalities"], |
| 2101 | json!(["Audio", "Video"]) |
| 2102 | ); |
| 2103 | } |
| 2104 | |
| 2105 | #[test] |
| 2106 | fn people_calls_dial_out_and_echo_does_not() { |
| 2107 | let people = InviteTarget::People { |
| 2108 | callees: vec![callee("8:orgid:b", "Bea")], |
| 2109 | thread_id: "19:a_b@unq.gbl.spaces".into(), |
| 2110 | }; |
| 2111 | assert_eq!( |
| 2112 | body_for(&people)["conversationRequest"]["suppressDialout"], |
| 2113 | false |
| 2114 | ); |
| 2115 | assert_eq!( |
| 2116 | body_for(&InviteTarget::Echo)["conversationRequest"]["suppressDialout"], |
| 2117 | true |
| 2118 | ); |
| 2119 | } |
| 2120 | |
| 2121 | #[test] |
| 2122 | fn ringing_progress_names_the_sender() { |
| 2123 | let body = ringing_body(&from()); |
| 2124 | assert_eq!(body["callProgress"]["status"], "ringing"); |
| 2125 | assert_eq!(body["callProgress"]["sender"]["id"], from().mri); |
| 2126 | } |
| 2127 | } |