Created
March 3, 2009 09:03
-
-
Save noplans/73247 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
# vim:fileencoding=utf-8 | |
# http://www.smokeymonkey.net/2009/03/lastfmrankruby.html | |
require 'rubygems' if RUBY_VERSION < '1.9' | |
require 'open-uri' | |
require 'nokogiri' | |
require 'date' | |
require 'activesupport' | |
def extract_from(url, regexp) | |
id = $1 if regexp =~ url['href'] | |
username = url.inner_text | |
return id, username | |
end | |
def parse(track, element) | |
case element | |
when 'date' | |
Date.parse(track.at('date').inner_text) | |
else | |
track.at(element).inner_text | |
end | |
end | |
def check_enabled? | |
timestamp = 'timestamp.yaml' | |
last_checked = File.exist?(timestamp) ? YAML.load(File.open(timestamp)) : 30.minutes.ago | |
Time.now - last_checked > 30.minutes | |
end | |
unless check_enabled? | |
puts 'too early' | |
exit | |
end | |
doc = Nokogiri::HTML(open('http://twitter.g.hatena.ne.jp/keyword/Last.fm%E9%83%A8')) | |
header, *users = doc.xpath('//div[@class="section"][3]/table/tr') | |
users = users.map do |user| | |
twitter, lastfm = user.xpath('td/a') | |
t_id, t_name = extract_from(twitter, %r|http://twitter\.com/(.*)|) | |
l_id, = extract_from(lastfm, %r!http://www\.last(?:fm\.jp|\.fm)/user/(.*[^/])!) | |
{:twitter => {:id => t_id, :name => t_name}, :lastfm => l_id} | |
end | |
tracks = users.inject([]) do |list, user| | |
url = "http://ws.audioscrobbler.com/1.0/user/%s/recenttracks.xml" % user[:lastfm] | |
result = begin | |
doc = Nokogiri::XML(open(url)) | |
track = doc.at('//recenttracks/track') | |
%w(date artist name).map{|element| parse(track, element)} << user[:lastfm] << user[:twitter][:id] | |
rescue | |
[] | |
end | |
list + [result] | |
end.reject(&:empty?).sort{|a,b| b[0] <=> a[0]} # sort by date | |
YAML.dump(Time.now, File.open('timestamp.yaml', 'w')) | |
YAML.dump(tracks, File.open('lastfm.yaml', 'w')) | |
recent_music = tracks.first.each{|info| puts info} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment