1use std::collections::HashMap;
7use std::ops::Deref;
8use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
9use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
10
11use chrono::{DateTime, Utc};
12use futures_util::stream::{self, BoxStream};
13use futures_util::{SinkExt, StreamExt};
14use serde::{Deserialize, Serialize};
15use serde_json::{Map, Value, json};
16use tokio::net::TcpStream;
17use tokio::sync::{mpsc, watch};
18use tokio_tungstenite::tungstenite::Message;
19use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
20
21use super::contacts::Owner;
22use crate::authentification::CredentialsOrApiKey;
23use crate::error::{Error, Result};
24use crate::http::{client, ok, websocket};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
27#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
28pub enum CallEndStatus {
29 Completed,
30 NoAnswer,
31 Busy,
32 Failed,
33 Canceled,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
37pub struct CallEnd {
38 pub status: CallEndStatus,
39 pub duration: f64,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
43#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
44pub enum RingEnd {
45 Accepted,
46 Taken,
47 Voicemail,
48 HungUp,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
53#[serde(rename_all = "UPPERCASE")]
54pub enum CallDirection {
55 In,
56 Out,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
61#[serde(rename_all = "UPPERCASE")]
62pub enum CallStatus {
63 Ringing,
64 Active,
65 Ended,
66}
67
68type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
69
70fn text(value: &Value, fallback: &str) -> String {
71 match value {
72 Value::Null => fallback.to_string(),
73 Value::String(text) => text.clone(),
74 value => value.to_string(),
75 }
76}
77
78fn phone_socket_url(
79 authorization: &CredentialsOrApiKey,
80 path: &str,
81 query: &[(&str, &str)],
82) -> String {
83 let header = match authorization {
84 CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
85 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
86 };
87 let authorization = json!({ "Authorization": header }).to_string();
88 let base = websocket(&super::get_url());
89 match reqwest::Url::parse(&format!("{base}{path}")) {
90 Ok(mut url) => {
91 {
92 let mut pairs = url.query_pairs_mut();
93 for (key, value) in query {
94 pairs.append_pair(key, value);
95 }
96 pairs.append_pair("authorization", &authorization);
97 }
98 url.to_string()
99 }
100 Err(_) => format!("{base}{path}"),
101 }
102}
103
104type StatusListener = Arc<dyn Fn(CallStatus) + Send + Sync>;
105
106struct CallState {
107 status: Mutex<CallStatus>,
108 listeners: Mutex<Vec<(u64, StatusListener)>>,
109 next_listener: AtomicU64,
110 closed: AtomicBool,
111 audio: Mutex<Option<mpsc::UnboundedReceiver<Vec<u8>>>>,
112 outbox: mpsc::UnboundedSender<Message>,
113 ended: watch::Receiver<Option<CallEnd>>,
114}
115
116fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
117 mutex.lock().unwrap_or_else(PoisonError::into_inner)
118}
119
120impl CallState {
121 fn set_status(&self, status: CallStatus) {
122 {
123 let mut current = lock(&self.status);
124 if *current == status {
125 return;
126 }
127 *current = status;
128 }
129 let listeners: Vec<StatusListener> = lock(&self.listeners)
130 .iter()
131 .map(|(_, listener)| listener.clone())
132 .collect();
133 for listener in listeners {
134 listener(status);
135 }
136 }
137}
138
139#[derive(Clone)]
140pub struct PhoneCall {
141 pub id: String,
142 pub direction: CallDirection,
143 pub line: String,
145 pub peer: String,
147 inner: Arc<CallState>,
148}
149
150impl PhoneCall {
151 pub fn status(&self) -> CallStatus {
152 *lock(&self.inner.status)
153 }
154
155 pub fn on_status(
158 &self,
159 listener: impl Fn(CallStatus) + Send + Sync + 'static,
160 ) -> Box<dyn FnOnce() + Send + Sync> {
161 let id = self.inner.next_listener.fetch_add(1, Ordering::Relaxed);
162 lock(&self.inner.listeners).push((id, Arc::new(listener)));
163 let inner = Arc::downgrade(&self.inner);
164 Box::new(move || {
165 if let Some(inner) = inner.upgrade() {
166 lock(&inner.listeners).retain(|(other, _)| *other != id);
167 }
168 })
169 }
170
171 pub fn audio(&self) -> BoxStream<'static, Vec<u8>> {
174 match lock(&self.inner.audio).take() {
175 Some(receiver) => stream::unfold(receiver, |mut receiver| async move {
176 receiver.recv().await.map(|chunk| (chunk, receiver))
177 })
178 .boxed(),
179 None => stream::empty().boxed(),
180 }
181 }
182
183 pub fn send(&self, pcm: Vec<u8>) {
185 if !self.inner.closed.load(Ordering::SeqCst) {
186 let _ = self.inner.outbox.send(Message::binary(pcm));
187 }
188 }
189
190 pub async fn hangup(&self) -> CallEnd {
191 if !self.inner.closed.load(Ordering::SeqCst) {
192 let _ = self
193 .inner
194 .outbox
195 .send(Message::text(json!({ "event": "hangup" }).to_string()));
196 }
197 self.ended().await
198 }
199
200 pub async fn ended(&self) -> CallEnd {
202 let mut ended = self.inner.ended.clone();
203 match ended.wait_for(Option::is_some).await {
204 Ok(end) => end.unwrap_or(CallEnd {
205 status: CallEndStatus::Failed,
206 duration: 0.0,
207 }),
208 Err(_) => CallEnd {
209 status: CallEndStatus::Failed,
210 duration: 0.0,
211 },
212 }
213 }
214
215 pub fn from_json(json: &Value, ws: Socket) -> PhoneCall {
217 let (mut write, mut read) = ws.split();
218 let (outbox, mut queue) = mpsc::unbounded_channel::<Message>();
219 tokio::spawn(async move {
220 while let Some(message) = queue.recv().await {
221 let closing = matches!(message, Message::Close(_));
222 if write.send(message).await.is_err() || closing {
223 break;
224 }
225 }
226 let _ = write.close().await;
227 });
228 let (audio_sender, audio) = mpsc::unbounded_channel();
229 let (finish, ended) = watch::channel(None);
230 let inner = Arc::new(CallState {
231 status: Mutex::new(match json["status"].as_str() {
232 Some("ACTIVE") => CallStatus::Active,
233 Some("ENDED") => CallStatus::Ended,
234 _ => CallStatus::Ringing,
235 }),
236 listeners: Mutex::new(Vec::new()),
237 next_listener: AtomicU64::new(0),
238 closed: AtomicBool::new(false),
239 audio: Mutex::new(Some(audio)),
240 outbox: outbox.clone(),
241 ended,
242 });
243
244 let state = inner.clone();
245 tokio::spawn(async move {
246 let mut audio_sender = Some(audio_sender);
247 let close =
248 |end: CallEnd, audio_sender: &mut Option<mpsc::UnboundedSender<Vec<u8>>>| {
249 if state.closed.swap(true, Ordering::SeqCst) {
250 return;
251 }
252 state.set_status(CallStatus::Ended);
253 audio_sender.take();
254 finish.send_replace(Some(end));
255 };
256 loop {
257 match read.next().await {
258 Some(Ok(Message::Binary(bytes))) => {
259 if let Some(sender) = &audio_sender {
260 let _ = sender.send(bytes.to_vec());
261 }
262 }
263 Some(Ok(Message::Text(raw))) => {
264 let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) else {
265 continue;
266 };
267 match packet["event"].as_str() {
268 Some("status") => {
269 if packet["data"]["status"] == "ACTIVE" {
270 state.set_status(CallStatus::Active);
271 }
272 }
273 Some("ended") => {
274 close(
275 CallEnd {
276 status: serde_json::from_value(
277 packet["data"]["status"].clone(),
278 )
279 .unwrap_or(CallEndStatus::Completed),
280 duration: packet["data"]["duration"]
281 .as_f64()
282 .unwrap_or_default(),
283 },
284 &mut audio_sender,
285 );
286 let _ = outbox.send(Message::Close(None));
287 }
288 Some("error") => close(
289 CallEnd {
290 status: CallEndStatus::Failed,
291 duration: 0.0,
292 },
293 &mut audio_sender,
294 ),
295 _ => {}
296 }
297 }
298 Some(Ok(Message::Close(_))) | None => {
299 let status = if *lock(&state.status) == CallStatus::Active {
300 CallEndStatus::Completed
301 } else {
302 CallEndStatus::Failed
303 };
304 close(
305 CallEnd {
306 status,
307 duration: 0.0,
308 },
309 &mut audio_sender,
310 );
311 break;
312 }
313 Some(Err(_)) => {
314 close(
315 CallEnd {
316 status: CallEndStatus::Failed,
317 duration: 0.0,
318 },
319 &mut audio_sender,
320 );
321 break;
322 }
323 Some(Ok(_)) => {}
324 }
325 }
326 });
327
328 PhoneCall {
329 id: text(&json["id"], "undefined"),
330 direction: if json["direction"] == "IN" {
331 CallDirection::In
332 } else {
333 CallDirection::Out
334 },
335 line: text(&json["line"], ""),
336 peer: text(&json["peer"], ""),
337 inner,
338 }
339 }
340}
341
342async fn open_socket(url: &str) -> Result<Socket> {
343 tokio_tungstenite::connect_async(url)
344 .await
345 .map(|(socket, _)| socket)
346 .map_err(|_| Error::Message("Phone connection failed.".to_string()))
347}
348
349async fn open_call(authorization: &CredentialsOrApiKey, first: Value) -> Result<PhoneCall> {
351 let mut socket =
352 open_socket(&phone_socket_url(authorization, "/cicada/phone/call", &[])).await?;
353 socket
354 .send(Message::text(first.to_string()))
355 .await
356 .map_err(|_| Error::Message("Phone connection failed.".to_string()))?;
357 loop {
358 match socket.next().await {
359 Some(Ok(Message::Text(raw))) => {
360 let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) else {
361 continue;
362 };
363 if packet["event"] == "call" {
364 return Ok(PhoneCall::from_json(&packet["data"], socket));
365 }
366 if packet["event"] == "error" {
367 let _ = socket.close(None).await;
368 return Err(Error::Message(
369 packet["message"]
370 .as_str()
371 .unwrap_or("The call failed.")
372 .to_string(),
373 ));
374 }
375 }
376 Some(Ok(Message::Close(_))) | None => {
377 return Err(Error::Message(
378 "The call ended before it started.".to_string(),
379 ));
380 }
381 Some(Err(_)) => {
382 return Err(Error::Message("Phone connection failed.".to_string()));
383 }
384 Some(Ok(_)) => {}
385 }
386 }
387}
388
389struct Ring {
390 accepted: AtomicBool,
391 ended: watch::Sender<Option<RingEnd>>,
392}
393
394impl Ring {
395 fn end(&self, reason: RingEnd) {
396 let reason = if self.accepted.load(Ordering::SeqCst) {
397 RingEnd::Accepted
398 } else {
399 reason
400 };
401 self.ended.send_if_modified(|ended| {
402 if ended.is_some() {
403 return false;
404 }
405 *ended = Some(reason);
406 true
407 });
408 }
409}
410
411#[derive(Clone)]
412pub struct IncomingCall {
413 pub id: String,
414 pub line: String,
416 pub peer: String,
418
419 authorization: CredentialsOrApiKey,
420 ring: Arc<Ring>,
421}
422
423impl IncomingCall {
424 pub async fn accept(&self) -> Result<PhoneCall> {
426 let call = open_call(
427 &self.authorization,
428 json!({ "event": "answer", "id": self.id }),
429 )
430 .await?;
431 self.ring.accepted.store(true, Ordering::SeqCst);
432 self.ring.end(RingEnd::Accepted);
433 Ok(call)
434 }
435
436 pub async fn ringing(&self) -> RingEnd {
438 let mut ended = self.ring.ended.subscribe();
439 match ended.wait_for(Option::is_some).await {
440 Ok(reason) => reason.unwrap_or(RingEnd::HungUp),
441 Err(_) => RingEnd::HungUp,
442 }
443 }
444
445 pub fn from_json(json: &Value, authorization: &CredentialsOrApiKey) -> IncomingCall {
446 IncomingCall {
447 id: text(&json["id"], "undefined"),
448 line: text(&json["line"], ""),
449 peer: text(&json["peer"], ""),
450 authorization: authorization.clone(),
451 ring: Arc::new(Ring {
452 accepted: AtomicBool::new(false),
453 ended: watch::channel(None).0,
454 }),
455 }
456 }
457}
458
459type Ringing = Arc<Mutex<HashMap<String, IncomingCall>>>;
460
461fn end_all(ringing: &Ringing) {
462 for (_, call) in lock(ringing).drain() {
463 call.ring.end(RingEnd::HungUp);
464 }
465}
466
467pub struct Listening {
469 ringing: Ringing,
470 outbox: mpsc::UnboundedSender<Message>,
471}
472
473impl Listening {
474 pub fn close(&self) {
475 end_all(&self.ringing);
476 let _ = self.outbox.send(Message::Close(None));
477 }
478}
479
480fn handle_listen_packet(
481 packet: &Value,
482 authorization: &CredentialsOrApiKey,
483 ringing: &Ringing,
484 on_incoming: &(dyn Fn(IncomingCall) + Send + Sync),
485) {
486 match packet["event"].as_str() {
487 Some("incoming") => {
488 let call = IncomingCall::from_json(&packet["data"], authorization);
489 lock(ringing).insert(call.id.clone(), call.clone());
490 on_incoming(call);
491 }
492 Some("ring-end") => {
493 let id = text(&packet["data"]["id"], "undefined");
494 let Some(call) = lock(ringing).remove(&id) else {
495 return;
496 };
497 call.ring.end(
498 serde_json::from_value(packet["data"]["reason"].clone()).unwrap_or(RingEnd::HungUp),
499 );
500 }
501 _ => {}
502 }
503}
504
505pub async fn listen(
507 authorization: &CredentialsOrApiKey,
508 inbox: &str,
509 on_incoming: impl Fn(IncomingCall) + Send + Sync + 'static,
510) -> Result<Listening> {
511 let socket = open_socket(&phone_socket_url(
512 authorization,
513 "/cicada/phone/listen",
514 &[("inbox", inbox)],
515 ))
516 .await?;
517 let (mut write, mut read) = socket.split();
518 let ringing: Ringing = Arc::new(Mutex::new(HashMap::new()));
519 let on_incoming: Arc<dyn Fn(IncomingCall) + Send + Sync> = Arc::new(on_incoming);
520
521 loop {
522 match read.next().await {
523 Some(Ok(Message::Text(raw))) => {
524 let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) else {
525 continue;
526 };
527 match packet["event"].as_str() {
528 Some("listening") => break,
529 Some("error") => {
530 return Err(Error::Message(
531 packet["message"]
532 .as_str()
533 .unwrap_or("Could not listen for calls.")
534 .to_string(),
535 ));
536 }
537 _ => {
538 handle_listen_packet(&packet, authorization, &ringing, on_incoming.as_ref())
539 }
540 }
541 }
542 Some(Ok(Message::Close(_))) | None => {
543 return Err(Error::Message("Phone connection closed.".to_string()));
544 }
545 Some(Err(_)) => {
546 return Err(Error::Message("Phone connection failed.".to_string()));
547 }
548 Some(Ok(_)) => {}
549 }
550 }
551
552 let (outbox, mut queue) = mpsc::unbounded_channel::<Message>();
553 tokio::spawn(async move {
554 while let Some(message) = queue.recv().await {
555 let closing = matches!(message, Message::Close(_));
556 if write.send(message).await.is_err() || closing {
557 break;
558 }
559 }
560 let _ = write.close().await;
561 });
562 let listening = ringing.clone();
563 let authorization = authorization.clone();
564 tokio::spawn(async move {
565 while let Some(Ok(message)) = read.next().await {
566 match message {
567 Message::Text(raw) => {
568 if let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) {
569 handle_listen_packet(
570 &packet,
571 &authorization,
572 &listening,
573 on_incoming.as_ref(),
574 );
575 }
576 }
577 Message::Close(_) => break,
578 _ => {}
579 }
580 }
581 end_all(&listening);
582 });
583
584 Ok(Listening { ringing, outbox })
585}
586
587pub async fn call(
589 authorization: &CredentialsOrApiKey,
590 inbox: &str,
591 to: &str,
592 from: Option<&str>,
593) -> Result<PhoneCall> {
594 let mut first = json!({ "event": "dial", "inbox": inbox, "to": to });
595 if let Some(from) = from.filter(|from| !from.is_empty()) {
596 first["from"] = Value::from(from);
597 }
598 open_call(authorization, first).await
599}
600
601#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
603#[serde(rename_all = "camelCase")]
604pub struct CallSpan {
605 pub start_ms: f64,
606 pub end_ms: f64,
607}
608
609#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
611pub enum CallSpeaker {
612 Them,
613 You,
614 Agent,
615}
616
617#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
620pub struct CallSegment {
621 #[serde(flatten)]
622 pub span: CallSpan,
623 pub speaker: CallSpeaker,
624 pub text: String,
625 #[serde(default)]
626 pub words: Vec<CallSpan>,
627}
628
629impl Deref for CallSegment {
630 type Target = CallSpan;
631 fn deref(&self) -> &CallSpan {
632 &self.span
633 }
634}
635
636#[derive(Debug, Clone, PartialEq, Serialize)]
638#[serde(rename_all = "camelCase")]
639pub struct CallRecord {
640 pub id: String,
641 pub direction: CallDirection,
642 pub peer: String,
644 pub peer_owner: Option<Owner>,
646 pub line: String,
648 pub status: String,
649 pub started_at: DateTime<Utc>,
650 pub duration: f64,
652 pub agent: bool,
654 pub voicemail: bool,
656 pub recorded: bool,
658 pub segments: Vec<CallSegment>,
659}
660
661impl CallRecord {
662 pub fn from_json(json: &Value) -> CallRecord {
663 let flag = |key: &str| match &json[key] {
664 Value::Bool(value) => *value,
665 Value::Null => false,
666 Value::Number(number) => number.as_f64().is_some_and(|number| number != 0.0),
667 Value::String(value) => !value.is_empty(),
668 _ => true,
669 };
670 CallRecord {
671 id: text(&json["id"], "undefined"),
672 direction: if json["direction"] == "in" {
673 CallDirection::In
674 } else {
675 CallDirection::Out
676 },
677 peer: text(&json["peer"], ""),
678 peer_owner: json["peerOwner"]
679 .is_object()
680 .then(|| Owner::from_json(&json["peerOwner"])),
681 line: text(&json["line"], ""),
682 status: text(&json["status"], ""),
683 started_at: crate::tickets::parse_date(&json["startedAt"]).unwrap_or_default(),
684 duration: json["duration"].as_f64().unwrap_or_default(),
685 agent: flag("agent"),
686 voicemail: flag("voicemail"),
687 recorded: flag("recorded"),
688 segments: json["segments"]
689 .as_array()
690 .into_iter()
691 .flatten()
692 .filter_map(|segment| serde_json::from_value(segment.clone()).ok())
693 .collect(),
694 }
695 }
696}
697
698#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
700pub struct HistoryOptions {
701 #[serde(default, skip_serializing_if = "Option::is_none")]
702 pub voicemails: Option<bool>,
703 #[serde(default, skip_serializing_if = "Option::is_none")]
704 pub query: Option<String>,
705 #[serde(default, skip_serializing_if = "Option::is_none")]
706 pub cursor: Option<u32>,
707 #[serde(default, skip_serializing_if = "Option::is_none")]
708 pub max: Option<u32>,
709}
710
711fn authorized(
712 request: reqwest::RequestBuilder,
713 authorization: &CredentialsOrApiKey,
714) -> reqwest::RequestBuilder {
715 request.header("Content-Type", "application/json").header(
716 "Authorization",
717 match authorization {
718 CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
719 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
720 },
721 )
722}
723
724pub async fn history(
726 authorization: &CredentialsOrApiKey,
727 inbox: &str,
728 opts: HistoryOptions,
729) -> Result<Vec<CallRecord>> {
730 let mut body = Map::new();
731 body.insert("inbox".to_string(), Value::from(inbox));
732 if let Value::Object(fields) = serde_json::to_value(&opts)? {
733 body.extend(fields);
734 }
735 let response = authorized(
736 client().post(format!("{}/cicada/phone/history", super::get_url())),
737 authorization,
738 )
739 .json(&body)
740 .send()
741 .await?;
742 let json: Value = ok(response).await?.json().await?;
743 Ok(json
744 .as_array()
745 .into_iter()
746 .flatten()
747 .map(CallRecord::from_json)
748 .collect())
749}
750
751pub async fn recording(authorization: &CredentialsOrApiKey, call: &str) -> Result<Vec<u8>> {
753 let response = authorized(
754 client().post(format!("{}/cicada/phone/recording", super::get_url())),
755 authorization,
756 )
757 .json(&json!({ "call": call }))
758 .send()
759 .await?;
760 Ok(ok(response).await?.bytes().await?.to_vec())
761}