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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
use reqwest::{Client as HttpClient, Url};
use crate::{errors::SignalWireError, types::*};
#[derive(Debug)]
pub struct SignalWireClient {
pub project_id: String,
pub api_key: String,
pub space_name: String,
pub http_client: HttpClient,
}
impl SignalWireClient {
/// Creates a new SignalWire client.
///
/// # Arguments
///
/// * `space_name` - The space name of your SignalWire project.
/// * `project_id` - The project ID for authentication.
/// * `api_key` - The API key for authentication.
///
/// # Returns
///
/// A new instance of `SignalWireClient`.
pub fn new(space_name: &str, project_id: &str, api_key: &str) -> Self {
SignalWireClient {
space_name: space_name.to_string(),
project_id: project_id.to_string(),
api_key: api_key.to_string(),
http_client: HttpClient::new(),
}
}
/// Retrieves a JSON Web Token (JWT) and a refresh token for authentication.
///
/// This method fetches a JWT used for authenticating further requests to the SignalWire API.
/// Both a JWT token and a refresh token are returned upon a successful call.
///
/// # Returns
///
/// A `Result` containing either:
/// - `JwtResponse` with `jwt_token` and `refresh_token` if successful.
/// - `SignalWireError` if the request fails or is unauthorized.
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn get_jwt(&self) -> Result<JwtResponse, SignalWireError> {
let url = format!("https://{}.signalwire.com/api/relay/rest/jwt", self.space_name);
let response = self
.http_client
.post(&url)
.basic_auth(&self.project_id, Some(&self.api_key))
.header("Content-Length", "0")
.body("")
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignalWireError::Unauthorized);
}
let jwt_response: JwtResponse = serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
Ok(jwt_response)
}
/// Blocking version of `get_jwt`.
///
/// # Returns
///
/// A `Result` containing either:
/// - `JwtResponse` with `jwt_token` and `refresh_token` if successful.
/// - `SignalWireError` if the request fails or is unauthorized.
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `get_jwt`.")]
#[cfg(feature = "blocking")]
pub fn get_jwt_blocking(&self) -> Result<JwtResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.get_jwt())
}
/// Fetches available phone numbers for a given country.
/// Currently the only country supported by SignalWire is "US".
///
/// # Arguments
///
/// * `iso_country` - The ISO country code to query against.
/// * `query_params` - Additional query parameters as key-value pairs.
///
/// # Returns
///
/// A `Result` containing either an `PhoneNumbersAvailableResponse` or a `SignalWireError`.
pub async fn get_phone_numbers_available(&self, iso_country: &str, query_params: &[(String, String)]) -> Result<PhoneNumbersAvailableResponse, SignalWireError> {
let url = format!(
"https://{}.signalwire.com/api/laml/2010-04-01/Accounts/{}/AvailablePhoneNumbers/{}/Local",
self.space_name, self.project_id, iso_country
);
println!("URL: {}", url);
let url = Url::parse_with_params(&url, query_params).map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
let response = self
.http_client
.get(url)
.basic_auth(&self.project_id, Some(&self.api_key))
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status.is_client_error() || status.is_server_error() {
return Err(SignalWireError::Unexpected(response_text));
}
let phone_numbers_response: PhoneNumbersAvailableResponse = serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
Ok(phone_numbers_response)
}
/// Blocking version of `get_phone_numbers_available`.
///
/// # Arguments
///
/// * `iso_country` - The ISO country code to query against.
/// * `query_params` - Additional query parameters as key-value pairs.
///
/// # Returns
///
/// A `Result` containing either an `PhoneNumbersAvailableResponse` or a `SignalWireError`.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `get_phone_numbers_available`.")]
#[cfg(feature = "blocking")]
pub fn get_phone_numbers_available_blocking(&self, iso_country: &str, query_params: &[(String, String)]) -> Result<PhoneNumbersAvailableResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.get_phone_numbers_available(iso_country, query_params))
}
/// Retrieves a list of phone numbers owned by the client.
///
/// # Arguments
///
/// * `query_params` - Additional query parameters as key-value pairs.
///
/// # Returns
///
/// A `Result` containing either:
/// - `PhoneNumbersOwnedResponse` with detailed phone number info if successful.
/// - `SignalWireError` if the request fails or is unauthorized.
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn get_phone_numbers_owned(&self, query_params: &[(String, String)]) -> Result<PhoneNumbersOwnedResponse, SignalWireError> {
let url = format!("https://{}.signalwire.com/api/relay/rest/phone_numbers", self.space_name);
let url = Url::parse_with_params(&url, query_params).map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
let response = self
.http_client
.get(url)
.basic_auth(&self.project_id, Some(&self.api_key))
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignalWireError::Unauthorized);
} else if status.is_client_error() || status.is_server_error() {
return Err(SignalWireError::Unexpected(response_text));
} else {
let phone_numbers_response: PhoneNumbersOwnedResponse = serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
Ok(phone_numbers_response)
}
}
/// Blocking version of `get_phone_numbers_owned`.
///
/// # Arguments
///
/// * `query_params` - Additional query parameters as key-value pairs.
///
/// # Returns
///
/// A `Result` containing either:
/// - `OwnedPhoneNumbersResponse` with detailed phone number info if successful.
/// - `SignalWireError` if the request fails or is unauthorized.
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `get_phone_numbers_owned`.")]
#[cfg(feature = "blocking")]
pub fn get_phone_numbers_owned_blocking(&self, query_params: &[(String, String)]) -> Result<PhoneNumbersOwnedResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.get_phone_numbers_owned(query_params))
}
/// Buy a phone number.
///
/// # Arguments
///
/// * `phone_number` - The phone number to buy.
///
/// # Returns
///
/// A `Result` containing either:
/// - `BuyPhoneNumberResponse` with detailed phone number info if successful.
/// - `SignalWireError` if the request fails or is unauthorized.
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn buy_phone_number(&self, phone_number: &str) -> Result<BuyPhoneNumberResponse, SignalWireError> {
let url = format!("https://{}.signalwire.com/api/relay/rest/phone_numbers", self.space_name);
let response = self
.http_client
.post(&url)
.basic_auth(&self.project_id, Some(&self.api_key))
.json(&BuyPhoneNumberRequest { number: phone_number.to_string() })
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status.is_client_error() || status.is_server_error() {
return Err(SignalWireError::Unexpected(response_text));
}
let buy_phone_number_response: BuyPhoneNumberResponse = serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
Ok(buy_phone_number_response)
}
/// Blocking version of `buy_phone_number`.
///
/// # Arguments
///
/// * `phone_number` - The phone number to buy.
///
/// # Returns
///
/// A `Result` containing either:
/// - `BuyPhoneNumberResponse` with detailed phone number info if successful.
/// - `SignalWireError` if the request fails or is unauthorized.
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `buy_phone_number`.")]
#[cfg(feature = "blocking")]
pub fn buy_phone_number_blocking(&self, phone_number: &str) -> Result<BuyPhoneNumberResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.buy_phone_number(phone_number))
}
/// Sends an SMS message using the SignalWire API.
///
/// # Arguments
///
/// * `message` - The SMS message details including `body`, `from`, and `to`.
///
/// # Returns
///
/// A `Result` containing either:
/// - `SmsResponse` with details about the sent message if successful.
/// - `SignalWireError` if the request fails or is unauthorized.
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn send_sms(&self, message: &SmsMessage) -> Result<SmsResponse, SignalWireError> {
let url = format!("https://{}.signalwire.com/api/laml/2010-04-01/Accounts/{}/Messages", self.space_name, self.project_id);
let form = [("From", &message.from), ("To", &message.to), ("Body", &message.body)];
let response = self
.http_client
.post(&url)
.basic_auth(&self.project_id, Some(&self.api_key))
.form(&form)
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignalWireError::Unauthorized);
} else if status.is_client_error() || status.is_server_error() {
return Err(SignalWireError::Unexpected(response_text));
}
let sms_response: SmsResponse = serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(format!("Failed to parse response: {}. Response was: {}", e, response_text)))?;
Ok(sms_response)
}
/// Blocking version of `send_sms`.
///
/// # Arguments
///
/// * `message` - The SMS message details including `body`, `from`, and `to`.
///
/// # Returns
///
/// A `Result` containing either:
/// - `SmsResponse` with details about the sent message if successful.
/// - `SignalWireError` if the request fails or is unauthorized.
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `send_sms`.")]
#[cfg(feature = "blocking")]
pub fn send_sms_blocking(&self, message: &SmsMessage) -> Result<SmsResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.send_sms(message))
}
/// Get the status of a message by its SID (message identifier).
///
/// This method allows you to check the current delivery status of a message
/// that was previously sent via the SignalWire API.
///
/// # Arguments
///
/// * `message_sid` - The SID (unique identifier) of the message to check
///
/// # Returns
///
/// A `Result` containing either:
/// - `SmsResponse` with the complete message details, including its current status
/// - `SignalWireError` if the request fails or the message can't be found
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Returns `SignalWireError::NotFound` if the message SID doesn't exist.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn get_message_status(&self, message_sid: &str) -> Result<SmsResponse, SignalWireError> {
let url = format!("https://{}.signalwire.com/api/laml/2010-04-01/Accounts/{}/Messages/{}", self.space_name, self.project_id, message_sid);
let response = self
.http_client
.get(&url)
.basic_auth(&self.project_id, Some(&self.api_key))
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignalWireError::Unauthorized);
} else if status == reqwest::StatusCode::NOT_FOUND {
return Err(SignalWireError::NotFound(format!("Message with SID {} not found", message_sid)));
} else if status.is_client_error() || status.is_server_error() {
return Err(SignalWireError::Unexpected(response_text));
}
let sms_response: SmsResponse = serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(format!("Failed to parse response: {}. Response was: {}", e, response_text)))?;
Ok(sms_response)
}
/// Blocking version of `get_message_status`.
///
/// # Arguments
///
/// * `message_sid` - The SID (unique identifier) of the message to check
///
/// # Returns
///
/// A `Result` containing either:
/// - `SmsResponse` with the complete message details, including its current status
/// - `SignalWireError` if the request fails or the message can't be found
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Returns `SignalWireError::NotFound` if the message SID doesn't exist.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `get_message_status`.")]
#[cfg(feature = "blocking")]
pub fn get_message_status_blocking(&self, message_sid: &str) -> Result<SmsResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.get_message_status(message_sid))
}
// ---------- Subproject (Account) Methods ----------
/// Lists all subprojects (accounts) for the current project.
///
/// This method returns a list that contains the current Project and any subprojects.
///
/// # Arguments
///
/// * `query_params` - Optional query parameters for filtering subprojects
///
/// # Returns
///
/// A `Result` containing either:
/// - `SubprojectsListResponse` with the list of subprojects if successful
/// - `SignalWireError` if the request fails
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn list_subprojects(&self, query_params: &[(String, String)]) -> Result<SubprojectsListResponse, SignalWireError> {
let url = format!("https://{}.signalwire.com/api/laml/2010-04-01/Accounts", self.space_name);
let url = Url::parse_with_params(&url, query_params).map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
let response = self
.http_client
.get(url)
.basic_auth(&self.project_id, Some(&self.api_key))
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignalWireError::Unauthorized);
} else if status.is_client_error() || status.is_server_error() {
return Err(SignalWireError::Unexpected(response_text));
}
let subprojects_response: SubprojectsListResponse = serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(format!("Failed to parse response: {}. Response was: {}", e, response_text)))?;
Ok(subprojects_response)
}
/// Blocking version of `list_subprojects`.
///
/// # Arguments
///
/// * `query_params` - Optional query parameters for filtering subprojects
///
/// # Returns
///
/// A `Result` containing either:
/// - `SubprojectsListResponse` with the list of subprojects if successful
/// - `SignalWireError` if the request fails
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `list_subprojects`.")]
#[cfg(feature = "blocking")]
pub fn list_subprojects_blocking(&self, query_params: &[(String, String)]) -> Result<SubprojectsListResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.list_subprojects(query_params))
}
/// Get details for a specific subproject (account).
///
/// # Arguments
///
/// * `subproject_sid` - The SID (unique identifier) of the subproject to retrieve
///
/// # Returns
///
/// A `Result` containing either:
/// - `SubprojectResponse` with the subproject details if successful
/// - `SignalWireError` if the request fails
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Returns `SignalWireError::NotFound` if the subproject SID doesn't exist.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn get_subproject(&self, subproject_sid: &str) -> Result<SubprojectResponse, SignalWireError> {
let url = format!("https://{}.signalwire.com/api/laml/2010-04-01/Accounts/{}", self.space_name, subproject_sid);
let response = self
.http_client
.get(&url)
.basic_auth(&self.project_id, Some(&self.api_key))
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignalWireError::Unauthorized);
} else if status == reqwest::StatusCode::NOT_FOUND {
return Err(SignalWireError::NotFound(format!("Subproject with SID {} not found", subproject_sid)));
} else if status.is_client_error() || status.is_server_error() {
return Err(SignalWireError::Unexpected(response_text));
}
let subproject_response: SubprojectResponse = serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(format!("Failed to parse response: {}. Response was: {}", e, response_text)))?;
Ok(subproject_response)
}
/// Blocking version of `get_subproject`.
///
/// # Arguments
///
/// * `subproject_sid` - The SID (unique identifier) of the subproject to retrieve
///
/// # Returns
///
/// A `Result` containing either:
/// - `SubprojectResponse` with the subproject details if successful
/// - `SignalWireError` if the request fails
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Returns `SignalWireError::NotFound` if the subproject SID doesn't exist.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `get_subproject`.")]
#[cfg(feature = "blocking")]
pub fn get_subproject_blocking(&self, subproject_sid: &str) -> Result<SubprojectResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.get_subproject(subproject_sid))
}
/// Creates a new subproject (account) within the current project.
///
/// # Arguments
///
/// * `friendly_name` - A human-readable name for the subproject
///
/// # Returns
///
/// A `Result` containing either:
/// - `SubprojectResponse` with the details of the created subproject if successful
/// - `SignalWireError` if the request fails
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn create_subproject(&self, friendly_name: &str) -> Result<SubprojectResponse, SignalWireError> {
let url = format!("https://{}.signalwire.com/api/laml/2010-04-01/Accounts", self.space_name);
let form = [("FriendlyName", friendly_name)];
let response = self
.http_client
.post(&url)
.basic_auth(&self.project_id, Some(&self.api_key))
.form(&form)
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignalWireError::Unauthorized);
} else if status.is_client_error() || status.is_server_error() {
return Err(SignalWireError::Unexpected(response_text));
}
let subproject_response: SubprojectResponse = serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(format!("Failed to parse response: {}. Response was: {}", e, response_text)))?;
Ok(subproject_response)
}
/// Blocking version of `create_subproject`.
///
/// # Arguments
///
/// * `friendly_name` - A human-readable name for the subproject
///
/// # Returns
///
/// A `Result` containing either:
/// - `SubprojectResponse` with the details of the created subproject if successful
/// - `SignalWireError` if the request fails
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `create_subproject`.")]
#[cfg(feature = "blocking")]
pub fn create_subproject_blocking(&self, friendly_name: &str) -> Result<SubprojectResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.create_subproject(friendly_name))
}
/// Updates an existing subproject (account).
///
/// # Arguments
///
/// * `subproject_sid` - The SID (unique identifier) of the subproject to update
/// * `friendly_name` - A new human-readable name for the subproject
/// * `status` - Optional status to set for the subproject ("active" or "suspended")
///
/// # Returns
///
/// A `Result` containing either:
/// - `SubprojectResponse` with the updated subproject details if successful
/// - `SignalWireError` if the request fails
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Returns `SignalWireError::NotFound` if the subproject SID doesn't exist.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn update_subproject(&self, subproject_sid: &str, friendly_name: &str, status: Option<&str>) -> Result<SubprojectResponse, SignalWireError> {
let url = format!("https://{}.signalwire.com/api/laml/2010-04-01/Accounts/{}", self.space_name, subproject_sid);
let mut form = vec![("FriendlyName", friendly_name)];
if let Some(status_value) = status {
form.push(("Status", status_value));
}
let response = self
.http_client
.post(&url)
.basic_auth(&self.project_id, Some(&self.api_key))
.form(&form)
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignalWireError::Unauthorized);
} else if status == reqwest::StatusCode::NOT_FOUND {
return Err(SignalWireError::NotFound(format!("Subproject with SID {} not found", subproject_sid)));
} else if status.is_client_error() || status.is_server_error() {
return Err(SignalWireError::Unexpected(response_text));
}
let subproject_response: SubprojectResponse = serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(format!("Failed to parse response: {}. Response was: {}", e, response_text)))?;
Ok(subproject_response)
}
/// Blocking version of `update_subproject`.
///
/// # Arguments
///
/// * `subproject_sid` - The SID (unique identifier) of the subproject to update
/// * `friendly_name` - A new human-readable name for the subproject
/// * `status` - Optional status to set for the subproject ("active" or "suspended")
///
/// # Returns
///
/// A `Result` containing either:
/// - `SubprojectResponse` with the updated subproject details if successful
/// - `SignalWireError` if the request fails
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Returns `SignalWireError::NotFound` if the subproject SID doesn't exist.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `update_subproject`.")]
#[cfg(feature = "blocking")]
pub fn update_subproject_blocking(&self, subproject_sid: &str, friendly_name: &str, status: Option<&str>) -> Result<SubprojectResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.update_subproject(subproject_sid, friendly_name, status))
}
/// Deletes a subproject (account).
///
/// # Arguments
///
/// * `subproject_sid` - The SID (unique identifier) of the subproject to delete
///
/// # Returns
///
/// A `Result` containing either:
/// - `()` if the subproject was successfully deleted
/// - `SignalWireError` if the request fails
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Returns `SignalWireError::NotFound` if the subproject SID doesn't exist.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn delete_subproject(&self, subproject_sid: &str) -> Result<(), SignalWireError> {
let url = format!("https://{}.signalwire.com/api/laml/2010-04-01/Accounts/{}", self.space_name, subproject_sid);
let response = self
.http_client
.delete(&url)
.basic_auth(&self.project_id, Some(&self.api_key))
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignalWireError::Unauthorized);
} else if status == reqwest::StatusCode::NOT_FOUND {
return Err(SignalWireError::NotFound(format!("Subproject with SID {} not found", subproject_sid)));
} else if status.is_client_error() || status.is_server_error() {
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
return Err(SignalWireError::Unexpected(response_text));
}
// Success, return empty result
Ok(())
}
/// Blocking version of `delete_subproject`.
///
/// # Arguments
///
/// * `subproject_sid` - The SID (unique identifier) of the subproject to delete
///
/// # Returns
///
/// A `Result` containing either:
/// - `()` if the subproject was successfully deleted
/// - `SignalWireError` if the request fails
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Returns `SignalWireError::NotFound` if the subproject SID doesn't exist.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `delete_subproject`.")]
#[cfg(feature = "blocking")]
pub fn delete_subproject_blocking(&self, subproject_sid: &str) -> Result<(), SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.delete_subproject(subproject_sid))
}
// ---------- Subproject Resource Methods ----------
/// Lists phone numbers owned by a specific subproject.
///
/// This method allows you to retrieve all phone numbers that belong to a specific subproject
/// using your main account's credentials.
///
/// # Arguments
///
/// * `subproject_sid` - The SID (unique identifier) of the subproject
/// * `query_params` - Additional query parameters as key-value pairs.
///
/// # Returns
///
/// A `Result` containing either:
/// - `SubprojectPhoneNumbersResponse` with detailed phone number info if successful.
/// - `SignalWireError` if the request fails or is unauthorized.
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Returns `SignalWireError::NotFound` if the subproject SID doesn't exist.
/// Other `SignalWireError` variants may be returned for unexpected issues.
pub async fn get_subproject_phone_numbers(&self, subproject_sid: &str, query_params: &[(String, String)]) -> Result<SubprojectPhoneNumbersResponse, SignalWireError> {
// First check if the subproject exists
self.get_subproject(subproject_sid).await?;
// URL to get phone numbers from a specific subproject
let url = format!("https://{}.signalwire.com/api/laml/2010-04-01/Accounts/{}/IncomingPhoneNumbers", self.space_name, subproject_sid);
let url = Url::parse_with_params(&url, query_params).map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
let response = self
.http_client
.get(url)
.basic_auth(&self.project_id, Some(&self.api_key))
.send()
.await
.map_err(|e| SignalWireError::HttpError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| SignalWireError::Unexpected(e.to_string()))?;
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignalWireError::Unauthorized);
} else if status == reqwest::StatusCode::NOT_FOUND {
return Err(SignalWireError::NotFound(format!("Subproject with SID {} not found", subproject_sid)));
} else if status.is_client_error() || status.is_server_error() {
return Err(SignalWireError::Unexpected(response_text));
}
let phone_numbers_response: SubprojectPhoneNumbersResponse =
serde_json::from_str(&response_text).map_err(|e| SignalWireError::Unexpected(format!("Failed to parse response: {}. Response was: {}", e, response_text)))?;
Ok(phone_numbers_response)
}
/// Blocking version of `get_subproject_phone_numbers`.
///
/// # Arguments
///
/// * `subproject_sid` - The SID (unique identifier) of the subproject
/// * `query_params` - Additional query parameters as key-value pairs.
///
/// # Returns
///
/// A `Result` containing either:
/// - `SubprojectPhoneNumbersResponse` with detailed phone number info if successful.
/// - `SignalWireError` if the request fails or is unauthorized.
///
/// # Errors
///
/// Returns `SignalWireError::Unauthorized` if authentication fails.
/// Returns `SignalWireError::NotFound` if the subproject SID doesn't exist.
/// Other `SignalWireError` variants may be returned for unexpected issues.
#[cfg_attr(feature = "blocking", doc = "Blocking version of `get_subproject_phone_numbers`.")]
#[cfg(feature = "blocking")]
pub fn get_subproject_phone_numbers_blocking(&self, subproject_sid: &str, query_params: &[(String, String)]) -> Result<SubprojectPhoneNumbersResponse, SignalWireError> {
tokio::runtime::Runtime::new().unwrap().block_on(self.get_subproject_phone_numbers(subproject_sid, query_params))
}
}