Last active
December 28, 2015 06:09
-
-
Save brianlow/67dd25a0dad9386892d0 to your computer and use it in GitHub Desktop.
Spotify: Copy all songs from all your playlists into 'Your Music' (songs / albums / artists)
This file contains hidden or 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
# Add an application at https://developer.spotify.com/my-applications | |
# Whitelist redirect url http://posthere.io/brians-importer | |
# Copy client id into url below | |
# https://accounts.spotify.com/authorize?client_id=4260a40e3f514766802819f094e3be82&redirect_uri=http%3A%2F%2Fposthere.io%2Fbrians-importer&response_type=token&scope=playlist-read-private%20playlist-modify-public%20playlist-modify-private%20user-library-read%20user-library-modify | |
# Browse to URL | |
# On successful authorization, you will be redirected, from this URL copy the token param in variable below | |
require 'httparty' | |
token = '... your token here ...' | |
headers = { headers: {"Authorization" => "Bearer #{token}"} } | |
# Get playlists | |
res = HTTParty.get('https://api.spotify.com/v1/me/playlists', headers) | |
puts "#{res.code} - #{res.body}" unless res.success? | |
playlists = res['items'].map { |x| OpenStruct.new({name: x['name'], track_url: x['tracks']['href']}) } | |
playlists.each do |playlist| | |
# Get playlist tracks | |
puts "Getting playlist #{playlist.name}" | |
res = {'next' => playlist.track_url} | |
playlist_tracks = [] | |
while res['next'] | |
puts " Getting #{res['next']}" | |
res = HTTParty.get(res['next'], headers) | |
puts "#{res.code} - #{res.body}" unless res.success? | |
playlist_tracks.push *res['items'].map { |x| OpenStruct.new({artist: x['track']['artists'].first['name'], album:x['track']['album']['name'], name: x['track']['name'], id: x['track']['id']}) } | |
end | |
# Add tracks | |
playlist_tracks.each_slice(50) do |tracks| | |
tracks.each { |track| puts " Adding #{track.artist[0..14].ljust(15)} - #{track.album[0..14].ljust(15)} - #{track.name[0..24].ljust(25)}" } | |
res = HTTParty.put("https://api.spotify.com/v1/me/tracks?ids=#{tracks.collect(&:id).join(',')}", headers) | |
puts "#{res.code} - #{res.body}" unless res.success? | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment