aboutsummaryrefslogtreecommitdiff
path: root/src/tw/user.rs
blob: 4fde026d781c737a0c55098309fd2747223cb539 (plain)
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
extern crate serde_json;

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct User {
    pub id: String,
    pub name: String,
    pub handle: String,
    #[serde(default)]
    pub protected: bool,
    #[serde(default)]
    pub verified: bool
}

impl Default for User {
    fn default() -> User {
        User {
            id: "".to_owned(),
            name: "_default_".to_owned(),
            handle: "_default_".to_owned(),
            protected: false,
            verified: false
        }
    }
}

impl User {
    pub fn from_json(json: serde_json::Value) -> Result<User, String> {
        if let serde_json::Value::Object(json_map) = json {
            if let (
                Some(id_str),
                Some(name),
                Some(screen_name),
                Some(protected),
                Some(bluecheck)
            ) = (
                json_map.get("id_str").and_then(|x| x.as_str()),
                json_map.get("name").and_then(|x| x.as_str()),
                json_map.get("screen_name").and_then(|x| x.as_str()),
                json_map.get("protected").and_then(|x| x.as_bool()),
                json_map.get("verified").and_then(|x| x.as_bool())
            ) {
                Ok(User {
                    id: id_str.to_owned(),
                    name: name.to_owned(),
                    handle: screen_name.to_owned(),
                    protected: protected.to_owned(),
                    verified: bluecheck.to_owned()
                })
            } else {
                Err("user json missing one of id_str, name, screen_name".to_owned())
            }
        } else {
            Err(format!("Invalid json: {:?}", json))
        }
    }
}