]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blobdiff - data/rbot/plugins/lastfm.rb
url plugin: add list of hosts for which no link info should be retrieved
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / lastfm.rb
index 49ef9fed826459b363dee82f5b9f471bfbaa89d8..4ec79510873861dee5ba494f5a4702a0a2475236 100644 (file)
 #
 # License:: GPL v2
 
-require 'open-uri'
-
 class ::LastFmEvent
+  # matches are:
+  # 1. day 2. moth 3. year 4. url_who 5. who 6. url_where 7. where 8. how_many
+  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
   attr_accessor :url, :date, :artist, :location, :attendance
   def initialize(url, date, artist, location, attendance)
     @url = url
@@ -35,13 +36,19 @@ class ::LastFmEvent
 end
 
 class LastFmPlugin < Plugin
+  BotConfig.register BotConfigIntegerValue.new('lastfm.max_events',
+    :default => 25, :validate => Proc.new{|v| v > 1},
+    :desc => "Maximum number of events to display.")
+  BotConfig.register BotConfigIntegerValue.new('lastfm.default_events',
+    :default => 3, :validate => Proc.new{|v| v > 1},
+    :desc => "Default number of events to display.")
 
   LASTFM = "http://www.last.fm"
 
   def help(plugin, topic="")
-    case topic.intern
+    case (topic.intern rescue nil)
     when :event, :events
-      "lastfm events in <location> => show information on events in or near <location>. lastfm events by <artist/group> => show information on events by <artist/group>"
+      "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']}"
     when :artist, :group
       "lastfm artist <name> => show information on artist/group <name> from last.fm"
     when :song, :track
@@ -54,75 +61,83 @@ class LastFmPlugin < Plugin
   end
 
   def find_event(m, params)
+    num = params[:num] || @bot.config['lastfm.default_events']
+    num = num.to_i.clip(1, @bot.config['lastfm.max_events'])
+
     location = artist = nil
     location = params[:location].to_s if params[:location]
     artist = params[:who].to_s if params[:who]
     page = nil
     spec = location ? "in #{location}" : "by #{artist}"
-    begin
-      if location
-        esc = URI.escape(location)
-        page = @bot.httputil.get "#{LASTFM}/events/?findloc=#{esc}"
-      else
-        esc = URI.escape(artist)
-        page = @bot.httputil.get "#{LASTFM}/events?s=#{esc}&findloc="
-      end
-
-      if page
-        events = Array.new
-        disp_events = Array.new
-
-        # matches are:
-        # 1. day 2. moth 3. year 4. url_who 5. who 6. url_where 7. where 8. how_many
-        pre_events = page.scan(/<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)
-        # debug pre_events.inspect
-        if pre_events.empty?
-          m.reply "No events found #{spec}, sorry"
-        end
-        pre_events.each { |day, month, year, url_who, who, url_where, where, how_many|
-          date = Time.utc(year.to_i, month.to_i, day.to_i)
-          url = LASTFM + url_who
-          if who.match(/<strong>(.*?)<\/strong>(.+)?/)
-            artist = Bold + $1.ircify_html + Bold
-            artist << ", " << $2.ircify_html if $2
-          else
-            debug "who: #{who.inspect}"
-            artist = who.ircify_html
-          end
-          if where.match(/<strong>(.*?)<\/strong>(?:<br\s*\/>(.+)?)?/)
-            loc = Bold + $1.ircify_html + Bold
-            loc << ", " << $2.ircify_html if $2
-          else
-            debug where.inspect
-            loc = where.ircify_html
+    query = location ? "?findloc=#{CGI.escape(location)}" : "?s=#{CGI.escape(artist)}&findloc="
+    Thread.new {
+      begin
+        page = @bot.httputil.get LASTFM + "/events/" + query
+        if page
+          events = Array.new
+          disp_events = Array.new
+
+          pre_events = page.scan(LastFmEvent::REGEXP)
+          # debug pre_events.inspect
+          if pre_events.empty?
+            # We may not find any even because the page gives a list
+            # of locations instead. In this case, retry with the first of
+            # these location
+            if page.match(/<a href="(\/events\/\?l=[^"]+)">/)
+              debug "Rechecking with #{$1}"
+              page = @bot.httputil.get(LASTFM+$1)
+              pre_events = page.scan(LastFmEvent::REGEXP) if page
+            end
+            if pre_events.empty?
+              m.reply "No events found #{spec}, sorry"
+              Thread.exit
+            end
           end
-          attendance = how_many.ircify_html
-          events << LastFmEvent.new(url, date, artist, loc, attendance)
-        }
-        # debug events.inspect
-
-        events[0..2].each { |event|
-          disp_events << event.to_s
-        }
-        m.reply disp_events.join(' | ')
-      else
-        m.reply "No events found #{spec}"
-        return
+          pre_events.each { |day, month, year, url_who, who, url_where, where, how_many|
+            date = Time.utc(year.to_i, month.to_i, day.to_i)
+            url = LASTFM + url_who
+            if who.match(/<strong>(.*?)<\/strong>(.+)?/)
+              artist = Bold + $1.ircify_html + Bold
+              artist << ", " << $2.ircify_html if $2
+            else
+              debug "who: #{who.inspect}"
+              artist = who.ircify_html
+            end
+            if where.match(/<strong>(.*?)<\/strong>(?:<br\s*\/>(.+)?)?/)
+              loc = Bold + $1.ircify_html + Bold
+              loc << ", " << $2.ircify_html if $2
+            else
+              debug where.inspect
+              loc = where.ircify_html
+            end
+            attendance = how_many.ircify_html
+            events << LastFmEvent.new(url, date, artist, loc, attendance)
+          }
+          # debug events.inspect
+
+          events[0...num].each { |event|
+            disp_events << event.to_s
+          }
+          m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
+        else
+          m.reply "No events found #{spec}"
+          Thread.exit
+        end
+      rescue Exception => e
+        m.reply "I had problems looking for events #{spec}"
+        error e.inspect
+        debug e.backtrace.join("\n")
+        debug page[0...10*1024] if page
+        Thread.exit
       end
-    rescue Exception => e
-      m.reply "I had problems looking for events #{spec}"
-      error e.inspect
-      debug e.backtrace.join("\n")
-      debug page[0...10*1024] if page
-      return
-    end
+    }
   end
 
   def find_artist(m, params)
     artist = params[:who].to_s
     page = nil
     begin
-      esc = URI.escape(artist)
+      esc = URI.escape(CGI.escape(artist))
       page = @bot.httputil.get "#{LASTFM}/music/#{esc}"
       if page
         if page.match(/<h1 class="h1artist"><a href="([^"]+)">(.*?)<\/a><\/h1>/)
@@ -163,20 +178,22 @@ class LastFmPlugin < Plugin
     action = params[:action].intern
     action = :neighbours if action == :neighbors
     user = params[:user]
-    begin
-      data = open("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
-      m.reply "#{action} for #{user}:"
-      m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
-    rescue
-      m.reply "could not find #{action} for #{user} (is #{user} a user?)"
-    end
+    Thread.new {
+      begin
+        data = @bot.httputil.get("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
+        m.reply "#{action} for #{user}:"
+        m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
+      rescue
+        m.reply "could not find #{action} for #{user} (is #{user} a user?)"
+      end
+    }
   end
 end
 
 plugin = LastFmPlugin.new
-plugin.map 'lastfm event[s] in *location', :action => :find_event
-plugin.map 'lastfm event[s] by *who', :action => :find_event
-plugin.map 'lastfm event[s] [for] *who', :action => :find_event
+plugin.map 'lastfm [:num] event[s] in *location', :action => :find_event, :requirements => { :num => /\d+/ }
+plugin.map 'lastfm [:num] event[s] by *who', :action => :find_event, :requirements => { :num => /\d+/ }
+plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_event, :requirements => { :num => /\d+/ }
 plugin.map 'lastfm artist *who', :action => :find_artist
 plugin.map 'lastfm group *who', :action => :find_artist
 plugin.map 'lastfm track *dunno', :action => :find_track