]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blobdiff - data/rbot/plugins/rss.rb
reaction plugin: fix reaction removal when no index was specified
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / rss.rb
index 885ac84d44792c634f2fc2cc0c6c47abfb20d6cd..22aa742ff6bc3c08f98a1020123f9c8e19ace2f2 100644 (file)
@@ -16,8 +16,6 @@
 \r
 require 'rss'\r
 \r
-# Add support for Slashdot namespace in RDF. The code is just an adaptation of\r
-# the DublinCore code.\r
 module ::RSS\r
 \r
   # Make an  'unique' ID for a given item, based on appropriate bot options\r
@@ -30,6 +28,8 @@ module ::RSS
     [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
@@ -46,13 +46,20 @@ module ::RSS
           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
+\r
+          # This will fail with older version of the Ruby RSS module\r
+          begin\r
+            klass.install_have_children_element(name, SLASH_URI, "*",\r
+                                                full_name, full_plural_name)\r
+            klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI)\r
+          rescue ArgumentError\r
+            klass.module_eval("install_have_children_element(#{full_name.dump}, #{full_plural_name.dump})")\r
+          end\r
+\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
+          remove_method :#{full_name}     if method_defined? :#{full_name}\r
+          remove_method :#{full_name}=    if method_defined? :#{full_name}=\r
+          remove_method :set_#{full_name} if method_defined? :set_#{full_name}\r
 \r
           def #{full_name}\r
             @#{full_name}.first and @#{full_name}.first.value\r
@@ -105,9 +112,15 @@ module ::RSS
           alias_method(:value=, :content=)\r
 \r
           def initialize(*args)\r
-            if Utils.element_initialize_arguments?(args)\r
-              super\r
-            else\r
+            begin\r
+              if Utils.element_initialize_arguments?(args)\r
+                super\r
+              else\r
+                super()\r
+                self.content = args[0]\r
+              end\r
+            # Older Ruby RSS module\r
+            rescue NoMethodError\r
               super()\r
               self.content = args[0]\r
             end\r
@@ -229,19 +242,19 @@ class ::RssBlob
 end\r
 \r
 class RSSFeedsPlugin < Plugin\r
-  BotConfig.register BotConfigIntegerValue.new('rss.head_max',\r
-    :default => 30, :validate => Proc.new{|v| v > 0 && v < 200},\r
+  Config.register Config::IntegerValue.new('rss.head_max',\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
+  Config.register Config::IntegerValue.new('rss.text_max',\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
+  Config.register Config::IntegerValue.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
+  Config.register Config::BooleanValue.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
@@ -270,15 +283,15 @@ class RSSFeedsPlugin < Plugin
       # the restore to work.\r
       #\r
       # This is actually pretty safe for a number of reasons:\r
-      #  * the code is only called if standard marshalling fails\r
-      #  * the string we look for is quite unlikely to appear randomly\r
-      #  * if the string appears somewhere and the patched string isn't recoverable\r
-      #    either, we'll get another (unrecoverable) error, which makes the rss\r
-      #    plugin unsable, just like it was if no recovery was attempted\r
-      #  * if the string appears somewhere and the patched string is recoverable,\r
-      #    we may get a b0rked feed, which is eventually overwritten by a clean\r
-      #    one, so the worst thing that can happen is that a feed update spams\r
-      #    the watchers once\r
+      # * the code is only called if standard marshalling fails\r
+      # * the string we look for is quite unlikely to appear randomly\r
+      # * if the string appears somewhere and the patched string isn't recoverable\r
+      #   either, we'll get another (unrecoverable) error, which makes the rss\r
+      #   plugin unsable, just like it was if no recovery was attempted\r
+      # * if the string appears somewhere and the patched string is recoverable,\r
+      #   we may get a b0rked feed, which is eventually overwritten by a clean\r
+      #   one, so the worst thing that can happen is that a feed update spams\r
+      #   the watchers once\r
       @registry.recovery = Proc.new { |val|\r
         patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")\r
         ret = Marshal.restore(patched)\r
@@ -289,6 +302,7 @@ class RSSFeedsPlugin < Plugin
       }\r
 \r
       @feeds = @registry[:feeds]\r
+      raise unless @feeds\r
 \r
       @registry.recovery = nil\r
 \r
@@ -297,7 +311,7 @@ class RSSFeedsPlugin < Plugin
         @feeds.delete(k)\r
       }\r
       @feeds.each { |k, f|\r
-        f.mutex = Mutex.new unless f.mutex\r
+        f.mutex = Mutex.new\r
         f.sanitize_watchers\r
         parseRss(f) if f.xml\r
       }\r
@@ -318,6 +332,7 @@ class RSSFeedsPlugin < Plugin
 \r
   def cleanup\r
     stop_watches\r
+    super\r
   end\r
 \r
   def save\r
@@ -336,7 +351,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
@@ -413,7 +428,25 @@ class RSSFeedsPlugin < Plugin
 \r
     m.reply "lemme fetch it..."\r
     title = items = nil\r
-    fetched = fetchRss(feed, m, false)\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
@@ -574,6 +607,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
@@ -658,7 +692,7 @@ class RSSFeedsPlugin < Plugin
     status = Hash.new\r
     status[:failures] = 0\r
     status[:first_run] = true\r
-    @watch[feed.handle] = @bot.timer.add(0, status) {\r
+    @watch[feed.handle] = @bot.timer.add(0) {\r
       debug "watcher for #{feed} started"\r
       failures = status[:failures]\r
       first_run = status.delete(:first_run)\r
@@ -668,7 +702,10 @@ class RSSFeedsPlugin < Plugin
         unless fetchRss(feed)\r
           failures += 1\r
         else\r
-          if first_run or (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
@@ -685,6 +722,7 @@ class RSSFeedsPlugin < Plugin
               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
@@ -695,6 +733,10 @@ class RSSFeedsPlugin < Plugin
               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
                   uid = RSS.item_uid_for_bot(item, uid_opts)\r
@@ -706,7 +748,7 @@ class RSSFeedsPlugin < Plugin
                   else\r
                     debug "accepting new #{uid} #{item.inspect}"\r
                     debug [uid, txt].inspect\r
-                    warn "same text! #{txt}" if otxt.include?(txt)\r
+                    warning "same text! #{txt}" if otxt.include?(txt)\r
                     false\r
                   end\r
                 }\r
@@ -732,12 +774,16 @@ class RSSFeedsPlugin < Plugin
 \r
       status[:failures] = failures\r
 \r
+      timer = nil\r
+      seconds = @bot.config['rss.thread_sleep']\r
       feed.mutex.synchronize do\r
-        seconds = (feed.refresh_rate || @bot.config['rss.thread_sleep']) * (failures + 1)\r
-        seconds += seconds * (rand(100)-50)/100\r
-        debug "watcher for #{feed} going to sleep #{seconds} seconds.."\r
-        @bot.timer.reschedule(@watch[feed.handle], seconds)\r
+        timer = @watch[feed.handle]\r
+        seconds = feed.refresh_rate if feed.refresh_rate\r
       end\r
+      seconds *= failures + 1\r
+      seconds += seconds * (rand(100)-50)/100\r
+      debug "watcher for #{feed} going to sleep #{seconds} seconds.."\r
+      @bot.timer.reschedule(timer, seconds) rescue warning "watcher for #{feed} failed to reschedule: #{$!.inspect}"\r
     }\r
     debug "watcher for #{feed} added"\r
   end\r
@@ -752,13 +798,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
@@ -769,15 +815,26 @@ class RSSFeedsPlugin < Plugin
       end\r
     end\r
 \r
-    title = "#{Bold}#{item.title.ircify_html}#{Bold}" if item.title\r
+    tit_opt = {}\r
+    # Twitters don't need a cap on the title length since they have a hard\r
+    # limit to 160 characters, and most of them are under 140 characters\r
+    tit_opt[:limit] = @bot.config['rss.head_max'] unless feed.type == 'twitter'\r
 \r
-    desc = item.description.ircify_html(:a_href => :link_out) if item.description\r
+    title = "#{Bold}#{item.title.ircify_html(tit_opt)}#{Bold}" if item.title\r
+\r
+    desc_opt = {\r
+      :limit => @bot.config['rss.text_max'],\r
+      :a_href => :link_out\r
+    }\r
+    desc = item.description.ircify_html(desc_opt) 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 rescue nil\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
@@ -785,8 +842,9 @@ class RSSFeedsPlugin < Plugin
     at = ((item.title && item.link) ? ' @ ' : '')\r
     case feed.type\r
     when 'blog'\r
+      author << " " if author\r
       abt = category ? "about #{category} " : ""\r
-      line1 = "#{handle}#{date}#{author} blogged #{abt}at #{link}"\r
+      line1 = "#{handle}#{date}#{author}blogged #{abt}at #{link}"\r
       line2 = "#{handle}#{title} - #{desc}"\r
     when 'forum'\r
       line1 = "#{handle}#{date}#{title}#{at}#{link}"\r
@@ -933,6 +991,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