lastfm plugin: tries to parse the current station. will show just listened track...
[rbot] / data / rbot / plugins / lastfm.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: lastfm plugin for rbot
5 #
6 # Author:: Jeremy Voorhis
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 # Author:: Casey Link <unnamedrambler@gmail.com>
9 #
10 # Copyright:: (C) 2005 Jeremy Voorhis
11 # Copyright:: (C) 2007 Giuseppe Bilotta
12 # Copyright:: (C) 2008 Casey Link
13 #
14 # License:: GPL v2
15
16 class ::LastFmEvent
17   SELECTOR = /<tr class="vevent.*?<\/tr>/m
18   # matches are:
19   # 1. day 2. moth 3. year 4. url_who 5. who 6. url_where 7. where 8. how_many
20   # TODO festival have TWO dates  -------+
21   # TODO event type -------------+       |
22   #                              V       V
23   MATCHER = /<tr class="vevent\s+\w+\s+(?:\S+\s+)?\S+?-(\d\d)-(\d\d)-(\d\d\d\d)\s*">.*?<a class="url summary" href="(\/event\/\d+)">(.*?)<\/a>.*?<a href="(\/venue\/\d+)">(.*?)<\/a>.*?<td>(?:(.*?) attending\s+)?.*?<\/td>\s+<\/tr>/m
24   attr_accessor :url, :date, :artist, :location, :attendance
25   def initialize(url, date, artist, location, attendance)
26     @url = url
27     @date = date
28     @artist = artist
29     @location = location
30     @attendance = attendance
31   end
32
33   def compact_display
34     if @attendance.empty?
35       return "%s %s @ %s %s" % [@date.strftime("%a %b, %d %Y"), @artist, @location, @url]
36     else
37       return "%s %s @ %s (%s) %s" % [@date.strftime("%a %b, %d %Y"), @artist, @location, @attendance, @url]
38     end
39   end
40   alias :to_s :compact_display
41
42 end
43
44 class LastFmPlugin < Plugin
45   Config.register Config::IntegerValue.new('lastfm.max_events',
46     :default => 25, :validate => Proc.new{|v| v > 1},
47     :desc => "Maximum number of events to display.")
48   Config.register Config::IntegerValue.new('lastfm.default_events',
49     :default => 3, :validate => Proc.new{|v| v > 1},
50     :desc => "Default number of events to display.")
51
52   LASTFM = "http://www.last.fm"
53
54   def initialize
55     super
56     class << @registry
57       def store(val)
58         val
59       end
60       def restore(val)
61         val
62       end
63     end
64   end
65
66   def help(plugin, topic="")
67     case (topic.intern rescue nil)
68     when :event, :events
69       "lastfm [<num>] events in <location> => show information on events in or near <location>. lastfm [<num>] events by <artist/group> => show information on events by <artist/group>. The number of events <num> that can be displayed is optional, defaults to #{@bot.config['lastfm.default_events']} and cannot be higher than #{@bot.config['lastfm.max_events']}"
70     when :artist, :group
71       "lastfm artist <name> => show information on artist/group <name> from last.fm"
72     when :song, :track
73       "lastfm track <name> => show information on track/song <name> from last.fm [not implemented yet]"
74     when :album
75       "lastfm album <name> => show information on album <name> from last.fm [not implemented yet]"
76     when :now
77       "lastfm now [<user>] => show the now playing track from last.fm"
78     when :set
79       "lastfm set <user> => associate your current irc nick with a last.fm user"
80     when :who
81       "lastfm who [<nick>] => show who <nick> is at last.fm. if <nick> is empty, show who you are at lastfm."
82     else
83       "lastfm => show your now playing track at lastfm. lastfm <function> [<user>] => lastfm data for <user> on last.fm where <function> in [recenttracks, topartists, topalbums, toptracks, tags, friends, neighbors]. other topics: events, artist, group, song, track, album, now, set, who"
84     end
85   end
86
87   def find_event(m, params)
88     num = params[:num] || @bot.config['lastfm.default_events']
89     num = num.to_i.clip(1, @bot.config['lastfm.max_events'])
90
91     location = artist = nil
92     location = params[:location].to_s if params[:location]
93     artist = params[:who].to_s if params[:who]
94     page = nil
95     spec = location ? "in #{location}" : "by #{artist}"
96     query = location ? "?findloc=#{CGI.escape(location)}" : "?s=#{CGI.escape(artist)}&findloc="
97     begin
98       page = @bot.httputil.get LASTFM + "/events/" + query
99       if page
100         events = Array.new
101         disp_events = Array.new
102
103         pre_events = page.scan(LastFmEvent::SELECTOR)
104         # debug pre_events.inspect
105         if pre_events.empty?
106           # We may not find any even because the page gives a list
107           # of locations instead. In this case, retry with the first of
108           # these location
109           if page.match(/<a href="(\/events\/\?l=[^"]+)">/)
110             debug "Rechecking with #{$1}"
111             page = @bot.httputil.get(LASTFM+$1)
112             debug page
113             pre_events = page.scan(LastFmEvent::SELECTOR) if page
114             debug pre_events
115           end
116           if pre_events.empty?
117             m.reply "No events found #{spec}, sorry"
118             return
119           end
120         end
121         pre_events.each { |s| s.scan(LastFmEvent::MATCHER) { |day, month, year, url_who, who, url_where, where, how_many|
122           date = Time.utc(year.to_i, month.to_i, day.to_i)
123           url = LASTFM + url_who
124           if who.match(/<strong>(.*?)<\/strong>(.+)?/)
125             artist = Bold + $1.ircify_html + Bold
126             artist << ", " << $2.ircify_html if $2
127           else
128             debug "who: #{who.inspect}"
129             artist = who.ircify_html
130           end
131           if where.match(/<strong>(.*?)<\/strong>(?:<br\s*\/>(.+)?)?/)
132             loc = Bold + $1.ircify_html + Bold
133             loc << ", " << $2.ircify_html if $2
134           else
135             debug where.inspect
136             loc = where.ircify_html
137           end
138           attendance = how_many ? how_many.ircify_html : ''
139           events << LastFmEvent.new(url, date, artist, loc, attendance)
140         } }
141         # debug events.inspect
142
143         events[0...num].each { |event|
144           disp_events << event.to_s
145         }
146         m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
147       else
148         m.reply "No events found #{spec}"
149         return
150       end
151     rescue Exception => e
152       m.reply "I had problems looking for events #{spec}"
153       error e.inspect
154       debug e.backtrace.join("\n")
155       debug page[0...10*1024] if page
156       return
157     end
158   end
159
160   def now_playing(m, params)
161     opts = { :cache => false }
162     user = nil
163     if params[:who] then
164       user = params[:who].to_s
165     elsif @registry.has_key? ( m.sourcenick ) then
166       user = @registry[ m.sourcenick ]
167     else
168       # m.reply "I don't know who you are on last.fm. Use 'lastfm set username' to identify yourself."
169       # return
170       user = m.sourcenick
171     end
172     page = nil
173     begin
174       page = @bot.httputil.get("#{LASTFM}/user/#{user}", opts)
175       if page
176         if page.match(/class="nowListening">\s*<td class="subject">\s*<a href="\/music.*?">(.*)<\/a>\s*<\/td/)
177           track = $1
178           if page.match(/class="nowListening currentStation">\s*(.*?)<\/a>/m)
179             m.reply "#{user} is #{$1.ircify_html}"
180           end
181           m.reply "#{user} is jammin to #{track.ircify_html}"
182         elsif page.match(/class="justlistened first">\s*<td class="subject">.*<\/span><\/a>?(.*)<\/a>\s*<\/td>\s*<td class="date">\s*just/m)
183           m.reply "#{user} just jammed to #{$1.ircify_html}"
184         else
185           params[:action] = "recenttracks"
186           params[:user] = user
187           lastfm(m, params)
188         end
189       else
190         return if params[:recurs]
191         if @registry.has_key? ( user ) then
192           params[:who] = @registry[ user ]
193           params[:recurs] = true
194           now_playing(m, params)
195         else
196           m.reply "#{user} doesn't exist at last.fm. Perhaps you need to: lastfm set <username>"
197         end
198       end
199     rescue
200       m.reply "I had problems getting #{user}'s current info"
201     end
202   end
203
204   def find_artist(m, params)
205     artist = params[:who].to_s
206     page = nil
207     begin
208       esc = URI.escape(CGI.escape(artist))
209       page = @bot.httputil.get "#{LASTFM}/music/#{esc}"
210       if page
211         if page.match(/<h1 class="h1artist"><a href="([^"]+)">(.*?)<\/a><\/h1>/)
212           url = LASTFM + $1
213           title = $2.ircify_html
214         else
215           raise "No URL/Title found for #{artist}"
216         end
217
218         wiki = "This artist doesn't have a description yet. You can help by writing it: #{url}/+wiki?action=edit"
219         if page.match(/<div (?:class|id)="wikiAbstract">(.*?)<\/div>/m)
220           wiki = $1.ircify_html
221         end
222
223         m.reply "%s : %s\n%s" % [title, url, wiki], :overlong => :truncate
224       else
225         m.reply "no data found on #{artist}"
226         return
227       end
228     rescue Exception => e
229       m.reply "I had problems looking for #{artist}"
230       error e.inspect
231       debug e.backtrace.join("\n")
232       debug page[0...10*1024] if page
233       return
234     end
235   end
236
237   def find_track(m, params)
238     m.reply "not implemented yet, sorry"
239   end
240
241   def find_album(m, params)
242     m.reply "not implemented yet, sorry"
243   end
244
245   def set_user(m, params)
246     user = params[:who].to_s
247     nick = m.sourcenick
248     @registry[ nick ] = user
249     m.reply "Ok, I'll remember that #{nick} is #{user} at last.fm"
250   end
251
252   def get_user(m, params)
253     nick = ""
254     if params[:who] then
255       nick = params[:who].to_s
256     else 
257       nick = m.sourcenick
258     end
259     if @registry.has_key?( nick ) then
260       user = @registry[ nick ]
261       m.reply "#{nick} is #{user} at last.fm"
262     else
263       m.reply "Sorry, I don't know who #{nick} is at last.fm perhaps you need to: lastfm set <username>"
264     end
265   end
266
267   def lastfm(m, params)
268     action = params[:action].intern
269     action = :neighbours if action == :neighbors
270     user = nil
271     if params[:user] then
272       user = params[:user].to_s
273     elsif @registry.has_key? ( m.sourcenick ) then
274       user = @registry[ m.sourcenick ]
275     else
276       # m.reply "I don't know who you are on last.fm. Use 'lastfm set username' to identify yourself."
277       # return
278       user = m.sourcenick
279     end
280     begin
281       data = @bot.httputil.get("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
282       m.reply "#{action} for #{user}:"
283       m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
284     rescue
285       m.reply "could not find #{action} for #{user} (is #{user} a user?). perhaps you need to: lastfm set <username>"
286     end
287   end
288 end
289
290 plugin = LastFmPlugin.new
291 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
292 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
293 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
294 plugin.map 'lastfm artist *who', :action => :find_artist, :thread => true
295 plugin.map 'lastfm group *who', :action => :find_artist, :thread => true
296 plugin.map 'lastfm now *who', :action => :now_playing, :thread => true
297 plugin.map 'lastfm now', :action => :now_playing, :thread => true
298 plugin.map 'lastfm track *dunno', :action => :find_track
299 plugin.map 'lastfm song *dunno', :action => :find_track
300 plugin.map 'lastfm album *dunno', :action => :find_album
301 plugin.map 'lastfm set *who', :action => :set_user, :thread => true
302 plugin.map 'lastfm who *who', :action => :get_user, :thread => true
303 plugin.map 'lastfm who', :action => :get_user, :thread => true
304 plugin.map 'lastfm :action *user', :thread => true
305 plugin.map 'lastfm :action', :thread => true
306 plugin.map 'lastfm', :action => :now_playing, :thread => true