Skip to content

Instantly share code, notes, and snippets.

@glouvigny
Created January 21, 2017 12:40
Show Gist options
  • Save glouvigny/eb8be8718b00c2a3d4f30c54c62028f2 to your computer and use it in GitHub Desktop.
Save glouvigny/eb8be8718b00c2a3d4f30c54c62028f2 to your computer and use it in GitHub Desktop.
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