1 | import { Client, PlaylistTrack } from '[email protected]'; |
2 | import * as wmill from 'windmill-client'; |
3 |
|
4 | type Spotify = { |
5 | token: string; |
6 | } |
7 |
|
8 | const MAX_TRACKS_PER_PAGE = 100; |
9 |
|
10 | export async function main( |
11 | spotifyCredentials: Spotify, |
12 | playlistId: string, |
13 | fetchIntervalMs: number = 1000, |
14 | failOnSizeMismatch: boolean = false |
15 | ) { |
16 | const client = await Client.create({ |
17 | token: spotifyCredentials.token, |
18 | userAuthorizedToken: true |
19 | }); |
20 |
|
21 | const playlist = await client.playlists.get(playlistId); |
22 |
|
23 | if (!playlist) { |
24 | throw new Error(`getPlaylist call returned null (id: ${playlistId})`); |
25 | } |
26 |
|
27 | console.log(`Fetching all ${playlist.totalTracks} tracks from playlist '${playlist.name}' (id: ${playlistId})`); |
28 |
|
29 | const results: PlaylistTrack[] = []; |
30 | while (results.length < playlist.totalTracks) { |
31 | if (results.length != 0) { |
32 | |
33 | await new Promise(res => setTimeout(res, fetchIntervalMs)); |
34 | } |
35 |
|
36 | const tracks = await client.playlists.getTracks(playlistId, { |
37 | offset: results.length, |
38 | limit: MAX_TRACKS_PER_PAGE |
39 | }); |
40 |
|
41 | if (tracks.length === 0) { |
42 | break; |
43 | } |
44 |
|
45 | results.push(...tracks); |
46 |
|
47 | const percentProgress = (results.length / playlist.totalTracks) * 100; |
48 |
|
49 | await wmill.setProgress(percentProgress); |
50 |
|
51 | console.log(`Fetched ${tracks.length} tracks (${results.length} total, ${percentProgress.toFixed(2)}% done)`); |
52 | } |
53 |
|
54 | if (playlist.totalTracks !== results.length) { |
55 | 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`; |
56 |
|
57 | if (failOnSizeMismatch) { |
58 | throw new Error(errorMessage); |
59 | } |
60 |
|
61 | console.error(`WARNING: ${errorMessage}`); |
62 | } |
63 |
|
64 | console.log(`Returning ${results.length} total fetched tracks`); |
65 | return results; |
66 | } |
67 |
|