├── .github └── workflows │ └── actions.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── examples └── runtime.rs ├── rustfmt.toml ├── src ├── call.rs ├── conference.rs ├── error.rs ├── lib.rs ├── macros.rs ├── message.rs ├── recording.rs └── twiml.rs └── twiml ├── Cargo.toml ├── README.md └── src ├── dial.rs ├── error.rs ├── gather.rs ├── hangup.rs ├── lib.rs ├── msg.rs ├── play.rs ├── redirect.rs ├── response.rs └── say.rs /.github/workflows/actions.yml: -------------------------------------------------------------------------------- 1 | # Based on https://github.com/actions-rs/meta/blob/master/recipes/msrv.md 2 | 3 | on: [push, pull_request] 4 | 5 | name: Actions 6 | 7 | jobs: 8 | check: 9 | name: Check 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | rust: 14 | - stable 15 | - beta 16 | - nightly 17 | steps: 18 | - name: Checkout sources 19 | uses: actions/checkout@v2 20 | 21 | - name: Install toolchain 22 | uses: actions-rs/toolchain@v1 23 | with: 24 | toolchain: ${{ matrix.rust }} 25 | override: true 26 | 27 | - name: Run cargo check 28 | uses: actions-rs/cargo@v1 29 | with: 30 | command: check 31 | 32 | test: 33 | name: Test Suite 34 | runs-on: ubuntu-latest 35 | strategy: 36 | matrix: 37 | rust: 38 | - stable 39 | - beta 40 | - nightly 41 | steps: 42 | - name: Checkout sources 43 | uses: actions/checkout@v2 44 | 45 | - name: Install toolchain 46 | uses: actions-rs/toolchain@v1 47 | with: 48 | toolchain: ${{ matrix.rust }} 49 | override: true 50 | 51 | - name: Run cargo test 52 | uses: actions-rs/cargo@v1 53 | with: 54 | command: test 55 | 56 | fmt: 57 | name: Rustfmt 58 | runs-on: ubuntu-latest 59 | strategy: 60 | matrix: 61 | rust: 62 | - stable 63 | - beta 64 | steps: 65 | - name: Checkout sources 66 | uses: actions/checkout@v2 67 | 68 | - name: Install toolchain 69 | uses: actions-rs/toolchain@v1 70 | with: 71 | toolchain: ${{ matrix.rust }} 72 | override: true 73 | 74 | - name: Install rustfmt 75 | run: rustup component add rustfmt 76 | 77 | - name: Run cargo fmt 78 | uses: actions-rs/cargo@v1 79 | with: 80 | command: fmt 81 | args: --all -- --check 82 | 83 | clippy: 84 | name: Clippy 85 | runs-on: ubuntu-latest 86 | strategy: 87 | matrix: 88 | rust: 89 | - stable 90 | - beta 91 | - nightly 92 | steps: 93 | - name: Checkout sources 94 | uses: actions/checkout@v2 95 | 96 | - name: Install toolchain 97 | uses: actions-rs/toolchain@v1 98 | with: 99 | toolchain: ${{ matrix.rust }} 100 | override: true 101 | 102 | - name: Install clippy 103 | run: rustup component add clippy 104 | 105 | - name: Run cargo clippy 106 | uses: actions-rs/cargo@v1 107 | with: 108 | command: clippy 109 | args: -- -D warnings -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | 5 | rls -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "twilio-async" 3 | version = "0.6.0" 4 | description = """ 5 | An async and ergonomic wrapper around Twilio API & TwiML 6 | """ 7 | readme = "README.md" 8 | repository = "https://github.com/leshow/twilio" 9 | documentation = "https://docs.rs/tokio/0.5.0/twilio-async/" 10 | license = "MIT" 11 | keywords = ["twilio", "twiml", "api", "async", "hyper"] 12 | categories = ["network-programming", "api-bindings", "web-programming", "development-tools"] 13 | authors = ["Evan Cameron "] 14 | edition = "2021" 15 | 16 | [workspace] 17 | members = ["./", "twiml"] 18 | 19 | [dependencies] 20 | async-trait = "0.1" 21 | bytes = "1" 22 | hyper = { version = "0.14", features = ["stream", "client", "http1"] } 23 | hyper-tls = "0.5" 24 | typed-headers = "0.2" 25 | http = "0.2" 26 | url = "2.2" 27 | serde = { version = "1.0", features = ["derive"] } 28 | serde_json = "1.0" 29 | twiml = { version = "0.4", path = "twiml" } 30 | 31 | [dev-dependencies] 32 | tokio = { version = "1", features = ["full"] } 33 | 34 | [[example]] 35 | name = "runtime" 36 | path = "examples/runtime.rs" 37 | 38 | [package.metadata.docs.rs] 39 | all-features = true 40 | rustdoc-args = ["--cfg", "docsrs"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2018 Evan Cameron 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # twilio-async 2 | 3 | ## Example Usage 4 | 5 | An async and ergonomic wrapper around Twilio API & TwiML. 6 | 7 | All types can run `run()` or a similar function. They return a value that implements `Deserialize`. 8 | 9 | The `examples/` dir has up to date working example code. 10 | 11 | Messages: 12 | 13 | ```rust 14 | 15 | #[tokio::main] 16 | async fn main() -> Result<(), Box> { 17 | let twilio = Twilio::new(account_sid, token)?; 18 | // sending a message 19 | twilio.send_msg("from", "to", "Hello World").run().await?; 20 | // sending a body-less message with media 21 | twilio 22 | .send_msg("from", "to", "body") 23 | .media("http://i0.kym-cdn.com/photos/images/newsfeed/000/377/946/0b9.jpg") 24 | .run().await?; 25 | // get details about a message 26 | twilio.msg("messagesid").run().await?; 27 | // redact a message 28 | twilio.msg("messagesid").redact().await?; 29 | // get a msg media url 30 | twilio.msg("messagesid").media().await?; 31 | // delete a msg 32 | twilio.msg("messagesid").delete().await?; 33 | // get all messages 34 | twilio.msgs().run().await?; 35 | // get all messages between some time 36 | twilio.msgs().between("start date", "end date").run().await?; 37 | // get all messages on a specific date 38 | twilio.msgs().on("date").run().await?; 39 | } 40 | ``` 41 | 42 | Calls: 43 | 44 | ```rust 45 | let twilio = Twilio::new(env::var("TWILIO_SID")?, env::var("TWILIO_TOKEN")?)?; 46 | let (status, resp) = twilio 47 | .call("from", "to", "http://demo.twilio.com/docs/voice.xml") 48 | .run().await?; 49 | ``` 50 | 51 | Twiml: 52 | 53 | ```rust 54 | use twilio_async::twiml::Response; 55 | 56 | let resp = Response::new() 57 | .say("Hello World") // builder pattern also supports say(Say::new("Hello World").lang("de")...) 58 | .play("https://api.twilio.com/Cowbell.mp3") 59 | .build(); 60 | let s = "Hello Worldhttps://api.twilio.com/Cowbell.mp3"; 61 | assert_eq!(resp.unwrap(), s.to_string()); 62 | ``` 63 | 64 | ## Contributing 65 | 66 | There is untested code for conferences/recordings. 67 | 68 | The TwiML work is complete and has some test coverage. 69 | 70 | PRs and suggestions are welcome. 71 | -------------------------------------------------------------------------------- /examples/runtime.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | use std::{env, error::Error}; 3 | use twilio_async::{MsgResp, Twilio, TwilioJson, TwilioRequest}; 4 | 5 | type Result = std::result::Result>; 6 | 7 | #[tokio::main] 8 | async fn main() -> Result<()> { 9 | let twilio = Twilio::new(env::var("TWILIO_SID")?, env::var("TWILIO_TOKEN")?)?; 10 | println!("{:?}", twilio); 11 | try_msg(twilio).await?; 12 | // try_call(twilio).await?; 13 | // try_conference(twilio).await?; 14 | Ok(()) 15 | } 16 | 17 | async fn try_conference(twilio: Twilio) -> Result<()> { 18 | let _resp = twilio.conferences().run().await?; 19 | 20 | let resp = twilio 21 | .conference("EH5bc4f5c62684f43d0acadb3d88a43e38") 22 | .run() 23 | .await?; 24 | 25 | println!("{:?}", resp); 26 | Ok(()) 27 | } 28 | 29 | async fn try_msg(twilio: Twilio) -> Result<()> { 30 | let num = env::var("OUTBOUND_NUM")?; 31 | // sending a message 32 | let resp = twilio.send_msg(&num, &num, "Hello World").run().await?; 33 | 34 | println!("{:?}", resp); 35 | // sending with media 36 | let resp = twilio 37 | .send_msg("18193074013", &num, "foo") 38 | .media("http://i0.kym-cdn.com/photos/images/newsfeed/000/377/946/0b9.jpg") 39 | .run() 40 | .await?; 41 | // get individual msg 42 | if let TwilioJson::Success(MsgResp { sid, .. }) = resp { 43 | let resp = twilio.msg(&sid).run().await?; 44 | println!("{:?}", resp); 45 | } 46 | // delete a message 47 | twilio 48 | .msg("SM5585720d3f244b1cb054862040b7b858") 49 | .delete() 50 | .await?; 51 | // there's also redact() 52 | // get a msg media url 53 | // twilio.msg("messagesid").media()?; 54 | // // get all messages 55 | let resp = twilio.msgs().run().await?; 56 | println!("{:?}", resp); 57 | // // get all messages between some time 58 | let resp = twilio 59 | .msgs() 60 | .between("2010-01-01", "2020-01-01") 61 | .run() 62 | .await?; 63 | println!("{:?}", resp); 64 | // // get all messages on a specific date 65 | let resp = twilio.msgs().on("2020-01-01").run().await?; 66 | println!("{:?}", resp); 67 | Ok(()) 68 | } 69 | 70 | async fn try_call(twilio: Twilio) -> Result<()> { 71 | let resp = twilio 72 | .call( 73 | "18193074013", 74 | &env::var("OUTBOUND_NUM")?, 75 | "http://demo.twilio.com/docs/voice.xml", 76 | ) 77 | .run() 78 | .await?; 79 | 80 | println!("{:?}", resp); 81 | Ok(()) 82 | } 83 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | condense_wildcard_suffixes = true 2 | merge_imports = true 3 | merge_derives = true 4 | normalize_comments = true 5 | reorder_impl_items = true 6 | use_field_init_shorthand = true 7 | use_try_shorthand = true 8 | wrap_comments = true 9 | unstable_features = true 10 | format_code_in_doc_comments = true -------------------------------------------------------------------------------- /src/call.rs: -------------------------------------------------------------------------------- 1 | use super::{encode_pairs, Execute, Twilio, TwilioErr, TwilioJson, TwilioRequest, TwilioResp}; 2 | use async_trait::async_trait; 3 | use hyper::{self, Method}; 4 | use serde::Deserialize; 5 | 6 | #[derive(Debug, Default)] 7 | pub struct Call<'a> { 8 | from: &'a str, 9 | to: &'a str, 10 | url: &'a str, 11 | sid: Option<&'a str>, 12 | callerid: Option<&'a str>, 13 | machine_detection: Option, 14 | record: Option, 15 | send_digits: Option<&'a str>, 16 | status_callback: Option<&'a str>, 17 | callback_event: Option, 18 | timeout: Option<&'a str>, 19 | } 20 | 21 | #[derive(Debug)] 22 | pub enum CallbackEvent { 23 | Initiated, 24 | Ringing, 25 | Answered, 26 | Completed, 27 | } 28 | 29 | use self::CallbackEvent::*; 30 | 31 | impl<'a> Call<'a> { 32 | pub fn new(from: &'a str, to: &'a str, url: &'a str) -> Call<'a> { 33 | Call { 34 | from, 35 | to, 36 | url, 37 | ..Call::default() 38 | } 39 | } 40 | } 41 | 42 | impl<'a> ToString for Call<'a> { 43 | fn to_string(&self) -> String { 44 | let mut pairs = vec![("To", self.to), ("From", self.from), ("Url", self.url)]; 45 | pair!(self, sid, "ApplicationSid", pairs); 46 | pair!(self, callerid, "CallerId", pairs); 47 | if let Some(detection) = self.machine_detection { 48 | if detection { 49 | pairs.push(("MachineDetection", "Enable")); 50 | } 51 | } 52 | if let Some(record) = self.record { 53 | if record { 54 | pairs.push(("Record", "true")); 55 | } 56 | } 57 | if let Some(ref cb) = self.callback_event { 58 | let event = match *cb { 59 | Initiated => "initiated", 60 | Ringing => "ringing", 61 | Answered => "answered", 62 | Completed => "completed", 63 | }; 64 | pairs.push(("StatusCallbackEvent", event)); 65 | } 66 | pair!(self, timeout, "Timeout", pairs); 67 | pair!(self, send_digits, "SendDigits", pairs); 68 | pair!(self, status_callback, "StatusCallback", pairs); 69 | 70 | encode_pairs(pairs).unwrap() 71 | } 72 | } 73 | 74 | #[derive(Debug, Deserialize)] 75 | #[allow(non_camel_case_types)] 76 | pub enum CallStatus { 77 | queued, 78 | ringing, 79 | #[serde(rename = "in-progress")] 80 | inprogress, 81 | canceled, 82 | completed, 83 | failed, 84 | busy, 85 | #[serde(rename = "no-answer")] 86 | noanswer, 87 | } 88 | 89 | #[derive(Deserialize, Debug)] 90 | pub struct CallResp { 91 | pub from: String, 92 | pub to: String, 93 | pub sid: String, 94 | pub start_time: Option, 95 | pub status: CallStatus, 96 | pub account_sid: String, 97 | pub caller_name: Option, 98 | pub duration: Option, 99 | pub price: Option, 100 | pub price_unit: String, 101 | pub uri: String, 102 | pub date_created: Option, 103 | pub end_time: Option, 104 | pub phone_number_sid: String, 105 | pub direction: Direction, 106 | } 107 | 108 | #[derive(Debug, Deserialize)] 109 | #[allow(non_camel_case_types)] 110 | pub enum Direction { 111 | inbound, 112 | #[serde(rename = "outbound-api")] 113 | outbound_api, 114 | #[serde(rename = "outbound-dial")] 115 | outbound_dial, 116 | #[serde(rename = "trunking-terminating")] 117 | trunking_terminating, 118 | #[serde(rename = "trunking-originating")] 119 | trunking_originating, 120 | } 121 | 122 | #[derive(Debug)] 123 | pub struct SendCall<'a> { 124 | pub call: Call<'a>, 125 | pub client: &'a Twilio, 126 | } 127 | 128 | execute!(SendCall); 129 | 130 | #[async_trait] 131 | impl<'a> TwilioRequest for SendCall<'a> { 132 | type Resp = CallResp; 133 | 134 | async fn run(&self) -> TwilioResp> { 135 | let call = self.call.to_string(); 136 | self.execute(Method::POST, "Calls.json", Some(call)).await 137 | } 138 | } 139 | 140 | impl<'a> SendCall<'a> { 141 | pub fn sid(mut self, sid: &'a str) -> SendCall<'a> { 142 | self.call.sid = Some(sid); 143 | self 144 | } 145 | 146 | pub fn callerid(mut self, callerid: &'a str) -> SendCall<'a> { 147 | self.call.callerid = Some(callerid); 148 | self 149 | } 150 | 151 | pub fn machine_detection(mut self, machine_detection: bool) -> SendCall<'a> { 152 | self.call.machine_detection = Some(machine_detection); 153 | self 154 | } 155 | 156 | pub fn record(mut self, record: bool) -> SendCall<'a> { 157 | self.call.record = Some(record); 158 | self 159 | } 160 | 161 | pub fn send_digits(mut self, send_digits: &'a str) -> SendCall<'a> { 162 | self.call.send_digits = Some(send_digits); 163 | self 164 | } 165 | 166 | pub fn status_callback(mut self, callback: &'a str) -> SendCall<'a> { 167 | self.call.status_callback = Some(callback); 168 | self 169 | } 170 | 171 | pub fn callback_event(mut self, event: CallbackEvent) -> SendCall<'a> { 172 | self.call.callback_event = Some(event); 173 | self 174 | } 175 | 176 | pub fn timeout(mut self, timeout: &'a str) -> SendCall<'a> { 177 | self.call.timeout = Some(timeout); 178 | self 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/conference.rs: -------------------------------------------------------------------------------- 1 | use super::{encode_pairs, Execute, Twilio, TwilioErr, TwilioJson, TwilioRequest, TwilioResp}; 2 | use async_trait::async_trait; 3 | use hyper::{self, Method}; 4 | use serde::Deserialize; 5 | 6 | #[derive(Debug, Default)] 7 | pub struct Conference<'a> { 8 | sid: &'a str, 9 | status: Option<&'a str>, 10 | } 11 | 12 | const COMPLETED: &str = "completed"; 13 | 14 | impl<'a> Conference<'a> { 15 | pub fn new(sid: &'a str) -> Conference<'a> { 16 | Conference { sid, status: None } 17 | } 18 | } 19 | 20 | // GET ONE CONFERENCE 21 | #[derive(Debug)] 22 | pub struct GetConference<'a> { 23 | pub conference: Conference<'a>, 24 | pub client: &'a Twilio, 25 | } 26 | 27 | impl<'a> GetConference<'a> { 28 | pub fn end(mut self) -> GetConference<'a> { 29 | self.conference.status = Some(COMPLETED); 30 | self 31 | } 32 | } 33 | 34 | execute!(GetConference); 35 | 36 | #[async_trait] 37 | impl<'a> TwilioRequest for GetConference<'a> { 38 | type Resp = ConferenceResp; 39 | 40 | async fn run(&self) -> TwilioResp> { 41 | let url = format!("Conferences/{}.json", self.conference.sid); 42 | match self.conference.status { 43 | Some(status) => { 44 | self.execute( 45 | Method::POST, 46 | url, 47 | Some(encode_pairs(&[("Status", status)]).unwrap()), 48 | ) 49 | .await 50 | } 51 | None => self.execute(Method::GET, url, None).await, 52 | } 53 | } 54 | } 55 | 56 | // GET ALL CONFERENCES 57 | #[derive(Debug)] 58 | pub struct Conferences<'a> { 59 | pub client: &'a Twilio, 60 | } 61 | 62 | execute!(Conferences); 63 | 64 | #[async_trait] 65 | impl<'a> TwilioRequest for Conferences<'a> { 66 | type Resp = ListConferencesResp; 67 | 68 | async fn run(&self) -> TwilioResp> { 69 | self.execute(Method::GET, "Conferences.json", None).await 70 | } 71 | } 72 | 73 | #[derive(Deserialize, Debug)] 74 | pub struct ListConferencesResp { 75 | pub conferences: Vec, 76 | pub end: usize, 77 | pub next_page_uri: Option, 78 | pub previous_page_uri: Option, 79 | pub uri: String, 80 | pub start: usize, 81 | pub page: usize, 82 | pub page_size: usize, 83 | } 84 | 85 | #[derive(Deserialize, Debug)] 86 | pub struct ConferenceResp { 87 | pub account_sid: String, 88 | pub date_created: Option, 89 | pub date_updated: String, 90 | pub friendly_name: String, 91 | pub region: String, 92 | pub sid: String, 93 | pub status: String, 94 | pub uri: String, 95 | } 96 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use std::{cell, error::Error, fmt, io, string}; 2 | 3 | // Errors 4 | #[derive(Debug)] 5 | pub enum TwilioErr { 6 | Io(io::Error), 7 | UrlParse(http::uri::InvalidUri), 8 | NetworkErr(hyper::Error), 9 | SerdeErr(serde_json::Error), 10 | BorrowErr(cell::BorrowMutError), 11 | Utf8Err(string::FromUtf8Error), 12 | HttpErr(http::Error), 13 | HeaderErr(typed_headers::Error), 14 | } 15 | 16 | pub use super::TwilioErr::*; 17 | 18 | pub type TwilioResult = Result; 19 | 20 | impl Error for TwilioErr { 21 | fn source(&self) -> Option<&(dyn Error + 'static)> { 22 | match *self { 23 | Io(ref e) => e.source(), 24 | SerdeErr(ref e) => e.source(), 25 | UrlParse(ref e) => e.source(), 26 | NetworkErr(ref e) => e.source(), 27 | BorrowErr(ref e) => e.source(), 28 | Utf8Err(ref e) => e.source(), 29 | HttpErr(ref e) => e.source(), 30 | HeaderErr(ref e) => e.source(), 31 | } 32 | } 33 | } 34 | 35 | impl fmt::Display for TwilioErr { 36 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 37 | match *self { 38 | Io(ref e) => write!(f, "IO Error: {}", e), 39 | SerdeErr(ref e) => write!(f, "Serde JSON Error: {}", e), 40 | UrlParse(ref e) => write!(f, "URL parse error: {}", e), 41 | NetworkErr(ref e) => write!(f, "There was a network error. {}", e), 42 | BorrowErr(ref e) => write!(f, "Error trying to get client reference. {}", e), 43 | Utf8Err(ref e) => write!(f, "Error converting to utf-8 string: {}", e), 44 | HttpErr(ref e) => write!(f, "Http error when building req: {}", e), 45 | HeaderErr(ref e) => write!(f, "Error creating header value: {}", e), 46 | } 47 | } 48 | } 49 | 50 | from!(cell::BorrowMutError, BorrowErr); 51 | from!(hyper::Error, NetworkErr); 52 | from!(serde_json::Error, SerdeErr); 53 | from!(http::uri::InvalidUri, UrlParse); 54 | from!(io::Error, Io); 55 | from!(string::FromUtf8Error, Utf8Err); 56 | from!(http::Error, HttpErr); 57 | from!(typed_headers::Error, HeaderErr); 58 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | #![doc(html_root_url = "https://docs.rs/twilio-async/0.5.0")] 3 | #![allow( 4 | clippy::cognitive_complexity, 5 | clippy::large_enum_variant, 6 | clippy::needless_doctest_main, 7 | clippy::needless_lifetimes 8 | )] 9 | #![warn( 10 | missing_debug_implementations, 11 | // missing_docs, 12 | rust_2018_idioms, 13 | unreachable_pub 14 | )] 15 | #![deny(rustdoc::broken_intra_doc_links)] 16 | #![doc(test( 17 | no_crate_inject, 18 | attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables)) 19 | ))] 20 | #![cfg_attr(docsrs, feature(doc_cfg))] 21 | 22 | //! An async client library for interaction with twilio APIs 23 | //! An async and ergonomic wrapper around Twilio API & TwiML. 24 | //! 25 | //! All types can run `run()` or a similar function. They return a value that 26 | //! implements `Deserialize`. 27 | //! 28 | //! The `examples/` dir has up to date working example code. 29 | //! 30 | //! Messages: 31 | //! 32 | //! ```rust,no_run 33 | //! 34 | //! use std::env; 35 | //! use twilio_async::{Twilio, TwilioRequest}; 36 | //! 37 | //! #[tokio::main] 38 | //! async fn main() -> Result<(), Box> { 39 | //! let twilio = Twilio::new(env::var("TWILIO_SID")?, env::var("TWILIO_TOKEN")?)?; 40 | //! // sending a message 41 | //! twilio.send_msg("from", "to", "Hello World").run().await?; 42 | //! // sending a body-less message with media 43 | //! twilio 44 | //! .send_msg("from", "to", "body") 45 | //! .media("http://i0.kym-cdn.com/photos/images/newsfeed/000/377/946/0b9.jpg") 46 | //! .run().await?; 47 | //! // get details about a message 48 | //! twilio.msg("messagesid").run().await?; 49 | //! // redact a message 50 | //! twilio.msg("messagesid").redact().await?; 51 | //! // get a msg media url 52 | //! twilio.msg("messagesid").media().await?; 53 | //! // delete a msg 54 | //! twilio.msg("messagesid").delete().await?; 55 | //! // get all messages 56 | //! twilio.msgs().run().await?; 57 | //! // get all messages between some time 58 | //! twilio.msgs().between("start date", "end date").run().await?; 59 | //! // get all messages on a specific date 60 | //! twilio.msgs().on("date").run().await?; 61 | //! Ok(()) 62 | //! } 63 | //! ``` 64 | //! 65 | //! Calls: 66 | //! 67 | //! ```rust,no_run 68 | //! 69 | //! # use std::{error::Error, env}; 70 | //! # use twilio_async::{Twilio, TwilioJson, TwilioRequest}; 71 | //! 72 | //! # #[tokio::main] 73 | //! # async fn main() -> Result<(), Box> { 74 | //! let twilio = Twilio::new(env::var("TWILIO_SID")?, env::var("TWILIO_TOKEN")?)?; 75 | //! if let TwilioJson::Success(call) = twilio 76 | //! .call("from", "to", "http://demo.twilio.com/docs/voice.xml") 77 | //! .run().await? { 78 | //! // do something with `call` 79 | //! } 80 | //! # Ok(()) 81 | //! # } 82 | //! ``` 83 | //! 84 | //! Twiml: 85 | //! 86 | //! ```rust 87 | //! # fn main() { 88 | //! use twilio_async::twiml::{Response, Twiml}; 89 | //! 90 | //! let resp = Response::new() 91 | //! .say("Hello World") // builder pattern also supports say(Say::new("Hello World").lang("de")...) 92 | //! .play("https://api.twilio.com/Cowbell.mp3") 93 | //! .build(); 94 | //! let s = "Hello Worldhttps://api.twilio.com/Cowbell.mp3"; 95 | //! assert_eq!(resp.unwrap(), s.to_string()); 96 | //! # } 97 | //! ``` 98 | 99 | #[macro_use] 100 | mod macros; 101 | mod call; 102 | mod conference; 103 | pub mod error; 104 | mod message; 105 | mod recording; 106 | pub mod twiml; 107 | 108 | pub use crate::{call::*, conference::*, error::*, message::*, recording::*}; 109 | 110 | use async_trait::async_trait; 111 | use hyper::{client::HttpConnector, Body, Client, Method, Request}; 112 | use hyper_tls::HttpsConnector; 113 | use serde::Deserialize; 114 | use std::borrow::Borrow; 115 | 116 | pub use typed_headers::{Authorization, Credentials}; 117 | pub use url::{form_urlencoded, Url}; 118 | 119 | #[derive(Debug)] 120 | pub struct Twilio { 121 | sid: String, 122 | auth: Authorization, 123 | client: Client, hyper::Body>, 124 | } 125 | 126 | pub type TwilioResp = Result; 127 | 128 | impl Twilio { 129 | pub fn new(sid: S, token: P) -> TwilioResult 130 | where 131 | S: Into, 132 | P: AsRef, 133 | { 134 | let sid = sid.into(); 135 | let client = Client::builder().build::<_, hyper::Body>(HttpsConnector::new()); 136 | 137 | Ok(Twilio { 138 | auth: Authorization(Credentials::basic(&sid, token.as_ref())?), 139 | sid, 140 | client, 141 | }) 142 | } 143 | 144 | pub fn send_msg<'a>(&'a self, from: &'a str, to: &'a str, body: &'a str) -> SendMsg<'a> { 145 | SendMsg { 146 | msg: Msg::new(from, to, body), 147 | client: self, 148 | } 149 | } 150 | 151 | pub fn msg<'a>(&'a self, message_sid: &'a str) -> GetMessage<'a> { 152 | GetMessage { 153 | message_sid, 154 | client: self, 155 | } 156 | } 157 | 158 | pub fn msgs(&self) -> Messages<'_> { 159 | Messages { client: self } 160 | } 161 | 162 | pub fn call<'a>(&'a self, from: &'a str, to: &'a str, url: &'a str) -> SendCall<'a> { 163 | SendCall { 164 | call: Call::new(from, to, url), 165 | client: self, 166 | } 167 | } 168 | 169 | pub fn conference<'a>(&'a self, sid: &'a str) -> GetConference<'a> { 170 | GetConference { 171 | conference: Conference::new(sid), 172 | client: self, 173 | } 174 | } 175 | 176 | pub fn conferences(&self) -> Conferences<'_> { 177 | Conferences { client: self } 178 | } 179 | 180 | pub fn recording<'a>(&'a self, sid: &'a str) -> GetRecording<'a> { 181 | GetRecording { 182 | recording: Recording::new(sid), 183 | client: self, 184 | } 185 | } 186 | 187 | pub fn recordings(&self) -> Recordings<'_> { 188 | Recordings { client: self } 189 | } 190 | } 191 | 192 | #[derive(Debug, Deserialize)] 193 | #[serde(untagged)] 194 | pub enum TwilioJson { 195 | Success(T), 196 | Fail { 197 | code: usize, 198 | message: String, 199 | status: usize, 200 | }, 201 | } 202 | 203 | #[async_trait] 204 | pub trait Execute { 205 | fn request( 206 | &self, 207 | method: Method, 208 | url: U, 209 | body: Option, 210 | ) -> Result, TwilioErr> 211 | where 212 | U: AsRef; 213 | async fn execute( 214 | &self, 215 | method: Method, 216 | url: U, 217 | body: Option, 218 | ) -> TwilioResp> 219 | where 220 | U: AsRef + Send, 221 | D: for<'de> serde::Deserialize<'de>; 222 | } 223 | 224 | #[async_trait] 225 | pub trait TwilioRequest: Execute { 226 | type Resp: for<'de> serde::Deserialize<'de>; 227 | async fn run(&self) -> TwilioResp>; 228 | } 229 | 230 | pub fn encode_pairs(pairs: I) -> Option 231 | where 232 | K: AsRef, 233 | V: AsRef, 234 | I: IntoIterator, 235 | I::Item: Borrow<(K, V)>, 236 | { 237 | let mut partial = form_urlencoded::Serializer::new(String::new()); 238 | for pair in pairs { 239 | let &(ref k, ref v) = pair.borrow(); 240 | partial.append_pair(k.as_ref(), v.as_ref()); 241 | } 242 | let encoded = partial.finish(); 243 | Some(encoded) 244 | } 245 | 246 | pub fn url_encode(pairs: I) -> String 247 | where 248 | K: AsRef, 249 | V: AsRef, 250 | I: IntoIterator, 251 | I::Item: Borrow<(K, V)>, 252 | { 253 | pairs 254 | .into_iter() 255 | .map(|pair| { 256 | let &(ref k, ref v) = pair.borrow(); 257 | format!("{}={}", k.as_ref(), v.as_ref()) 258 | }) 259 | .fold(String::new(), |mut acc, item| { 260 | acc.push_str(&item); 261 | acc.push('&'); 262 | acc 263 | }) 264 | } 265 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | macro_rules! execute { 2 | ($ty:tt) => { 3 | #[async_trait] 4 | impl<'a> Execute for $ty<'a> { 5 | fn request( 6 | &self, 7 | method: Method, 8 | url: U, 9 | body: Option, 10 | ) -> Result, TwilioErr> 11 | where 12 | U: AsRef, 13 | { 14 | use hyper::{ 15 | header::{HeaderMap, HeaderValue, CONTENT_TYPE}, 16 | Request, 17 | }; 18 | use typed_headers::HeaderMapExt; 19 | const BASE: &str = "https://api.twilio.com/2010-04-01/Accounts"; 20 | 21 | let url = format!("{}/{}/{}", BASE, self.client.sid, url.as_ref()) 22 | .parse::()?; 23 | let mut request = Request::builder().method(method).uri(url); 24 | 25 | let mut hmap = HeaderMap::new(); 26 | hmap.typed_insert(&self.client.auth); 27 | for (k, v) in hmap { 28 | request = request.header(k.unwrap().as_str(), v); 29 | } 30 | Ok(match body { 31 | Some(body) => request 32 | .header( 33 | CONTENT_TYPE, 34 | HeaderValue::from_static("application/x-www-form-urlencoded"), 35 | ) 36 | .body(hyper::Body::from(body))?, 37 | None => request.body(hyper::Body::empty())?, 38 | }) 39 | } 40 | 41 | async fn execute( 42 | &self, 43 | method: Method, 44 | url: U, 45 | body: Option, 46 | ) -> TwilioResp> 47 | where 48 | U: AsRef + Send, 49 | D: for<'de> serde::Deserialize<'de>, 50 | { 51 | use bytes::Buf; 52 | use serde_json; 53 | 54 | let req = self.request(method, url, body)?; 55 | 56 | let res = self 57 | .client 58 | .client 59 | .request(req) 60 | .await 61 | .map_err(TwilioErr::NetworkErr)?; 62 | 63 | let body = hyper::body::aggregate(res).await?; 64 | 65 | let json_resp = serde_json::from_reader(body.reader())?; 66 | Ok(json_resp) 67 | } 68 | } 69 | }; 70 | } 71 | 72 | macro_rules! from { 73 | ($x:ty, $variant:ident) => { 74 | impl From<$x> for TwilioErr { 75 | fn from(e: $x) -> Self { 76 | $variant(e) 77 | } 78 | } 79 | }; 80 | } 81 | 82 | macro_rules! pair { 83 | ($x:ident, $field:ident, $name:tt, $vec:ident) => { 84 | if let Some($field) = $x.$field { 85 | $vec.push(($name, $field)); 86 | } 87 | }; 88 | } 89 | -------------------------------------------------------------------------------- /src/message.rs: -------------------------------------------------------------------------------- 1 | use super::{ 2 | encode_pairs, url_encode, Execute, Twilio, TwilioErr, TwilioJson, TwilioRequest, TwilioResp, 3 | }; 4 | use async_trait::async_trait; 5 | use hyper::{self, Method}; 6 | use serde::Deserialize; 7 | 8 | #[derive(Default, Debug)] 9 | pub struct Msg<'a> { 10 | from: &'a str, 11 | to: &'a str, 12 | body: &'a str, 13 | media_url: Option<&'a str>, 14 | } 15 | 16 | impl<'a> Msg<'a> { 17 | pub fn new(from: &'a str, to: &'a str, body: &'a str) -> Msg<'a> { 18 | Msg { 19 | from, 20 | to, 21 | body, 22 | ..Msg::default() 23 | } 24 | } 25 | } 26 | 27 | impl<'a> ToString for Msg<'a> { 28 | fn to_string(&self) -> String { 29 | match self.media_url { 30 | Some(m_url) => encode_pairs(&[ 31 | ("To", self.to), 32 | ("From", self.from), 33 | ("Body", self.body), 34 | ("MediaUrl", m_url), 35 | ]) 36 | .unwrap(), 37 | None => { 38 | encode_pairs(&[("To", self.to), ("From", self.from), ("Body", self.body)]).unwrap() 39 | } 40 | } 41 | } 42 | } 43 | 44 | #[derive(Debug, Deserialize)] 45 | #[allow(non_camel_case_types)] 46 | pub enum MsgStatus { 47 | queued, 48 | sending, 49 | sent, 50 | failed, 51 | delivered, 52 | undelivered, 53 | receiving, 54 | received, 55 | } 56 | 57 | #[derive(Debug, Deserialize)] 58 | pub struct MsgResp { 59 | pub from: String, 60 | pub to: String, 61 | pub body: String, 62 | pub sid: String, 63 | pub status: MsgStatus, 64 | pub media_url: Option, 65 | pub price: Option, 66 | pub price_unit: String, 67 | pub uri: String, 68 | pub date_created: String, 69 | pub date_sent: Option, 70 | pub date_updated: String, 71 | } 72 | 73 | // for outbound sms 74 | #[derive(Debug)] 75 | pub struct SendMsg<'a> { 76 | pub msg: Msg<'a>, 77 | pub client: &'a Twilio, 78 | } 79 | 80 | impl<'a> SendMsg<'a> { 81 | pub fn media(mut self, media_url: &'a str) -> SendMsg<'a> { 82 | self.msg.media_url = Some(media_url); 83 | self 84 | } 85 | } 86 | 87 | execute!(SendMsg); 88 | 89 | #[async_trait] 90 | impl<'a> TwilioRequest for SendMsg<'a> { 91 | type Resp = MsgResp; 92 | 93 | async fn run(&self) -> TwilioResp> { 94 | let msg = self.msg.to_string(); 95 | self.execute(Method::POST, "Messages.json", Some(msg)).await 96 | } 97 | } 98 | 99 | #[derive(Debug)] 100 | pub struct GetMessage<'a> { 101 | pub message_sid: &'a str, 102 | pub client: &'a Twilio, 103 | } 104 | 105 | execute!(GetMessage); 106 | 107 | #[async_trait] 108 | impl<'a> TwilioRequest for GetMessage<'a> { 109 | type Resp = MsgResp; 110 | 111 | async fn run(&self) -> TwilioResp> { 112 | let msg_sid = format!("Messages/{}.json", self.message_sid); 113 | self.execute(Method::GET, msg_sid, None).await 114 | } 115 | } 116 | 117 | impl<'a> GetMessage<'a> { 118 | pub async fn redact(&self) -> TwilioResp> { 119 | let msg_sid = format!("Messages/{}.json", self.message_sid); 120 | self.execute(Method::POST, msg_sid, Some("Body=".into())) 121 | .await 122 | } 123 | 124 | pub async fn delete(&self) -> TwilioResp> { 125 | let msg_sid = format!("Messages/{}.json", self.message_sid); 126 | self.execute(Method::DELETE, msg_sid, None).await 127 | } 128 | 129 | pub async fn media(&self) -> TwilioResp> { 130 | let msg_sid = format!("Messages/{}/Media.json", self.message_sid); 131 | self.execute(Method::GET, msg_sid, None).await 132 | } 133 | } 134 | 135 | #[derive(Debug, Deserialize)] 136 | pub struct MediaResp { 137 | pub media_list: Vec, 138 | pub num_pages: i32, 139 | pub page: i32, 140 | pub page_size: i32, 141 | pub start: i32, 142 | pub total: i32, 143 | pub uri: String, 144 | pub account_sid: String, 145 | pub message_sid: String, 146 | } 147 | 148 | #[derive(Debug, Deserialize)] 149 | pub struct MediaItem { 150 | pub account_sid: String, 151 | pub content_type: String, 152 | pub sid: String, 153 | pub uri: String, 154 | pub message_sid: String, 155 | pub date_created: String, 156 | pub date_update: String, 157 | } 158 | 159 | #[derive(Debug)] 160 | pub struct Messages<'a> { 161 | pub client: &'a Twilio, 162 | } 163 | 164 | impl<'a> Messages<'a> { 165 | pub fn between(self, from: &'a str, to: &'a str) -> MessagesDetails<'a> { 166 | MessagesDetails { 167 | client: self.client, 168 | from: Some(from), 169 | to: Some(to), 170 | date_sent: None, 171 | } 172 | } 173 | 174 | pub fn on(self, date_sent: &'a str) -> MessagesDetails<'a> { 175 | MessagesDetails { 176 | client: self.client, 177 | from: None, 178 | to: None, 179 | date_sent: Some(date_sent), 180 | } 181 | } 182 | } 183 | 184 | execute!(Messages); 185 | 186 | #[async_trait] 187 | impl<'a> TwilioRequest for Messages<'a> { 188 | type Resp = ListAllMsgs; 189 | 190 | async fn run(&self) -> TwilioResp> { 191 | self.execute(Method::GET, "Messages.json", None).await 192 | } 193 | } 194 | 195 | #[derive(Debug)] 196 | pub struct MessagesDetails<'a> { 197 | pub client: &'a Twilio, 198 | pub from: Option<&'a str>, 199 | pub to: Option<&'a str>, 200 | pub date_sent: Option<&'a str>, 201 | } 202 | 203 | impl<'a> ToString for MessagesDetails<'a> { 204 | fn to_string(&self) -> String { 205 | let mut pairs = Vec::new(); 206 | pair!(self, from, "From", pairs); 207 | pair!(self, to, "To", pairs); 208 | pair!(self, date_sent, "DateSent", pairs); 209 | // does this have to be different? will the encode_pairs work here? 210 | url_encode(pairs) 211 | } 212 | } 213 | 214 | execute!(MessagesDetails); 215 | 216 | #[async_trait] 217 | impl<'a> TwilioRequest for MessagesDetails<'a> { 218 | type Resp = ListAllMsgs; 219 | 220 | async fn run(&self) -> TwilioResp> { 221 | let url = format!("Messages.json?{}", self.to_string()); 222 | self.execute(Method::GET, url, None).await 223 | } 224 | } 225 | 226 | #[derive(Debug, Deserialize)] 227 | pub struct ListAllMsgs { 228 | pub messages: Vec, 229 | pub page: usize, 230 | pub page_size: usize, 231 | pub uri: String, 232 | pub next_page_uri: Option, 233 | pub previous_page_uri: Option, 234 | } 235 | -------------------------------------------------------------------------------- /src/recording.rs: -------------------------------------------------------------------------------- 1 | use super::{Execute, Twilio, TwilioErr, TwilioJson, TwilioRequest, TwilioResp}; 2 | use async_trait::async_trait; 3 | use hyper::{self, Method}; 4 | use serde::Deserialize; 5 | 6 | #[derive(Debug, Default)] 7 | pub struct Recording<'a> { 8 | sid: &'a str, 9 | } 10 | 11 | impl<'a> Recording<'a> { 12 | pub fn new(sid: &'a str) -> Recording<'a> { 13 | Recording { sid } 14 | } 15 | } 16 | 17 | // GET ONE Recording 18 | #[derive(Debug)] 19 | pub struct GetRecording<'a> { 20 | pub recording: Recording<'a>, 21 | pub client: &'a Twilio, 22 | } 23 | 24 | execute!(GetRecording); 25 | 26 | #[async_trait] 27 | impl<'a> TwilioRequest for GetRecording<'a> { 28 | type Resp = RecordingResp; 29 | 30 | async fn run(&self) -> TwilioResp> { 31 | let url = format!("Recordings/{}.json", self.recording.sid); 32 | self.execute(Method::GET, url, None).await 33 | } 34 | } 35 | 36 | impl<'a> GetRecording<'a> { 37 | pub async fn delete(&self) -> TwilioResp>> { 38 | let url = format!("Recordings/{}.json", self.recording.sid); 39 | self.execute(Method::DELETE, url, None).await 40 | } 41 | } 42 | 43 | // GET ALL RECORDINGS 44 | #[derive(Debug)] 45 | pub struct Recordings<'a> { 46 | pub client: &'a Twilio, 47 | } 48 | 49 | execute!(Recordings); 50 | 51 | #[async_trait] 52 | impl<'a> TwilioRequest for Recordings<'a> { 53 | type Resp = ListRecordingResp; 54 | 55 | async fn run(&self) -> TwilioResp> { 56 | self.execute(Method::GET, "Recordings.json", None).await 57 | } 58 | } 59 | 60 | impl<'a> Recordings<'a> { 61 | pub async fn for_call(&self, call_sid: &'a str) -> TwilioResp> { 62 | let url = format!("Recordings.json?CallSid={}", call_sid); 63 | self.execute(Method::GET, url, None).await 64 | } 65 | 66 | pub async fn created( 67 | &self, 68 | date_created: &'a str, 69 | ) -> TwilioResp> { 70 | let url = format!("Recordings.json?DateCreated={}", date_created); 71 | self.execute(Method::GET, url, None).await 72 | } 73 | 74 | pub async fn range( 75 | &self, 76 | before: &'a str, 77 | after: &'a str, 78 | ) -> TwilioResp> { 79 | let url = format!( 80 | "Recordings.json?DateCreatedBefore={}&DateCreatedAfter={}", 81 | before, after 82 | ); 83 | self.execute(Method::GET, url, None).await 84 | } 85 | } 86 | 87 | #[derive(Deserialize, Debug)] 88 | pub struct ListRecordingResp { 89 | pub recordings: Vec, 90 | pub end: usize, 91 | pub account_sid: String, 92 | pub start: usize, 93 | pub page: usize, 94 | pub page_size: usize, 95 | } 96 | 97 | #[derive(Deserialize, Debug)] 98 | pub struct RecordingResp { 99 | pub account_sid: String, 100 | pub call_sid: String, 101 | pub channels: String, 102 | pub conference_sid: String, 103 | pub date_created: String, 104 | pub date_updated: String, 105 | pub end_time: String, 106 | pub start_time: String, 107 | pub price: String, 108 | pub price_unit: String, 109 | pub duration: String, 110 | pub encryption_details: EncryptionDetails, 111 | pub error_code: String, 112 | pub uri: String, 113 | pub status: RecordingStatus, 114 | } 115 | 116 | #[derive(Deserialize, Debug)] 117 | pub struct EncryptionDetails { 118 | pub encryption_public_key_sid: String, 119 | pub encryption_cek: String, 120 | pub encryption_iv: String, 121 | } 122 | 123 | #[derive(Deserialize, Debug)] 124 | #[allow(non_camel_case_types)] 125 | pub enum RecordingStatus { 126 | #[serde(rename = "in-progress")] 127 | inprogress, 128 | paused, 129 | stopped, 130 | processing, 131 | completed, 132 | failed, 133 | } 134 | -------------------------------------------------------------------------------- /src/twiml.rs: -------------------------------------------------------------------------------- 1 | pub use twiml::*; 2 | -------------------------------------------------------------------------------- /twiml/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "twiml" 3 | version = "0.4.0" 4 | description = """ 5 | Typesafe construction of Twilio TwiML 6 | """ 7 | repository = "https://github.com/leshow/twilio" 8 | keywords = ["twilio", "twiml", "api"] 9 | categories = ["network-programming", "api-bindings", "web-programming", "development-tools"] 10 | license = "MIT" 11 | authors = ["Evan Cameron "] 12 | edition = "2021" 13 | 14 | [dependencies] 15 | xml-rs = "0.8" 16 | -------------------------------------------------------------------------------- /twiml/README.md: -------------------------------------------------------------------------------- 1 | # TwiML 2 | 3 | ```rust 4 | #[test] 5 | fn twiml_response() { 6 | let resp = Response::new() 7 | .say("Hello World") 8 | .play("https://api.twilio.com/Cowbell.mp3") 9 | .build(); 10 | let s = "Hello Worldhttps://api.twilio.com/Cowbell.mp3"; 11 | assert_eq!(resp.unwrap(), s.to_string()); 12 | } 13 | 14 | #[test] 15 | fn twiml_resp_build() { 16 | let resp = Response::new() 17 | .say(Say::new("Hello World").lang("de").voice(Voice::alice)) 18 | .play("https://api.twilio.com/Cowbell.mp3") 19 | .build(); 20 | let s = "Hello Worldhttps://api.twilio.com/Cowbell.mp3"; 21 | assert_eq!(resp.unwrap(), s.to_string()); 22 | } 23 | 24 | #[test] 25 | fn twiml_say() { 26 | let say = Say::new("Hello World") 27 | .lang("de") 28 | .voice(Voice::alice) 29 | .build(); 30 | let s = "Hello World"; 31 | assert_eq!(say.unwrap(), s.to_string()); 32 | } 33 | 34 | #[test] 35 | fn twiml_play() { 36 | let play = Play::new("https://api.twilio.com/Cowbell.mp3") 37 | .count(3) 38 | .build(); 39 | let s = "https://api.twilio.com/Cowbell.mp3"; 40 | assert_eq!(play.unwrap(), s.to_string()); 41 | } 42 | 43 | #[test] 44 | fn twiml_response_dial() { 45 | let resp = Response::new().dial("415-123-4567").build(); 46 | let s = "415-123-4567"; 47 | assert_eq!(resp.unwrap(), s.to_string()); 48 | } 49 | 50 | #[test] 51 | fn twiml_response_hangup() { 52 | let resp = Response::new().hangup().build(); 53 | let s = ""; 54 | assert_eq!(resp.unwrap(), s.to_string()); 55 | } 56 | ``` 57 | -------------------------------------------------------------------------------- /twiml/src/dial.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use xml::{ 3 | writer::{EventWriter, XmlEvent}, 4 | EmitterConfig, 5 | }; 6 | 7 | #[derive(Debug)] 8 | pub struct Dial<'a> { 9 | method: Method, 10 | action: Option<&'a str>, 11 | timeout: usize, 12 | number: &'a str, 13 | recording_callback: Option<&'a str>, 14 | record: Record, 15 | } 16 | 17 | impl<'a> Default for Dial<'a> { 18 | fn default() -> Self { 19 | Dial { 20 | number: "", 21 | method: Method::Post, 22 | recording_callback: None, 23 | record: Record::DoNotRecord, 24 | action: None, 25 | timeout: 30, 26 | } 27 | } 28 | } 29 | 30 | impl<'a> Dial<'a> { 31 | pub fn new(number: &'a str) -> Self { 32 | Dial { 33 | number, 34 | ..Dial::default() 35 | } 36 | } 37 | 38 | pub fn method(mut self, method: Method) -> Self { 39 | self.method = method; 40 | self 41 | } 42 | 43 | pub fn action(mut self, url: &'a str) -> Self { 44 | self.action = Some(url); 45 | self 46 | } 47 | 48 | pub fn record(mut self, status: Record) -> Self { 49 | self.record = status; 50 | self 51 | } 52 | 53 | pub fn recording_callback(mut self, url: &'a str) -> Self { 54 | self.recording_callback = Some(url); 55 | self 56 | } 57 | 58 | pub fn timeout(mut self, timeout: usize) -> Self { 59 | self.timeout = timeout; 60 | self 61 | } 62 | } 63 | 64 | #[derive(Debug)] 65 | pub enum Record { 66 | DoNotRecord, 67 | RecordFromAnswer, 68 | RecordFromRinging, 69 | } 70 | 71 | impl Record { 72 | fn to_str(&self) -> &str { 73 | match *self { 74 | Record::DoNotRecord => "do-not-record", 75 | Record::RecordFromAnswer => "record-from-answer", 76 | Record::RecordFromRinging => "record-from-ringing", 77 | } 78 | } 79 | } 80 | 81 | impl<'a> Twiml for Dial<'a> { 82 | fn write(&self, w: &mut EventWriter) -> TwimlResult<()> { 83 | let timeout = self.timeout.to_string(); 84 | let el = XmlEvent::start_element("Dial") 85 | .attr("method", self.method.to_str()) 86 | .attr("timeout", &timeout) 87 | .attr("record", self.record.to_str()); 88 | 89 | // not sure how else to get around this particular move error 90 | match (self.action, self.recording_callback) { 91 | (None, None) => w.write(el)?, 92 | (Some(action), None) => w.write(el.attr("action", action))?, 93 | (None, Some(callback)) => w.write(el.attr("recordingStatusCallback", callback))?, 94 | (Some(action), Some(callback)) => w.write( 95 | el.attr("action", action) 96 | .attr("recordingStatusCallback", callback), 97 | )?, 98 | } 99 | 100 | w.write(self.number)?; 101 | w.write(XmlEvent::end_element())?; 102 | Ok(()) 103 | } 104 | 105 | fn build(&self) -> TwimlResult { 106 | // Create a buffer and serialize our nodes into it 107 | let mut writer = Vec::new(); 108 | { 109 | let mut w = EmitterConfig::new() 110 | .write_document_declaration(false) 111 | .create_writer(&mut writer); 112 | 113 | self.write(&mut w)?; 114 | } 115 | Ok(String::from_utf8(writer)?) 116 | } 117 | } 118 | 119 | impl<'a, T> From for Dial<'a> 120 | where 121 | T: Into<&'a str>, 122 | { 123 | fn from(s: T) -> Self { 124 | Dial::new(s.into()) 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /twiml/src/error.rs: -------------------------------------------------------------------------------- 1 | use std::{error::Error, fmt, io, string}; 2 | use xml::writer; 3 | 4 | // Errors 5 | #[derive(Debug)] 6 | pub enum TwimlErr { 7 | Io(io::Error), 8 | Utf8Err(string::FromUtf8Error), 9 | EmitterErr(writer::Error), 10 | } 11 | 12 | pub use super::TwimlErr::*; 13 | 14 | pub type TwimlResult = Result; 15 | 16 | impl Error for TwimlErr { 17 | fn source(&self) -> Option<&(dyn Error + 'static)> { 18 | match *self { 19 | Io(ref e) => e.source(), 20 | Utf8Err(ref e) => e.source(), 21 | EmitterErr(ref e) => e.source(), 22 | } 23 | } 24 | } 25 | 26 | impl fmt::Display for TwimlErr { 27 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 28 | match *self { 29 | Io(ref e) => write!(f, "IO Error: {}", e), 30 | Utf8Err(ref e) => write!(f, "Error converting to utf-8 string: {}", e), 31 | EmitterErr(ref e) => write!(f, "Error emitting xml: {}", e), 32 | } 33 | } 34 | } 35 | 36 | impl From for TwimlErr { 37 | fn from(e: io::Error) -> Self { 38 | Io(e) 39 | } 40 | } 41 | 42 | impl From for TwimlErr { 43 | fn from(e: string::FromUtf8Error) -> Self { 44 | Utf8Err(e) 45 | } 46 | } 47 | 48 | impl From for TwimlErr { 49 | fn from(e: writer::Error) -> Self { 50 | EmitterErr(e) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /twiml/src/gather.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use xml::{ 3 | writer::{EventWriter, XmlEvent}, 4 | EmitterConfig, 5 | }; 6 | 7 | #[derive(Debug)] 8 | pub struct Gather<'a> { 9 | method: Method, 10 | action: Option<&'a str>, 11 | key: char, 12 | timeout: usize, 13 | body: GatherBody<'a>, 14 | } 15 | 16 | #[derive(Debug)] 17 | enum GatherBody<'a> { 18 | Nil, 19 | Say(Say<'a>), 20 | Play(Play<'a>), 21 | Redirect(Redirect<'a>), 22 | } 23 | 24 | impl<'a> Default for Gather<'a> { 25 | fn default() -> Self { 26 | Gather { 27 | body: GatherBody::Nil, 28 | method: Method::Post, 29 | key: '#', 30 | action: None, 31 | timeout: 5, 32 | } 33 | } 34 | } 35 | 36 | impl<'a> Gather<'a> { 37 | pub fn say>>(mut self, say: S) -> Self { 38 | self.body = GatherBody::Say(say.into()); 39 | self 40 | } 41 | 42 | pub fn play>>(mut self, play: P) -> Self { 43 | self.body = GatherBody::Play(play.into()); 44 | self 45 | } 46 | 47 | pub fn redirect>>(mut self, redirect: R) -> Self { 48 | self.body = GatherBody::Redirect(redirect.into()); 49 | self 50 | } 51 | 52 | pub fn method(mut self, method: Method) -> Self { 53 | self.method = method; 54 | self 55 | } 56 | 57 | pub fn finish_on_key(mut self, key: char) -> Self { 58 | self.key = key; 59 | self 60 | } 61 | 62 | pub fn timeout(mut self, timeout: usize) -> Self { 63 | self.timeout = timeout; 64 | self 65 | } 66 | } 67 | 68 | impl<'a> Twiml for Gather<'a> { 69 | fn write(&self, w: &mut EventWriter) -> TwimlResult<()> { 70 | let timeout = self.timeout.to_string(); 71 | let key = self.key.to_string(); 72 | let el = XmlEvent::start_element("Gather") 73 | .attr("method", self.method.to_str()) 74 | .attr("timeout", &timeout) 75 | .attr("finishOnKey", &key); 76 | if let Some(action) = self.action { 77 | w.write(el.attr("action", action))?; 78 | } else { 79 | w.write(el)?; 80 | } 81 | match self.body { 82 | GatherBody::Nil => {} 83 | GatherBody::Play(ref val) => val.write(w)?, 84 | GatherBody::Say(ref val) => val.write(w)?, 85 | GatherBody::Redirect(ref val) => val.write(w)?, 86 | } 87 | 88 | w.write(XmlEvent::end_element())?; 89 | Ok(()) 90 | } 91 | 92 | fn build(&self) -> TwimlResult { 93 | // Create a buffer and serialize our nodes into it 94 | let mut writer = Vec::new(); 95 | { 96 | let mut w = EmitterConfig::new() 97 | .write_document_declaration(false) 98 | .create_writer(&mut writer); 99 | 100 | self.write(&mut w)?; 101 | } 102 | Ok(String::from_utf8(writer)?) 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /twiml/src/hangup.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use xml::{ 3 | writer::{EventWriter, XmlEvent}, 4 | EmitterConfig, 5 | }; 6 | 7 | #[derive(Debug, Default)] 8 | pub struct Hangup; 9 | 10 | impl Hangup { 11 | pub fn new() -> Self { 12 | Hangup 13 | } 14 | } 15 | 16 | impl Twiml for Hangup { 17 | fn write(&self, w: &mut EventWriter) -> TwimlResult<()> { 18 | w.write(XmlEvent::start_element("Hangup"))?; 19 | w.write(XmlEvent::end_element())?; 20 | Ok(()) 21 | } 22 | 23 | fn build(&self) -> TwimlResult { 24 | // Create a buffer and serialize our nodes into it 25 | let mut writer = Vec::new(); 26 | { 27 | let mut w = EmitterConfig::new() 28 | .write_document_declaration(false) 29 | .create_writer(&mut writer); 30 | 31 | self.write(&mut w)?; 32 | } 33 | Ok(String::from_utf8(writer)?) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /twiml/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod dial; 2 | pub mod error; 3 | mod gather; 4 | mod hangup; 5 | mod msg; 6 | mod play; 7 | mod redirect; 8 | mod response; 9 | mod say; 10 | 11 | pub use crate::{ 12 | dial::*, error::*, gather::*, hangup::*, msg::*, play::*, redirect::*, response::*, say::*, 13 | }; 14 | 15 | use std::io::Write; 16 | use xml::writer::EventWriter; 17 | 18 | pub trait Twiml { 19 | fn write(&self, w: &mut EventWriter) -> TwimlResult<()>; 20 | fn build(&self) -> TwimlResult; 21 | } 22 | 23 | #[derive(Debug)] 24 | pub enum Method { 25 | Get, 26 | Post, 27 | } 28 | 29 | impl Method { 30 | fn to_str(&self) -> &str { 31 | match *self { 32 | Method::Get => "GET", 33 | Method::Post => "POST", 34 | } 35 | } 36 | } 37 | 38 | #[cfg(test)] 39 | mod tests { 40 | use super::*; 41 | 42 | #[test] 43 | fn twiml_response() { 44 | let resp = Response::new() 45 | .say("Hello World") 46 | .play("https://api.twilio.com/Cowbell.mp3") 47 | .build(); 48 | let s = "Hello Worldhttps://api.twilio.com/Cowbell.mp3"; 49 | assert_eq!(resp.unwrap(), s.to_string()); 50 | } 51 | 52 | #[test] 53 | fn twiml_resp_build() { 54 | let resp = Response::new() 55 | .say(Say::new("Hello World").lang("de").voice(Voice::alice)) 56 | .play("https://api.twilio.com/Cowbell.mp3") 57 | .build(); 58 | let s = "Hello Worldhttps://api.twilio.com/Cowbell.mp3"; 59 | assert_eq!(resp.unwrap(), s.to_string()); 60 | } 61 | 62 | #[test] 63 | fn twiml_say() { 64 | let say = Say::new("Hello World") 65 | .lang("de") 66 | .voice(Voice::alice) 67 | .build(); 68 | let s = "Hello World"; 69 | assert_eq!(say.unwrap(), s.to_string()); 70 | } 71 | 72 | #[test] 73 | fn twiml_play() { 74 | let play = Play::new("https://api.twilio.com/Cowbell.mp3") 75 | .count(3) 76 | .build(); 77 | let s = "https://api.twilio.com/Cowbell.mp3"; 78 | assert_eq!(play.unwrap(), s.to_string()); 79 | } 80 | 81 | #[test] 82 | fn twiml_response_dial() { 83 | let resp = Response::new().dial("415-123-4567").build(); 84 | let s = "415-123-4567"; 85 | assert_eq!(resp.unwrap(), s.to_string()); 86 | } 87 | 88 | #[test] 89 | fn twiml_response_hangup() { 90 | let resp = Response::new().hangup().build(); 91 | let s = ""; 92 | assert_eq!(resp.unwrap(), s.to_string()); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /twiml/src/msg.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use xml::{ 3 | writer::{EventWriter, XmlEvent}, 4 | EmitterConfig, 5 | }; 6 | 7 | #[derive(Debug)] 8 | pub struct Msg<'a> { 9 | media: Option<&'a str>, 10 | body: &'a str, 11 | } 12 | 13 | impl<'a> Msg<'a> { 14 | pub fn new(body: &'a str) -> Self { 15 | Msg { body, media: None } 16 | } 17 | 18 | pub fn media(mut self, media: &'a str) -> Self { 19 | self.media = Some(media); 20 | self 21 | } 22 | } 23 | 24 | impl<'a> Twiml for Msg<'a> { 25 | fn write(&self, w: &mut EventWriter) -> TwimlResult<()> { 26 | w.write(XmlEvent::start_element("Message"))?; // .attr("loop", &self.count.to_string()) 27 | w.write(XmlEvent::start_element("Body"))?; 28 | w.write(self.body)?; 29 | w.write(XmlEvent::end_element())?; 30 | w.write(XmlEvent::end_element())?; 31 | Ok(()) 32 | } 33 | 34 | fn build(&self) -> TwimlResult { 35 | // Create a buffer and serialize our nodes into it 36 | let mut writer = Vec::new(); 37 | { 38 | let mut w = EmitterConfig::new() 39 | .write_document_declaration(false) 40 | .create_writer(&mut writer); 41 | 42 | self.write(&mut w)?; 43 | } 44 | Ok(String::from_utf8(writer)?) 45 | } 46 | } 47 | 48 | impl<'a, T> From for Msg<'a> 49 | where 50 | T: Into<&'a str>, 51 | { 52 | fn from(s: T) -> Self { 53 | Msg::new(s.into()) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /twiml/src/play.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use xml::{ 3 | writer::{EventWriter, XmlEvent}, 4 | EmitterConfig, 5 | }; 6 | 7 | #[derive(Debug)] 8 | pub struct Play<'a> { 9 | count: usize, 10 | body: &'a str, 11 | } 12 | 13 | impl<'a> Play<'a> { 14 | pub fn new(body: &'a str) -> Self { 15 | Play { body, count: 1 } 16 | } 17 | 18 | pub fn count(mut self, count: usize) -> Play<'a> { 19 | self.count = count; 20 | self 21 | } 22 | } 23 | 24 | impl<'a> Twiml for Play<'a> { 25 | fn write(&self, w: &mut EventWriter) -> TwimlResult<()> { 26 | w.write(XmlEvent::start_element("Play").attr("loop", &self.count.to_string()))?; 27 | w.write(self.body)?; 28 | w.write(XmlEvent::end_element())?; 29 | Ok(()) 30 | } 31 | 32 | fn build(&self) -> TwimlResult { 33 | // Create a buffer and serialize our nodes into it 34 | let mut writer = Vec::new(); 35 | { 36 | let mut w = EmitterConfig::new() 37 | .write_document_declaration(false) 38 | .create_writer(&mut writer); 39 | 40 | self.write(&mut w)?; 41 | } 42 | Ok(String::from_utf8(writer)?) 43 | } 44 | } 45 | 46 | impl<'a, T> From for Play<'a> 47 | where 48 | T: Into<&'a str>, 49 | { 50 | fn from(s: T) -> Self { 51 | Play::new(s.into()) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /twiml/src/redirect.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use xml::{ 3 | writer::{EventWriter, XmlEvent}, 4 | EmitterConfig, 5 | }; 6 | 7 | #[derive(Debug)] 8 | pub struct Redirect<'a> { 9 | method: Method, 10 | body: &'a str, 11 | } 12 | 13 | impl<'a> Default for Redirect<'a> { 14 | fn default() -> Self { 15 | Redirect { 16 | body: "", 17 | method: Method::Post, 18 | } 19 | } 20 | } 21 | 22 | impl<'a> Redirect<'a> { 23 | pub fn new(body: &'a str) -> Self { 24 | Redirect { 25 | body, 26 | ..Redirect::default() 27 | } 28 | } 29 | 30 | pub fn method(mut self, method: Method) -> Self { 31 | self.method = method; 32 | self 33 | } 34 | } 35 | 36 | impl<'a> Twiml for Redirect<'a> { 37 | fn write(&self, w: &mut EventWriter) -> TwimlResult<()> { 38 | w.write(XmlEvent::start_element("Redirect").attr("method", self.method.to_str()))?; 39 | w.write(self.body)?; 40 | w.write(XmlEvent::end_element())?; 41 | Ok(()) 42 | } 43 | 44 | fn build(&self) -> TwimlResult { 45 | // Create a buffer and serialize our nodes into it 46 | let mut writer = Vec::new(); 47 | { 48 | let mut w = EmitterConfig::new() 49 | .write_document_declaration(false) 50 | .create_writer(&mut writer); 51 | 52 | self.write(&mut w)?; 53 | } 54 | Ok(String::from_utf8(writer)?) 55 | } 56 | } 57 | 58 | impl<'a, T> From for Redirect<'a> 59 | where 60 | T: Into<&'a str>, 61 | { 62 | fn from(s: T) -> Self { 63 | Redirect::new(s.into()) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /twiml/src/response.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use xml::{writer::XmlEvent, EmitterConfig}; 3 | 4 | #[derive(Debug, Default)] 5 | pub struct Response<'a> { 6 | say: Option>, 7 | play: Option>, 8 | msg: Option>, 9 | redirect: Option>, 10 | gather: Option>, 11 | dial: Option>, 12 | hangup: Option, 13 | } 14 | 15 | impl<'a> Response<'a> { 16 | pub fn new() -> Self { 17 | Response { 18 | say: None, 19 | play: None, 20 | msg: None, 21 | redirect: None, 22 | gather: None, 23 | dial: None, 24 | hangup: None, 25 | } 26 | } 27 | 28 | pub fn say>>(mut self, say: S) -> Self { 29 | self.say = Some(say.into()); 30 | self 31 | } 32 | 33 | pub fn play>>(mut self, play: P) -> Self { 34 | self.play = Some(play.into()); 35 | self 36 | } 37 | 38 | pub fn redirect>>(mut self, redirect: R) -> Self { 39 | self.redirect = Some(redirect.into()); 40 | self 41 | } 42 | 43 | pub fn msg>>(mut self, msg: M) -> Self { 44 | self.msg = Some(msg.into()); 45 | self 46 | } 47 | 48 | pub fn gather(mut self, gather: Gather<'a>) -> Self { 49 | self.gather = Some(gather); 50 | self 51 | } 52 | 53 | pub fn dial>>(mut self, dial: D) -> Self { 54 | self.dial = Some(dial.into()); 55 | self 56 | } 57 | 58 | pub fn hangup(mut self) -> Self { 59 | self.hangup = Some(Hangup::new()); 60 | self 61 | } 62 | } 63 | 64 | impl<'a> Twiml for Response<'a> { 65 | fn write(&self, w: &mut EventWriter) -> TwimlResult<()> { 66 | w.write(XmlEvent::start_element("Response"))?; 67 | if let Some(ref val) = self.say { 68 | val.write(w)?; 69 | } 70 | if let Some(ref val) = self.play { 71 | val.write(w)?; 72 | } 73 | if let Some(ref val) = self.redirect { 74 | val.write(w)?; 75 | } 76 | if let Some(ref val) = self.msg { 77 | val.write(w)?; 78 | } 79 | if let Some(ref val) = self.gather { 80 | val.write(w)?; 81 | } 82 | if let Some(ref val) = self.dial { 83 | val.write(w)?; 84 | } 85 | if let Some(ref val) = self.hangup { 86 | val.write(w)?; 87 | } 88 | w.write(XmlEvent::end_element())?; 89 | Ok(()) 90 | } 91 | 92 | fn build(&self) -> TwimlResult { 93 | // Create a buffer and serialize our nodes into it 94 | let mut writer = Vec::new(); 95 | { 96 | let mut w = EmitterConfig::new() 97 | .write_document_declaration(false) 98 | .create_writer(&mut writer); 99 | self.write(&mut w)?; 100 | } 101 | Ok(String::from_utf8(writer)?) 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /twiml/src/say.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use xml::{ 3 | writer::{EventWriter, XmlEvent}, 4 | EmitterConfig, 5 | }; 6 | 7 | #[derive(Debug)] 8 | pub struct Say<'a> { 9 | voice: Voice, 10 | count: usize, 11 | language: &'a str, 12 | body: &'a str, 13 | } 14 | 15 | #[derive(Debug)] 16 | #[allow(non_camel_case_types)] 17 | pub enum Voice { 18 | man, 19 | woman, 20 | alice, 21 | } 22 | 23 | impl<'a> Say<'a> { 24 | pub fn new(body: &'a str) -> Self { 25 | Say { 26 | body, 27 | voice: Voice::man, 28 | count: 1, 29 | language: "en", 30 | } 31 | } 32 | 33 | pub fn lang(mut self, language: &'a str) -> Say<'a> { 34 | self.language = language; 35 | self 36 | } 37 | 38 | pub fn voice(mut self, voice: Voice) -> Say<'a> { 39 | self.voice = voice; 40 | self 41 | } 42 | 43 | pub fn say_count(mut self, count: usize) -> Say<'a> { 44 | self.count = count; 45 | self 46 | } 47 | } 48 | 49 | impl<'a> Twiml for Say<'a> { 50 | fn write(&self, w: &mut EventWriter) -> TwimlResult<()> { 51 | // Create a buffer and serialize our nodes into it 52 | w.write( 53 | XmlEvent::start_element("Say") 54 | .attr("voice", self.voice.to_str()) 55 | .attr("language", self.language) 56 | .attr("loop", &self.count.to_string()), 57 | )?; 58 | w.write(self.body)?; 59 | w.write(XmlEvent::end_element())?; 60 | Ok(()) 61 | } 62 | 63 | fn build(&self) -> TwimlResult { 64 | // Create a buffer and serialize our nodes into it 65 | let mut writer = Vec::new(); 66 | { 67 | let mut w = EmitterConfig::new() 68 | .write_document_declaration(false) 69 | .create_writer(&mut writer); 70 | 71 | self.write(&mut w)?; 72 | } 73 | Ok(String::from_utf8(writer)?) 74 | } 75 | } 76 | 77 | impl Voice { 78 | pub fn to_str(&self) -> &str { 79 | match *self { 80 | Voice::man => "man", 81 | Voice::woman => "woman", 82 | Voice::alice => "alice", 83 | } 84 | } 85 | } 86 | 87 | impl<'a, T> From for Say<'a> 88 | where 89 | T: Into<&'a str>, 90 | { 91 | fn from(s: T) -> Self { 92 | Say::new(s.into()) 93 | } 94 | } 95 | --------------------------------------------------------------------------------