Announcements

Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

Get all recently played tracks for a given period

Get all recently played tracks for a given period

Plan: Premium

Country: US

Device: Macbook Air 2015

Operating System: MacOS

 

My Question or Issue

I'm using the get recently played endpoint to get my recently played tracks, I want to get tracks from December 31, 2022(not inclusive) up to today(February 2, 2024, not inclusive). I'm using the after param and passing the unix timestamp for December 31, 2022 (1672462800000). I'm able to get my listening history but at one point it just repeats itself as if it's not moving to next page. I get 1275 items but only 50 of those are unique. I think I'm having troubles with the pagination but the before and after params from the request body as well as the before and after values of the cursors from the response, are confusing me a lot. Could someone please tell me what am I doing wrong? Any and all help are greatly appreciated. Find my code below.

Here is my code:

export const getRecentlyPlayedTracks = async (after?: number, before?: number) => {
try {
let allResults: PlayHistory[] = [];
let nextPage: number | undefined = 1672462800000;

console.log("after value coming from function param= ", nextPage);

while(nextPage){
console.log("first timestamp for after param= ", nextPage);
const response: any = await spotify_api.get('me/player/recently-played', {params: {
limit: 50,
after: nextPage // this is a unix timestamp in millisecond and this date is december 31, 2022, 00h00m00s
}});

//the before becomes the after so i can get to the previous set of songs

const currentResults = response.data.items;
console.log("cursors= ", response.data.cursors);

allResults = [...allResults, ...currentResults];

const lastItemTimestamp = currentResults[currentResults.length - 1]?.played_at;
const lastItemUnixTimestamp = lastItemTimestamp ? new Date(lastItemTimestamp).getTime() : undefined;

console.log("Timestamp gotten from played_at property in response= ", lastItemUnixTimestamp);
nextPage = response.data.next && lastItemUnixTimestamp ? lastItemUnixTimestamp : undefined;
}

return allResults;
}
catch (error: any) {
console.error('Error with the request', error);
if(error.status === '401') console.log("BAD or EXPIRED token");
throw error;
}
}

 

Reply
1 Reply

same issue here, any luck?

Suggested posts