lastfm-client 4.0.1

A modern, async Rust library for fetching and analyzing Last.fm user data
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use crate::api::{
    FriendsRequestBuilder, LovedTracksRequestBuilder, PersonalTagsRequestBuilder,
    RecentTracksRequestBuilder, TopAlbumsRequestBuilder, TopArtistsRequestBuilder,
    TopTagsRequestBuilder, TopTracksRequestBuilder, UserInfoRequestBuilder,
    WeeklyAlbumChartRequestBuilder, WeeklyArtistChartRequestBuilder, WeeklyChartListRequestBuilder,
    WeeklyTrackChartRequestBuilder,
};
use crate::client::{
    HttpClient, RateLimitedClient, RateLimiter, ReqwestClient, RetryClient, RetryPolicy,
};
use crate::config::{Config, ConfigBuilder};
use crate::error::Result;
use std::sync::Arc;

/// Main Last.fm API client
///
/// This is the entry point for interacting with the Last.fm API using the new v2.0 API.
///
/// # Example
/// ```
/// use lastfm_client::LastFmClient;
/// use std::time::Duration;
///
/// // Create client with custom configuration
/// let client = LastFmClient::builder()
///     .api_key("your_api_key")
///     .timeout(Duration::from_secs(60))
///     .max_concurrent_requests(10)
///     .build()
///     .unwrap();
///
/// // Use client.recent_tracks() to fetch data
/// ```
pub struct LastFmClient {
    config: Arc<Config>,
    http: Arc<dyn HttpClient>,
}

impl std::fmt::Debug for LastFmClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LastFmClient")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

impl LastFmClient {
    /// Create a new configuration builder
    ///
    /// This is the recommended way to create a `LastFmClient`.
    ///
    /// # Example
    /// ```no_run
    /// use lastfm_client::LastFmClient;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = LastFmClient::builder()
    ///     .api_key("your_api_key")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::new()
    }

    /// Create a new `LastFmClient` with default configuration
    ///
    /// This will automatically try to load the API key from the `LAST_FM_API_KEY`
    /// environment variable. All other settings use sensible defaults.
    ///
    /// # Example
    /// ```no_run
    /// use lastfm_client::LastFmClient;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = LastFmClient::new()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    /// Returns an error if the API key is not set and cannot be loaded from environment
    pub fn new() -> Result<Self> {
        let config = ConfigBuilder::build_with_defaults()?;
        Ok(Self::from_config(config))
    }

    /// Create a new `LastFmClient` from a configuration
    ///
    /// This automatically sets up retry logic and rate limiting based on the configuration.
    /// Most users should use `builder()` instead.
    #[must_use]
    pub fn from_config(config: Config) -> Self {
        // Create base HTTP client
        let base_client = ReqwestClient::new();

        // Build the HTTP client with retry and rate limiting
        let retry_policy = RetryPolicy::exponential(config.retry_attempts());
        let http: Arc<dyn HttpClient> = if let Some(rate_limit_config) = config.rate_limit() {
            let retry_client = RetryClient::new(base_client, retry_policy);

            let limiter = Arc::new(RateLimiter::new(
                rate_limit_config.max_requests,
                rate_limit_config.per_duration,
            ));
            Arc::new(RateLimitedClient::new(retry_client, limiter))
        } else {
            Arc::new(RetryClient::new(base_client, retry_policy))
        };

        Self {
            config: Arc::new(config),
            http,
        }
    }

    /// Create a new `LastFmClient` with a custom HTTP client
    ///
    /// This is primarily useful for testing with a mock HTTP client.
    ///
    /// # Example
    /// ```
    /// use lastfm_client::{LastFmClient, Config, ConfigBuilder};
    /// use lastfm_client::client::MockClient;
    /// use std::sync::Arc;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let config = ConfigBuilder::new()
    ///     .api_key("test_key")
    ///     .build()?;
    ///
    /// let mock = MockClient::new();
    /// let client = LastFmClient::with_http(config, Arc::new(mock));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_http(config: Config, http: Arc<dyn HttpClient>) -> Self {
        Self {
            config: Arc::new(config),
            http,
        }
    }

    /// Get a builder for recent tracks requests
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::{LastFmClient, prelude::*};
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let tracks = client
    ///     .recent_tracks("username")
    ///     .limit(100)
    ///     .fetch()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn recent_tracks(&self, username: impl Into<String>) -> RecentTracksRequestBuilder {
        RecentTracksRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Get a builder for loved tracks requests
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::{LastFmClient, prelude::*};
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let tracks = client
    ///     .loved_tracks("username")
    ///     .limit(100)
    ///     .fetch()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn loved_tracks(&self, username: impl Into<String>) -> LovedTracksRequestBuilder {
        LovedTracksRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Get a builder for top tracks requests
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::{LastFmClient, prelude::*};
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let tracks = client
    ///     .top_tracks("username")
    ///     .limit(100)
    ///     .fetch()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn top_tracks(&self, username: impl Into<String>) -> TopTracksRequestBuilder {
        TopTracksRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Get a builder for top artists requests
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::{LastFmClient, prelude::*};
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let artists = client
    ///     .top_artists("username")
    ///     .limit(100)
    ///     .fetch()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn top_artists(&self, username: impl Into<String>) -> TopArtistsRequestBuilder {
        TopArtistsRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Get a builder for top albums requests
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::{LastFmClient, prelude::*};
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let albums = client
    ///     .top_albums("username")
    ///     .limit(100)
    ///     .fetch()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn top_albums(&self, username: impl Into<String>) -> TopAlbumsRequestBuilder {
        TopAlbumsRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Get a builder for top tags requests
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::LastFmClient;
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let tags = client
    ///     .top_tags("username")
    ///     .limit(20)
    ///     .fetch()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn top_tags(&self, username: impl Into<String>) -> TopTagsRequestBuilder {
        TopTagsRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Get a builder for `user.getWeeklyChartList` requests
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::LastFmClient;
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let ranges = client.weekly_chart_list("username").fetch().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn weekly_chart_list(&self, username: impl Into<String>) -> WeeklyChartListRequestBuilder {
        WeeklyChartListRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Get a builder for `user.getWeeklyTrackChart` requests
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::LastFmClient;
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let ranges = client.weekly_chart_list("username").fetch().await?;
    /// if let Some(range) = ranges.first() {
    ///     let tracks = client.weekly_track_chart("username").range(range).fetch().await?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn weekly_track_chart(
        &self,
        username: impl Into<String>,
    ) -> WeeklyTrackChartRequestBuilder {
        WeeklyTrackChartRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Get a builder for `user.getWeeklyArtistChart` requests
    pub fn weekly_artist_chart(
        &self,
        username: impl Into<String>,
    ) -> WeeklyArtistChartRequestBuilder {
        WeeklyArtistChartRequestBuilder::new(
            self.http.clone(),
            self.config.clone(),
            username.into(),
        )
    }

    /// Get a builder for `user.getWeeklyAlbumChart` requests
    pub fn weekly_album_chart(
        &self,
        username: impl Into<String>,
    ) -> WeeklyAlbumChartRequestBuilder {
        WeeklyAlbumChartRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Get a builder for friends requests
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::LastFmClient;
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let friends = client.friends("rj").fetch_all().await?;
    /// for friend in &friends {
    ///     println!("{}", friend.name);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn friends(&self, username: impl Into<String>) -> FriendsRequestBuilder {
        FriendsRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Get a builder for personal tags requests
    ///
    /// Returns tracks, artists, or albums that the user has tagged with the given tag.
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::LastFmClient;
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let page = client.personal_tags("rj", "rock").fetch_tracks().await?;
    /// for track in &page.tracks {
    ///     println!("{} - {}", track.artist_name, track.name);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn personal_tags(
        &self,
        username: impl Into<String>,
        tag: impl Into<String>,
    ) -> PersonalTagsRequestBuilder {
        PersonalTagsRequestBuilder::new(
            self.http.clone(),
            self.config.clone(),
            username.into(),
            tag.into(),
        )
    }

    /// Get a builder for user profile requests
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::LastFmClient;
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let info = client.user_info("rj").fetch().await?;
    /// println!("{} has {} scrobbles", info.name, info.play_count);
    /// # Ok(())
    /// # }
    /// ```
    pub fn user_info(&self, username: impl Into<String>) -> UserInfoRequestBuilder {
        UserInfoRequestBuilder::new(self.http.clone(), self.config.clone(), username.into())
    }

    /// Check if a Last.fm user exists
    ///
    /// # Example
    /// ```no_run
    /// # use lastfm_client::LastFmClient;
    /// # async fn example(client: LastFmClient) -> Result<(), Box<dyn std::error::Error>> {
    /// if client.user_exists("rj").await? {
    ///     println!("User exists!");
    /// } else {
    ///     println!("User not found");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    /// Returns an error if the request fails due to network issues or other API errors
    /// (not including "user not found" which returns `Ok(false)`)
    pub async fn user_exists(&self, username: impl Into<String>) -> Result<bool> {
        use crate::error::LastFmError;

        match self.user_info(username).fetch().await {
            Ok(_) => Ok(true),
            Err(LastFmError::Api { error_code, .. }) if error_code == 6 || error_code == 7 => {
                Ok(false)
            }
            Err(e) => Err(e),
        }
    }

    /// Get a reference to the configuration
    #[must_use]
    pub fn config(&self) -> &Config {
        &self.config
    }
}

// Convenience: allow building the client directly from the ConfigBuilder
impl ConfigBuilder {
    /// Build a `LastFmClient` directly from this builder
    ///
    /// This is equivalent to calling `build().map(LastFmClient::from_config)`.
    ///
    /// # Errors
    /// Returns an error if the builder is missing required fields (e.g., API key).
    pub fn build_client(self) -> Result<LastFmClient> {
        self.build().map(LastFmClient::from_config)
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::client::MockClient;

    #[test]
    fn test_client_from_config() {
        let config = ConfigBuilder::new().api_key("test_key").build().unwrap();

        let client = LastFmClient::from_config(config);
        assert_eq!(client.config().api_key(), "test_key");
    }

    #[test]
    fn test_client_with_mock() {
        let config = ConfigBuilder::new().api_key("test_key").build().unwrap();

        let mock = MockClient::new();
        let http = Arc::new(mock);
        let client = LastFmClient::with_http(config, http);
        assert_eq!(client.config().api_key(), "test_key");
    }

    #[test]
    fn test_builder() {
        let client = LastFmClient::builder()
            .api_key("test_key")
            .build()
            .map(LastFmClient::from_config)
            .unwrap();

        assert_eq!(client.config().api_key(), "test_key");
    }

    #[tokio::test]
    async fn test_user_exists_returns_true() {
        use serde_json::json;

        let config = ConfigBuilder::new().api_key("test_key").build().unwrap();

        let mock = MockClient::new().with_response(
            "user.getinfo",
            json!({
                "user": {
                    "name": "rj",
                    "realname": "Richard Jones",
                    "url": "https://www.last.fm/user/rj",
                    "country": "UK",
                    "age": "0",
                    "gender": "m",
                    "subscriber": "0",
                    "playcount": "12345",
                    "playlists": "0",
                    "registered": { "unixtime": "1104874958", "#text": "2005-01-05 00:00" }
                }
            }),
        );

        let client = LastFmClient::with_http(config, Arc::new(mock));
        let result = client.user_exists("rj").await;

        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn test_user_exists_returns_false_for_error_6() {
        use serde_json::json;

        let config = ConfigBuilder::new().api_key("test_key").build().unwrap();

        // Mock returns error code 6 (Invalid parameters / user not found)
        let mock = MockClient::new().with_response(
            "user.getinfo",
            json!({
                "error": 6,
                "message": "User not found"
            }),
        );

        let client = LastFmClient::with_http(config, Arc::new(mock));
        let result = client.user_exists("nonexistentuser").await;

        assert!(result.is_ok());
        assert!(!result.unwrap());
    }

    #[tokio::test]
    async fn test_user_exists_returns_false_for_error_7() {
        use serde_json::json;

        let config = ConfigBuilder::new().api_key("test_key").build().unwrap();

        // Mock returns error code 7 (Invalid resource specified)
        let mock = MockClient::new().with_response(
            "user.getinfo",
            json!({
                "error": 7,
                "message": "Invalid resource specified"
            }),
        );

        let client = LastFmClient::with_http(config, Arc::new(mock));
        let result = client.user_exists("invaliduser").await;

        assert!(result.is_ok());
        assert!(!result.unwrap());
    }

    #[tokio::test]
    async fn test_user_exists_propagates_other_api_errors() {
        use crate::error::LastFmError;
        use serde_json::json;

        let config = ConfigBuilder::new().api_key("test_key").build().unwrap();

        // Mock returns error code 10 (Invalid API key)
        let mock = MockClient::new().with_response(
            "user.getinfo",
            json!({
                "error": 10,
                "message": "Invalid API key"
            }),
        );

        let client = LastFmClient::with_http(config, Arc::new(mock));
        let result = client.user_exists("someuser").await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, LastFmError::Api { error_code: 10, .. }));
    }
}