Created
January 21, 2017 12:40
-
-
Save glouvigny/eb8be8718b00c2a3d4f30c54c62028f2 to your computer and use it in GitHub Desktop.
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
let pause = function (ms) { | |
return new Promise(function (resolve, reject) { | |
setTimeout(function () { | |
return resolve(true); | |
}, ms); | |
}); | |
}; | |
let fetchArtists = async function (lastFmApiKey) { | |
let res = await fetch('https://ws.audioscrobbler.com/2.0/?method=library.getartists&api_key=' + lastFmApiKey + '&user=guillaumel&limit=500&format=json'); | |
return (await res.json()).artists.artist.map(a => a.name) | |
.filter(name => name.indexOf('feat.') === -1) | |
.filter(name => name.indexOf('featuring') === -1) | |
}; | |
let followArtists = async function (oauthToken, artists) { | |
let artistIds = []; | |
while (artists.length) { | |
let artistName = artists.shift(); | |
let json = await fetch('https://api.spotify.com/v1/search?q=' + encodeURIComponent(artistName) + '&type=artist').then(res => res.json()); | |
if (json.artists && json.artists.items && json.artists.items.length > 0) { | |
artistIds.push(json.artists.items[0].id); | |
} | |
if (artistIds.length === 50 || artists.length === 0) { | |
console.log(artistIds); | |
await fetch('https://api.spotify.com/v1/me/following?type=artist', { | |
method: "PUT", | |
body: JSON.stringify({ids: artistIds}), | |
headers: { | |
'Accept': 'application/json', | |
'Content-Type': 'application/json', | |
'Authorization': 'Bearer ' + oauthToken, | |
}, | |
}) | |
// PUT to follow | |
artistIds = []; | |
} | |
await pause(100); | |
} | |
} | |
fetchArtists(YOUR_LAST_FM_API_KEY).then(followArtists.bind(null, YOUR_SPOTIFY_OAUTH_TOKEN)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment