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
use crate::errors::SignalWireError;
use crate::types::*;
use reqwest::Client as HttpClient;
use reqwest::Url;
#[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))
}
}