fauna-api 1.0.859

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
//! Calls on an inbox's linked Twilio numbers. Each person on a call has their own socket
//! carrying their audio. The audio matches Parrot's generate_voice: everyone else on the call
//! arrives as PCM16 mono 16 kHz (generate_voice's input) and what you say goes out as PCM16
//! mono 24 kHz (its output), so a voice agent can sit on a call with no resampling. Calls
//! ring, and show while they're in progress, in the inbox's room (inboxes::InboxRoom).

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, Profile};
use crate::error::{Error, Result};
use crate::http::{client, ok, websocket};

/// Someone on a call from the inbox's side, one per seat: the same person on two sockets is
/// two seats.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CallPerson {
    pub id: String,
    pub profile: Profile,
}

fn people(json: &Value) -> Vec<CallPerson> {
    json.as_array()
        .into_iter()
        .flatten()
        .filter(|person| !person["id"].is_null())
        .map(|person| CallPerson {
            id: text(&person["id"], ""),
            profile: serde_json::from_value(person["profile"].clone()).unwrap_or_default(),
        })
        .collect()
}

#[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,
}

/// `'IN' | 'OUT'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum CallDirection {
    In,
    Out,
}

/// `'RINGING' | 'ACTIVE' | 'ENDED'` in the TypeScript SDK.
#[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>;
type PeopleListener = Arc<dyn Fn() + Send + Sync>;

struct CallState {
    status: Mutex<CallStatus>,
    listeners: Mutex<Vec<(u64, StatusListener)>>,
    people: Mutex<Vec<CallPerson>>,
    agent: AtomicBool,
    people_listeners: Mutex<Vec<(u64, PeopleListener)>>,
    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);
        }
    }

    fn set_people(&self, packet: &Value) {
        *lock(&self.people) = people(&packet["people"]);
        self.agent
            .store(packet["agent"].as_bool().unwrap_or(false), Ordering::SeqCst);
        let listeners: Vec<PeopleListener> = lock(&self.people_listeners)
            .iter()
            .map(|(_, listener)| listener.clone())
            .collect();
        for listener in listeners {
            listener();
        }
    }
}

#[derive(Clone)]
pub struct PhoneCall {
    pub id: String,
    pub direction: CallDirection,
    /// The linked Twilio number, E.164.
    pub line: String,
    /// The other party, E.164.
    pub peer: String,
    /// Your seat on the call.
    pub seat: String,
    inner: Arc<CallState>,
}

impl PhoneCall {
    pub fn status(&self) -> CallStatus {
        *lock(&self.inner.status)
    }

    /// Who is on the call from the inbox's side, you included, one entry per seat.
    pub fn people(&self) -> Vec<CallPerson> {
        lock(&self.inner.people).clone()
    }

    /// The inbox's agent is on the call.
    pub fn agent(&self) -> bool {
        self.inner.agent.load(Ordering::SeqCst)
    }

    /// Calls `listener` when someone from the inbox joins or leaves the call, or the agent
    /// does. Returns a function that stops listening.
    pub fn on_people(
        &self,
        listener: impl Fn() + Send + Sync + 'static,
    ) -> Box<dyn FnOnce() + Send + Sync> {
        let id = self.inner.next_listener.fetch_add(1, Ordering::Relaxed);
        lock(&self.inner.people_listeners).push((id, Arc::new(listener)));
        let inner = Arc::downgrade(&self.inner);
        Box::new(move || {
            if let Some(inner) = inner.upgrade() {
                lock(&inner.people_listeners).retain(|(other, _)| *other != id);
            }
        })
    }

    /// Calls `listener` when the call is answered (ACTIVE) and when it ends (ENDED).
    /// Returns a function that stops listening.
    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);
            }
        })
    }

    /// Everyone else on the call, mixed: PCM16 mono 16 kHz, the same as generate_voice's
    /// audio input. One stream per call; later calls get an empty stream.
    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(),
        }
    }

    /// What you say, to everyone else on the call: PCM16 mono 24 kHz, the same as
    /// generate_voice's audio output.
    pub fn send(&self, pcm: Vec<u8>) {
        if !self.inner.closed.load(Ordering::SeqCst) {
            let _ = self.inner.outbox.send(Message::binary(pcm));
        }
    }

    /// Takes the inbox's agent off the call; the call carries on with everyone else.
    pub fn remove_agent(&self) {
        if !self.inner.closed.load(Ordering::SeqCst) {
            let _ = self.inner.outbox.send(Message::text(
                json!({ "event": "remove-agent" }).to_string(),
            ));
        }
    }

    /// Takes you off the call. It ends once nobody from the inbox is left on it, or when the
    /// other party hangs up.
    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
    }

    /// Resolves once the call is over. duration is seconds of talk, 0 when never answered.
    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,
            },
        }
    }

    /// Takes over a call socket the server has confirmed the call on.
    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()),
            people: Mutex::new(people(&json["people"])),
            agent: AtomicBool::new(json["agent"].as_bool().unwrap_or(false)),
            people_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("people") => state.set_people(&packet["data"]),
                            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"], ""),
            seat: text(&json["seat"], ""),
            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()))
}

/// Opens a call socket and resolves with the call once the server confirms it.
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(_)) => {}
        }
    }
}

/// How an incoming call stops ringing: you accept it, or its inbox's room says it stopped.
struct Ring {
    accepted: watch::Sender<bool>,
    ends: Option<watch::Receiver<Option<RingEnd>>>,
}

/// A call ringing on one of an inbox's lines, from its room.
#[derive(Clone)]
pub struct IncomingCall {
    pub id: String,
    /// The inbox's number that was called.
    pub line: String,
    /// Who is calling.
    pub peer: String,

    authorization: CredentialsOrApiKey,
    ring: Arc<Ring>,
}

impl IncomingCall {
    /// Fails with "Someone else took the call." when someone else answered first.
    pub async fn accept(&self) -> Result<PhoneCall> {
        let call = open_call(
            &self.authorization,
            json!({ "event": "answer", "id": self.id }),
        )
        .await?;
        self.ring.accepted.send_replace(true);
        Ok(call)
    }

    /// Resolves when it stops ringing for you.
    pub async fn ringing(&self) -> RingEnd {
        let mut accepted = self.ring.accepted.subscribe();
        let ended = async {
            match self.ring.ends.clone() {
                Some(mut ends) => match ends.wait_for(Option::is_some).await {
                    Ok(reason) => reason.unwrap_or(RingEnd::HungUp),
                    Err(_) => RingEnd::HungUp,
                },
                None => std::future::pending().await,
            }
        };
        let reason = tokio::select! {
            _ = accepted.wait_for(|accepted| *accepted) => RingEnd::Accepted,
            reason = ended => reason,
        };
        if *self.ring.accepted.borrow() {
            RingEnd::Accepted
        } else {
            reason
        }
    }

    /// `ends` turns to the reason once the inbox's room says it stopped ringing.
    pub fn from_json(
        json: &Value,
        authorization: &CredentialsOrApiKey,
        ends: Option<watch::Receiver<Option<RingEnd>>>,
    ) -> IncomingCall {
        IncomingCall {
            id: text(&json["id"], "undefined"),
            line: text(&json["line"], ""),
            peer: text(&json["peer"], ""),
            authorization: authorization.clone(),
            ring: Arc::new(Ring {
                accepted: watch::channel(false).0,
                ends,
            }),
        }
    }
}

/// A call in progress on one of an inbox's lines, from its room.
#[derive(Clone)]
pub struct ActiveCall {
    pub id: String,
    pub direction: CallDirection,
    /// The inbox's line, E.164.
    pub line: String,
    /// The other party, E.164.
    pub peer: String,
    pub started_at: DateTime<Utc>,
    /// The inbox's agent is on it.
    pub agent: bool,
    /// Who is on it from the inbox's side, one entry per seat.
    pub people: Vec<CallPerson>,

    authorization: CredentialsOrApiKey,
}

impl ActiveCall {
    /// Joins the call: you hear everyone on it, and they hear you.
    pub async fn join(&self) -> Result<PhoneCall> {
        open_call(
            &self.authorization,
            json!({ "event": "join", "id": self.id }),
        )
        .await
    }

    pub fn from_json(json: &Value, authorization: &CredentialsOrApiKey) -> ActiveCall {
        ActiveCall {
            id: text(&json["id"], "undefined"),
            direction: if json["direction"] == "IN" {
                CallDirection::In
            } else {
                CallDirection::Out
            },
            line: text(&json["line"], ""),
            peer: text(&json["peer"], ""),
            started_at: json["startedAt"]
                .as_i64()
                .and_then(DateTime::from_timestamp_millis)
                .unwrap_or_default(),
            agent: json["agent"].as_bool().unwrap_or(false),
            people: people(&json["people"]),
            authorization: authorization.clone(),
        }
    }
}
/// Calls `to` from one of the inbox's phone lines: `from`, or its first line.
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
}

/// Where in a recording something was said, in milliseconds from its start.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CallSpan {
    pub start_ms: f64,
    pub end_ms: f64,
}

/// `'Them' | 'Agent' | 'Person'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CallSpeaker {
    Them,
    Agent,
    Person,
}

/// Someone speaking in a recorded call, each word timed. `Them` is the other party, `Agent`
/// the inbox's agent, and `Person` someone from the inbox, named by `person`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CallSegment {
    #[serde(flatten)]
    pub span: CallSpan,
    pub speaker: CallSpeaker,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub person: Option<Profile>,
    pub text: String,
    #[serde(default)]
    pub words: Vec<CallSpan>,
}

impl Deref for CallSegment {
    type Target = CallSpan;
    fn deref(&self) -> &CallSpan {
        &self.span
    }
}

/// A call on one of the inbox's lines, with its recording's timed transcript.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallRecord {
    pub id: String,
    pub direction: CallDirection,
    /// The other party, E.164.
    pub peer: String,
    /// When `peer` is one of the inbox's owners: who they are.
    pub peer_owner: Option<Owner>,
    /// The inbox's line, E.164.
    pub line: String,
    pub status: String,
    pub started_at: DateTime<Utc>,
    /// Seconds it was connected.
    pub duration: f64,
    /// The inbox's agent took or placed it.
    pub agent: bool,
    /// A message left on the line, or a call that reached their voicemail.
    pub voicemail: bool,
    /// Its audio can be fetched with recording().
    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(),
        }
    }
}

/// The `opts` argument of `history`.
#[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),
        },
    )
}

/// The inbox's calls, newest first. `voicemails: Some(true)` keeps only voicemails and
/// `Some(false)` only calls; both without it. `query` matches what was said, the number, or
/// the contact's name.
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())
}

/// A recorded call's audio, MP3.
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())
}