Created
November 17, 2015 05:51
-
-
Save johnholdun/e84ee4822a135ecc740b to your computer and use it in GitHub Desktop.
download all your tracks from last.fm
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
require 'active_support/all' | |
require 'open-uri' | |
require 'nokogiri' | |
require 'csv' | |
require 'pry' | |
LAST_FM_ENDPOINT = 'http://ws.audioscrobbler.com/2.0/' | |
PAGE_SIZE = 200 | |
def result(username, api_key, page) | |
params = { | |
method: 'user.getrecenttracks', | |
user: username, | |
api_key: api_key, | |
limit: PAGE_SIZE, | |
page: page | |
} | |
open("#{LAST_FM_ENDPOINT}?#{params.to_query}").read | |
end | |
def tracks(username, api_key, page) | |
doc = Nokogiri::XML result(username, api_key, page) | |
doc.css(:track).map do |track| | |
Hash[%i(date name artist album).map do |key| | |
value = track.css(key).text | |
value = Time.parse(value).to_i if key == :date | |
[key, value] | |
end] | |
end | |
end | |
def save(username, api_key, filename, page = 1) | |
headers = %i(date name artist album) | |
CSV.open(filename, 'a') do |csv| | |
csv << headers unless File.size?(filename) | |
begin | |
last_result = tracks username, api_key, page | |
last_result.each do |track| | |
csv << headers.map { |key| track[key] } | |
end | |
puts "#{last_result.size} results" | |
page += 1 | |
end while last_result.size == PAGE_SIZE | |
end | |
end | |
username = 'narration' | |
api_key = '974a5ebc077564f72bd639d122479d4b' | |
filename = './scrobbles.csv' | |
save username, api_key, filename |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment