X-Git-Url: https://git.netwichtig.de/gitweb/?a=blobdiff_plain;f=data%2Frbot%2Fplugins%2Frss.rb;h=22aa742ff6bc3c08f98a1020123f9c8e19ace2f2;hb=8fdc4283433cf3e8969e728dbd3f17b3da63d65a;hp=caebc3fc6795465671dd3cbd62c547cbbab2f181;hpb=edd1cf77be07ae507014574141e920ad23eb164d;p=user%2Fhenk%2Fcode%2Fruby%2Frbot.git diff --git a/data/rbot/plugins/rss.rb b/data/rbot/plugins/rss.rb index caebc3fc..22aa742f 100644 --- a/data/rbot/plugins/rss.rb +++ b/data/rbot/plugins/rss.rb @@ -14,15 +14,147 @@ # # License:: MIT license -require 'rss/parser' -require 'rss/1.0' -require 'rss/2.0' -require 'rss/dublincore' -# begin -# require 'rss/dublincore/2.0' -# rescue -# warning "Unable to load RSS libraries, RSS plugin functionality crippled" -# end +require 'rss' + +module ::RSS + + # Make an 'unique' ID for a given item, based on appropriate bot options + # Currently only suppored is bot.config['rss.show_updated']: when true, the + # description is included in the uid hashing, otherwise it's not + # + def RSS.item_uid_for_bot(item, opts={}) + options = { :show_updated => true}.merge(opts) + desc = options[:show_updated] ? item.description : nil + [item.title, item.link, desc].hash + end + + # Add support for Slashdot namespace in RDF. The code is just an adaptation + # of the DublinCore code. + unless defined?(SLASH_PREFIX) + SLASH_PREFIX = 'slash' + SLASH_URI = "http://purl.org/rss/1.0/modules/slash/" + + RDF.install_ns(SLASH_PREFIX, SLASH_URI) + + module BaseSlashModel + def append_features(klass) + super + + return if klass.instance_of?(Module) + SlashModel::ELEMENT_NAME_INFOS.each do |name, plural_name| + plural = plural_name || "#{name}s" + full_name = "#{SLASH_PREFIX}_#{name}" + full_plural_name = "#{SLASH_PREFIX}_#{plural}" + klass_name = "Slash#{Utils.to_class_name(name)}" + + # This will fail with older version of the Ruby RSS module + begin + klass.install_have_children_element(name, SLASH_URI, "*", + full_name, full_plural_name) + klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI) + rescue ArgumentError + klass.module_eval("install_have_children_element(#{full_name.dump}, #{full_plural_name.dump})") + end + + klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0)) + remove_method :#{full_name} if method_defined? :#{full_name} + remove_method :#{full_name}= if method_defined? :#{full_name}= + remove_method :set_#{full_name} if method_defined? :set_#{full_name} + + def #{full_name} + @#{full_name}.first and @#{full_name}.first.value + end + + def #{full_name}=(new_value) + @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value) + end + alias set_#{full_name} #{full_name}= + EOC + end + end + end + + module SlashModel + extend BaseModel + extend BaseSlashModel + + TEXT_ELEMENTS = { + "department" => nil, + "section" => nil, + "comments" => nil, + "hit_parade" => nil + } + + ELEMENT_NAME_INFOS = SlashModel::TEXT_ELEMENTS.to_a + + ELEMENTS = TEXT_ELEMENTS.keys + + ELEMENTS.each do |name, plural_name| + module_eval(<<-EOC, *get_file_and_line_from_caller(0)) + class Slash#{Utils.to_class_name(name)} < Element + include RSS10 + + content_setup + + class << self + def required_prefix + SLASH_PREFIX + end + + def required_uri + SLASH_URI + end + end + + @tag_name = #{name.dump} + + alias_method(:value, :content) + alias_method(:value=, :content=) + + def initialize(*args) + begin + if Utils.element_initialize_arguments?(args) + super + else + super() + self.content = args[0] + end + # Older Ruby RSS module + rescue NoMethodError + super() + self.content = args[0] + end + end + + def full_name + tag_name_with_prefix(SLASH_PREFIX) + end + + def maker_target(target) + target.new_#{name} + end + + def setup_maker_attributes(#{name}) + #{name}.content = content + end + end + EOC + end + end + + class RDF + class Item; include SlashModel; end + end + + SlashModel::ELEMENTS.each do |name| + class_name = Utils.to_class_name(name) + BaseListener.install_class_name(SLASH_URI, name, "Slash#{class_name}") + end + + SlashModel::ELEMENTS.collect! {|name| "#{SLASH_PREFIX}_#{name}"} + end +end + class ::RssBlob attr_accessor :url @@ -53,11 +185,13 @@ class ::RssBlob end def dup - self.class.new(@url, - @handle, - @type ? @type.dup : nil, - @watchers.dup, - @xml ? @xml.dup : nil) + @mutex.synchronize do + self.class.new(@url, + @handle, + @type ? @type.dup : nil, + @watchers.dup, + @xml ? @xml.dup : nil) + end end # Downcase all watchers, possibly turning them into Strings if they weren't @@ -81,12 +215,16 @@ class ::RssBlob if watched_by?(who) return nil end - @watchers << who.downcase + @mutex.synchronize do + @watchers << who.downcase + end return who end def rm_watch(who) - @watchers.delete(who.downcase) + @mutex.synchronize do + @watchers.delete(who.downcase) + end end def to_a @@ -104,28 +242,76 @@ class ::RssBlob end class RSSFeedsPlugin < Plugin - BotConfig.register BotConfigIntegerValue.new('rss.head_max', - :default => 30, :validate => Proc.new{|v| v > 0 && v < 200}, + Config.register Config::IntegerValue.new('rss.head_max', + :default => 100, :validate => Proc.new{|v| v > 0 && v < 200}, :desc => "How many characters to use of a RSS item header") - BotConfig.register BotConfigIntegerValue.new('rss.text_max', - :default => 90, :validate => Proc.new{|v| v > 0 && v < 400}, + Config.register Config::IntegerValue.new('rss.text_max', + :default => 200, :validate => Proc.new{|v| v > 0 && v < 400}, :desc => "How many characters to use of a RSS item text") - BotConfig.register BotConfigIntegerValue.new('rss.thread_sleep', + Config.register Config::IntegerValue.new('rss.thread_sleep', :default => 300, :validate => Proc.new{|v| v > 30}, :desc => "How many seconds to sleep before checking RSS feeds again") + Config.register Config::BooleanValue.new('rss.show_updated', + :default => true, + :desc => "Whether feed items for which the description was changed should be shown as new") + + # We used to save the Mutex with the RssBlob, which was idiotic. And + # since Mutexes dumped in one version might not be resotrable in another, + # we need a few tricks to be able to restore data from other versions of Ruby + # + # When migrating 1.8.6 => 1.8.5, all we need to do is define an empty + # #marshal_load() method for Mutex. For 1.8.5 => 1.8.6 we need something + # dirtier, as seen later on in the initialization code. + unless Mutex.new.respond_to?(:marshal_load) + class ::Mutex + def marshal_load(str) + return + end + end + end + + attr_reader :feeds + def initialize super if @registry.has_key?(:feeds) + # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the + # data unrestorable. If this happens, we patch the data, thus allowing + # the restore to work. + # + # This is actually pretty safe for a number of reasons: + # * the code is only called if standard marshalling fails + # * the string we look for is quite unlikely to appear randomly + # * if the string appears somewhere and the patched string isn't recoverable + # either, we'll get another (unrecoverable) error, which makes the rss + # plugin unsable, just like it was if no recovery was attempted + # * if the string appears somewhere and the patched string is recoverable, + # we may get a b0rked feed, which is eventually overwritten by a clean + # one, so the worst thing that can happen is that a feed update spams + # the watchers once + @registry.recovery = Proc.new { |val| + patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject") + ret = Marshal.restore(patched) + ret.each_value { |blob| + blob.mutex = nil + blob + } + } + @feeds = @registry[:feeds] + raise unless @feeds + + @registry.recovery = nil + @feeds.keys.grep(/[A-Z]/) { |k| @feeds[k.downcase] = @feeds[k] @feeds.delete(k) } @feeds.each { |k, f| - f.mutex = Mutex.new unless f.mutex + f.mutex = Mutex.new f.sanitize_watchers parseRss(f) if f.xml } @@ -146,14 +332,15 @@ class RSSFeedsPlugin < Plugin def cleanup stop_watches + super end def save unparsed = Hash.new() @feeds.each { |k, f| - f.mutex.synchronize do - unparsed[k] = f.dup - end + unparsed[k] = f.dup + # we don't want to save the mutex + unparsed[k].mutex = nil } @registry[:feeds] = unparsed end @@ -164,7 +351,7 @@ class RSSFeedsPlugin < Plugin debug "Stopping watch #{handle}" @bot.timer.remove(@watch[handle]) @watch.delete(handle) - rescue => e + rescue Exception => e report_problem("Failed to stop watch for #{handle}", e, nil) end end @@ -241,7 +428,25 @@ class RSSFeedsPlugin < Plugin m.reply "lemme fetch it..." title = items = nil - fetched = fetchRss(feed, m) + we_were_watching = false + + if @watch.key?(feed.handle) + # If a feed is being watched, we run the watcher thread + # so that all watchers can be informed of changes to + # the feed. Before we do that, though, we remove the + # show requester from the watchlist, if present, lest + # he gets the update twice. + if feed.watched_by?(m.replyto) + we_were_watching = true + feed.rm_watch(m.replyto) + end + @bot.timer.reschedule(@watch[feed.handle], 0) + if we_were_watching + feed.add_watch(m.replyto) + end + else + fetched = fetchRss(feed, m, false) + end return unless fetched or feed.xml if not fetched and feed.items m.reply "using old data" @@ -291,7 +496,7 @@ class RSSFeedsPlugin < Plugin reply = "no feeds found" reply << " matching #{wanted}" if wanted end - m.reply reply + m.reply reply, :max_lines => reply.length end def watched_rss(m, params) @@ -402,6 +607,7 @@ class RSSFeedsPlugin < Plugin def del_rss(m, params, pass=false) feed = unwatch_rss(m, params, true) + return unless feed if feed.watched? m.reply "someone else is watching #{feed.handle}, I won't remove it from my list" return @@ -485,16 +691,21 @@ class RSSFeedsPlugin < Plugin end status = Hash.new status[:failures] = 0 - @watch[feed.handle] = @bot.timer.add(0, status) { + status[:first_run] = true + @watch[feed.handle] = @bot.timer.add(0) { debug "watcher for #{feed} started" failures = status[:failures] + first_run = status.delete(:first_run) begin debug "fetching #{feed}" oldxml = feed.xml ? feed.xml.dup : nil unless fetchRss(feed) failures += 1 else - if oldxml and oldxml == feed.xml + if first_run + debug "first run for #{feed}, getting items" + parseRss(feed) + elsif oldxml and oldxml == feed.xml debug "xml for #{feed} didn't change" failures -= 1 if failures > 0 else @@ -503,16 +714,45 @@ class RSSFeedsPlugin < Plugin parseRss(feed) failures -= 1 if failures > 0 else - otxt = feed.items.map { |item| item.to_s } + # This one is used for debugging + otxt = [] + + # These are used for checking new items vs old ones + uid_opts = { :show_updated => @bot.config['rss.show_updated'] } + oids = Set.new feed.items.map { |item| + uid = RSS.item_uid_for_bot(item, uid_opts) + otxt << item.to_s + debug [uid, item].inspect + debug [uid, otxt.last].inspect + uid + } + unless parseRss(feed) debug "no items in feed #{feed}" failures += 1 else debug "Checking if new items are available for #{feed}" failures -= 1 if failures > 0 + # debug "Old:" + # debug oldxml + # debug "New:" + # debug feed.xml + dispItems = feed.items.reject { |item| - otxt.include?(item.to_s) + uid = RSS.item_uid_for_bot(item, uid_opts) + txt = item.to_s + if oids.include?(uid) + debug "rejecting old #{uid} #{item.inspect}" + debug [uid, txt].inspect + true + else + debug "accepting new #{uid} #{item.inspect}" + debug [uid, txt].inspect + warning "same text! #{txt}" if otxt.include?(txt) + false + end } + if dispItems.length > 0 debug "Found #{dispItems.length} new items in #{feed}" # When displaying watched feeds, publish them from older to newer @@ -534,12 +774,16 @@ class RSSFeedsPlugin < Plugin status[:failures] = failures + timer = nil + seconds = @bot.config['rss.thread_sleep'] feed.mutex.synchronize do - seconds = (feed.refresh_rate || @bot.config['rss.thread_sleep']) * (failures + 1) - seconds += seconds * (rand(100)-50)/100 - debug "watcher for #{feed} going to sleep #{seconds} seconds.." - @bot.timer.reschedule(@watch[feed.handle], seconds) + timer = @watch[feed.handle] + seconds = feed.refresh_rate if feed.refresh_rate end + seconds *= failures + 1 + seconds += seconds * (rand(100)-50)/100 + debug "watcher for #{feed} going to sleep #{seconds} seconds.." + @bot.timer.reschedule(timer, seconds) rescue warning "watcher for #{feed} failed to reschedule: #{$!.inspect}" } debug "watcher for #{feed} added" end @@ -554,13 +798,13 @@ class RSSFeedsPlugin < Plugin if opts.key?(:date) && opts[:date] if item.respond_to?(:pubDate) if item.pubDate.class <= Time - date = item.pubDate.strftime("%Y/%m/%d %H.%M.%S") + date = item.pubDate.strftime("%Y/%m/%d %H:%M") else date = item.pubDate.to_s end elsif item.respond_to?(:date) if item.date.class <= Time - date = item.date.strftime("%Y/%m/%d %H.%M.%S") + date = item.date.strftime("%Y/%m/%d %H:%M") else date = item.date.to_s end @@ -570,28 +814,56 @@ class RSSFeedsPlugin < Plugin date += " :: " end end - title = "#{Bold}#{item.title.chomp.riphtml}#{Bold}" if item.title - desc = item.description.gsub(/\s+/,' ').strip.riphtml if item.description + + tit_opt = {} + # Twitters don't need a cap on the title length since they have a hard + # limit to 160 characters, and most of them are under 140 characters + tit_opt[:limit] = @bot.config['rss.head_max'] unless feed.type == 'twitter' + + title = "#{Bold}#{item.title.ircify_html(tit_opt)}#{Bold}" if item.title + + desc_opt = { + :limit => @bot.config['rss.text_max'], + :a_href => :link_out + } + desc = item.description.ircify_html(desc_opt) if item.description + link = item.link.chomp if item.link + + debug item.inspect + category = item.dc_subject rescue item.category.content rescue nil + category = nil if category and category.empty? + author = item.dc_creator rescue item.author rescue nil + author = nil if author and author.empty? + line1 = nil line2 = nil + + at = ((item.title && item.link) ? ' @ ' : '') case feed.type when 'blog' - line1 = "#{handle}#{date}#{item.category.content} blogged at #{link}" + author << " " if author + abt = category ? "about #{category} " : "" + line1 = "#{handle}#{date}#{author}blogged #{abt}at #{link}" line2 = "#{handle}#{title} - #{desc}" when 'forum' - line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}" + line1 = "#{handle}#{date}#{title}#{at}#{link}" when 'wiki' - line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link} has been edited by #{item.dc_creator}. #{desc}" + line1 = "#{handle}#{date}#{title}#{at}#{link} has been edited by #{author}. #{desc}" when 'gmane' - line1 = "#{handle}#{date}Message #{title} sent by #{item.dc_creator}. #{desc}" + line1 = "#{handle}#{date}Message #{title} sent by #{author}. #{desc}" when 'trac' line1 = "#{handle}#{date}#{title} @ #{link}" unless item.title =~ /^Changeset \[(\d+)\]/ line2 = "#{handle}#{date}#{desc}" end + when '/.' + dept = "(from the #{item.slash_department} dept) " rescue nil + sec = " in section #{item.slash_section}" rescue nil + + line1 = "#{handle}#{date}#{dept}#{title}#{at}#{link} (posted by #{author}#{sec})" else - line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}" + line1 = "#{handle}#{date}#{title}#{at}#{link}" end places.each { |loc| @bot.say loc, line1, :overlong => :truncate @@ -600,10 +872,13 @@ class RSSFeedsPlugin < Plugin } end - def fetchRss(feed, m=nil) + def fetchRss(feed, m=nil, cache=true) begin # Use 60 sec timeout, cause the default is too low - xml = @bot.httputil.get_cached(feed.url, 60, 60) + xml = @bot.httputil.get(feed.url, + :read_timeout => 60, + :open_timeout => 60, + :cache => cache) rescue URI::InvalidURIError, URI::BadURIError => e report_problem("invalid rss feed #{feed.url}", e, m) return nil @@ -616,6 +891,11 @@ class RSSFeedsPlugin < Plugin report_problem("reading feed #{feed} failed", nil, m) return nil end + # Ok, 0.9 feeds are not supported, maybe because + # Netscape happily removed the DTD. So what we do is just to + # reassign the 0.9 RDFs to 1.0, and hope it goes right. + xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"", + "xmlns=\"http://purl.org/rss/1.0/\"") feed.mutex.synchronize do feed.xml = xml end @@ -629,11 +909,12 @@ class RSSFeedsPlugin < Plugin begin ## do validate parse rss = RSS::Parser.parse(xml) - debug "parsed #{feed}" + debug "parsed and validated #{feed}" rescue RSS::InvalidRSSError ## do non validate parse for invalid RSS 1.0 begin rss = RSS::Parser.parse(xml, false) + debug "parsed but not validated #{feed}" rescue RSS::Error => e report_problem("parsing rss stream failed, whoops =(", e, m) return nil @@ -710,6 +991,9 @@ plugin.map 'rss replace :handle :url :type', plugin.map 'rss forcereplace :handle :url :type', :action => 'forcereplace_rss', :defaults => {:type => nil} +plugin.map 'rss watch :handle [in :chan]', + :action => 'watch_rss', + :defaults => {:url => nil, :type => nil} plugin.map 'rss watch :handle :url :type [in :chan]', :action => 'watch_rss', :defaults => {:url => nil, :type => nil}