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
#[cfg(feature = "voice")]
mod call;
#[cfg(feature = "sms")]
mod message;

#[cfg(feature = "webhook")]
pub mod twiml;
#[cfg(feature = "webhook")]
mod webhook;

#[cfg(feature = "voice")]
pub use call::{Call, OutboundCall};
#[cfg(feature = "sms")]
pub use message::{Message, OutboundMessage};

use http::{
    header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE},
    Method, StatusCode,
};
use isahc::{
    auth::{Authentication, Credentials},
    config::Configurable,
    AsyncBody, AsyncReadResponseExt,
};

use std::{
    collections::BTreeMap,
    error::Error,
    fmt::{self, Display, Formatter},
};

pub const GET: Method = Method::GET;
pub const POST: Method = Method::POST;
pub const PUT: Method = Method::PUT;

pub struct Client {
    account_id: String,
    auth_token: String,
}

fn url_encode(params: &[(&str, &str)]) -> String {
    params
        .iter()
        .map(|&t| {
            let (k, v) = t;
            format!("{}={}", k, v)
        })
        .fold("".to_string(), |mut acc, item| {
            acc.push_str(&item);
            acc.push_str("&");
            acc.replace("+", "%2B")
        })
}

#[derive(Debug)]
pub enum TwilioError {
    NetworkError(http::Error),
    TransmissionError(isahc::error::Error),
    HTTPError(StatusCode),
    ParsingError,
    AuthError,
    BadRequest,
}

impl Display for TwilioError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            TwilioError::NetworkError(ref e) => e.fmt(f),
            TwilioError::TransmissionError(ref e) => e.fmt(f),
            TwilioError::HTTPError(ref s) => write!(f, "Invalid HTTP status code: {}", s),
            TwilioError::ParsingError => f.write_str("Parsing error"),
            TwilioError::AuthError => f.write_str("Missing `X-Twilio-Signature` header in request"),
            TwilioError::BadRequest => f.write_str("Bad request"),
        }
    }
}

impl Error for TwilioError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match *self {
            TwilioError::NetworkError(ref e) => Some(e),
            _ => None,
        }
    }
}

pub trait FromMap {
    fn from_map(m: BTreeMap<String, String>) -> Result<Box<Self>, TwilioError>;
}

impl Client {
    pub fn new(account_id: &str, auth_token: &str) -> Client {
        Client {
            account_id: account_id.to_string(),
            auth_token: auth_token.to_string(),
        }
    }

    async fn send_request<T>(
        &self,
        method: http::Method,
        endpoint: &str,
        params: &[(&str, &str)],
    ) -> Result<T, TwilioError>
    where
        T: serde::de::DeserializeOwned + std::marker::Unpin,
    {
        let url = format!(
            "https://api.twilio.com/2010-04-01/Accounts/{}/{}.json",
            self.account_id, endpoint
        );
        let req = isahc::Request::builder()
            .method(method)
            .uri(&url)
            .header(
                CONTENT_TYPE,
                HeaderValue::from_static("application/x-www-form-urlencoded"),
            )
            .authentication(Authentication::basic())
            .credentials(Credentials::new(
                self.account_id.clone(),
                self.auth_token.clone(),
            ))
            .body(AsyncBody::from(url_encode(params)))
            .map_err(|e| TwilioError::NetworkError(e))?;

        let mut resp = isahc::send_async(req)
            .await
            .map_err(TwilioError::TransmissionError)?;

        match resp.status() {
            StatusCode::CREATED | StatusCode::OK => {
                let value: T = resp.json().await.map_err(|_| TwilioError::ParsingError)?;
                Ok(value)
            }
            other => return Err(TwilioError::HTTPError(other)),
        }
    }

    #[cfg(feature = "webhook")]
    pub async fn respond_to_webhook<T: FromMap, F>(
        &self,
        req: http::Request<&[u8]>,
        mut logic: F,
    ) -> http::Response<String>
    where
        F: FnMut(T) -> twiml::Twiml,
    {
        let o: T = match self.parse_request::<T>(req).await {
            Ok(obj) => *obj,
            Err(_) => {
                let mut res = http::Response::new("Error.".to_string());
                *res.status_mut() = StatusCode::BAD_REQUEST;
                return res;
            }
        };

        let t = logic(o);
        let body = t.as_twiml();
        let len = body.len() as u64;
        let mut res = http::Response::new(body);
        res.headers_mut().insert(
            CONTENT_TYPE,
            HeaderValue::from_static(mime::TEXT_XML.as_ref()),
        );
        res.headers_mut().insert(CONTENT_LENGTH, len.into());
        res
    }
}