use std::collections::BTreeMap; use serde_json::{Map, Value, json}; use session::trusted_url::{HostRule, trusted_https_url}; use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session}; use url::{Position, Url}; use crate::captions::{self, BotAction}; use crate::error::{Error, Result}; use crate::organizer::{self, Invitee, Target}; use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message}; use crate::recording::{self, Consent, RecordingCommand, StartDetails}; use crate::relay::ic3_scope; use crate::roster::MeetingRole; use crate::timeline::Timeline; use crate::transfer::{self, TransferTarget}; use crate::trouter_events::{CallbackLinks, acceptance_links, acknowledgement_links}; use crate::video_layout::MediaDescription; pub const EPCONV_URL: &str = "https://api-emea.flightproxy.teams.microsoft.com/api/v2/epconv"; pub const ECHO_BOT_MRI: &str = "28:cf28171e-fcfd-47e4-a1d6-79460b0b3ca0"; pub const CHATSVC_REGION: &str = "emea"; 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"; 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"; const SDP_CONTENT_TYPE: &str = "application/sdp-ngc-1.0"; const ENDPOINT_CAPABILITIES: u64 = 73463; const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces"; const DIRECT_REQUIRED_FEATURES: &str = "nonByPass"; const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826; const TEAMS_HOSTS: [HostRule; 1] = [HostRule::Domain("teams.microsoft.com")]; const BACKEND_SUFFIX: &str = ".skype.com"; const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite"; const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep"; const CONVERSATION_LINK_NAMES: [&str; 11] = [ "conversationEnd", "conversationUpdate", "localParticipantUpdate", "addParticipantSuccess", "addParticipantFailure", "addModalitySuccess", "addModalityFailure", "confirmUnmute", "receiveMessage", "contentSharingUpdate", "contentSharingEnd", ]; const SUBSCRIBE_LINK_NAMES: [&str; 6] = [ "conversationEnd", "conversationUpdate", "localParticipantUpdate", "addParticipantSuccess", "addParticipantFailure", "receiveMessage", ]; const CALL_LINK_NAMES: [&str; 5] = [ "progress", "mediaAnswer", "acceptance", "redirection", "end", ]; const AUDIO_MODALITIES: [&str; 1] = ["Audio"]; pub(crate) const MEETING_MESSAGE_ID: &str = "0"; const RAISE_HANDS: &str = "raiseHands"; const CANCEL_CODE: i64 = 487; const DECLINE_CODE: i64 = 603; #[derive(Debug, Clone)] pub struct Participant { pub mri: String, pub display_name: String, pub endpoint_id: String, pub participant_id: String, pub language_id: String, } impl Participant { pub fn wire(&self) -> Value { json!({ "id": self.mri, "displayName": self.display_name, "endpointId": self.endpoint_id, "participantId": self.participant_id, "languageId": self.language_id, }) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Callee { pub mri: String, pub display_name: String, } #[derive(Debug, Clone, PartialEq)] pub struct MeetingTarget { pub thread_id: String, pub tenant_id: String, pub organizer_id: String, pub meeting_data: Option, } #[derive(Debug, Clone, PartialEq)] pub enum InviteTarget { Echo, People { callees: Vec, thread_id: String, }, Meeting(MeetingTarget), } #[derive(Debug, Clone)] pub struct TenantRouting { pub region: String, pub partition: String, pub ring: String, } impl Default for TenantRouting { fn default() -> Self { TenantRouting { region: "de".into(), partition: "de01".into(), ring: "general".into(), } } } #[derive(Debug, Clone)] pub struct Conversation { pub controller: String, pub links: BTreeMap, pub chat_thread: Option, pub roster: Option, } impl Conversation { pub fn link(&self, name: &str) -> Result<&str> { self.links .get(name) .map(String::as_str) .ok_or_else(|| Error::Signaling(format!("conversation has no '{name}' link"))) } } fn plain_https(url: &str) -> Result { Url::parse(url) .ok() .filter(|parsed| { parsed.scheme() == "https" && parsed.username().is_empty() && parsed.password().is_none() && parsed.port().is_none() && parsed.host_str().is_some() }) .ok_or_else(|| Error::Signaling("link is not plain https".into())) } /// Bearer requests only go to Teams hosts; links come from server answers. pub fn ensure_teams_url(url: &str) -> Result<()> { trusted_teams_url(url).map(|_| ()) } fn trusted_teams_url(url: &str) -> Result { trusted_https_url(url, &TEAMS_HOSTS).ok_or_else(|| { let host = Url::parse(url) .ok() .and_then(|parsed| parsed.host_str().map(str::to_owned)) .unwrap_or_default(); Error::Signaling(format!("refusing link to host {host}")) }) } fn is_backend_host(host: &str) -> bool { host.len() > BACKEND_SUFFIX.len() && host.ends_with(BACKEND_SUFFIX) && !host.starts_with('.') && !host.contains("..") && host.bytes().all(|byte| { byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-' }) } /// Push links may name a backend host directly; the browser always reaches those through flightproxy. pub fn routed_url(url: &str) -> Result { let parsed = plain_https(url)?; let host = parsed.host_str().unwrap_or_default(); if !is_backend_host(host) { return Ok(trusted_teams_url(url)?.into()); } let path = &parsed[Position::BeforePath..]; Ok(format!("{FLIGHTPROXY_EP}/{host}{path}")) } const FAILURE_BODY_CHARS: usize = 240; /// Status plus a short body excerpt for the timeline and `Error::Signaling`. pub(crate) fn signaling_failure_detail(status: u16, body: &str) -> String { let reason: String = body.chars().take(FAILURE_BODY_CHARS).collect(); format!("HTTP {status} {reason}") } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LeaveReason { Hangup, Cancel, } fn spaces_scope() -> Scope { Scope::new(SPACES, AUTHZ_SCOPE_NAME) } pub struct Signaling { session: Session, poll_session: Session, chain_id: String, routing: TenantRouting, timeline: Timeline, endpoint_state_sequence: std::sync::atomic::AtomicU32, state_sequence: std::sync::atomic::AtomicU32, } pub struct Invitation<'a> { pub from: &'a Participant, pub offer_sdp: &'a str, pub media_leg_id: &'a str, pub callbacks: &'a CallbackLinks, pub target: &'a InviteTarget, pub modalities: &'a [String], pub direct: bool, } impl Invitation<'_> { pub fn is_direct(&self) -> bool { self.direct && self.target.is_one_to_one() } } pub struct Answer<'a> { pub from: &'a Participant, pub answer_sdp: &'a str, pub media_leg_id: &'a str, pub callbacks: &'a CallbackLinks, pub modalities: &'a [String], } pub struct AttachRequest<'a> { pub from: &'a Participant, pub callbacks: &'a CallbackLinks, pub controller: Option<&'a str>, pub needs_media: bool, } #[derive(Debug, Clone)] pub struct Attached { pub offer_sdp: Option, pub from_mixer: bool, pub modalities: Vec, pub links: BTreeMap, pub conversation: Option, } impl Signaling { /// `poll_session` is a second CDP connection so the broker long poll never blocks the call requests. pub fn new( session: Session, poll_session: Session, routing: TenantRouting, timeline: Timeline, ) -> Self { Signaling { session, poll_session, chain_id: uuid::Uuid::new_v4().to_string(), routing, timeline, endpoint_state_sequence: std::sync::atomic::AtomicU32::new(2), state_sequence: std::sync::atomic::AtomicU32::new(0), } } fn request(&self, method: Method, url: &str, body: Option) -> Request { let mut request = match body { Some(body) => Request::with_body(method, url, body), None => Request { method, ..Request::get(url) }, }; request.headers = vec![ ("X-Microsoft-Skype-Chain-ID".into(), self.chain_id.clone()), ( "X-Microsoft-Skype-Message-ID".into(), uuid::Uuid::new_v4().to_string(), ), ("X-Microsoft-Skype-Client".into(), CLIENT_HEADER.into()), ("MS-Teams-Region".into(), self.routing.region.clone()), ("MS-Teams-Partition".into(), self.routing.partition.clone()), ("MS-Teams-Ring".into(), self.routing.ring.clone()), ("X-MS-Migration".into(), "True".into()), ("content-type".into(), "application/json".into()), ]; request } async fn exchange( &self, session: &Session, label: &str, mut request: Request, ) -> Result { request.url = routed_url(&request.url)?; let response = session.batch(&[request], &ic3_scope()).await?.remove(0); if response.is_success() { self.timeline .record(label, format!("HTTP {}", response.status)); return Ok(response); } let detail = signaling_failure_detail(response.status, &response.body.to_string()); self.timeline.record(label, detail.clone()); Err(Error::Signaling(format!("{label} answered {detail}"))) } async fn send( &self, label: &str, method: Method, url: &str, body: Option, ) -> Result { self.exchange(&self.session, label, self.request(method, url, body)) .await } pub async fn post_json(&self, label: &str, url: &str, body: Value) -> Result<()> { self.send(label, Method::Post, url, Some(body)) .await .map(|_| ()) } pub async fn post_json_body(&self, label: &str, url: &str, body: Value) -> Result { self.send(label, Method::Post, url, Some(body)) .await .map(|response| response.body) } pub async fn post_empty(&self, label: &str, url: &str) -> Result<()> { self.send(label, Method::Post, url, None).await.map(|_| ()) } pub async fn create_conversation(&self, invitation: &Invitation<'_>) -> Result { let response = self .send( "POST epconv", Method::Post, EPCONV_URL, Some(epconv_body(invitation)), ) .await?; conversation_from(&response.body) } pub async fn subscribe_meeting( &self, from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget, ) -> Result { let body = subscribe_body(from, callbacks, meeting); let response = self .send( "POST epconv subscribe", Method::Post, EPCONV_URL, Some(body), ) .await?; conversation_from(&response.body) } /// Opens a roster-only conversation for the meeting ID; the caller leaves it once the target is read. pub async fn resolve_meeting( &self, from: &Participant, callbacks: &CallbackLinks, meeting_data: &Value, ) -> Result<(MeetingTarget, Conversation)> { let body = crate::join::resolve_body(from, callbacks, meeting_data); let response = self .send("POST epconv resolve", Method::Post, EPCONV_URL, Some(body)) .await?; let target = crate::join::target_from_answer(&response.body, meeting_data)?; Ok((target, conversation_from(&response.body)?)) } /// A running meeting answers from the conversation that owns it, so its controller and links replace the subscribed ones. pub async fn join_meeting( &self, subscribed: &Conversation, invitation: &Invitation<'_>, ) -> Result { let response = self .send( "POST join", Method::Post, &subscribed.controller, Some(epconv_body(invitation)), ) .await?; Ok(joined_conversation(subscribed, &response.body)) } pub fn next_endpoint_sequence(&self) -> u32 { self.endpoint_state_sequence .fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1 } pub async fn update_endpoint_state( &self, conversation: &Conversation, from: &Participant, muted: bool, ) -> Result<()> { let body = json!({ "from": from.wire(), "endpointState": { "endpointStateSequenceNumber": self.next_endpoint_sequence(), "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}}, "state": {"isMuted": muted}, }, }); let url = conversation.link("updateEndpointState")?; self.post_json("POST updateEndpointState", url, body).await } fn next_state_sequence(&self) -> u32 { self.state_sequence .fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1 } pub async fn raise_hand( &self, conversation: &Conversation, from: &Participant, ) -> Result { let body = raise_hand_body(from.wire(), self.next_state_sequence()); let response = self .send( "POST publishState", Method::Post, conversation.link("publishState")?, Some(body), ) .await?; Ok(hand_receipt_from(&response.body)) } pub async fn lower_hands( &self, conversation: &Conversation, from: &Participant, state_ids: &[String], ) -> Result<()> { let body = remove_states_body(from.wire(), self.next_state_sequence(), state_ids); self.post_json("POST removeState", conversation.link("removeState")?, body) .await } pub async fn lower_all_hands( &self, conversation: &Conversation, from: &Participant, ) -> Result<()> { let body = remove_all_hands_body(from.wire(), self.next_state_sequence()); self.post_json("POST removeState", conversation.link("removeState")?, body) .await } pub async fn send_reaction( &self, conversation: &Conversation, from: &Participant, reaction: Reaction, ) -> Result<()> { let body = reaction_message( from.wire(), reaction, &uuid::Uuid::new_v4().to_string(), &uuid::Uuid::new_v4().to_string(), ); self.post_json("POST sendMessage", conversation.link("sendMessage")?, body) .await } pub async fn update_media_descriptions( &self, url: &str, descriptions: &[MediaDescription], request_id: u32, ) -> Result<()> { let body = json!({ "UpdateMediaDescriptions": { "mediaDescriptions": { "descriptions": descriptions.iter().map(MediaDescription::wire).collect::>(), "requestId": request_id, }, }, }); self.post_json("POST updateMediaDescriptions", url, body) .await } pub async fn add_echo_bot( &self, conversation: &Conversation, from: &Participant, thread_id: Option<&str>, callbacks: &CallbackLinks, ) -> Result<()> { let body = echo_bot_add_body(from, thread_id, callbacks); let url = conversation.link("addParticipantAndModality")?; self.post_json("POST add (echo bot)", url, body).await } pub async fn update_endpoint_metadata( &self, conversation: &Conversation, from: &Participant, ) -> Result<()> { self.put_endpoint_metadata(conversation, from, json!({"holographicCapabilities": 3})) .await } pub async fn set_caption_preference( &self, conversation: &Conversation, from: &Participant, captions: bool, ) -> Result<()> { self.put_endpoint_metadata(conversation, from, captions::endpoint_metadata(captions)) .await } async fn put_endpoint_metadata( &self, conversation: &Conversation, from: &Participant, metadata: Value, ) -> Result<()> { let body = json!({"participants": {"from": from.wire()}, "endpointMetadata": metadata}); let url = conversation.link("updateEndpointMetadata")?; self.send("PUT updateEndpointMetadata", Method::Put, url, Some(body)) .await .map(|_| ()) } pub async fn admit( &self, conversation: &Conversation, from: &Participant, target: Target<'_>, callbacks: &CallbackLinks, ) -> Result { let body = organizer::admit_body( from.wire(), target, callbacks, &uuid::Uuid::new_v4().to_string(), ); self.send( "POST admit", Method::Post, conversation.link("admit")?, Some(body), ) .await .map(|response| response.status) } pub async fn remove_participant( &self, conversation: &Conversation, from: &Participant, target: Target<'_>, callbacks: &CallbackLinks, ) -> Result { let body = organizer::remove_participant_body(from.wire(), target, callbacks); self.send( "POST removeParticipant", Method::Post, conversation.link("removeParticipant")?, Some(body), ) .await .map(|response| response.status) } pub async fn mute_participant( &self, conversation: &Conversation, from: &Participant, mri: &str, ) -> Result { let body = organizer::mute_participants_body(from.wire(), &[mri.to_owned()]); self.send( "POST mute", Method::Post, conversation.link("mute")?, Some(body), ) .await .map(|response| response.status) } pub async fn mute_everyone( &self, conversation: &Conversation, from: &Participant, others: &[String], ) -> Result { let body = organizer::mute_everyone_body(from.wire(), others); self.send( "POST mute (all)", Method::Post, conversation.link("mute")?, Some(body), ) .await .map(|response| response.status) } pub async fn spotlight( &self, conversation: &Conversation, from: &Participant, mri: &str, ) -> Result { let body = organizer::spotlight_body(from.wire(), self.next_state_sequence(), mri, &from.mri); self.send( "POST publishState (spotlight)", Method::Post, conversation.link("publishState")?, Some(body), ) .await .map(|response| response.status) } pub async fn set_lock( &self, conversation: &Conversation, from: &Participant, locked: bool, ) -> Result { let body = organizer::lock_body(from.wire(), locked, self.next_state_sequence()); self.send( "PUT updateMeetingSettings", Method::Put, conversation.link("updateMeetingSettings")?, Some(body), ) .await .map(|response| response.status) } pub async fn change_role( &self, conversation: &Conversation, from: &Participant, mri: &str, role: MeetingRole, ) -> Result { let body = organizer::role_body(from.wire(), mri, role); self.send( "POST updateParticipantRole", Method::Post, conversation.link("updateParticipantRole")?, Some(body), ) .await .map(|response| response.status) } pub async fn publish_attendee_state( &self, conversation: &Conversation, from: &Participant, state_type: &str, mri: &str, ) -> Result { let body = organizer::attendee_state_body( from.wire(), state_type, self.next_state_sequence(), mri, ); self.send( "POST publishState (attendee)", Method::Post, conversation.link("publishState")?, Some(body), ) .await .map(|response| response.status) } pub async fn add_participants( &self, conversation: &Conversation, from: &Participant, callees: &[Callee], group_thread: Option<&str>, meeting: Option<&MeetingTarget>, callbacks: &CallbackLinks, ) -> Result { let invitees: Vec = callees .iter() .map(|callee| Invitee { callee: callee.clone(), participant_id: uuid::Uuid::new_v4().to_string(), }) .collect(); let group_chat = group_thread.map_or(Value::Null, |thread_id| { organizer::group_chat_for(thread_id, meeting.is_some()) }); let body = organizer::add_participants_body( from.wire(), &invitees, group_chat, meeting, callbacks, ); let url = conversation.link(organizer::add_link_name(group_thread.is_some()))?; self.send("POST add (invite)", Method::Post, url, Some(body)) .await .map(|response| response.status) } pub async fn add_caption_bot( &self, conversation: &Conversation, from: &Participant, thread_id: &str, callbacks: &CallbackLinks, threadless: bool, ) -> Result { let body = captions::add_bot_body( from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks, threadless, ); let link = if threadless { "addParticipant" } else { "addParticipantAndModality" }; let mut request = self.request(Method::Post, conversation.link(link)?, Some(body)); request = request.with_body_token( captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER, ); self.exchange(&self.session, "POST add (caption bot)", request) .await .map(|response| response.status) } pub async fn caption_command( &self, command_url: &str, action: BotAction, from: &Participant, ) -> Result<()> { ensure_teams_url(command_url)?; let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let body = captions::command_body(action, &from.mri, &from.participant_id, ×tamp); self.bot_command(command_url, body, "caption command") .await .map(|_| ()) } pub async fn caption_language_command( &self, command_url: &str, from: &Participant, language_tag: &str, ) -> Result<()> { ensure_teams_url(command_url)?; let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let body = captions::language_body(&from.mri, &from.participant_id, ×tamp, language_tag); self.bot_command(command_url, body, "caption language command") .await .map(|_| ()) } async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result { let command_url = trusted_teams_url(command_url)?; let arguments = json!({ "url": command_url.as_str(), "body": body, "recorderResource": captions::RECORDER_RESOURCE, "recorderScope": captions::RECORDER_SCOPE, "requestId": uuid::Uuid::new_v4().to_string(), "chainId": self.chain_id, }); let answer = self .session .run_with_token( App::Teams, &spaces_scope(), captions::COMMAND_SCRIPT, &arguments, false, ) .await?; let status = answer["status"].as_u64().unwrap_or_default(); self.timeline .record(format!("POST {label}"), format!("HTTP {status}")); if (200..300).contains(&status) { return Ok(status as u16); } let reason = answer["error"].as_str().unwrap_or("no answer"); Err(Error::Signaling(format!( "{label} answered HTTP {status} {reason}" ))) } pub async fn recording_command( &self, command_url: &str, command: RecordingCommand, from: &Participant, title: &str, ) -> Result { ensure_teams_url(command_url)?; let now = chrono::Utc::now(); let timestamp = now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let file_name = recording::file_name(title, now); let correlation_id = uuid::Uuid::new_v4().to_string(); let details = StartDetails { own_mri: &from.mri, participant_leg_id: &from.participant_id, timestamp: ×tamp, file_name: &file_name, meeting_title: title, organizer_name: &from.display_name, correlation_id: &correlation_id, }; self.bot_command( command_url, recording::command_body(command, details), "recording command", ) .await } pub async fn consent_to_recording( &self, conversation: &Conversation, from: &Participant, consent: Consent, ) -> Result { let body = recording::consent_body(from.wire(), self.next_state_sequence(), consent); self.send( "POST publishState (recording consent)", Method::Post, conversation.link("publishState")?, Some(body), ) .await .map(|response| response.status) } pub async fn transfer( &self, transfer_url: &str, from: &Participant, target: TransferTarget<'_>, callbacks: &CallbackLinks, ) -> Result<()> { let body = transfer::transfer_body(from, target, callbacks); self.post_json("POST transfer", transfer_url, body).await } /// One broker long poll; answers the next subscribe URL. pub async fn poll_broker(&self, url: &str) -> Result> { let mut request = self.request(Method::Get, url, None); request.headers.push(("X-UseBatching".into(), "1".into())); let response = self .exchange(&self.poll_session, "GET broker subscribe", request) .await?; Ok(response.body["nextSubscribeUrl"] .as_str() .map(str::to_owned)) } pub async fn leave( &self, conversation: &Conversation, from: &Participant, reason: LeaveReason, ) -> Result<()> { let url = conversation.link("leave")?; self.post_json("POST leave", url, leave_body(from, reason)) .await } pub async fn end_for_all(&self, conversation: &Conversation, from: &Participant) -> Result<()> { self.send( "DELETE conversation", Method::Delete, &conversation.controller, Some(end_for_all_body(from)), ) .await .map(|_| ()) } pub async fn attach(&self, url: &str, request: &AttachRequest<'_>) -> Result { let response = self .send("POST attach", Method::Post, url, Some(attach_body(request))) .await?; attached_from(&response.body) } pub async fn send_ringing(&self, url: &str, from: &Participant) -> Result<()> { self.post_json("POST progress", url, ringing_body(from)) .await } pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result> { let response = self .send( "POST acceptance", Method::Post, url, Some(acceptance_body(answer)), ) .await?; Ok(acknowledgement_links(&response.body)) } pub async fn decline(&self, call_leg_url: &str) -> Result<()> { self.send( "DELETE callLeg (decline)", Method::Delete, call_leg_url, Some(decline_body()), ) .await .map(|_| ()) } pub async fn end_call_leg(&self, call_leg_url: &str) -> Result<()> { self.send( "DELETE callLeg (hangup)", Method::Delete, call_leg_url, Some(hangup_call_leg_body()), ) .await .map(|_| ()) } pub async fn reject_renegotiation( &self, url: &str, from: &Participant, call_id: &str, failure: NegotiationFailure, ) -> Result<()> { self.post_json( "POST rejection (renegotiation)", url, negotiation_failure_body(from, call_id, failure), ) .await } pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> { self.post_json( "POST callLeg keep-alive", call_leg_url, json!({"callParticipantUpdate": {}}), ) .await } pub async fn keep_conversation_alive( &self, conversation: &Conversation, from: &Participant, callbacks: &CallbackLinks, ) -> Result<()> { let url = conversation.link("notificationLinks")?; self.post_json( "POST notificationLinks", url, notification_links_body(from, callbacks), ) .await } } fn link_map(names: &[&str], make: impl Fn(&str) -> String) -> Map { names .iter() .map(|name| ((*name).to_owned(), Value::String(make(name)))) .collect() } fn roster_request(callbacks: &CallbackLinks) -> Value { json!({"type": "Delta", "rosterUpdate": callbacks.conversation("rosterUpdate")}) } fn conversation_properties() -> Value { json!({ "allowConversationWithoutHost": true, "enableGroupCallEventMessages": true, "enableGroupCallUpgradeMessage": false, "enableGroupCallMeetupGeneration": false, }) } pub(crate) fn endpoint_state() -> Value { json!({ "endpointStateSequenceNumber": 2, "endpointProperties": {"additionalEndpointProperties": {"infoShownInReportMode": "FullInformation"}}, }) } fn media_content(sdp: &str, media_leg_id: &str, with_descriptions: bool) -> Value { let mut content = json!({ "contentType": SDP_CONTENT_TYPE, "blob": sdp, "clientLocation": "DE", "mediaLegId": media_leg_id, }); if with_descriptions { content["mediaDescriptions"] = json!({"descriptions": [], "requestId": 1}); } content } fn media_controller_links(callbacks: &CallbackLinks) -> Value { json!({ "controlVideoStreaming": callbacks.call("controlVideoStreaming"), "csrcInfo": callbacks.call("csrcInfo"), }) } /// The 1:1 chat of two people: both object ids sorted as plain strings. pub fn one_to_one_thread(own_object_id: &str, peer_mri: &str) -> Option { let peer = peer_mri.strip_prefix("8:orgid:")?; let (first, second) = if own_object_id <= peer { (own_object_id, peer) } else { (peer, own_object_id) }; Some(format!("19:{first}_{second}{ONE_TO_ONE_THREAD_SUFFIX}")) } impl InviteTarget { pub fn is_one_to_one(&self) -> bool { match self { InviteTarget::People { callees, thread_id } => { callees.len() == 1 && thread_id.ends_with(ONE_TO_ONE_THREAD_SUFFIX) } InviteTarget::Echo | InviteTarget::Meeting(_) => false, } } } fn invitation_media(invitation: &Invitation<'_>) -> Value { if !invitation.is_direct() { return media_content(invitation.offer_sdp, invitation.media_leg_id, true); } let mut content = media_content(invitation.offer_sdp, invitation.media_leg_id, false); content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES); content } fn group_chat(invitation: &Invitation<'_>) -> Value { if invitation.is_direct() { return Value::Null; } match invitation.target { InviteTarget::Echo => Value::Null, InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}), InviteTarget::Meeting(meeting) => { json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}) } } } fn callee_wire(callee: &Callee) -> Value { json!({"id": callee.mri, "displayName": callee.display_name}) } pub fn epconv_body(invitation: &Invitation<'_>) -> Value { let callbacks = invitation.callbacks; let target = invitation.target; let to: Vec = match target { InviteTarget::People { callees, .. } => callees.iter().map(callee_wire).collect(), InviteTarget::Echo | InviteTarget::Meeting(_) => Vec::new(), }; let mut request = json!({ "conversationType": null, "subject": null, "suppressDialout": to.is_empty(), "roster": roster_request(callbacks), "properties": conversation_properties(), "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)), }); if matches!(target, InviteTarget::Echo) { request["scenario"] = json!("UserInitiatedTestCall"); } let (meeting_info, meeting_data) = match target { InviteTarget::Meeting(meeting) => ( json!({"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}), meeting.meeting_data.clone().unwrap_or(Value::Null), ), _ => (Value::Null, Value::Null), }; json!({ "conversationRequest": request, "contentSharing": null, "participants": {"from": invitation.from.wire(), "to": to}, "capabilities": null, "endpointCapabilities": ENDPOINT_CAPABILITIES, "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES, "endpointMetadata": {"holographicCapabilities": 3}, "groupContext": null, "groupChat": group_chat(invitation), "meetingInfo": meeting_info, "meetingData": meeting_data, "endpointState": endpoint_state(), "callInvitation": { "callModalities": invitation.modalities, "replaces": null, "transferor": null, "clientTransferContext": null, "customContext": null, "links": link_map(&CALL_LINK_NAMES, |name| callbacks.call(name)), "clientContentForMediaController": media_controller_links(callbacks), "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false}, "emergencyContent": null, "mediaContent": invitation_media(invitation), }, }) } pub(crate) fn subscribe_request(callbacks: &CallbackLinks) -> Value { json!({ "roster": roster_request(callbacks), "properties": conversation_properties(), "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)), }) } pub fn subscribe_body( from: &Participant, callbacks: &CallbackLinks, meeting: &MeetingTarget, ) -> Value { json!({ "conversationRequest": subscribe_request(callbacks), "participants": {"from": from.wire()}, "groupChat": {"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}, "meetingInfo": {"tenantId": meeting.tenant_id, "organizerId": meeting.organizer_id}, "endpointState": endpoint_state(), }) } pub fn leave_body(from: &Participant, reason: LeaveReason) -> Value { let call_end = match reason { LeaveReason::Hangup => { json!({"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}) } LeaveReason::Cancel => { json!({"code": CANCEL_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated"}) } }; json!({ "participants": {"from": from.wire()}, "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndNoModalityConnected"}, "callTransactionEnd": call_end, }) } pub fn end_for_all_body(from: &Participant) -> Value { json!({ "participants": {"from": from.wire()}, "conversationTransactionEnd": {"reason": "noError", "code": 0, "phrase": "ConversationEndForAllInitiated"}, "callTransactionEnd": {"code": 0, "phrase": "CallEndReasonLocalUserInitiated"}, }) } pub fn decline_body() -> Value { json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}}) } pub fn hangup_call_leg_body() -> Value { json!({"callEnd": {"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}}) } pub fn ringing_body(from: &Participant) -> Value { json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}}) } pub fn attach_body(request: &AttachRequest<'_>) -> Value { let callbacks = request.callbacks; let mut body = json!({ "attach": { "requireMediaContent": request.needs_media, "links": {"end": callbacks.call("end")}, }, "capabilities": null, "endpointCapabilities": ENDPOINT_CAPABILITIES, }); if let Some(controller) = request.controller { body["additionalActions"] = json!([{ "name": "join", "url": controller, "waitForResponse": true, "input": { "conversationRequest": { "roster": roster_request(callbacks), "links": link_map(&SUBSCRIBE_LINK_NAMES, |name| callbacks.conversation(name)), }, "participants": {"from": request.from.wire()}, "endpointMetadata": {"holographicCapabilities": 3}, "endpointCapabilities": ENDPOINT_CAPABILITIES, }, }]); } body } pub fn acceptance_body(answer: &Answer<'_>) -> Value { let callbacks = answer.callbacks; json!({ "callAcceptance": { "acceptedBy": answer.from.wire(), "acceptedCallModalities": answer.modalities, "endpointCapabilities": ENDPOINT_CAPABILITIES, "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES, "links": acceptance_links(callbacks), "clientContentForMediaController": media_controller_links(callbacks), "mediaContent": media_content(answer.answer_sdp, answer.media_leg_id, false), "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false}, "callKeepAliveInterval": null, }, }) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NegotiationFailure { InProgress, AnswerError, } impl NegotiationFailure { fn wire(self) -> (u16, u32, &'static str) { match self { NegotiationFailure::InProgress => (491, 3118, "NegotiationIsInProgress"), NegotiationFailure::AnswerError => (488, 3102, "CallEndReasonMediaAnswerError"), } } } pub fn negotiation_failure_body( from: &Participant, call_id: &str, failure: NegotiationFailure, ) -> Value { let (code, sub_code, phrase) = failure.wire(); json!({ "mediaNegotiationFailure": {"sender": from.wire(), "code": code, "subCode": sub_code, "phrase": phrase}, "debugContent": {"callId": call_id, "endpointId": from.endpoint_id}, }) } pub fn renegotiation_body( from: &Participant, callbacks: &CallbackLinks, offer_sdp: &str, media_leg_id: &str, modalities: &[String], new_offer: bool, direct: bool, ) -> Value { json!({ "mediaNegotiation": { "callModalities": modalities, "sender": from.wire(), "links": { "mediaAnswer": callbacks.call("mediaAnswer"), "rejection": callbacks.call("rejection"), }, "mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer, direct), }, }) } fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool, direct: bool) -> Value { let mut content = media_content(sdp, media_leg_id, !direct); if direct { content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES); } content["newOffer"] = json!(new_offer); content } pub fn escalation_answer_body( from: &Participant, callbacks: &CallbackLinks, answer_sdp: &str, media_leg_id: &str, ) -> Value { json!({ "mediaAnswer": { "callModalities": AUDIO_MODALITIES, "sender": from.wire(), "links": {"mediaAcknowledgement": callbacks.call("mediaAcknowledgement")}, "clientContentForMediaController": media_controller_links(callbacks), "mediaContent": media_content(answer_sdp, media_leg_id, false), }, }) } pub fn notification_links_body(from: &Participant, callbacks: &CallbackLinks) -> Value { json!({ "participants": {"from": from.wire()}, "roster": roster_request(callbacks), "links": link_map(&CONVERSATION_LINK_NAMES, |name| callbacks.conversation(name)), }) } fn conversation_from(body: &Value) -> Result { let controller = body["conversationController"] .as_str() .ok_or_else(|| Error::Signaling("answer without conversationController".into()))? .to_owned(); let links = body["links"] .as_object() .map(|links| { links .iter() .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned()))) .collect() }) .unwrap_or_default(); let roster = Some(&body["roster"]) .filter(|roster| roster.is_object()) .cloned(); Ok(Conversation { controller, links, chat_thread: chat_thread_id(body), roster, }) } fn joined_conversation(subscribed: &Conversation, answer: &Value) -> Conversation { let Ok(joined) = conversation_from(answer) else { return subscribed.clone(); }; let mut links = subscribed.links.clone(); links.extend(joined.links); Conversation { controller: joined.controller, links, chat_thread: joined .chat_thread .or_else(|| subscribed.chat_thread.clone()), roster: joined.roster.or_else(|| subscribed.roster.clone()), } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct HandReceipt { pub state_id: Option, pub rank: u64, } pub fn hand_receipt_from(body: &Value) -> HandReceipt { let published = &body["publishStateResponse"]; HandReceipt { state_id: published["stateId"].as_str().map(str::to_owned), rank: published["typeRank"].as_u64().unwrap_or(u64::MAX), } } pub fn raise_hand_body(from: Value, sequence_number: u32) -> Value { json!({ "from": from, "publishedState": { "stateType": RAISE_HANDS, "level": "user", "content": {"skinTone": DEFAULT_SKIN_TONE}, "sequenceNumber": sequence_number, }, }) } pub fn remove_states_body(from: Value, sequence_number: u32, state_ids: &[String]) -> Value { json!({"from": from, "sequenceNumber": sequence_number, "scope": "specified", "stateIds": state_ids}) } pub fn remove_all_hands_body(from: Value, sequence_number: u32) -> Value { json!({"from": from, "sequenceNumber": sequence_number, "scope": "all", "stateType": RAISE_HANDS}) } pub fn chat_thread_id(body: &Value) -> Option { body["activeModalities"]["groupChat"]["threadId"] .as_str() .map(str::to_owned) } fn attached_from(body: &Value) -> Result { let invitation = &body["callInvitation"]; if invitation.is_null() { return Err(Error::Signaling( "attach answer without callInvitation".into(), )); } let links = invitation["links"] .as_object() .map(|links| { links .iter() .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned()))) .collect() }) .unwrap_or_default(); let modalities = invitation["callModalities"] .as_array() .map(|items| { items .iter() .filter_map(|item| item.as_str().map(str::to_owned)) .collect() }) .unwrap_or_default(); Ok(Attached { offer_sdp: invitation["mediaContent"]["blob"] .as_str() .map(str::to_owned), from_mixer: invitation["mediaContent"]["fromMixer"] .as_bool() .unwrap_or(false), modalities, links, conversation: conversation_from(&body["additionalActionResponses"][0]["output"]).ok(), }) } #[derive(Debug, Clone)] pub struct SelfIdentity { pub object_id: String, pub display_name: String, } pub async fn fetch_self(session: &Session) -> Result { let response = session .request( Method::Get, &format!("{GRAPH}/v1.0/me?$select=id,displayName"), &Scope::graph("User.ReadBasic.All"), None, ) .await?; Ok(SelfIdentity { object_id: response.body["id"] .as_str() .ok_or_else(|| Error::Signaling("graph /me without id".into()))? .to_owned(), display_name: response.body["displayName"] .as_str() .unwrap_or_default() .to_owned(), }) } pub(crate) fn echo_bot_add_body( from: &Participant, thread_id: Option<&str>, callbacks: &CallbackLinks, ) -> Value { json!({ "disableUnmute": false, "participants": { "from": from.wire(), "to": [{"id": ECHO_BOT_MRI, "participantId": uuid::Uuid::new_v4().to_string()}], }, "participantInvitationData": {}, "replacementDetails": null, "groupContext": null, "groupChat": thread_id.map(|thread_id| json!({"threadId": thread_id, "messageId": null})), "links": { "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"), "addParticipantFailure": callbacks.conversation("addParticipantFailure"), }, }) } /// The 1:1 chat with the Echo bot; Teams sends it as `groupChat` when adding the bot. pub async fn find_echo_bot_thread( session: &Session, self_object_id: &str, ) -> Result> { let bot_id = ECHO_BOT_MRI.trim_start_matches("28:"); for thread_id in [ format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"), format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"), ] { let url = chatsvc::conversations::thread_url(CHATSVC_REGION, &thread_id); let response = session .batch(&[Request::get(url)], &ic3_scope()) .await? .remove(0); if response.is_success() { return Ok(Some(thread_id)); } } Ok(None) } /// Finds the Echo bot 1:1 chat or creates it so `add_echo_bot` can send `groupChat`. pub async fn ensure_echo_bot_thread(session: &Session, self_object_id: &str) -> Result { if let Some(thread_id) = find_echo_bot_thread(session, self_object_id).await? { return Ok(thread_id); } let self_mri = format!("8:orgid:{self_object_id}"); match chatsvc::ThreadMembers::with_region(session, CHATSVC_REGION) .create_one_to_one(&[self_mri, ECHO_BOT_MRI.to_owned()]) .await { Ok(thread_id) => Ok(thread_id), Err(error) => { // Create may succeed without a parseable id; the unique roster is still findable. if let Some(thread_id) = find_echo_bot_thread(session, self_object_id).await? { return Ok(thread_id); } Err(Error::Signaling(format!( "echo bot chat create failed: {error}" ))) } } } #[cfg(test)] mod tests { use super::*; #[test] fn raising_publishes_a_raise_hands_state_and_lowering_names_the_state() { let raised = raise_hand_body(json!({"id": "8:orgid:me"}), 4); assert_eq!(raised["publishedState"]["stateType"], "raiseHands"); assert_eq!(raised["publishedState"]["level"], "user"); assert_eq!(raised["publishedState"]["sequenceNumber"], 4); let lowered = remove_states_body(json!({"id": "8:orgid:me"}), 5, &["s-1".to_owned()]); assert_eq!(lowered["scope"], "specified"); assert_eq!(lowered["stateIds"][0], "s-1"); let all = remove_all_hands_body(json!({"id": "8:orgid:me"}), 6); assert_eq!(all["scope"], "all"); assert_eq!(all["stateType"], "raiseHands"); } #[test] fn a_raised_hand_reads_state_id_and_rank_from_the_publish_response() { let body = json!({"publishStateResponse": {"stateId": "s-9", "typeRank": 3}}); assert_eq!( hand_receipt_from(&body), HandReceipt { state_id: Some("s-9".to_owned()), rank: 3 } ); assert_eq!( hand_receipt_from(&json!({})), HandReceipt { state_id: None, rank: u64::MAX } ); } #[test] fn the_meeting_chat_thread_comes_from_the_group_chat_modality() { let body = json!({"activeModalities": {"groupChat": {"threadId": "19:meeting_abc@thread.v2"}}}); assert_eq!( chat_thread_id(&body).as_deref(), Some("19:meeting_abc@thread.v2") ); assert_eq!(chat_thread_id(&json!({"activeModalities": {}})), None); } fn from() -> Participant { Participant { mri: "8:orgid:00000000-0000-0000-0000-000000000001".into(), display_name: "Test".into(), endpoint_id: "e".into(), participant_id: "p".into(), language_id: "en-gb".into(), } } fn callbacks() -> CallbackLinks { CallbackLinks::new( "https://pub-ent-x-f.trouter.teams.microsoft.com:3443/v4/f/abc/", "call-1", ) } fn body_for(target: &InviteTarget) -> Value { let from = from(); let callbacks = callbacks(); epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target, modalities: &["Audio".to_owned()], direct: true, }) } fn callee(mri: &str, name: &str) -> Callee { Callee { mri: mri.into(), display_name: name.into(), } } #[test] fn only_teams_hosts_get_the_bearer() { assert!( ensure_teams_url( "https://api.flightproxy.teams.microsoft.com/api/v2/ep/conv-x/conv/1/leave?i=1" ) .is_ok() ); assert!(ensure_teams_url(EPCONV_URL).is_ok()); assert!(ensure_teams_url("https://teams.microsoft.com/trap/tokens").is_ok()); assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err()); assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err()); assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err()); for bypass in [ "https://evil.example\\.teams.microsoft.com/x", "https://evil.example#.teams.microsoft.com/x", "https://a.teams.microsoft.com:x@evil.example/", ] { assert!(ensure_teams_url(bypass).is_err(), "{bypass}"); assert!(routed_url(bypass).is_err(), "{bypass}"); } } #[test] fn backend_links_go_through_flightproxy() { assert_eq!( routed_url("https://cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2") .unwrap(), "https://api.flightproxy.teams.microsoft.com/api/v2/ep/cc-euno-06-prod-aks.cc.skype.com/cc/v1/active/1/attach?i=2" ); assert_eq!( routed_url("https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y").unwrap(), "https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y" ); assert!(routed_url("https://evil.skype.com.example/x").is_err()); assert_eq!( routed_url("https://CC.skype.com/x").unwrap(), format!("{FLIGHTPROXY_EP}/cc.skype.com/x") ); assert!(routed_url("https://cc.skype.com:x@evil.example/x").is_err()); assert!(routed_url("https://evil.example\\.cc.skype.com/x").is_err()); assert!(routed_url("https://user@cc.skype.com/x").is_err()); assert!(routed_url("http://cc.skype.com/x").is_err()); assert!(routed_url("https://.skype.com/x").is_err()); } #[test] fn signaling_failure_detail_keeps_status_and_a_short_body() { let detail = signaling_failure_detail(400, &"x".repeat(300)); assert!(detail.starts_with("HTTP 400 ")); assert_eq!( detail.chars().count(), "HTTP 400 ".chars().count() + FAILURE_BODY_CHARS ); } #[test] fn echo_bot_add_body_carries_the_group_chat_thread() { let body = echo_bot_add_body(&from(), Some("19:me_bot@unq.gbl.spaces"), &callbacks()); assert_eq!(body["groupChat"]["threadId"], "19:me_bot@unq.gbl.spaces"); assert_eq!(body["groupChat"]["messageId"], Value::Null); assert_eq!(body["participants"]["to"][0]["id"], ECHO_BOT_MRI); assert!(!body["groupChat"].is_null()); let without = echo_bot_add_body(&from(), None, &callbacks()); assert_eq!(without["groupChat"], Value::Null); } #[test] fn echo_body_matches_the_captured_test_call_shape() { let body = body_for(&InviteTarget::Echo); assert_eq!( body["conversationRequest"]["scenario"], "UserInitiatedTestCall" ); assert_eq!(body["participants"]["to"], json!([])); assert_eq!(body["groupChat"], Value::Null); assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"])); assert_eq!( body["callInvitation"]["mediaContent"]["contentType"], SDP_CONTENT_TYPE ); assert!( body["callInvitation"]["links"]["acceptance"] .as_str() .unwrap() .ends_with("/call/acceptance/") ); assert_eq!( body["conversationRequest"]["links"] .as_object() .unwrap() .len(), 11 ); } #[test] fn one_to_one_body_names_the_callee_without_a_chat_thread() { let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into(), }; let body = body_for(&target); assert_eq!( body["participants"]["to"], json!([{"id": "8:orgid:b", "displayName": "Bea"}]) ); assert_eq!(body["groupChat"], Value::Null); let media = &body["callInvitation"]["mediaContent"]; assert_eq!(media["requiredFeatures"], "nonByPass"); assert!(media.get("mediaDescriptions").is_none()); assert!(body["conversationRequest"].get("scenario").is_none()); assert_eq!(body["meetingInfo"], Value::Null); assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"])); } #[test] fn a_one_to_one_call_that_may_not_go_direct_keeps_the_chat_thread() { let from = from(); let callbacks = callbacks(); let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into(), }; let modalities = vec!["Audio".to_owned()]; let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities, direct: false, }); assert_eq!(body["groupChat"]["threadId"], "19:a_b@unq.gbl.spaces"); assert!(body["callInvitation"]["mediaContent"]["mediaDescriptions"].is_object()); } #[test] fn group_body_invites_every_callee_on_the_group_thread() { let target = InviteTarget::People { callees: vec![ callee("8:orgid:b", "Bea"), callee("8:orgid:c", "Cy"), callee("8:orgid:d", "Di"), ], thread_id: "19:group@thread.v2".into(), }; let body = body_for(&target); let to = body["participants"]["to"].as_array().unwrap(); assert_eq!(to.len(), 3); assert_eq!(to[2]["id"], "8:orgid:d"); assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2"); assert_eq!(body["groupChat"]["messageId"], Value::Null); let media = &body["callInvitation"]["mediaContent"]; assert!(media.get("requiredFeatures").is_none()); assert!(media["mediaDescriptions"].is_object()); } #[test] fn meeting_join_body_carries_thread_and_meeting_info() { let target = InviteTarget::Meeting(MeetingTarget { thread_id: "19:meeting_x@thread.v2".into(), tenant_id: "tenant".into(), organizer_id: "organizer".into(), meeting_data: Some(json!({"meetingCode": "123"})), }); let body = body_for(&target); assert_eq!( body["groupChat"], json!({"threadId": "19:meeting_x@thread.v2", "messageId": "0"}) ); assert_eq!( body["meetingInfo"], json!({"tenantId": "tenant", "organizerId": "organizer"}) ); assert_eq!(body["meetingData"]["meetingCode"], "123"); assert_eq!(body["participants"]["to"], json!([])); assert!(body["conversationRequest"].get("scenario").is_none()); assert!( body["endpointState"]["endpointProperties"] .get("preheatProperties") .is_none() ); } #[test] fn meeting_subscribe_is_roster_only() { let meeting = MeetingTarget { thread_id: "19:meeting_x@thread.v2".into(), tenant_id: "tenant".into(), organizer_id: "organizer".into(), meeting_data: None, }; let body = subscribe_body(&from(), &callbacks(), &meeting); assert!(body.get("callInvitation").is_none()); assert!(body["participants"].get("to").is_none()); assert_eq!( body["conversationRequest"]["links"] .as_object() .unwrap() .len(), 6 ); assert_eq!(body["groupChat"]["messageId"], "0"); assert_eq!(body["meetingInfo"]["organizerId"], "organizer"); } #[test] fn leave_bodies_differ_by_reason() { let hangup = leave_body(&from(), LeaveReason::Hangup); assert_eq!(hangup["callTransactionEnd"]["code"], 0); let cancel = leave_body(&from(), LeaveReason::Cancel); assert_eq!(cancel["callTransactionEnd"]["code"], 487); assert_eq!( cancel["callTransactionEnd"]["phrase"], "CallEndReasonLocalUserInitiated" ); assert_eq!( cancel["conversationTransactionEnd"]["phrase"], "ConversationEndNoModalityConnected" ); let end = end_for_all_body(&from()); assert_eq!( end["conversationTransactionEnd"]["phrase"], "ConversationEndForAllInitiated" ); } #[test] fn decline_uses_603() { let body = decline_body(); assert_eq!(body["callEnd"]["code"], 603); assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"])); } #[test] fn hangup_call_leg_uses_success_end() { let body = hangup_call_leg_body(); assert_eq!(body["callEnd"]["code"], 0); assert_eq!(body["callEnd"]["phrase"], "CallEndReasonLocalUserInitiated"); } #[test] fn attach_asks_for_media_and_joins_the_conversation() { let from = from(); let callbacks = callbacks(); let body = attach_body(&AttachRequest { from: &from, callbacks: &callbacks, controller: Some("https://conv/controller"), needs_media: true, }); assert_eq!(body["attach"]["requireMediaContent"], true); assert!( body["attach"]["links"]["end"] .as_str() .unwrap() .ends_with("/call/end/") ); let action = &body["additionalActions"][0]; assert_eq!(action["name"], "join"); assert_eq!(action["url"], "https://conv/controller"); assert_eq!(action["waitForResponse"], true); assert_eq!( action["input"]["conversationRequest"]["links"] .as_object() .unwrap() .len(), 6 ); let without = attach_body(&AttachRequest { from: &from, callbacks: &callbacks, controller: None, needs_media: false, }); assert!(without.get("additionalActions").is_none()); assert_eq!(without["attach"]["requireMediaContent"], false); } #[test] fn attach_answer_yields_offer_links_and_conversation() { let body = json!({ "callInvitation": { "links": {"acceptance": "https://cc/accept", "callLeg": "https://cc/leg", "progress": "https://cc/progress"}, "mediaContent": {"blob": "v=0\r\n"}, "callModalities": ["Audio"], }, "additionalActionResponses": [{"output": {"conversationController": "https://conv/c", "links": {"leave": "https://conv/leave"}}}], }); let attached = attached_from(&body).unwrap(); assert_eq!(attached.offer_sdp.as_deref(), Some("v=0\r\n")); assert_eq!(attached.links["callLeg"], "https://cc/leg"); assert_eq!(attached.modalities, vec!["Audio".to_owned()]); let conversation = attached.conversation.unwrap(); assert_eq!(conversation.controller, "https://conv/c"); assert_eq!(conversation.link("leave").unwrap(), "https://conv/leave"); assert!(attached_from(&json!({})).is_err()); } #[test] fn a_running_meeting_answers_from_its_owning_conversation_with_the_roster() { let subscribed = conversation_from(&json!({ "conversationController": "https://conv/subscribed", "links": {"leave": "https://conv/subscribed/leave", "mute": "https://conv/subscribed/mute"}, })) .unwrap(); assert_eq!(subscribed.roster, None); let answer: Value = serde_json::from_str(include_str!("../tests/fixtures/meeting_join_answer.json")) .unwrap(); let joined = joined_conversation(&subscribed, &answer); assert_eq!(joined.controller, "https://conv.example/conv/joined"); assert_eq!( joined.link("leave").unwrap(), "https://conv.example/conv/joined/leave" ); assert_eq!(joined.link("mute").unwrap(), "https://conv/subscribed/mute"); assert_eq!( joined.roster.unwrap()["participants"] .as_object() .unwrap() .len(), 4 ); assert_eq!( joined_conversation(&subscribed, &json!({})).controller, "https://conv/subscribed" ); } #[test] fn acceptance_carries_the_answer_and_callback_links() { let from = from(); let callbacks = callbacks(); let modalities = vec!["Audio".to_owned()]; let body = acceptance_body(&Answer { from: &from, answer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, modalities: &modalities, }); let accepted = &body["callAcceptance"]; assert_eq!(accepted["acceptedBy"]["id"], from.mri); assert_eq!(accepted["acceptedCallModalities"], json!(["Audio"])); assert_eq!(accepted["mediaContent"]["blob"], "v=0\r\n"); assert_eq!(accepted["links"].as_object().unwrap().len(), 7); assert!( accepted["links"]["mediaRenegotiation"] .as_str() .unwrap() .ends_with("/call/mediaRenegotiation/") ); assert_eq!(accepted["callKeepAliveInterval"], Value::Null); } #[test] fn the_one_to_one_chat_sorts_both_ids() { assert_eq!( one_to_one_thread("f74e", "8:orgid:a1b2").as_deref(), Some("19:a1b2_f74e@unq.gbl.spaces") ); assert_eq!( one_to_one_thread("a1b2", "8:orgid:f74e").as_deref(), Some("19:a1b2_f74e@unq.gbl.spaces") ); assert_eq!(one_to_one_thread("a1b2", "28:bot"), None); } #[test] fn a_refused_offer_says_why() { let body = negotiation_failure_body(&from(), "call-1", NegotiationFailure::InProgress); assert_eq!(body["mediaNegotiationFailure"]["code"], 491); assert_eq!(body["mediaNegotiationFailure"]["subCode"], 3118); assert_eq!( body["mediaNegotiationFailure"]["phrase"], "NegotiationIsInProgress" ); assert_eq!(body["debugContent"]["callId"], "call-1"); assert_eq!( negotiation_failure_body(&from(), "c", NegotiationFailure::AnswerError)["mediaNegotiationFailure"] ["code"], 488 ); } #[test] fn renegotiation_messages_name_their_reply_links() { let from = from(); let callbacks = callbacks(); let offer = renegotiation_body( &from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned()], true, false, ); let negotiation = &offer["mediaNegotiation"]; assert_eq!(negotiation["mediaContent"]["newOffer"], true); assert_eq!(negotiation["callModalities"], json!(["Audio"])); let same_peer = renegotiation_body( &from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned(), "Video".to_owned()], false, true, ); assert_eq!( same_peer["mediaNegotiation"]["mediaContent"]["newOffer"], false ); assert_eq!( same_peer["mediaNegotiation"]["mediaContent"]["requiredFeatures"], "nonByPass" ); assert!( same_peer["mediaNegotiation"]["mediaContent"] .get("mediaDescriptions") .is_none() ); assert!(negotiation["mediaContent"]["mediaDescriptions"].is_object()); assert_eq!( same_peer["mediaNegotiation"]["callModalities"], json!(["Audio", "Video"]) ); assert!( negotiation["links"]["mediaAnswer"] .as_str() .unwrap() .ends_with("/call/mediaAnswer/") ); assert!( negotiation["links"]["rejection"] .as_str() .unwrap() .ends_with("/call/rejection/") ); let answer = escalation_answer_body(&from, &callbacks, "v=0\r\n", "AB"); assert!( answer["mediaAnswer"]["links"]["mediaAcknowledgement"] .as_str() .unwrap() .ends_with("/call/mediaAcknowledgement/") ); } #[test] fn a_video_call_invites_with_audio_and_video() { let from = from(); let callbacks = callbacks(); let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into(), }; let modalities = vec!["Audio".to_owned(), "Video".to_owned()]; let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities, direct: true, }); assert_eq!( body["callInvitation"]["callModalities"], json!(["Audio", "Video"]) ); } #[test] fn people_calls_dial_out_and_echo_does_not() { let people = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into(), }; assert_eq!( body_for(&people)["conversationRequest"]["suppressDialout"], false ); assert_eq!( body_for(&InviteTarget::Echo)["conversationRequest"]["suppressDialout"], true ); } #[test] fn ringing_progress_names_the_sender() { let body = ringing_body(&from()); assert_eq!(body["callProgress"]["status"], "ringing"); assert_eq!(body["callProgress"]["sender"]["id"], from().mri); } }