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