rustfm-scrobble 1.1.1

Last.fm Scrobble crate for Rust
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
// Last.fm scrobble API 2.0 client
use std::collections::HashMap;
use std::fmt;
use ureq;

use crate::auth::Credentials;
use crate::models::responses::{
    AuthResponse, BatchScrobbleResponse, BatchScrobbleResponseWrapper, NowPlayingResponse,
    NowPlayingResponseWrapper, ScrobbleResponse, ScrobbleResponseWrapper, SessionResponse,
};

pub enum ApiOperation {
    AuthWebSession,
    AuthMobileSession,
    NowPlaying,
    Scrobble,
}

impl fmt::Display for ApiOperation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let str = match *self {
            Self::AuthWebSession => "auth.getSession",
            Self::AuthMobileSession => "auth.getMobileSession",
            Self::NowPlaying => "track.updateNowPlaying",
            Self::Scrobble => "track.scrobble",
        };
        write!(f, "{}", str)
    }
}

pub struct LastFm {
    auth: Credentials,
    http_client: ureq::Agent,
}

impl LastFm {
    pub fn new(api_key: &str, api_secret: &str) -> Self {
        let partial_auth = Credentials::new_partial(api_key, api_secret);
        let http_client = ureq::agent();

        Self {
            auth: partial_auth,
            http_client,
        }
    }

    pub fn set_user_credentials(&mut self, username: &str, password: &str) {
        self.auth.set_user_credentials(username, password);
    }

    pub fn set_user_token(&mut self, token: &str) {
        self.auth.set_user_token(token);
    }

    pub fn authenticate_with_password(&mut self) -> Result<SessionResponse, String> {
        let params = self.auth.get_auth_request_params()?;

        let body = self
            .api_request(&ApiOperation::AuthMobileSession, params)
            .map_err(|msg| format!("Authentication failed: {}", msg))?;

        let decoded: AuthResponse = serde_json::from_str(body.as_str())
            .map_err(|err| format!("Authentication failed: {}", err))?;

        self.auth.set_session_key(&decoded.session.key);

        Ok(decoded.session)
    }

    pub fn authenticate_with_token(&mut self) -> Result<SessionResponse, String> {
        let params = self.auth.get_auth_request_params()?;

        let body = self
            .api_request(&ApiOperation::AuthWebSession, params)
            .map_err(|msg| format!("Authentication failed: {}", msg))?;

        let decoded: AuthResponse = serde_json::from_str(body.as_str())
            .map_err(|err| format!("Authentication failed: {}", err))?;

        self.auth.set_session_key(&decoded.session.key);

        Ok(decoded.session)
    }

    /// Authenticates with a session key 
    /// 
    /// This requires no initial authentication with the API, so we simply store the key. It must be a valid session
    /// key. Session keys are documented at `Scrobbler::authenticate_with_session_key`.
    pub fn authenticate_with_session_key(&mut self, session_key: &str) {
        self.auth.set_session_key(session_key)
    }

    pub fn session_key(&self) -> Option<&str> {
        self.auth.session_key()
    }

    pub fn send_now_playing(
        &self,
        params: &HashMap<String, String>,
    ) -> Result<NowPlayingResponse, String> {
        let body = self
            .send_authenticated_request(&ApiOperation::NowPlaying, params)
            .map_err(|msg| format!("Now playing request failed: {}", msg))?;

        let decoded: NowPlayingResponseWrapper = serde_json::from_str(body.as_str())
            .map_err(|msg| format!("Now playing request failed: {}", msg))?;

        Ok(decoded.nowplaying)
    }

    pub fn send_scrobble(
        &self,
        params: &HashMap<String, String>,
    ) -> Result<ScrobbleResponse, String> {
        let body = self
            .send_authenticated_request(&ApiOperation::Scrobble, params)
            .map_err(|msg| format!("Scrobble request failed: {}", msg))?;

        let decoded: ScrobbleResponseWrapper = serde_json::from_str(body.as_str())
            .map_err(|msg| format!("Scrobble request failed: {}", msg))?;

        Ok(decoded.scrobbles.scrobble)
    }

    pub fn send_batch_scrobbles(
        &self,
        params: &HashMap<String, String>,
    ) -> Result<BatchScrobbleResponse, String> {
        let body = self
            .send_authenticated_request(&ApiOperation::Scrobble, params)
            .map_err(|msg| format!("Batch scrobble request failed: {}", msg))?;

        let wrapper: BatchScrobbleResponseWrapper = serde_json::from_str(body.as_str())
            .map_err(|msg| format!("Batch scrobble request failed: {}", msg))?;

        Ok(BatchScrobbleResponse {
            scrobbles: wrapper.scrobbles.scrobbles,
        })
    }

    pub fn send_authenticated_request(
        &self,
        operation: &ApiOperation,
        params: &HashMap<String, String>,
    ) -> Result<String, String> {
        if !self.auth.is_authenticated() {
            return Err("Not authenticated".to_string());
        }

        let mut req_params = self.auth.get_request_params();
        for (k, v) in params {
            req_params.insert(k.clone(), v.clone());
        }

        self.api_request(&operation, req_params)
    }

    fn api_request(
        &self,
        operation: &ApiOperation,
        params: HashMap<String, String>,
    ) -> Result<String, String> {
        let resp = self
            .send_request(&operation, params)
            .map_err(|err| err.to_string())?;

        if resp.error() {
            return Err(format!("Non Success status ({})", resp.status()));
        }

        let resp_body = resp
            .into_string()
            .map_err(|_| "Failed to read response body".to_string())?;

        Ok(resp_body)
    }

    fn send_request(
        &self,
        operation: &ApiOperation,
        mut params: HashMap<String, String>,
    ) -> Result<ureq::Response, String> {
        #[cfg(not(test))]
        let url = "https://ws.audioscrobbler.com/2.0/?format=json";
        #[cfg(test)]
        let url = &mockito::server_url();

        let signature = self.auth.get_signature(operation.to_string(), &params);

        params.insert("method".to_string(), operation.to_string());
        params.insert("api_sig".to_string(), signature);

        let params: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();

        let resp = self.http_client.post(url).send_form(&params[..]);
        match resp.synthetic_error() {
            None => Ok(resp),
            Some(e) => Err(e.to_string()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mockito::mock;

    #[test]
    fn check_send_api_requests() {
        let _m = mock("POST", mockito::Matcher::Any)
            .match_body(mockito::Matcher::Any)
            .create();
        let mut client = LastFm::new("key", "secret");
        client.auth.set_user_credentials("username", "password");
        let params = client.auth.get_auth_request_params().unwrap();

        let resp = client.api_request(&ApiOperation::AuthWebSession, params.clone());
        assert!(resp.is_ok());
        let resp = client.api_request(&ApiOperation::AuthMobileSession, params.clone());
        assert!(resp.is_ok());
        let resp = client.api_request(&ApiOperation::Scrobble, params.clone());
        assert!(resp.is_ok());
        let resp = client.api_request(&ApiOperation::NowPlaying, params.clone());
        assert!(resp.is_ok());

        // authenticated request
        let resp = client.send_authenticated_request(&ApiOperation::NowPlaying, &params);
        assert!(resp.is_err());
        client.auth.set_session_key("sesh");
        let resp = client.send_authenticated_request(&ApiOperation::NowPlaying, &params);
        assert!(resp.is_ok());
    }

    #[test]
    fn check_send_scrobble() {
        let _m = mock("POST", mockito::Matcher::Any).create();

        let mut client = LastFm::new("key", "secret");
        client.auth.set_user_credentials("username", "password");
        client.auth.set_session_key("SeshKey");
        let params = client.auth.get_auth_request_params().unwrap();

        let resp = client.send_scrobble(&params);
        assert!(resp.is_err());

        let _m = mock("POST", mockito::Matcher::Any)
            .with_body(
                r#"
            { 
                "scrobbles": [{
                        "artist": [ "0", "foo floyd and the fruit flies" ],
                        "album": [ "1", "old bananas" ], 
                        "albumArtist": [ "0", "foo floyd"],
                        "track": [ "1", "old bananas"], 
                        "timestamp": "2019-10-04 13:23:40" 
                }]
            }
            "#,
            )
            .create();

        let resp = client.send_scrobble(&params);
        assert!(resp.is_ok());
    }

    #[test]
    fn check_send_batch_scrobble() {
        let _m = mock("POST", mockito::Matcher::Any).create();

        let mut client = LastFm::new("key", "secret");
        client.auth.set_user_credentials("username", "password");
        client.auth.set_session_key("SeshKey");
        let params = client.auth.get_auth_request_params().unwrap();

        let resp = client.send_batch_scrobbles(&params);
        assert!(resp.is_err());

        // Test with parsing single-scrobble response
        let _m = mock("POST", mockito::Matcher::Any)
            .with_body(
                r#"
            { 
                "scrobbles": {
                    "scrobble":
                        {
                            "artist": [ "0", "foo floyd and the fruit flies" ],
                            "album": [ "1", "old bananas" ], 
                            "albumArtist": [ "0", "foo floyd"],
                            "track": [ "1", "old bananas"], 
                            "timestamp": "2019-10-04 13:23:40" 
                        }
                }
            }
            "#,
            )
            .create();

        let resp = client.send_batch_scrobbles(&params);
        assert!(resp.is_ok());

        // Test with parsing multi-scrobble response
        let _m = mock("POST", mockito::Matcher::Any)
            .with_body(
                r#"
            { 
                "scrobbles": {
                    "scrobble":[
                        {
                            "artist": [ "0", "foo floyd and the fruit flies" ],
                            "album": [ "1", "old bananas" ], 
                            "albumArtist": [ "0", "foo floyd"],
                            "track": [ "1", "old bananas"], 
                            "timestamp": "2019-10-04 13:23:40" 
                        },
                        {
                            "artist": [ "0", "foo floyd and the fruit flies" ],
                            "album": [ "1", "old bananas" ], 
                            "albumArtist": [ "0", "foo floyd"],
                            "track": [ "1", "old bananas"], 
                            "timestamp": "2019-10-04 13:23:40" 
                        }
                    ]
                }
            }
            "#,
            )
            .create();

        let resp = client.send_batch_scrobbles(&params);
        assert!(resp.is_ok());
    }

    #[test]
    fn check_send_now_playing() {
        let _m = mock("POST", mockito::Matcher::Any).create();

        let mut client = LastFm::new("key", "secret");
        client.auth.set_user_credentials("username", "password");
        client.auth.set_session_key("SeshKey");
        let params = client.auth.get_auth_request_params().unwrap();

        let resp = client.send_now_playing(&params);
        assert!(resp.is_err());

        let _m = mock("POST", mockito::Matcher::Any)
            .with_body(
                r#"
            { 
                "nowplaying": {
                            "artist": [ "0", "foo floyd and the fruit flies" ],
                            "album": [ "1", "old bananas" ], 
                            "albumArtist": [ "0", "foo floyd"],
                            "track": [ "1", "old bananas"], 
                            "timestamp": "2019-10-04 13:23:40" 
                        }
            }
            "#,
            )
            .create();

        let resp = client.send_now_playing(&params);
        assert!(resp.is_ok());
    }

    #[test]
    fn check_set_user_creds_and_token_then_auth() {
        let mut client = LastFm::new("key", "secret");
        client.set_user_credentials("user", "pass");
        client.set_user_token("SomeToken");

        let _m = mock("POST", mockito::Matcher::Any).create();

        let res = client.authenticate_with_password();
        assert!(res.is_err());

        let _m = mock("POST", mockito::Matcher::Any)
            .with_body(
                r#"
                {   
                    "session": {
                        "key": "key",
                        "subscriber": 1337,
                        "name": "foo floyd"
                    }
                }
            "#,
            )
            .create();

        let res = client.authenticate_with_password();
        assert!(res.is_ok());
    }

    #[test]
    fn check_session_key_authentication() {
        let mut client = LastFm::new("key", "secret");
        client.set_user_credentials("user", "pass");
        client.authenticate_with_session_key("seshkey");
        assert_eq!("seshkey", client.session_key().unwrap());
    }
}