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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use std::fmt;
use std::str;
use std::io::Read;
use reqwest::Client;
use ::connection::map_response_code;
use ::errors::ApiError;
use ::MSGAPI_URL;
#[derive(Debug, PartialEq)]
pub enum LookupCriterion {
Phone(String),
PhoneHash(String),
Email(String),
EmailHash(String),
}
impl fmt::Display for LookupCriterion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&LookupCriterion::Phone(ref n) => write!(f, "phone {}", n),
&LookupCriterion::PhoneHash(ref nh) => write!(f, "phone hash {}", nh),
&LookupCriterion::Email(ref e) => write!(f, "email {}", e),
&LookupCriterion::EmailHash(ref eh) => write!(f, "email hash {}", eh),
}
}
}
#[derive(Debug, PartialEq)]
pub struct Capabilities {
pub text: bool,
pub image: bool,
pub video: bool,
pub audio: bool,
pub file: bool,
pub other: Vec<String>,
}
impl Capabilities {
fn new() -> Self {
Capabilities {
text: false,
image: false,
video: false,
audio: false,
file: false,
other: Vec::new(),
}
}
}
impl str::FromStr for Capabilities {
type Err = ApiError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut capabilities = Capabilities::new();
for capability in s.split(',').map(str::trim).map(str::to_lowercase) {
match capability.as_ref() {
"text" => capabilities.text = true,
"image" => capabilities.image = true,
"video" => capabilities.video = true,
"audio" => capabilities.audio = true,
"file" => capabilities.file = true,
_ if capability.len() > 0 => capabilities.other.push(capability),
_ => { },
};
};
Ok(capabilities)
}
}
impl fmt::Display for Capabilities {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{ text: {}, image: {}, video: {}, audio: {}, file: {}",
self.text, self.image, self.video, self.audio, self.file)?;
if self.other.len() > 0 {
write!(f, ", other: {} }}", self.other.join(","))?;
} else {
write!(f, " }}")?;
}
Ok(())
}
}
impl Capabilities {
pub fn can(&self, capability: &str) -> bool {
match capability {
"text" => self.text,
"image" => self.image,
"video" => self.video,
"audio" => self.audio,
"file" => self.file,
_ => self.other.contains(&capability.to_lowercase()),
}
}
}
pub fn lookup_pubkey(our_id: &str, their_id: &str, secret: &str) -> Result<String, ApiError> {
let client = Client::new().expect("Could not initialize HTTP client");
let url = format!("{}/pubkeys/{}?from={}&secret={}", MSGAPI_URL, their_id, our_id, secret);
debug!("Looking up public key for {}", their_id);
let mut res = client.get(&url).expect("Could not parse URL").send()?;
try!(map_response_code(&res.status(), None));
let mut body = String::new();
try!(res.read_to_string(&mut body));
Ok(body)
}
pub fn lookup_id(criterion: &LookupCriterion, our_id: &str, secret: &str) -> Result<String, ApiError> {
let client = Client::new().expect("Could not initialize HTTP client");
let url_base = match criterion {
&LookupCriterion::Phone(ref val) => format!("{}/lookup/phone/{}", MSGAPI_URL, val),
&LookupCriterion::PhoneHash(ref val) => format!("{}/lookup/phone_hash/{}", MSGAPI_URL, val),
&LookupCriterion::Email(ref val) => format!("{}/lookup/email/{}", MSGAPI_URL, val),
&LookupCriterion::EmailHash(ref val) => format!("{}/lookup/email_hash/{}", MSGAPI_URL, val),
};
let url = format!("{}?from={}&secret={}", url_base, our_id, secret);
debug!("Looking up id key for {}", criterion);
let mut res = client.get(&url).expect("Could not parse URL").send()?;
try!(map_response_code(&res.status(), Some(ApiError::BadHashLength)));
let mut body = String::new();
try!(res.read_to_string(&mut body));
Ok(body)
}
pub fn lookup_credits(our_id: &str, secret: &str) -> Result<i64, ApiError> {
let client = Client::new().expect("Could not initialize HTTP client");
let url = format!("{}/credits?from={}&secret={}", MSGAPI_URL, our_id, secret);
debug!("Looking up remaining credits");
let mut res = client.get(&url).expect("Could not parse URL").send()?;
try!(map_response_code(&res.status(), None));
let mut body = String::new();
try!(res.read_to_string(&mut body));
body.trim().parse::<i64>()
.map_err(|_| ApiError::ParseError(format!("Could not parse response body as i64: \"{}\"", body)))
}
pub fn lookup_capabilities(our_id: &str, their_id: &str, secret: &str) -> Result<Capabilities, ApiError> {
let client = Client::new().expect("Could not initialize HTTP client");
let url = format!("{}/capabilities/{}?from={}&secret={}", MSGAPI_URL, their_id, our_id, secret);
debug!("Looking up capabilities for {}", their_id);
let mut res = client.get(&url).expect("Could not parse URL").send()?;
try!(map_response_code(&res.status(), Some(ApiError::BadHashLength)));
let mut body = String::new();
try!(res.read_to_string(&mut body));
body.parse()
}
#[cfg(test)]
mod tests {
use super::{LookupCriterion, Capabilities};
#[test]
fn test_lookup_criterion_display() {
let phone = LookupCriterion::Phone("1234".to_string());
let phone_hash = LookupCriterion::PhoneHash("1234567890abcdef".to_string());
let email = LookupCriterion::Email("user@example.com".to_string());
let email_hash = LookupCriterion::EmailHash("1234567890abcdef".to_string());
assert_eq!(&phone.to_string(), "phone 1234");
assert_eq!(&phone_hash.to_string(), "phone hash 1234567890abcdef");
assert_eq!(&email.to_string(), "email user@example.com");
assert_eq!(&email_hash.to_string(), "email hash 1234567890abcdef");
}
#[test]
fn test_parse_capabilities_empty() {
assert_eq!("".parse::<Capabilities>().unwrap(), Capabilities {
text: false,
image: false,
video: false,
audio: false,
file: false,
other: vec![],
});
}
#[test]
fn test_parse_capabilities_simple() {
assert_eq!("image".parse::<Capabilities>().unwrap(), Capabilities {
text: false,
image: true,
video: false,
audio: false,
file: false,
other: vec![],
});
}
#[test]
fn test_parse_capabilities_combined() {
assert_eq!("image,video,file".parse::<Capabilities>().unwrap(), Capabilities {
text: false,
image: true,
video: true,
audio: false,
file: true,
other: vec![],
});
}
#[test]
fn test_parse_capabilities_unknown() {
assert_eq!("jetpack,text,lasersword".parse::<Capabilities>().unwrap(), Capabilities {
text: true,
image: false,
video: false,
audio: false,
file: false,
other: vec!["jetpack".into(), "lasersword".into()],
});
}
#[test]
fn test_parse_capabilities_cleanup() {
assert_eq!("jetpack,Text ,LASERSWORD,,.,".parse::<Capabilities>().unwrap(), Capabilities {
text: true,
image: false,
video: false,
audio: false,
file: false,
other: vec!["jetpack".into(), "lasersword".into(), ".".into()],
});
}
#[test]
fn test_parse_capabilities_can() {
let cap = "jetpack,Text ,LASERSWORD,,.,".parse::<Capabilities>().unwrap();
assert_eq!(cap, Capabilities {
text: true,
image: false,
video: false,
audio: false,
file: false,
other: vec!["jetpack".into(), "lasersword".into(), ".".into()],
});
assert!(cap.can("jetpack"));
assert!(cap.can("text"));
assert!(cap.can("lasersword"));
assert!(cap.can("."));
assert!(!cap.can("image"));
}
}