Skip to content

Commit 2f927d2

Browse files
committed
- add spotify auth refresh when token expires
- extract spotify api calls into `spotifyFetch` helper - handle auth errors in player instance listeners - move auth refresh logic into dedicated `refreshAuth` function
1 parent b0bf536 commit 2f927d2

File tree

1 file changed

+43
-8
lines changed

1 file changed

+43
-8
lines changed

tools/spotify_music_quiz_cards.html

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -219,14 +219,10 @@
219219
if (!playlistId) {
220220
throw new Error('Could not extract playlist ID from URL');
221221
}
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+
230226
const data = await response.json();
231227
return data.items
232228
.filter(item => item?.track && item.track.album?.release_date)
@@ -363,8 +359,47 @@ <h3 class="title">${track.name}</h3>
363359

364360
document.getElementById('pauseResumeButton').onclick = togglePauseResume;
365361
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+
366373
playerInstance.connect();
367374
}
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+
}
368403
</script>
369404
<script src="https://sdk.scdn.co/spotify-player.js"></script>
370405
</body>

0 commit comments

Comments
 (0)