use serde::Deserialize;
use std::marker::PhantomData;
use crate::{
error::{Error, LastFMError},
model::{Attributes, Image, TrackDate},
user::User,
Client, RequestBuilder,
};
#[derive(Debug, Deserialize)]
pub struct RecentTracks {
#[serde(rename = "@attr")]
pub attrs: Attributes,
#[serde(rename = "track")]
pub tracks: Vec<Track>,
}
#[derive(Debug, Deserialize)]
pub struct Track {
pub artist: Artist,
#[serde(rename = "@attr")]
pub attrs: Option<TrackAttributes>,
pub name: String,
pub album: Album,
pub url: String,
pub streamable: String,
#[serde(rename = "image")]
pub images: Vec<Image>,
pub date: Option<TrackDate>,
}
#[derive(Debug, Deserialize)]
pub struct Artist {
#[serde(rename = "#text")]
pub name: String,
}
#[derive(Debug, Deserialize)]
pub struct Album {
#[serde(rename = "#text")]
pub name: String,
}
#[derive(Debug, Deserialize)]
pub struct TrackAttributes {
#[serde(rename = "nowplaying")]
pub now_playing: String,
}
impl RecentTracks {
pub async fn build<'a>(client: &'a mut Client, user: &str) -> RequestBuilder<'a, RecentTracks> {
let url = client.build_url(vec![("method", "user.getRecentTracks"), ("user", user)]).await;
RequestBuilder { client, url, phantom: PhantomData }
}
}
impl<'a> RequestBuilder<'a, RecentTracks> {
add_param!(with_limit, limit, usize);
add_param!(with_page, page, usize);
pub async fn send(&'a mut self) -> Result<RecentTracks, Error> {
match self.client.request(&self.url).await {
Ok(response) => {
let body = response.text().await.unwrap();
match serde_json::from_str::<LastFMError>(&body) {
Ok(lastm_error) => Err(Error::LastFMError(lastm_error.into())),
Err(_) => match serde_json::from_str::<User>(&body) {
Ok(user) => Ok(user.recent_tracks.ok_or("Error while getting recent tracks").unwrap()),
Err(e) => Err(Error::ParsingError(e)),
},
}
}
Err(err) => Err(Error::HTTPError(err)),
}
}
}
impl<'a> Client {
pub async fn recent_tracks(&'a mut self, user: &str) -> RequestBuilder<'a, RecentTracks> { RecentTracks::build(self, user).await }
}