fractal-api 0.7.0

Fractal Global Credits API client library
Documentation
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use std::io::Read;

use hyper::method::Method;
use hyper::header::{Headers, Authorization};
use rustc_serialize::json;

use chrono::NaiveDate;
use utils::Address;
use dto::{FromDTO, UserDTO, ProfileDTO, AuthenticationCodeDTO, ResponseDTO, UpdateUserDTO,
          SearchUserDTO};

use super::{Client, VoidDTO};
use error::{Result, Error};
use super::types::{User, Profile};
use super::oauth::AccessToken;

/// User methods for the client.
///
/// This are the user getters, setters and creators for the client.
impl Client {
    /// Resends the email confirmation
    pub fn resend_email_confirmation(&self, access_token: &AccessToken) -> Result<()> {
        if access_token.get_user_id().is_some() && !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let _ = self.send_request(Method::Get,
                              format!("{}resend_email_confirmation", self.url),
                              headers,
                              None::<&VoidDTO>)?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired user token")))
        }
    }

    /// Get the user
    pub fn get_user(&self, access_token: &AccessToken, user_id: u64) -> Result<User> {
        if (access_token.is_user(user_id) || access_token.is_admin()) &&
           !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let mut response = self.send_request(Method::Get,
                              format!("{}user/{}", self.url, user_id),
                              headers,
                              None::<&VoidDTO>)?;
            let mut response_str = String::new();
            let _ = response.read_to_string(&mut response_str)?;
            Ok(User::from_dto(json::decode::<UserDTO>(&response_str)?)?)
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired admin or user \
                                               token, and in the case of a user token, the ID \
                                               in the token must match the given ID")))
        }
    }

    /// Gets the logged in users info
    pub fn get_me(&self, access_token: &AccessToken) -> Result<User> {
        let user_id = access_token.get_user_id();
        if user_id.is_some() && !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let mut response = self.send_request(Method::Get,
                              format!("{}user/{}", self.url, user_id.unwrap()),
                              headers,
                              None::<&VoidDTO>)?;
            let mut response_str = String::new();
            let _ = response.read_to_string(&mut response_str)?;
            Ok(User::from_dto(json::decode::<UserDTO>(&response_str)?)?)
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired user token")))
        }
    }

    /// Gets all users.
    pub fn get_all_users(&self, access_token: &AccessToken) -> Result<Vec<User>> {
        if access_token.is_admin() && !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let mut response = self.send_request(Method::Get,
                              format!("{}all_users", self.url),
                              headers,
                              None::<&VoidDTO>)?;
            let mut response_str = String::new();
            let _ = response.read_to_string(&mut response_str)?;
            let dto_users: Vec<UserDTO> = json::decode(&response_str)?;
            Ok(dto_users.into_iter()
                .filter_map(|u| match User::from_dto(u) {
                    Ok(u) => Some(u),
                    Err(_) => None,
                })
                .collect())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired admin token")))
        }
    }

    /// Deletes the given user.
    pub fn delete_user(&self, access_token: &AccessToken, user_id: u64) -> Result<()> {
        if access_token.is_admin() && !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let _ = self.send_request(Method::Delete,
                              format!("{}user/{}", self.url, user_id),
                              headers,
                              None::<&VoidDTO>)?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired admin token")))
        }
    }

    // TODO update user

    /// Generates a new authenticator code, and returns the URL.
    pub fn generate_authenticator_code(&self, access_token: &AccessToken) -> Result<String> {
        if access_token.get_user_id().is_some() && !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let mut response = self.send_request(Method::Get,
                              format!("{}generate_authenticator_code", self.url),
                              headers,
                              None::<&VoidDTO>)?;
            let mut response_str = String::new();
            let _ = response.read_to_string(&mut response_str)?;
            Ok(json::decode::<ResponseDTO>(&response_str)?.message)
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired user token")))
        }
    }

    /// Authenticates the user with 2FA
    pub fn authenticate(&self, access_token: &AccessToken, code: u32) -> Result<()> {
        if access_token.get_user_id().is_some() && !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let dto = AuthenticationCodeDTO { code: code };
            let _ = self.send_request(Method::Post,
                              format!("{}authenticate", self.url),
                              headers,
                              Some(&dto))?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired user token")))
        }
    }


    /// Sets the users username
    pub fn set_username<U: Into<String>>(&self,
                                         access_token: &AccessToken,
                                         user_id: u64,
                                         username: U)
                                         -> Result<()> {
        if (access_token.is_user(user_id) || access_token.is_admin()) &&
           !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let dto = UpdateUserDTO {
                new_username: Some(username.into()),
                new_email: None,
                new_first: None,
                new_last: None,
                old_password: None,
                new_password: None,
                new_phone: None,
                new_birthday: None,
                new_image: None,
                new_address: None,
            };
            let _ = self.send_request(Method::Post,
                              format!("{}update_user/{}", self.url, user_id),
                              headers,
                              Some(&dto))?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired admin or user \
                                               token, and in the case of a user token, the ID \
                                               in the token must match the given ID")))
        }
    }

    /// Sets the users phone
    pub fn set_phone<P: Into<String>>(&self,
                                      access_token: &AccessToken,
                                      user_id: u64,
                                      phone: P)
                                      -> Result<()> {
        if (access_token.is_user(user_id) || access_token.is_admin()) &&
           !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let dto = UpdateUserDTO {
                new_username: None,
                new_email: None,
                new_first: None,
                new_last: None,
                old_password: None,
                new_password: None,
                new_phone: Some(phone.into()),
                new_birthday: None,
                new_image: None,
                new_address: None,
            };
            let _ = self.send_request(Method::Post,
                              format!("{}update_user/{}", self.url, user_id),
                              headers,
                              Some(&dto))?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired admin or user \
                                               token, and in the case of a user token, the ID \
                                               in the token must match the given ID")))
        }
    }

    /// Sets the users birthday
    pub fn set_birthday(&self,
                        access_token: &AccessToken,
                        user_id: u64,
                        birthday: NaiveDate)
                        -> Result<()> {
        if (access_token.is_user(user_id) || access_token.is_admin()) &&
           !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let dto = UpdateUserDTO {
                new_username: None,
                new_email: None,
                new_first: None,
                new_last: None,
                old_password: None,
                new_password: None,
                new_phone: None,
                new_birthday: Some(birthday),
                new_image: None,
                new_address: None,
            };
            let _ = self.send_request(Method::Post,
                              format!("{}update_user/{}", self.url, user_id),
                              headers,
                              Some(&dto))?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired admin or user \
                                               token, and in the case of a user token, the ID \
                                               in the token must match the given ID")))
        }
    }

    /// Sets the users first and last name
    pub fn set_name<F: Into<String>, L: Into<String>>(&self,
                                                      access_token: &AccessToken,
                                                      user_id: u64,
                                                      first: F,
                                                      last: L)
                                                      -> Result<()> {
        if (access_token.is_user(user_id) || access_token.is_admin()) &&
           !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let dto = UpdateUserDTO {
                new_username: None,
                new_email: None,
                new_first: Some(first.into()),
                new_last: Some(last.into()),
                old_password: None,
                new_password: None,
                new_phone: None,
                new_birthday: None,
                new_image: None,
                new_address: None,
            };
            let _ = self.send_request(Method::Post,
                              format!("{}update_user/{}", self.url, user_id),
                              headers,
                              Some(&dto))?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired admin or user \
                                               token, and in the case of a user token, the ID \
                                               in the token must match the given ID")))
        }
    }

    /// Sets the users email
    pub fn set_email<E: Into<String>>(&self,
                                      access_token: &AccessToken,
                                      user_id: u64,
                                      email: E)
                                      -> Result<()> {
        if (access_token.is_user(user_id) || access_token.is_admin()) &&
           !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let dto = UpdateUserDTO {
                new_username: None,
                new_email: Some(email.into()),
                new_first: None,
                new_last: None,
                old_password: None,
                new_password: None,
                new_phone: None,
                new_birthday: None,
                new_image: None,
                new_address: None,
            };
            let _ = self.send_request(Method::Post,
                              format!("{}update_user/{}", self.url, user_id),
                              headers,
                              Some(&dto))?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired admin or user \
                                               token, and in the case of a user token, the ID \
                                               in the token must match the given ID")))
        }
    }

    /// Sets the users profile picture to the given URL
    pub fn set_image<I: Into<String>>(&self,
                                      access_token: &AccessToken,
                                      user_id: u64,
                                      image_url: I)
                                      -> Result<()> {
        if (access_token.is_user(user_id) || access_token.is_admin()) &&
           !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let dto = UpdateUserDTO {
                new_username: None,
                new_email: None,
                new_first: None,
                new_last: None,
                old_password: None,
                new_password: None,
                new_phone: None,
                new_birthday: None,
                new_image: Some(image_url.into()),
                new_address: None,
            };
            let _ = self.send_request(Method::Post,
                              format!("{}update_user/{}", self.url, user_id),
                              headers,
                              Some(&dto))?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired admin or user \
                                               token, and in the case of a user token, the ID \
                                               in the token must match the given ID")))
        }
    }

    /// Sets the users address
    pub fn set_address(&self,
                       access_token: &AccessToken,
                       user_id: u64,
                       address: Address)
                       -> Result<()> {
        if (access_token.is_user(user_id) || access_token.is_admin()) &&
           !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let dto = UpdateUserDTO {
                new_username: None,
                new_email: None,
                new_first: None,
                new_last: None,
                old_password: None,
                new_password: None,
                new_phone: None,
                new_birthday: None,
                new_image: None,
                new_address: Some(address),
            };
            let _ = self.send_request(Method::Post,
                              format!("{}update_user/{}", self.url, user_id),
                              headers,
                              Some(&dto))?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired admin or user \
                                               token, and in the case of a user token, the ID \
                                               in the token must match the given ID")))
        }
    }

    /// Sets the user password
    pub fn set_password<O: Into<String>, N: Into<String>>(&self,
                                                          access_token: &AccessToken,
                                                          old_password: O,
                                                          new_password: N)
                                                          -> Result<()> {
        let user_id = access_token.get_user_id();
        if user_id.is_some() && !access_token.has_expired() {
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let dto = UpdateUserDTO {
                new_username: None,
                new_email: None,
                new_first: None,
                new_last: None,
                old_password: Some(old_password.into()),
                new_password: Some(new_password.into()),
                new_phone: None,
                new_birthday: None,
                new_image: None,
                new_address: None,
            };
            let _ = self.send_request(Method::Post,
                              format!("{}update_user/{}", self.url, user_id.unwrap()),
                              headers,
                              Some(&dto))?;
            Ok(())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired user token")))
        }
    }

    /// Searches users doing a random search with the given string. It will try to find the string
    /// in names, emails etc.
    ///
    /// It will panic if the `include_me` or `include_friends` variables are set and the token is
    /// not an user scoped token.
    pub fn search_user_random<R: Into<String>>(&self,
                                               access_token: &AccessToken,
                                               random: R,
                                               include_me: bool,
                                               include_friends: bool)
                                               -> Result<Vec<Profile>> {
        let user_id = access_token.get_user_id();
        if (access_token.is_public() || user_id.is_some()) && !access_token.has_expired() {
            if (include_me || include_friends) && user_id.is_none() {
                panic!("to include the current user or friends the token must be a user scoped \
                        token");
            }
            let mut headers = Headers::new();
            headers.set(Authorization(access_token.get_token()));
            let dto = SearchUserDTO {
                random: Some(random.into()),
                username: None,
                email: None,
                first_name: None,
                last_name: None,
                age: None,
                country: None,
                state: None,
                city: None,
                phone: None,
                all: false,
                include_me: include_me,
                include_friends: include_friends,
            };
            let mut response = self.send_request(Method::Post,
                              format!("{}search_user", self.url),
                              headers,
                              Some(&dto))?;
            let mut response_str = String::new();
            let _ = response.read_to_string(&mut response_str)?;
            let dto_users: Vec<ProfileDTO> = json::decode(&response_str)?;
            Ok(dto_users.into_iter()
                .filter_map(|u| match Profile::from_dto(u) {
                    Ok(u) => Some(u),
                    Err(_) => None,
                })
                .collect())
        } else {
            Err(Error::Forbidden(String::from("the token must be an unexpired public or user \
                                               token")))
        }
    }
}