├── .gitignore ├── Cargo.toml ├── examples ├── send_message.rs └── make_call.rs ├── src ├── serde_helper.rs ├── lib.rs ├── messages.rs └── calls.rs ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | .vscode/ 5 | .idea/ 6 | *.iml 7 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "twilio_rust" 3 | version = "0.1.0" 4 | authors = ["Ameya Lokare "] 5 | 6 | [dependencies] 7 | hyper = "0.11" 8 | hyper-tls = "0.1.2" 9 | futures = "0.1" 10 | tokio-core = "0.1" 11 | serde = "1.0" 12 | serde_json = "1.0" 13 | serde_derive = "1.0" 14 | chrono = { version = "0.4", features = ["serde"] } 15 | url = "1.5.1" 16 | -------------------------------------------------------------------------------- /examples/send_message.rs: -------------------------------------------------------------------------------- 1 | extern crate twilio_rust; 2 | extern crate tokio_core; 3 | 4 | use std::env; 5 | use tokio_core::reactor::Core; 6 | use twilio_rust::Client; 7 | use twilio_rust::messages::{Messages, OutboundMessageBuilder, MessageFrom}; 8 | 9 | fn main() { 10 | 11 | let from_num = env::var("FROM_NUMBER").expect("FROM_NUMBER must be set to a valid caller ID for your account"); 12 | let to_num = env::var("TO_NUMBER").expect("TO_NUMBER must be set to the number you want to send the message to"); 13 | 14 | // Create the tokio event loop 15 | let mut core = Core::new().unwrap(); 16 | 17 | // Create the twilio client 18 | let client = Client::new_from_env(&core.handle()).unwrap(); 19 | 20 | let messages = Messages::new(&client); 21 | 22 | // Create the outbound SMS 23 | let outbound_sms = OutboundMessageBuilder::new_sms( 24 | MessageFrom::From(&from_num), 25 | &to_num, 26 | "Hello from Rust!" 27 | ).build(); 28 | 29 | let work = messages.send_message(&outbound_sms); 30 | let sms = core.run(work).unwrap(); 31 | println!("Queued outbound SMS {}", sms.sid); 32 | } 33 | -------------------------------------------------------------------------------- /src/serde_helper.rs: -------------------------------------------------------------------------------- 1 | use serde::{self, Deserialize, Deserializer}; 2 | use serde_json::Value; 3 | use serde::de::Error; 4 | use chrono::prelude::*; 5 | 6 | pub fn deserialize_rfc2822<'de, D>(deserializer: D) -> Result>, D::Error> 7 | where 8 | D: Deserializer<'de>, 9 | { 10 | let value = Value::deserialize(deserializer)?; 11 | match value { 12 | Value::Null => Ok(None), 13 | Value::String(s) => DateTime::parse_from_rfc2822(&s) 14 | .map(|dt| dt.with_timezone(&Utc)) 15 | .map_err(serde::de::Error::custom) 16 | .map(|dt| Some(dt)), 17 | _ => Err(Error::custom(String::from("Expected string or null"))), 18 | } 19 | } 20 | 21 | pub fn deserialize_str_to_u32<'de, D>(deserializer: D) -> Result, D::Error> 22 | where D: Deserializer<'de> { 23 | let value = Value::deserialize(deserializer)?; 24 | match value { 25 | Value::Null => Ok(None), 26 | Value::String(s) => s.parse::() 27 | .map(|x| Some(x)) 28 | .map_err(serde::de::Error::custom), 29 | _ => Err(Error::custom(String::from("Expected string or null"))), 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /examples/make_call.rs: -------------------------------------------------------------------------------- 1 | extern crate twilio_rust; 2 | extern crate tokio_core; 3 | extern crate url; 4 | 5 | use std::env; 6 | use tokio_core::reactor::Core; 7 | use twilio_rust::Client; 8 | use twilio_rust::calls::{Calls, OutboundCallBuilder}; 9 | use url::Url; 10 | 11 | fn main() { 12 | 13 | let from_num = env::var("FROM_NUMBER").expect("FROM_NUMBER must be set to a valid caller ID for your account"); 14 | let to_num = env::var("TO_NUMBER").expect("TO_NUMBER must be set to the number you want to call"); 15 | 16 | // Create the tokio event loop 17 | let mut core = Core::new().unwrap(); 18 | 19 | // Create the twilio client 20 | let client = Client::new_from_env(&core.handle()).unwrap(); 21 | 22 | let calls = Calls::new(&client); 23 | let cb_url = Url::parse("http://twimlets.com/echo?\ 24 | Twiml=%3CResponse%3E%3CSay%3EHello+Rust.%3C%2FSay%3E%3C%2FResponse%3E") 25 | .unwrap(); 26 | 27 | // Create the outbound call 28 | let outbound_call = OutboundCallBuilder::new(&from_num, &to_num , &cb_url).build(); 29 | 30 | let work = calls.make_call(&outbound_call); 31 | let call = core.run(work).unwrap(); 32 | println!("Queued outbound call {}", call.sid); 33 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # twilio_rust 2 | A rust-lang client library for Twilio based on [hyper.rs](https://hyper.rs/). As such, network I/O is done asynchronously 3 | and all results are returned as futures. 4 | 5 | # Getting started 6 | 7 | Let's start with an example of sending an SMS (You can run this example with `cargo run --example send_message`). 8 | 9 | You will need your Twilio credentials first: 10 | ```bash 11 | export ACCOUNT_SID= 12 | export AUTH_TOKEN= 13 | ``` 14 | To send an SMS, you will also need a "from" number i.e a valid callerId in your Twilio accout, and the "to" number i.e the number you want to send the message to: 15 | ```bash 16 | export FROM_NUMBER= 17 | export TO_NUMBER= 18 | ``` 19 | 20 | ```rust 21 | let from_num = env::var("FROM_NUMBER").expect("FROM_NUMBER must be set to a valid caller ID for your account"); 22 | let to_num = env::var("TO_NUMBER").expect("TO_NUMBER must be set to the number you want to send the message to"); 23 | // Create the tokio event loop 24 | let mut core = Core::new().unwrap(); 25 | 26 | // Create the twilio client 27 | let client = Client::new_from_env(&core.handle()).unwrap(); 28 | 29 | let messages = Messages::new(&client); 30 | 31 | // Create the outbound SMS 32 | let outbound_sms = OutboundMessageBuilder::new_sms( 33 | MessageFrom::From(&from_num), 34 | &to_num, 35 | "Hello from Rust!" 36 | ).build(); 37 | 38 | let work = messages.send_message(&outbound_sms); 39 | let sms = core.run(work).unwrap(); 40 | println!("Queued outbound SMS {}", sms.sid); 41 | ``` 42 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate chrono; 2 | extern crate futures; 3 | extern crate hyper; 4 | extern crate hyper_tls; 5 | extern crate serde; 6 | #[macro_use] 7 | extern crate serde_derive; 8 | extern crate serde_json; 9 | extern crate tokio_core; 10 | extern crate url; 11 | 12 | use std::str; 13 | use std::str::FromStr; 14 | use std::option::Option; 15 | use std::env; 16 | use std::io; 17 | use futures::{Future, Stream, future}; 18 | use tokio_core::reactor::Handle; 19 | use hyper::client::{FutureResponse, HttpConnector}; 20 | use hyper_tls::HttpsConnector; 21 | use hyper::{Body, Request, Uri, StatusCode}; 22 | use hyper::header::{Authorization, Basic}; 23 | use serde_json::value::Value; 24 | 25 | pub const BASE_URI: &str = "https://api.twilio.com"; 26 | 27 | pub mod calls; 28 | pub mod messages; 29 | mod serde_helper; 30 | 31 | 32 | pub struct Client { 33 | account_sid: String, 34 | auth_token: String, 35 | client: hyper::Client, Body>, 36 | } 37 | 38 | #[derive(Debug)] 39 | pub enum TwilioError { 40 | Hyper(hyper::error::Error), 41 | Serde(serde_json::Error), 42 | BadResponse(hyper::Response), 43 | MalformedResponse, 44 | } 45 | 46 | pub struct Page { 47 | pub items: Vec, 48 | pub next_page_uri: Option, 49 | } 50 | 51 | pub trait ToUrlEncoded { 52 | fn to_url_encoded(&self) -> String; 53 | } 54 | 55 | impl Client { 56 | pub fn new(account_sid: &str, auth_token: &str, handle: &Handle) -> Result { 57 | let client = hyper::Client::configure() 58 | .connector(HttpsConnector::new(4, handle).unwrap()) 59 | .build(handle); 60 | Ok(Client { 61 | account_sid: account_sid.to_string(), 62 | auth_token: auth_token.to_string(), 63 | client: client, 64 | }) 65 | } 66 | 67 | pub fn new_from_env(handle: &Handle) -> Result { 68 | let account_sid = env::var("ACCOUNT_SID").expect("ACCOUNT_SID env variable must be set!"); 69 | let auth_token = env::var("AUTH_TOKEN").expect("AUTH_TOKEN env variable must be set!"); 70 | Self::new(&account_sid, &auth_token, handle) 71 | } 72 | 73 | fn send_request(&self, mut req: Request) -> FutureResponse { 74 | req.headers_mut().set(Authorization(Basic { 75 | username: self.account_sid.to_owned(), 76 | password: Some(self.auth_token.to_owned()), 77 | })); 78 | self.client.request(req) 79 | } 80 | 81 | fn make_req<'de, T>(&self, req: Request) -> Box + 'de> 82 | where T: 'de + serde::de::DeserializeOwned 83 | { 84 | let fut = self.send_request(req) 85 | .map_err(|err| TwilioError::Hyper(err)) 86 | .and_then(|res| { 87 | match res.status() { 88 | StatusCode::Ok | StatusCode::Created => future::ok(res), 89 | _ => future::err(TwilioError::BadResponse(res)), 90 | } 91 | }) 92 | .and_then(|res| { 93 | res.body().concat2().map_err(|err| TwilioError::Hyper(err)) 94 | }) 95 | .and_then(move |body| { 96 | let call_res = serde_json::from_slice(&body).map_err(|err| TwilioError::Serde(err)); 97 | future::result(call_res) 98 | }); 99 | Box::new(fut) 100 | } 101 | 102 | fn get_page(&self, req: Request) -> Box, Error = TwilioError>> { 103 | let fut = self.send_request(req) 104 | .map_err(|err| TwilioError::Hyper(err)) 105 | .and_then(|res| { 106 | res.body().concat2().map_err(|err| TwilioError::Hyper(err)) 107 | }) 108 | .and_then(move |body| { 109 | let call_res: Result = serde_json::from_slice(&body) 110 | .map_err(|err| TwilioError::Serde(err)); 111 | let final_res = call_res.and_then(move|v| { 112 | let next_page_uri = match v["next_page_uri"] { 113 | Value::String(ref uri) => Uri::from_str(&format!("{}{}", BASE_URI, uri)).ok(), 114 | _ => None, 115 | }; 116 | v.get("calls") 117 | .ok_or(TwilioError::MalformedResponse) 118 | .and_then(move |v| v.as_array().ok_or(TwilioError::MalformedResponse)) 119 | .map(move|calls| { 120 | let des_calls: Vec = calls.to_owned().into_iter().map(move|c| { 121 | let call: calls::Call = serde_json::from_value(c).unwrap(); // XXX: figure out if we should quit even if a single result is bad 122 | call 123 | }).collect(); 124 | Page { 125 | items: des_calls, 126 | next_page_uri, 127 | } 128 | }) 129 | }); 130 | future::result(final_res) 131 | }); 132 | Box::new(fut) 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/messages.rs: -------------------------------------------------------------------------------- 1 | extern crate hyper; 2 | 3 | use ::{Client, ToUrlEncoded}; 4 | use url::{form_urlencoded, Url}; 5 | use chrono::prelude::*; 6 | use serde_helper; 7 | use hyper::{Method, Request}; 8 | use hyper::header::{ContentType, ContentLength}; 9 | use futures::Future; 10 | 11 | pub struct Messages<'a> { 12 | client: &'a Client, 13 | } 14 | 15 | #[derive(Debug, Deserialize, PartialEq)] 16 | #[serde(rename_all = "lowercase")] 17 | pub enum MessageStatus { 18 | Accepted, 19 | Queued, 20 | Sending, 21 | Sent, 22 | Failed, 23 | Delivered, 24 | Undelivered, 25 | Receiving, 26 | Received, 27 | } 28 | 29 | #[derive(Debug, Deserialize, PartialEq)] 30 | #[serde(rename_all = "kebab-case")] 31 | pub enum MessageDirection { 32 | Inbound, 33 | OutboundApi, 34 | OutboundCall, 35 | OutboundReply, 36 | } 37 | 38 | 39 | #[derive(Deserialize)] 40 | pub struct Message { 41 | pub sid: String, 42 | pub account_sid: String, 43 | pub messaging_service_sid: Option, 44 | pub from: String, 45 | pub to: String, 46 | pub body: String, 47 | #[serde(deserialize_with = "serde_helper::deserialize_str_to_u32")] pub num_segments: Option, 48 | pub status: MessageStatus, 49 | pub error_code: Option, 50 | pub error_message: Option, 51 | pub direction: MessageDirection, 52 | pub price: Option, 53 | pub price_unit: Option, 54 | #[serde(deserialize_with = "serde_helper::deserialize_rfc2822")] pub date_created: Option>, 55 | #[serde(deserialize_with = "serde_helper::deserialize_rfc2822")] pub date_updated: Option>, 56 | #[serde(deserialize_with = "serde_helper::deserialize_rfc2822")] pub date_sent: Option>, 57 | } 58 | 59 | #[derive(Copy, Clone)] 60 | pub enum MessageBody<'a> { 61 | SMS(&'a str), 62 | MMS(&'a Url), 63 | } 64 | 65 | #[derive(Copy, Clone)] 66 | pub enum MessageFrom<'a> { 67 | From(&'a str), 68 | MessagingServiceSid(&'a str), 69 | } 70 | 71 | pub struct OutboundMessage<'a> { 72 | to: &'a str, 73 | from: MessageFrom<'a>, 74 | body: MessageBody<'a>, 75 | status_callback: Option<&'a Url>, 76 | application_sid: Option<&'a str>, 77 | max_price: Option<&'a str>, 78 | provide_feedback: bool, 79 | validity_period: Option, 80 | } 81 | 82 | pub struct OutboundMessageBuilder<'a> { 83 | to: &'a str, 84 | from: MessageFrom<'a>, 85 | body: MessageBody<'a>, 86 | status_callback: Option<&'a Url>, 87 | application_sid: Option<&'a str>, 88 | max_price: Option<&'a str>, 89 | provide_feedback: bool, 90 | validity_period: Option, 91 | } 92 | 93 | impl<'a> OutboundMessageBuilder<'a> { 94 | pub fn new_sms(from: MessageFrom<'a>, to: &'a str, body: &'a str) -> OutboundMessageBuilder<'a> { 95 | OutboundMessageBuilder { 96 | from, 97 | to, 98 | body: MessageBody::SMS(body), 99 | status_callback: None, 100 | application_sid: None, 101 | max_price: None, 102 | provide_feedback: false, 103 | validity_period: None, 104 | } 105 | } 106 | 107 | pub fn new_mms(from: MessageFrom<'a>, to: &'a str, body: &'a Url) -> OutboundMessageBuilder<'a> { 108 | OutboundMessageBuilder { 109 | from, 110 | to, 111 | body: MessageBody::MMS(body), 112 | status_callback: None, 113 | application_sid: None, 114 | max_price: None, 115 | provide_feedback: false, 116 | validity_period: None, 117 | } 118 | } 119 | 120 | pub fn with_status_callback(&mut self, url: &'a Url) -> &mut Self { 121 | self.status_callback = Some(url); 122 | self 123 | } 124 | 125 | pub fn with_application_sid(&mut self, application_sid: &'a str) -> &mut Self { 126 | self.application_sid = Some(application_sid); 127 | self 128 | } 129 | 130 | pub fn with_max_price(&mut self, max_price: &'a str) -> &mut Self { 131 | self.max_price = Some(max_price); 132 | self 133 | } 134 | 135 | pub fn with_provide_feedback(&mut self, provide_feedback: bool) -> &mut Self { 136 | self.provide_feedback = provide_feedback; 137 | self 138 | } 139 | 140 | pub fn with_validity_period(&mut self, validity_period: u32) -> &mut Self { 141 | self.validity_period = Some(validity_period); 142 | self 143 | } 144 | 145 | pub fn build(&self) -> OutboundMessage<'a> { 146 | OutboundMessage { 147 | from: self.from, 148 | to: self.to, 149 | body: self.body, 150 | status_callback: self.status_callback, 151 | application_sid: self.application_sid, 152 | max_price: self.max_price, 153 | provide_feedback: self.provide_feedback, 154 | validity_period: self.validity_period, 155 | } 156 | } 157 | } 158 | 159 | impl<'a> ToUrlEncoded for OutboundMessage<'a> { 160 | 161 | fn to_url_encoded(&self) -> String { 162 | let mut encoder = form_urlencoded::Serializer::new(String::new()); 163 | encoder.append_pair("To", self.to); 164 | 165 | let (name, value) = match self.from { 166 | MessageFrom::From(x) => ("From", x), 167 | MessageFrom::MessagingServiceSid(x) => ("MessagingServiceSid", x), 168 | }; 169 | 170 | encoder.append_pair(name, value); 171 | 172 | let (name, value) = match self.body { 173 | MessageBody::SMS(x) => ("Body", x), 174 | MessageBody::MMS(x) => ("MediaUrl", x.as_str()), 175 | }; 176 | 177 | encoder.append_pair(name, value); 178 | 179 | if let Some(url) = self.status_callback { 180 | encoder.append_pair("StatusCallback", url.as_str()); 181 | } 182 | 183 | if let Some(application_sid) = self.application_sid { 184 | encoder.append_pair("ApplicationSid", application_sid); 185 | } 186 | 187 | if let Some(max_price) = self.max_price { 188 | encoder.append_pair("MaxPrice", max_price); 189 | } 190 | 191 | if self.provide_feedback { 192 | encoder.append_pair("ProvideFeedback", "true"); 193 | } 194 | 195 | if let Some(validity_period) = self.validity_period { 196 | encoder.append_pair("ValidityPeriod", &validity_period.to_string()); 197 | } 198 | 199 | 200 | encoder.finish() 201 | } 202 | } 203 | 204 | impl<'a> Messages<'a> { 205 | 206 | pub fn new(client: &'a Client) -> Messages { 207 | Messages { client } 208 | } 209 | 210 | pub fn send_message(&self, message: &'a OutboundMessage) -> Box> { 211 | let encoded_params = message.to_url_encoded(); 212 | let uri = format!( 213 | "{}/2010-04-01/Accounts/{}/Messages.json", 214 | ::BASE_URI, 215 | self.client.account_sid).parse().unwrap(); 216 | let mut req = Request::new(Method::Post, uri); 217 | req.headers_mut().set(ContentType::form_url_encoded()); 218 | req.headers_mut().set(ContentLength(encoded_params.len() as u64)); 219 | req.set_body(encoded_params.into_bytes()); 220 | self.client.make_req(req) 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/calls.rs: -------------------------------------------------------------------------------- 1 | extern crate hyper; 2 | 3 | use std::str; 4 | use ::{Client, ToUrlEncoded}; 5 | use serde_helper; 6 | use chrono::prelude::*; 7 | use futures::{Future, future}; 8 | use hyper::{Body, Method, Request}; 9 | use hyper::header::{ContentType, ContentLength}; 10 | use url::{form_urlencoded, Url}; 11 | 12 | pub struct Calls<'a> { 13 | client: &'a Client, 14 | } 15 | 16 | #[derive(Deserialize)] 17 | pub struct Call { 18 | pub sid: String, 19 | pub account_sid: String, 20 | pub parent_call_sid: Option, 21 | pub from: String, 22 | pub to: String, 23 | pub phone_number_sid: Option, 24 | pub status: CallStatus, 25 | pub duration: Option, 26 | pub answered_by: Option, 27 | pub price: Option, 28 | pub price_unit: Option, 29 | pub direction: Option, 30 | pub forwarded_from: Option, 31 | pub to_formatted: Option, 32 | pub from_formatted: Option, 33 | pub caller_name: Option, 34 | #[serde(deserialize_with = "serde_helper::deserialize_rfc2822")] pub date_created: Option>, 35 | #[serde(deserialize_with = "serde_helper::deserialize_rfc2822")] pub date_updated: Option>, 36 | #[serde(deserialize_with = "serde_helper::deserialize_rfc2822")] pub start_time: Option>, 37 | #[serde(deserialize_with = "serde_helper::deserialize_rfc2822")] pub end_time: Option>, 38 | } 39 | 40 | #[derive(Debug, Deserialize, PartialEq)] 41 | #[serde(rename_all = "lowercase")] 42 | pub enum CallStatus { 43 | Queued, 44 | Ringing, 45 | #[serde(rename = "in-progress")] InProgress, 46 | Canceled, 47 | Completed, 48 | Busy, 49 | Failed, 50 | } 51 | 52 | #[derive(Debug, Deserialize, PartialEq)] 53 | #[serde(rename_all = "kebab-case")] 54 | pub enum Direction { 55 | Inbound, 56 | OutboundApi, 57 | OutboundDial, 58 | TrunkingTerminating, 59 | TrunkingOriginating, 60 | } 61 | 62 | #[derive(Copy, Clone)] 63 | pub enum TwimlSource<'a> { 64 | Url(&'a Url), 65 | ApplicationSid(&'a str), 66 | } 67 | 68 | #[derive(Copy, Clone)] 69 | pub enum CallbackMethod { 70 | Post, 71 | Get, 72 | } 73 | 74 | impl CallbackMethod { 75 | pub fn name(&self) -> &str { 76 | match *self { 77 | CallbackMethod::Post => "POST", 78 | CallbackMethod::Get => "GET", 79 | } 80 | } 81 | } 82 | 83 | pub enum StatusCallbackEvent { 84 | Initiated, 85 | Ringing, 86 | Answered, 87 | Completed, 88 | } 89 | 90 | impl StatusCallbackEvent { 91 | pub fn name(&self) -> &str { 92 | match *self { 93 | StatusCallbackEvent::Initiated => "initiated", 94 | StatusCallbackEvent::Ringing => "ringing", 95 | StatusCallbackEvent::Answered => "answered", 96 | StatusCallbackEvent::Completed => "completed", 97 | } 98 | } 99 | } 100 | 101 | #[derive(Copy, Clone)] 102 | pub enum RecordingChannel { 103 | Mono, 104 | Dual, 105 | } 106 | 107 | impl RecordingChannel { 108 | pub fn name(&self) -> &str { 109 | match *self { 110 | RecordingChannel::Mono => "mono", 111 | RecordingChannel::Dual => "dual", 112 | } 113 | } 114 | } 115 | 116 | #[derive(Copy, Clone)] 117 | pub enum ModifyCallStatus { 118 | Canceled, 119 | Completed, 120 | } 121 | 122 | impl ModifyCallStatus { 123 | pub fn name(&self) -> &str { 124 | match *self { 125 | ModifyCallStatus::Canceled => "canceled", 126 | ModifyCallStatus::Completed => "completed", 127 | } 128 | } 129 | } 130 | 131 | pub struct OutboundCall<'a> { 132 | from: &'a str, 133 | to: &'a str, 134 | twiml_source: TwimlSource<'a>, 135 | method: Option, 136 | fallback_url: Option<&'a Url>, 137 | fallback_method: Option, 138 | status_callback: Option<&'a Url>, 139 | status_callback_method: Option, 140 | status_callback_event: &'a [StatusCallbackEvent], 141 | send_digits: Option<&'a str>, 142 | timeout: Option, 143 | record: Option, 144 | recording_channels: Option, 145 | recording_status_callback: Option<&'a Url>, 146 | recording_status_callback_method: Option, 147 | } 148 | 149 | pub struct OutboundCallBuilder<'a> { 150 | from: &'a str, 151 | to: &'a str, 152 | twiml_source: TwimlSource<'a>, 153 | method: Option, 154 | fallback_url: Option<&'a Url>, 155 | fallback_method: Option, 156 | status_callback: Option<&'a Url>, 157 | status_callback_method: Option, 158 | status_callback_event: &'a [StatusCallbackEvent], 159 | send_digits: Option<&'a str>, 160 | timeout: Option, 161 | record: Option, 162 | recording_channels: Option, 163 | recording_status_callback: Option<&'a Url>, 164 | recording_status_callback_method: Option, 165 | } 166 | 167 | impl<'a> OutboundCallBuilder<'a> { 168 | pub fn new(from: &'a str, to: &'a str, url: &'a Url) -> OutboundCallBuilder<'a> { 169 | OutboundCallBuilder { 170 | from, 171 | to, 172 | twiml_source: TwimlSource::Url(url), 173 | method: None, 174 | fallback_url: None, 175 | fallback_method: None, 176 | status_callback: None, 177 | status_callback_method: None, 178 | status_callback_event: &[], 179 | send_digits: None, 180 | timeout: None, 181 | record: None, 182 | recording_channels: None, 183 | recording_status_callback: None, 184 | recording_status_callback_method: None, 185 | } 186 | } 187 | 188 | pub fn with_method(&mut self, method: CallbackMethod) -> &mut Self { 189 | self.method = Some(method); 190 | self 191 | } 192 | 193 | pub fn with_fallback_url(&mut self, fallback_url: &'a Url) -> &mut Self { 194 | self.fallback_url = Some(fallback_url); 195 | self 196 | } 197 | 198 | pub fn with_fallback_method(&mut self, fallback_method: CallbackMethod) -> &mut Self { 199 | self.fallback_method = Some(fallback_method); 200 | self 201 | } 202 | 203 | pub fn with_status_callback(&mut self, status_callback: &'a Url) -> &mut Self { 204 | self.status_callback = Some(status_callback); 205 | self 206 | } 207 | 208 | pub fn with_status_callback_events(&mut self, events: &'a [StatusCallbackEvent]) -> &mut Self { 209 | self.status_callback_event = events; 210 | self 211 | } 212 | 213 | pub fn with_send_digits(&mut self, digits: &'a str) -> &mut Self { 214 | self.send_digits = Some(digits); 215 | self 216 | } 217 | 218 | pub fn with_timeout(&mut self, timeout: u32) -> &mut Self { 219 | self.timeout = Some(timeout); 220 | self 221 | } 222 | 223 | pub fn with_record(&mut self, record: bool) -> &mut Self { 224 | self.record = Some(record); 225 | self 226 | } 227 | 228 | pub fn with_recording_channels(&mut self, recording_channels: RecordingChannel) -> &mut Self { 229 | self.recording_channels = Some(recording_channels); 230 | self 231 | } 232 | 233 | pub fn with_recording_status_callback(&mut self, url: &'a Url) -> &mut Self { 234 | self.recording_status_callback = Some(url); 235 | self 236 | } 237 | 238 | pub fn with_recording_status_callback_method(&mut self, method: CallbackMethod) -> &mut Self { 239 | self.recording_status_callback_method = Some(method); 240 | self 241 | } 242 | 243 | pub fn build(&mut self) -> OutboundCall<'a> { 244 | OutboundCall { 245 | from: self.from, 246 | to: self.to, 247 | twiml_source: self.twiml_source, 248 | method: self.method, 249 | fallback_url: self.fallback_url, 250 | fallback_method: self.fallback_method, 251 | status_callback: self.status_callback, 252 | status_callback_method: self.status_callback_method, 253 | status_callback_event: self.status_callback_event, 254 | send_digits: self.send_digits, 255 | timeout: self.timeout, 256 | record: self.record, 257 | recording_channels: self.recording_channels, 258 | recording_status_callback: self.recording_status_callback, 259 | recording_status_callback_method: self.recording_status_callback_method, 260 | } 261 | } 262 | } 263 | 264 | impl<'a> ToUrlEncoded for OutboundCall<'a> { 265 | 266 | fn to_url_encoded(&self) -> String { 267 | let mut encoder = form_urlencoded::Serializer::new(String::new()); 268 | encoder.append_pair("From", self.from); 269 | encoder.append_pair("To", self.to); 270 | let (name, value) = match self.twiml_source { 271 | TwimlSource::Url(x) => ("Url", x.as_str()), 272 | TwimlSource::ApplicationSid(x) => ("ApplicationSid", x), 273 | }; 274 | encoder.append_pair(name, value); 275 | if let Some(ref x) = self.method { 276 | encoder.append_pair("Method", x.name()); 277 | } 278 | 279 | if let Some(url) = self.fallback_url { 280 | encoder.append_pair("FallbackUrl", url.as_str()); 281 | } 282 | if let Some(ref x) = self.fallback_method { 283 | encoder.append_pair("FallbackMethod", x.name()); 284 | } 285 | 286 | if let Some(url) = self.status_callback { 287 | encoder.append_pair("StatusCallback", url.as_str()); 288 | } 289 | if let Some(ref x) = self.status_callback_method { 290 | encoder.append_pair("StatusCallbackMethod", x.name()); 291 | } 292 | for e in self.status_callback_event.iter() { 293 | encoder.append_pair("StatusCallbackEvent", e.name()); 294 | } 295 | 296 | if let Some(digits) = self.send_digits { 297 | encoder.append_pair("SendDigits", digits); 298 | } 299 | if let Some(timeout) = self.timeout { 300 | encoder.append_pair("Timeout", &timeout.to_string()); 301 | } 302 | if let Some(record) = self.record { 303 | encoder.append_pair("Record", &record.to_string()); 304 | } 305 | if let Some(recording_channel) = self.recording_channels { 306 | encoder.append_pair("RecordingChannels", recording_channel.name()); 307 | } 308 | if let Some(recording_status_callback) = self.recording_status_callback { 309 | encoder.append_pair("RecordingStatusCallback", recording_status_callback.as_str()); 310 | } 311 | if let Some(recording_status_callback_method) = self.recording_status_callback_method { 312 | encoder.append_pair("RecordingStatusCallbackMethod", recording_status_callback_method.name()); 313 | } 314 | encoder.finish() 315 | } 316 | } 317 | 318 | impl<'a> Calls<'a> { 319 | 320 | pub fn new(client: &Client) -> Calls { 321 | Calls { client } 322 | } 323 | 324 | pub fn get_call( 325 | &self, 326 | call_sid: &str, 327 | ) -> Box> { 328 | let uri = format!( 329 | "{}/2010-04-01/Accounts/{}/Calls/{}.json", 330 | ::BASE_URI, 331 | self.client.account_sid, 332 | call_sid 333 | ).parse() 334 | .unwrap(); 335 | let req: Request = Request::new(Method::Get, uri); 336 | self.client.make_req(req) 337 | } 338 | 339 | pub fn make_call(&self, outbound_call: &OutboundCall) -> Box> { 340 | let encoded_params = outbound_call.to_url_encoded(); 341 | let uri = format!( 342 | "{}/2010-04-01/Accounts/{}/Calls.json", 343 | ::BASE_URI, 344 | self.client.account_sid).parse().unwrap(); 345 | let mut req = Request::new(Method::Post, uri); 346 | req.headers_mut().set(ContentType::form_url_encoded()); 347 | req.headers_mut().set(ContentLength(encoded_params.len() as u64)); 348 | req.set_body(encoded_params.into_bytes()); 349 | self.client.make_req(req) 350 | } 351 | 352 | pub fn get_calls(&self) -> Box, Error = ::TwilioError>> { 353 | let uri = format!( 354 | "{}/2010-04-01/Accounts/{}/Calls.json", 355 | ::BASE_URI, 356 | self.client.account_sid).parse().unwrap(); 357 | let req = Request::new(Method::Get, uri); 358 | self.client.get_page(req) 359 | } 360 | 361 | pub fn get_calls_with_page_size(&self, page_size: u16) -> Box, Error = ::TwilioError>> { 362 | let uri = format!( 363 | "{}/2010-04-01/Accounts/{}/Calls.json?PageSize={}", 364 | ::BASE_URI, 365 | self.client.account_sid, page_size).parse().unwrap(); 366 | let req = Request::new(Method::Get, uri); 367 | self.client.get_page(req) 368 | } 369 | 370 | pub fn get_next_page(&self, page: &::Page) -> Box>, Error = ::TwilioError>> { 371 | match page.next_page_uri.as_ref() { 372 | Some(uri) => { 373 | let req = Request::new(Method::Get, uri.clone()); 374 | Box::new(self.client.get_page(req).map(|p| Some(p))) 375 | }, 376 | None => Box::new(future::ok(None)) 377 | } 378 | } 379 | 380 | pub fn redirect_call(&self, call_sid: &str, redirect_url: &Url, 381 | redirect_method: Option) -> Box> { 382 | 383 | let mut encoder = form_urlencoded::Serializer::new(String::new()); 384 | encoder.append_pair("Url", redirect_url.as_str()); 385 | if let Some(method) = redirect_method { 386 | encoder.append_pair("Method", method.name()); 387 | } 388 | let params: String = encoder.finish(); 389 | let uri = format!( 390 | "{}/2010-04-01/Accounts/{}/Calls/{}.json", 391 | ::BASE_URI, 392 | self.client.account_sid, 393 | call_sid 394 | ).parse() 395 | .unwrap(); 396 | let mut req = Request::new(Method::Post, uri); 397 | req.headers_mut().set(ContentType::form_url_encoded()); 398 | req.headers_mut().set(ContentLength(params.len() as u64)); 399 | req.set_body(params.into_bytes()); 400 | self.client.make_req(req) 401 | } 402 | } 403 | 404 | #[cfg(test)] 405 | mod test { 406 | 407 | use super::*; 408 | use serde_json; 409 | 410 | #[test] 411 | fn test_callstatus_deserialize() { 412 | assert_eq!(CallStatus::Queued, serde_json::from_str("\"queued\"").unwrap()); 413 | assert_eq!(CallStatus::InProgress, serde_json::from_str("\"in-progress\"").unwrap()); 414 | } 415 | 416 | #[test] 417 | fn test_direction_deserialize() { 418 | assert_eq!(Direction::TrunkingTerminating, serde_json::from_str("\"trunking-terminating\"").unwrap()); 419 | } 420 | 421 | #[test] 422 | fn test_url_encoding() { 423 | let url = Url::parse("http://www.example.com").unwrap(); 424 | let outbound_call = OutboundCallBuilder::new("tom", "jerry", &url).build(); 425 | let url_encoded = outbound_call.to_url_encoded(); 426 | assert_eq!("From=tom&To=jerry&Url=http%3A%2F%2Fwww.example.com%2F", &url_encoded); 427 | } 428 | 429 | #[test] 430 | fn test_status_callback() { 431 | let url = Url::parse("http://www.example.com").unwrap(); 432 | let events = [StatusCallbackEvent::Answered, StatusCallbackEvent::Ringing]; 433 | let outbound_call = OutboundCallBuilder::new("tom", "jerry", &url) 434 | .with_status_callback_events(&events) 435 | .build(); 436 | let url_encoded = outbound_call.to_url_encoded(); 437 | assert_eq!("From=tom&To=jerry&Url=http%3A%2F%2Fwww.example.com%2F\ 438 | &StatusCallbackEvent=answered&StatusCallbackEvent=ringing", &url_encoded); 439 | } 440 | 441 | 442 | } --------------------------------------------------------------------------------