rss plugin: provide htmlinfo filter
[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     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 find_artist(m, params)
141     artist = params[:who].to_s
142     page = nil
143     begin
144       esc = URI.escape(CGI.escape(artist))
145       page = @bot.httputil.get "#{LASTFM}/music/#{esc}"
146       if page
147         if page.match(/<h1 class="h1artist"><a href="([^"]+)">(.*?)<\/a><\/h1>/)
148           url = LASTFM + $1
149           title = $2.ircify_html
150         else
151           raise "No URL/Title found for #{artist}"
152         end
153
154         wiki = "This artist doesn't have a description yet. You can help by writing it: #{url}/+wiki?action=edit"
155         if page.match(/<div (?:class|id)="wikiAbstract">(.*?)<\/div>/m)
156           wiki = $1.ircify_html
157         end
158
159         m.reply "%s : %s\n%s" % [title, url, wiki], :overlong => :truncate
160       else
161         m.reply "no data found on #{artist}"
162         return
163       end
164     rescue Exception => e
165       m.reply "I had problems looking for #{artist}"
166       error e.inspect
167       debug e.backtrace.join("\n")
168       debug page[0...10*1024] if page
169       return
170     end
171   end
172
173   def find_track(m, params)
174     m.reply "not implemented yet, sorry"
175   end
176
177   def find_album(m, params)
178     m.reply "not implemented yet, sorry"
179   end
180
181   def lastfm(m, params)
182     action = params[:action].intern
183     action = :neighbours if action == :neighbors
184     user = params[:user]
185     begin
186       data = @bot.httputil.get("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
187       m.reply "#{action} for #{user}:"
188       m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
189     rescue
190       m.reply "could not find #{action} for #{user} (is #{user} a user?)"
191     end
192   end
193 end
194
195 plugin = LastFmPlugin.new
196 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
197 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
198 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_event, :requirements => { :num => /\d+/ }, :thread => true
199 plugin.map 'lastfm artist *who', :action => :find_artist, :thread => true
200 plugin.map 'lastfm group *who', :action => :find_artist, :thread => true
201 plugin.map 'lastfm track *dunno', :action => :find_track
202 plugin.map 'lastfm song *dunno', :action => :find_track
203 plugin.map 'lastfm album *dunno', :action => :find_album
204 plugin.map 'lastfm :action *user', :thread => true