]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blobdiff - data/rbot/plugins/rss.rb
Call 'super' method from #cleanup() in all plugins
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / rss.rb
index 68a5271b6921a5e43786be545ea7bb70ce710a41..905daad81ffcfa49c36fc88ea484441c8a5bdbda 100644 (file)
 #\r
 # License:: MIT license\r
 \r
-# require 'rss/parser'\r
-# require 'rss/1.0'\r
-# require 'rss/2.0'\r
-# require 'rss/dublincore'\r
-# # begin\r
-# #   require 'rss/dublincore/2.0'\r
-# # rescue\r
-# #   warning "Unable to load RSS libraries, RSS plugin functionality crippled"\r
-# # end\r
-#\r
-# GB: Let's just go for the simple stuff:\r
-#\r
 require 'rss'\r
 \r
+module ::RSS\r
+\r
+  # Make an  'unique' ID for a given item, based on appropriate bot options\r
+  # Currently only suppored is bot.config['rss.show_updated']: when true, the\r
+  # description is included in the uid hashing, otherwise it's not\r
+  #\r
+  def RSS.item_uid_for_bot(item, opts={})\r
+    options = { :show_updated => true}.merge(opts)\r
+    desc = options[:show_updated] ? item.description : nil\r
+    [item.title, item.link, desc].hash\r
+  end\r
+\r
+  # Add support for Slashdot namespace in RDF. The code is just an adaptation\r
+  # of the DublinCore code.\r
+  unless defined?(SLASH_PREFIX)\r
+    SLASH_PREFIX = 'slash'\r
+    SLASH_URI = "http://purl.org/rss/1.0/modules/slash/"\r
+\r
+    RDF.install_ns(SLASH_PREFIX, SLASH_URI)\r
+\r
+    module BaseSlashModel\r
+      def append_features(klass)\r
+        super\r
+\r
+        return if klass.instance_of?(Module)\r
+        SlashModel::ELEMENT_NAME_INFOS.each do |name, plural_name|\r
+          plural = plural_name || "#{name}s"\r
+          full_name = "#{SLASH_PREFIX}_#{name}"\r
+          full_plural_name = "#{SLASH_PREFIX}_#{plural}"\r
+          klass_name = "Slash#{Utils.to_class_name(name)}"\r
+          klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI)\r
+          klass.install_have_children_element(name, SLASH_URI, "*",\r
+                                              full_name, full_plural_name)\r
+          klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0))\r
+          remove_method :#{full_name}\r
+          remove_method :#{full_name}=\r
+          remove_method :set_#{full_name}\r
+\r
+          def #{full_name}\r
+            @#{full_name}.first and @#{full_name}.first.value\r
+          end\r
+\r
+          def #{full_name}=(new_value)\r
+            @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value)\r
+          end\r
+          alias set_#{full_name} #{full_name}=\r
+        EOC\r
+        end\r
+      end\r
+    end\r
+\r
+    module SlashModel\r
+      extend BaseModel\r
+      extend BaseSlashModel\r
+\r
+      TEXT_ELEMENTS = {\r
+      "department" => nil,\r
+      "section" => nil,\r
+      "comments" =>  nil,\r
+      "hit_parade" => nil\r
+      }\r
+\r
+      ELEMENT_NAME_INFOS = SlashModel::TEXT_ELEMENTS.to_a\r
+\r
+      ELEMENTS = TEXT_ELEMENTS.keys\r
+\r
+      ELEMENTS.each do |name, plural_name|\r
+        module_eval(<<-EOC, *get_file_and_line_from_caller(0))\r
+        class Slash#{Utils.to_class_name(name)} < Element\r
+          include RSS10\r
+\r
+          content_setup\r
+\r
+          class << self\r
+            def required_prefix\r
+              SLASH_PREFIX\r
+            end\r
+\r
+            def required_uri\r
+              SLASH_URI\r
+            end\r
+          end\r
+\r
+          @tag_name = #{name.dump}\r
+\r
+          alias_method(:value, :content)\r
+          alias_method(:value=, :content=)\r
+\r
+          def initialize(*args)\r
+            if Utils.element_initialize_arguments?(args)\r
+              super\r
+            else\r
+              super()\r
+              self.content = args[0]\r
+            end\r
+          end\r
+\r
+          def full_name\r
+            tag_name_with_prefix(SLASH_PREFIX)\r
+          end\r
+\r
+          def maker_target(target)\r
+            target.new_#{name}\r
+          end\r
+\r
+          def setup_maker_attributes(#{name})\r
+            #{name}.content = content\r
+          end\r
+        end\r
+      EOC\r
+      end\r
+    end\r
+\r
+    class RDF\r
+      class Item; include SlashModel; end\r
+    end\r
+\r
+    SlashModel::ELEMENTS.each do |name|\r
+      class_name = Utils.to_class_name(name)\r
+      BaseListener.install_class_name(SLASH_URI, name, "Slash#{class_name}")\r
+    end\r
+\r
+    SlashModel::ELEMENTS.collect! {|name| "#{SLASH_PREFIX}_#{name}"}\r
+  end\r
+end\r
+\r
+\r
 class ::RssBlob\r
   attr_accessor :url\r
   attr_accessor :handle\r
@@ -115,17 +230,21 @@ end
 \r
 class RSSFeedsPlugin < Plugin\r
   BotConfig.register BotConfigIntegerValue.new('rss.head_max',\r
-    :default => 30, :validate => Proc.new{|v| v > 0 && v < 200},\r
+    :default => 100, :validate => Proc.new{|v| v > 0 && v < 200},\r
     :desc => "How many characters to use of a RSS item header")\r
 \r
   BotConfig.register BotConfigIntegerValue.new('rss.text_max',\r
-    :default => 90, :validate => Proc.new{|v| v > 0 && v < 400},\r
+    :default => 200, :validate => Proc.new{|v| v > 0 && v < 400},\r
     :desc => "How many characters to use of a RSS item text")\r
 \r
   BotConfig.register BotConfigIntegerValue.new('rss.thread_sleep',\r
     :default => 300, :validate => Proc.new{|v| v > 30},\r
     :desc => "How many seconds to sleep before checking RSS feeds again")\r
 \r
+  BotConfig.register BotConfigBooleanValue.new('rss.show_updated',\r
+    :default => true,\r
+    :desc => "Whether feed items for which the description was changed should be shown as new")\r
+\r
   # We used to save the Mutex with the RssBlob, which was idiotic. And\r
   # since Mutexes dumped in one version might not be resotrable in another,\r
   # we need a few tricks to be able to restore data from other versions of Ruby\r
@@ -141,6 +260,8 @@ class RSSFeedsPlugin < Plugin
     end\r
   end\r
 \r
+  attr_reader :feeds\r
+\r
   def initialize\r
     super\r
     if @registry.has_key?(:feeds)\r
@@ -168,6 +289,7 @@ class RSSFeedsPlugin < Plugin
       }\r
 \r
       @feeds = @registry[:feeds]\r
+      raise unless @feeds\r
 \r
       @registry.recovery = nil\r
 \r
@@ -197,6 +319,7 @@ class RSSFeedsPlugin < Plugin
 \r
   def cleanup\r
     stop_watches\r
+    super\r
   end\r
 \r
   def save\r
@@ -215,7 +338,7 @@ class RSSFeedsPlugin < Plugin
         debug "Stopping watch #{handle}"\r
         @bot.timer.remove(@watch[handle])\r
         @watch.delete(handle)\r
-      rescue => e\r
+      rescue Exception => e\r
         report_problem("Failed to stop watch for #{handle}", e, nil)\r
       end\r
     end\r
@@ -292,7 +415,25 @@ class RSSFeedsPlugin < Plugin
 \r
     m.reply "lemme fetch it..."\r
     title = items = nil\r
-    fetched = fetchRss(feed, m)\r
+    we_were_watching = false\r
+\r
+    if @watch.key?(feed.handle)\r
+      # If a feed is being watched, we run the watcher thread\r
+      # so that all watchers can be informed of changes to\r
+      # the feed. Before we do that, though, we remove the\r
+      # show requester from the watchlist, if present, lest\r
+      # he gets the update twice.\r
+      if feed.watched_by?(m.replyto)\r
+        we_were_watching = true\r
+        feed.rm_watch(m.replyto)\r
+      end\r
+      @bot.timer.reschedule(@watch[feed.handle], 0)\r
+      if we_were_watching\r
+        feed.add_watch(m.replyto)\r
+      end\r
+    else\r
+      fetched = fetchRss(feed, m, false)\r
+    end\r
     return unless fetched or feed.xml\r
     if not fetched and feed.items\r
       m.reply "using old data"\r
@@ -342,7 +483,7 @@ class RSSFeedsPlugin < Plugin
       reply = "no feeds found"\r
       reply << " matching #{wanted}" if wanted\r
     end\r
-    m.reply reply\r
+    m.reply reply, :max_lines => reply.length\r
   end\r
 \r
   def watched_rss(m, params)\r
@@ -453,6 +594,7 @@ class RSSFeedsPlugin < Plugin
 \r
   def del_rss(m, params, pass=false)\r
     feed = unwatch_rss(m, params, true)\r
+    return unless feed\r
     if feed.watched?\r
       m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"\r
       return\r
@@ -536,16 +678,21 @@ class RSSFeedsPlugin < Plugin
     end\r
     status = Hash.new\r
     status[:failures] = 0\r
+    status[:first_run] = true\r
     @watch[feed.handle] = @bot.timer.add(0, status) {\r
       debug "watcher for #{feed} started"\r
       failures = status[:failures]\r
+      first_run = status.delete(:first_run)\r
       begin\r
         debug "fetching #{feed}"\r
         oldxml = feed.xml ? feed.xml.dup : nil\r
         unless fetchRss(feed)\r
           failures += 1\r
         else\r
-          if oldxml and oldxml == feed.xml\r
+          if first_run\r
+            debug "first run for #{feed}, getting items"\r
+            parseRss(feed)\r
+          elsif oldxml and oldxml == feed.xml\r
             debug "xml for #{feed} didn't change"\r
             failures -= 1 if failures > 0\r
           else\r
@@ -554,16 +701,45 @@ class RSSFeedsPlugin < Plugin
               parseRss(feed)\r
               failures -= 1 if failures > 0\r
             else\r
-              otxt = feed.items.map { |item| item.to_s }\r
+              # This one is used for debugging\r
+              otxt = []\r
+\r
+              # These are used for checking new items vs old ones\r
+              uid_opts = { :show_updated => @bot.config['rss.show_updated'] }\r
+              oids = Set.new feed.items.map { |item|\r
+                uid = RSS.item_uid_for_bot(item, uid_opts)\r
+                otxt << item.to_s\r
+                debug [uid, item].inspect\r
+                debug [uid, otxt.last].inspect\r
+                uid\r
+              }\r
+\r
               unless parseRss(feed)\r
                 debug "no items in feed #{feed}"\r
                 failures += 1\r
               else\r
                 debug "Checking if new items are available for #{feed}"\r
                 failures -= 1 if failures > 0\r
+                # debug "Old:"\r
+                # debug oldxml\r
+                # debug "New:"\r
+                # debug feed.xml\r
+\r
                 dispItems = feed.items.reject { |item|\r
-                  otxt.include?(item.to_s)\r
+                  uid = RSS.item_uid_for_bot(item, uid_opts)\r
+                  txt = item.to_s\r
+                  if oids.include?(uid)\r
+                    debug "rejecting old #{uid} #{item.inspect}"\r
+                    debug [uid, txt].inspect\r
+                    true\r
+                  else\r
+                    debug "accepting new #{uid} #{item.inspect}"\r
+                    debug [uid, txt].inspect\r
+                    warning "same text! #{txt}" if otxt.include?(txt)\r
+                    false\r
+                  end\r
                 }\r
+\r
                 if dispItems.length > 0\r
                   debug "Found #{dispItems.length} new items in #{feed}"\r
                   # When displaying watched feeds, publish them from older to newer\r
@@ -605,13 +781,13 @@ class RSSFeedsPlugin < Plugin
       if opts.key?(:date) && opts[:date]\r
         if item.respond_to?(:pubDate) \r
           if item.pubDate.class <= Time\r
-            date = item.pubDate.strftime("%Y/%m/%d %H.%M.%S")\r
+            date = item.pubDate.strftime("%Y/%m/%d %H:%M")\r
           else\r
             date = item.pubDate.to_s\r
           end\r
         elsif  item.respond_to?(:date)\r
           if item.date.class <= Time\r
-            date = item.date.strftime("%Y/%m/%d %H.%M.%S")\r
+            date = item.date.strftime("%Y/%m/%d %H:%M")\r
           else\r
             date = item.date.to_s\r
           end\r
@@ -621,28 +797,47 @@ class RSSFeedsPlugin < Plugin
         date += " :: "\r
       end\r
     end\r
-    title = "#{Bold}#{item.title.chomp.riphtml}#{Bold}" if item.title\r
-    desc = item.description.gsub(/\s+/,' ').strip.riphtml if item.description\r
+\r
+    title = "#{Bold}#{item.title.ircify_html :limit => @bot.config['rss.head_max']}#{Bold}" if item.title\r
+\r
+    desc = item.description.ircify_html(:limit => @bot.config['rss.text_max'], :a_href => :link_out) if item.description\r
+\r
     link = item.link.chomp if item.link\r
+\r
+    debug item.inspect\r
+    category = item.dc_subject rescue item.category.content rescue nil\r
+    category = nil if category and category.empty?\r
+    author = item.dc_creator rescue item.author rescue nil\r
+    author = nil if author and author.empty?\r
+\r
     line1 = nil\r
     line2 = nil\r
+\r
+    at = ((item.title && item.link) ? ' @ ' : '')\r
     case feed.type\r
     when 'blog'\r
-      line1 = "#{handle}#{date}#{item.category.content} blogged at #{link}"\r
+      author << " " if author\r
+      abt = category ? "about #{category} " : ""\r
+      line1 = "#{handle}#{date}#{author}blogged #{abt}at #{link}"\r
       line2 = "#{handle}#{title} - #{desc}"\r
     when 'forum'\r
-      line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"\r
+      line1 = "#{handle}#{date}#{title}#{at}#{link}"\r
     when 'wiki'\r
-      line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link} has been edited by #{item.dc_creator}. #{desc}"\r
+      line1 = "#{handle}#{date}#{title}#{at}#{link} has been edited by #{author}. #{desc}"\r
     when 'gmane'\r
-      line1 = "#{handle}#{date}Message #{title} sent by #{item.dc_creator}. #{desc}"\r
+      line1 = "#{handle}#{date}Message #{title} sent by #{author}. #{desc}"\r
     when 'trac'\r
       line1 = "#{handle}#{date}#{title} @ #{link}"\r
       unless item.title =~ /^Changeset \[(\d+)\]/\r
         line2 = "#{handle}#{date}#{desc}"\r
       end\r
+    when '/.'\r
+      dept = "(from the #{item.slash_department} dept) " rescue nil\r
+      sec = " in section #{item.slash_section}" rescue nil\r
+\r
+      line1 = "#{handle}#{date}#{dept}#{title}#{at}#{link} (posted by #{author}#{sec})"\r
     else\r
-      line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"\r
+      line1 = "#{handle}#{date}#{title}#{at}#{link}"\r
     end\r
     places.each { |loc|\r
       @bot.say loc, line1, :overlong => :truncate\r
@@ -651,12 +846,13 @@ class RSSFeedsPlugin < Plugin
     }\r
   end\r
 \r
-  def fetchRss(feed, m=nil)\r
+  def fetchRss(feed, m=nil, cache=true)\r
     begin\r
       # Use 60 sec timeout, cause the default is too low\r
       xml = @bot.httputil.get(feed.url,\r
                               :read_timeout => 60,\r
-                              :open_timeout => 60)\r
+                              :open_timeout => 60,\r
+                              :cache => cache)\r
     rescue URI::InvalidURIError, URI::BadURIError => e\r
       report_problem("invalid rss feed #{feed.url}", e, m)\r
       return nil\r
@@ -769,6 +965,9 @@ plugin.map 'rss replace :handle :url :type',
 plugin.map 'rss forcereplace :handle :url :type',\r
   :action => 'forcereplace_rss',\r
   :defaults => {:type => nil}\r
+plugin.map 'rss watch :handle [in :chan]',\r
+  :action => 'watch_rss',\r
+  :defaults => {:url => nil, :type => nil}\r
 plugin.map 'rss watch :handle :url :type [in :chan]',\r
   :action => 'watch_rss',\r
   :defaults => {:url => nil, :type => nil}\r