lastfm-client 2.0.0

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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
use crate::analytics::AnalysisHandler;
use crate::api::Period;
use crate::api::constants::{API_MAX_LIMIT, BASE_URL, CHUNK_SIZE};
use crate::config;
use crate::error::{LastFmError, LastFmErrorResponse, Result};
use crate::file_handler::{FileFormat, FileHandler};
use crate::types::{
    LovedTrack, RecentTrack, RecentTrackExtended, Timestamped, TopTrack, UserLovedTracks,
    UserRecentTracks, UserRecentTracksExtended, UserTopTracks,
};
use crate::url_builder::{QueryParams, Url};

use futures::future::join_all;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::fs::File;
use std::path::Path;

#[derive(Debug, Clone, Copy)]
pub enum TrackLimit {
    Limited(u32),
    Unlimited,
}

impl From<Option<u32>> for TrackLimit {
    fn from(opt: Option<u32>) -> Self {
        match opt {
            Some(limit) => TrackLimit::Limited(limit),
            None => TrackLimit::Unlimited,
        }
    }
}

trait TrackContainer {
    type TrackType;

    fn total_tracks(&self) -> u32;
    fn tracks(self) -> Vec<Self::TrackType>;
}

impl TrackContainer for UserLovedTracks {
    type TrackType = LovedTrack;

    fn total_tracks(&self) -> u32 {
        self.lovedtracks.attr.total
    }
    fn tracks(self) -> Vec<Self::TrackType> {
        self.lovedtracks.track
    }
}

impl TrackContainer for UserRecentTracks {
    type TrackType = RecentTrack;

    fn total_tracks(&self) -> u32 {
        self.recenttracks.attr.total
    }
    fn tracks(self) -> Vec<Self::TrackType> {
        self.recenttracks.track
    }
}

impl TrackContainer for UserRecentTracksExtended {
    type TrackType = RecentTrackExtended;

    fn total_tracks(&self) -> u32 {
        self.recenttracks.attr.total
    }
    fn tracks(self) -> Vec<Self::TrackType> {
        self.recenttracks.track
    }
}

impl TrackContainer for UserTopTracks {
    type TrackType = TopTrack;

    fn total_tracks(&self) -> u32 {
        self.toptracks.attr.total
    }
    fn tracks(self) -> Vec<Self::TrackType> {
        self.toptracks.track
    }
}

/// Represents a track's play count information
#[derive(Debug, Serialize)]
pub struct TrackPlayInfo {
    pub name: String,
    pub play_count: u32,
    pub artist: String,
    pub album: Option<String>,
    pub image_url: Option<String>,
    pub currently_playing: bool,
    pub date: Option<u32>,
    pub url: String,
}

#[derive(Debug, Clone)]
pub struct LastFMHandler {
    url: Url,
    base_options: QueryParams,
}

impl LastFMHandler {
    /// Creates a new `LastFMHandler` instance.
    ///
    /// # Arguments
    /// * `username` - The Last.fm username.
    ///
    /// # Errors
    /// Returns `LastFmError::MissingEnvVar` if the environment variable `LAST_FM_API_KEY` is not set.
    ///
    /// # Returns
    /// * `Result<Self>` - The created `LastFMHandler` instance.
    pub fn new(username: &str) -> Result<Self> {
        let api_key = config::get_required_env_var("LAST_FM_API_KEY")?;

        let mut base_options = QueryParams::new();
        base_options.insert("api_key".to_string(), api_key);
        base_options.insert("limit".to_string(), API_MAX_LIMIT.to_string());
        base_options.insert("format".to_string(), "json".to_string());
        base_options.insert("user".to_string(), username.to_string());

        let url = Url::new(BASE_URL);

        Ok(LastFMHandler { url, base_options })
    }

    /// Get loved tracks for a user with all available options.
    ///
    /// This is the most flexible method for fetching loved tracks, exposing all parameters
    /// supported by the Last.fm API's `user.getlovedtracks` method.
    ///
    /// # Arguments
    /// * `limit` - The number of tracks to fetch. Use `None` or `TrackLimit::Unlimited` to fetch all tracks.
    ///
    /// # Errors
    /// Returns an error if the API request fails.
    ///
    /// # Returns
    /// * `Result<Vec<LovedTrack>>` - The fetched loved tracks.
    ///
    /// # Examples
    /// ```ignore
    /// // Get all loved tracks
    /// let tracks = handler.get_user_loved_tracks_with_options(None).await?;
    ///
    /// // Get first 100 loved tracks
    /// let tracks = handler.get_user_loved_tracks_with_options(Some(100)).await?;
    /// ```
    #[deprecated(
        since = "2.0.0",
        note = "Use `LovedTracksClient` from the `api` module instead"
    )]
    pub async fn get_user_loved_tracks_with_options(
        &self,
        limit: impl Into<TrackLimit>,
    ) -> Result<Vec<LovedTrack>> {
        self.get_user_tracks::<UserLovedTracks>("user.getlovedtracks", limit.into(), None)
            .await
    }

    /// Get loved tracks for a user.
    ///
    /// # Arguments
    /// * `limit` - The number of tracks to fetch. If None, fetch all tracks.
    ///
    /// # Errors
    /// Returns an error if the API request fails.
    ///
    /// # Returns
    /// * `Result<Vec<LovedTrack>, Error>` - The fetched tracks.
    #[deprecated(
        since = "2.0.0",
        note = "Use `LovedTracksClient` from the `api` module instead"
    )]
    pub async fn get_user_loved_tracks(
        &self,
        limit: impl Into<TrackLimit>,
    ) -> Result<Vec<LovedTrack>> {
        #[allow(deprecated)]
        self.get_user_loved_tracks_with_options(limit).await
    }

    /// Get recent tracks for a user.
    ///
    /// # Arguments
    /// * `limit` - The number of tracks to fetch. If None, fetch all tracks.
    ///
    /// # Errors
    /// Returns an error if the API request fails.
    ///
    /// # Returns
    /// * `Result<Vec<RecentTrack>, Error>` - The fetched tracks.
    #[deprecated(
        since = "2.0.0",
        note = "Use `RecentTracksClient` from the `api` module instead"
    )]
    pub async fn get_user_recent_tracks(
        &self,
        limit: impl Into<TrackLimit>,
    ) -> Result<Vec<RecentTrack>> {
        #[allow(deprecated)]
        self.get_user_recent_tracks_with_options(limit, None, None, false)
            .await
    }

    /// Get top tracks for a user with all available options.
    ///
    /// This is the most flexible method for fetching top tracks, exposing all parameters
    /// supported by the Last.fm API's `user.gettoptracks` method.
    ///
    /// # Arguments
    /// * `limit` - The number of tracks to fetch. Use `None` or `TrackLimit::Unlimited` to fetch all available top tracks.
    /// * `period` - Optional period filter for the time range:
    ///   - `Period::Overall` - All time (default if None)
    ///   - `Period::Week` - Last 7 days
    ///   - `Period::Month` - Last month
    ///   - `Period::ThreeMonth` - Last 3 months
    ///   - `Period::SixMonth` - Last 6 months
    ///   - `Period::TwelveMonth` - Last 12 months
    ///
    /// # Errors
    /// Returns an error if the API request fails.
    ///
    /// # Returns
    /// * `Result<Vec<TopTrack>>` - The fetched top tracks.
    ///
    /// # Examples
    /// ```ignore
    /// // Get all-time top 50 tracks
    /// let tracks = handler.get_user_top_tracks_with_options(Some(50), None).await?;
    ///
    /// // Get top tracks from the last week
    /// let tracks = handler.get_user_top_tracks_with_options(None, Some(Period::Week)).await?;
    ///
    /// // Get top 100 tracks from the last 3 months
    /// let tracks = handler.get_user_top_tracks_with_options(Some(100), Some(Period::ThreeMonth)).await?;
    /// ```
    #[deprecated(
        since = "2.0.0",
        note = "Use `TopTracksClient` from the `api` module instead"
    )]
    pub async fn get_user_top_tracks_with_options(
        &self,
        limit: impl Into<TrackLimit>,
        period: Option<Period>,
    ) -> Result<Vec<TopTrack>> {
        let mut params = QueryParams::new();
        if let Some(p) = period {
            params.insert("period".to_string(), p.as_api_str().to_string());
        }

        self.get_user_tracks::<UserTopTracks>("user.gettoptracks", limit.into(), Some(params))
            .await
    }

    /// Get top tracks for a user.
    ///
    /// # Arguments
    /// * `limit` - The number of tracks to fetch. If None, fetch all available top tracks.
    /// * `period` - Optional period filter
    ///   (`Period::Overall`, `Period::SevenDay`, `Period::OneMonth`,
    ///   `Period::ThreeMonth`, `Period::SixMonth`, `Period::TwelveMonth`)
    ///
    /// # Errors
    /// Returns an error if the API request fails.
    ///
    /// # Returns
    /// * `Result<Vec<TopTrack>>` - The fetched tracks.
    #[deprecated(
        since = "2.0.0",
        note = "Use `TopTracksClient` from the `api` module instead"
    )]
    pub async fn get_user_top_tracks(
        &self,
        limit: impl Into<TrackLimit>,
        period: Option<Period>,
    ) -> Result<Vec<TopTrack>> {
        #[allow(deprecated)]
        self.get_user_top_tracks_with_options(limit, period).await
    }

    /// Get tracks for a user.
    ///
    /// # Arguments
    /// * `method` - The method to call.
    /// * `limit` - The number of tracks to fetch. If None, fetch all tracks.
    ///
    /// # Returns
    /// * `Result<Vec<T::TrackType>, Error>` - The fetched tracks.
    async fn get_user_tracks<T: DeserializeOwned + TrackContainer>(
        &self,
        method: &str,
        limit: TrackLimit,
        additional_params: Option<QueryParams>,
    ) -> Result<Vec<T::TrackType>> {
        let mut params = self.base_options.clone();
        if let Some(additional_params) = additional_params {
            params.extend(additional_params);
        }

        // Make an initial request to get the total number of tracks
        let mut base_params: QueryParams = HashMap::new();
        base_params.insert("limit".to_string(), "1".to_string());
        base_params.insert("page".to_string(), "1".to_string());
        base_params.extend(params.clone());

        let initial_response: T = self.fetch(method, &base_params).await?;
        let total_tracks = initial_response.total_tracks();

        let final_limit = match limit {
            TrackLimit::Limited(l) => l.min(total_tracks),
            TrackLimit::Unlimited => total_tracks,
        };

        tracing::debug!("Need to fetch {} tracks", final_limit);

        if final_limit <= API_MAX_LIMIT {
            // If we need less than the API limit, just make a single request
            let mut base_params: QueryParams = HashMap::new();
            base_params.insert("limit".to_string(), final_limit.to_string());
            base_params.insert("page".to_string(), "1".to_string());
            base_params.extend(params);

            let response: T = self.fetch(method, &base_params).await?;
            return Ok(response
                .tracks()
                .into_iter()
                .take(final_limit as usize)
                .collect());
        }

        let chunk_nb = final_limit.div_ceil(CHUNK_SIZE);

        let mut all_tracks = Vec::new();

        // Process chunks sequentially
        for chunk_index in 0..chunk_nb {
            tracing::debug!("Processing chunk {}/{}", chunk_index + 1, chunk_nb);
            let chunk_params = params.clone();

            // Calculate how many API calls we need for this chunk
            let chunk_api_calls = if chunk_index == chunk_nb - 1 {
                // Last chunk
                final_limit % CHUNK_SIZE / API_MAX_LIMIT + 1
            } else {
                CHUNK_SIZE / API_MAX_LIMIT
            };

            // Create futures for concurrent API calls within this chunk
            let api_call_futures: Vec<_> = (0..chunk_api_calls)
                .map(|call_index| {
                    let mut call_params = chunk_params.clone();
                    let call_limit =
                        (final_limit - chunk_index * CHUNK_SIZE - call_index * API_MAX_LIMIT)
                            .min(API_MAX_LIMIT);

                    let page = chunk_index * CHUNK_SIZE / API_MAX_LIMIT + call_index + 1;

                    call_params.insert("limit".to_string(), call_limit.to_string());
                    call_params.insert("page".to_string(), page.to_string());

                    async move {
                        let response: T = self.fetch(method, &call_params).await?;
                        Ok::<_, LastFmError>(
                            response
                                .tracks()
                                .into_iter()
                                .take(call_limit as usize)
                                .collect::<Vec<_>>(),
                        )
                    }
                })
                .collect();

            // Process all API calls in this chunk concurrently
            let chunk_results = join_all(api_call_futures).await;

            // Collect results from this chunk
            for result in chunk_results {
                all_tracks.extend(result?);
            }
        }

        Ok(all_tracks)
    }

    /// Fetch data from the `LastFM` API.
    ///
    /// # Arguments
    /// * `method` - The method to call.
    /// * `params` - The parameters to pass to the API.
    ///
    /// # Returns
    /// * `Result<T, Error>` - The fetched data.
    async fn fetch<T: DeserializeOwned>(&self, method: &str, params: &QueryParams) -> Result<T> {
        let mut final_params = self.base_options.clone();
        final_params.insert("method".to_string(), method.to_string());
        final_params.extend(params.clone());

        let base_url = self.url.clone().add_args(final_params).build();

        let response = reqwest::get(&base_url).await?;

        // Check if the response is an error
        if !response.status().is_success() {
            let error: LastFmErrorResponse = response.json().await?;
            return Err(LastFmError::Api {
                method: method.to_string(),
                message: error.message,
                error_code: error.error,
                retryable: false,
            });
        }

        // Try to parse the successful response
        let parsed_response = response.json::<T>().await?;
        Ok(parsed_response)
    }

    /// Get and save recent tracks to a file.
    ///
    /// # Arguments
    /// * `limit` - The number of tracks to fetch. If None, fetch all tracks.
    /// * `format` - The file format to save the tracks in.
    ///
    /// # Errors
    /// * `LastFmError::Api` - If the API returns an error.
    /// * `LastFmError::Io` - If there is an error saving the file.
    ///
    /// # Returns
    /// * `Result<String, Box<dyn std::error::Error>>` - The filename of the saved file.
    pub async fn get_and_save_recent_tracks(
        &self,
        limit: impl Into<TrackLimit>,
        format: FileFormat,
        filename_prefix: &str,
    ) -> Result<String> {
        #[allow(deprecated)]
        let tracks = self.get_user_recent_tracks(limit).await?;
        tracing::info!("Saving {} tracks to file", tracks.len());
        let filename =
            FileHandler::save(&tracks, &format, filename_prefix).map_err(LastFmError::Io)?;
        Ok(filename)
    }

    /// Get and save loved tracks to a file.
    ///
    /// # Arguments
    /// * `limit` - The number of tracks to fetch. If None, fetch all tracks.
    /// * `format` - The file format to save the tracks in.
    ///
    /// # Errors
    /// * `FileError` - If there was an error reading or writing the file
    /// * `InvalidUtf8` - If the file path is not valid UTF-8
    ///
    /// # Returns
    /// * `Result<String, Box<dyn std::error::Error>>` - The filename of the saved file.
    pub async fn get_and_save_loved_tracks(
        &self,
        limit: impl Into<TrackLimit>,
        format: FileFormat,
    ) -> Result<String> {
        #[allow(deprecated)]
        let tracks = self.get_user_loved_tracks(limit).await?;
        let filename =
            FileHandler::save(&tracks, &format, "loved_tracks").map_err(LastFmError::Io)?;
        Ok(filename)
    }

    /// Get recent tracks for a user since a given timestamp.
    ///
    /// # Arguments
    /// * `from` - The timestamp to fetch tracks since.
    /// * `to` - Optional timestamp to fetch tracks until.
    /// * `limit` - The number of tracks to fetch. If None, fetch all tracks.
    ///
    /// # Errors
    /// * `FileError` - If there was an error reading or writing the file
    /// * `InvalidUtf8` - If the file path is not valid UTF-8
    ///
    /// # Returns
    /// * `Vec<RecentTrack>` - The fetched tracks.
    #[allow(dead_code)]
    pub async fn get_user_recent_tracks_since(
        &self,
        from: i64,
        to: Option<i64>,
        limit: impl Into<TrackLimit>,
    ) -> Result<Vec<RecentTrack>> {
        #[allow(deprecated)]
        self.get_user_recent_tracks_with_options(limit, Some(from), to, false)
            .await
    }

    /// Get recent tracks for a user with all available options.
    ///
    /// This is the most flexible method for fetching recent tracks, exposing all parameters
    /// supported by the Last.fm API's `user.getrecenttracks` method.
    ///
    /// # Arguments
    /// * `limit` - The number of tracks to fetch. Use `None` or `TrackLimit::Unlimited` to fetch all tracks.
    /// * `from` - Optional timestamp (Unix timestamp in seconds) to fetch tracks from this time onwards.
    /// * `to` - Optional timestamp (Unix timestamp in seconds) to fetch tracks up until this time.
    /// * `extended` - If `true`, fetches extended track information including additional artist details.
    ///
    /// # Errors
    /// Returns an error if the API request fails.
    ///
    /// # Returns
    /// * `Result<Vec<RecentTrack>>` - The fetched tracks (normal format).
    /// * `Result<Vec<RecentTrackExtended>>` - The fetched tracks (extended format) if `extended` is `true`.
    ///
    /// # Examples
    /// ```ignore
    /// // Get last 50 tracks
    /// let tracks = handler.get_user_recent_tracks_with_options(Some(50), None, None, false).await?;
    ///
    /// // Get tracks from the last week
    /// let one_week_ago = (Utc::now() - Duration::days(7)).timestamp();
    /// let tracks = handler.get_user_recent_tracks_with_options(None, Some(one_week_ago), None, false).await?;
    ///
    /// // Get tracks between two dates with extended info
    /// let tracks = handler.get_user_recent_tracks_with_options(None, Some(start), Some(end), true).await?;
    /// ```
    #[deprecated(
        since = "2.0.0",
        note = "Use `RecentTracksClient` from the `api` module instead"
    )]
    pub async fn get_user_recent_tracks_with_options(
        &self,
        limit: impl Into<TrackLimit>,
        from: Option<i64>,
        to: Option<i64>,
        extended: bool,
    ) -> Result<Vec<RecentTrack>> {
        let mut params = QueryParams::new();

        if let Some(from_timestamp) = from {
            params.insert("from".to_string(), from_timestamp.to_string());
        }

        if let Some(to_timestamp) = to {
            params.insert("to".to_string(), to_timestamp.to_string());
        }

        if extended {
            params.insert("extended".to_string(), "1".to_string());
        }

        self.get_user_tracks::<UserRecentTracks>("user.getrecenttracks", limit.into(), Some(params))
            .await
    }

    /// Get recent tracks for a user with extended information.
    ///
    /// This method is similar to `get_user_recent_tracks_with_options` but returns
    /// the extended track format which includes additional artist details.
    ///
    /// # Arguments
    /// * `limit` - The number of tracks to fetch. Use `None` or `TrackLimit::Unlimited` to fetch all tracks.
    /// * `from` - Optional timestamp (Unix timestamp in seconds) to fetch tracks from this time onwards.
    /// * `to` - Optional timestamp (Unix timestamp in seconds) to fetch tracks up until this time.
    ///
    /// # Errors
    /// Returns an error if the API request fails.
    ///
    /// # Returns
    /// * `Result<Vec<RecentTrackExtended>>` - The fetched tracks with extended information.
    #[deprecated(
        since = "2.0.0",
        note = "Use `RecentTracksClient` from the `api` module instead"
    )]
    pub async fn get_user_recent_tracks_extended(
        &self,
        limit: impl Into<TrackLimit>,
        from: Option<i64>,
        to: Option<i64>,
    ) -> Result<Vec<RecentTrackExtended>> {
        let mut params = QueryParams::new();

        if let Some(from_timestamp) = from {
            params.insert("from".to_string(), from_timestamp.to_string());
        }

        if let Some(to_timestamp) = to {
            params.insert("to".to_string(), to_timestamp.to_string());
        }

        params.insert("extended".to_string(), "1".to_string());

        self.get_user_tracks::<UserRecentTracksExtended>(
            "user.getrecenttracks",
            limit.into(),
            Some(params),
        )
        .await
    }

    /// Get all recent tracks for a user between two dates.
    ///
    /// Convenience method for fetching all tracks within a specific time range.
    /// This always fetches unlimited tracks (all tracks in the range).
    ///
    /// # Arguments
    /// * `from` - Start timestamp (Unix timestamp in seconds) - tracks from this time onwards.
    /// * `to` - End timestamp (Unix timestamp in seconds) - tracks up until this time.
    /// * `extended` - If `true`, fetches extended track information including additional artist details.
    ///
    /// # Errors
    /// Returns an error if the API request fails.
    ///
    /// # Returns
    /// * `Result<Vec<RecentTrack>>` - All fetched tracks in the date range (normal format).
    ///
    /// # Examples
    /// ```ignore
    /// // Get all tracks from January 2024
    /// let start = Utc.ymd(2024, 1, 1).and_hms(0, 0, 0).timestamp();
    /// let end = Utc.ymd(2024, 2, 1).and_hms(0, 0, 0).timestamp();
    /// let tracks = handler.get_user_recent_tracks_between(start, end, false).await?;
    ///
    /// // Get all tracks from last week with extended info
    /// let one_week_ago = (Utc::now() - Duration::days(7)).timestamp();
    /// let now = Utc::now().timestamp();
    /// let tracks = handler.get_user_recent_tracks_between(one_week_ago, now, true).await?;
    /// ```
    #[deprecated(
        since = "2.0.0",
        note = "Use `RecentTracksClient` from the `api` module instead"
    )]
    pub async fn get_user_recent_tracks_between(
        &self,
        from: i64,
        to: i64,
        extended: bool,
    ) -> Result<Vec<RecentTrack>> {
        #[allow(deprecated)]
        self.get_user_recent_tracks_with_options(
            TrackLimit::Unlimited,
            Some(from),
            Some(to),
            extended,
        )
        .await
    }

    /// Get all recent tracks for a user between two dates with extended information.
    ///
    /// Convenience method for fetching all tracks with extended information within a specific time range.
    /// This always fetches unlimited tracks (all tracks in the range) with extended data.
    ///
    /// # Arguments
    /// * `from` - Start timestamp (Unix timestamp in seconds) - tracks from this time onwards.
    /// * `to` - End timestamp (Unix timestamp in seconds) - tracks up until this time.
    ///
    /// # Errors
    /// Returns an error if the API request fails.
    ///
    /// # Returns
    /// * `Result<Vec<RecentTrackExtended>>` - All fetched tracks in the date range with extended information.
    ///
    /// # Examples
    /// ```ignore
    /// // Get all tracks from January 2024 with extended info
    /// let start = Utc.ymd(2024, 1, 1).and_hms(0, 0, 0).timestamp();
    /// let end = Utc.ymd(2024, 2, 1).and_hms(0, 0, 0).timestamp();
    /// let tracks = handler.get_user_recent_tracks_between_extended(start, end).await?;
    /// ```
    #[deprecated(
        since = "2.0.0",
        note = "Use `RecentTracksClient` from the `api` module instead"
    )]
    pub async fn get_user_recent_tracks_between_extended(
        &self,
        from: i64,
        to: i64,
    ) -> Result<Vec<RecentTrackExtended>> {
        #[allow(deprecated)]
        self.get_user_recent_tracks_extended(TrackLimit::Unlimited, Some(from), Some(to))
            .await
    }

    /// Get loved tracks for a user since a given timestamp.
    ///
    /// # Arguments
    /// * `timestamp` - The timestamp to fetch tracks since.
    /// * `limit` - The number of tracks to fetch. If None, fetch all tracks.
    ///
    /// # Errors
    /// * `FileError` - If there was an error reading or writing the file
    /// * `InvalidUtf8` - If the file path is not valid UTF-8
    ///
    /// # Returns
    /// * `Vec<LovedTrack>` - The fetched tracks.
    #[allow(dead_code)]
    pub async fn get_user_loved_tracks_since(
        &self,
        timestamp: u32,
        limit: impl Into<TrackLimit>,
    ) -> Result<Vec<LovedTrack>> {
        #[allow(deprecated)]
        let tracks = self.get_user_loved_tracks(limit).await?;

        Ok(tracks
            .into_iter()
            .filter(|track| track.date.uts > timestamp)
            .collect())
    }

    /// Update a tracks file with new tracks.
    ///
    /// # Arguments
    /// * `file_path` - Path to the file to update.
    /// * `fetch_since` - Function to fetch tracks since a given timestamp.
    ///
    /// # Errors
    /// * `FileError` - If there was an error reading or writing the file
    ///
    /// # Panics
    /// * If the file path is not valid UTF-8
    ///
    /// # Returns
    /// * `Result<String, Box<dyn std::error::Error>>` - The filename of the updated file.
    #[allow(dead_code)]
    pub async fn update_tracks_file<T: DeserializeOwned + Serialize + Timestamped>(
        &self,
        file_path: &Path,
    ) -> Result<String> {
        // Get the most recent timestamp from the file
        let last_timestamp =
            AnalysisHandler::get_most_recent_timestamp::<T>(file_path)?.unwrap_or(0);

        // Find the recent tracks in the file
        let recent_tracks = self
            .get_user_recent_tracks_since(last_timestamp, None, None)
            .await?;

        let file_path_str = file_path
            .to_str()
            .ok_or_else(|| LastFmError::Other("Invalid file path (non-UTF8)".to_string()))?;

        // Append the new tracks to the file
        let updated_file = FileHandler::append(&recent_tracks, file_path_str)?;

        Ok(updated_file)
    }

    /// Export play counts for the last X songs with additional track information
    ///
    /// # Arguments
    /// * `limit` - Number of recent tracks to analyze
    /// * `file_path` - Path to the file to save the play counts to
    ///
    /// # Errors
    /// * `FileError` - If there was an error reading or writing the file
    ///
    /// # Returns
    /// * `Result<String>` - Path to the saved JSON file containing play counts
    pub async fn export_recent_play_counts(&self, limit: impl Into<TrackLimit>) -> Result<String> {
        // Get recent tracks
        #[allow(deprecated)]
        let tracks = self.get_user_recent_tracks(limit.into()).await?;

        // Count plays and collect track info
        let mut play_counts: HashMap<String, TrackPlayInfo> = HashMap::new();

        for track in tracks {
            let entry = play_counts
                .entry(track.name.clone())
                .or_insert(TrackPlayInfo {
                    name: track.name.clone(),
                    play_count: 0,
                    artist: track.artist.text.clone(),
                    album: Some(track.album.text.clone()),
                    image_url: track
                        .image
                        .iter()
                        .find(|img| img.size == "large")
                        .map(|img| img.text.clone())
                        .or_else(|| track.image.first().map(|img| img.text.clone())),
                    currently_playing: track.attr.is_some_and(|attr| attr.nowplaying == "true"),
                    date: track.date.map(|date| date.uts),
                    url: track.url,
                });

            entry.play_count += 1;
        }

        // Convert HashMap values into a Vec
        let play_counts_vec: Vec<TrackPlayInfo> = play_counts.into_values().collect();

        // Save to file
        let filename = FileHandler::save(&[play_counts_vec], &FileFormat::Json, "play_counts")
            .map_err(LastFmError::Io)?;

        Ok(filename)
    }

    /// Update or create a file with play counts for the last X songs with additional track information
    ///
    /// # Arguments
    /// * `limit` - Number of recent tracks to analyze
    /// * `file_path` - Path to the file to update/create
    ///
    /// # Errors
    /// * `LastFmError::Api` - If the API returns an error
    /// * `LastFmError::Io` - If there is an error reading or writing the file
    ///
    /// # Returns
    /// * `Result<String>` - Path to the updated/created JSON file containing play counts
    pub async fn update_recent_play_counts(
        &self,
        limit: impl Into<TrackLimit>,
        file_path: &str,
    ) -> Result<String> {
        // Get recent tracks
        #[allow(deprecated)]
        let tracks = self.get_user_recent_tracks(limit.into()).await?;

        // Count plays and collect track info
        let mut play_counts: HashMap<String, TrackPlayInfo> = HashMap::new();

        for track in tracks {
            let entry = play_counts
                .entry(track.name.clone())
                .or_insert(TrackPlayInfo {
                    name: track.name.clone(),
                    play_count: 0,
                    artist: track.artist.text.clone(),
                    album: Some(track.album.text.clone()),
                    image_url: track
                        .image
                        .iter()
                        .find(|img| img.size == "extralarge") // Best size for album art
                        .map(|img| img.text.clone())
                        .or_else(|| track.image.first().map(|img| img.text.clone())),
                    currently_playing: track
                        .attr
                        .as_ref()
                        .is_some_and(|val| val.nowplaying == "true"),
                    date: track.date.map(|date| date.uts),
                    url: track.url,
                });

            entry.play_count += 1;
        }

        // Convert HashMap values into a Vec
        let play_counts_vec: Vec<TrackPlayInfo> = play_counts.into_values().collect();

        // Create the file (overwriting if it exists)
        let file = File::create(file_path).map_err(LastFmError::Io)?;
        serde_json::to_writer_pretty(file, &play_counts_vec).map_err(LastFmError::Parse)?;

        Ok(file_path.to_string())
    }

    /// Check if the user is currently playing a track
    ///
    /// # Errors
    /// * `LastFmError` - If there was an error communicating with Last.fm
    ///
    /// # Returns
    /// * `Result<Option<RecentTrack>>` - The currently playing track if any
    pub async fn is_currently_playing(&self) -> Result<Option<RecentTrack>> {
        let mut params = QueryParams::new();
        params.insert("limit".to_string(), "1".to_string());

        let tracks = self
            .get_user_tracks::<UserRecentTracks>(
                "user.getrecenttracks",
                TrackLimit::Limited(1),
                Some(params),
            )
            .await?;

        // Check if the first track has the "now playing" attribute
        Ok(tracks.first().and_then(|track| {
            if track
                .attr
                .as_ref()
                .is_some_and(|val| val.nowplaying == "true")
            {
                Some(track.clone())
            } else {
                None
            }
        }))
    }

    /// Update a file with the currently playing track information
    ///
    /// # Arguments
    /// * `file_path` - Path to the file to update
    ///
    /// # Errors
    /// * `LastFmError::Api` - If the API returns an error
    /// * `LastFmError::Io` - If there is an error reading or writing the file
    /// * `LastFmError::Parse` - If there is an error parsing the JSON
    ///
    /// # Returns
    /// * `Result<Option<RecentTrack>>` - The currently playing track if any
    pub async fn update_currently_listening(&self, file_path: &str) -> Result<Option<RecentTrack>> {
        let current_track = self.is_currently_playing().await?;

        // Create or overwrite the file
        let file = File::create(file_path).map_err(LastFmError::Io)?;

        if let Some(track) = &current_track {
            serde_json::to_writer_pretty(file, track).map_err(LastFmError::Parse)?;
        } else {
            // Write an empty object when no track is playing
            serde_json::to_writer_pretty(file, &serde_json::json!({}))
                .map_err(LastFmError::Parse)?;
        }

        Ok(current_track)
    }
}