import { Client, PlaylistTrack } from '[email protected]';
import * as wmill from 'windmill-client';
type Spotify = {
token: string;
}
const MAX_TRACKS_PER_PAGE = 100; // this is the max limit allowed by the API
export async function main(
spotifyCredentials: Spotify,
playlistId: string,
fetchIntervalMs: number = 1000,
failOnSizeMismatch: boolean = false
) {
const client = await Client.create({
token: spotifyCredentials.token,
userAuthorizedToken: true
});
const playlist = await client.playlists.get(playlistId);
if (!playlist) {
throw new Error(`getPlaylist call returned null (id: ${playlistId})`);
}
console.log(`Fetching all ${playlist.totalTracks} tracks from playlist '${playlist.name}' (id: ${playlistId})`);
const results: PlaylistTrack[] = [];
while (results.length < playlist.totalTracks) {
if (results.length != 0) {
// wait for a specified interval between calls to avoid being rate limited
await new Promise(res => setTimeout(res, fetchIntervalMs));
}
const tracks = await client.playlists.getTracks(playlistId, {
offset: results.length,
limit: MAX_TRACKS_PER_PAGE
});
if (tracks.length === 0) {
break;
}
results.push(...tracks);
const percentProgress = (results.length / playlist.totalTracks) * 100;
await wmill.setProgress(percentProgress);
console.log(`Fetched ${tracks.length} tracks (${results.length} total, ${percentProgress.toFixed(2)}% done)`);
}
if (playlist.totalTracks !== results.length) {
const errorMessage = `The input playlist contains ${playlist.totalTracks} tracks but the result contains ${results.length} tracks. The size of the playlist may have changed during this script's execution`;
if (failOnSizeMismatch) {
throw new Error(errorMessage);
}
console.error(`WARNING: ${errorMessage}`);
}
console.log(`Returning ${results.length} total fetched tracks`);
return results;
}
Submitted by alec minchington932 473 days ago