Created
March 4, 2025 12:51
-
-
Save joerx/1a6e743b8edb90b12b7db948789fe3d4 to your computer and use it in GitHub Desktop.
Obsidian user script for spotify API integration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CLIENT_ID = '...'; | |
const CLIENT_SECRET = '...'; | |
const refreshToken = '...' | |
async function refreshAccessToken() { | |
const tokenData = `${CLIENT_ID}:${CLIENT_SECRET}`; | |
const base64token = btoa(tokenData); | |
const data = new URLSearchParams(); | |
data.append('grant_type', 'refresh_token'); | |
data.append('refresh_token', refreshToken); | |
try { | |
const response = await fetch('https://accounts.spotify.com/api/token', { | |
method: 'POST', | |
headers: { | |
'Authorization': `Basic ${base64token}`, | |
'Content-Type': 'application/x-www-form-urlencoded', | |
}, | |
body: data, | |
}); | |
if (response.ok) { | |
const { access_token } = await response.json(); | |
return access_token; | |
} else { | |
console.error('Error refreshing access token', response.status, await response.text()); | |
return null; | |
} | |
} catch (error) { | |
console.error('Error refreshing access token', error); | |
return null; | |
} | |
} | |
async function getCurrentlyPlayingTrack(accessToken) { | |
try { | |
const response = await fetch('https://api.spotify.com/v1/me/player/currently-playing', { | |
headers: { | |
'Authorization': `Bearer ${accessToken}`, | |
}, | |
}); | |
if (response.ok) { | |
const currentlyPlayingTrack = await response.json(); | |
return currentlyPlayingTrack; | |
} else { | |
console.error('Error getting currently playing track', response.status, await response.text()); | |
return null; | |
} | |
} catch (error) { | |
console.error('Error getting currently playing track', error); | |
return null; | |
} | |
} | |
async function spotify() { | |
const accessToken = await refreshAccessToken(); | |
if (accessToken) { | |
const currentlyPlayingTrack = await getCurrentlyPlayingTrack(accessToken); | |
if (currentlyPlayingTrack) { | |
const { is_playing, item } = currentlyPlayingTrack; | |
const imageUrl = item.album.images[0].url; | |
const artistName = item.artists[0].name; | |
const externalUrl = item.external_urls.spotify; | |
const trackName = item.name; | |
const imgName = String(item.album.images[0].url); | |
const imageName = imgName.split('/')[4] // get album image name | |
const extractedData = { | |
isPlaying: is_playing, | |
imageURL: imageUrl, | |
artistName: artistName, | |
externalUrl: externalUrl, | |
trackName: trackName, | |
imageName: imageName | |
}; | |
return extractedData; | |
} | |
} | |
} | |
module.exports = spotify; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment