lastfm-client 3.5.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
use std::collections::HashMap;
use std::fmt;

use serde::{Deserialize, Serialize};

use crate::types::utils::{bool_from_str, u32_from_str};

// BASE TYPES =================================================================

/// Basic type containing `MusicBrainz` ID and text content
///
/// Used for artist and album information in track responses
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct BaseMbidText {
    /// `MusicBrainz` Identifier (may be empty string if not available)
    pub mbid: String,
    /// Text content (artist name, album name, etc.)
    #[serde(rename = "#text")]
    pub text: String,
}

/// Extended object type with `MusicBrainz` ID, URL, and name
///
/// Used for artist and album information in extended track responses
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct BaseObject {
    /// `MusicBrainz` Identifier (may be empty string if not available)
    pub mbid: String,
    /// Last.fm URL for this object
    #[serde(default)]
    pub url: String,
    /// Name of the object (artist name, album name, etc.)
    #[serde(alias = "#text")]
    pub name: String,
}

/// Image information for tracks and albums
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TrackImage {
    /// Image size (e.g., "small", "medium", "large", "extralarge")
    pub size: String,
    /// URL to the image
    #[serde(rename = "#text")]
    pub text: String,
}

/// Streamability information for a track
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct Streamable {
    /// Whether the full track is streamable ("0" or "1")
    pub fulltrack: String,
    /// Additional streamability information
    #[serde(rename = "#text")]
    pub text: String,
}

/// Detailed artist information
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct Artist {
    /// Artist name
    pub name: String,
    /// `MusicBrainz` Identifier (may be empty string if not available)
    pub mbid: String,
    /// Last.fm URL for this artist
    #[serde(default)]
    pub url: String,
    /// Artist images in various sizes
    pub image: Vec<TrackImage>,
}

// DATE TYPE ==================================================================
// Unified - handles both API deserialization and storage

/// Date/timestamp information for tracks
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct Date {
    /// Unix timestamp in seconds (not milliseconds) since January 1, 1970 UTC
    #[serde(deserialize_with = "u32_from_str")]
    pub uts: u32,
    /// Human-readable date string (e.g., "31 Jan 2024, 12:00")
    #[serde(rename = "#text")]
    pub text: String,
}

// ATTRIBUTES =================================================================

/// Attributes for recent tracks indicating current playback status
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct Attributes {
    /// Whether this track is currently playing ("true" or "false")
    pub nowplaying: String,
}

/// Rank attributes for top tracks
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct RankAttr {
    /// Numeric rank as a string (e.g., "1", "2", "3")
    pub rank: String,
}

// RECENT TRACK ===============================================================
// Unified - no more ApiRecentTrack vs RecentTrack split!

/// A track from a user's recent listening history
///
/// Retrieved from the `user.getrecenttracks` API endpoint
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct RecentTrack {
    /// Artist information
    pub artist: BaseMbidText,
    /// Whether the track is streamable on Last.fm
    #[serde(deserialize_with = "bool_from_str")]
    pub streamable: bool,
    /// Track/album images in various sizes
    pub image: Vec<TrackImage>,
    /// Album information
    pub album: BaseMbidText,
    /// Attributes (present if track is currently playing)
    #[serde(rename = "@attr")]
    pub attr: Option<Attributes>,
    /// When the track was played (None if currently playing)
    pub date: Option<Date>,
    /// Track name
    pub name: String,
    /// `MusicBrainz` track identifier (may be empty string)
    pub mbid: String,
    /// Last.fm URL for this track
    pub url: String,
}

impl fmt::Display for RecentTrack {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let status = if self.attr.is_some() {
            " [NOW PLAYING]"
        } else {
            ""
        };
        let date_str = self
            .date
            .as_ref()
            .map_or(String::new(), |d| format!(" ({})", d.text));

        write!(
            f,
            "{} - {} [{}]{date_str}{status}",
            self.name, self.artist.text, self.album.text
        )
    }
}

/// A track from recent listening history with extended artist/album information
///
/// Retrieved when using the `extended=1` parameter with `user.getrecenttracks`
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct RecentTrackExtended {
    /// Extended artist information (includes URL)
    pub artist: BaseObject,
    /// Whether the track is streamable on Last.fm
    #[serde(deserialize_with = "bool_from_str")]
    pub streamable: bool,
    /// Track/album images in various sizes
    pub image: Vec<TrackImage>,
    /// Extended album information (includes URL)
    pub album: BaseObject,
    /// Additional attributes (format varies, use `HashMap`)
    #[serde(rename = "@attr")]
    pub attr: Option<HashMap<String, String>>,
    /// When the track was played (None if currently playing)
    pub date: Option<Date>,
    /// Track name
    pub name: String,
    /// `MusicBrainz` track identifier (may be empty string)
    pub mbid: String,
    /// Last.fm URL for this track
    #[serde(default)]
    pub url: String,
}

impl fmt::Display for RecentTrackExtended {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let is_now_playing = self
            .attr
            .as_ref()
            .and_then(|a| a.get("nowplaying"))
            .is_some_and(|v| v == "true");
        let status = if is_now_playing { " [NOW PLAYING]" } else { "" };
        let date_str = self
            .date
            .as_ref()
            .map_or(String::new(), |d| format!(" ({})", d.text));

        write!(
            f,
            "{} - {} [{}]{date_str}{status}",
            self.name, self.artist.name, self.album.name
        )
    }
}

// LOVED TRACK ================================================================

/// A track that a user has marked as "loved" on Last.fm
///
/// Retrieved from the `user.getlovedtracks` API endpoint
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct LovedTrack {
    /// Artist information with URL
    pub artist: BaseObject,
    /// When the track was loved
    pub date: Date,
    /// Track/album images in various sizes
    pub image: Vec<TrackImage>,
    /// Streamability information
    pub streamable: Streamable,
    /// Track name
    pub name: String,
    /// `MusicBrainz` track identifier (may be empty string)
    pub mbid: String,
    /// Last.fm URL for this track
    pub url: String,
}

impl fmt::Display for LovedTrack {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} - {} (loved {})",
            self.name, self.artist.name, self.date.text
        )
    }
}

// TOP TRACK ==================================================================

/// A track from a user's top tracks, ranked by play count
///
/// Retrieved from the `user.gettoptracks` API endpoint
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TopTrack {
    /// Streamability information
    pub streamable: Streamable,
    /// `MusicBrainz` track identifier (may be empty string)
    pub mbid: String,
    /// Track name
    pub name: String,
    /// Track/album images in various sizes
    pub image: Vec<TrackImage>,
    /// Artist information with URL
    pub artist: BaseObject,
    /// Last.fm URL for this track
    pub url: String,
    /// Track duration in seconds
    #[serde(deserialize_with = "u32_from_str")]
    pub duration: u32,
    /// Rank attributes (position in top tracks)
    #[serde(rename = "@attr")]
    pub attr: RankAttr,
    /// Total number of times this track has been played
    #[serde(deserialize_with = "u32_from_str")]
    pub playcount: u32,
}

impl fmt::Display for TopTrack {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "#{} - {} by {} ({} plays)",
            self.attr.rank, self.name, self.artist.name, self.playcount
        )
    }
}

// RESPONSE WRAPPERS ==========================================================

/// Base response metadata included in all paginated API responses
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct BaseResponse {
    /// Username the request was made for
    pub user: String,
    /// Total number of pages available
    #[serde(deserialize_with = "u32_from_str", rename = "totalPages")]
    pub total_pages: u32,
    /// Current page number (1-indexed)
    #[serde(deserialize_with = "u32_from_str")]
    pub page: u32,
    /// Number of items per page
    #[serde(deserialize_with = "u32_from_str", rename = "perPage")]
    pub per_page: u32,
    /// Total number of items available across all pages
    #[serde(deserialize_with = "u32_from_str")]
    pub total: u32,
}

/// Recent tracks response wrapper
#[derive(Serialize, Deserialize, Debug)]
#[non_exhaustive]
pub struct RecentTracks {
    /// List of recent tracks
    pub track: Vec<RecentTrack>,
    /// Response metadata
    #[serde(rename = "@attr")]
    pub attr: BaseResponse,
}

/// Top-level recent tracks API response
#[derive(Serialize, Deserialize, Debug)]
#[non_exhaustive]
pub struct UserRecentTracks {
    /// Recent tracks data
    pub recenttracks: RecentTracks,
}

/// Recent tracks extended response wrapper
#[derive(Serialize, Deserialize, Debug)]
#[non_exhaustive]
pub struct RecentTracksExtended {
    /// List of extended recent tracks
    pub track: Vec<RecentTrackExtended>,
    /// Response metadata
    #[serde(rename = "@attr")]
    pub attr: BaseResponse,
}

/// Top-level extended recent tracks API response
#[derive(Serialize, Deserialize, Debug)]
#[non_exhaustive]
pub struct UserRecentTracksExtended {
    /// Extended recent tracks data
    pub recenttracks: RecentTracksExtended,
}

/// Loved tracks response wrapper
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct LovedTracks {
    /// List of loved tracks
    pub track: Vec<LovedTrack>,
    /// Response metadata
    #[serde(rename = "@attr")]
    pub attr: BaseResponse,
}

/// Top-level loved tracks API response
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct UserLovedTracks {
    /// Loved tracks data
    pub lovedtracks: LovedTracks,
}

/// Top tracks response wrapper
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TopTracks {
    /// List of top tracks
    pub track: Vec<TopTrack>,
    /// Response metadata
    #[serde(rename = "@attr")]
    pub attr: BaseResponse,
}

/// Top-level top tracks API response
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct UserTopTracks {
    /// Top tracks data
    pub toptracks: TopTracks,
}

// ANALYTICS ==================================================================

/// Represents a track's play count information
#[derive(Debug, Serialize)]
#[non_exhaustive]
pub struct TrackPlayInfo {
    /// Track name
    pub name: String,
    /// Number of times played
    pub play_count: u32,
    /// Artist name
    pub artist: String,
    /// Album name (if available)
    pub album: Option<String>,
    /// Image URL (if available)
    pub image_url: Option<String>,
    /// Whether the track is currently playing
    pub currently_playing: bool,
    /// Unix timestamp of when played
    pub date: Option<u32>,
    /// Last.fm URL
    pub url: String,
}

// TRAITS =====================================================================

/// Trait for types that have a timestamp
pub trait Timestamped {
    /// Get the timestamp as a Unix epoch in seconds
    fn get_timestamp(&self) -> Option<u32>;
}

impl Timestamped for RecentTrack {
    fn get_timestamp(&self) -> Option<u32> {
        self.date.as_ref().map(|d| d.uts)
    }
}

impl Timestamped for LovedTrack {
    fn get_timestamp(&self) -> Option<u32> {
        Some(self.date.uts)
    }
}

impl Timestamped for RecentTrackExtended {
    fn get_timestamp(&self) -> Option<u32> {
        self.date.as_ref().map(|d| d.uts)
    }
}

// SQLITE EXPORT ==============================================================

#[cfg(feature = "sqlite")]
impl crate::sqlite::SqliteExportable for RecentTrack {
    fn table_name() -> &'static str {
        "recent_tracks"
    }

    fn create_table_sql() -> &'static str {
        "CREATE TABLE IF NOT EXISTS recent_tracks (
            id         INTEGER PRIMARY KEY AUTOINCREMENT,
            name       TEXT    NOT NULL,
            url        TEXT    NOT NULL,
            artist     TEXT    NOT NULL,
            artist_mbid TEXT   NOT NULL,
            album      TEXT    NOT NULL,
            album_mbid TEXT    NOT NULL,
            date_uts   INTEGER,
            loved      INTEGER NOT NULL DEFAULT 0
        )"
    }

    fn insert_sql() -> &'static str {
        "INSERT INTO recent_tracks (name, url, artist, artist_mbid, album, album_mbid, date_uts, loved)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)"
    }

    fn bind_and_execute(&self, stmt: &mut rusqlite::Statement<'_>) -> rusqlite::Result<usize> {
        stmt.execute(rusqlite::params![
            self.name,
            self.url,
            self.artist.text,
            self.artist.mbid,
            self.album.text,
            self.album.mbid,
            self.date.as_ref().map(|d| d.uts),
            0_i32,
        ])
    }
}

#[cfg(feature = "sqlite")]
impl crate::sqlite::SqliteExportable for RecentTrackExtended {
    fn table_name() -> &'static str {
        "recent_tracks_extended"
    }

    fn create_table_sql() -> &'static str {
        "CREATE TABLE IF NOT EXISTS recent_tracks_extended (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            name        TEXT    NOT NULL,
            url         TEXT    NOT NULL,
            mbid        TEXT    NOT NULL,
            artist      TEXT    NOT NULL,
            artist_mbid TEXT    NOT NULL,
            artist_url  TEXT    NOT NULL,
            album       TEXT    NOT NULL,
            album_mbid  TEXT    NOT NULL,
            album_url   TEXT    NOT NULL,
            date_uts    INTEGER,
            loved       INTEGER NOT NULL DEFAULT 0
        )"
    }

    fn insert_sql() -> &'static str {
        "INSERT INTO recent_tracks_extended
             (name, url, mbid, artist, artist_mbid, artist_url, album, album_mbid, album_url, date_uts, loved)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)"
    }

    fn bind_and_execute(&self, stmt: &mut rusqlite::Statement<'_>) -> rusqlite::Result<usize> {
        stmt.execute(rusqlite::params![
            self.name,
            self.url,
            self.mbid,
            self.artist.name,
            self.artist.mbid,
            self.artist.url,
            self.album.name,
            self.album.mbid,
            self.album.url,
            self.date.as_ref().map(|d| d.uts),
            0_i32,
        ])
    }
}

#[cfg(feature = "sqlite")]
impl crate::sqlite::SqliteExportable for LovedTrack {
    fn table_name() -> &'static str {
        "loved_tracks"
    }

    fn create_table_sql() -> &'static str {
        "CREATE TABLE IF NOT EXISTS loved_tracks (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            name        TEXT    NOT NULL,
            url         TEXT    NOT NULL,
            artist      TEXT    NOT NULL,
            artist_mbid TEXT    NOT NULL,
            date_uts    INTEGER NOT NULL
        )"
    }

    fn insert_sql() -> &'static str {
        "INSERT INTO loved_tracks (name, url, artist, artist_mbid, date_uts)
         VALUES (?1, ?2, ?3, ?4, ?5)"
    }

    fn bind_and_execute(&self, stmt: &mut rusqlite::Statement<'_>) -> rusqlite::Result<usize> {
        stmt.execute(rusqlite::params![
            self.name,
            self.url,
            self.artist.name,
            self.artist.mbid,
            self.date.uts,
        ])
    }
}

#[cfg(feature = "sqlite")]
impl crate::sqlite::SqliteExportable for TopTrack {
    fn table_name() -> &'static str {
        "top_tracks"
    }

    fn create_table_sql() -> &'static str {
        "CREATE TABLE IF NOT EXISTS top_tracks (
            id        INTEGER PRIMARY KEY AUTOINCREMENT,
            name      TEXT    NOT NULL,
            url       TEXT    NOT NULL,
            artist    TEXT    NOT NULL,
            mbid      TEXT    NOT NULL,
            playcount INTEGER NOT NULL,
            rank      INTEGER NOT NULL
        )"
    }

    fn insert_sql() -> &'static str {
        "INSERT INTO top_tracks (name, url, artist, mbid, playcount, rank)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6)"
    }

    fn bind_and_execute(&self, stmt: &mut rusqlite::Statement<'_>) -> rusqlite::Result<usize> {
        let rank: u32 = self.attr.rank.parse().unwrap_or_default();
        stmt.execute(rusqlite::params![
            self.name,
            self.url,
            self.artist.name,
            self.mbid,
            self.playcount,
            rank,
        ])
    }
}

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

    #[test]
    fn test_date_deserialization() {
        use serde_json::json;
        let json_value = json!({
            "uts": "1_234_567_890",
            "#text": "2009-02-13 23:31:30"
        });
        let date: Date = serde_json::from_value(json_value).unwrap();
        assert_eq!(date.uts, 1_234_567_890);
        assert_eq!(date.text, "2009-02-13 23:31:30");
    }

    #[test]
    fn test_bool_from_str() {
        use serde_json::json;
        // Test that "1" deserializes to true
        let json_value = json!({
            "artist": {"mbid": "", "#text": "Test"},
            "streamable": "1",
            "image": [],
            "album": {"mbid": "", "#text": ""},
            "name": "Test",
            "mbid": "",
            "url": ""
        });
        let track: RecentTrack = serde_json::from_value(json_value).unwrap();
        assert!(track.streamable);
    }

    #[test]
    fn test_timestamped_trait() {
        let track = RecentTrack {
            artist: BaseMbidText {
                mbid: String::new(),
                text: "Artist".to_string(),
            },
            streamable: false,
            image: vec![],
            album: BaseMbidText {
                mbid: String::new(),
                text: String::new(),
            },
            attr: None,
            date: Some(Date {
                uts: 1_234_567_890,
                text: "test".to_string(),
            }),
            name: "Track".to_string(),
            mbid: String::new(),
            url: String::new(),
        };

        assert_eq!(track.get_timestamp(), Some(1_234_567_890));
    }
}