use std::collections::HashMap;
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use chrono::{DateTime, Utc};
use futures_util::stream::{self, BoxStream};
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use tokio::net::TcpStream;
use tokio::sync::{mpsc, watch};
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
use super::contacts::Owner;
use crate::authentification::CredentialsOrApiKey;
use crate::error::{Error, Result};
use crate::http::{client, ok, websocket};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CallEndStatus {
Completed,
NoAnswer,
Busy,
Failed,
Canceled,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct CallEnd {
pub status: CallEndStatus,
pub duration: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RingEnd {
Accepted,
Taken,
Voicemail,
HungUp,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum CallDirection {
In,
Out,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum CallStatus {
Ringing,
Active,
Ended,
}
type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
fn text(value: &Value, fallback: &str) -> String {
match value {
Value::Null => fallback.to_string(),
Value::String(text) => text.clone(),
value => value.to_string(),
}
}
fn phone_socket_url(
authorization: &CredentialsOrApiKey,
path: &str,
query: &[(&str, &str)],
) -> String {
let header = match authorization {
CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
};
let authorization = json!({ "Authorization": header }).to_string();
let base = websocket(&super::get_url());
match reqwest::Url::parse(&format!("{base}{path}")) {
Ok(mut url) => {
{
let mut pairs = url.query_pairs_mut();
for (key, value) in query {
pairs.append_pair(key, value);
}
pairs.append_pair("authorization", &authorization);
}
url.to_string()
}
Err(_) => format!("{base}{path}"),
}
}
type StatusListener = Arc<dyn Fn(CallStatus) + Send + Sync>;
struct CallState {
status: Mutex<CallStatus>,
listeners: Mutex<Vec<(u64, StatusListener)>>,
next_listener: AtomicU64,
closed: AtomicBool,
audio: Mutex<Option<mpsc::UnboundedReceiver<Vec<u8>>>>,
outbox: mpsc::UnboundedSender<Message>,
ended: watch::Receiver<Option<CallEnd>>,
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
impl CallState {
fn set_status(&self, status: CallStatus) {
{
let mut current = lock(&self.status);
if *current == status {
return;
}
*current = status;
}
let listeners: Vec<StatusListener> = lock(&self.listeners)
.iter()
.map(|(_, listener)| listener.clone())
.collect();
for listener in listeners {
listener(status);
}
}
}
#[derive(Clone)]
pub struct PhoneCall {
pub id: String,
pub direction: CallDirection,
pub line: String,
pub peer: String,
inner: Arc<CallState>,
}
impl PhoneCall {
pub fn status(&self) -> CallStatus {
*lock(&self.inner.status)
}
pub fn on_status(
&self,
listener: impl Fn(CallStatus) + Send + Sync + 'static,
) -> Box<dyn FnOnce() + Send + Sync> {
let id = self.inner.next_listener.fetch_add(1, Ordering::Relaxed);
lock(&self.inner.listeners).push((id, Arc::new(listener)));
let inner = Arc::downgrade(&self.inner);
Box::new(move || {
if let Some(inner) = inner.upgrade() {
lock(&inner.listeners).retain(|(other, _)| *other != id);
}
})
}
pub fn audio(&self) -> BoxStream<'static, Vec<u8>> {
match lock(&self.inner.audio).take() {
Some(receiver) => stream::unfold(receiver, |mut receiver| async move {
receiver.recv().await.map(|chunk| (chunk, receiver))
})
.boxed(),
None => stream::empty().boxed(),
}
}
pub fn send(&self, pcm: Vec<u8>) {
if !self.inner.closed.load(Ordering::SeqCst) {
let _ = self.inner.outbox.send(Message::binary(pcm));
}
}
pub async fn hangup(&self) -> CallEnd {
if !self.inner.closed.load(Ordering::SeqCst) {
let _ = self
.inner
.outbox
.send(Message::text(json!({ "event": "hangup" }).to_string()));
}
self.ended().await
}
pub async fn ended(&self) -> CallEnd {
let mut ended = self.inner.ended.clone();
match ended.wait_for(Option::is_some).await {
Ok(end) => end.unwrap_or(CallEnd {
status: CallEndStatus::Failed,
duration: 0.0,
}),
Err(_) => CallEnd {
status: CallEndStatus::Failed,
duration: 0.0,
},
}
}
pub fn from_json(json: &Value, ws: Socket) -> PhoneCall {
let (mut write, mut read) = ws.split();
let (outbox, mut queue) = mpsc::unbounded_channel::<Message>();
tokio::spawn(async move {
while let Some(message) = queue.recv().await {
let closing = matches!(message, Message::Close(_));
if write.send(message).await.is_err() || closing {
break;
}
}
let _ = write.close().await;
});
let (audio_sender, audio) = mpsc::unbounded_channel();
let (finish, ended) = watch::channel(None);
let inner = Arc::new(CallState {
status: Mutex::new(match json["status"].as_str() {
Some("ACTIVE") => CallStatus::Active,
Some("ENDED") => CallStatus::Ended,
_ => CallStatus::Ringing,
}),
listeners: Mutex::new(Vec::new()),
next_listener: AtomicU64::new(0),
closed: AtomicBool::new(false),
audio: Mutex::new(Some(audio)),
outbox: outbox.clone(),
ended,
});
let state = inner.clone();
tokio::spawn(async move {
let mut audio_sender = Some(audio_sender);
let close =
|end: CallEnd, audio_sender: &mut Option<mpsc::UnboundedSender<Vec<u8>>>| {
if state.closed.swap(true, Ordering::SeqCst) {
return;
}
state.set_status(CallStatus::Ended);
audio_sender.take();
finish.send_replace(Some(end));
};
loop {
match read.next().await {
Some(Ok(Message::Binary(bytes))) => {
if let Some(sender) = &audio_sender {
let _ = sender.send(bytes.to_vec());
}
}
Some(Ok(Message::Text(raw))) => {
let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) else {
continue;
};
match packet["event"].as_str() {
Some("status") => {
if packet["data"]["status"] == "ACTIVE" {
state.set_status(CallStatus::Active);
}
}
Some("ended") => {
close(
CallEnd {
status: serde_json::from_value(
packet["data"]["status"].clone(),
)
.unwrap_or(CallEndStatus::Completed),
duration: packet["data"]["duration"]
.as_f64()
.unwrap_or_default(),
},
&mut audio_sender,
);
let _ = outbox.send(Message::Close(None));
}
Some("error") => close(
CallEnd {
status: CallEndStatus::Failed,
duration: 0.0,
},
&mut audio_sender,
),
_ => {}
}
}
Some(Ok(Message::Close(_))) | None => {
let status = if *lock(&state.status) == CallStatus::Active {
CallEndStatus::Completed
} else {
CallEndStatus::Failed
};
close(
CallEnd {
status,
duration: 0.0,
},
&mut audio_sender,
);
break;
}
Some(Err(_)) => {
close(
CallEnd {
status: CallEndStatus::Failed,
duration: 0.0,
},
&mut audio_sender,
);
break;
}
Some(Ok(_)) => {}
}
}
});
PhoneCall {
id: text(&json["id"], "undefined"),
direction: if json["direction"] == "IN" {
CallDirection::In
} else {
CallDirection::Out
},
line: text(&json["line"], ""),
peer: text(&json["peer"], ""),
inner,
}
}
}
async fn open_socket(url: &str) -> Result<Socket> {
tokio_tungstenite::connect_async(url)
.await
.map(|(socket, _)| socket)
.map_err(|_| Error::Message("Phone connection failed.".to_string()))
}
async fn open_call(authorization: &CredentialsOrApiKey, first: Value) -> Result<PhoneCall> {
let mut socket =
open_socket(&phone_socket_url(authorization, "/cicada/phone/call", &[])).await?;
socket
.send(Message::text(first.to_string()))
.await
.map_err(|_| Error::Message("Phone connection failed.".to_string()))?;
loop {
match socket.next().await {
Some(Ok(Message::Text(raw))) => {
let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) else {
continue;
};
if packet["event"] == "call" {
return Ok(PhoneCall::from_json(&packet["data"], socket));
}
if packet["event"] == "error" {
let _ = socket.close(None).await;
return Err(Error::Message(
packet["message"]
.as_str()
.unwrap_or("The call failed.")
.to_string(),
));
}
}
Some(Ok(Message::Close(_))) | None => {
return Err(Error::Message(
"The call ended before it started.".to_string(),
));
}
Some(Err(_)) => {
return Err(Error::Message("Phone connection failed.".to_string()));
}
Some(Ok(_)) => {}
}
}
}
struct Ring {
accepted: AtomicBool,
ended: watch::Sender<Option<RingEnd>>,
}
impl Ring {
fn end(&self, reason: RingEnd) {
let reason = if self.accepted.load(Ordering::SeqCst) {
RingEnd::Accepted
} else {
reason
};
self.ended.send_if_modified(|ended| {
if ended.is_some() {
return false;
}
*ended = Some(reason);
true
});
}
}
#[derive(Clone)]
pub struct IncomingCall {
pub id: String,
pub line: String,
pub peer: String,
authorization: CredentialsOrApiKey,
ring: Arc<Ring>,
}
impl IncomingCall {
pub async fn accept(&self) -> Result<PhoneCall> {
let call = open_call(
&self.authorization,
json!({ "event": "answer", "id": self.id }),
)
.await?;
self.ring.accepted.store(true, Ordering::SeqCst);
self.ring.end(RingEnd::Accepted);
Ok(call)
}
pub async fn ringing(&self) -> RingEnd {
let mut ended = self.ring.ended.subscribe();
match ended.wait_for(Option::is_some).await {
Ok(reason) => reason.unwrap_or(RingEnd::HungUp),
Err(_) => RingEnd::HungUp,
}
}
pub fn from_json(json: &Value, authorization: &CredentialsOrApiKey) -> IncomingCall {
IncomingCall {
id: text(&json["id"], "undefined"),
line: text(&json["line"], ""),
peer: text(&json["peer"], ""),
authorization: authorization.clone(),
ring: Arc::new(Ring {
accepted: AtomicBool::new(false),
ended: watch::channel(None).0,
}),
}
}
}
type Ringing = Arc<Mutex<HashMap<String, IncomingCall>>>;
fn end_all(ringing: &Ringing) {
for (_, call) in lock(ringing).drain() {
call.ring.end(RingEnd::HungUp);
}
}
pub struct Listening {
ringing: Ringing,
outbox: mpsc::UnboundedSender<Message>,
}
impl Listening {
pub fn close(&self) {
end_all(&self.ringing);
let _ = self.outbox.send(Message::Close(None));
}
}
fn handle_listen_packet(
packet: &Value,
authorization: &CredentialsOrApiKey,
ringing: &Ringing,
on_incoming: &(dyn Fn(IncomingCall) + Send + Sync),
) {
match packet["event"].as_str() {
Some("incoming") => {
let call = IncomingCall::from_json(&packet["data"], authorization);
lock(ringing).insert(call.id.clone(), call.clone());
on_incoming(call);
}
Some("ring-end") => {
let id = text(&packet["data"]["id"], "undefined");
let Some(call) = lock(ringing).remove(&id) else {
return;
};
call.ring.end(
serde_json::from_value(packet["data"]["reason"].clone()).unwrap_or(RingEnd::HungUp),
);
}
_ => {}
}
}
pub async fn listen(
authorization: &CredentialsOrApiKey,
inbox: &str,
on_incoming: impl Fn(IncomingCall) + Send + Sync + 'static,
) -> Result<Listening> {
let socket = open_socket(&phone_socket_url(
authorization,
"/cicada/phone/listen",
&[("inbox", inbox)],
))
.await?;
let (mut write, mut read) = socket.split();
let ringing: Ringing = Arc::new(Mutex::new(HashMap::new()));
let on_incoming: Arc<dyn Fn(IncomingCall) + Send + Sync> = Arc::new(on_incoming);
loop {
match read.next().await {
Some(Ok(Message::Text(raw))) => {
let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) else {
continue;
};
match packet["event"].as_str() {
Some("listening") => break,
Some("error") => {
return Err(Error::Message(
packet["message"]
.as_str()
.unwrap_or("Could not listen for calls.")
.to_string(),
));
}
_ => {
handle_listen_packet(&packet, authorization, &ringing, on_incoming.as_ref())
}
}
}
Some(Ok(Message::Close(_))) | None => {
return Err(Error::Message("Phone connection closed.".to_string()));
}
Some(Err(_)) => {
return Err(Error::Message("Phone connection failed.".to_string()));
}
Some(Ok(_)) => {}
}
}
let (outbox, mut queue) = mpsc::unbounded_channel::<Message>();
tokio::spawn(async move {
while let Some(message) = queue.recv().await {
let closing = matches!(message, Message::Close(_));
if write.send(message).await.is_err() || closing {
break;
}
}
let _ = write.close().await;
});
let listening = ringing.clone();
let authorization = authorization.clone();
tokio::spawn(async move {
while let Some(Ok(message)) = read.next().await {
match message {
Message::Text(raw) => {
if let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) {
handle_listen_packet(
&packet,
&authorization,
&listening,
on_incoming.as_ref(),
);
}
}
Message::Close(_) => break,
_ => {}
}
}
end_all(&listening);
});
Ok(Listening { ringing, outbox })
}
pub async fn call(
authorization: &CredentialsOrApiKey,
inbox: &str,
to: &str,
from: Option<&str>,
) -> Result<PhoneCall> {
let mut first = json!({ "event": "dial", "inbox": inbox, "to": to });
if let Some(from) = from.filter(|from| !from.is_empty()) {
first["from"] = Value::from(from);
}
open_call(authorization, first).await
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CallSpan {
pub start_ms: f64,
pub end_ms: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CallSpeaker {
Them,
You,
Agent,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CallSegment {
#[serde(flatten)]
pub span: CallSpan,
pub speaker: CallSpeaker,
pub text: String,
#[serde(default)]
pub words: Vec<CallSpan>,
}
impl Deref for CallSegment {
type Target = CallSpan;
fn deref(&self) -> &CallSpan {
&self.span
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallRecord {
pub id: String,
pub direction: CallDirection,
pub peer: String,
pub peer_owner: Option<Owner>,
pub line: String,
pub status: String,
pub started_at: DateTime<Utc>,
pub duration: f64,
pub agent: bool,
pub voicemail: bool,
pub recorded: bool,
pub segments: Vec<CallSegment>,
}
impl CallRecord {
pub fn from_json(json: &Value) -> CallRecord {
let flag = |key: &str| match &json[key] {
Value::Bool(value) => *value,
Value::Null => false,
Value::Number(number) => number.as_f64().is_some_and(|number| number != 0.0),
Value::String(value) => !value.is_empty(),
_ => true,
};
CallRecord {
id: text(&json["id"], "undefined"),
direction: if json["direction"] == "in" {
CallDirection::In
} else {
CallDirection::Out
},
peer: text(&json["peer"], ""),
peer_owner: json["peerOwner"]
.is_object()
.then(|| Owner::from_json(&json["peerOwner"])),
line: text(&json["line"], ""),
status: text(&json["status"], ""),
started_at: crate::tickets::parse_date(&json["startedAt"]).unwrap_or_default(),
duration: json["duration"].as_f64().unwrap_or_default(),
agent: flag("agent"),
voicemail: flag("voicemail"),
recorded: flag("recorded"),
segments: json["segments"]
.as_array()
.into_iter()
.flatten()
.filter_map(|segment| serde_json::from_value(segment.clone()).ok())
.collect(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct HistoryOptions {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub voicemails: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub query: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cursor: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max: Option<u32>,
}
fn authorized(
request: reqwest::RequestBuilder,
authorization: &CredentialsOrApiKey,
) -> reqwest::RequestBuilder {
request.header("Content-Type", "application/json").header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
}
pub async fn history(
authorization: &CredentialsOrApiKey,
inbox: &str,
opts: HistoryOptions,
) -> Result<Vec<CallRecord>> {
let mut body = Map::new();
body.insert("inbox".to_string(), Value::from(inbox));
if let Value::Object(fields) = serde_json::to_value(&opts)? {
body.extend(fields);
}
let response = authorized(
client().post(format!("{}/cicada/phone/history", super::get_url())),
authorization,
)
.json(&body)
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(json
.as_array()
.into_iter()
.flatten()
.map(CallRecord::from_json)
.collect())
}
pub async fn recording(authorization: &CredentialsOrApiKey, call: &str) -> Result<Vec<u8>> {
let response = authorized(
client().post(format!("{}/cicada/phone/recording", super::get_url())),
authorization,
)
.json(&json!({ "call": call }))
.send()
.await?;
Ok(ok(response).await?.bytes().await?.to_vec())
}