lastfm plugin: no need to specify a username for functions that act on a user. fixed...
[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     end
171     page = nil
172     begin
173       page = @bot.httputil.get("#{LASTFM}/user/#{user}", opts)
174       if page
175         if page.match(/class="nowListening">\s*<td class="subject">\s*<a href="\/music.*?">(.*)<\/a>\s*<\/td/)
176           m.reply "#{user} is jammin to #{$1.ircify_html}"
177         else
178           m.reply "#{user} isn't listening to anything right now."
179         end
180       end
181     rescue
182       m.reply "I had problems getting #{user}'s current info"
183     end
184   end
185
186   def find_artist(m, params)
187     artist = params[:who].to_s
188     page = nil
189     begin
190       esc = URI.escape(CGI.escape(artist))
191       page = @bot.httputil.get "#{LASTFM}/music/#{esc}"
192       if page
193         if page.match(/<h1 class="h1artist"><a href="([^"]+)">(.*?)<\/a><\/h1>/)
194           url = LASTFM + $1
195           title = $2.ircify_html
196         else
197           raise "No URL/Title found for #{artist}"
198         end
199
200         wiki = "This artist doesn't have a description yet. You can help by writing it: #{url}/+wiki?action=edit"
201         if page.match(/<div (?:class|id)="wikiAbstract">(.*?)<\/div>/m)
202           wiki = $1.ircify_html
203         end
204
205         m.reply "%s : %s\n%s" % [title, url, wiki], :overlong => :truncate
206       else
207         m.reply "no data found on #{artist}"
208         return
209       end
210     rescue Exception => e
211       m.reply "I had problems looking for #{artist}"
212       error e.inspect
213       debug e.backtrace.join("\n")
214       debug page[0...10*1024] if page
215       return
216     end
217   end
218
219   def find_track(m, params)
220     m.reply "not implemented yet, sorry"
221   end
222
223   def find_album(m, params)
224     m.reply "not implemented yet, sorry"
225   end
226
227   def set_user(m, params)
228     user = params[:who].to_s
229     nick = m.sourcenick
230     @registry[ nick ] = user
231     m.reply "Ok, I'll remember that #{nick} is #{user} at last.fm"
232   end
233
234   def get_user(m, params)
235     nick = ""
236     if params[:who] then
237       nick = params[:who].to_s
238     else 
239       nick = m.sourcenick
240     end
241     if @registry.has_key?( nick ) then
242       user = @registry[ nick ]
243       m.reply "#{nick} is #{user} at last.fm"
244     else
245       m.reply "Sorry, I don't know who #{nick} is at last.fm"
246     end
247   end
248
249   def lastfm(m, params)
250     action = params[:action].intern
251     action = :neighbours if action == :neighbors
252     user = nil
253     if params[:user] then
254       user = params[:user].to_s
255     elsif @registry.has_key? ( m.sourcenick ) then
256       user = @registry[ m.sourcenick ]
257     else
258       m.reply "I don't know who you are on last.fm. Use 'lastfm set username' to identify yourself."
259       return
260     end
261     begin
262       data = @bot.httputil.get("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
263       m.reply "#{action} for #{user}:"
264       m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
265     rescue
266       m.reply "could not find #{action} for #{user} (is #{user} a user?)"
267     end
268   end
269 end
270
271 plugin = LastFmPlugin.new
272 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
273 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
274 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
275 plugin.map 'lastfm artist *who', :action => :find_artist, :thread => true
276 plugin.map 'lastfm group *who', :action => :find_artist, :thread => true
277 plugin.map 'lastfm now *who', :action => :now_playing, :thread => true
278 plugin.map 'lastfm now', :action => :now_playing, :thread => true
279 plugin.map 'lastfm track *dunno', :action => :find_track
280 plugin.map 'lastfm song *dunno', :action => :find_track
281 plugin.map 'lastfm album *dunno', :action => :find_album
282 plugin.map 'lastfm set *who', :action => :set_user, :thread => true
283 plugin.map 'lastfm who *who', :action => :get_user, :thread => true
284 plugin.map 'lastfm who', :action => :get_user, :thread => true
285 plugin.map 'lastfm :action *user', :thread => true
286 plugin.map 'lastfm :action', :thread => true
287 plugin.map 'lastfm', :action => :now_playing, :thread => true