livekit-api 0.4.19

Rust Server SDK for LiveKit
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
// Copyright 2025 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use livekit_protocol as proto;
use std::collections::HashMap;
use std::time::Duration;

use crate::access_token::SIPGrants;
use crate::get_env_keys;
use crate::services::twirp_client::TwirpClient;
use crate::services::{ServiceBase, ServiceResult, LIVEKIT_PACKAGE};
use pbjson_types::Duration as ProtoDuration;

const SVC: &str = "SIP";

#[derive(Debug)]
pub struct SIPClient {
    base: ServiceBase,
    client: TwirpClient,
}

#[deprecated]
#[derive(Default, Clone, Debug)]
pub struct CreateSIPTrunkOptions {
    /// Human-readable name for the Trunk.
    pub name: String,
    /// Optional free-form metadata.
    pub metadata: String,
    /// CIDR or IPs that traffic is accepted from
    /// An empty list means all inbound traffic is accepted.
    pub inbound_addresses: Vec<String>,
    /// Accepted `To` values. This Trunk will only accept a call made to
    /// these numbers. This allows you to have distinct Trunks for different phone
    /// numbers at the same provider.
    pub inbound_numbers: Vec<String>,
    /// Username and password used to authenticate inbound SIP invites
    /// May be empty to have no Authentication
    pub inbound_username: String,
    pub inbound_password: String,

    /// IP that SIP INVITE is sent too
    pub outbound_address: String,
    /// Username and password used to authenticate outbound SIP invites
    /// May be empty to have no Authentication
    pub outbound_username: String,
    pub outbound_password: String,
}

#[derive(Default, Clone, Debug)]
pub struct CreateSIPInboundTrunkOptions {
    /// Optional free-form metadata.
    pub metadata: Option<String>,
    /// CIDR or IPs that traffic is accepted from
    /// An empty list means all inbound traffic is accepted.
    pub allowed_addresses: Option<Vec<String>>,
    /// Accepted `To` values. This Trunk will only accept a call made to
    /// these numbers. This allows you to have distinct Trunks for different phone
    /// numbers at the same provider.
    pub allowed_numbers: Option<Vec<String>>,
    /// Username and password used to authenticate inbound SIP invites
    /// May be empty to have no Authentication
    pub auth_username: Option<String>,
    pub auth_password: Option<String>,
    pub headers: Option<HashMap<String, String>>,
    pub headers_to_attributes: Option<HashMap<String, String>>,
    pub attributes_to_headers: Option<HashMap<String, String>>,
    pub max_call_duration: Option<Duration>,
    pub ringing_timeout: Option<Duration>,
    pub krisp_enabled: Option<bool>,
}

#[derive(Default, Clone, Debug)]
pub struct CreateSIPOutboundTrunkOptions {
    pub transport: proto::SipTransport,
    /// Optional free-form metadata.
    pub metadata: String,
    /// Username and password used to authenticate outbound SIP invites
    /// May be empty to have no Authentication
    pub auth_username: String,
    pub auth_password: String,

    pub headers: Option<HashMap<String, String>>,
    pub headers_to_attributes: Option<HashMap<String, String>>,
    pub attributes_to_headers: Option<HashMap<String, String>>,
}

#[deprecated]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ListSIPTrunkFilter {
    All,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ListSIPInboundTrunkFilter {
    All,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ListSIPOutboundTrunkFilter {
    All,
}

#[derive(Default, Clone, Debug)]
pub struct CreateSIPDispatchRuleOptions {
    pub name: String,
    pub metadata: String,
    pub attributes: HashMap<String, String>,
    /// What trunks are accepted for this dispatch rule
    /// If empty all trunks will match this dispatch rule
    pub trunk_ids: Vec<String>,
    pub allowed_numbers: Vec<String>,
    pub hide_phone_number: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ListSIPDispatchRuleFilter {
    All,
}

#[derive(Default, Clone, Debug)]
pub struct CreateSIPParticipantOptions {
    /// Optional identity of the participant in LiveKit room
    pub participant_identity: String,
    /// Optionally set the name of the participant in a LiveKit room
    pub participant_name: Option<String>,
    /// Optionally set the free-form metadata of the participant in a LiveKit room
    pub participant_metadata: Option<String>,
    pub participant_attributes: Option<HashMap<String, String>>,
    // What number should be dialed via SIP
    pub sip_number: Option<String>,
    /// Optionally send following DTMF digits (extension codes) when making a call.
    /// Character 'w' can be used to add a 0.5 sec delay.
    pub dtmf: Option<String>,
    /// Wait for the call to be answered before returning.
    ///
    /// When `true`, the request blocks until the call is answered or fails,
    /// and returns SIP error codes (e.g., 486 Busy, 603 Decline) on failure.
    /// When `false` (default), returns immediately while the call is still dialing.
    pub wait_until_answered: Option<bool>,
    /// Optionally play dialtone in the room as an audible indicator for existing participants
    pub play_dialtone: Option<bool>,
    pub hide_phone_number: Option<bool>,
    pub ringing_timeout: Option<Duration>,
    pub max_call_duration: Option<Duration>,
    pub enable_krisp: Option<bool>,
}

impl SIPClient {
    pub fn with_api_key(host: &str, api_key: &str, api_secret: &str) -> Self {
        Self {
            base: ServiceBase::with_api_key(api_key, api_secret),
            client: TwirpClient::new(host, LIVEKIT_PACKAGE, None),
        }
    }

    pub fn new(host: &str) -> ServiceResult<Self> {
        let (api_key, api_secret) = get_env_keys()?;
        Ok(Self::with_api_key(host, &api_key, &api_secret))
    }

    fn duration_to_proto(d: Option<Duration>) -> Option<ProtoDuration> {
        d.map(|d| ProtoDuration { seconds: d.as_secs() as i64, nanos: d.subsec_nanos() as i32 })
    }

    pub async fn create_sip_inbound_trunk(
        &self,
        name: String,
        numbers: Vec<String>,
        options: CreateSIPInboundTrunkOptions,
    ) -> ServiceResult<proto::SipInboundTrunkInfo> {
        self.client
            .request(
                SVC,
                "CreateSIPInboundTrunk",
                proto::CreateSipInboundTrunkRequest {
                    trunk: Some(proto::SipInboundTrunkInfo {
                        sip_trunk_id: Default::default(),
                        name,
                        numbers,
                        metadata: options.metadata.unwrap_or_default(),
                        allowed_numbers: options.allowed_numbers.unwrap_or_default(),
                        allowed_addresses: options.allowed_addresses.unwrap_or_default(),
                        auth_username: options.auth_username.unwrap_or_default(),
                        auth_password: options.auth_password.unwrap_or_default(),
                        headers: options.headers.unwrap_or_default(),
                        headers_to_attributes: options.headers_to_attributes.unwrap_or_default(),
                        attributes_to_headers: options.attributes_to_headers.unwrap_or_default(),
                        krisp_enabled: options.krisp_enabled.unwrap_or(false),
                        max_call_duration: Self::duration_to_proto(options.max_call_duration),
                        ringing_timeout: Self::duration_to_proto(options.ringing_timeout),

                        // TODO: support these attributes
                        include_headers: Default::default(),
                        media_encryption: Default::default(),
                        created_at: Default::default(),
                        updated_at: Default::default(),
                    }),
                },
                self.base.auth_header(
                    Default::default(),
                    Some(SIPGrants { admin: true, ..Default::default() }),
                )?,
            )
            .await
            .map_err(Into::into)
    }

    pub async fn create_sip_outbound_trunk(
        &self,
        name: String,
        address: String,
        numbers: Vec<String>,
        options: CreateSIPOutboundTrunkOptions,
    ) -> ServiceResult<proto::SipOutboundTrunkInfo> {
        self.client
            .request(
                SVC,
                "CreateSIPOutboundTrunk",
                proto::CreateSipOutboundTrunkRequest {
                    trunk: Some(proto::SipOutboundTrunkInfo {
                        sip_trunk_id: Default::default(),
                        name,
                        address,
                        numbers,
                        transport: options.transport as i32,
                        metadata: options.metadata,

                        auth_username: options.auth_username.to_owned(),
                        auth_password: options.auth_password.to_owned(),

                        headers: options.headers.unwrap_or_default(),
                        headers_to_attributes: options.headers_to_attributes.unwrap_or_default(),
                        attributes_to_headers: options.attributes_to_headers.unwrap_or_default(),

                        // TODO: support these attributes
                        include_headers: Default::default(),
                        media_encryption: Default::default(),
                        destination_country: Default::default(),
                        created_at: Default::default(),
                        updated_at: Default::default(),
                        from_host: Default::default(),
                    }),
                },
                self.base.auth_header(
                    Default::default(),
                    Some(SIPGrants { admin: true, ..Default::default() }),
                )?,
            )
            .await
            .map_err(Into::into)
    }

    #[deprecated]
    pub async fn list_sip_trunk(
        &self,
        filter: ListSIPTrunkFilter,
    ) -> ServiceResult<Vec<proto::SipTrunkInfo>> {
        let resp: proto::ListSipTrunkResponse = self
            .client
            .request(
                SVC,
                "ListSIPTrunk",
                proto::ListSipTrunkRequest {
                    // TODO support these attributes
                    page: Default::default(),
                },
                self.base.auth_header(
                    Default::default(),
                    Some(SIPGrants { admin: true, ..Default::default() }),
                )?,
            )
            .await?;

        Ok(resp.items)
    }

    pub async fn list_sip_inbound_trunk(
        &self,
        filter: ListSIPInboundTrunkFilter,
    ) -> ServiceResult<Vec<proto::SipInboundTrunkInfo>> {
        let resp: proto::ListSipInboundTrunkResponse = self
            .client
            .request(
                SVC,
                "ListSIPInboundTrunk",
                proto::ListSipInboundTrunkRequest {
                    // TODO: support these attributes
                    page: Default::default(),
                    trunk_ids: Default::default(),
                    numbers: Default::default(),
                },
                self.base.auth_header(
                    Default::default(),
                    Some(SIPGrants { admin: true, ..Default::default() }),
                )?,
            )
            .await?;

        Ok(resp.items)
    }

    pub async fn list_sip_outbound_trunk(
        &self,
        filter: ListSIPOutboundTrunkFilter,
    ) -> ServiceResult<Vec<proto::SipOutboundTrunkInfo>> {
        let resp: proto::ListSipOutboundTrunkResponse = self
            .client
            .request(
                SVC,
                "ListSIPOutboundTrunk",
                proto::ListSipOutboundTrunkRequest {
                    // TODO: support these attributes
                    page: Default::default(),
                    trunk_ids: Default::default(),
                    numbers: Default::default(),
                },
                self.base.auth_header(
                    Default::default(),
                    Some(SIPGrants { admin: true, ..Default::default() }),
                )?,
            )
            .await?;

        Ok(resp.items)
    }

    pub async fn delete_sip_trunk(&self, sip_trunk_id: &str) -> ServiceResult<proto::SipTrunkInfo> {
        self.client
            .request(
                SVC,
                "DeleteSIPTrunk",
                proto::DeleteSipTrunkRequest { sip_trunk_id: sip_trunk_id.to_owned() },
                self.base.auth_header(
                    Default::default(),
                    Some(SIPGrants { admin: true, ..Default::default() }),
                )?,
            )
            .await
            .map_err(Into::into)
    }

    pub async fn create_sip_dispatch_rule(
        &self,
        rule: proto::sip_dispatch_rule::Rule,
        options: CreateSIPDispatchRuleOptions,
    ) -> ServiceResult<proto::SipDispatchRuleInfo> {
        self.client
            .request(
                SVC,
                "CreateSIPDispatchRule",
                proto::CreateSipDispatchRuleRequest {
                    name: options.name,
                    metadata: options.metadata,
                    attributes: options.attributes,
                    trunk_ids: options.trunk_ids.to_owned(),
                    inbound_numbers: options.allowed_numbers.to_owned(),
                    hide_phone_number: options.hide_phone_number,
                    rule: Some(proto::SipDispatchRule { rule: Some(rule.to_owned()) }),

                    ..Default::default()
                },
                self.base.auth_header(
                    Default::default(),
                    Some(SIPGrants { admin: true, ..Default::default() }),
                )?,
            )
            .await
            .map_err(Into::into)
    }

    pub async fn list_sip_dispatch_rule(
        &self,
        filter: ListSIPDispatchRuleFilter,
    ) -> ServiceResult<Vec<proto::SipDispatchRuleInfo>> {
        let resp: proto::ListSipDispatchRuleResponse = self
            .client
            .request(
                SVC,
                "ListSIPDispatchRule",
                proto::ListSipDispatchRuleRequest {
                    // TODO: support these attributes
                    page: Default::default(),
                    dispatch_rule_ids: Default::default(),
                    trunk_ids: Default::default(),
                },
                self.base.auth_header(
                    Default::default(),
                    Some(SIPGrants { admin: true, ..Default::default() }),
                )?,
            )
            .await?;

        Ok(resp.items)
    }

    pub async fn delete_sip_dispatch_rule(
        &self,
        sip_dispatch_rule_id: &str,
    ) -> ServiceResult<proto::SipDispatchRuleInfo> {
        self.client
            .request(
                SVC,
                "DeleteSIPDispatchRule",
                proto::DeleteSipDispatchRuleRequest {
                    sip_dispatch_rule_id: sip_dispatch_rule_id.to_owned(),
                },
                self.base.auth_header(
                    Default::default(),
                    Some(SIPGrants { admin: true, ..Default::default() }),
                )?,
            )
            .await
            .map_err(Into::into)
    }

    pub async fn create_sip_participant(
        &self,
        sip_trunk_id: String,
        call_to: String,
        room_name: String,
        options: CreateSIPParticipantOptions,
        outbound_trunk_config: Option<proto::SipOutboundConfig>,
    ) -> ServiceResult<proto::SipParticipantInfo> {
        self.client
            .request(
                SVC,
                "CreateSIPParticipant",
                proto::CreateSipParticipantRequest {
                    sip_trunk_id: sip_trunk_id.to_owned(),
                    trunk: outbound_trunk_config,
                    sip_call_to: call_to.to_owned(),
                    sip_number: options.sip_number.to_owned().unwrap_or_default(),
                    room_name: room_name.to_owned(),
                    participant_identity: options.participant_identity.to_owned(),
                    participant_name: options.participant_name.to_owned().unwrap_or_default(),
                    participant_metadata: options
                        .participant_metadata
                        .to_owned()
                        .unwrap_or_default(),
                    participant_attributes: options
                        .participant_attributes
                        .to_owned()
                        .unwrap_or_default(),
                    dtmf: options.dtmf.to_owned().unwrap_or_default(),
                    wait_until_answered: options.wait_until_answered.unwrap_or(false),
                    play_ringtone: options.play_dialtone.unwrap_or(false),
                    play_dialtone: options.play_dialtone.unwrap_or(false),
                    hide_phone_number: options.hide_phone_number.unwrap_or(false),
                    max_call_duration: Self::duration_to_proto(options.max_call_duration),
                    ringing_timeout: Self::duration_to_proto(options.ringing_timeout),

                    // TODO: rename local proto as well
                    krisp_enabled: options.enable_krisp.unwrap_or(false),

                    // TODO: support these attributes
                    headers: Default::default(),
                    include_headers: Default::default(),
                    media_encryption: Default::default(),
                    ..Default::default()
                },
                self.base.auth_header(
                    Default::default(),
                    Some(SIPGrants { call: true, ..Default::default() }),
                )?,
            )
            .await
            .map_err(Into::into)
    }
}