summaryrefslogtreecommitdiff
path: root/src/client.rs
blob: b814a52eac538f95dad43a2dbb4ba0178e776bf1 (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
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
//! Deezer client.
use std::fmt::Debug;
use std::time::Duration;

use hyper::client::{Client, HttpConnector};
use hyper::Uri;
use serde::Deserialize;

use crate::auth::{AccessToken, AuthCode};
use crate::errors::client::DeezerClientError;
use crate::playlist::Playlist;
use crate::user::{User, UserPlaylist, UserPlaylists};

/// Deezer API error.
#[derive(Debug, Deserialize)]
pub struct DeezerError
{
    /// Error type.
    #[serde(rename = "type")]
    pub err_type: String,

    /// Error message.
    pub message: String,

    /// Error code.
    pub code: u32,
}

#[derive(Debug, Deserialize)]
struct ErrorResponseBody
{
    error: DeezerError,
}

#[derive(Debug, Deserialize)]
struct AccessTokenResponse
{
    pub access_token: String,
    pub expires: u64,
}

impl From<AccessTokenResponse> for AccessToken
{
    fn from(response: AccessTokenResponse) -> Self
    {
        Self {
            access_token: response.access_token,
            expires: Duration::from_secs(response.expires),
        }
    }
}

/// Deezer client.
#[derive(Default)]
pub struct DeezerClient
{
    client: Client<HttpConnector>,
    api_uri_authority: &'static str,
    access_token_uri_authority: &'static str,
    access_token_uri_path: &'static str,
}

impl DeezerClient
{
    /// Creates a new Deezer client.
    #[must_use]
    pub fn new() -> Self
    {
        Self {
            client: Client::new(),
            api_uri_authority: "api.deezer.com",
            access_token_uri_authority: "connect.deezer.com",
            access_token_uri_path: "/oauth/access_token.php",
        }
    }

    /// Returns the authenticated user.
    ///
    /// # Errors
    /// Will return Err if either sending the request or parsing the response fails.
    pub async fn get_me(
        &self,
        access_token: AccessToken,
    ) -> Result<User, DeezerClientError>
    {
        let response = self
            .client
            .get(self.build_endpoint_uri(
                &"user/me".to_string(),
                &[("access_token", access_token.access_token)],
            )?)
            .await?;

        let body_buf = &*hyper::body::to_bytes(response).await?;

        let err_body_result: Result<ErrorResponseBody, _> =
            serde_json::from_slice(body_buf);

        if let Ok(err_body) = err_body_result {
            return Err(DeezerClientError::ReceivedErrorResponse(err_body.error));
        }

        serde_json::from_slice(body_buf).map_err(DeezerClientError::ParseResponseFailed)
    }

    /// Returns the playlists of a user.
    ///
    /// # Errors
    /// Will return Err if either sending the request or parsing the response fails.
    pub async fn get_user_playlists(
        &self,
        user_id: u64,
        access_token: AccessToken,
    ) -> Result<Vec<UserPlaylist>, DeezerClientError>
    {
        let response = self
            .client
            .get(self.build_endpoint_uri(
                &format!("user/{}/playlists", user_id),
                &[("access_token", access_token.access_token)],
            )?)
            .await?;

        let body_buf = &*hyper::body::to_bytes(response).await?;

        let err_body_result: Result<ErrorResponseBody, _> =
            serde_json::from_slice(body_buf);

        if let Ok(err_body) = err_body_result {
            return Err(DeezerClientError::ReceivedErrorResponse(err_body.error));
        }

        let user_playlists: UserPlaylists = serde_json::from_slice(body_buf)
            .map_err(DeezerClientError::ParseResponseFailed)?;

        Ok(user_playlists.data)
    }

    /// Returns a playlist.
    ///
    /// # Errors
    /// Will return Err if either sending the request or parsing the response fails.
    pub async fn get_playlist(
        &self,
        playlist_id: u64,
        access_token: AccessToken,
    ) -> Result<Playlist, DeezerClientError>
    {
        let response = self
            .client
            .get(self.build_endpoint_uri(
                &format!("playlist/{}", playlist_id),
                &[("access_token", access_token.access_token)],
            )?)
            .await?;

        let body_buf = &*hyper::body::to_bytes(response).await?;

        let err_body_result: Result<ErrorResponseBody, _> =
            serde_json::from_slice(body_buf);

        if let Ok(err_body) = err_body_result {
            return Err(DeezerClientError::ReceivedErrorResponse(err_body.error));
        }

        serde_json::from_slice(body_buf).map_err(DeezerClientError::ParseResponseFailed)
    }

    /// Returns a access token.
    ///
    /// # Errors
    /// Will return Err if either sending the request or parsing the response fails.
    pub async fn get_access_token(
        &self,
        app_id: u32,
        secret_key: String,
        auth_code: AuthCode,
    ) -> Result<AccessToken, DeezerClientError>
    {
        let uri = Uri::builder()
            .scheme("http")
            .authority(self.access_token_uri_authority)
            .path_and_query(format!(
                "{}?app_id={}&secret={}&code={}&output=json",
                self.access_token_uri_path, app_id, secret_key, auth_code
            ))
            .build()
            .map_err(|_| DeezerClientError::BuildAPIEndpointURIFailed)?;

        let response = self.client.get(uri).await?;

        let body_buf = &*hyper::body::to_bytes(response).await?;

        let err_body_result: Result<ErrorResponseBody, _> =
            serde_json::from_slice(body_buf);

        if let Ok(err_body) = err_body_result {
            return Err(DeezerClientError::ReceivedErrorResponse(err_body.error));
        }

        let access_token_response_result =
            serde_json::from_slice::<AccessTokenResponse>(body_buf);

        if let Ok(access_token_response) = access_token_response_result {
            Ok(access_token_response.into())
        } else {
            let body_str = std::str::from_utf8(body_buf)
                .map_err(|_| DeezerClientError::AuthErrorResponseNotUTF8)?;

            Err(DeezerClientError::ReceivedAuthErrorResponse(
                body_str.to_string(),
            ))
        }
    }

    fn build_endpoint_uri(
        &self,
        endpoint: &String,
        query_params: &[(&'static str, String)],
    ) -> Result<Uri, DeezerClientError>
    {
        Uri::builder()
            .scheme("http")
            .authority(self.api_uri_authority)
            .path_and_query(format!(
                "/{}?{}",
                endpoint,
                query_params
                    .iter()
                    .map(|(key, value)| format!("{}={}", key, value))
                    .fold(String::new(), |acc, query_param| format!(
                        "{}&{}",
                        acc, query_param
                    ))
            ))
            .build()
            .map_err(|_| DeezerClientError::BuildAPIEndpointURIFailed)
    }
}