X-Git-Url: https://git.netwichtig.de/gitweb/?a=blobdiff_plain;f=data%2Frbot%2Fplugins%2Frss.rb;h=f8d8c99795647db4672edbd791ee2675c012eb15;hb=24bb60775741d3731400f1e430ef6bf3a2e1b933;hp=5cd1ada3714a272766545acae007e40fbd751567;hpb=c6287fc15a15ec53602ca6c0d068523e4e0d8e98;p=user%2Fhenk%2Fcode%2Fruby%2Frbot.git diff --git a/data/rbot/plugins/rss.rb b/data/rbot/plugins/rss.rb index 5cd1ada3..f8d8c997 100644 --- a/data/rbot/plugins/rss.rb +++ b/data/rbot/plugins/rss.rb @@ -16,10 +16,25 @@ require 'rss' -# Add support for Slashdot namespace in RDF. The code is just an adaptation of -# the DublinCore code. 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 = nil + if options[:show_updated] + desc = item.content.content rescue item.description rescue nil + end + [(item.title.content rescue item.title rescue nil), + (item.link.href rescue 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/" @@ -36,13 +51,20 @@ module ::RSS full_name = "#{SLASH_PREFIX}_#{name}" full_plural_name = "#{SLASH_PREFIX}_#{plural}" klass_name = "Slash#{Utils.to_class_name(name)}" - klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI) - klass.install_have_children_element(name, SLASH_URI, "*", - full_name, full_plural_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} - remove_method :#{full_name}= - remove_method :set_#{full_name} + 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 @@ -95,9 +117,15 @@ module ::RSS alias_method(:value=, :content=) def initialize(*args) - if Utils.element_initialize_arguments?(args) - super - else + 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 @@ -134,17 +162,10 @@ end class ::RssBlob - attr_accessor :url - attr_accessor :handle - attr_accessor :type - attr :watchers - attr_accessor :refresh_rate - attr_accessor :xml - attr_accessor :title - attr_accessor :items - attr_accessor :mutex - - def initialize(url,handle=nil,type=nil,watchers=[], xml=nil) + attr_accessor :url, :handle, :type, :refresh_rate, :xml, :title, :items, + :mutex, :watchers, :last_fetched + + def initialize(url,handle=nil,type=nil,watchers=[], xml=nil, lf = nil) @url = url if handle @handle = handle @@ -158,6 +179,7 @@ class ::RssBlob @title = nil @items = nil @mutex = Mutex.new + @last_fetched = lf sanitize_watchers(watchers) end @@ -167,7 +189,8 @@ class ::RssBlob @handle, @type ? @type.dup : nil, @watchers.dup, - @xml ? @xml.dup : nil) + @xml ? @xml.dup : nil, + @last_fetched) end end @@ -219,18 +242,22 @@ 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 @@ -256,15 +283,15 @@ class RSSFeedsPlugin < Plugin # 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 + # * 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) @@ -275,6 +302,7 @@ class RSSFeedsPlugin < Plugin } @feeds = @registry[:feeds] + raise unless @feeds @registry.recovery = nil @@ -283,7 +311,7 @@ class RSSFeedsPlugin < Plugin @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 } @@ -304,6 +332,7 @@ class RSSFeedsPlugin < Plugin def cleanup stop_watches + super end def save @@ -322,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 @@ -358,10 +387,12 @@ class RSSFeedsPlugin < Plugin "rss watch #{Bold}handle#{Bold} [#{Bold}url#{Bold} [#{Bold}type#{Bold}]] [in #{Bold}chan#{Bold}]: watch rss #{Bold}handle#{Bold} for changes (in channel #{Bold}chan#{Bold}); when the other parameters are present, the feed will be created if it doesn't exist yet" when /(un|rm)watch/ "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes" + when /who(?: watche?s?)?/ + "rss who watches #{Bold}handle#{Bold}: lists watches for rss #{Bold}handle#{Bold}" when "rewatch" "rss rewatch : restart threads that watch for changes in watched rss" else - "manage RSS feeds: rss show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch" + "manage RSS feeds: rss show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch|who watches" end end @@ -399,7 +430,25 @@ class RSSFeedsPlugin < Plugin m.reply "lemme fetch it..." title = items = nil - fetched = fetchRss(feed, m, false) + 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" @@ -449,7 +498,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) @@ -560,6 +609,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 @@ -626,13 +676,23 @@ class RSSFeedsPlugin < Plugin end def rewatch_rss(m=nil, params=nil) - stop_watches + if params and handle = params[:handle] + feed = @feeds.fetch(handle.downcase, nil) + if feed + @bot.timer.reschedule(@watch[feed.handle], 0) + m.okay if m + else + m.reply _("no such feed %{handle}") % { :handle => handle } if m + end + else + stop_watches - # Read watches from list. - watchlist.each{ |handle, feed| - watchRss(feed, m) - } - m.okay if m + # Read watches from list. + watchlist.each{ |handle, feed| + watchRss(feed, m) + } + m.okay if m + end end private @@ -643,18 +703,26 @@ class RSSFeedsPlugin < Plugin end status = Hash.new status[:failures] = 0 - status[:first_run] = true - @watch[feed.handle] = @bot.timer.add(0, status) { - debug "watcher for #{feed} started" + tmout = 0 + if feed.last_fetched + tmout = feed.last_fetched + calculate_timeout(feed) - Time.now + tmout = 0 if tmout < 0 + end + debug "scheduling a watcher for #{feed} in #{tmout} seconds" + @watch[feed.handle] = @bot.timer.add(tmout) { + debug "watcher for #{feed} wakes up" failures = status[:failures] - first_run = status.delete(:first_run) begin debug "fetching #{feed}" + first_run = !feed.last_fetched oldxml = feed.xml ? feed.xml.dup : nil unless fetchRss(feed) failures += 1 else - if first_run or (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 @@ -663,16 +731,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 @@ -694,17 +791,35 @@ class RSSFeedsPlugin < Plugin status[:failures] = failures - 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.." + seconds = calculate_timeout(feed, failures) + debug "watcher for #{feed} going to sleep #{seconds} seconds.." + begin @bot.timer.reschedule(@watch[feed.handle], seconds) + rescue + warning "watcher for #{feed} failed to reschedule: #{$!.inspect}" end } debug "watcher for #{feed} added" end + def calculate_timeout(feed, failures = 0) + seconds = @bot.config['rss.thread_sleep'] + feed.mutex.synchronize do + seconds = feed.refresh_rate if feed.refresh_rate + end + seconds *= failures + 1 + seconds += seconds * (rand(100)-50)/100 + return seconds + end + + def select_nonempty(*ar) + debug ar + ret = ar.map { |i| (i && i.empty?) ? nil : i }.compact.first + (ret && ret.empty?) ? nil : ret + end + def printFormattedRss(feed, item, opts=nil) + debug item places = feed.watchers handle = "::#{feed.handle}:: " date = String.new @@ -712,15 +827,27 @@ class RSSFeedsPlugin < Plugin places = opts[:places] if opts.key?(:places) handle = opts[:handle].to_s if opts.key?(:handle) if opts.key?(:date) && opts[:date] - if item.respond_to?(:pubDate) + if item.respond_to?(:updated) + if item.updated.content.class <= Time + date = item.updated.content.strftime("%Y/%m/%d %H:%M") + else + date = item.updated.content.to_s + end + elsif item.respond_to?(:source) and item.source.respond_to?(:updated) + if item.source.updated.content.class <= Time + date = item.source.updated.content.strftime("%Y/%m/%d %H:%M") + else + date = item.source.updated.content.to_s + end + elsif 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) + 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 @@ -731,25 +858,57 @@ class RSSFeedsPlugin < Plugin end end - title = "#{Bold}#{item.title.ircify_html}#{Bold}" if item.title + 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' + + if item.title + base_title = item.title.to_s.dup + # git changesets are SHA1 hashes (40 hex digits), way too long, get rid of them, as they are + # visible in the URL anyway + # TODO make this optional? + base_title.sub!(/^Changeset \[([\da-f]{40})\]:/) { |c| "(git commit)"} if feed.type = 'trac' + title = "#{Bold}#{base_title.ircify_html(tit_opt)}#{Bold}" + end - desc = item.description.ircify_html if item.description + desc_opt = { + :limit => @bot.config['rss.text_max'], + :a_href => :link_out + } + + if item.respond_to? :description + desc = item.description.ircify_html(desc_opt) if item.description + else + if item.content.type == "html" + desc = item.content.content.ircify_html(desc_opt) + else + desc = item.content.content + if desc.size > desc_opt[:limit] + desc = desc.slice(0, desc_opt[:limit]) + "#{Reverse}...#{Reverse}" + end + end + end - link = item.link.chomp if item.link + link = item.link.href rescue item.link.chomp rescue nil - debug item.inspect - category = item.dc_subject rescue item.category rescue nil - author = item.dc_creator rescue item.author rescue nil + category = select_nonempty((item.category.content rescue nil), (idem.dc_subject rescue nil)) + author = select_nonempty((item.author.name.content rescue nil), (item.dc_creator rescue nil), (item.author rescue nil)) line1 = nil line2 = nil at = ((item.title && item.link) ? ' @ ' : '') + case feed.type when 'blog' + author += " " if author abt = category ? "about #{category} " : "" - line1 = "#{handle}#{date}#{author} blogged #{abt}at #{link}" + line1 = "#{handle}#{date}#{author}blogged #{abt}at #{link}" line2 = "#{handle}#{title} - #{desc}" + when 'git' + author += " " if author + line1 = "#{handle}#{date}#{author}commited #{title} @ #{link}" when 'forum' line1 = "#{handle}#{date}#{title}#{at}#{link}" when 'wiki' @@ -758,7 +917,7 @@ class RSSFeedsPlugin < Plugin line1 = "#{handle}#{date}Message #{title} sent by #{author}. #{desc}" when 'trac' line1 = "#{handle}#{date}#{title} @ #{link}" - unless item.title =~ /^Changeset \[(\d+)\]/ + unless item.title =~ /^(?:Changeset \[(?:[\da-f]+)\]|\(git commit\))/ line2 = "#{handle}#{date}#{desc}" end when '/.' @@ -768,6 +927,7 @@ class RSSFeedsPlugin < Plugin line1 = "#{handle}#{date}#{dept}#{title}#{at}#{link} (posted by #{author}#{sec})" else line1 = "#{handle}#{date}#{title}#{at}#{link}" + line1 << " (by #{author})" if author end places.each { |loc| @bot.say loc, line1, :overlong => :truncate @@ -777,6 +937,7 @@ class RSSFeedsPlugin < Plugin end def fetchRss(feed, m=nil, cache=true) + feed.last_fetched = Time.now begin # Use 60 sec timeout, cause the default is too low xml = @bot.httputil.get(feed.url, @@ -840,8 +1001,12 @@ class RSSFeedsPlugin < Plugin report_problem("bah! something went wrong =(", e, m) return nil end - rss.channel.title ||= "Unknown" - title = rss.channel.title + if rss.respond_to? :channel + rss.channel.title ||= "Unknown" + title = rss.channel.title + else + title = rss.title.content + end rss.items.each do |item| item.title ||= "Unknown" items << item @@ -861,6 +1026,9 @@ end plugin = RSSFeedsPlugin.new +plugin.default_auth( 'edit', false ) +plugin.default_auth( 'edit:add', true) + plugin.map 'rss show :handle :limit', :action => 'show_rss', :requirements => {:limit => /^\d+(?:\.\.\d+)?$/}, @@ -876,25 +1044,36 @@ plugin.map 'rss who watches :handle', :defaults => {:handle => nil} plugin.map 'rss add :handle :url :type', :action => 'add_rss', + :auth_path => 'edit', :defaults => {:type => nil} plugin.map 'rss change :what of :handle to :new', :action => 'change_rss', + :auth_path => 'edit', :requirements => { :what => /handle|url|format|type|refresh/ } plugin.map 'rss change :what for :handle to :new', :action => 'change_rss', + :auth_path => 'edit', :requirements => { :what => /handle|url|format|type|refesh/ } plugin.map 'rss del :handle', + :auth_path => 'edit:rm!', :action => 'del_rss' plugin.map 'rss delete :handle', + :auth_path => 'edit:rm!', :action => 'del_rss' plugin.map 'rss rm :handle', + :auth_path => 'edit:rm!', :action => 'del_rss' plugin.map 'rss replace :handle :url :type', + :auth_path => 'edit', :action => 'replace_rss', :defaults => {:type => nil} plugin.map 'rss forcereplace :handle :url :type', + :auth_path => 'edit', :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} @@ -902,6 +1081,5 @@ plugin.map 'rss unwatch :handle [in :chan]', :action => 'unwatch_rss' plugin.map 'rss rmwatch :handle [in :chan]', :action => 'unwatch_rss' -plugin.map 'rss rewatch', +plugin.map 'rss rewatch [:handle]', :action => 'rewatch_rss' -