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)
166 :link => %w{link.href link},
167 :guid => %w{guid.content guid},
168 :content => %w{content.content content},
169 :description => %w{description.content description},
170 :title => %w{title.content title},
171 :category => %w{category.content category},
172 :dc_subject => %w{dc_subject},
173 :author => %w{author.name.content author.name author},
174 :dc_creator => %w{dc_creator}
175 }.each { |name, chain| def_bang name, chain }
178 return nil unless self.respond_to? :categories
179 cats = categories.map do |c|
180 blank2nil { c.content rescue c rescue nil }
182 cats.empty? ? nil : cats
186 def blank2nil(&block)
188 (x && !x.empty?) ? x : nil
195 attr_accessor :url, :handle, :type, :refresh_rate, :xml, :title, :items,
196 :mutex, :watchers, :last_fetched, :http_cache, :last_success
198 def initialize(url,handle=nil,type=nil,watchers=[], xml=nil, lf = nil)
215 sanitize_watchers(watchers)
219 @mutex.synchronize do
222 @type ? @type.dup : nil,
224 @xml ? @xml.dup : nil,
229 # Downcase all watchers, possibly turning them into Strings if they weren't
230 def sanitize_watchers(list=@watchers)
243 @watchers.include?(who.downcase)
250 @mutex.synchronize do
251 @watchers << who.downcase
257 @mutex.synchronize do
258 @watchers.delete(who.downcase)
263 [@handle,@url,@type,@refresh_rate,@watchers]
266 def to_s(watchers=false)
268 a = self.to_a.flatten
272 a.compact.join(" | ")
276 class RSSFeedsPlugin < Plugin
277 Config.register Config::IntegerValue.new('rss.head_max',
278 :default => 100, :validate => Proc.new{|v| v > 0 && v < 200},
279 :desc => "How many characters to use of a RSS item header")
281 Config.register Config::IntegerValue.new('rss.text_max',
282 :default => 200, :validate => Proc.new{|v| v > 0 && v < 400},
283 :desc => "How many characters to use of a RSS item text")
285 Config.register Config::IntegerValue.new('rss.thread_sleep',
286 :default => 300, :validate => Proc.new{|v| v > 30},
287 :desc => "How many seconds to sleep before checking RSS feeds again")
289 Config.register Config::IntegerValue.new('rss.announce_timeout',
291 :desc => "Don't announce watched feed if these many seconds elapsed since the last successful update")
293 Config.register Config::IntegerValue.new('rss.announce_max',
295 :desc => "Maximum number of new items to announce when a watched feed is updated")
297 Config.register Config::BooleanValue.new('rss.show_updated',
299 :desc => "Whether feed items for which the description was changed should be shown as new")
301 Config.register Config::BooleanValue.new('rss.show_links',
303 :desc => "Whether to display links from the text of a feed item.")
305 Config.register Config::EnumValue.new('rss.announce_method',
306 :values => ['say', 'notice'],
308 :desc => "Whether to display links from the text of a feed item.")
310 # Make an 'unique' ID for a given item, based on appropriate bot options
311 # Currently only suppored is bot.config['rss.show_updated']: when false,
312 # only the guid/link is accounted for.
315 uid = [item.guid! || item.link!]
316 if @bot.config['rss.show_updated']
317 uid.push(item.content! || item.description!)
318 uid.unshift item.title!
320 # debug "taking hash of #{uid.inspect}"
325 # We used to save the Mutex with the RssBlob, which was idiotic. And
326 # since Mutexes dumped in one version might not be restorable in another,
327 # we need a few tricks to be able to restore data from other versions of Ruby
329 # When migrating 1.8.6 => 1.8.5, all we need to do is define an empty
330 # #marshal_load() method for Mutex. For 1.8.5 => 1.8.6 we need something
331 # dirtier, as seen later on in the initialization code.
332 unless Mutex.new.respond_to?(:marshal_load)
334 def marshal_load(str)
340 # Auxiliary method used to collect two lines for rss output filters,
341 # running substitutions against DataStream _s_ optionally joined
344 # For substitutions, *_wrap keys can be used to alter the content of
345 # other nonempty keys. If the value of *_wrap is a String, it will be
346 # put before and after the corresponding key; if it's an Array, the first
347 # and second elements will be used for wrapping; if it's nil, no wrapping
348 # will be done (useful to override a default wrapping).
351 # :handle_wrap => '::'::
352 # will wrap s[:handle] by prefixing and postfixing it with '::'
353 # :date_wrap => [nil, ' :: ']::
354 # will put ' :: ' after s[:date]
355 def make_stream(line1, line2, s, h={})
360 kk = k.to_s.chomp!('_wrap')
365 wraps[nk] = ss[nk].wrap_nonempty(v, v)
367 wraps[nk] = ss[nk].wrap_nonempty(*v)
371 warning "ignoring #{v.inspect} wrapping of unknown class"
378 DataStream.new([line1, line2].compact.join("\n") % subs, ss)
381 # Auxiliary method used to define rss output filters
382 def rss_type(key, &block)
383 @bot.register_filter(key, @outkey, &block)
386 # Define default output filters (rss types), and load custom ones.
387 # Custom filters are looked for in the plugin's default filter locations
388 # and in rss/types.rb under botclass.
389 # Preferably, the rss_type method should be used in these files, e.g.:
390 # rss_type :my_type do |s|
391 # line1 = "%{handle} and some %{author} info"
392 # make_stream(line1, nil, s)
394 # to define the new type 'my_type'. The keys available in the DataStream
397 # the actual rss item
404 # desc, link, category, author::
405 # the item description, link, category, author
407 # the string ' @ ' if the item has both an title and a link
408 # handle_wrap, date_wrap, title_wrap, ...::
409 # these keys can be defined to wrap the corresponding elements if they
410 # are nonempty. By default handle is wrapped with '::', date has a ' ::'
411 # appended and title is enbolden
414 @outkey ||= :"rss.out"
416 # Define an HTML info filter
417 @bot.register_filter(:rss, :htmlinfo) { |s| htmlinfo_filter(s) }
418 # This is the output format used by the input filter
419 rss_type :htmlinfo do |s|
420 line1 = "%{title}%{at}%{link}"
421 make_stream(line1, nil, s)
425 rss_type :default do |s|
426 line1 = "%{handle}%{date}%{title}%{at}%{link}"
427 line1 << " (by %{author})" if s[:author]
428 make_stream(line1, nil, s)
431 @user_types ||= datafile 'types.rb'
433 load_filters :path => @user_types
436 FEED_NS = %r{xmlns.*http://(purl\.org/rss|www.w3c.org/1999/02/22-rdf)}
437 def htmlinfo_filter(s)
438 return nil unless s[:headers] and s[:headers]['x-rbot-location']
439 return nil unless s[:headers]['content-type'].first.match(/xml|rss|atom|rdf/i) or
440 (s[:text].include?("<rdf:RDF") and s[:text].include?("<channel")) or
441 s[:text].include?("<rss") or s[:text].include?("<feed") or
442 s[:text].match(FEED_NS)
443 blob = RssBlob.new(s[:headers]['x-rbot-location'],"", :htmlinfo)
444 unless (fetchRss(blob, nil) and parseRss(blob, nil) rescue nil)
445 debug "#{s.pretty_inspect} is not an RSS feed, despite the appearances"
449 blob.items.each { |it|
450 output << printFormattedRss(blob, it)[:text]
452 return {:title => blob.title, :content => output.join(" | ")}
455 # Display the known rss types
456 def rss_types(m, params)
457 ar = @bot.filter_names(@outkey)
459 m.reply ar.map { |k| k.to_s }.sort!.join(", ")
469 if @registry.has_key?(:feeds)
470 # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the
471 # data unrestorable. If this happens, we patch the data, thus allowing
472 # the restore to work.
474 # This is actually pretty safe for a number of reasons:
475 # * the code is only called if standard marshalling fails
476 # * the string we look for is quite unlikely to appear randomly
477 # * if the string appears somewhere and the patched string isn't recoverable
478 # either, we'll get another (unrecoverable) error, which makes the rss
479 # plugin unsable, just like it was if no recovery was attempted
480 # * if the string appears somewhere and the patched string is recoverable,
481 # we may get a b0rked feed, which is eventually overwritten by a clean
482 # one, so the worst thing that can happen is that a feed update spams
484 @registry.recovery = Proc.new { |val|
485 patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")
486 ret = Marshal.restore(patched)
487 ret.each_value { |blob|
493 @feeds = @registry[:feeds]
494 raise LoadError, "corrupted feed database" unless @feeds
496 @registry.recovery = nil
498 @feeds.keys.grep(/[A-Z]/) { |k|
499 @feeds[k.downcase] = @feeds[k]
519 @feeds.select { |h, f| f.watched? }
528 unparsed = Hash.new()
531 # we don't want to save the mutex
532 unparsed[k].mutex = nil
534 @registry[:feeds] = unparsed
537 def stop_watch(handle)
538 if @watch.has_key?(handle)
540 debug "Stopping watch #{handle}"
541 @bot.timer.remove(@watch[handle])
542 @watch.delete(handle)
543 rescue Exception => e
544 report_problem("Failed to stop watch for #{handle}", e, nil)
550 @watch.each_key { |k|
555 def help(plugin,topic="")
558 "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"
560 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
562 "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
563 when "who", "watches", "who watches"
564 "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
566 "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})"
568 "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}"
569 when /^(del(ete)?|rm)$/
570 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
572 "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"
574 "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})"
576 "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"
578 "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
579 when /who(?: watche?s?)?/
580 "rss who watches #{Bold}handle#{Bold}: lists watches for rss #{Bold}handle#{Bold}"
582 "rss rewatch : restart threads that watch for changes in watched rss"
584 "rss types : show the rss types for which an output format exist (all other types will use the default one)"
586 "manage RSS feeds: rss types|show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch|who watches"
590 def report_problem(report, e=nil, m=nil)
591 if m && m.respond_to?(:reply)
598 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
602 def show_rss(m, params)
603 handle = params[:handle]
604 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
605 debug lims.to_a.inspect
607 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
608 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
609 rev = lims[1].to_i > lims[2].to_i
612 ul = [[lims[1].to_i-1, 0].max, 14].min
616 feed = @feeds.fetch(handle.downcase, nil)
618 m.reply "I don't know any feeds named #{handle}"
622 m.reply "lemme fetch it..."
624 we_were_watching = false
626 if @watch.key?(feed.handle)
627 # If a feed is being watched, we run the watcher thread
628 # so that all watchers can be informed of changes to
629 # the feed. Before we do that, though, we remove the
630 # show requester from the watchlist, if present, lest
631 # he gets the update twice.
632 if feed.watched_by?(m.replyto)
633 we_were_watching = true
634 feed.rm_watch(m.replyto)
636 @bot.timer.reschedule(@watch[feed.handle], 0)
638 feed.add_watch(m.replyto)
641 fetched = fetchRss(feed, m, false)
643 return unless fetched or feed.xml
644 if fetched or not feed.items
645 parsed = parseRss(feed, m)
647 return unless feed.items
648 m.reply "using old data" unless fetched and parsed and parsed > 0
653 # We sort the feeds in freshness order (newer ones first)
654 items = freshness_sort(items)
658 m.reply "Channel : #{title}"
660 printFormattedRss(feed, item, {
661 :places => [m.replyto],
664 :announce_method => :say
669 def itemDate(item,ex=nil)
670 return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
671 return item.date if item.respond_to?(:date) and item.date
675 def freshness_sort(items)
678 itemDate(b, notime) <=> itemDate(a, notime)
682 def list_rss(m, params)
683 wanted = params[:handle]
686 wanted_rx = Regexp.new(wanted, true)
687 listed.reject! { |handle| !handle.match(wanted_rx) }
691 if @bot.config['send.max_lines'] > 0 and listed.size > @bot.config['send.max_lines']
692 reply = listed.inject([]) do |ar, handle|
693 feed = @feeds[handle]
695 (string << " (#{feed.type})") if feed.type
696 (string << " (watched)") if feed.watched_by?(m.replyto)
699 elsif listed.size > 0
700 reply = listed.inject([]) do |ar, handle|
701 feed = @feeds[handle]
702 string = "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
703 (string << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
704 (string << " (watched)") if feed.watched_by?(m.replyto)
708 reply = "no feeds found"
709 reply << " matching #{wanted}" if wanted
711 m.reply reply, :max_lines => 0
714 def watched_rss(m, params)
715 wanted = params[:handle]
716 chan = params[:chan] || m.replyto
718 watchlist.each { |handle, feed|
719 next if wanted and !handle.match(/#{wanted}/i)
720 next unless feed.watched_by?(chan)
721 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
722 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
726 reply = "no watched feeds"
727 reply << " matching #{wanted}" if wanted
732 def who_watches(m, params)
733 wanted = params[:handle]
735 watchlist.each { |handle, feed|
736 next if wanted and !handle.match(/#{wanted}/i)
737 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
738 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
739 reply << ": watched by #{feed.watchers.join(', ')}"
743 reply = "no watched feeds"
744 reply << " matching #{wanted}" if wanted
749 def add_rss(m, params, force=false)
750 handle = params[:handle]
752 unless url.match(/https?/)
753 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
757 if @feeds.fetch(handle.downcase, nil) && !force
758 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
762 m.reply "You must specify both a handle and an url to add an RSS feed"
765 @feeds[handle.downcase] = RssBlob.new(url,handle,type)
766 reply = "Added RSS #{url} named #{handle}"
768 reply << " (format: #{type})"
774 def change_rss(m, params)
775 handle = params[:handle].downcase
776 feed = @feeds.fetch(handle, nil)
778 m.reply "No such feed with handle #{handle}"
781 case params[:what].intern
783 new = params[:new].downcase
784 if @feeds.key?(new) and @feeds[new]
785 m.reply "There already is a feed with handle #{new}"
788 feed.mutex.synchronize do
790 @feeds.delete(handle)
797 feed.mutex.synchronize do
802 new = nil if new == 'default'
803 feed.mutex.synchronize do
807 new = params[:new].to_i
808 new = nil if new == 0
809 feed.mutex.synchronize do
810 feed.refresh_rate = new
813 m.reply "Don't know how to change #{params[:what]} for feeds"
816 m.reply "Feed changed:"
817 list_rss(m, {:handle => handle})
820 def del_rss(m, params, pass=false)
821 feed = unwatch_rss(m, params, true)
824 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
827 @feeds.delete(feed.handle.downcase)
832 def replace_rss(m, params)
833 handle = params[:handle]
834 if @feeds.key?(handle.downcase)
835 del_rss(m, {:handle => handle}, true)
837 if @feeds.key?(handle.downcase)
838 m.reply "can't replace #{feed.handle}"
840 add_rss(m, params, true)
844 def forcereplace_rss(m, params)
845 add_rss(m, params, true)
848 def watch_rss(m, params)
849 handle = params[:handle]
850 chan = params[:chan] || m.replyto
856 feed = @feeds.fetch(handle.downcase, nil)
858 if feed.add_watch(chan)
862 m.reply "Already watching #{feed.handle} in #{chan}"
865 m.reply "Couldn't watch feed #{handle} (no such feed found)"
869 def unwatch_rss(m, params, pass=false)
870 handle = params[:handle].downcase
871 chan = params[:chan] || m.replyto
872 unless @feeds.has_key?(handle)
873 m.reply("dunno that feed")
876 feed = @feeds[handle]
877 if feed.rm_watch(chan)
878 m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
880 m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
888 def rewatch_rss(m=nil, params=nil)
889 if params and handle = params[:handle]
890 feed = @feeds.fetch(handle.downcase, nil)
892 feed.http_cache = false
893 @bot.timer.reschedule(@watch[feed.handle], (params[:delay] || 0).to_f)
896 m.reply _("no such feed %{handle}") % { :handle => handle } if m
901 # Read watches from list.
902 watchlist.each{ |handle, feed|
910 def watchRss(feed, m=nil)
911 if @watch.has_key?(feed.handle)
912 # report_problem("watcher thread for #{feed.handle} is already running", nil, m)
916 status[:failures] = 0
919 tmout = feed.last_fetched + calculate_timeout(feed) - Time.now
920 tmout = 0 if tmout < 0
922 debug "scheduling a watcher for #{feed} in #{tmout} seconds"
923 @watch[feed.handle] = @bot.timer.add(tmout) {
924 debug "watcher for #{feed} wakes up"
925 failures = status[:failures]
927 debug "fetching #{feed}"
929 first_run = !feed.last_success
930 if (@bot.config['rss.announce_timeout'] > 0 &&
931 (Time.now - feed.last_success > @bot.config['rss.announce_timeout']))
932 debug "#{feed} wasn't polled for too long, supressing output"
935 oldxml = feed.xml ? feed.xml.dup : nil
936 unless fetchRss(feed, nil, feed.http_cache)
939 feed.http_cache = true
941 debug "first run for #{feed}, getting items"
943 elsif oldxml and oldxml == feed.xml
944 debug "xml for #{feed} didn't change"
945 failures -= 1 if failures > 0
947 # This one is used for debugging
953 # These are used for checking new items vs old ones
954 oids = Set.new feed.items.map { |item|
957 debug [uid, item].inspect
958 debug [uid, otxt.last].inspect
963 nitems = parseRss(feed)
967 debug "no items in feed #{feed}"
969 debug "Checking if new items are available for #{feed}"
970 failures -= 1 if failures > 0
976 dispItems = feed.items.reject { |item|
979 if oids.include?(uid)
980 debug "rejecting old #{uid} #{item.inspect}"
981 debug [uid, txt].inspect
984 debug "accepting new #{uid} #{item.inspect}"
985 debug [uid, txt].inspect
986 warning "same text! #{txt}" if otxt.include?(txt)
991 if dispItems.length > 0
992 max = @bot.config['rss.announce_max']
993 debug "Found #{dispItems.length} new items in #{feed}"
994 if max > 0 and dispItems.length > max
995 debug "showing only the latest #{dispItems.length}"
996 feed.watchers.each do |loc|
997 @bot.say loc, (_("feed %{feed} had %{num} updates, showing the latest %{max}") % {
998 :feed => feed.handle,
999 :num => dispItems.length,
1003 dispItems.slice!(max..-1)
1005 # When displaying watched feeds, publish them from older to newer
1006 dispItems.reverse.each { |item|
1007 printFormattedRss(feed, item)
1010 debug "No new items found in #{feed}"
1015 rescue Exception => e
1016 error "Error watching #{feed}: #{e.inspect}"
1017 debug e.backtrace.join("\n")
1021 status[:failures] = failures
1023 seconds = calculate_timeout(feed, failures)
1024 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
1026 @bot.timer.reschedule(@watch[feed.handle], seconds)
1028 warning "watcher for #{feed} failed to reschedule: #{$!.inspect}"
1031 debug "watcher for #{feed} added"
1034 def calculate_timeout(feed, failures = 0)
1035 seconds = @bot.config['rss.thread_sleep']
1036 feed.mutex.synchronize do
1037 seconds = feed.refresh_rate if feed.refresh_rate
1039 seconds *= failures + 1
1040 seconds += seconds * (rand(100)-50)/100
1045 if obj.kind_of? Time
1046 obj.strftime("%Y/%m/%d %H:%M")
1052 def printFormattedRss(feed, item, options={})
1055 :places => feed.watchers,
1056 :handle => feed.handle,
1058 :announce_method => @bot.config['rss.announce_method']
1061 places = opts[:places]
1062 announce_method = opts[:announce_method]
1064 handle = opts[:handle].to_s
1068 if item.respond_to?(:updated)
1069 make_date(item.updated.content)
1070 elsif item.respond_to?(:source) and item.source.respond_to?(:updated)
1071 make_date(item.source.updated.content)
1072 elsif item.respond_to?(:pubDate)
1073 make_date(item.pubDate)
1074 elsif item.respond_to?(:date)
1075 make_date(item.date)
1084 # Twitters don't need a cap on the title length since they have a hard
1085 # limit to 160 characters, and most of them are under 140 characters
1086 tit_opt[:limit] = @bot.config['rss.head_max'] unless feed.type == 'twitter'
1089 base_title = item.title.to_s.dup
1090 # git changesets are SHA1 hashes (40 hex digits), way too long, get rid of them, as they are
1091 # visible in the URL anyway
1092 # TODO make this optional?
1093 base_title.sub!(/^Changeset \[([\da-f]{40})\]:/) { |c| "(git commit)"} if feed.type == 'trac'
1094 title = base_title.ircify_html(tit_opt)
1098 desc_opt[:limit] = @bot.config['rss.text_max']
1099 desc_opt[:a_href] = :link_out if @bot.config['rss.show_links']
1101 # We prefer content_encoded here as it tends to provide more html formatting
1102 # for use with ircify_html.
1103 if item.respond_to?(:content_encoded) && item.content_encoded
1104 desc = item.content_encoded.ircify_html(desc_opt)
1105 elsif item.respond_to?(:description) && item.description
1106 desc = item.description.ircify_html(desc_opt)
1107 elsif item.respond_to?(:content) && item.content
1108 if item.content.type == "html"
1109 desc = item.content.content.ircify_html(desc_opt)
1111 desc = item.content.content
1112 if desc.size > desc_opt[:limit]
1113 desc = desc.slice(0, desc_opt[:limit]) + "#{Reverse}...#{Reverse}"
1123 categories = item.categories!
1124 category = item.category! || item.dc_subject!
1125 category.strip! if category
1126 author = item.dc_creator! || item.author!
1127 author.strip! if author
1132 at = ((item.title && item.link) ? ' @ ' : '')
1134 key = @bot.global_filter_name(feed.type, @outkey)
1135 key = @bot.global_filter_name(:default, @outkey) unless @bot.has_filter?(key)
1140 :handle_wrap => ['::', ':: '],
1142 :date_wrap => [nil, ' :: '],
1144 :title_wrap => Bold,
1145 :desc => desc, :link => link,
1146 :categories => categories,
1147 :category => category, :author => author, :at => at
1149 output = @bot.filter(key, stream_hash)
1151 return output if places.empty?
1154 output.to_s.each_line { |line|
1155 @bot.__send__(announce_method, loc, line, :overlong => :truncate)
1160 def fetchRss(feed, m=nil, cache=true)
1161 feed.last_fetched = Time.now
1163 # Use 60 sec timeout, cause the default is too low
1164 xml = @bot.httputil.get(feed.url,
1165 :read_timeout => 60,
1166 :open_timeout => 60,
1168 rescue URI::InvalidURIError, URI::BadURIError => e
1169 report_problem("invalid rss feed #{feed.url}", e, m)
1172 report_problem("error getting #{feed.url}", e, m)
1175 debug "fetched #{feed}"
1177 report_problem("reading feed #{feed} failed", nil, m)
1180 # Ok, 0.9 feeds are not supported, maybe because
1181 # Netscape happily removed the DTD. So what we do is just to
1182 # reassign the 0.9 RDFs to 1.0, and hope it goes right.
1183 xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",
1184 "xmlns=\"http://purl.org/rss/1.0/\"")
1185 # make sure the parser doesn't double-convert in case the feed is not UTF-8
1186 xml.sub!(/<\?xml (.*?)\?>/) do |match|
1187 if /\bencoding=(['"])(.*?)\1/.match(match)
1188 match.sub!(/\bencoding=(['"])(?:.*?)\1/,'encoding="UTF-8"')
1192 feed.mutex.synchronize do
1194 feed.last_success = Time.now
1199 def parseRss(feed, m=nil)
1200 return nil unless feed.xml
1201 feed.mutex.synchronize do
1205 RSS::AVAILABLE_PARSERS.each do |parser|
1207 ## do validate parse
1208 rss = RSS::Parser.parse(xml, true, true, parser)
1209 debug "parsed and validated #{feed} with #{parser}"
1211 rescue RSS::InvalidRSSError
1213 ## do non validate parse for invalid RSS 1.0
1214 rss = RSS::Parser.parse(xml, false, true, parser)
1215 debug "parsed but not validated #{feed} with #{parser}"
1217 rescue RSS::Error => e
1218 errors << [parser, e, "parsing rss stream failed, whoops =("]
1220 rescue RSS::Error => e
1221 errors << [parser, e, "parsing rss stream failed, oioi"]
1223 errors << [parser, e, "processing error occured, sorry =("]
1226 unless errors.empty?
1228 self.send(:report_problem, errors.last[2], errors.last[1], m)
1229 return nil unless rss
1233 if xml.match(/xmlns\s*=\s*(['"])http:\/\/www.w3.org\/2005\/Atom\1/) and not defined?(RSS::Atom)
1234 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)
1236 report_problem("#{feed.handle} @ #{feed.url} doesn't seem to contain an RSS or Atom feed I can read", nil, m)
1241 rss.output_encoding = 'UTF-8'
1242 rescue RSS::UnknownConvertMethod => e
1243 report_problem("bah! something went wrong =(", e, m)
1246 if rss.respond_to? :channel
1247 rss.channel.title ||= "(?)"
1248 title = rss.channel.title
1250 title = rss.title.content
1252 rss.items.each do |item|
1253 item.title ||= "(?)"
1259 report_problem("no items found in the feed, maybe try weed?", e, m)
1261 feed.title = title.strip
1269 plugin = RSSFeedsPlugin.new
1271 plugin.default_auth( 'edit', false )
1272 plugin.default_auth( 'edit:add', true)
1274 plugin.map 'rss show :handle :limit',
1275 :action => 'show_rss',
1276 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
1277 :defaults => {:limit => 5}
1278 plugin.map 'rss list :handle',
1279 :action => 'list_rss',
1280 :defaults => {:handle => nil}
1281 plugin.map 'rss watched :handle [in :chan]',
1282 :action => 'watched_rss',
1283 :defaults => {:handle => nil}
1284 plugin.map 'rss who watches :handle',
1285 :action => 'who_watches',
1286 :defaults => {:handle => nil}
1287 plugin.map 'rss add :handle :url :type',
1288 :action => 'add_rss',
1289 :auth_path => 'edit',
1290 :defaults => {:type => nil}
1291 plugin.map 'rss change :what of :handle to :new',
1292 :action => 'change_rss',
1293 :auth_path => 'edit',
1294 :requirements => { :what => /handle|url|format|type|refresh/ }
1295 plugin.map 'rss change :what for :handle to :new',
1296 :action => 'change_rss',
1297 :auth_path => 'edit',
1298 :requirements => { :what => /handle|url|format|type|refesh/ }
1299 plugin.map 'rss del :handle',
1300 :auth_path => 'edit:rm!',
1301 :action => 'del_rss'
1302 plugin.map 'rss delete :handle',
1303 :auth_path => 'edit:rm!',
1304 :action => 'del_rss'
1305 plugin.map 'rss rm :handle',
1306 :auth_path => 'edit:rm!',
1307 :action => 'del_rss'
1308 plugin.map 'rss replace :handle :url :type',
1309 :auth_path => 'edit',
1310 :action => 'replace_rss',
1311 :defaults => {:type => nil}
1312 plugin.map 'rss forcereplace :handle :url :type',
1313 :auth_path => 'edit',
1314 :action => 'forcereplace_rss',
1315 :defaults => {:type => nil}
1316 plugin.map 'rss watch :handle [in :chan]',
1317 :action => 'watch_rss',
1318 :defaults => {:url => nil, :type => nil}
1319 plugin.map 'rss watch :handle :url :type [in :chan]',
1320 :action => 'watch_rss',
1321 :defaults => {:url => nil, :type => nil}
1322 plugin.map 'rss unwatch :handle [in :chan]',
1323 :action => 'unwatch_rss'
1324 plugin.map 'rss rmwatch :handle [in :chan]',
1325 :action => 'unwatch_rss'
1326 plugin.map 'rss rewatch [:handle] [:delay]',
1327 :action => 'rewatch_rss'
1328 plugin.map 'rss types',
1329 :action => 'rss_types'