From 447e64b1caa95135549638708c672eeb82a4fa61 Mon Sep 17 00:00:00 2001 From: kraxarn Date: Sun, 12 Apr 2020 20:43:53 +0200 Subject: [PATCH] Add pagination to album tracks, fixes #7 --- src/spotify/spotify.cpp | 24 ++++++++++++++++++++++++ src/spotify/spotify.hpp | 2 ++ 2 files changed, 26 insertions(+) diff --git a/src/spotify/spotify.cpp b/src/spotify/spotify.cpp index d1f1a1122..cc2864efb 100644 --- a/src/spotify/spotify.cpp +++ b/src/spotify/spotify.cpp @@ -273,6 +273,26 @@ AudioFeatures Spotify::trackAudioFeatures(QString trackId) return AudioFeatures(json.object()); } +QVector Spotify::albumTracks(const QString &albumId, const QString &albumName, int offset) +{ + auto json = get(QString("albums/%1/tracks?limit=50&offset=%2").arg(albumId).arg(offset)).object(); + auto trackItems = json["items"].toArray(); + QVector tracks; + tracks.reserve(50); + // Add all in current page + for (auto item : trackItems) + { + auto t = Track(item.toObject()); + // Album name is not included, so we have to set it manually + t.album = albumName; + tracks.append(t); + } + // Add all in next page + if (json.contains("next") && !json["next"].isNull()) + tracks.append(albumTracks(albumId, albumName, json["offset"].toInt() + json["limit"].toInt())); + return tracks; +} + QVector *Spotify::albumTracks(const QString &albumID) { auto json = get(QString("albums/%1").arg(albumID)); @@ -287,6 +307,10 @@ QVector *Spotify::albumTracks(const QString &albumID) t.album = albumName; tracks->append(t); } + // Check if we have any more to add + auto tracksLimit = json["tracks"].toObject()["limit"].toInt(); + if (json["tracks"].toObject()["total"].toInt() > tracksLimit) + tracks->append(albumTracks(albumID, albumName, tracksLimit)); // Return final vector return tracks; } diff --git a/src/spotify/spotify.hpp b/src/spotify/spotify.hpp index 9f471b276..20343d2b9 100644 --- a/src/spotify/spotify.hpp +++ b/src/spotify/spotify.hpp @@ -92,6 +92,8 @@ namespace spt template QVector loadItems(const QString &url); + QVector albumTracks(const QString &albumId, const QString &albumName, int offset); + bool refresh(); }; } \ No newline at end of file