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