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 # Make an 'unique' ID for a given item, based on appropriate bot options
29 # Currently only suppored is bot.config['rss.show_updated']: when true, the
30 # description is included in the uid hashing, otherwise it's not
32 def RSS.item_uid_for_bot(item, opts={})
33 options = { :show_updated => true}.merge(opts)
35 if options[:show_updated]
36 desc = item.content.content rescue item.description rescue nil
38 [(item.title.content rescue item.title rescue nil),
39 (item.link.href rescue item.link),
43 # Add support for Slashdot namespace in RDF. The code is just an adaptation
44 # of the DublinCore code.
45 unless defined?(SLASH_PREFIX)
46 SLASH_PREFIX = 'slash'
47 SLASH_URI = "http://purl.org/rss/1.0/modules/slash/"
49 RDF.install_ns(SLASH_PREFIX, SLASH_URI)
52 def append_features(klass)
55 return if klass.instance_of?(Module)
56 SlashModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
57 plural = plural_name || "#{name}s"
58 full_name = "#{SLASH_PREFIX}_#{name}"
59 full_plural_name = "#{SLASH_PREFIX}_#{plural}"
60 klass_name = "Slash#{Utils.to_class_name(name)}"
62 # This will fail with older version of the Ruby RSS module
64 klass.install_have_children_element(name, SLASH_URI, "*",
65 full_name, full_plural_name)
66 klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI)
68 klass.module_eval("install_have_children_element(#{full_name.dump}, #{full_plural_name.dump})")
71 klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0))
72 remove_method :#{full_name} if method_defined? :#{full_name}
73 remove_method :#{full_name}= if method_defined? :#{full_name}=
74 remove_method :set_#{full_name} if method_defined? :set_#{full_name}
77 @#{full_name}.first and @#{full_name}.first.value
80 def #{full_name}=(new_value)
81 @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value)
83 alias set_#{full_name} #{full_name}=
100 ELEMENT_NAME_INFOS = SlashModel::TEXT_ELEMENTS.to_a
102 ELEMENTS = TEXT_ELEMENTS.keys
104 ELEMENTS.each do |name, plural_name|
105 module_eval(<<-EOC, *get_file_and_line_from_caller(0))
106 class Slash#{Utils.to_class_name(name)} < Element
121 @tag_name = #{name.dump}
123 alias_method(:value, :content)
124 alias_method(:value=, :content=)
126 def initialize(*args)
128 if Utils.element_initialize_arguments?(args)
132 self.content = args[0]
134 # Older Ruby RSS module
137 self.content = args[0]
142 tag_name_with_prefix(SLASH_PREFIX)
145 def maker_target(target)
149 def setup_maker_attributes(#{name})
150 #{name}.content = content
158 class Item; include SlashModel; end
161 SlashModel::ELEMENTS.each do |name|
162 class_name = Utils.to_class_name(name)
163 BaseListener.install_class_name(SLASH_URI, name, "Slash#{class_name}")
166 SlashModel::ELEMENTS.collect! {|name| "#{SLASH_PREFIX}_#{name}"}
172 attr_accessor :url, :handle, :type, :refresh_rate, :xml, :title, :items,
173 :mutex, :watchers, :last_fetched
175 def initialize(url,handle=nil,type=nil,watchers=[], xml=nil, lf = nil)
190 sanitize_watchers(watchers)
194 @mutex.synchronize do
197 @type ? @type.dup : nil,
199 @xml ? @xml.dup : nil,
204 # Downcase all watchers, possibly turning them into Strings if they weren't
205 def sanitize_watchers(list=@watchers)
218 @watchers.include?(who.downcase)
225 @mutex.synchronize do
226 @watchers << who.downcase
232 @mutex.synchronize do
233 @watchers.delete(who.downcase)
238 [@handle,@url,@type,@refresh_rate,@watchers]
241 def to_s(watchers=false)
243 a = self.to_a.flatten
247 a.compact.join(" | ")
251 class RSSFeedsPlugin < Plugin
252 Config.register Config::IntegerValue.new('rss.head_max',
253 :default => 100, :validate => Proc.new{|v| v > 0 && v < 200},
254 :desc => "How many characters to use of a RSS item header")
256 Config.register Config::IntegerValue.new('rss.text_max',
257 :default => 200, :validate => Proc.new{|v| v > 0 && v < 400},
258 :desc => "How many characters to use of a RSS item text")
260 Config.register Config::IntegerValue.new('rss.thread_sleep',
261 :default => 300, :validate => Proc.new{|v| v > 30},
262 :desc => "How many seconds to sleep before checking RSS feeds again")
264 Config.register Config::BooleanValue.new('rss.show_updated',
266 :desc => "Whether feed items for which the description was changed should be shown as new")
268 Config.register Config::BooleanValue.new('rss.show_links',
270 :desc => "Whether to display links from the text of a feed item.")
272 # We used to save the Mutex with the RssBlob, which was idiotic. And
273 # since Mutexes dumped in one version might not be resotrable in another,
274 # we need a few tricks to be able to restore data from other versions of Ruby
276 # When migrating 1.8.6 => 1.8.5, all we need to do is define an empty
277 # #marshal_load() method for Mutex. For 1.8.5 => 1.8.6 we need something
278 # dirtier, as seen later on in the initialization code.
279 unless Mutex.new.respond_to?(:marshal_load)
281 def marshal_load(str)
287 # Auxiliary method used to collect two lines for rss output filters,
288 # running substitutions against DataStream _s_ optionally joined
290 def make_stream(line1, line2, s, h={})
292 DataStream.new([line1, line2].compact.join("\n") % ss, ss)
295 # Define default RSS filters
297 # TODO: load personal ones
300 @bot.register_filter(:blog, @outkey) { |s|
301 author = s[:author] ? (s[:author] + " ") : ""
302 abt = s[:category] ? "about #{s[:category]} " : ""
303 line1 = "%{handle}%{date}%{author}blogged %{abt}at %{link}"
304 line2 = "%{handle}%{title} - %{desc}"
305 make_stream(line1, line2, s, :author => author, :abt => abt)
307 @bot.register_filter(:photoblog, @outkey) { |s|
308 author = s[:author] ? (s[:author] + " ") : ""
309 abt = s[:category] ? "under #{s[:category]} " : ""
310 line1 = "%{handle}%{date}%{author}added an image %{abt}at %{link}"
311 line2 = "%{handle}%{title} - %{desc}"
312 make_stream(line1, line2, s, :author => author, :abt => abt)
314 @bot.register_filter(:news, @outkey) { |s|
315 line1 = "%{handle}%{date}%{title} @ %{link}" % s
316 line2 = "%{handle}%{date}%{desc}" % s
317 make_stream(line1, line2, s)
319 @bot.register_filter(:git, @outkey) { |s|
320 author = s[:author] ? (s[:author] + " ") : ""
321 line1 = "%{handle}%{date}%{author}committed %{title} @ %{link}"
322 make_stream(line1, nil, s, :author => author)
324 @bot.register_filter(:forum, @outkey) { |s|
325 line1 = "%{handle}%{date}%{title}%{at}%{link}"
326 make_stream(line1, nil, s)
328 @bot.register_filter(:wiki, @outkey) { |s|
329 line1 = "%{handle}%{date}%{title}%{at}%{link}"
330 line1 << "has been edited by %{author}. %{desc}"
331 make_stream(line1, nil, s)
333 @bot.register_filter(:gmane, @outkey) { |s|
334 line1 = "%{handle}%{date}Message %{title} sent by %{author}. %{desc}"
335 make_stream(line1, nil, s)
337 @bot.register_filter(:trac, @outkey) { |s|
338 author = s[:author].sub(/@\S+?\s*>/, "@...>") + ": " if s[:author]
339 line1 = "%{handle}%{date}%{author}%{title} @ %{link}"
341 unless s[:item].title =~ /^(?:Changeset \[(?:[\da-f]+)\]|\(git commit\))/
342 line2 = "%{handle}%{date}%{desc}"
344 make_stream(line1, line2, s, :author => author)
346 @bot.register_filter(:"/.", @outkey) { |s|
347 dept = "(from the #{s[:item].slash_department} dept) " rescue nil
348 sec = " in section #{s[:item].slash_section}" rescue nil
349 line1 = "%{handle}%{date}%{dept}%{title}%{at}%{link} "
350 line1 << "(posted by %{author}%{sec})"
351 make_stream(line1, nil, s, :dept => dept, :sec => sec)
353 @bot.register_filter(:default, @outkey) { |s|
354 line1 = "%{handle}%{date}%{title}%{at}%{link}"
355 line1 << " (by %{author})" if s[:author]
356 make_stream(line1, nil, s)
359 # Define an HTML info filter too
360 @bot.register_filter(:rss, :htmlinfo) { |s| htmlinfo_filter(s) }
362 # This is the output format used by the input filter
363 @bot.register_filter(:htmlinfo, @outkey) { |s|
364 line1 = "%{title}%{at}%{link}"
365 make_stream(line1, nil, s)
369 FEED_NS = %r{xmlns.*http://(purl\.org/rss|www.w3c.org/1999/02/22-rdf)}
370 def htmlinfo_filter(s)
371 return nil unless s[:headers] and s[:headers]['x-rbot-location']
372 return nil unless s[:headers]['content-type'].first.match(/xml|rss|atom|rdf/i) or
373 (s[:text].include?("<rdf:RDF") and s[:text].include?("<channel")) or
374 s[:text].include?("<rss") or s[:text].include?("<feed") or
375 s[:text].match(FEED_NS)
376 blob = RssBlob.new(s[:headers]['x-rbot-location'],"", :htmlinfo)
377 unless (fetchRss(blob, nil) and parseRss(blob, nil) rescue nil)
378 debug "#{s.pretty_inspect} is not an RSS feed, despite the appearances"
382 blob.items.each { |it|
383 output << printFormattedRss(blob, it)[:text]
385 return {:title => blob.title, :content => output.join(" | ")}
388 # Display the known rss types
389 def rss_types(m, params)
390 ar = @bot.filter_names(@outkey)
392 m.reply ar.map { |k| k.to_s }.sort!.join(", ")
402 if @registry.has_key?(:feeds)
403 # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the
404 # data unrestorable. If this happens, we patch the data, thus allowing
405 # the restore to work.
407 # This is actually pretty safe for a number of reasons:
408 # * the code is only called if standard marshalling fails
409 # * the string we look for is quite unlikely to appear randomly
410 # * if the string appears somewhere and the patched string isn't recoverable
411 # either, we'll get another (unrecoverable) error, which makes the rss
412 # plugin unsable, just like it was if no recovery was attempted
413 # * if the string appears somewhere and the patched string is recoverable,
414 # we may get a b0rked feed, which is eventually overwritten by a clean
415 # one, so the worst thing that can happen is that a feed update spams
417 @registry.recovery = Proc.new { |val|
418 patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")
419 ret = Marshal.restore(patched)
420 ret.each_value { |blob|
426 @feeds = @registry[:feeds]
429 @registry.recovery = nil
431 @feeds.keys.grep(/[A-Z]/) { |k|
432 @feeds[k.downcase] = @feeds[k]
452 @feeds.select { |h, f| f.watched? }
461 unparsed = Hash.new()
464 # we don't want to save the mutex
465 unparsed[k].mutex = nil
467 @registry[:feeds] = unparsed
470 def stop_watch(handle)
471 if @watch.has_key?(handle)
473 debug "Stopping watch #{handle}"
474 @bot.timer.remove(@watch[handle])
475 @watch.delete(handle)
476 rescue Exception => e
477 report_problem("Failed to stop watch for #{handle}", e, nil)
483 @watch.each_key { |k|
488 def help(plugin,topic="")
491 "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"
493 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
495 "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
496 when "who", "watches", "who watches"
497 "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
499 "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})"
501 "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}"
502 when /^(del(ete)?|rm)$/
503 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
505 "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"
507 "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})"
509 "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"
511 "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
512 when /who(?: watche?s?)?/
513 "rss who watches #{Bold}handle#{Bold}: lists watches for rss #{Bold}handle#{Bold}"
515 "rss rewatch : restart threads that watch for changes in watched rss"
517 "rss types : show the rss types for which an output format existi (all other types will use the default one)"
519 "manage RSS feeds: rss types|show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch|who watches"
523 def report_problem(report, e=nil, m=nil)
524 if m && m.respond_to?(:reply)
531 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
535 def show_rss(m, params)
536 handle = params[:handle]
537 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
538 debug lims.to_a.inspect
540 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
541 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
542 rev = lims[1].to_i > lims[2].to_i
545 ul = [[lims[1].to_i-1, 0].max, 14].min
549 feed = @feeds.fetch(handle.downcase, nil)
551 m.reply "I don't know any feeds named #{handle}"
555 m.reply "lemme fetch it..."
557 we_were_watching = false
559 if @watch.key?(feed.handle)
560 # If a feed is being watched, we run the watcher thread
561 # so that all watchers can be informed of changes to
562 # the feed. Before we do that, though, we remove the
563 # show requester from the watchlist, if present, lest
564 # he gets the update twice.
565 if feed.watched_by?(m.replyto)
566 we_were_watching = true
567 feed.rm_watch(m.replyto)
569 @bot.timer.reschedule(@watch[feed.handle], 0)
571 feed.add_watch(m.replyto)
574 fetched = fetchRss(feed, m, false)
576 return unless fetched or feed.xml
577 if not fetched and feed.items
578 m.reply "using old data"
580 parsed = parseRss(feed, m)
581 m.reply "using old data" unless parsed
583 return unless feed.items
587 # We sort the feeds in freshness order (newer ones first)
588 items = freshness_sort(items)
592 m.reply "Channel : #{title}"
594 printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})
598 def itemDate(item,ex=nil)
599 return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
600 return item.date if item.respond_to?(:date) and item.date
604 def freshness_sort(items)
607 itemDate(b, notime) <=> itemDate(a, notime)
611 def list_rss(m, params)
612 wanted = params[:handle]
614 @feeds.each { |handle, feed|
615 next if wanted and !handle.match(/#{wanted}/i)
616 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
617 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
618 (reply << " (watched)") if feed.watched_by?(m.replyto)
622 reply = "no feeds found"
623 reply << " matching #{wanted}" if wanted
625 m.reply reply, :max_lines => reply.length
628 def watched_rss(m, params)
629 wanted = params[:handle]
630 chan = params[:chan] || m.replyto
632 watchlist.each { |handle, feed|
633 next if wanted and !handle.match(/#{wanted}/i)
634 next unless feed.watched_by?(chan)
635 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
636 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
640 reply = "no watched feeds"
641 reply << " matching #{wanted}" if wanted
646 def who_watches(m, params)
647 wanted = params[:handle]
649 watchlist.each { |handle, feed|
650 next if wanted and !handle.match(/#{wanted}/i)
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
653 reply << ": watched by #{feed.watchers.join(', ')}"
657 reply = "no watched feeds"
658 reply << " matching #{wanted}" if wanted
663 def add_rss(m, params, force=false)
664 handle = params[:handle]
666 unless url.match(/https?/)
667 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
671 if @feeds.fetch(handle.downcase, nil) && !force
672 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
676 m.reply "You must specify both a handle and an url to add an RSS feed"
679 @feeds[handle.downcase] = RssBlob.new(url,handle,type)
680 reply = "Added RSS #{url} named #{handle}"
682 reply << " (format: #{type})"
688 def change_rss(m, params)
689 handle = params[:handle].downcase
690 feed = @feeds.fetch(handle, nil)
692 m.reply "No such feed with handle #{handle}"
695 case params[:what].intern
697 new = params[:new].downcase
698 if @feeds.key?(new) and @feeds[new]
699 m.reply "There already is a feed with handle #{new}"
702 feed.mutex.synchronize do
704 @feeds.delete(handle)
711 feed.mutex.synchronize do
716 new = nil if new == 'default'
717 feed.mutex.synchronize do
721 new = params[:new].to_i
722 new = nil if new == 0
723 feed.mutex.synchronize do
724 feed.refresh_rate = new
727 m.reply "Don't know how to change #{params[:what]} for feeds"
730 m.reply "Feed changed:"
731 list_rss(m, {:handle => handle})
734 def del_rss(m, params, pass=false)
735 feed = unwatch_rss(m, params, true)
738 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
741 @feeds.delete(feed.handle.downcase)
746 def replace_rss(m, params)
747 handle = params[:handle]
748 if @feeds.key?(handle.downcase)
749 del_rss(m, {:handle => handle}, true)
751 if @feeds.key?(handle.downcase)
752 m.reply "can't replace #{feed.handle}"
754 add_rss(m, params, true)
758 def forcereplace_rss(m, params)
759 add_rss(m, params, true)
762 def watch_rss(m, params)
763 handle = params[:handle]
764 chan = params[:chan] || m.replyto
770 feed = @feeds.fetch(handle.downcase, nil)
772 if feed.add_watch(chan)
776 m.reply "Already watching #{feed.handle} in #{chan}"
779 m.reply "Couldn't watch feed #{handle} (no such feed found)"
783 def unwatch_rss(m, params, pass=false)
784 handle = params[:handle].downcase
785 chan = params[:chan] || m.replyto
786 unless @feeds.has_key?(handle)
787 m.reply("dunno that feed")
790 feed = @feeds[handle]
791 if feed.rm_watch(chan)
792 m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
794 m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
802 def rewatch_rss(m=nil, params=nil)
803 if params and handle = params[:handle]
804 feed = @feeds.fetch(handle.downcase, nil)
806 @bot.timer.reschedule(@watch[feed.handle], (params[:delay] || 0).to_f)
809 m.reply _("no such feed %{handle}") % { :handle => handle } if m
814 # Read watches from list.
815 watchlist.each{ |handle, feed|
823 def watchRss(feed, m=nil)
824 if @watch.has_key?(feed.handle)
825 report_problem("watcher thread for #{feed.handle} is already running", nil, m)
829 status[:failures] = 0
832 tmout = feed.last_fetched + calculate_timeout(feed) - Time.now
833 tmout = 0 if tmout < 0
835 debug "scheduling a watcher for #{feed} in #{tmout} seconds"
836 @watch[feed.handle] = @bot.timer.add(tmout) {
837 debug "watcher for #{feed} wakes up"
838 failures = status[:failures]
840 debug "fetching #{feed}"
841 first_run = !feed.last_fetched
842 oldxml = feed.xml ? feed.xml.dup : nil
843 unless fetchRss(feed)
847 debug "first run for #{feed}, getting items"
849 elsif oldxml and oldxml == feed.xml
850 debug "xml for #{feed} didn't change"
851 failures -= 1 if failures > 0
854 debug "no previous items in feed #{feed}"
856 failures -= 1 if failures > 0
858 # This one is used for debugging
861 # These are used for checking new items vs old ones
862 uid_opts = { :show_updated => @bot.config['rss.show_updated'] }
863 oids = Set.new feed.items.map { |item|
864 uid = RSS.item_uid_for_bot(item, uid_opts)
866 debug [uid, item].inspect
867 debug [uid, otxt.last].inspect
871 unless parseRss(feed)
872 debug "no items in feed #{feed}"
875 debug "Checking if new items are available for #{feed}"
876 failures -= 1 if failures > 0
882 dispItems = feed.items.reject { |item|
883 uid = RSS.item_uid_for_bot(item, uid_opts)
885 if oids.include?(uid)
886 debug "rejecting old #{uid} #{item.inspect}"
887 debug [uid, txt].inspect
890 debug "accepting new #{uid} #{item.inspect}"
891 debug [uid, txt].inspect
892 warning "same text! #{txt}" if otxt.include?(txt)
897 if dispItems.length > 0
898 debug "Found #{dispItems.length} new items in #{feed}"
899 # When displaying watched feeds, publish them from older to newer
900 dispItems.reverse.each { |item|
901 printFormattedRss(feed, item)
904 debug "No new items found in #{feed}"
910 rescue Exception => e
911 error "Error watching #{feed}: #{e.inspect}"
912 debug e.backtrace.join("\n")
916 status[:failures] = failures
918 seconds = calculate_timeout(feed, failures)
919 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
921 @bot.timer.reschedule(@watch[feed.handle], seconds)
923 warning "watcher for #{feed} failed to reschedule: #{$!.inspect}"
926 debug "watcher for #{feed} added"
929 def calculate_timeout(feed, failures = 0)
930 seconds = @bot.config['rss.thread_sleep']
931 feed.mutex.synchronize do
932 seconds = feed.refresh_rate if feed.refresh_rate
934 seconds *= failures + 1
935 seconds += seconds * (rand(100)-50)/100
939 def select_nonempty(*ar)
941 ret = ar.map { |i| (i && i.empty?) ? nil : i }.compact.first
942 (ret && ret.empty?) ? nil : ret
945 def printFormattedRss(feed, item, opts=nil)
947 places = feed.watchers
948 handle = feed.handle.empty? ? "" : "::#{feed.handle}:: "
951 places = opts[:places] if opts.key?(:places)
952 handle = opts[:handle].to_s if opts.key?(:handle)
953 if opts.key?(:date) && opts[:date]
954 if item.respond_to?(:updated)
955 if item.updated.content.class <= Time
956 date = item.updated.content.strftime("%Y/%m/%d %H:%M")
958 date = item.updated.content.to_s
960 elsif item.respond_to?(:source) and item.source.respond_to?(:updated)
961 if item.source.updated.content.class <= Time
962 date = item.source.updated.content.strftime("%Y/%m/%d %H:%M")
964 date = item.source.updated.content.to_s
966 elsif item.respond_to?(:pubDate)
967 if item.pubDate.class <= Time
968 date = item.pubDate.strftime("%Y/%m/%d %H:%M")
970 date = item.pubDate.to_s
972 elsif item.respond_to?(:date)
973 if item.date.class <= Time
974 date = item.date.strftime("%Y/%m/%d %H:%M")
976 date = item.date.to_s
986 # Twitters don't need a cap on the title length since they have a hard
987 # limit to 160 characters, and most of them are under 140 characters
988 tit_opt[:limit] = @bot.config['rss.head_max'] unless feed.type == 'twitter'
991 base_title = item.title.to_s.dup
992 # git changesets are SHA1 hashes (40 hex digits), way too long, get rid of them, as they are
993 # visible in the URL anyway
994 # TODO make this optional?
995 base_title.sub!(/^Changeset \[([\da-f]{40})\]:/) { |c| "(git commit)"} if feed.type == 'trac'
996 title = "#{Bold}#{base_title.ircify_html(tit_opt)}#{Bold}"
1000 desc_opt[:limit] = @bot.config['rss.text_max']
1001 desc_opt[:a_href] = :link_out if @bot.config['rss.show_links']
1003 # We prefer content_encoded here as it tends to provide more html formatting
1004 # for use with ircify_html.
1005 if item.respond_to?(:content_encoded) && item.content_encoded
1006 desc = item.content_encoded.ircify_html(desc_opt)
1007 elsif item.respond_to?(:description) && item.description
1008 desc = item.description.ircify_html(desc_opt)
1009 elsif item.respond_to?(:content) && item.content
1010 if item.content.type == "html"
1011 desc = item.content.content.ircify_html(desc_opt)
1013 desc = item.content.content
1014 if desc.size > desc_opt[:limit]
1015 desc = desc.slice(0, desc_opt[:limit]) + "#{Reverse}...#{Reverse}"
1022 link = item.link.href rescue item.link.chomp rescue nil
1024 category = select_nonempty((item.category.content rescue nil), (item.dc_subject rescue nil))
1025 author = select_nonempty((item.author.name.content rescue nil), (item.dc_creator rescue nil), (item.author rescue nil))
1030 at = ((item.title && item.link) ? ' @ ' : '')
1032 key = @bot.global_filter_name(feed.type, @outkey)
1033 key = @bot.global_filter_name(:default, @outkey) unless @bot.has_filter?(key)
1035 output = @bot.filter(key, :item => item, :handle => handle, :date => date,
1036 :title => title, :desc => desc, :link => link,
1037 :category => category, :author => author, :at => at)
1039 return output if places.empty?
1042 output.to_s.each_line { |line|
1043 @bot.say loc, line, :overlong => :truncate
1048 def fetchRss(feed, m=nil, cache=true)
1049 feed.last_fetched = Time.now
1051 # Use 60 sec timeout, cause the default is too low
1052 xml = @bot.httputil.get(feed.url,
1053 :read_timeout => 60,
1054 :open_timeout => 60,
1056 rescue URI::InvalidURIError, URI::BadURIError => e
1057 report_problem("invalid rss feed #{feed.url}", e, m)
1060 report_problem("error getting #{feed.url}", e, m)
1063 debug "fetched #{feed}"
1065 report_problem("reading feed #{feed} failed", nil, m)
1068 # Ok, 0.9 feeds are not supported, maybe because
1069 # Netscape happily removed the DTD. So what we do is just to
1070 # reassign the 0.9 RDFs to 1.0, and hope it goes right.
1071 xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",
1072 "xmlns=\"http://purl.org/rss/1.0/\"")
1073 feed.mutex.synchronize do
1079 def parseRss(feed, m=nil)
1080 return nil unless feed.xml
1081 feed.mutex.synchronize do
1084 ## do validate parse
1085 rss = RSS::Parser.parse(xml)
1086 debug "parsed and validated #{feed}"
1087 rescue RSS::InvalidRSSError
1088 ## do non validate parse for invalid RSS 1.0
1090 rss = RSS::Parser.parse(xml, false)
1091 debug "parsed but not validated #{feed}"
1092 rescue RSS::Error => e
1093 report_problem("parsing rss stream failed, whoops =(", e, m)
1096 rescue RSS::Error => e
1097 report_problem("parsing rss stream failed, oioi", e, m)
1100 report_problem("processing error occured, sorry =(", e, m)
1105 report_problem("#{feed} does not include RSS 1.0 or 0.9x/2.0", nil, m)
1108 rss.output_encoding = 'UTF-8'
1109 rescue RSS::UnknownConvertMethod => e
1110 report_problem("bah! something went wrong =(", e, m)
1113 if rss.respond_to? :channel
1114 rss.channel.title ||= "(?)"
1115 title = rss.channel.title
1117 title = rss.title.content
1119 rss.items.each do |item|
1120 item.title ||= "(?)"
1126 report_problem("no items found in the feed, maybe try weed?", e, m)
1136 plugin = RSSFeedsPlugin.new
1138 plugin.default_auth( 'edit', false )
1139 plugin.default_auth( 'edit:add', true)
1141 plugin.map 'rss show :handle :limit',
1142 :action => 'show_rss',
1143 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
1144 :defaults => {:limit => 5}
1145 plugin.map 'rss list :handle',
1146 :action => 'list_rss',
1147 :defaults => {:handle => nil}
1148 plugin.map 'rss watched :handle [in :chan]',
1149 :action => 'watched_rss',
1150 :defaults => {:handle => nil}
1151 plugin.map 'rss who watches :handle',
1152 :action => 'who_watches',
1153 :defaults => {:handle => nil}
1154 plugin.map 'rss add :handle :url :type',
1155 :action => 'add_rss',
1156 :auth_path => 'edit',
1157 :defaults => {:type => nil}
1158 plugin.map 'rss change :what of :handle to :new',
1159 :action => 'change_rss',
1160 :auth_path => 'edit',
1161 :requirements => { :what => /handle|url|format|type|refresh/ }
1162 plugin.map 'rss change :what for :handle to :new',
1163 :action => 'change_rss',
1164 :auth_path => 'edit',
1165 :requirements => { :what => /handle|url|format|type|refesh/ }
1166 plugin.map 'rss del :handle',
1167 :auth_path => 'edit:rm!',
1168 :action => 'del_rss'
1169 plugin.map 'rss delete :handle',
1170 :auth_path => 'edit:rm!',
1171 :action => 'del_rss'
1172 plugin.map 'rss rm :handle',
1173 :auth_path => 'edit:rm!',
1174 :action => 'del_rss'
1175 plugin.map 'rss replace :handle :url :type',
1176 :auth_path => 'edit',
1177 :action => 'replace_rss',
1178 :defaults => {:type => nil}
1179 plugin.map 'rss forcereplace :handle :url :type',
1180 :auth_path => 'edit',
1181 :action => 'forcereplace_rss',
1182 :defaults => {:type => nil}
1183 plugin.map 'rss watch :handle [in :chan]',
1184 :action => 'watch_rss',
1185 :defaults => {:url => nil, :type => nil}
1186 plugin.map 'rss watch :handle :url :type [in :chan]',
1187 :action => 'watch_rss',
1188 :defaults => {:url => nil, :type => nil}
1189 plugin.map 'rss unwatch :handle [in :chan]',
1190 :action => 'unwatch_rss'
1191 plugin.map 'rss rmwatch :handle [in :chan]',
1192 :action => 'unwatch_rss'
1193 plugin.map 'rss rewatch [:handle] [:delay]',
1194 :action => 'rewatch_rss'
1195 plugin.map 'rss types',
1196 :action => 'rss_types'