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