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
/*! This crate is an *synchronous* implementation of the Twilio API in Rust built
upon Reqwest and Serde.
Coverage is partial yet provides an idiomatic usage pattern currently covering:
- Accounts
- Conversations
This crate has been developed alongside the `twilly-cli` crate which provides an
enhanced Twilio CLI experience.
# Example
Interaction is done via a Twilio client that can be created via a constructor. The config
parameter is a `TwilioConfig` struct of an account SID & auth token pair.
```
let twilio = twilly::Client::new(&config);
```
To retrieve accounts from the client:
```
twilio.accounts().list(Some(&friendly_name), None);
```
To delete a conversation:
```
twilio.conversations().delete(&conversation_sid);
```
*/
pub mod account;
pub mod conversation;
use std::fmt;
use account::Accounts;
use conversation::Conversations;
use reqwest::{blocking::Response, Method};
use serde::{Deserialize, Serialize};
use strum_macros::{Display, EnumIter, EnumString};
/// Account SID & auth token pair required for
/// authenticating requests to Twilio.
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct TwilioConfig {
/// Twilio account SID, begins with AC...
pub account_sid: String,
/// Twilio account auth token
pub auth_token: String,
}
impl TwilioConfig {
pub fn build(account_sid: String, auth_token: String) -> TwilioConfig {
if !account_sid.starts_with("AC") {
panic!("Account SID must start with AC");
} else if account_sid.len() != 34 {
panic!(
"Account SID should be 34 characters in length. Was {}",
account_sid.len()
)
}
if auth_token.len() != 32 {
panic!(
"Auth token should be 32 characters in length. Was {}",
auth_token.len()
)
}
TwilioConfig {
account_sid,
auth_token,
}
}
}
/// The Twilio client used for interaction with
/// Twilio's API.
pub struct Client {
pub config: TwilioConfig,
client: reqwest::blocking::Client,
}
/// Crate error wrapping containing a `kind` used
/// to differentiate errors.
#[derive(Debug)]
pub struct TwilioError {
pub kind: ErrorKind,
}
impl fmt::Display for TwilioError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind.as_str())
}
}
/// A list of possible errors from the Twilio client.
#[derive(Debug)]
pub enum ErrorKind {
/// Network related error during the request.
NetworkError(reqwest::Error),
/// Twilio returned error
TwilioError(TwilioApiError),
/// Unable to parse request or response body
ParsingError(reqwest::Error),
}
impl ErrorKind {
fn as_str(&self) -> String {
match self {
ErrorKind::NetworkError(error) => format!("Network error reaching Twilio: {}", &error),
ErrorKind::ParsingError(error) => format!("Unable to parse response: {}", &error),
ErrorKind::TwilioError(error) => {
format!("Error: {}", &error)
}
}
}
}
/// Twilio error response.
#[derive(Debug, Serialize, Deserialize)]
pub struct TwilioApiError {
/// Twilio specific error code
pub code: u32,
/// Detail of the error
pub message: String,
/// Where to find more info on the error
pub more_info: String,
/// HTTP status code
pub status: u16,
}
impl fmt::Display for TwilioApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} from Twilio. ({}) {}. For more info see: {}",
self.status, self.code, self.message, self.more_info
)
}
}
/// Available Twilio resources to access.
#[derive(Display, EnumIter, EnumString, PartialEq)]
pub enum SubResource {
Account,
Conversations,
}
impl Client {
/// Create a Twilio client ready to send requests based on the
/// provided config.
pub fn new(config: &TwilioConfig) -> Self {
Self {
config: config.clone(),
client: reqwest::blocking::Client::new(),
}
}
/// Dispatches a request to Twilio and handles parsing the response.
///
/// If the method allows for a request body then `params` sends this
/// as X-www-form-urlencoded otherwise `params` are attached as query
/// string parameters.
///
/// Will return a result of either the resource type or one of the
/// possible errors ([`Error`]).
fn send_request<T, U>(
&self,
method: Method,
url: &str,
params: Option<&U>,
) -> Result<T, TwilioError>
where
T: serde::de::DeserializeOwned,
U: Serialize + ?Sized,
{
let response = self.send_http_request(method, url, params)?;
match response.status().is_success() {
true => response.json::<T>().map_err(|error| TwilioError {
kind: ErrorKind::ParsingError(error),
}),
false => {
let parsed_twilio_error = response.json::<TwilioApiError>();
match parsed_twilio_error {
Ok(twilio_error) => Err(TwilioError {
kind: ErrorKind::TwilioError(twilio_error),
}),
Err(error) => Err(TwilioError {
kind: ErrorKind::ParsingError(error),
}),
}
}
}
}
/// Dispatches a request to Twilio ignoring the response returned. This is generally
/// for mutating where either the response is irrelevant or there is nothing returned.
///
/// If the method allows for a request body then `params` sends this
/// as X-www-form-urlencoded otherwise `params` are attached as query
/// string parameters.
///
/// Will return a result of either the resource type or one of the
/// possible errors ([`Error`]).
fn send_request_and_ignore_response<T>(
&self,
method: Method,
url: &str,
params: Option<&T>,
) -> Result<(), TwilioError>
where
T: Serialize + ?Sized,
{
let response = self.send_http_request(method, url, params)?;
match response.status().is_success() {
true => Ok(()),
false => {
let parsed_twilio_error = response.json::<TwilioApiError>();
match parsed_twilio_error {
Ok(twilio_error) => Err(TwilioError {
kind: ErrorKind::TwilioError(twilio_error),
}),
Err(error) => Err(TwilioError {
kind: ErrorKind::ParsingError(error),
}),
}
}
}
}
// Helper function for `send_request`. Not designed to be used independently.
fn send_http_request<T>(
&self,
method: Method,
url: &str,
params: Option<&T>,
) -> Result<Response, TwilioError>
where
T: Serialize + ?Sized,
{
match method {
Method::GET => self
.client
.request(method, url)
.basic_auth(&self.config.account_sid, Some(&self.config.auth_token))
.query(¶ms)
.send(),
_ => self
.client
.request(method, url)
.basic_auth(&self.config.account_sid, Some(&self.config.auth_token))
.form(¶ms)
.send(),
}
.map_err(|error| TwilioError {
kind: ErrorKind::NetworkError(error),
})
}
/// Account related functions.
pub fn accounts<'a>(&'a self) -> Accounts {
Accounts { client: self }
}
/// Conversation related functions.
pub fn conversations<'a>(&'a self) -> Conversations {
Conversations { client: self }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "Account SID must start with AC")]
fn account_sid_regex() {
TwilioConfig::build(String::from("ThisisnotanaccountSID"), String::from("1234"));
}
#[test]
#[should_panic(expected = "Account SID should be 34 characters in length. Was 23")]
fn account_sid_len() {
TwilioConfig::build(
String::from("ACThisisnotanaccountSID"),
String::from("1234"),
);
}
#[test]
#[should_panic(expected = "Auth token should be 32 characters in length. Was 20")]
fn auth_token_len() {
TwilioConfig::build(
String::from("AC11111111111111111111111111111111"),
String::from("11111111111111111111"),
);
}
#[test]
fn config_on_good_credentials() {
let account_sid = String::from("AC11111111111111111111111111111111");
let auth_token = String::from("11111111111111111111111111111111");
let config = TwilioConfig::build(account_sid.clone(), auth_token.clone());
assert_eq!(account_sid, config.account_sid);
assert_eq!(auth_token, config.auth_token);
}
}