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
//! Inbound and outbound SIP trunks.

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::common::MessageResponse;
use crate::error::Result;
use crate::pagination::{auto_page, paginate, ListParams, Page, PageFetcher};
use crate::query::QueryBuilder;
use crate::resources::escape;
use crate::resources::sip::{SipAuth, SipMediaEncryption, SipRegion, SipTransport};

const INBOUND_PATH: &str = "/v2/sip/inbound-gateways";
const OUTBOUND_PATH: &str = "/v2/sip/outbound-gateways";

/// An inbound or outbound SIP trunk.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SipTrunk {
    /// The trunk id.
    pub id: String,
    /// The trunk's display name.
    pub name: Option<String>,
    /// The SIP host, for outbound trunks.
    pub address: Option<String>,
    /// The E.164 numbers this trunk handles.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub numbers: Vec<String>,
    /// The allowed source IPs and CIDRs.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub allowed_addresses: Vec<String>,
    /// The allowed caller-number patterns.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub allowed_numbers: Vec<String>,
    /// Whether media is encrypted.
    pub media_encryption: Option<SipMediaEncryption>,
    /// The SIP transport.
    pub transport: Option<SipTransport>,
    /// Whether calls on this trunk are recorded.
    pub record: Option<bool>,
    /// Free-form tags.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub tags: Vec<String>,
    /// The SIP credentials.
    pub auth: Option<SipAuth>,
    /// The SIP region.
    pub geo_region: Option<SipRegion>,
    /// Free-form metadata.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub metadata: HashMap<String, String>,
    /// Whether noise cancellation is applied.
    pub noise_cancellation: Option<bool>,
    /// Whether DTMF is enabled.
    pub enable_dtmf: Option<bool>,
    /// Any fields the server returned that this SDK does not model yet.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// The parameters for [`InboundTrunkResource::create`].
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateInboundTrunkParams {
    /// The display name. Required.
    pub name: String,
    /// The E.164 numbers this trunk handles. Required, non-empty.
    pub numbers: Vec<String>,
    /// The SIP credentials.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth: Option<SipAuth>,
    /// The allowed source IPs and CIDRs.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allowed_addresses: Vec<String>,
    /// The allowed caller-number patterns, e.g. `+91*`.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allowed_numbers: Vec<String>,
    /// Whether to encrypt media.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_encryption: Option<SipMediaEncryption>,
    /// Whether to record calls on this trunk.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub record: Option<bool>,
    /// Whether to apply noise cancellation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub noise_cancellation: Option<bool>,
    /// Whether to enable DTMF.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_dtmf: Option<bool>,
    /// Free-form metadata.
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, String>,
    /// Free-form tags.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    /// The SIP region.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geo_region: Option<SipRegion>,
}

/// The parameters for [`InboundTrunkResource::update`].
///
/// Omitted fields keep their current value, **except** `record`,
/// `noise_cancellation` and `enable_dtmf`, which reset to `false` when omitted,
/// and `geo_region`, which is cleared. Send the complete desired state.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateInboundTrunkParams {
    /// The display name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The E.164 numbers this trunk handles.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub numbers: Vec<String>,
    /// The SIP credentials.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth: Option<SipAuth>,
    /// The allowed source IPs and CIDRs.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allowed_addresses: Vec<String>,
    /// The allowed caller-number patterns.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allowed_numbers: Vec<String>,
    /// Whether to encrypt media.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_encryption: Option<SipMediaEncryption>,
    /// Whether to record calls. Resets to `false` when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub record: Option<bool>,
    /// Whether to apply noise cancellation. Resets to `false` when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub noise_cancellation: Option<bool>,
    /// Whether to enable DTMF. Resets to `false` when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_dtmf: Option<bool>,
    /// Free-form metadata.
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, String>,
    /// Free-form tags.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    /// The SIP region. Cleared when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geo_region: Option<SipRegion>,
}

/// The parameters for [`OutboundTrunkResource::create`].
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateOutboundTrunkParams {
    /// The display name. Required.
    pub name: String,
    /// The SIP host, e.g. `sip.telnyx.com:5061`. Required.
    pub address: String,
    /// The E.164 numbers for this trunk. The server rejects an outbound trunk
    /// without numbers.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub numbers: Vec<String>,
    /// The SIP transport. Defaults to TLS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transport: Option<SipTransport>,
    /// The SIP credentials.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth: Option<SipAuth>,
    /// Whether to encrypt media.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_encryption: Option<SipMediaEncryption>,
    /// Whether to record calls on this trunk.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub record: Option<bool>,
    /// Whether to apply noise cancellation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub noise_cancellation: Option<bool>,
    /// Whether to enable DTMF.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_dtmf: Option<bool>,
    /// Free-form metadata.
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, String>,
    /// Free-form tags.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    /// The SIP region.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geo_region: Option<SipRegion>,
}

/// The parameters for [`OutboundTrunkResource::update`]. The same reset
/// semantics as [`UpdateInboundTrunkParams`] apply.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateOutboundTrunkParams {
    /// The display name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The E.164 numbers for this trunk.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub numbers: Vec<String>,
    /// The SIP host.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<String>,
    /// The SIP transport.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transport: Option<SipTransport>,
    /// The SIP credentials.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth: Option<SipAuth>,
    /// Whether to encrypt media.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_encryption: Option<SipMediaEncryption>,
    /// Whether to record calls. Resets to `false` when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub record: Option<bool>,
    /// Whether to apply noise cancellation. Resets to `false` when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub noise_cancellation: Option<bool>,
    /// Whether to enable DTMF. Resets to `false` when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_dtmf: Option<bool>,
    /// Free-form metadata.
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, String>,
    /// Free-form tags.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    /// The SIP region. Cleared when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geo_region: Option<SipRegion>,
    /// The allowed caller-number patterns. Outbound trunks accept this on update.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub allowed_numbers: Vec<String>,
}

/// The query parameters for listing trunks.
#[derive(Debug, Clone, Default)]
pub struct SipTrunkListParams {
    /// 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 trunk id.
    pub id: Option<String>,
    /// A case-insensitive search on the trunk's name.
    pub search: Option<String>,
}

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

fn trunk_fetcher(client: &Client, path: &'static str, params: &SipTrunkListParams) -> PageFetcher {
    let client = 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("id", params.id.as_deref())
                .opt_str("search", params.search.as_deref())
                .into_pairs();
            client
                .json::<Value>(Method::GET, path, CallOptions::new().query(query))
                .await
        })
    })
}

/// Inbound SIP trunks: connections that receive calls for a set of numbers.
/// Reached via [`SipTrunksResource::inbound`].
#[derive(Debug, Clone, Copy)]
pub struct InboundTrunkResource<'a> {
    client: &'a Client,
}

impl<'a> InboundTrunkResource<'a> {
    /// Creates an inbound trunk.
    pub async fn create(&self, params: CreateInboundTrunkParams) -> Result<SipTrunk> {
        self.client
            .json(Method::POST, INBOUND_PATH, CallOptions::json(&params)?)
            .await
    }

    /// Lists inbound trunks, one page at a time.
    pub async fn list(&self, params: SipTrunkListParams) -> Result<Page<SipTrunk>> {
        let fetcher = trunk_fetcher(self.client, INBOUND_PATH, &params);
        paginate(fetcher, &params.pagination(), "data", None).await
    }

    /// Lists inbound trunks, transparently fetching every page.
    pub fn list_stream(
        &self,
        params: SipTrunkListParams,
    ) -> impl Stream<Item = Result<SipTrunk>> + Send {
        let fetcher = trunk_fetcher(self.client, INBOUND_PATH, &params);
        auto_page(fetcher, params.pagination(), "data", None)
    }

    /// Fetches an inbound trunk by id.
    pub async fn get(&self, trunk_id: &str) -> Result<SipTrunk> {
        let path = format!("{INBOUND_PATH}/{}", escape(trunk_id));
        self.client
            .json(Method::GET, &path, CallOptions::new())
            .await
    }

    /// Partially updates an inbound trunk. See [`UpdateInboundTrunkParams`] for
    /// the fields that reset when omitted.
    pub async fn update(
        &self,
        trunk_id: &str,
        params: UpdateInboundTrunkParams,
    ) -> Result<SipTrunk> {
        let path = format!("{INBOUND_PATH}/{}", escape(trunk_id));
        self.client
            .json(Method::PATCH, &path, CallOptions::json(&params)?)
            .await
    }

    /// Deletes an inbound trunk.
    pub async fn delete(&self, trunk_id: &str) -> Result<MessageResponse> {
        let path = format!("{INBOUND_PATH}/{}", escape(trunk_id));
        self.client
            .json(Method::DELETE, &path, CallOptions::new())
            .await
    }
}

/// Outbound SIP trunks: connections used to place calls to a SIP host. Reached
/// via [`SipTrunksResource::outbound`].
#[derive(Debug, Clone, Copy)]
pub struct OutboundTrunkResource<'a> {
    client: &'a Client,
}

impl<'a> OutboundTrunkResource<'a> {
    /// Creates an outbound trunk.
    pub async fn create(&self, params: CreateOutboundTrunkParams) -> Result<SipTrunk> {
        self.client
            .json(Method::POST, OUTBOUND_PATH, CallOptions::json(&params)?)
            .await
    }

    /// Lists outbound trunks, one page at a time.
    pub async fn list(&self, params: SipTrunkListParams) -> Result<Page<SipTrunk>> {
        let fetcher = trunk_fetcher(self.client, OUTBOUND_PATH, &params);
        paginate(fetcher, &params.pagination(), "data", None).await
    }

    /// Lists outbound trunks, transparently fetching every page.
    pub fn list_stream(
        &self,
        params: SipTrunkListParams,
    ) -> impl Stream<Item = Result<SipTrunk>> + Send {
        let fetcher = trunk_fetcher(self.client, OUTBOUND_PATH, &params);
        auto_page(fetcher, params.pagination(), "data", None)
    }

    /// Fetches an outbound trunk by id.
    pub async fn get(&self, trunk_id: &str) -> Result<SipTrunk> {
        let path = format!("{OUTBOUND_PATH}/{}", escape(trunk_id));
        self.client
            .json(Method::GET, &path, CallOptions::new())
            .await
    }

    /// Partially updates an outbound trunk. The same reset semantics as the
    /// inbound update apply.
    pub async fn update(
        &self,
        trunk_id: &str,
        params: UpdateOutboundTrunkParams,
    ) -> Result<SipTrunk> {
        let path = format!("{OUTBOUND_PATH}/{}", escape(trunk_id));
        self.client
            .json(Method::PATCH, &path, CallOptions::json(&params)?)
            .await
    }

    /// Deletes an outbound trunk.
    pub async fn delete(&self, trunk_id: &str) -> Result<MessageResponse> {
        let path = format!("{OUTBOUND_PATH}/{}", escape(trunk_id));
        self.client
            .json(Method::DELETE, &path, CallOptions::new())
            .await
    }
}

/// Groups the inbound and outbound trunk sub-resources. Reached via
/// [`SipResource::trunks`](crate::SipResource::trunks).
#[derive(Debug, Clone, Copy)]
pub struct SipTrunksResource<'a> {
    client: &'a Client,
}

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

    /// Inbound trunks: connections that receive calls for a set of numbers.
    pub fn inbound(&self) -> InboundTrunkResource<'a> {
        InboundTrunkResource {
            client: self.client,
        }
    }

    /// Outbound trunks: connections used to place calls to a SIP host.
    pub fn outbound(&self) -> OutboundTrunkResource<'a> {
        OutboundTrunkResource {
            client: self.client,
        }
    }
}