videosdk-server-sdk 0.1.0

Rust server SDK for the VideoSDK v2 REST APIs
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
//! Places and manages SIP calls.

use std::collections::HashMap;
use std::sync::Arc;

use futures_util::Stream;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::client::{CallOptions, Client};
use crate::error::{Error, Result};
use crate::pagination::{auto_page, paginate, ItemMapper, ListParams, Page, PageFetcher};
use crate::query::QueryBuilder;
use crate::resources::escape;
use crate::resources::sip::{SipCallStatus, SipDirection, SipIncludeHeaders, SipMediaEncryption};

const PATH: &str = "/v2/sip/call";

/// A SIP call.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SipCall {
    /// The call id.
    ///
    /// The list endpoint keys this `callId`; the SDK surfaces it here either way.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub id: String,
    /// The call's direction.
    #[serde(rename = "type")]
    pub direction: Option<SipDirection>,
    /// The SIP transport used.
    pub transport: Option<String>,
    /// The upstream provider.
    pub provider: Option<String>,
    /// The gateway the call was placed through.
    pub gateway_id: Option<String>,
    /// The routing rule that matched.
    pub rule_id: Option<String>,
    /// The room the call landed in.
    pub room_id: Option<String>,
    /// The destination number.
    pub to: Option<String>,
    /// The source number.
    pub from: Option<String>,
    /// Transfer details, when the call was transferred.
    pub transfer: Option<Value>,
    /// The session the call belongs to.
    pub session_id: Option<String>,
    /// The call's lifecycle status.
    pub status: Option<SipCallStatus>,
    /// Free-form metadata.
    pub metadata: Option<Map<String, Value>>,
    /// When the call started.
    pub start: Option<String>,
    /// When the call ended.
    pub end: Option<String>,
    /// The call's state transitions.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub timelog: Vec<Value>,
    /// The region the call ran in.
    pub region: Option<String>,
    /// Provider-specific details.
    pub additional_details: Option<Value>,
    /// Any fields the server returned that this SDK does not model yet.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// The parameters for [`SipCallsResource::create`].
///
/// When the call originates from a provisioned phone number — `call_from` is a
/// provisioned number, typically with `routing_rule_id` — then `record_audio`,
/// `dtmf`, `hide_phone_number`, `headers`, `include_headers` and
/// `media_encryption` are taken from the matching routing rule and gateway, so
/// the per-call values here are ignored. When the call is placed directly
/// through an outbound gateway (`gateway_id`), the per-call values apply.
#[derive(Debug, Clone, Default)]
pub struct CreateSipCallParams {
    /// The destination number. Required.
    pub call_to: String,
    /// The source number. Required unless derivable from `gateway_id`.
    pub call_from: Option<String>,
    /// The destination room.
    pub room_id: Option<String>,
    /// The id to assign the call's participant in the destination room.
    ///
    /// Ignored when `participant` is set.
    pub participant_id: Option<String>,
    /// The outbound gateway to place the call through.
    pub gateway_id: Option<String>,
    /// The outbound routing rule to place the call through.
    pub routing_rule_id: Option<String>,
    /// The full participant configuration, overriding `participant_id`.
    pub participant: Option<Map<String, Value>>,
    /// Free-form metadata.
    pub metadata: Option<Map<String, Value>>,
    /// Whether to record the call's audio.
    pub record_audio: Option<bool>,
    /// Whether to block until the call is answered.
    pub wait_until_answered: Option<bool>,
    /// How long to ring before giving up, in seconds.
    pub ringing_timeout: Option<u32>,
    /// Whether to enable DTMF.
    pub dtmf: Option<bool>,
    /// The maximum call duration, in seconds.
    pub max_call_duration: Option<u32>,
    /// Whether to encrypt media.
    pub media_encryption: Option<SipMediaEncryption>,
    /// Whether to hide the caller's number from the room.
    pub hide_phone_number: Option<bool>,
    /// Headers to add to the outbound call.
    pub headers: HashMap<String, String>,
    /// Which SIP headers to forward.
    pub include_headers: Option<SipIncludeHeaders>,
}

/// `call_to` becomes `sipCallTo`, `call_from` becomes `sipCallFrom`, and
/// `room_id` becomes `destinationRoomId`.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct CreateSipCallWire {
    sip_call_to: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    sip_call_from: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    destination_room_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    participant: Option<Map<String, Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    gateway_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    routing_rule_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    metadata: Option<Map<String, Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    record_audio: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    wait_until_answered: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ringing_timeout: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    dtmf: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_call_duration: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    media_encryption: Option<SipMediaEncryption>,
    #[serde(skip_serializing_if = "Option::is_none")]
    hide_phone_number: Option<bool>,
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    headers: HashMap<String, String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    include_headers: Option<SipIncludeHeaders>,
}

impl From<CreateSipCallParams> for CreateSipCallWire {
    fn from(params: CreateSipCallParams) -> Self {
        // `participant_id` is sugar for a participant object.
        let participant = params.participant.or_else(|| {
            params.participant_id.map(|id| {
                let mut map = Map::new();
                map.insert("id".to_string(), Value::String(id));
                map
            })
        });

        Self {
            sip_call_to: params.call_to,
            sip_call_from: params.call_from,
            destination_room_id: params.room_id,
            participant,
            gateway_id: params.gateway_id,
            routing_rule_id: params.routing_rule_id,
            metadata: params.metadata,
            record_audio: params.record_audio,
            wait_until_answered: params.wait_until_answered,
            ringing_timeout: params.ringing_timeout,
            dtmf: params.dtmf,
            max_call_duration: params.max_call_duration,
            media_encryption: params.media_encryption,
            hide_phone_number: params.hide_phone_number,
            headers: params.headers,
            include_headers: params.include_headers,
        }
    }
}

/// The parameters for [`SipCallsResource::transfer`].
#[derive(Debug, Clone, Default)]
pub struct TransferSipCallParams {
    /// The destination to transfer to.
    pub to: Option<String>,
    /// The participant configuration for the transferred leg.
    pub participant: Option<Map<String, Value>>,
    /// Whether to play a dial tone during the transfer.
    pub play_dialtone: Option<bool>,
}

/// `to` becomes `transferTo`.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct TransferWire<'a> {
    call_id: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    transfer_to: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    participant: Option<&'a Map<String, Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    play_dialtone: Option<bool>,
}

/// The parameters for [`SipCallsResource::switch_room`].
#[derive(Debug, Clone, Default)]
pub struct SwitchRoomParams {
    /// The destination room. Required.
    pub room_id: String,
    /// The id to assign the call's participant in the destination room.
    pub participant_id: Option<String>,
    /// A token authorizing the move.
    pub token: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct SwitchRoomWire<'a> {
    call_id: &'a str,
    room_id: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    participant_id: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    token: Option<&'a str>,
}

/// The query parameters for [`SipCallsResource::list`].
#[derive(Debug, Clone, Default)]
pub struct SipCallListParams {
    /// The 1-based page number.
    pub page: Option<u32>,
    /// Items per page.
    pub per_page: Option<u32>,
    /// An opaque cursor from a previous page.
    pub cursor: Option<String>,
    /// Filters by room id.
    pub room_id: Option<String>,
    /// Filters by session id.
    pub session_id: Option<String>,
    /// Filters by call id.
    pub id: Option<String>,
    /// Filters by gateway id.
    pub gateway_id: Option<String>,
    /// Filters by routing-rule id.
    pub rule_id: Option<String>,
    /// Filters by direction.
    pub direction: Option<SipDirection>,
    /// Matches on `to`, `from` or `room_id`.
    pub search: Option<String>,
    /// Filters by call start, in epoch milliseconds. Start of the range.
    pub start_date: Option<i64>,
    /// Filters by call start, in epoch milliseconds. End of the range.
    pub end_date: Option<i64>,
}

impl SipCallListParams {
    fn pagination(&self) -> ListParams {
        ListParams {
            page: self.page,
            per_page: self.per_page,
            cursor: self.cursor.clone(),
        }
    }
}

/// The list aggregation exposes the id as `callId`. Surface it as `id`, so a
/// listed call has the same shape as a fetched one.
fn call_item_mapper() -> ItemMapper<SipCall> {
    Arc::new(|value: Value| {
        let mut call: SipCall =
            serde_json::from_value(value).map_err(|e| Error::decode("SIP call list item", e))?;
        if call.id.is_empty() {
            if let Some(call_id) = call.extra.get("callId").and_then(Value::as_str) {
                call.id = call_id.to_string();
            }
        }
        Ok(call)
    })
}

/// SIP calls. Reached via [`SipResource::calls`](crate::SipResource::calls).
#[derive(Debug, Clone, Copy)]
pub struct SipCallsResource<'a> {
    client: &'a Client,
}

impl<'a> SipCallsResource<'a> {
    pub(crate) fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// Places an outbound call.
    pub async fn create(&self, params: CreateSipCallParams) -> Result<SipCall> {
        if params.call_to.is_empty() {
            return Err(Error::validation(
                "sip.calls().create() requires call_to, the destination number",
            ));
        }
        let body = CreateSipCallWire::from(params);
        self.client
            .data(Method::POST, PATH, CallOptions::json(&body)?)
            .await
    }

    /// Lists calls, one page at a time.
    pub async fn list(&self, params: SipCallListParams) -> Result<Page<SipCall>> {
        paginate(
            self.fetcher(&params),
            &params.pagination(),
            "data",
            Some(call_item_mapper()),
        )
        .await
    }

    /// Lists calls, transparently fetching every page.
    pub fn list_stream(
        &self,
        params: SipCallListParams,
    ) -> impl Stream<Item = Result<SipCall>> + Send {
        auto_page(
            self.fetcher(&params),
            params.pagination(),
            "data",
            Some(call_item_mapper()),
        )
    }

    /// Fetches a call by id.
    pub async fn get(&self, call_id: &str) -> Result<SipCall> {
        let path = format!("{PATH}/{}", escape(call_id));
        self.client
            .data(Method::GET, &path, CallOptions::new())
            .await
    }

    /// Cold-transfers an answered call.
    pub async fn transfer(&self, call_id: &str, params: TransferSipCallParams) -> Result<SipCall> {
        let body = TransferWire {
            call_id,
            transfer_to: params.to.as_deref(),
            participant: params.participant.as_ref(),
            play_dialtone: params.play_dialtone,
        };
        let path = format!("{PATH}/transfer");
        self.client
            .data(Method::POST, &path, CallOptions::json(&body)?)
            .await
    }

    /// Hangs up a call.
    pub async fn end(&self, call_id: &str) -> Result<SipCall> {
        let body = serde_json::json!({ "callId": call_id });
        let path = format!("{PATH}/end");
        self.client
            .data(Method::POST, &path, CallOptions::json(&body)?)
            .await
    }

    /// Moves an active SIP leg to another room.
    pub async fn switch_room(&self, call_id: &str, params: SwitchRoomParams) -> Result<SipCall> {
        let body = SwitchRoomWire {
            call_id,
            room_id: &params.room_id,
            participant_id: params.participant_id.as_deref(),
            token: params.token.as_deref(),
        };
        let path = format!("{PATH}/switch-room");
        self.client
            .data(Method::POST, &path, CallOptions::json(&body)?)
            .await
    }

    fn fetcher(&self, params: &SipCallListParams) -> PageFetcher {
        let client = self.client.clone();
        let params = params.clone();
        Arc::new(move |page, per_page| {
            let client = client.clone();
            let params = params.clone();
            Box::pin(async move {
                let query = QueryBuilder::new()
                    .opt("page", page)
                    .opt("perPage", per_page)
                    .opt_str("roomId", params.room_id.as_deref())
                    .opt_str("sessionId", params.session_id.as_deref())
                    .opt_str("id", params.id.as_deref())
                    .opt_str("gatewayId", params.gateway_id.as_deref())
                    .opt_str("ruleId", params.rule_id.as_deref())
                    .opt_str("type", params.direction.as_ref().map(SipDirection::as_str))
                    .opt_str("search", params.search.as_deref())
                    .opt("startDate", params.start_date)
                    .opt("endDate", params.end_date)
                    .into_pairs();
                client
                    .json::<Value>(Method::GET, PATH, CallOptions::new().query(query))
                    .await
            })
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn wire(params: CreateSipCallParams) -> Value {
        serde_json::to_value(CreateSipCallWire::from(params)).unwrap()
    }

    #[test]
    fn create_renames_call_to_and_call_from() {
        let body = wire(CreateSipCallParams {
            call_to: "+15550001".into(),
            call_from: Some("+15550002".into()),
            room_id: Some("r-1".into()),
            ..Default::default()
        });
        assert_eq!(
            body,
            json!({
                "sipCallTo": "+15550001",
                "sipCallFrom": "+15550002",
                "destinationRoomId": "r-1",
            })
        );
    }

    #[test]
    fn participant_id_is_sugar_for_a_participant_object() {
        let body = wire(CreateSipCallParams {
            call_to: "+1".into(),
            participant_id: Some("p-1".into()),
            ..Default::default()
        });
        assert_eq!(body["participant"], json!({"id": "p-1"}));
    }

    #[test]
    fn an_explicit_participant_wins_over_participant_id() {
        let mut participant = Map::new();
        participant.insert("id".into(), json!("explicit"));
        participant.insert("name".into(), json!("Ada"));

        let body = wire(CreateSipCallParams {
            call_to: "+1".into(),
            participant_id: Some("sugar".into()),
            participant: Some(participant),
            ..Default::default()
        });
        assert_eq!(body["participant"]["id"], json!("explicit"));
        assert_eq!(body["participant"]["name"], json!("Ada"));
    }

    #[test]
    fn absent_options_are_omitted() {
        let body = wire(CreateSipCallParams {
            call_to: "+1".into(),
            ..Default::default()
        });
        assert_eq!(body, json!({"sipCallTo": "+1"}));
    }

    #[test]
    fn the_list_mapper_surfaces_call_id_as_id() {
        let mapper = call_item_mapper();
        let call = mapper(json!({"callId": "c-1", "to": "+1"})).unwrap();
        assert_eq!(call.id, "c-1");

        // A real `id` is never overwritten.
        let call = mapper(json!({"id": "real", "callId": "c-1"})).unwrap();
        assert_eq!(call.id, "real");
    }

    #[test]
    fn transfer_renames_to_as_transfer_to() {
        let body = serde_json::to_value(TransferWire {
            call_id: "c-1",
            transfer_to: Some("+15550003"),
            participant: None,
            play_dialtone: Some(true),
        })
        .unwrap();
        assert_eq!(
            body,
            json!({"callId": "c-1", "transferTo": "+15550003", "playDialtone": true})
        );
    }
}