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
use crate::error::{Error, LastFMError};
use crate::{Client, RequestBuilder};
use serde::Deserialize;
use serde_json;
use std::io::Read;
use std::marker::PhantomData;
#[derive(Debug, Deserialize)]
pub struct UserInfo {
#[serde(rename = "user")]
pub user: User,
}
#[derive(Debug, Deserialize)]
pub struct User {
#[serde(rename = "playcount")]
pub total_tracks: String,
#[serde(rename = "name")]
pub username: String,
pub url: String,
pub country: String,
#[serde(rename = "image")]
pub images: Vec<Image>,
pub registered: Registered,
#[serde(rename = "realname")]
pub display_name: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct Image {
#[serde(rename = "size")]
pub image_size: String,
#[serde(rename = "#text")]
pub image_url: String,
}
#[derive(Debug, Deserialize)]
pub struct Registered {
#[serde(rename = "unixtime")]
pub unix_timestamp: String,
#[serde(rename = "#text")]
pub friendly_date: i64,
}
impl UserInfo {
pub fn build<'a>(client: &'a mut Client, user: &str) -> RequestBuilder<'a, UserInfo> {
let url = client.build_url(vec![("method", "user.getInfo"), ("user", user)]);
RequestBuilder { client, url, phantom: PhantomData }
}
}
impl<'a> RequestBuilder<'a, UserInfo> {
pub fn send(&'a mut self) -> Result<UserInfo, Error> {
match self.client.request(&self.url) {
Ok(mut response) => {
let mut body = String::new();
response.read_to_string(&mut body).unwrap();
match serde_json::from_str::<LastFMError>(&*body) {
Ok(lastm_error) => Err(Error::LastFMError(lastm_error.into())),
Err(_) => match serde_json::from_str::<UserInfo>(&*body) {
Ok(user) => Ok(user),
Err(e) => Err(Error::ParsingError(e)),
},
}
}
Err(err) => Err(Error::HTTPError(err)),
}
}
}
impl<'a> Client {
pub fn user_info(&'a mut self, user: &str) -> RequestBuilder<'a, UserInfo> {
UserInfo::build(self, user)
}
}
#[cfg(test)]
mod tests {
use crate::tests::make_client;
#[test]
fn test_user_info() {
let mut client = make_client();
let user_info = client.user_info("LAST.HQ").send();
println!("{:#?}", user_info);
assert!(user_info.is_ok());
}
}