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}"}
156 def def_bang(name, chain)
159 blank2nil { #{chain.join(' rescue ')} rescue nil }
161 >, *get_file_and_line_from_caller(0)
165 # Atom categories are squashed to their label only
167 :link => %w{link.href link},
168 :guid => %w{guid.content guid},
169 :content => %w{content.content content},
170 :description => %w{description.content description},
171 :title => %w{title.content title},
172 :category => %w{category.content category.label category},
173 :dc_subject => %w{dc_subject},
174 :author => %w{author.name.content author.name author},
175 :dc_creator => %w{dc_creator}
176 }.each { |name, chain| def_bang name, chain }
179 return nil unless self.respond_to? :categories
180 cats = categories.map do |c|
181 blank2nil { c.content rescue c.label rescue c rescue nil }
183 cats.empty? ? nil : cats
187 def blank2nil(&block)
189 (x && !x.empty?) ? x : nil
196 attr_accessor :url, :handle, :type, :refresh_rate, :xml, :title, :items,
197 :mutex, :watchers, :last_fetched, :http_cache, :last_success
199 def initialize(url,handle=nil,type=nil,watchers=[], xml=nil, lf = nil)
216 sanitize_watchers(watchers)
220 @mutex.synchronize do
223 @type ? @type.dup : nil,
225 @xml ? @xml.dup : nil,
230 # Downcase all watchers, possibly turning them into Strings if they weren't
231 def sanitize_watchers(list=@watchers)
244 @watchers.include?(who.downcase)
251 @mutex.synchronize do
252 @watchers << who.downcase
258 @mutex.synchronize do
259 @watchers.delete(who.downcase)
264 [@handle,@url,@type,@refresh_rate,@watchers]
267 def to_s(watchers=false)
269 a = self.to_a.flatten
273 a.compact.join(" | ")
277 class RSSFeedsPlugin < Plugin
278 Config.register Config::IntegerValue.new('rss.head_max',
279 :default => 100, :validate => Proc.new{|v| v > 0 && v < 200},
280 :desc => "How many characters to use of a RSS item header")
282 Config.register Config::IntegerValue.new('rss.text_max',
283 :default => 200, :validate => Proc.new{|v| v > 0 && v < 400},
284 :desc => "How many characters to use of a RSS item text")
286 Config.register Config::IntegerValue.new('rss.thread_sleep',
287 :default => 300, :validate => Proc.new{|v| v > 30},
288 :desc => "How many seconds to sleep before checking RSS feeds again")
290 Config.register Config::IntegerValue.new('rss.announce_timeout',
292 :desc => "Don't announce watched feed if these many seconds elapsed since the last successful update")
294 Config.register Config::IntegerValue.new('rss.announce_max',
296 :desc => "Maximum number of new items to announce when a watched feed is updated")
298 Config.register Config::BooleanValue.new('rss.show_updated',
300 :desc => "Whether feed items for which the description was changed should be shown as new")
302 Config.register Config::BooleanValue.new('rss.show_links',
304 :desc => "Whether to display links from the text of a feed item.")
306 Config.register Config::EnumValue.new('rss.announce_method',
307 :values => ['say', 'notice'],
309 :desc => "Whether to display links from the text of a feed item.")
311 # Make an 'unique' ID for a given item, based on appropriate bot options
312 # Currently only suppored is bot.config['rss.show_updated']: when false,
313 # only the guid/link is accounted for.
316 uid = [item.guid! || item.link!]
317 if @bot.config['rss.show_updated']
318 uid.push(item.content! || item.description!)
319 uid.unshift item.title!
321 # debug "taking hash of #{uid.inspect}"
326 # We used to save the Mutex with the RssBlob, which was idiotic. And
327 # since Mutexes dumped in one version might not be restorable in another,
328 # we need a few tricks to be able to restore data from other versions of Ruby
330 # When migrating 1.8.6 => 1.8.5, all we need to do is define an empty
331 # #marshal_load() method for Mutex. For 1.8.5 => 1.8.6 we need something
332 # dirtier, as seen later on in the initialization code.
333 unless Mutex.new.respond_to?(:marshal_load)
335 def marshal_load(str)
341 # Auxiliary method used to collect two lines for rss output filters,
342 # running substitutions against DataStream _s_ optionally joined
345 # For substitutions, *_wrap keys can be used to alter the content of
346 # other nonempty keys. If the value of *_wrap is a String, it will be
347 # put before and after the corresponding key; if it's an Array, the first
348 # and second elements will be used for wrapping; if it's nil, no wrapping
349 # will be done (useful to override a default wrapping).
352 # :handle_wrap => '::'::
353 # will wrap s[:handle] by prefixing and postfixing it with '::'
354 # :date_wrap => [nil, ' :: ']::
355 # will put ' :: ' after s[:date]
356 def make_stream(line1, line2, s, h={})
361 kk = k.to_s.chomp!('_wrap')
366 wraps[nk] = ss[nk].wrap_nonempty(v, v)
368 wraps[nk] = ss[nk].wrap_nonempty(*v)
372 warning "ignoring #{v.inspect} wrapping of unknown class"
379 DataStream.new([line1, line2].compact.join("\n") % subs, ss)
382 # Auxiliary method used to define rss output filters
383 def rss_type(key, &block)
384 @bot.register_filter(key, @outkey, &block)
387 # Define default output filters (rss types), and load custom ones.
388 # Custom filters are looked for in the plugin's default filter locations
389 # and in rss/types.rb under botclass.
390 # Preferably, the rss_type method should be used in these files, e.g.:
391 # rss_type :my_type do |s|
392 # line1 = "%{handle} and some %{author} info"
393 # make_stream(line1, nil, s)
395 # to define the new type 'my_type'. The keys available in the DataStream
398 # the actual rss item
405 # desc, link, category, author::
406 # the item description, link, category, author
408 # the string ' @ ' if the item has both an title and a link
409 # handle_wrap, date_wrap, title_wrap, ...::
410 # these keys can be defined to wrap the corresponding elements if they
411 # are nonempty. By default handle is wrapped with '::', date has a ' ::'
412 # appended and title is enbolden
415 @outkey ||= :"rss.out"
417 # Define an HTML info filter
418 @bot.register_filter(:rss, :htmlinfo) { |s| htmlinfo_filter(s) }
419 # This is the output format used by the input filter
420 rss_type :htmlinfo do |s|
421 line1 = "%{title}%{at}%{link}"
422 make_stream(line1, nil, s)
426 rss_type :default do |s|
427 line1 = "%{handle}%{date}%{title}%{at}%{link}"
428 line1 << " (by %{author})" if s[:author]
429 make_stream(line1, nil, s)
432 @user_types ||= datafile 'types.rb'
434 load_filters :path => @user_types
437 FEED_NS = %r{xmlns.*http://(purl\.org/rss|www.w3c.org/1999/02/22-rdf)}
438 def htmlinfo_filter(s)
439 return nil unless s[:headers] and s[:headers]['x-rbot-location']
440 return nil unless s[:headers]['content-type'].first.match(/xml|rss|atom|rdf/i) or
441 (s[:text].include?("<rdf:RDF") and s[:text].include?("<channel")) or
442 s[:text].include?("<rss") or s[:text].include?("<feed") or
443 s[:text].match(FEED_NS)
444 blob = RssBlob.new(s[:headers]['x-rbot-location'],"", :htmlinfo)
445 unless (fetchRss(blob, nil) and parseRss(blob, nil) rescue nil)
446 debug "#{s.pretty_inspect} is not an RSS feed, despite the appearances"
450 blob.items.each { |it|
451 output << printFormattedRss(blob, it)[:text]
453 return {:title => blob.title, :content => output.join(" | ")}
456 # Display the known rss types
457 def rss_types(m, params)
458 ar = @bot.filter_names(@outkey)
460 m.reply ar.map { |k| k.to_s }.sort!.join(", ")
470 if @registry.has_key?(:feeds)
471 # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the
472 # data unrestorable. If this happens, we patch the data, thus allowing
473 # the restore to work.
475 # This is actually pretty safe for a number of reasons:
476 # * the code is only called if standard marshalling fails
477 # * the string we look for is quite unlikely to appear randomly
478 # * if the string appears somewhere and the patched string isn't recoverable
479 # either, we'll get another (unrecoverable) error, which makes the rss
480 # plugin unsable, just like it was if no recovery was attempted
481 # * if the string appears somewhere and the patched string is recoverable,
482 # we may get a b0rked feed, which is eventually overwritten by a clean
483 # one, so the worst thing that can happen is that a feed update spams
485 @registry.recovery = Proc.new { |val|
486 patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")
487 ret = Marshal.restore(patched)
488 ret.each_value { |blob|
494 @feeds = @registry[:feeds]
495 raise LoadError, "corrupted feed database" unless @feeds
497 @registry.recovery = nil
499 @feeds.keys.grep(/[A-Z]/) { |k|
500 @feeds[k.downcase] = @feeds[k]
520 @feeds.select { |h, f| f.watched? }
529 unparsed = Hash.new()
532 # we don't want to save the mutex
533 unparsed[k].mutex = nil
535 @registry[:feeds] = unparsed
538 def stop_watch(handle)
539 if @watch.has_key?(handle)
541 debug "Stopping watch #{handle}"
542 @bot.timer.remove(@watch[handle])
543 @watch.delete(handle)
544 rescue Exception => e
545 report_problem("Failed to stop watch for #{handle}", e, nil)
551 @watch.each_key { |k|
556 def help(plugin,topic="")
559 "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"
561 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
563 "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
564 when "who", "watches", "who watches"
565 "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
567 "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})"
569 "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}"
570 when /^(del(ete)?|rm)$/
571 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
573 "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"
575 "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})"
577 "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"
579 "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
580 when /who(?: watche?s?)?/
581 "rss who watches #{Bold}handle#{Bold}: lists watches for rss #{Bold}handle#{Bold}"
583 "rss rewatch : restart threads that watch for changes in watched rss"
585 "rss types : show the rss types for which an output format exist (all other types will use the default one)"
587 "manage RSS feeds: rss types|show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch|who watches"
591 def report_problem(report, e=nil, m=nil)
592 if m && m.respond_to?(:reply)
599 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
603 def show_rss(m, params)
604 handle = params[:handle]
605 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
606 debug lims.to_a.inspect
608 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
609 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
610 rev = lims[1].to_i > lims[2].to_i
613 ul = [[lims[1].to_i-1, 0].max, 14].min
617 feed = @feeds.fetch(handle.downcase, nil)
619 m.reply "I don't know any feeds named #{handle}"
623 m.reply "lemme fetch it..."
625 we_were_watching = false
627 if @watch.key?(feed.handle)
628 # If a feed is being watched, we run the watcher thread
629 # so that all watchers can be informed of changes to
630 # the feed. Before we do that, though, we remove the
631 # show requester from the watchlist, if present, lest
632 # he gets the update twice.
633 if feed.watched_by?(m.replyto)
634 we_were_watching = true
635 feed.rm_watch(m.replyto)
637 @bot.timer.reschedule(@watch[feed.handle], 0)
639 feed.add_watch(m.replyto)
642 fetched = fetchRss(feed, m, false)
644 return unless fetched or feed.xml
645 if fetched or not feed.items
646 parsed = parseRss(feed, m)
648 return unless feed.items
649 m.reply "using old data" unless fetched and parsed and parsed > 0
654 # We sort the feeds in freshness order (newer ones first)
655 items = freshness_sort(items)
659 m.reply "Channel : #{title}"
661 printFormattedRss(feed, item, {
662 :places => [m.replyto],
665 :announce_method => :say
670 def itemDate(item,ex=nil)
671 return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
672 return item.date if item.respond_to?(:date) and item.date
676 def freshness_sort(items)
679 itemDate(b, notime) <=> itemDate(a, notime)
683 def list_rss(m, params)
684 wanted = params[:handle]
687 wanted_rx = Regexp.new(wanted, true)
688 listed.reject! { |handle| !handle.match(wanted_rx) }
692 if @bot.config['send.max_lines'] > 0 and listed.size > @bot.config['send.max_lines']
693 reply = listed.inject([]) do |ar, handle|
694 feed = @feeds[handle]
696 (string << " (#{feed.type})") if feed.type
697 (string << " (watched)") if feed.watched_by?(m.replyto)
700 elsif listed.size > 0
701 reply = listed.inject([]) do |ar, handle|
702 feed = @feeds[handle]
703 string = "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
704 (string << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
705 (string << " (watched)") if feed.watched_by?(m.replyto)
709 reply = "no feeds found"
710 reply << " matching #{wanted}" if wanted
712 m.reply reply, :max_lines => 0
715 def watched_rss(m, params)
716 wanted = params[:handle]
717 chan = params[:chan] || m.replyto
719 watchlist.each { |handle, feed|
720 next if wanted and !handle.match(/#{wanted}/i)
721 next unless feed.watched_by?(chan)
722 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
723 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
727 reply = "no watched feeds"
728 reply << " matching #{wanted}" if wanted
733 def who_watches(m, params)
734 wanted = params[:handle]
736 watchlist.each { |handle, feed|
737 next if wanted and !handle.match(/#{wanted}/i)
738 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
739 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
740 reply << ": watched by #{feed.watchers.join(', ')}"
744 reply = "no watched feeds"
745 reply << " matching #{wanted}" if wanted
750 def add_rss(m, params, force=false)
751 handle = params[:handle]
753 unless url.match(/https?/)
754 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
758 if @feeds.fetch(handle.downcase, nil) && !force
759 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
763 m.reply "You must specify both a handle and an url to add an RSS feed"
766 @feeds[handle.downcase] = RssBlob.new(url,handle,type)
767 reply = "Added RSS #{url} named #{handle}"
769 reply << " (format: #{type})"
775 def change_rss(m, params)
776 handle = params[:handle].downcase
777 feed = @feeds.fetch(handle, nil)
779 m.reply "No such feed with handle #{handle}"
782 case params[:what].intern
784 # preserve rename case, but beware of key
785 realnew = params[:new]
786 new = realnew.downcase
787 if feed.handle.downcase == new
788 if feed.handle == realnew
789 m.reply _("You want me to rename %{handle} to itself?") % {
790 :handle => feed.handle
794 feed.mutex.synchronize do
795 feed.handle = realnew
798 elsif @feeds.key?(new) and @feeds[new]
799 m.reply "There already is a feed with handle #{new}"
802 feed.mutex.synchronize do
804 @feeds.delete(handle)
805 feed.handle = realnew
811 feed.mutex.synchronize do
816 new = nil if new == 'default'
817 feed.mutex.synchronize do
821 new = params[:new].to_i
822 new = nil if new == 0
823 feed.mutex.synchronize do
824 feed.refresh_rate = new
827 m.reply "Don't know how to change #{params[:what]} for feeds"
830 m.reply "Feed changed:"
831 list_rss(m, {:handle => handle})
834 def del_rss(m, params, pass=false)
835 feed = unwatch_rss(m, params, true)
838 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
841 @feeds.delete(feed.handle.downcase)
846 def replace_rss(m, params)
847 handle = params[:handle]
848 if @feeds.key?(handle.downcase)
849 del_rss(m, {:handle => handle}, true)
851 if @feeds.key?(handle.downcase)
852 m.reply "can't replace #{feed.handle}"
854 add_rss(m, params, true)
858 def forcereplace_rss(m, params)
859 add_rss(m, params, true)
862 def watch_rss(m, params)
863 handle = params[:handle]
864 chan = params[:chan] || m.replyto
870 feed = @feeds.fetch(handle.downcase, nil)
872 if feed.add_watch(chan)
876 m.reply "Already watching #{feed.handle} in #{chan}"
879 m.reply "Couldn't watch feed #{handle} (no such feed found)"
883 def unwatch_rss(m, params, pass=false)
884 handle = params[:handle].downcase
885 chan = params[:chan] || m.replyto
886 unless @feeds.has_key?(handle)
887 m.reply("dunno that feed")
890 feed = @feeds[handle]
891 if feed.rm_watch(chan)
892 m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
894 m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
902 def rewatch_rss(m=nil, params=nil)
903 if params and handle = params[:handle]
904 feed = @feeds.fetch(handle.downcase, nil)
906 feed.http_cache = false
907 @bot.timer.reschedule(@watch[feed.handle], (params[:delay] || 0).to_f)
910 m.reply _("no such feed %{handle}") % { :handle => handle } if m
915 # Read watches from list.
916 watchlist.each{ |handle, feed|
924 def watchRss(feed, m=nil)
925 if @watch.has_key?(feed.handle)
926 # report_problem("watcher thread for #{feed.handle} is already running", nil, m)
930 status[:failures] = 0
933 tmout = feed.last_fetched + calculate_timeout(feed) - Time.now
934 tmout = 0 if tmout < 0
936 debug "scheduling a watcher for #{feed} in #{tmout} seconds"
937 @watch[feed.handle] = @bot.timer.add(tmout) {
938 debug "watcher for #{feed} wakes up"
939 failures = status[:failures]
941 debug "fetching #{feed}"
943 first_run = !feed.last_success
944 if (!first_run && @bot.config['rss.announce_timeout'] > 0 &&
945 (Time.now - feed.last_success > @bot.config['rss.announce_timeout']))
946 debug "#{feed} wasn't polled for too long, supressing output"
949 oldxml = feed.xml ? feed.xml.dup : nil
950 unless fetchRss(feed, nil, feed.http_cache)
953 feed.http_cache = true
955 debug "first run for #{feed}, getting items"
957 elsif oldxml and oldxml == feed.xml
958 debug "xml for #{feed} didn't change"
959 failures -= 1 if failures > 0
961 # This one is used for debugging
967 # These are used for checking new items vs old ones
968 oids = Set.new feed.items.map { |item|
971 debug [uid, item].inspect
972 debug [uid, otxt.last].inspect
977 nitems = parseRss(feed)
981 debug "no items in feed #{feed}"
983 debug "Checking if new items are available for #{feed}"
984 failures -= 1 if failures > 0
990 dispItems = feed.items.reject { |item|
993 if oids.include?(uid)
994 debug "rejecting old #{uid} #{item.inspect}"
995 debug [uid, txt].inspect
998 debug "accepting new #{uid} #{item.inspect}"
999 debug [uid, txt].inspect
1000 warning "same text! #{txt}" if otxt.include?(txt)
1005 if dispItems.length > 0
1006 max = @bot.config['rss.announce_max']
1007 debug "Found #{dispItems.length} new items in #{feed}"
1008 if max > 0 and dispItems.length > max
1009 debug "showing only the latest #{dispItems.length}"
1010 feed.watchers.each do |loc|
1011 @bot.say loc, (_("feed %{feed} had %{num} updates, showing the latest %{max}") % {
1012 :feed => feed.handle,
1013 :num => dispItems.length,
1017 dispItems.slice!(max..-1)
1019 # When displaying watched feeds, publish them from older to newer
1020 dispItems.reverse.each { |item|
1021 printFormattedRss(feed, item)
1024 debug "No new items found in #{feed}"
1029 rescue Exception => e
1030 error "Error watching #{feed}: #{e.inspect}"
1031 debug e.backtrace.join("\n")
1035 status[:failures] = failures
1037 seconds = calculate_timeout(feed, failures)
1038 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
1040 @bot.timer.reschedule(@watch[feed.handle], seconds)
1042 warning "watcher for #{feed} failed to reschedule: #{$!.inspect}"
1045 debug "watcher for #{feed} added"
1048 def calculate_timeout(feed, failures = 0)
1049 seconds = @bot.config['rss.thread_sleep']
1050 feed.mutex.synchronize do
1051 seconds = feed.refresh_rate if feed.refresh_rate
1053 seconds *= failures + 1
1054 seconds += seconds * (rand(100)-50)/100
1059 if obj.kind_of? Time
1060 obj.strftime("%Y/%m/%d %H:%M")
1066 def printFormattedRss(feed, item, options={})
1069 :places => feed.watchers,
1070 :handle => feed.handle,
1072 :announce_method => @bot.config['rss.announce_method']
1075 places = opts[:places]
1076 announce_method = opts[:announce_method]
1078 handle = opts[:handle].to_s
1082 if item.respond_to?(:updated)
1083 make_date(item.updated.content)
1084 elsif item.respond_to?(:source) and item.source.respond_to?(:updated)
1085 make_date(item.source.updated.content)
1086 elsif item.respond_to?(:pubDate)
1087 make_date(item.pubDate)
1088 elsif item.respond_to?(:date)
1089 make_date(item.date)
1098 # Twitters don't need a cap on the title length since they have a hard
1099 # limit to 160 characters, and most of them are under 140 characters
1100 tit_opt[:limit] = @bot.config['rss.head_max'] unless feed.type == 'twitter'
1103 base_title = item.title.to_s.dup
1104 # git changesets are SHA1 hashes (40 hex digits), way too long, get rid of them, as they are
1105 # visible in the URL anyway
1106 # TODO make this optional?
1107 base_title.sub!(/^Changeset \[([\da-f]{40})\]:/) { |c| "(git commit)"} if feed.type == 'trac'
1108 title = base_title.ircify_html(tit_opt)
1112 desc_opt[:limit] = @bot.config['rss.text_max']
1113 desc_opt[:a_href] = :link_out if @bot.config['rss.show_links']
1115 # We prefer content_encoded here as it tends to provide more html formatting
1116 # for use with ircify_html.
1117 if item.respond_to?(:content_encoded) && item.content_encoded
1118 desc = item.content_encoded.ircify_html(desc_opt)
1119 elsif item.respond_to?(:description) && item.description
1120 desc = item.description.ircify_html(desc_opt)
1121 elsif item.respond_to?(:content) && item.content
1122 if item.content.type == "html"
1123 desc = item.content.content.ircify_html(desc_opt)
1125 desc = item.content.content
1126 if desc.size > desc_opt[:limit]
1127 desc = desc.slice(0, desc_opt[:limit]) + "#{Reverse}...#{Reverse}"
1137 categories = item.categories!
1138 category = item.category! || item.dc_subject!
1139 category.strip! if category
1140 author = item.dc_creator! || item.author!
1141 author.strip! if author
1146 at = ((item.title && item.link) ? ' @ ' : '')
1148 key = @bot.global_filter_name(feed.type, @outkey)
1149 key = @bot.global_filter_name(:default, @outkey) unless @bot.has_filter?(key)
1154 :handle_wrap => ['::', ':: '],
1156 :date_wrap => [nil, ' :: '],
1158 :title_wrap => Bold,
1159 :desc => desc, :link => link,
1160 :categories => categories,
1161 :category => category, :author => author, :at => at
1163 output = @bot.filter(key, stream_hash)
1165 return output if places.empty?
1168 output.to_s.each_line { |line|
1169 @bot.__send__(announce_method, loc, line, :overlong => :truncate)
1174 def fetchRss(feed, m=nil, cache=true)
1175 feed.last_fetched = Time.now
1177 # Use 60 sec timeout, cause the default is too low
1178 xml = @bot.httputil.get(feed.url,
1179 :read_timeout => 60,
1180 :open_timeout => 60,
1182 rescue URI::InvalidURIError, URI::BadURIError => e
1183 report_problem("invalid rss feed #{feed.url}", e, m)
1186 report_problem("error getting #{feed.url}", e, m)
1189 debug "fetched #{feed}"
1191 report_problem("reading feed #{feed} failed", nil, m)
1194 # Ok, 0.9 feeds are not supported, maybe because
1195 # Netscape happily removed the DTD. So what we do is just to
1196 # reassign the 0.9 RDFs to 1.0, and hope it goes right.
1197 xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",
1198 "xmlns=\"http://purl.org/rss/1.0/\"")
1199 # make sure the parser doesn't double-convert in case the feed is not UTF-8
1200 xml.sub!(/<\?xml (.*?)\?>/) do |match|
1201 if /\bencoding=(['"])(.*?)\1/.match(match)
1202 match.sub!(/\bencoding=(['"])(?:.*?)\1/,'encoding="UTF-8"')
1206 feed.mutex.synchronize do
1208 feed.last_success = Time.now
1213 def parseRss(feed, m=nil)
1214 return nil unless feed.xml
1215 feed.mutex.synchronize do
1219 RSS::AVAILABLE_PARSERS.each do |parser|
1221 ## do validate parse
1222 rss = RSS::Parser.parse(xml, true, true, parser)
1223 debug "parsed and validated #{feed} with #{parser}"
1225 rescue RSS::InvalidRSSError
1227 ## do non validate parse for invalid RSS 1.0
1228 rss = RSS::Parser.parse(xml, false, true, parser)
1229 debug "parsed but not validated #{feed} with #{parser}"
1231 rescue RSS::Error => e
1232 errors << [parser, e, "parsing rss stream failed, whoops =("]
1234 rescue RSS::Error => e
1235 errors << [parser, e, "parsing rss stream failed, oioi"]
1237 errors << [parser, e, "processing error occured, sorry =("]
1240 unless errors.empty?
1242 self.send(:report_problem, errors.last[2], errors.last[1], m)
1243 return nil unless rss
1247 if xml.match(/xmlns\s*=\s*(['"])http:\/\/www.w3.org\/2005\/Atom\1/) and not defined?(RSS::Atom)
1248 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)
1250 report_problem("#{feed.handle} @ #{feed.url} doesn't seem to contain an RSS or Atom feed I can read", nil, m)
1255 rss.output_encoding = 'UTF-8'
1256 rescue RSS::UnknownConvertMethod => e
1257 report_problem("bah! something went wrong =(", e, m)
1260 if rss.respond_to? :channel
1261 rss.channel.title ||= "(?)"
1262 title = rss.channel.title
1264 title = rss.title.content
1266 rss.items.each do |item|
1267 item.title ||= "(?)"
1273 report_problem("no items found in the feed, maybe try weed?", e, m)
1275 feed.title = title.strip
1283 plugin = RSSFeedsPlugin.new
1285 plugin.default_auth( 'edit', false )
1286 plugin.default_auth( 'edit:add', true)
1288 plugin.map 'rss show :handle :limit',
1289 :action => 'show_rss',
1290 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
1291 :defaults => {:limit => 5}
1292 plugin.map 'rss list :handle',
1293 :action => 'list_rss',
1294 :defaults => {:handle => nil}
1295 plugin.map 'rss watched :handle [in :chan]',
1296 :action => 'watched_rss',
1297 :defaults => {:handle => nil}
1298 plugin.map 'rss who watches :handle',
1299 :action => 'who_watches',
1300 :defaults => {:handle => nil}
1301 plugin.map 'rss add :handle :url :type',
1302 :action => 'add_rss',
1303 :auth_path => 'edit',
1304 :defaults => {:type => nil}
1305 plugin.map 'rss change :what of :handle to :new',
1306 :action => 'change_rss',
1307 :auth_path => 'edit',
1308 :requirements => { :what => /handle|url|format|type|refresh/ }
1309 plugin.map 'rss change :what for :handle to :new',
1310 :action => 'change_rss',
1311 :auth_path => 'edit',
1312 :requirements => { :what => /handle|url|format|type|refesh/ }
1313 plugin.map 'rss del :handle',
1314 :auth_path => 'edit:rm!',
1315 :action => 'del_rss'
1316 plugin.map 'rss delete :handle',
1317 :auth_path => 'edit:rm!',
1318 :action => 'del_rss'
1319 plugin.map 'rss rm :handle',
1320 :auth_path => 'edit:rm!',
1321 :action => 'del_rss'
1322 plugin.map 'rss replace :handle :url :type',
1323 :auth_path => 'edit',
1324 :action => 'replace_rss',
1325 :defaults => {:type => nil}
1326 plugin.map 'rss forcereplace :handle :url :type',
1327 :auth_path => 'edit',
1328 :action => 'forcereplace_rss',
1329 :defaults => {:type => nil}
1330 plugin.map 'rss watch :handle [in :chan]',
1331 :action => 'watch_rss',
1332 :defaults => {:url => nil, :type => nil}
1333 plugin.map 'rss watch :handle :url :type [in :chan]',
1334 :action => 'watch_rss',
1335 :defaults => {:url => nil, :type => nil}
1336 plugin.map 'rss unwatch :handle [in :chan]',
1337 :action => 'unwatch_rss'
1338 plugin.map 'rss rmwatch :handle [in :chan]',
1339 :action => 'unwatch_rss'
1340 plugin.map 'rss rewatch [:handle] [:delay]',
1341 :action => 'rewatch_rss'
1342 plugin.map 'rss types',
1343 :action => 'rss_types'