4 # :title: RSS feed plugin for rbot
6 # Author:: Stanislav Karchebny <berkus@madfire.net>
7 # Author:: Ian Monroe <ian@monroe.nu>
8 # Author:: Mark Kretschmann <markey@web.de>
9 # Author:: Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
11 # Copyright:: (C) 2004 Stanislav Karchebny
12 # Copyright:: (C) 2005 Ian Monroe, Mark Kretschmann
13 # Copyright:: (C) 2006-2007 Giuseppe Bilotta
15 # License:: MIT license
19 # Try to load rss/content/2.0 so we can access the data in <content:encoded>
22 require 'rss/content/2.0'
28 # Add support for Slashdot namespace in RDF. The code is just an adaptation
29 # of the DublinCore code.
30 unless defined?(SLASH_PREFIX)
31 SLASH_PREFIX = 'slash'
32 SLASH_URI = "http://purl.org/rss/1.0/modules/slash/"
34 RDF.install_ns(SLASH_PREFIX, SLASH_URI)
37 def append_features(klass)
40 return if klass.instance_of?(Module)
41 SlashModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
42 plural = plural_name || "#{name}s"
43 full_name = "#{SLASH_PREFIX}_#{name}"
44 full_plural_name = "#{SLASH_PREFIX}_#{plural}"
45 klass_name = "Slash#{Utils.to_class_name(name)}"
47 # This will fail with older version of the Ruby RSS module
49 klass.install_have_children_element(name, SLASH_URI, "*",
50 full_name, full_plural_name)
51 klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI)
53 klass.module_eval("install_have_children_element(#{full_name.dump}, #{full_plural_name.dump})")
56 klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0))
57 remove_method :#{full_name} if method_defined? :#{full_name}
58 remove_method :#{full_name}= if method_defined? :#{full_name}=
59 remove_method :set_#{full_name} if method_defined? :set_#{full_name}
62 @#{full_name}.first and @#{full_name}.first.value
65 def #{full_name}=(new_value)
66 @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value)
68 alias set_#{full_name} #{full_name}=
85 ELEMENT_NAME_INFOS = SlashModel::TEXT_ELEMENTS.to_a
87 ELEMENTS = TEXT_ELEMENTS.keys
89 ELEMENTS.each do |name, plural_name|
90 module_eval(<<-EOC, *get_file_and_line_from_caller(0))
91 class Slash#{Utils.to_class_name(name)} < Element
106 @tag_name = #{name.dump}
108 alias_method(:value, :content)
109 alias_method(:value=, :content=)
111 def initialize(*args)
113 if Utils.element_initialize_arguments?(args)
117 self.content = args[0]
119 # Older Ruby RSS module
122 self.content = args[0]
127 tag_name_with_prefix(SLASH_PREFIX)
130 def maker_target(target)
134 def setup_maker_attributes(#{name})
135 #{name}.content = content
143 class Item; include SlashModel; end
146 SlashModel::ELEMENTS.each do |name|
147 class_name = Utils.to_class_name(name)
148 BaseListener.install_class_name(SLASH_URI, name, "Slash#{class_name}")
151 SlashModel::ELEMENTS.collect! {|name| "#{SLASH_PREFIX}_#{name}"}
157 attr_accessor :url, :handle, :type, :refresh_rate, :xml, :title, :items,
158 :mutex, :watchers, :last_fetched
160 def initialize(url,handle=nil,type=nil,watchers=[], xml=nil, lf = nil)
175 sanitize_watchers(watchers)
179 @mutex.synchronize do
182 @type ? @type.dup : nil,
184 @xml ? @xml.dup : nil,
189 # Downcase all watchers, possibly turning them into Strings if they weren't
190 def sanitize_watchers(list=@watchers)
203 @watchers.include?(who.downcase)
210 @mutex.synchronize do
211 @watchers << who.downcase
217 @mutex.synchronize do
218 @watchers.delete(who.downcase)
223 [@handle,@url,@type,@refresh_rate,@watchers]
226 def to_s(watchers=false)
228 a = self.to_a.flatten
232 a.compact.join(" | ")
236 class RSSFeedsPlugin < Plugin
237 Config.register Config::IntegerValue.new('rss.head_max',
238 :default => 100, :validate => Proc.new{|v| v > 0 && v < 200},
239 :desc => "How many characters to use of a RSS item header")
241 Config.register Config::IntegerValue.new('rss.text_max',
242 :default => 200, :validate => Proc.new{|v| v > 0 && v < 400},
243 :desc => "How many characters to use of a RSS item text")
245 Config.register Config::IntegerValue.new('rss.thread_sleep',
246 :default => 300, :validate => Proc.new{|v| v > 30},
247 :desc => "How many seconds to sleep before checking RSS feeds again")
249 Config.register Config::BooleanValue.new('rss.show_updated',
251 :desc => "Whether feed items for which the description was changed should be shown as new")
253 Config.register Config::BooleanValue.new('rss.show_links',
255 :desc => "Whether to display links from the text of a feed item.")
257 # Make an 'unique' ID for a given item, based on appropriate bot options
258 # Currently only suppored is bot.config['rss.show_updated']: when false,
259 # only the guid/link is accounted for.
261 def block_rescue(df = nil, &block)
262 v = block.call rescue nil
263 (String === v && '' != v) ? v : nil
268 (block_rescue do item.guid.content end ||
269 block_rescue do item.guid end ||
270 block_rescue do item.link.href end ||
271 block_rescue do item.link end
274 if @bot.config['rss.show_updated']
276 block_rescue do item.content.content end ||
277 block_rescue do item.description end
280 block_rescue do item.title.content end ||
281 block_rescue do item.title end
284 # debug "taking hash of #{uid.inspect}"
289 # We used to save the Mutex with the RssBlob, which was idiotic. And
290 # since Mutexes dumped in one version might not be resotrable in another,
291 # we need a few tricks to be able to restore data from other versions of Ruby
293 # When migrating 1.8.6 => 1.8.5, all we need to do is define an empty
294 # #marshal_load() method for Mutex. For 1.8.5 => 1.8.6 we need something
295 # dirtier, as seen later on in the initialization code.
296 unless Mutex.new.respond_to?(:marshal_load)
298 def marshal_load(str)
304 # Auxiliary method used to collect two lines for rss output filters,
305 # running substitutions against DataStream _s_ optionally joined
307 def make_stream(line1, line2, s, h={})
309 DataStream.new([line1, line2].compact.join("\n") % ss, ss)
312 # Define default RSS filters
314 # TODO: load personal ones
317 @bot.register_filter(:blog, @outkey) { |s|
318 author = s[:author] ? (s[:author] + " ") : ""
319 abt = s[:category] ? "about #{s[:category]} " : ""
320 line1 = "%{handle}%{date}%{author}blogged %{abt}at %{link}"
321 line2 = "%{handle}%{title} - %{desc}"
322 make_stream(line1, line2, s, :author => author, :abt => abt)
324 @bot.register_filter(:photoblog, @outkey) { |s|
325 author = s[:author] ? (s[:author] + " ") : ""
326 abt = s[:category] ? "under #{s[:category]} " : ""
327 line1 = "%{handle}%{date}%{author}added an image %{abt}at %{link}"
328 line2 = "%{handle}%{title} - %{desc}"
329 make_stream(line1, line2, s, :author => author, :abt => abt)
331 @bot.register_filter(:news, @outkey) { |s|
332 line1 = "%{handle}%{date}%{title} @ %{link}" % s
333 line2 = "%{handle}%{date}%{desc}" % s
334 make_stream(line1, line2, s)
336 @bot.register_filter(:git, @outkey) { |s|
337 author = s[:author] ? (s[:author] + " ") : ""
338 line1 = "%{handle}%{date}%{author}committed %{title} @ %{link}"
339 make_stream(line1, nil, s, :author => author)
341 @bot.register_filter(:forum, @outkey) { |s|
342 line1 = "%{handle}%{date}%{title}%{at}%{link}"
343 make_stream(line1, nil, s)
345 @bot.register_filter(:wiki, @outkey) { |s|
346 line1 = "%{handle}%{date}%{title}%{at}%{link}"
347 line1 << "has been edited by %{author}. %{desc}"
348 make_stream(line1, nil, s)
350 @bot.register_filter(:gmane, @outkey) { |s|
351 line1 = "%{handle}%{date}Message %{title} sent by %{author}. %{desc}"
352 make_stream(line1, nil, s)
354 @bot.register_filter(:trac, @outkey) { |s|
355 author = s[:author].sub(/@\S+?\s*>/, "@...>") + ": " if s[:author]
356 line1 = "%{handle}%{date}%{author}%{title} @ %{link}"
358 unless s[:item].title =~ /^(?:Changeset \[(?:[\da-f]+)\]|\(git commit\))/
359 line2 = "%{handle}%{date}%{desc}"
361 make_stream(line1, line2, s, :author => author)
363 @bot.register_filter(:"/.", @outkey) { |s|
364 dept = "(from the #{s[:item].slash_department} dept) " rescue nil
365 sec = " in section #{s[:item].slash_section}" rescue nil
366 line1 = "%{handle}%{date}%{dept}%{title}%{at}%{link} "
367 line1 << "(posted by %{author}%{sec})"
368 make_stream(line1, nil, s, :dept => dept, :sec => sec)
370 @bot.register_filter(:default, @outkey) { |s|
371 line1 = "%{handle}%{date}%{title}%{at}%{link}"
372 line1 << " (by %{author})" if s[:author]
373 make_stream(line1, nil, s)
376 # Define an HTML info filter too
377 @bot.register_filter(:rss, :htmlinfo) { |s| htmlinfo_filter(s) }
379 # This is the output format used by the input filter
380 @bot.register_filter(:htmlinfo, @outkey) { |s|
381 line1 = "%{title}%{at}%{link}"
382 make_stream(line1, nil, s)
386 FEED_NS = %r{xmlns.*http://(purl\.org/rss|www.w3c.org/1999/02/22-rdf)}
387 def htmlinfo_filter(s)
388 return nil unless s[:headers] and s[:headers]['x-rbot-location']
389 return nil unless s[:headers]['content-type'].first.match(/xml|rss|atom|rdf/i) or
390 (s[:text].include?("<rdf:RDF") and s[:text].include?("<channel")) or
391 s[:text].include?("<rss") or s[:text].include?("<feed") or
392 s[:text].match(FEED_NS)
393 blob = RssBlob.new(s[:headers]['x-rbot-location'],"", :htmlinfo)
394 unless (fetchRss(blob, nil) and parseRss(blob, nil) rescue nil)
395 debug "#{s.pretty_inspect} is not an RSS feed, despite the appearances"
399 blob.items.each { |it|
400 output << printFormattedRss(blob, it)[:text]
402 return {:title => blob.title, :content => output.join(" | ")}
405 # Display the known rss types
406 def rss_types(m, params)
407 ar = @bot.filter_names(@outkey)
409 m.reply ar.map { |k| k.to_s }.sort!.join(", ")
419 if @registry.has_key?(:feeds)
420 # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the
421 # data unrestorable. If this happens, we patch the data, thus allowing
422 # the restore to work.
424 # This is actually pretty safe for a number of reasons:
425 # * the code is only called if standard marshalling fails
426 # * the string we look for is quite unlikely to appear randomly
427 # * if the string appears somewhere and the patched string isn't recoverable
428 # either, we'll get another (unrecoverable) error, which makes the rss
429 # plugin unsable, just like it was if no recovery was attempted
430 # * if the string appears somewhere and the patched string is recoverable,
431 # we may get a b0rked feed, which is eventually overwritten by a clean
432 # one, so the worst thing that can happen is that a feed update spams
434 @registry.recovery = Proc.new { |val|
435 patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")
436 ret = Marshal.restore(patched)
437 ret.each_value { |blob|
443 @feeds = @registry[:feeds]
446 @registry.recovery = nil
448 @feeds.keys.grep(/[A-Z]/) { |k|
449 @feeds[k.downcase] = @feeds[k]
469 @feeds.select { |h, f| f.watched? }
478 unparsed = Hash.new()
481 # we don't want to save the mutex
482 unparsed[k].mutex = nil
484 @registry[:feeds] = unparsed
487 def stop_watch(handle)
488 if @watch.has_key?(handle)
490 debug "Stopping watch #{handle}"
491 @bot.timer.remove(@watch[handle])
492 @watch.delete(handle)
493 rescue Exception => e
494 report_problem("Failed to stop watch for #{handle}", e, nil)
500 @watch.each_key { |k|
505 def help(plugin,topic="")
508 "rss show #{Bold}handle#{Bold} [#{Bold}limit#{Bold}] : show #{Bold}limit#{Bold} (default: 5, max: 15) entries from rss #{Bold}handle#{Bold}; #{Bold}limit#{Bold} can also be in the form a..b, to display a specific range of items"
510 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
512 "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
513 when "who", "watches", "who watches"
514 "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
516 "rss add #{Bold}handle#{Bold} #{Bold}url#{Bold} [#{Bold}type#{Bold}] : add a new rss called #{Bold}handle#{Bold} from url #{Bold}url#{Bold} (of type #{Bold}type#{Bold})"
518 "rss change #{Bold}what#{Bold} of #{Bold}handle#{Bold} to #{Bold}new#{Bold} : change the #{Underline}handle#{Underline}, #{Underline}url#{Underline}, #{Underline}type#{Underline} or #{Underline}refresh#{Underline} rate of rss called #{Bold}handle#{Bold} to value #{Bold}new#{Bold}"
519 when /^(del(ete)?|rm)$/
520 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
522 "rss replace #{Bold}handle#{Bold} #{Bold}url#{Bold} [#{Bold}type#{Bold}] : try to replace the url of rss called #{Bold}handle#{Bold} with #{Bold}url#{Bold} (of type #{Bold}type#{Bold}); only works if nobody else is watching it"
524 "rss forcereplace #{Bold}handle#{Bold} #{Bold}url#{Bold} [#{Bold}type#{Bold}] : replace the url of rss called #{Bold}handle#{Bold} with #{Bold}url#{Bold} (of type #{Bold}type#{Bold})"
526 "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"
528 "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
529 when /who(?: watche?s?)?/
530 "rss who watches #{Bold}handle#{Bold}: lists watches for rss #{Bold}handle#{Bold}"
532 "rss rewatch : restart threads that watch for changes in watched rss"
534 "rss types : show the rss types for which an output format existi (all other types will use the default one)"
536 "manage RSS feeds: rss types|show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch|who watches"
540 def report_problem(report, e=nil, m=nil)
541 if m && m.respond_to?(:reply)
548 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
552 def show_rss(m, params)
553 handle = params[:handle]
554 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
555 debug lims.to_a.inspect
557 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
558 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
559 rev = lims[1].to_i > lims[2].to_i
562 ul = [[lims[1].to_i-1, 0].max, 14].min
566 feed = @feeds.fetch(handle.downcase, nil)
568 m.reply "I don't know any feeds named #{handle}"
572 m.reply "lemme fetch it..."
574 we_were_watching = false
576 if @watch.key?(feed.handle)
577 # If a feed is being watched, we run the watcher thread
578 # so that all watchers can be informed of changes to
579 # the feed. Before we do that, though, we remove the
580 # show requester from the watchlist, if present, lest
581 # he gets the update twice.
582 if feed.watched_by?(m.replyto)
583 we_were_watching = true
584 feed.rm_watch(m.replyto)
586 @bot.timer.reschedule(@watch[feed.handle], 0)
588 feed.add_watch(m.replyto)
591 fetched = fetchRss(feed, m, false)
593 return unless fetched or feed.xml
594 if fetched or not feed.items
595 parsed = parseRss(feed, m)
597 return unless feed.items
598 m.reply "using old data" unless fetched and parsed
603 # We sort the feeds in freshness order (newer ones first)
604 items = freshness_sort(items)
608 m.reply "Channel : #{title}"
610 printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})
614 def itemDate(item,ex=nil)
615 return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
616 return item.date if item.respond_to?(:date) and item.date
620 def freshness_sort(items)
623 itemDate(b, notime) <=> itemDate(a, notime)
627 def list_rss(m, params)
628 wanted = params[:handle]
630 @feeds.each { |handle, feed|
631 next if wanted and !handle.match(/#{wanted}/i)
632 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
633 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
634 (reply << " (watched)") if feed.watched_by?(m.replyto)
638 reply = "no feeds found"
639 reply << " matching #{wanted}" if wanted
641 m.reply reply, :max_lines => reply.length
644 def watched_rss(m, params)
645 wanted = params[:handle]
646 chan = params[:chan] || m.replyto
648 watchlist.each { |handle, feed|
649 next if wanted and !handle.match(/#{wanted}/i)
650 next unless feed.watched_by?(chan)
651 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
652 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
656 reply = "no watched feeds"
657 reply << " matching #{wanted}" if wanted
662 def who_watches(m, params)
663 wanted = params[:handle]
665 watchlist.each { |handle, feed|
666 next if wanted and !handle.match(/#{wanted}/i)
667 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
668 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
669 reply << ": watched by #{feed.watchers.join(', ')}"
673 reply = "no watched feeds"
674 reply << " matching #{wanted}" if wanted
679 def add_rss(m, params, force=false)
680 handle = params[:handle]
682 unless url.match(/https?/)
683 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
687 if @feeds.fetch(handle.downcase, nil) && !force
688 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
692 m.reply "You must specify both a handle and an url to add an RSS feed"
695 @feeds[handle.downcase] = RssBlob.new(url,handle,type)
696 reply = "Added RSS #{url} named #{handle}"
698 reply << " (format: #{type})"
704 def change_rss(m, params)
705 handle = params[:handle].downcase
706 feed = @feeds.fetch(handle, nil)
708 m.reply "No such feed with handle #{handle}"
711 case params[:what].intern
713 new = params[:new].downcase
714 if @feeds.key?(new) and @feeds[new]
715 m.reply "There already is a feed with handle #{new}"
718 feed.mutex.synchronize do
720 @feeds.delete(handle)
727 feed.mutex.synchronize do
732 new = nil if new == 'default'
733 feed.mutex.synchronize do
737 new = params[:new].to_i
738 new = nil if new == 0
739 feed.mutex.synchronize do
740 feed.refresh_rate = new
743 m.reply "Don't know how to change #{params[:what]} for feeds"
746 m.reply "Feed changed:"
747 list_rss(m, {:handle => handle})
750 def del_rss(m, params, pass=false)
751 feed = unwatch_rss(m, params, true)
754 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
757 @feeds.delete(feed.handle.downcase)
762 def replace_rss(m, params)
763 handle = params[:handle]
764 if @feeds.key?(handle.downcase)
765 del_rss(m, {:handle => handle}, true)
767 if @feeds.key?(handle.downcase)
768 m.reply "can't replace #{feed.handle}"
770 add_rss(m, params, true)
774 def forcereplace_rss(m, params)
775 add_rss(m, params, true)
778 def watch_rss(m, params)
779 handle = params[:handle]
780 chan = params[:chan] || m.replyto
786 feed = @feeds.fetch(handle.downcase, nil)
788 if feed.add_watch(chan)
792 m.reply "Already watching #{feed.handle} in #{chan}"
795 m.reply "Couldn't watch feed #{handle} (no such feed found)"
799 def unwatch_rss(m, params, pass=false)
800 handle = params[:handle].downcase
801 chan = params[:chan] || m.replyto
802 unless @feeds.has_key?(handle)
803 m.reply("dunno that feed")
806 feed = @feeds[handle]
807 if feed.rm_watch(chan)
808 m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
810 m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
818 def rewatch_rss(m=nil, params=nil)
819 if params and handle = params[:handle]
820 feed = @feeds.fetch(handle.downcase, nil)
822 @bot.timer.reschedule(@watch[feed.handle], (params[:delay] || 0).to_f)
825 m.reply _("no such feed %{handle}") % { :handle => handle } if m
830 # Read watches from list.
831 watchlist.each{ |handle, feed|
839 def watchRss(feed, m=nil)
840 if @watch.has_key?(feed.handle)
841 report_problem("watcher thread for #{feed.handle} is already running", nil, m)
845 status[:failures] = 0
848 tmout = feed.last_fetched + calculate_timeout(feed) - Time.now
849 tmout = 0 if tmout < 0
851 debug "scheduling a watcher for #{feed} in #{tmout} seconds"
852 @watch[feed.handle] = @bot.timer.add(tmout) {
853 debug "watcher for #{feed} wakes up"
854 failures = status[:failures]
856 debug "fetching #{feed}"
857 first_run = !feed.last_fetched
858 oldxml = feed.xml ? feed.xml.dup : nil
859 unless fetchRss(feed)
863 debug "first run for #{feed}, getting items"
865 elsif oldxml and oldxml == feed.xml
866 debug "xml for #{feed} didn't change"
867 failures -= 1 if failures > 0
870 debug "no previous items in feed #{feed}"
872 failures -= 1 if failures > 0
874 # This one is used for debugging
877 # These are used for checking new items vs old ones
878 oids = Set.new feed.items.map { |item|
881 debug [uid, item].inspect
882 debug [uid, otxt.last].inspect
886 unless parseRss(feed)
887 debug "no items in feed #{feed}"
890 debug "Checking if new items are available for #{feed}"
891 failures -= 1 if failures > 0
897 dispItems = feed.items.reject { |item|
900 if oids.include?(uid)
901 debug "rejecting old #{uid} #{item.inspect}"
902 debug [uid, txt].inspect
905 debug "accepting new #{uid} #{item.inspect}"
906 debug [uid, txt].inspect
907 warning "same text! #{txt}" if otxt.include?(txt)
912 if dispItems.length > 0
913 debug "Found #{dispItems.length} new items in #{feed}"
914 # When displaying watched feeds, publish them from older to newer
915 dispItems.reverse.each { |item|
916 printFormattedRss(feed, item)
919 debug "No new items found in #{feed}"
925 rescue Exception => e
926 error "Error watching #{feed}: #{e.inspect}"
927 debug e.backtrace.join("\n")
931 status[:failures] = failures
933 seconds = calculate_timeout(feed, failures)
934 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
936 @bot.timer.reschedule(@watch[feed.handle], seconds)
938 warning "watcher for #{feed} failed to reschedule: #{$!.inspect}"
941 debug "watcher for #{feed} added"
944 def calculate_timeout(feed, failures = 0)
945 seconds = @bot.config['rss.thread_sleep']
946 feed.mutex.synchronize do
947 seconds = feed.refresh_rate if feed.refresh_rate
949 seconds *= failures + 1
950 seconds += seconds * (rand(100)-50)/100
954 def select_nonempty(*ar)
956 ar.each { |i| return i unless i.nil_or_empty? }
960 def printFormattedRss(feed, item, opts=nil)
962 places = feed.watchers
963 handle = feed.handle.empty? ? "" : "::#{feed.handle}:: "
966 places = opts[:places] if opts.key?(:places)
967 handle = opts[:handle].to_s if opts.key?(:handle)
968 if opts.key?(:date) && opts[:date]
969 if item.respond_to?(:updated)
970 if item.updated.content.class <= Time
971 date = item.updated.content.strftime("%Y/%m/%d %H:%M")
973 date = item.updated.content.to_s
975 elsif item.respond_to?(:source) and item.source.respond_to?(:updated)
976 if item.source.updated.content.class <= Time
977 date = item.source.updated.content.strftime("%Y/%m/%d %H:%M")
979 date = item.source.updated.content.to_s
981 elsif item.respond_to?(:pubDate)
982 if item.pubDate.class <= Time
983 date = item.pubDate.strftime("%Y/%m/%d %H:%M")
985 date = item.pubDate.to_s
987 elsif item.respond_to?(:date)
988 if item.date.class <= Time
989 date = item.date.strftime("%Y/%m/%d %H:%M")
991 date = item.date.to_s
1001 # Twitters don't need a cap on the title length since they have a hard
1002 # limit to 160 characters, and most of them are under 140 characters
1003 tit_opt[:limit] = @bot.config['rss.head_max'] unless feed.type == 'twitter'
1006 base_title = item.title.to_s.dup
1007 # git changesets are SHA1 hashes (40 hex digits), way too long, get rid of them, as they are
1008 # visible in the URL anyway
1009 # TODO make this optional?
1010 base_title.sub!(/^Changeset \[([\da-f]{40})\]:/) { |c| "(git commit)"} if feed.type == 'trac'
1011 title = "#{Bold}#{base_title.ircify_html(tit_opt)}#{Bold}"
1015 desc_opt[:limit] = @bot.config['rss.text_max']
1016 desc_opt[:a_href] = :link_out if @bot.config['rss.show_links']
1018 # We prefer content_encoded here as it tends to provide more html formatting
1019 # for use with ircify_html.
1020 if item.respond_to?(:content_encoded) && item.content_encoded
1021 desc = item.content_encoded.ircify_html(desc_opt)
1022 elsif item.respond_to?(:description) && item.description
1023 desc = item.description.ircify_html(desc_opt)
1024 elsif item.respond_to?(:content) && item.content
1025 if item.content.type == "html"
1026 desc = item.content.content.ircify_html(desc_opt)
1028 desc = item.content.content
1029 if desc.size > desc_opt[:limit]
1030 desc = desc.slice(0, desc_opt[:limit]) + "#{Reverse}...#{Reverse}"
1037 link = item.link.href rescue item.link rescue nil
1040 category = select_nonempty((item.category.content rescue nil), (item.dc_subject rescue nil))
1041 category.strip! if category
1042 author = select_nonempty((item.author.name.content rescue nil), (item.dc_creator rescue nil), (item.author rescue nil))
1043 author.strip! if author
1048 at = ((item.title && item.link) ? ' @ ' : '')
1050 key = @bot.global_filter_name(feed.type, @outkey)
1051 key = @bot.global_filter_name(:default, @outkey) unless @bot.has_filter?(key)
1053 output = @bot.filter(key, :item => item, :handle => handle, :date => date,
1054 :title => title, :desc => desc, :link => link,
1055 :category => category, :author => author, :at => at)
1057 return output if places.empty?
1060 output.to_s.each_line { |line|
1061 @bot.say loc, line, :overlong => :truncate
1066 def fetchRss(feed, m=nil, cache=true)
1067 feed.last_fetched = Time.now
1069 # Use 60 sec timeout, cause the default is too low
1070 xml = @bot.httputil.get(feed.url,
1071 :read_timeout => 60,
1072 :open_timeout => 60,
1074 rescue URI::InvalidURIError, URI::BadURIError => e
1075 report_problem("invalid rss feed #{feed.url}", e, m)
1078 report_problem("error getting #{feed.url}", e, m)
1081 debug "fetched #{feed}"
1083 report_problem("reading feed #{feed} failed", nil, m)
1086 # Ok, 0.9 feeds are not supported, maybe because
1087 # Netscape happily removed the DTD. So what we do is just to
1088 # reassign the 0.9 RDFs to 1.0, and hope it goes right.
1089 xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",
1090 "xmlns=\"http://purl.org/rss/1.0/\"")
1091 feed.mutex.synchronize do
1097 def parseRss(feed, m=nil)
1098 return nil unless feed.xml
1099 feed.mutex.synchronize do
1102 ## do validate parse
1103 rss = RSS::Parser.parse(xml)
1104 debug "parsed and validated #{feed}"
1105 rescue RSS::InvalidRSSError
1106 ## do non validate parse for invalid RSS 1.0
1108 rss = RSS::Parser.parse(xml, false)
1109 debug "parsed but not validated #{feed}"
1110 rescue RSS::Error => e
1111 report_problem("parsing rss stream failed, whoops =(", e, m)
1114 rescue RSS::Error => e
1115 report_problem("parsing rss stream failed, oioi", e, m)
1118 report_problem("processing error occured, sorry =(", e, m)
1123 if xml.match(/xmlns\s*=\s*(['"])http:\/\/www.w3.org\/2005\/Atom\1/) and not defined?(RSS::Atom)
1124 report_problem("#{feed.handle} @ #{feed.url} looks like an Atom feed, but your Ruby/RSS library doesn't seem to support it. Consider getting the latest version from http://raa.ruby-lang.org/project/rss/", nil, m)
1126 report_problem("#{feed.handle} @ #{feed.url} doesn't seem to contain an RSS or Atom feed I can read", nil, m)
1131 rss.output_encoding = 'UTF-8'
1132 rescue RSS::UnknownConvertMethod => e
1133 report_problem("bah! something went wrong =(", e, m)
1136 if rss.respond_to? :channel
1137 rss.channel.title ||= "(?)"
1138 title = rss.channel.title
1140 title = rss.title.content
1142 rss.items.each do |item|
1143 item.title ||= "(?)"
1149 report_problem("no items found in the feed, maybe try weed?", e, m)
1159 plugin = RSSFeedsPlugin.new
1161 plugin.default_auth( 'edit', false )
1162 plugin.default_auth( 'edit:add', true)
1164 plugin.map 'rss show :handle :limit',
1165 :action => 'show_rss',
1166 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
1167 :defaults => {:limit => 5}
1168 plugin.map 'rss list :handle',
1169 :action => 'list_rss',
1170 :defaults => {:handle => nil}
1171 plugin.map 'rss watched :handle [in :chan]',
1172 :action => 'watched_rss',
1173 :defaults => {:handle => nil}
1174 plugin.map 'rss who watches :handle',
1175 :action => 'who_watches',
1176 :defaults => {:handle => nil}
1177 plugin.map 'rss add :handle :url :type',
1178 :action => 'add_rss',
1179 :auth_path => 'edit',
1180 :defaults => {:type => nil}
1181 plugin.map 'rss change :what of :handle to :new',
1182 :action => 'change_rss',
1183 :auth_path => 'edit',
1184 :requirements => { :what => /handle|url|format|type|refresh/ }
1185 plugin.map 'rss change :what for :handle to :new',
1186 :action => 'change_rss',
1187 :auth_path => 'edit',
1188 :requirements => { :what => /handle|url|format|type|refesh/ }
1189 plugin.map 'rss del :handle',
1190 :auth_path => 'edit:rm!',
1191 :action => 'del_rss'
1192 plugin.map 'rss delete :handle',
1193 :auth_path => 'edit:rm!',
1194 :action => 'del_rss'
1195 plugin.map 'rss rm :handle',
1196 :auth_path => 'edit:rm!',
1197 :action => 'del_rss'
1198 plugin.map 'rss replace :handle :url :type',
1199 :auth_path => 'edit',
1200 :action => 'replace_rss',
1201 :defaults => {:type => nil}
1202 plugin.map 'rss forcereplace :handle :url :type',
1203 :auth_path => 'edit',
1204 :action => 'forcereplace_rss',
1205 :defaults => {:type => nil}
1206 plugin.map 'rss watch :handle [in :chan]',
1207 :action => 'watch_rss',
1208 :defaults => {:url => nil, :type => nil}
1209 plugin.map 'rss watch :handle :url :type [in :chan]',
1210 :action => 'watch_rss',
1211 :defaults => {:url => nil, :type => nil}
1212 plugin.map 'rss unwatch :handle [in :chan]',
1213 :action => 'unwatch_rss'
1214 plugin.map 'rss rmwatch :handle [in :chan]',
1215 :action => 'unwatch_rss'
1216 plugin.map 'rss rewatch [:handle] [:delay]',
1217 :action => 'rewatch_rss'
1218 plugin.map 'rss types',
1219 :action => 'rss_types'