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