Jake.codes

TimeSpent, for Last.fm

Saturday, April 13, 2013

Looks up your Last.fm history and adds up the duration of all the songs you played in the last week. Great for use with Spotify or Rdio to see if you are getting your money worth.

require 'json'
require 'open-uri'
require 'cgi'
require 'chronic'

# Get a Last.fm API key at http://www.last.fm/api/accounts
LASTFM_KEY = ""
LASTFM_USERNAME = ""

page = 1
totalDuration = 0
today = Chronic.parse("today").to_i
lastWeek = Chronic.parse("one week ago").to_i

url = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=#{LASTFM_USERNAME}&from=#{lastWeek}&to=#{today}&limit=200&api_key=#{LASTFM_KEY}&format=json"
lastfmDetails = open(url) do |file|
    JSON.parse(file.read)
end
totalPages = lastfmDetails['recenttracks']['@attr']['totalPages'].to_i
totalSongs = lastfmDetails['recenttracks']['@attr']['total'].to_i

totalPages.times {
    url = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=#{LASTFM_USERNAME}&from=#{lastWeek}&to=#{today}&limit=200&page=#{page}&api_key=#{LASTFM_KEY}&format=json"
    recentlyPlayed = open(url) do |file|
        JSON.parse(file.read)
    end
    recentlyPlayed['recenttracks']['track'].each do |track|
        song = track['name']
        artist = track['artist']['#text']

        url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=#{LASTFM_KEY}&artist=#{CGI::escape(artist)}&track=#{CGI::escape(song)}&format=json"
        trackInfo = open(url) do |file|
            JSON.parse(file.read)
        end

        duration = trackInfo['track']['duration'].to_i / 1000

        totalDuration += duration
    end
    page += 1
}

puts "In the last week you have listened to #{totalSongs} songs for a total of #{totalDuration/60} minutes."