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
|
use crate::config::Config;
use reqwest::blocking::Client;
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt::{self, Display, Formatter};
const TWILIO_BASE_URL: &str = "https://api.twilio.com/2010-04-01/Accounts";
#[derive(Deserialize, Debug)]
pub struct Message {
pub from: String,
pub to: String,
pub body: String,
}
// list of possible values: https://www.twilio.com/docs/sms/api/message-resource#message-status-values
#[derive(Debug, Deserialize, Clone)]
#[allow(non_camel_case_types)]
pub enum MessageStatus {
accepted,
scheduled,
queued,
sending,
sent,
receiving,
received,
delivered,
undelivered,
failed,
read,
canceled,
}
#[derive(Deserialize, Debug, Clone)]
pub struct MessageResponse {
pub status: Option<MessageStatus>,
}
#[derive(Debug)]
pub enum TwilioError {
HTTPError(reqwest::StatusCode),
}
impl Display for TwilioError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match *self {
TwilioError::HTTPError(ref s) => write!(f, "Invalid HTTP status code: {}", s),
}
}
}
impl Message {
pub fn send(&self, config: &Config) -> Result<MessageResponse, TwilioError> {
let url = format!("{}/{}/Messages.json", TWILIO_BASE_URL, config.account_sid);
let mut form = HashMap::new();
form.insert("From", &self.from);
form.insert("To", &self.to);
form.insert("Body", &self.body);
let client = Client::new();
let response = client
.post(url)
.basic_auth(&config.account_sid, Some(&config.auth_token))
.form(&form)
.send()
.unwrap();
match response.status() {
reqwest::StatusCode::CREATED | reqwest::StatusCode::OK => {}
other => return Err(TwilioError::HTTPError(other)),
};
Ok(response.json().unwrap())
}
}
|