Created
May 30, 2009 05:55
-
-
Save youpy/120400 to your computer and use it in GitHub Desktop.
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
require 'rubygems' | |
require 'nokogiri' | |
require 'open-uri' | |
def main | |
html = Nokogiri(open('http://www.last.fm/user/youpy/friends').read) | |
next_link = nil | |
tracks = [] | |
begin | |
spans = html.search('//p[@class="nowListening"]/span') | |
unless spans.empty? | |
spans.each do |span| | |
tracks << span.search('.//a').map {|e| e.text } | |
end | |
end | |
next_link = html.at('//a[@class="nextlink"]') | |
end while next_link && html = Nokogiri(open(URI('http://www.last.fm/') + URI(next_link[:href])).read) | |
itunes = ITunes() | |
unless itunes.playing? | |
tracks.sort_by { rand }.each do |track| | |
artist, name = track | |
unless (found_tracks = itunes.search_track(name, artist)).empty? | |
selected_track = found_tracks.sort_by {|track| track.duration }.last | |
itunes.play(selected_track, :once => 1) | |
break | |
end | |
end | |
end | |
end | |
def ITunes | |
case RUBY_PLATFORM | |
when /darwin/ | |
ITunes::Mac.new | |
when /win/ | |
ITunes::Windows.new | |
else | |
raise "not implemented yet" | |
end | |
end | |
module ITunes | |
class Mac | |
def initialize | |
require 'rbosa' | |
OSA.utf8_strings = true | |
@itunes = OSA.app('iTunes') | |
end | |
def playing? | |
@itunes.player_state.to_s == 'playing' | |
end | |
def current_track | |
{ | |
:name => @itunes.current_track.name, | |
:artist => @itunes.current_track.artist, | |
:rating => @itunes.current_track.rating | |
} | |
end | |
def search_track(name, artist) | |
library.playlists[0].search([name, artist].join(' ')) | |
end | |
def play(track, options = {}) | |
@itunes.play(track, options) | |
end | |
private | |
def library | |
@itunes.sources.find {|s| s.kind == OSA::ITunes::ESRC::LIBRARY } | |
end | |
end | |
class Windows | |
def initialize | |
require 'win32ole' | |
@itunes = WIN32OLE.new("iTunes.Application") | |
end | |
def playing? | |
@itunes.CurrentTrack | |
end | |
def current_track | |
{ | |
:name => @itunes.CurrentTrack.Name, | |
:artist => @itunes.CurrentTrack.Artist, | |
:rating => @itunes.CurrentTrack.Rating | |
} | |
end | |
def search_track(name, artist) | |
@itunes.LibraryPlaylist.Search([name, artist].join(' ')) | |
end | |
def play(track, options = {}) | |
raise "I don't know how to play selected track..." | |
end | |
end | |
end | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment