rustpbx 0.4.2

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
// Integration tests for RWI WebSocket interface
// These tests require a running RustPBX instance with RWI configured

use futures::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::time::timeout;
use tokio_tungstenite::{connect_async, tungstenite::Message};

const RWI_URL: &str = "ws://127.0.0.1:8088/rwi/v1";
const TEST_TOKEN: &str = "test-token-rwi";

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RwiRequest {
    #[serde(rename = "rwi")]
    pub version: String,
    #[serde(rename = "action_id")]
    pub action_id: Option<String>,
    pub action: String,
    pub params: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RwiResponse {
    #[serde(rename = "rwi")]
    pub version: String,
    #[serde(rename = "action_id")]
    pub action_id: Option<String>,
    pub response: String,
    pub data: Option<serde_json::Value>,
    pub error: Option<RwiError>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RwiError {
    pub code: String,
    pub message: String,
}

impl RwiRequest {
    pub fn new(action: &str) -> Self {
        Self {
            version: "1.0".to_string(),
            action_id: Some(uuid::Uuid::new_v4().to_string()),
            action: action.to_string(),
            params: None,
        }
    }

    pub fn with_params(mut self, params: serde_json::Value) -> Self {
        self.params = Some(params);
        self
    }

    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap()
    }
}

pub struct RwiTestClient {
    ws: tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<TcpStream>>,
}

/// Type alias for test client results.
pub type TestResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;

impl RwiTestClient {
    pub async fn connect() -> TestResult<Self> {
        let url = format!("{}?token={}", RWI_URL, TEST_TOKEN);
        let (ws_stream, _) = timeout(Duration::from_secs(10), connect_async(&url)).await??;

        Ok(Self { ws: ws_stream })
    }

    pub async fn send_request(&mut self, request: RwiRequest) -> TestResult<RwiResponse> {
        let json = request.to_json();
        self.ws.send(Message::Text(json.into())).await?;

        // Wait for response
        let msg = match timeout(Duration::from_secs(5), self.ws.next()).await {
            Ok(Some(Ok(msg))) => msg,
            Ok(Some(Err(e))) => return Err(e.to_string().into()),
            Ok(None) => return Err("Stream ended".into()),
            Err(_) => return Err("Timeout".into()),
        };

        match msg {
            Message::Text(text) => {
                let response: RwiResponse = serde_json::from_str(&text)?;
                Ok(response)
            }
            Message::Close(_) => Err("Connection closed".into()),
            _ => Err("Unexpected message type".into()),
        }
    }

    pub async fn subscribe(&mut self, contexts: Vec<&str>) -> TestResult<RwiResponse> {
        let request = RwiRequest::new("session.subscribe")
            .with_params(serde_json::json!({ "contexts": contexts }));
        self.send_request(request).await
    }

    pub async fn list_calls(&mut self) -> TestResult<RwiResponse> {
        let request = RwiRequest::new("session.list_calls");
        self.send_request(request).await
    }

    pub async fn answer_call(&mut self, call_id: &str) -> TestResult<RwiResponse> {
        let request =
            RwiRequest::new("call.answer").with_params(serde_json::json!({ "call_id": call_id }));
        self.send_request(request).await
    }

    pub async fn hangup_call(
        &mut self,
        call_id: &str,
        reason: Option<&str>,
    ) -> TestResult<RwiResponse> {
        let mut params = serde_json::json!({ "call_id": call_id });
        if let Some(r) = reason {
            params["reason"] = serde_json::json!(r);
        }
        let request = RwiRequest::new("call.hangup").with_params(params);
        self.send_request(request).await
    }

    pub async fn reject_call(
        &mut self,
        call_id: &str,
        reason: Option<&str>,
    ) -> TestResult<RwiResponse> {
        let mut params = serde_json::json!({ "call_id": call_id });
        if let Some(r) = reason {
            params["reason"] = serde_json::json!(r);
        }
        let request = RwiRequest::new("call.reject").with_params(params);
        self.send_request(request).await
    }

    pub async fn ring_call(&mut self, call_id: &str) -> TestResult<RwiResponse> {
        let request =
            RwiRequest::new("call.ring").with_params(serde_json::json!({ "call_id": call_id }));
        self.send_request(request).await
    }

    pub async fn transfer_call(&mut self, call_id: &str, target: &str) -> TestResult<RwiResponse> {
        let request = RwiRequest::new("call.transfer")
            .with_params(serde_json::json!({ "call_id": call_id, "target": target }));
        self.send_request(request).await
    }

    pub async fn originate(
        &mut self,
        call_id: &str,
        destination: &str,
        caller_id: Option<&str>,
    ) -> TestResult<RwiResponse> {
        let mut params = serde_json::json!({
            "call_id": call_id,
            "destination": destination,
        });
        if let Some(cid) = caller_id {
            params["caller_id"] = serde_json::json!(cid);
        }
        let request = RwiRequest::new("call.originate").with_params(params);
        self.send_request(request).await
    }

    pub async fn bridge(&mut self, leg_a: &str, leg_b: &str) -> TestResult<RwiResponse> {
        let request = RwiRequest::new("call.bridge")
            .with_params(serde_json::json!({ "leg_a": leg_a, "leg_b": leg_b }));
        self.send_request(request).await
    }

    pub async fn media_play(
        &mut self,
        call_id: &str,
        source_type: &str,
        uri: &str,
    ) -> TestResult<RwiResponse> {
        let request = RwiRequest::new("media.play").with_params(serde_json::json!({
            "call_id": call_id,
            "source": {
                "type": source_type,
                "uri": uri
            }
        }));
        self.send_request(request).await
    }

    pub async fn queue_enqueue(
        &mut self,
        call_id: &str,
        queue_id: &str,
        priority: Option<u32>,
    ) -> TestResult<RwiResponse> {
        let mut params = serde_json::json!({
            "call_id": call_id,
            "queue_id": queue_id,
        });
        if let Some(p) = priority {
            params["priority"] = serde_json::json!(p);
        }
        let request = RwiRequest::new("queue.enqueue").with_params(params);
        self.send_request(request).await
    }

    pub async fn queue_dequeue(&mut self, call_id: &str) -> TestResult<RwiResponse> {
        let request =
            RwiRequest::new("queue.dequeue").with_params(serde_json::json!({ "call_id": call_id }));
        self.send_request(request).await
    }

    pub async fn send_dtmf(&mut self, call_id: &str, digits: &str) -> TestResult<RwiResponse> {
        let request = RwiRequest::new("call.send_dtmf")
            .with_params(serde_json::json!({ "call_id": call_id, "digits": digits }));
        self.send_request(request).await
    }

    pub async fn conference_create(&mut self, conf_id: &str) -> TestResult<RwiResponse> {
        let request = RwiRequest::new("conference.create")
            .with_params(serde_json::json!({ "conference_id": conf_id }));
        self.send_request(request).await
    }

    pub async fn conference_add(
        &mut self,
        conf_id: &str,
        call_id: &str,
    ) -> TestResult<RwiResponse> {
        let request = RwiRequest::new("conference.add")
            .with_params(serde_json::json!({ "conference_id": conf_id, "call_id": call_id }));
        self.send_request(request).await
    }

    pub async fn conference_remove(
        &mut self,
        conf_id: &str,
        call_id: &str,
    ) -> TestResult<RwiResponse> {
        let request = RwiRequest::new("conference.remove")
            .with_params(serde_json::json!({ "conference_id": conf_id, "call_id": call_id }));
        self.send_request(request).await
    }

    pub async fn conference_destroy(&mut self, conf_id: &str) -> TestResult<RwiResponse> {
        let request = RwiRequest::new("conference.destroy")
            .with_params(serde_json::json!({ "conference_id": conf_id }));
        self.send_request(request).await
    }

    pub async fn close(mut self) -> TestResult<()> {
        self.ws.close(None).await?;
        Ok(())
    }
}

// ===== Integration Tests =====

/// Test basic connection and authentication
#[tokio::test]
async fn test_rwi_connection_and_auth() {
    // This test requires RWI to be configured and running
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            // Connection successful - try to subscribe
            let result = client.subscribe(vec!["default"]).await;
            assert!(result.is_ok(), "Subscribe should work with valid token");

            let _ = client.close().await;
        }
        Err(e) => {
            // If connection fails, RWI might not be configured
            // Skip test in this case
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test session.subscribe
#[tokio::test]
async fn test_session_subscribe() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            let result = client.subscribe(vec!["context1", "context2"]).await;
            assert!(result.is_ok());

            let response = result.unwrap();
            assert_eq!(response.response, "success");

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test session.list_calls on empty registry
#[tokio::test]
async fn test_session_list_calls_empty() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            let _ = client.subscribe(vec!["default"]).await;

            let result = client.list_calls().await;
            assert!(result.is_ok());

            let response = result.unwrap();
            assert_eq!(response.response, "success");
            // Data should be an array (could be empty)
            if let Some(data) = response.data {
                assert!(data.is_array(), "list_calls should return array");
            }

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test call operations on non-existent call
#[tokio::test]
async fn test_call_operations_on_nonexistent_call() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            let _ = client.subscribe(vec!["default"]).await;

            // Try to answer non-existent call
            let result = client.answer_call("nonexistent-call-id").await;
            assert!(result.is_ok());

            let response = result.unwrap();
            // Should return error for non-existent call
            assert_eq!(
                response.response, "error",
                "Expected error for non-existent call"
            );
            assert!(response.error.is_some());

            // Try to hangup non-existent call
            let result = client.hangup_call("nonexistent-call-id", None).await;
            assert!(result.is_ok());

            let response = result.unwrap();
            assert_eq!(response.response, "error");

            // Try to ring non-existent call
            let result = client.ring_call("nonexistent-call-id").await;
            assert!(result.is_ok());

            let response = result.unwrap();
            assert_eq!(response.response, "error");

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test call.reject with different reasons
#[tokio::test]
async fn test_call_reject_reasons() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            let _ = client.subscribe(vec!["default"]).await;

            // Test busy rejection
            let result = client.reject_call("test-call", Some("busy")).await;
            assert!(result.is_ok());

            // Test forbidden rejection
            let result = client.reject_call("test-call", Some("forbidden")).await;
            assert!(result.is_ok());

            // Test not_found rejection
            let result = client.reject_call("test-call", Some("not_found")).await;
            assert!(result.is_ok());

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test call.transfer
#[tokio::test]
async fn test_call_transfer() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            let _ = client.subscribe(vec!["default"]).await;

            // Try to transfer non-existent call
            let result = client.transfer_call("test-call", "sip:3000@local").await;
            assert!(result.is_ok());

            let response = result.unwrap();
            // Should fail because call doesn't exist
            assert_eq!(response.response, "error");

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test call.originate (will fail without actual SIP setup)
#[tokio::test]
async fn test_call_originate() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            let _ = client.subscribe(vec!["default"]).await;

            // Try to originate a call
            let result = client
                .originate("new-call", "sip:test@local", Some("1001"))
                .await;
            assert!(result.is_ok());

            let response = result.unwrap();
            // May succeed or fail depending on SIP backend availability
            // But the command should be accepted
            println!("Originate response: {:?}", response);

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test call.bridge (will fail without actual calls)
#[tokio::test]
async fn test_call_bridge() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            let _ = client.subscribe(vec!["default"]).await;

            // Try to bridge non-existent calls
            let result = client.bridge("leg-a", "leg-b").await;
            assert!(result.is_ok());

            let response = result.unwrap();
            // Should fail because calls don't exist
            assert_eq!(response.response, "error");

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test media.play (not implemented yet)
#[tokio::test]
async fn test_media_play() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            let _ = client.subscribe(vec!["default"]).await;

            // Try to play media on non-existent call
            let result = client.media_play("test-call", "file", "welcome.wav").await;
            assert!(result.is_ok());

            let response = result.unwrap();
            // Should fail - not implemented or call not found
            println!("Media play response: {:?}", response);

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test invalid action
#[tokio::test]
async fn test_invalid_action() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            let request = RwiRequest::new("invalid.action");
            let result = client.send_request(request).await;

            // Should get an error response
            assert!(result.is_ok());
            let response = result.unwrap();
            assert_eq!(response.response, "error");

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test missing action field
#[tokio::test]
async fn test_missing_action() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            // Send request without action field
            let json = r#"{"rwi": "1.0", "params": {}}"#;
            client.ws.send(Message::Text(json.into())).await.unwrap();

            // Should get error response
            let msg = timeout(Duration::from_secs(5), client.ws.next()).await;
            assert!(msg.is_ok());

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test multiple sequential operations
#[tokio::test]
async fn test_sequential_operations() {
    let result = RwiTestClient::connect().await;

    match result {
        Ok(mut client) => {
            let _ = client.subscribe(vec!["default"]).await;

            // Sequential operations should all work (even if calls don't exist)
            let _ = client.list_calls().await;
            let _ = client.ring_call("call-1").await;
            let _ = client.answer_call("call-1").await;
            let _ = client.transfer_call("call-1", "sip:3000@local").await;
            let _ = client.hangup_call("call-1", None).await;

            let _ = client.close().await;
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}

/// Test reconnection
#[tokio::test]
async fn test_reconnection() {
    // Try to connect, disconnect, and reconnect
    let result1 = RwiTestClient::connect().await;

    match result1 {
        Ok(mut client1) => {
            // First connection - subscribe
            let result = client1.subscribe(vec!["default"]).await;
            assert!(result.is_ok());

            // Close first connection
            let _ = client1.close().await;

            // Wait a bit
            tokio::time::sleep(Duration::from_millis(100)).await;

            // Second connection
            let result2 = RwiTestClient::connect().await;
            match result2 {
                Ok(mut client2) => {
                    // Second connection should also work
                    let result = client2.subscribe(vec!["default"]).await;
                    assert!(result.is_ok());

                    let _ = client2.close().await;
                }
                Err(e) => {
                    println!("Second connection failed: {}. Skipping.", e);
                }
            }
        }
        Err(e) => {
            println!("RWI not available: {}. Skipping test.", e);
        }
    }
}