|
219 | 219 | if (!playlistId) { |
220 | 220 | throw new Error('Could not extract playlist ID from URL'); |
221 | 221 | } |
222 | | - const response = await fetch(`https://api.spotify.com/v1/playlists/${playlistId}/tracks`, { |
223 | | - headers: { |
224 | | - 'Authorization': `Bearer ${localStorage.getItem('spotify_access_token')}` |
225 | | - } |
226 | | - }); |
227 | | - if (!response.ok) { |
228 | | - throw new Error(`API request failed with status ${response.status}`); |
229 | | - } |
| 222 | + |
| 223 | + const response = await spotifyFetch(`https://api.spotify.com/v1/playlists/${playlistId}/tracks`); |
| 224 | + if (!response) return []; // Handle case where auth refresh was triggered |
| 225 | + |
230 | 226 | const data = await response.json(); |
231 | 227 | return data.items |
232 | 228 | .filter(item => item?.track && item.track.album?.release_date) |
@@ -363,8 +359,47 @@ <h3 class="title">${track.name}</h3> |
363 | 359 |
|
364 | 360 | document.getElementById('pauseResumeButton').onclick = togglePauseResume; |
365 | 361 | document.getElementById('createQRButton').onclick = createQRCodesFromPlaylist; |
| 362 | + |
| 363 | + playerInstance.addListener('authentication_error', ({ message }) => { |
| 364 | + console.error('Authentication error:', message); |
| 365 | + refreshAuth(); |
| 366 | + }); |
| 367 | + |
| 368 | + playerInstance.addListener('initialization_error', ({ message }) => { |
| 369 | + console.error('Failed to initialize:', message); |
| 370 | + refreshAuth(); |
| 371 | + }); |
| 372 | + |
366 | 373 | playerInstance.connect(); |
367 | 374 | } |
| 375 | + |
| 376 | + function refreshAuth() { |
| 377 | + const clientId = localStorage.getItem('spotify_client_id'); |
| 378 | + const scope = 'streaming user-read-email user-read-private user-modify-playback-state playlist-read-private'; |
| 379 | + window.location.href = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scope)}`; |
| 380 | + } |
| 381 | + |
| 382 | + async function spotifyFetch(url, options = {}) { |
| 383 | + const response = await fetch(url, { |
| 384 | + ...options, |
| 385 | + headers: { |
| 386 | + 'Authorization': `Bearer ${localStorage.getItem('spotify_access_token')}`, |
| 387 | + ...options.headers |
| 388 | + } |
| 389 | + }); |
| 390 | + |
| 391 | + if (response.status === 401) { |
| 392 | + // Token is invalid, refresh authentication |
| 393 | + refreshAuth(); |
| 394 | + return; |
| 395 | + } |
| 396 | + |
| 397 | + if (!response.ok) { |
| 398 | + throw new Error(`API request failed with status ${response.status}`); |
| 399 | + } |
| 400 | + |
| 401 | + return response; |
| 402 | + } |
368 | 403 | </script> |
369 | 404 | <script src="https://sdk.scdn.co/spotify-player.js"></script> |
370 | 405 | </body> |
|
0 commit comments