lastfm plugin: added now playing info to the help
[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 #
9 # Copyright:: (C) 2005 Jeremy Voorhis
10 # Copyright:: (C) 2007 Giuseppe Bilotta
11 #
12 # License:: GPL v2
13
14 class ::LastFmEvent
15   SELECTOR = /<tr class="vevent.*?<\/tr>/m
16   # matches are:
17   # 1. day 2. moth 3. year 4. url_who 5. who 6. url_where 7. where 8. how_many
18   # TODO festival have TWO dates  -------+
19   # TODO event type -------------+       |
20   #                              V       V
21   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
22   attr_accessor :url, :date, :artist, :location, :attendance
23   def initialize(url, date, artist, location, attendance)
24     @url = url
25     @date = date
26     @artist = artist
27     @location = location
28     @attendance = attendance
29   end
30
31   def compact_display
32     if @attendance.empty?
33       return "%s %s @ %s %s" % [@date.strftime("%a %b, %d %Y"), @artist, @location, @url]
34     else
35       return "%s %s @ %s (%s) %s" % [@date.strftime("%a %b, %d %Y"), @artist, @location, @attendance, @url]
36     end
37   end
38   alias :to_s :compact_display
39
40 end
41
42 class LastFmPlugin < Plugin
43   Config.register Config::IntegerValue.new('lastfm.max_events',
44     :default => 25, :validate => Proc.new{|v| v > 1},
45     :desc => "Maximum number of events to display.")
46   Config.register Config::IntegerValue.new('lastfm.default_events',
47     :default => 3, :validate => Proc.new{|v| v > 1},
48     :desc => "Default number of events to display.")
49
50   LASTFM = "http://www.last.fm"
51
52   def help(plugin, topic="")
53     case (topic.intern rescue nil)
54     when :event, :events
55       "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']}"
56     when :artist, :group
57       "lastfm artist <name> => show information on artist/group <name> from last.fm"
58     when :song, :track
59       "lastfm track <name> => show information on track/song <name> from last.fm [not implemented yet]"
60     when :album
61       "lastfm album <name> => show information on album <name> from last.fm [not implemented yet]"
62     when :now
63       "lastfm now <user> => show the now playing track from last.fm"
64     else
65       "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"
66     end
67   end
68
69   def find_event(m, params)
70     num = params[:num] || @bot.config['lastfm.default_events']
71     num = num.to_i.clip(1, @bot.config['lastfm.max_events'])
72
73     location = artist = nil
74     location = params[:location].to_s if params[:location]
75     artist = params[:who].to_s if params[:who]
76     page = nil
77     spec = location ? "in #{location}" : "by #{artist}"
78     query = location ? "?findloc=#{CGI.escape(location)}" : "?s=#{CGI.escape(artist)}&findloc="
79     begin
80       page = @bot.httputil.get LASTFM + "/events/" + query
81       if page
82         events = Array.new
83         disp_events = Array.new
84
85         pre_events = page.scan(LastFmEvent::SELECTOR)
86         # debug pre_events.inspect
87         if pre_events.empty?
88           # We may not find any even because the page gives a list
89           # of locations instead. In this case, retry with the first of
90           # these location
91           if page.match(/<a href="(\/events\/\?l=[^"]+)">/)
92             debug "Rechecking with #{$1}"
93             page = @bot.httputil.get(LASTFM+$1)
94             debug page
95             pre_events = page.scan(LastFmEvent::SELECTOR) if page
96             debug pre_events
97           end
98           if pre_events.empty?
99             m.reply "No events found #{spec}, sorry"
100             return
101           end
102         end
103         pre_events.each { |s| s.scan(LastFmEvent::MATCHER) { |day, month, year, url_who, who, url_where, where, how_many|
104           date = Time.utc(year.to_i, month.to_i, day.to_i)
105           url = LASTFM + url_who
106           if who.match(/<strong>(.*?)<\/strong>(.+)?/)
107             artist = Bold + $1.ircify_html + Bold
108             artist << ", " << $2.ircify_html if $2
109           else
110             debug "who: #{who.inspect}"
111             artist = who.ircify_html
112           end
113           if where.match(/<strong>(.*?)<\/strong>(?:<br\s*\/>(.+)?)?/)
114             loc = Bold + $1.ircify_html + Bold
115             loc << ", " << $2.ircify_html if $2
116           else
117             debug where.inspect
118             loc = where.ircify_html
119           end
120           attendance = how_many ? how_many.ircify_html : ''
121           events << LastFmEvent.new(url, date, artist, loc, attendance)
122         } }
123         # debug events.inspect
124
125         events[0...num].each { |event|
126           disp_events << event.to_s
127         }
128         m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
129       else
130         m.reply "No events found #{spec}"
131         return
132       end
133     rescue Exception => e
134       m.reply "I had problems looking for events #{spec}"
135       error e.inspect
136       debug e.backtrace.join("\n")
137       debug page[0...10*1024] if page
138       return
139     end
140   end
141
142   def now_playing(m, params)
143     opts = { :cache => false }
144     user = params[:who].to_s
145     page = nil
146     begin
147       page = @bot.httputil.get("#{LASTFM}/user/#{user}", opts)
148       if page
149         if page.match(/class="nowListening">\s*<td class="subject">\s*<a href="\/music.*?">(.*)<\/a>\s*<\/td/)
150           m.reply "#{user} is jammin to #{$1.ircify_html}"
151         else
152           m.reply "#{user} isn't listening to anything right now."
153         end
154       end
155     rescue
156       m.reply "I had problems getting #{user}'s current info"
157     end
158   end
159
160   def find_artist(m, params)
161     artist = params[:who].to_s
162     page = nil
163     begin
164       esc = URI.escape(CGI.escape(artist))
165       page = @bot.httputil.get "#{LASTFM}/music/#{esc}"
166       if page
167         if page.match(/<h1 class="h1artist"><a href="([^"]+)">(.*?)<\/a><\/h1>/)
168           url = LASTFM + $1
169           title = $2.ircify_html
170         else
171           raise "No URL/Title found for #{artist}"
172         end
173
174         wiki = "This artist doesn't have a description yet. You can help by writing it: #{url}/+wiki?action=edit"
175         if page.match(/<div (?:class|id)="wikiAbstract">(.*?)<\/div>/m)
176           wiki = $1.ircify_html
177         end
178
179         m.reply "%s : %s\n%s" % [title, url, wiki], :overlong => :truncate
180       else
181         m.reply "no data found on #{artist}"
182         return
183       end
184     rescue Exception => e
185       m.reply "I had problems looking for #{artist}"
186       error e.inspect
187       debug e.backtrace.join("\n")
188       debug page[0...10*1024] if page
189       return
190     end
191   end
192
193   def find_track(m, params)
194     m.reply "not implemented yet, sorry"
195   end
196
197   def find_album(m, params)
198     m.reply "not implemented yet, sorry"
199   end
200
201   def lastfm(m, params)
202     action = params[:action].intern
203     action = :neighbours if action == :neighbors
204     user = params[:user]
205     begin
206       data = @bot.httputil.get("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
207       m.reply "#{action} for #{user}:"
208       m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
209     rescue
210       m.reply "could not find #{action} for #{user} (is #{user} a user?)"
211     end
212   end
213 end
214
215 plugin = LastFmPlugin.new
216 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
217 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
218 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
219 plugin.map 'lastfm artist *who', :action => :find_artist, :thread => true
220 plugin.map 'lastfm group *who', :action => :find_artist, :thread => true
221 plugin.map 'lastfm now *who', :action => :now_playing, :thread => true
222 plugin.map 'lastfm track *dunno', :action => :find_track
223 plugin.map 'lastfm song *dunno', :action => :find_track
224 plugin.map 'lastfm album *dunno', :action => :find_album
225 plugin.map 'lastfm :action *user', :thread => true