asterisk-rs-ari 0.2.0

Async Rust client for the Asterisk REST Interface (ARI)
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
//! Typed ARI events deserialized from WebSocket JSON.

use serde::{Deserialize, Serialize};

/// all known ARI event types
///
/// uses serde's internally tagged representation keyed on the `type` field.
/// unknown event types deserialize to the `Unknown` variant instead of failing.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type")]
pub enum AriEvent {
    StasisStart {
        channel: Channel,
        #[serde(default)]
        args: Vec<String>,
        #[serde(default)]
        replace_channel: Option<Channel>,
    },
    StasisEnd {
        channel: Channel,
    },
    ChannelCreated {
        channel: Channel,
    },
    ChannelDestroyed {
        channel: Channel,
        cause: i32,
        cause_txt: String,
    },
    ChannelStateChange {
        channel: Channel,
    },
    ChannelDtmfReceived {
        channel: Channel,
        digit: String,
        duration_ms: u32,
    },
    ChannelHangupRequest {
        channel: Channel,
    },
    ChannelVarset {
        channel: Option<Channel>,
        variable: String,
        value: String,
    },
    BridgeCreated {
        bridge: Bridge,
    },
    BridgeDestroyed {
        bridge: Bridge,
    },
    ChannelEnteredBridge {
        bridge: Bridge,
        channel: Channel,
    },
    ChannelLeftBridge {
        bridge: Bridge,
        channel: Channel,
    },
    PlaybackStarted {
        playback: Playback,
    },
    PlaybackFinished {
        playback: Playback,
    },
    RecordingStarted {
        recording: LiveRecording,
    },
    RecordingFinished {
        recording: LiveRecording,
    },
    /// channel caller id changed
    ChannelCallerId {
        channel: Channel,
        caller_presentation: i32,
        caller_presentation_txt: String,
    },
    /// channel connected line changed
    ChannelConnectedLine {
        channel: Channel,
    },
    /// channel dialplan location changed
    ChannelDialplan {
        channel: Channel,
        dialplan_app: String,
        dialplan_app_data: String,
    },
    /// channel placed on hold
    ChannelHold {
        channel: Channel,
        #[serde(default)]
        musicclass: Option<String>,
    },
    /// channel removed from hold
    ChannelUnhold {
        channel: Channel,
    },
    /// channel talking started
    ChannelTalkingStarted {
        channel: Channel,
    },
    /// channel talking finished
    ChannelTalkingFinished {
        channel: Channel,
        duration: i32,
    },
    /// tone detected on channel
    ChannelToneDetected {
        channel: Channel,
    },
    /// channel transfer via REFER
    ChannelTransfer {
        channel: Channel,
        #[serde(default)]
        refer_to: Option<Box<ReferTo>>,
        #[serde(default)]
        referred_by: Option<Box<ReferredBy>>,
        #[serde(default)]
        state: Option<String>,
    },
    /// user-defined event from the dialplan
    ChannelUserevent {
        #[serde(default)]
        channel: Option<Channel>,
        #[serde(default)]
        bridge: Option<Bridge>,
        #[serde(default)]
        endpoint: Option<Endpoint>,
        eventname: String,
        #[serde(default)]
        userevent: serde_json::Value,
    },
    /// dial event with caller and peer channels
    Dial {
        peer: Channel,
        #[serde(default)]
        caller: Option<Channel>,
        #[serde(default)]
        forwarded: Option<Channel>,
        dialstatus: String,
        #[serde(default)]
        dialstring: Option<String>,
        #[serde(default)]
        forward: Option<String>,
    },
    /// bridge attended transfer completed
    BridgeAttendedTransfer {
        transferer_first_leg: Channel,
        transferer_second_leg: Channel,
        result: String,
        destination_type: String,
        is_external: bool,
        #[serde(default)]
        transferee: Option<Box<Channel>>,
        #[serde(default)]
        transfer_target: Option<Box<Channel>>,
        #[serde(default)]
        replace_channel: Option<Box<Channel>>,
        #[serde(default)]
        transferer_first_leg_bridge: Option<Bridge>,
        #[serde(default)]
        transferer_second_leg_bridge: Option<Bridge>,
        #[serde(default)]
        destination_bridge: Option<String>,
        #[serde(default)]
        destination_application: Option<String>,
        #[serde(default)]
        destination_link_first_leg: Option<Box<Channel>>,
        #[serde(default)]
        destination_link_second_leg: Option<Box<Channel>>,
        #[serde(default)]
        destination_threeway_channel: Option<Box<Channel>>,
        #[serde(default)]
        destination_threeway_bridge: Option<Bridge>,
    },
    /// bridge blind transfer completed
    BridgeBlindTransfer {
        channel: Channel,
        exten: String,
        context: String,
        result: String,
        is_external: bool,
        #[serde(default)]
        bridge: Option<Bridge>,
        #[serde(default)]
        transferee: Option<Channel>,
        #[serde(default)]
        replace_channel: Option<Channel>,
    },
    /// two bridges merged
    BridgeMerged {
        bridge: Bridge,
        bridge_from: Bridge,
    },
    /// bridge video source changed
    BridgeVideoSourceChanged {
        bridge: Bridge,
        #[serde(default)]
        old_video_source_id: Option<String>,
    },
    /// contact status changed
    ContactStatusChange {
        contact_info: ContactInfo,
        endpoint: Endpoint,
    },
    /// device state changed
    DeviceStateChanged {
        device_state: DeviceState,
    },
    /// endpoint state changed
    EndpointStateChange {
        endpoint: Endpoint,
    },
    /// peer status changed
    PeerStatusChange {
        endpoint: Endpoint,
        peer: Peer,
    },
    /// playback continuing to next media uri
    PlaybackContinuing {
        playback: Playback,
    },
    /// recording failed
    RecordingFailed {
        recording: LiveRecording,
    },
    /// application move failed
    ApplicationMoveFailed {
        channel: Channel,
        destination: String,
        #[serde(default)]
        args: Vec<String>,
    },
    /// application registered
    ApplicationRegistered {},
    /// application replaced by another websocket connection
    ApplicationReplaced {},
    /// application unregistered
    ApplicationUnregistered {},
    /// text message received
    TextMessageReceived {
        message: TextMessage,
        #[serde(default)]
        endpoint: Option<Endpoint>,
    },
    /// REST API response over websocket
    RESTResponse {
        status_code: i32,
        reason_phrase: String,
        uri: String,
        request_id: String,
        transaction_id: String,
        #[serde(default)]
        content_type: Option<String>,
        #[serde(default)]
        message_body: Option<String>,
    },
    /// catch-all for event types not yet modeled
    #[serde(other)]
    Unknown,
}

impl asterisk_rs_core::event::Event for AriEvent {}

/// contact info for PJSIP registration status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContactInfo {
    pub uri: String,
    pub contact_status: String,
    pub aor: String,
    #[serde(default)]
    pub roundtrip_usec: Option<String>,
}

/// peer status information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Peer {
    pub peer_status: String,
    #[serde(default)]
    pub address: Option<String>,
    #[serde(default)]
    pub port: Option<String>,
    #[serde(default)]
    pub cause: Option<String>,
    #[serde(default)]
    pub time: Option<String>,
}

/// endpoint state information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Endpoint {
    pub technology: String,
    pub resource: String,
    #[serde(default)]
    pub state: Option<String>,
    #[serde(default)]
    pub channel_ids: Vec<String>,
}

/// device state information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceState {
    pub name: String,
    pub state: String,
}

/// text message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextMessage {
    pub from: String,
    pub to: String,
    pub body: String,
}

/// refer-to information for channel transfers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReferTo {
    #[serde(default)]
    pub destination_channel: Option<Channel>,
    #[serde(default)]
    pub connected_channel: Option<Channel>,
    #[serde(default)]
    pub bridge: Option<Bridge>,
}

/// referred-by information for channel transfers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReferredBy {
    pub source_channel: Channel,
    #[serde(default)]
    pub connected_channel: Option<Channel>,
    #[serde(default)]
    pub bridge: Option<Bridge>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Channel {
    pub id: String,
    pub name: String,
    pub state: String,
    #[serde(default)]
    pub caller: CallerId,
    #[serde(default)]
    pub connected: CallerId,
    #[serde(default)]
    pub dialplan: DialplanCep,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CallerId {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub number: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DialplanCep {
    #[serde(default)]
    pub context: String,
    #[serde(default)]
    pub exten: String,
    #[serde(default)]
    pub priority: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bridge {
    pub id: String,
    pub technology: String,
    pub bridge_type: String,
    #[serde(default)]
    pub channels: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Playback {
    pub id: String,
    pub media_uri: String,
    pub state: String,
    #[serde(default)]
    pub target_uri: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiveRecording {
    pub name: String,
    pub format: String,
    pub state: String,
    #[serde(default)]
    pub target_uri: String,
}

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

    #[test]
    fn deserialize_stasis_start() {
        let json = r#"{
            "type": "StasisStart",
            "channel": {
                "id": "1234.5",
                "name": "PJSIP/alice-00000001",
                "state": "Ring",
                "caller": { "name": "Alice", "number": "1001" },
                "connected": { "name": "", "number": "" },
                "dialplan": { "context": "default", "exten": "100", "priority": 1 }
            },
            "args": ["arg1", "arg2"]
        }"#;

        let event: AriEvent = serde_json::from_str(json).expect("stasis start should deserialize");

        match event {
            AriEvent::StasisStart {
                channel,
                args,
                replace_channel,
            } => {
                assert_eq!(channel.id, "1234.5");
                assert_eq!(channel.name, "PJSIP/alice-00000001");
                assert_eq!(channel.state, "Ring");
                assert_eq!(channel.caller.name, "Alice");
                assert_eq!(channel.caller.number, "1001");
                assert_eq!(args, vec!["arg1", "arg2"]);
                assert!(replace_channel.is_none());
            }
            other => panic!("expected StasisStart, got {other:?}"),
        }
    }

    #[test]
    fn deserialize_channel_dtmf_received() {
        let json = r#"{
            "type": "ChannelDtmfReceived",
            "channel": {
                "id": "chan-1",
                "name": "PJSIP/bob-00000002",
                "state": "Up"
            },
            "digit": "5",
            "duration_ms": 120
        }"#;

        let event: AriEvent = serde_json::from_str(json).expect("dtmf received should deserialize");

        match event {
            AriEvent::ChannelDtmfReceived {
                channel,
                digit,
                duration_ms,
            } => {
                assert_eq!(channel.id, "chan-1");
                assert_eq!(digit, "5");
                assert_eq!(duration_ms, 120);
            }
            other => panic!("expected ChannelDtmfReceived, got {other:?}"),
        }
    }

    #[test]
    fn deserialize_unknown_event() {
        let json = r#"{
            "type": "SomeNewEventType",
            "data": "whatever"
        }"#;

        let event: AriEvent = serde_json::from_str(json)
            .expect("unknown event types should not fail deserialization");

        assert!(matches!(event, AriEvent::Unknown));
    }

    #[test]
    fn deserialize_stasis_start_minimal() {
        // no optional fields provided
        let json = r#"{
            "type": "StasisStart",
            "channel": {
                "id": "abc",
                "name": "SIP/trunk-00000001",
                "state": "Ring"
            }
        }"#;

        let event: AriEvent =
            serde_json::from_str(json).expect("minimal stasis start should deserialize");

        match event {
            AriEvent::StasisStart {
                channel,
                args,
                replace_channel,
            } => {
                assert_eq!(channel.id, "abc");
                assert!(args.is_empty());
                assert!(replace_channel.is_none());
            }
            other => panic!("expected StasisStart, got {other:?}"),
        }
    }

    #[test]
    fn deserialize_dial_event() {
        let json = r#"{
            "type": "Dial",
            "peer": {
                "id": "peer-1",
                "name": "PJSIP/200-00000002",
                "state": "Ring"
            },
            "caller": {
                "id": "caller-1",
                "name": "PJSIP/100-00000001",
                "state": "Up"
            },
            "dialstatus": "RINGING",
            "dialstring": "200"
        }"#;
        let event: AriEvent = serde_json::from_str(json).expect("dial should deserialize");
        match event {
            AriEvent::Dial {
                peer,
                caller,
                dialstatus,
                ..
            } => {
                assert_eq!(peer.id, "peer-1");
                assert!(caller.is_some());
                assert_eq!(dialstatus, "RINGING");
            }
            other => panic!("expected Dial, got {other:?}"),
        }
    }

    #[test]
    fn deserialize_channel_hold_event() {
        let json = r#"{
            "type": "ChannelHold",
            "channel": {
                "id": "hold-1",
                "name": "PJSIP/100-00000001",
                "state": "Up"
            },
            "musicclass": "default"
        }"#;
        let event: AriEvent = serde_json::from_str(json).expect("hold should deserialize");
        match event {
            AriEvent::ChannelHold {
                channel,
                musicclass,
            } => {
                assert_eq!(channel.id, "hold-1");
                assert_eq!(musicclass.as_deref(), Some("default"));
            }
            other => panic!("expected ChannelHold, got {other:?}"),
        }
    }

    #[test]
    fn deserialize_bridge_blind_transfer() {
        let json = r#"{
            "type": "BridgeBlindTransfer",
            "channel": {
                "id": "xfer-1",
                "name": "PJSIP/100-00000001",
                "state": "Up"
            },
            "exten": "200",
            "context": "default",
            "result": "Success",
            "is_external": false
        }"#;
        let event: AriEvent =
            serde_json::from_str(json).expect("blind transfer should deserialize");
        match event {
            AriEvent::BridgeBlindTransfer {
                channel,
                exten,
                context,
                result,
                is_external,
                ..
            } => {
                assert_eq!(channel.id, "xfer-1");
                assert_eq!(exten, "200");
                assert_eq!(context, "default");
                assert_eq!(result, "Success");
                assert!(!is_external);
            }
            other => panic!("expected BridgeBlindTransfer, got {other:?}"),
        }
    }

    #[test]
    fn deserialize_peer_status_change() {
        let json = r#"{
            "type": "PeerStatusChange",
            "endpoint": {
                "technology": "PJSIP",
                "resource": "100",
                "state": "online"
            },
            "peer": {
                "peer_status": "Reachable",
                "address": "192.168.1.100",
                "port": "5060"
            }
        }"#;
        let event: AriEvent = serde_json::from_str(json).expect("peer status should deserialize");
        match event {
            AriEvent::PeerStatusChange { endpoint, peer } => {
                assert_eq!(endpoint.resource, "100");
                assert_eq!(peer.peer_status, "Reachable");
            }
            other => panic!("expected PeerStatusChange, got {other:?}"),
        }
    }

    #[test]
    fn deserialize_contact_status_change() {
        let json = r#"{
            "type": "ContactStatusChange",
            "contact_info": {
                "uri": "sip:100@192.168.1.100:5060",
                "contact_status": "Reachable",
                "aor": "100"
            },
            "endpoint": {
                "technology": "PJSIP",
                "resource": "100"
            }
        }"#;
        let event: AriEvent =
            serde_json::from_str(json).expect("contact status should deserialize");
        match event {
            AriEvent::ContactStatusChange {
                contact_info,
                endpoint,
            } => {
                assert_eq!(contact_info.aor, "100");
                assert_eq!(endpoint.resource, "100");
            }
            other => panic!("expected ContactStatusChange, got {other:?}"),
        }
    }

    #[test]
    fn deserialize_device_state_changed() {
        let json = r#"{
            "type": "DeviceStateChanged",
            "device_state": {
                "name": "PJSIP/100",
                "state": "INUSE"
            }
        }"#;
        let event: AriEvent = serde_json::from_str(json).expect("device state should deserialize");
        match event {
            AriEvent::DeviceStateChanged { device_state } => {
                assert_eq!(device_state.name, "PJSIP/100");
                assert_eq!(device_state.state, "INUSE");
            }
            other => panic!("expected DeviceStateChanged, got {other:?}"),
        }
    }

    #[test]
    fn deserialize_playback_continuing() {
        let json = r#"{
            "type": "PlaybackContinuing",
            "playback": {
                "id": "pb-1",
                "media_uri": "sound:hello-world",
                "state": "playing",
                "target_uri": "channel:abc"
            }
        }"#;
        let event: AriEvent =
            serde_json::from_str(json).expect("playback continuing should deserialize");
        assert!(matches!(event, AriEvent::PlaybackContinuing { .. }));
    }

    #[test]
    fn deserialize_recording_failed() {
        let json = r#"{
            "type": "RecordingFailed",
            "recording": {
                "name": "rec-1",
                "format": "wav",
                "state": "failed",
                "target_uri": "channel:abc"
            }
        }"#;
        let event: AriEvent =
            serde_json::from_str(json).expect("recording failed should deserialize");
        assert!(matches!(event, AriEvent::RecordingFailed { .. }));
    }
}