1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
extern crate hyper;

use ::{Client, ToUrlEncoded};
use url::{form_urlencoded, Url};
use chrono::prelude::*;
use serde_helper;
use hyper::{Method, Request};
use hyper::header::{ContentType, ContentLength};
use futures::Future;

pub struct Messages<'a> {
    client: &'a Client,
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MessageStatus {
    Accepted,
    Queued,
    Sending,
    Sent,
    Failed,
    Delivered,
    Undelivered,
    Receiving,
    Received,
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum MessageDirection {
    Inbound,
    OutboundApi,
    OutboundCall,
    OutboundReply,
}


#[derive(Deserialize)]
pub struct Message {
    pub sid: String,
    pub account_sid: String,
    pub messaging_service_sid: Option<String>,
    pub from: String,
    pub to: String,
    pub body: String,
    #[serde(deserialize_with = "serde_helper::deserialize_str_to_u32")] pub num_segments: Option<u32>,
    pub status: MessageStatus,
    pub error_code: Option<String>,
    pub error_message: Option<String>,
    pub direction: MessageDirection,
    pub price: Option<String>,
    pub price_unit: Option<String>,
    #[serde(deserialize_with = "serde_helper::deserialize_rfc2822")] pub date_created: Option<DateTime<Utc>>,
    #[serde(deserialize_with = "serde_helper::deserialize_rfc2822")] pub date_updated: Option<DateTime<Utc>>,
    #[serde(deserialize_with = "serde_helper::deserialize_rfc2822")] pub date_sent: Option<DateTime<Utc>>,
}

#[derive(Copy, Clone)]
pub enum MessageBody<'a> {
    SMS(&'a str),
    MMS(&'a Url),
}

#[derive(Copy, Clone)]
pub enum MessageFrom<'a> {
    From(&'a str),
    MessagingServiceSid(&'a str),
}

pub struct OutboundMessage<'a> {
    to: &'a str,
    from: MessageFrom<'a>,
    body: MessageBody<'a>,
    status_callback: Option<&'a Url>,
    application_sid: Option<&'a str>,
    max_price: Option<&'a str>,
    provide_feedback: bool,
    validity_period: Option<u32>,
}

pub struct OutboundMessageBuilder<'a> {
    to: &'a str,
    from: MessageFrom<'a>,
    body: MessageBody<'a>,
    status_callback: Option<&'a Url>,
    application_sid: Option<&'a str>,
    max_price: Option<&'a str>,
    provide_feedback: bool,
    validity_period: Option<u32>,
}

impl<'a> OutboundMessageBuilder<'a> {
    pub fn new_sms(from: MessageFrom<'a>, to: &'a str, body: &'a str) -> OutboundMessageBuilder<'a> {
        OutboundMessageBuilder {
            from,
            to,
            body: MessageBody::SMS(body),
            status_callback: None,
            application_sid: None,
            max_price: None,
            provide_feedback: false,
            validity_period: None,
        }
    }

    pub fn new_mms(from: MessageFrom<'a>, to: &'a str, body: &'a Url) -> OutboundMessageBuilder<'a> {
        OutboundMessageBuilder {
            from,
            to,
            body: MessageBody::MMS(body),
            status_callback: None,
            application_sid: None,
            max_price: None,
            provide_feedback: false,
            validity_period: None,
        }
    }

    pub fn with_status_callback(&mut self, url: &'a Url) -> &mut Self {
        self.status_callback = Some(url);
        self
    }

    pub fn with_application_sid(&mut self, application_sid: &'a str) -> &mut Self {
        self.application_sid = Some(application_sid);
        self
    }

    pub fn with_max_price(&mut self, max_price: &'a str) -> &mut Self {
        self.max_price = Some(max_price);
        self
    }

    pub fn with_provide_feedback(&mut self, provide_feedback: bool) -> &mut Self {
        self.provide_feedback = provide_feedback;
        self
    }

    pub fn with_validity_period(&mut self, validity_period: u32) -> &mut Self {
        self.validity_period = Some(validity_period);
        self
    }

    pub fn build(&self) -> OutboundMessage<'a> {
        OutboundMessage {
            from: self.from,
            to: self.to,
            body: self.body,
            status_callback: self.status_callback,
            application_sid: self.application_sid,
            max_price: self.max_price,
            provide_feedback: self.provide_feedback,
            validity_period: self.validity_period,
        }
    }
}

impl<'a> ToUrlEncoded for OutboundMessage<'a> {

    fn to_url_encoded(&self) -> String {
        let mut encoder = form_urlencoded::Serializer::new(String::new());
        encoder.append_pair("To", self.to);

        let (name, value) = match self.from {
            MessageFrom::From(x) => ("From", x),
            MessageFrom::MessagingServiceSid(x) => ("MessagingServiceSid", x),
        };

        encoder.append_pair(name, value);

        let (name, value) = match self.body {
            MessageBody::SMS(x) => ("Body", x),
            MessageBody::MMS(x) => ("MediaUrl", x.as_str()),
        };

        encoder.append_pair(name, value);

        if let Some(url) = self.status_callback {
            encoder.append_pair("StatusCallback", url.as_str());
        }

        if let Some(application_sid) = self.application_sid {
            encoder.append_pair("ApplicationSid", application_sid);
        }

        if let Some(max_price) = self.max_price {
            encoder.append_pair("MaxPrice", max_price);
        }

        if self.provide_feedback {
            encoder.append_pair("ProvideFeedback", "true");
        }

        if let Some(validity_period) = self.validity_period {
            encoder.append_pair("ValidityPeriod", &validity_period.to_string());
        }


        encoder.finish()
    }
}

impl<'a> Messages<'a> {

    pub fn new(client: &'a Client) -> Messages {
        Messages { client }
    }

    pub fn send_message(&self, message: &'a OutboundMessage) -> Box<Future<Item = Message, Error = ::TwilioError>> {
        let encoded_params = message.to_url_encoded();
        let uri = format!(
            "{}/2010-04-01/Accounts/{}/Messages.json",
            ::BASE_URI,
            self.client.account_sid).parse().unwrap();
        let mut req = Request::new(Method::Post, uri);
        req.headers_mut().set(ContentType::form_url_encoded());
        req.headers_mut().set(ContentLength(encoded_params.len() as u64));
        req.set_body(encoded_params.into_bytes());
        self.client.make_req(req)
    }
}