rustpbx 0.4.6

A SIP PBX implementation in Rust
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
//! Unified CallCommand - the single command type for session control
//!
//! This enum represents all possible commands that can be sent to a session.
//! It serves as the unified interface between:
//! - RWI (Realtime WebSocket Interface)
//! - Console/HTTP API
//! - Internal event handling
//!
//! ## Design Notes
//!
//! 1. Commands are protocol-agnostic - adapters translate from external protocols
//! 2. Each command has explicit leg targeting via `LegId`
//! 3. Media commands include capability-aware options

use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;

use super::{HangupCommand, LegId, MediaSource, RingbackPolicy};

/// Type alias for CallCommand sender.
pub type CallCommandTx = mpsc::Sender<CallCommand>;
/// Type alias for CallCommand receiver.
pub type CallCommandRx = mpsc::Receiver<CallCommand>;

/// Unified command for session control
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum CallCommand {
    // ============================================================================
    // Basic Call Control
    // ============================================================================
    /// Answer an incoming call leg
    Answer {
        /// The leg to answer
        leg_id: LegId,
    },

    /// Reject an incoming call leg
    Reject {
        /// The leg to reject
        leg_id: LegId,
        /// Optional rejection reason
        reason: Option<String>,
    },

    /// Start ringing indication (send 180 Ringing)
    Ring {
        /// The leg to ring
        leg_id: LegId,
        /// Ringback policy (how to handle ringback tone)
        ringback: Option<RingbackPolicy>,
    },

    /// Hangup the session or a specific leg
    Hangup(HangupCommand),

    /// Bridge two legs together
    Bridge {
        /// First leg (A-leg)
        leg_a: LegId,
        /// Second leg (B-leg)
        leg_b: LegId,
        /// Bridge mode
        mode: P2PMode,
    },

    /// Remove a leg from its bridge
    Unbridge {
        /// The leg to unbridge
        leg_id: LegId,
    },

    /// Bridge two legs from different sessions (cross-session P2P).
    /// Used when downgrading from a conference to P2P after transfer completion.
    BridgeCrossSession {
        /// First session ID
        session_a: String,
        /// First leg ID within session_a
        leg_a: LegId,
        /// Second session ID
        session_b: String,
        /// Second leg ID within session_b
        leg_b: LegId,
    },

    /// Transfer a leg to a target (blind transfer)
    Transfer {
        /// The leg to transfer
        leg_id: LegId,
        /// Transfer target (SIP URI or endpoint)
        target: String,
        /// Whether this is an attended transfer
        attended: bool,
    },

    /// Complete an attended transfer
    TransferComplete {
        /// The consultation leg
        consult_leg: LegId,
    },

    /// Cancel an attended transfer
    TransferCancel {
        /// The consultation leg to hangup
        consult_leg: LegId,
    },

    /// Complete a cross-session attended transfer by migrating a leg into a conference.
    /// This is used in the BC -> ABC conference flow where leg_c from session2
    /// needs to be migrated into a conference that also includes legs from session1.
    TransferCompleteCrossSession {
        /// The session ID containing the leg to migrate
        from_session: String,
        /// The leg ID within from_session to migrate
        leg_id: LegId,
        /// The target conference ID to migrate the leg into
        into_conference: String,
    },

    /// Place a leg on hold
    Hold {
        /// The leg to hold
        leg_id: LegId,
        /// Optional music source to play while on hold
        music: Option<MediaSource>,
    },

    /// Release a leg from hold
    Unhold {
        /// The leg to unhold
        leg_id: LegId,
    },

    /// Play audio to a leg or all legs
    Play {
        /// Target leg (None = all legs)
        leg_id: Option<LegId>,
        /// Audio source
        source: MediaSource,
        /// Playback options
        options: Option<PlayOptions>,
    },

    /// Stop audio playback
    StopPlayback {
        /// Target leg (None = all legs)
        leg_id: Option<LegId>,
    },

    /// Send DTMF digits
    SendDtmf {
        /// Target leg
        leg_id: LegId,
        /// DTMF digits to send
        digits: String,
    },

    /// Collect DTMF digits from a leg and fire a dtmf_collected / dtmf_collect_timeout event.
    DtmfCollect {
        /// Target leg to collect from (None = caller)
        leg_id: Option<LegId>,
        /// Minimum digits required before a timeout fires a collected event
        min_digits: u32,
        /// Maximum digits to collect (stops immediately when reached)
        max_digits: u32,
        /// Inter-digit / overall timeout in milliseconds
        timeout_ms: u64,
        /// Optional terminator digit (not included in result)
        terminator: Option<char>,
    },

    /// Start recording
    StartRecording {
        /// Recording configuration
        config: RecordConfig,
    },

    /// Pause recording
    PauseRecording,

    /// Resume recording
    ResumeRecording,

    /// Stop recording
    StopRecording,

    /// Supervisor listen mode (monitoring only)
    SupervisorListen {
        /// Supervisor's leg (or supervisor session ID for cross-session monitoring)
        supervisor_leg: LegId,
        /// Target leg to monitor
        target_leg: LegId,
        /// Optional supervisor session ID when monitoring from a different session
        supervisor_session_id: Option<String>,
    },

    /// Supervisor whisper mode (can talk to agent only)
    SupervisorWhisper {
        /// Supervisor's leg (or supervisor session ID for cross-session monitoring)
        supervisor_leg: LegId,
        /// Target leg (agent)
        target_leg: LegId,
        /// Optional supervisor session ID when monitoring from a different session
        supervisor_session_id: Option<String>,
    },

    /// Supervisor barge mode (join conversation)
    SupervisorBarge {
        /// Supervisor's leg (or supervisor session ID for cross-session monitoring)
        supervisor_leg: LegId,
        /// Target leg (agent)
        target_leg: LegId,
        /// Optional supervisor session ID when monitoring from a different session
        supervisor_session_id: Option<String>,
    },

    /// Supervisor takeover mode (replace agent)
    SupervisorTakeover {
        /// Supervisor's leg (or supervisor session ID for cross-session monitoring)
        supervisor_leg: LegId,
        /// Target leg (agent to be replaced)
        target_leg: LegId,
        /// Optional supervisor session ID when monitoring from a different session
        supervisor_session_id: Option<String>,
    },

    /// Stop supervisor mode
    SupervisorStop {
        /// Supervisor's leg
        supervisor_leg: LegId,
    },

    /// Create a conference
    ConferenceCreate {
        /// Conference ID
        conf_id: String,
        /// Conference options
        options: ConferenceOptions,
    },

    /// Add a leg to a conference
    ConferenceAdd {
        /// Conference ID
        conf_id: String,
        /// Leg to add
        leg_id: LegId,
    },

    /// Remove a leg from a conference
    ConferenceRemove {
        /// Conference ID
        conf_id: String,
        /// Leg to remove
        leg_id: LegId,
    },

    /// Mute a leg in a conference
    ConferenceMute {
        /// Conference ID
        conf_id: String,
        /// Leg to mute
        leg_id: LegId,
    },

    /// Unmute a leg in a conference
    ConferenceUnmute {
        /// Conference ID
        conf_id: String,
        /// Leg to unmute
        leg_id: LegId,
    },

    /// Destroy a conference
    ConferenceDestroy {
        /// Conference ID
        conf_id: String,
    },

    /// Host ends the entire conference (validates host identity)
    ConferenceEnd {
        /// Conference ID
        conf_id: String,
        /// Leg ID of the host requesting the end
        host_leg_id: LegId,
    },

    /// Kick a participant from a conference (alias for remove with notification)
    ConferenceKick {
        /// Conference ID
        conf_id: String,
        /// Leg to kick
        leg_id: LegId,
    },

    /// Mute all participants in a conference
    ConferenceMuteAll {
        /// Conference ID
        conf_id: String,
    },

    /// Get conference info (participants, state, etc.)
    ConferenceInfo {
        /// Conference ID
        conf_id: String,
    },

    /// List all conferences
    ConferenceList,

    /// Enqueue a leg into a queue
    QueueEnqueue {
        /// Leg to enqueue
        leg_id: LegId,
        /// Queue ID or name
        queue_id: String,
        /// Priority (higher = more important)
        priority: Option<u32>,
    },

    /// Remove a leg from a queue
    QueueDequeue {
        /// Leg to dequeue
        leg_id: LegId,
    },

    /// Start an application (IVR, Voicemail, etc.)
    StartApp {
        /// Application name
        app_name: String,
        /// Application parameters
        params: Option<serde_json::Value>,
        /// Whether to auto-answer the call
        auto_answer: bool,
    },

    /// Stop the current application
    StopApp {
        /// Reason for stopping
        reason: Option<String>,
    },

    /// Inject an event into the running application
    InjectAppEvent {
        /// The event to inject
        event: AppEvent,
    },

    /// Handle a re-INVITE
    HandleReInvite {
        /// Target leg
        leg_id: LegId,
        /// New SDP
        sdp: String,
    },

    /// Refresh the session (send re-INVITE)
    RefreshSession,

    /// Mute a specific track
    MuteTrack {
        /// Track ID
        track_id: String,
    },

    /// Unmute a specific track
    UnmuteTrack {
        /// Track ID
        track_id: String,
    },

    /// Send a SIP MESSAGE request
    SendSipMessage {
        /// Content-Type header value
        content_type: String,
        /// Message body
        body: String,
    },

    /// Send a SIP NOTIFY request
    SendSipNotify {
        /// Event header value
        event: String,
        /// Content-Type header value
        content_type: String,
        /// Notify body
        body: String,
    },

    /// Join a conference mixer (for attended-transfer or 3-way calling)
    JoinMixer {
        /// Mixer ID / conference room ID
        mixer_id: String,
    },

    /// Leave the current conference mixer
    LeaveMixer,

    /// Send a SIP OPTIONS ping
    SendSipOptionsPing,

    /// Add a new SIP leg to the session
    LegAdd {
        /// SIP URI target
        target: String,
        /// Optional leg ID (auto-generated if not provided)
        leg_id: Option<LegId>,
    },

    /// Remove a leg from the session
    LegRemove {
        /// Leg ID to remove
        leg_id: LegId,
    },

    /// Leg dial completed successfully (async notification)
    /// Leg connected (async notification)
    LegConnected {
        /// Leg ID that connected
        leg_id: LegId,
        /// Answer SDP from the leg (for codec resolution)
        answer_sdp: Option<String>,
    },

    /// Leg dial failed (async notification)
    LegFailed {
        /// Leg ID that failed
        leg_id: LegId,
        /// Failure reason
        reason: String,
    },
}

/// Point-to-point bridge mode
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum P2PMode {
    /// Standard audio bridge
    #[default]
    Audio,
    /// Video bridge
    Video,
    /// Audio and video
    AudioVideo,
}

/// Audio playback options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlayOptions {
    /// Whether to loop the audio
    pub loop_playback: bool,
    /// Whether to wait for completion before returning
    pub await_completion: bool,
    /// Whether to interrupt on DTMF
    pub interrupt_on_dtmf: bool,
    /// Optional track ID for tracking
    pub track_id: Option<String>,
    /// Whether to send progress (183) before playing
    pub send_progress: bool,
}

impl Default for PlayOptions {
    fn default() -> Self {
        Self {
            loop_playback: false,
            await_completion: false,
            interrupt_on_dtmf: true,
            track_id: None,
            send_progress: false,
        }
    }
}

/// Recording configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecordConfig {
    /// Output file path
    pub path: String,
    /// Maximum recording duration
    pub max_duration_secs: Option<u32>,
    /// Whether to play a beep before recording
    pub beep: bool,
    /// Audio format
    pub format: Option<String>,
}

/// Conference options
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ConferenceOptions {
    /// Maximum number of participants
    pub max_participants: Option<u32>,
    /// Whether to record the conference
    pub record: bool,
    /// Recording path (if recording)
    pub record_path: Option<String>,
}

/// Application event for injection
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AppEvent {
    /// DTMF digit received
    Dtmf { digit: String },
    /// Audio playback completed
    AudioComplete { track_id: String, interrupted: bool },
    /// Recording completed
    RecordingComplete { recording_id: String, path: String },
    /// Custom event
    Custom {
        name: String,
        data: serde_json::Value,
    },
    /// Timeout event
    Timeout { timer_id: String },
}

impl CallCommand {
    /// Check if this command requires media capabilities
    pub fn requires_media(&self) -> bool {
        matches!(
            self,
            CallCommand::Play { .. }
                | CallCommand::StartRecording { .. }
                | CallCommand::SupervisorListen { .. }
                | CallCommand::SupervisorWhisper { .. }
                | CallCommand::SupervisorBarge { .. }
                | CallCommand::SupervisorTakeover { .. }
                | CallCommand::Hold { music: Some(_), .. }
        )
    }

    /// Check if this is a signaling-only command (works in bypass mode)
    pub fn is_signaling_only(&self) -> bool {
        matches!(
            self,
            CallCommand::Answer { .. }
                | CallCommand::Reject { .. }
                | CallCommand::Hangup(_)
                | CallCommand::Transfer { .. }
                | CallCommand::Hold { music: None, .. }
                | CallCommand::Unhold { .. }
        )
    }

    /// Get the target leg ID if this command targets a specific leg
    pub fn target_leg(&self) -> Option<&LegId> {
        match self {
            CallCommand::Answer { leg_id } => Some(leg_id),
            CallCommand::Reject { leg_id, .. } => Some(leg_id),
            CallCommand::Ring { leg_id, .. } => Some(leg_id),
            CallCommand::Hangup(cmd) => cmd.leg_id.as_ref(),
            CallCommand::Bridge { leg_a, .. } => Some(leg_a),
            CallCommand::Unbridge { leg_id } => Some(leg_id),
            CallCommand::Transfer { leg_id, .. } => Some(leg_id),
            CallCommand::Hold { leg_id, .. } => Some(leg_id),
            CallCommand::Unhold { leg_id } => Some(leg_id),
            CallCommand::Play {
                leg_id: Some(leg_id),
                ..
            } => Some(leg_id),
            CallCommand::StopPlayback {
                leg_id: Some(leg_id),
            } => Some(leg_id),
            CallCommand::SendDtmf { leg_id, .. } => Some(leg_id),
            CallCommand::SupervisorListen { supervisor_leg, .. } => Some(supervisor_leg),
            CallCommand::SupervisorWhisper { supervisor_leg, .. } => Some(supervisor_leg),
            CallCommand::SupervisorBarge { supervisor_leg, .. } => Some(supervisor_leg),
            CallCommand::SupervisorTakeover { supervisor_leg, .. } => Some(supervisor_leg),
            CallCommand::SupervisorStop { supervisor_leg } => Some(supervisor_leg),
            CallCommand::ConferenceAdd { leg_id, .. } => Some(leg_id),
            CallCommand::ConferenceRemove { leg_id, .. } => Some(leg_id),
            CallCommand::ConferenceMute { leg_id, .. } => Some(leg_id),
            CallCommand::ConferenceUnmute { leg_id, .. } => Some(leg_id),
            CallCommand::ConferenceKick { leg_id, .. } => Some(leg_id),
            CallCommand::ConferenceEnd { host_leg_id, .. } => Some(host_leg_id),
            CallCommand::QueueEnqueue { leg_id, .. } => Some(leg_id),
            CallCommand::QueueDequeue { leg_id } => Some(leg_id),
            CallCommand::HandleReInvite { leg_id, .. } => Some(leg_id),
            _ => None,
        }
    }
}

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

    #[test]
    fn call_command_requires_media() {
        let play = CallCommand::Play {
            leg_id: None,
            source: MediaSource::file("test.wav"),
            options: None,
        };
        assert!(play.requires_media());

        let answer = CallCommand::Answer {
            leg_id: LegId::new("leg-1"),
        };
        assert!(!answer.requires_media());
    }

    #[test]
    fn call_command_signaling_only() {
        let answer = CallCommand::Answer {
            leg_id: LegId::new("leg-1"),
        };
        assert!(answer.is_signaling_only());

        let play = CallCommand::Play {
            leg_id: None,
            source: MediaSource::file("test.wav"),
            options: None,
        };
        assert!(!play.is_signaling_only());
    }

    #[test]
    fn call_command_target_leg() {
        let answer = CallCommand::Answer {
            leg_id: LegId::new("leg-1"),
        };
        assert_eq!(answer.target_leg().map(|l| l.as_str()), Some("leg-1"));

        let start_recording = CallCommand::StartRecording {
            config: RecordConfig {
                path: "/tmp/rec.wav".to_string(),
                max_duration_secs: None,
                beep: false,
                format: None,
            },
        };
        assert!(start_recording.target_leg().is_none());
    }

    #[test]
    fn call_command_conference_new_variants() {
        let kick = CallCommand::ConferenceKick {
            conf_id: "conf-1".to_string(),
            leg_id: LegId::new("leg-1"),
        };
        assert_eq!(kick.target_leg().map(|l| l.as_str()), Some("leg-1"));

        let mute_all = CallCommand::ConferenceMuteAll {
            conf_id: "conf-1".to_string(),
        };
        assert!(mute_all.target_leg().is_none());

        let info = CallCommand::ConferenceInfo {
            conf_id: "conf-1".to_string(),
        };
        assert!(info.target_leg().is_none());

        let list = CallCommand::ConferenceList;
        assert!(list.target_leg().is_none());
    }

    #[test]
    fn call_command_serialization_roundtrip() {
        let kick = CallCommand::ConferenceKick {
            conf_id: "conf-1".to_string(),
            leg_id: LegId::new("leg-1"),
        };
        let json = serde_json::to_string(&kick).unwrap();
        let parsed: CallCommand = serde_json::from_str(&json).unwrap();
        assert!(matches!(parsed, CallCommand::ConferenceKick { .. }));

        let mute_all = CallCommand::ConferenceMuteAll {
            conf_id: "conf-1".to_string(),
        };
        let json = serde_json::to_string(&mute_all).unwrap();
        let parsed: CallCommand = serde_json::from_str(&json).unwrap();
        assert!(matches!(parsed, CallCommand::ConferenceMuteAll { .. }));

        let list = CallCommand::ConferenceList;
        let json = serde_json::to_string(&list).unwrap();
        let parsed: CallCommand = serde_json::from_str(&json).unwrap();
        assert!(matches!(parsed, CallCommand::ConferenceList));
    }
}