]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/lastfm.rb
bc7f819c8f0065343962935e8140673e303dd8b0
[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 #
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     else
63       "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"
64     end
65   end
66
67   def find_event(m, params)
68     num = params[:num] || @bot.config['lastfm.default_events']
69     num = num.to_i.clip(1, @bot.config['lastfm.max_events'])
70
71     location = artist = nil
72     location = params[:location].to_s if params[:location]
73     artist = params[:who].to_s if params[:who]
74     page = nil
75     spec = location ? "in #{location}" : "by #{artist}"
76     query = location ? "?findloc=#{CGI.escape(location)}" : "?s=#{CGI.escape(artist)}&findloc="
77     begin
78       page = @bot.httputil.get LASTFM + "/events/" + query
79       if page
80         events = Array.new
81         disp_events = Array.new
82
83         pre_events = page.scan(LastFmEvent::SELECTOR)
84         # debug pre_events.inspect
85         if pre_events.empty?
86           # We may not find any even because the page gives a list
87           # of locations instead. In this case, retry with the first of
88           # these location
89           if page.match(/<a href="(\/events\/\?l=[^"]+)">/)
90             debug "Rechecking with #{$1}"
91             page = @bot.httputil.get(LASTFM+$1)
92             debug page
93             pre_events = page.scan(LastFmEvent::SELECTOR) if page
94             debug pre_events
95           end
96           if pre_events.empty?
97             m.reply "No events found #{spec}, sorry"
98             return
99           end
100         end
101         pre_events.each { |s| s.scan(LastFmEvent::MATCHER) { |day, month, year, url_who, who, url_where, where, how_many|
102           date = Time.utc(year.to_i, month.to_i, day.to_i)
103           url = LASTFM + url_who
104           if who.match(/<strong>(.*?)<\/strong>(.+)?/)
105             artist = Bold + $1.ircify_html + Bold
106             artist << ", " << $2.ircify_html if $2
107           else
108             debug "who: #{who.inspect}"
109             artist = who.ircify_html
110           end
111           if where.match(/<strong>(.*?)<\/strong>(?:<br\s*\/>(.+)?)?/)
112             loc = Bold + $1.ircify_html + Bold
113             loc << ", " << $2.ircify_html if $2
114           else
115             debug where.inspect
116             loc = where.ircify_html
117           end
118           attendance = how_many ? how_many.ircify_html : ''
119           events << LastFmEvent.new(url, date, artist, loc, attendance)
120         } }
121         # debug events.inspect
122
123         events[0...num].each { |event|
124           disp_events << event.to_s
125         }
126         m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
127       else
128         m.reply "No events found #{spec}"
129         return
130       end
131     rescue Exception => e
132       m.reply "I had problems looking for events #{spec}"
133       error e.inspect
134       debug e.backtrace.join("\n")
135       debug page[0...10*1024] if page
136       return
137     end
138   end
139
140   def now_playing(m, params)
141     opts = { :cache => false }
142     user = params[:who].to_s
143     page = nil
144     begin
145       page = @bot.httputil.get("#{LASTFM}/user/#{user}", opts)
146       if page
147         if page.match(/class="nowListening">\s*<td class="subject">\s*<a href="\/music.*?">(.*)<\/a>\s*<\/td/)
148           m.reply "#{user} is jammin to #{$1.ircify_html}"
149         else
150           m.reply "#{user} isn't listening to anything right now."
151         end
152       end
153     rescue
154       m.reply "I had problems getting #{user}'s current info"
155     end
156   end
157
158   def find_artist(m, params)
159     artist = params[:who].to_s
160     page = nil
161     begin
162       esc = URI.escape(CGI.escape(artist))
163       page = @bot.httputil.get "#{LASTFM}/music/#{esc}"
164       if page
165         if page.match(/<h1 class="h1artist"><a href="([^"]+)">(.*?)<\/a><\/h1>/)
166           url = LASTFM + $1
167           title = $2.ircify_html
168         else
169           raise "No URL/Title found for #{artist}"
170         end
171
172         wiki = "This artist doesn't have a description yet. You can help by writing it: #{url}/+wiki?action=edit"
173         if page.match(/<div (?:class|id)="wikiAbstract">(.*?)<\/div>/m)
174           wiki = $1.ircify_html
175         end
176
177         m.reply "%s : %s\n%s" % [title, url, wiki], :overlong => :truncate
178       else
179         m.reply "no data found on #{artist}"
180         return
181       end
182     rescue Exception => e
183       m.reply "I had problems looking for #{artist}"
184       error e.inspect
185       debug e.backtrace.join("\n")
186       debug page[0...10*1024] if page
187       return
188     end
189   end
190
191   def find_track(m, params)
192     m.reply "not implemented yet, sorry"
193   end
194
195   def find_album(m, params)
196     m.reply "not implemented yet, sorry"
197   end
198
199   def lastfm(m, params)
200     action = params[:action].intern
201     action = :neighbours if action == :neighbors
202     user = params[:user]
203     begin
204       data = @bot.httputil.get("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
205       m.reply "#{action} for #{user}:"
206       m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
207     rescue
208       m.reply "could not find #{action} for #{user} (is #{user} a user?)"
209     end
210   end
211 end
212
213 plugin = LastFmPlugin.new
214 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
215 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
216 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
217 plugin.map 'lastfm artist *who', :action => :find_artist, :thread => true
218 plugin.map 'lastfm group *who', :action => :find_artist, :thread => true
219 plugin.map 'lastfm now *who', :action => :now_playing, :thread => true
220 plugin.map 'lastfm track *dunno', :action => :find_track
221 plugin.map 'lastfm song *dunno', :action => :find_track
222 plugin.map 'lastfm album *dunno', :action => :find_album
223 plugin.map 'lastfm :action *user', :thread => true