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 def blank2nil(&block)
180 (x && !x.empty?) ? x : nil
187 attr_accessor :url, :handle, :type, :refresh_rate, :xml, :title, :items,
188 :mutex, :watchers, :last_fetched, :http_cache, :last_success
190 def initialize(url,handle=nil,type=nil,watchers=[], xml=nil, lf = nil)
207 sanitize_watchers(watchers)
211 @mutex.synchronize do
214 @type ? @type.dup : nil,
216 @xml ? @xml.dup : nil,
221 # Downcase all watchers, possibly turning them into Strings if they weren't
222 def sanitize_watchers(list=@watchers)
235 @watchers.include?(who.downcase)
242 @mutex.synchronize do
243 @watchers << who.downcase
249 @mutex.synchronize do
250 @watchers.delete(who.downcase)
255 [@handle,@url,@type,@refresh_rate,@watchers]
258 def to_s(watchers=false)
260 a = self.to_a.flatten
264 a.compact.join(" | ")
268 class RSSFeedsPlugin < Plugin
269 Config.register Config::IntegerValue.new('rss.head_max',
270 :default => 100, :validate => Proc.new{|v| v > 0 && v < 200},
271 :desc => "How many characters to use of a RSS item header")
273 Config.register Config::IntegerValue.new('rss.text_max',
274 :default => 200, :validate => Proc.new{|v| v > 0 && v < 400},
275 :desc => "How many characters to use of a RSS item text")
277 Config.register Config::IntegerValue.new('rss.thread_sleep',
278 :default => 300, :validate => Proc.new{|v| v > 30},
279 :desc => "How many seconds to sleep before checking RSS feeds again")
281 Config.register Config::IntegerValue.new('rss.announce_timeout',
283 :desc => "Don't announce watched feed if these many seconds elapsed since the last successful update")
285 Config.register Config::IntegerValue.new('rss.announce_max',
287 :desc => "Maximum number of new items to announce when a watched feed is updated")
289 Config.register Config::BooleanValue.new('rss.show_updated',
291 :desc => "Whether feed items for which the description was changed should be shown as new")
293 Config.register Config::BooleanValue.new('rss.show_links',
295 :desc => "Whether to display links from the text of a feed item.")
297 Config.register Config::EnumValue.new('rss.announce_method',
298 :values => ['say', 'notice'],
300 :desc => "Whether to display links from the text of a feed item.")
302 # Make an 'unique' ID for a given item, based on appropriate bot options
303 # Currently only suppored is bot.config['rss.show_updated']: when false,
304 # only the guid/link is accounted for.
307 uid = [item.guid! || item.link!]
308 if @bot.config['rss.show_updated']
309 uid.push(item.content! || item.description!)
310 uid.unshift item.title!
312 # debug "taking hash of #{uid.inspect}"
317 # We used to save the Mutex with the RssBlob, which was idiotic. And
318 # since Mutexes dumped in one version might not be restorable in another,
319 # we need a few tricks to be able to restore data from other versions of Ruby
321 # When migrating 1.8.6 => 1.8.5, all we need to do is define an empty
322 # #marshal_load() method for Mutex. For 1.8.5 => 1.8.6 we need something
323 # dirtier, as seen later on in the initialization code.
324 unless Mutex.new.respond_to?(:marshal_load)
326 def marshal_load(str)
332 # Auxiliary method used to collect two lines for rss output filters,
333 # running substitutions against DataStream _s_ optionally joined
336 # For substitutions, *_wrap keys can be used to alter the content of
337 # other nonempty keys. If the value of *_wrap is a String, it will be
338 # put before and after the corresponding key; if it's an Array, the first
339 # and second elements will be used for wrapping; if it's nil, no wrapping
340 # will be done (useful to override a default wrapping).
343 # :handle_wrap => '::'::
344 # will wrap s[:handle] by prefixing and postfixing it with '::'
345 # :date_wrap => [nil, ' :: ']::
346 # will put ' :: ' after s[:date]
347 def make_stream(line1, line2, s, h={})
352 kk = k.to_s.chomp!('_wrap')
357 wraps[nk] = ss[nk].wrap_nonempty(v, v)
359 wraps[nk] = ss[nk].wrap_nonempty(*v)
363 warning "ignoring #{v.inspect} wrapping of unknown class"
370 DataStream.new([line1, line2].compact.join("\n") % subs, ss)
373 # Auxiliary method used to define rss output filters
374 def rss_type(key, &block)
375 @bot.register_filter(key, @outkey, &block)
378 # Define default output filters (rss types), and load custom ones.
379 # Custom filters are looked for in the plugin's default filter locations
380 # and in rss/types under botclass.
381 # Preferably, the rss_type method should be used in these files, e.g.:
382 # rss_type :my_type do |s|
383 # line1 = "%{handle} and some %{author} info"
384 # make_stream(line1, nil, s)
386 # to define the new type 'my_type'. The keys available in the DataStream
389 # the actual rss item
396 # desc, link, category, author::
397 # the item description, link, category, author
399 # the string ' @ ' if the item has both an title and a link
400 # handle_wrap, date_wrap, title_wrap, ...::
401 # these keys can be defined to wrap the corresponding elements if they
402 # are nonempty. By default handle is wrapped with '::', date has a ' ::'
403 # appended and title is enbolden
406 @outkey ||= :"rss.out"
408 # Define an HTML info filter
409 @bot.register_filter(:rss, :htmlinfo) { |s| htmlinfo_filter(s) }
410 # This is the output format used by the input filter
411 rss_type :htmlinfo do |s|
412 line1 = "%{title}%{at}%{link}"
413 make_stream(line1, nil, s)
417 rss_type :default do |s|
418 line1 = "%{handle}%{date}%{title}%{at}%{link}"
419 line1 << " (by %{author})" if s[:author]
420 make_stream(line1, nil, s)
423 @user_types ||= datafile 'types.rb'
425 load_filters :path => @user_types
428 FEED_NS = %r{xmlns.*http://(purl\.org/rss|www.w3c.org/1999/02/22-rdf)}
429 def htmlinfo_filter(s)
430 return nil unless s[:headers] and s[:headers]['x-rbot-location']
431 return nil unless s[:headers]['content-type'].first.match(/xml|rss|atom|rdf/i) or
432 (s[:text].include?("<rdf:RDF") and s[:text].include?("<channel")) or
433 s[:text].include?("<rss") or s[:text].include?("<feed") or
434 s[:text].match(FEED_NS)
435 blob = RssBlob.new(s[:headers]['x-rbot-location'],"", :htmlinfo)
436 unless (fetchRss(blob, nil) and parseRss(blob, nil) rescue nil)
437 debug "#{s.pretty_inspect} is not an RSS feed, despite the appearances"
441 blob.items.each { |it|
442 output << printFormattedRss(blob, it)[:text]
444 return {:title => blob.title, :content => output.join(" | ")}
447 # Display the known rss types
448 def rss_types(m, params)
449 ar = @bot.filter_names(@outkey)
451 m.reply ar.map { |k| k.to_s }.sort!.join(", ")
461 if @registry.has_key?(:feeds)
462 # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the
463 # data unrestorable. If this happens, we patch the data, thus allowing
464 # the restore to work.
466 # This is actually pretty safe for a number of reasons:
467 # * the code is only called if standard marshalling fails
468 # * the string we look for is quite unlikely to appear randomly
469 # * if the string appears somewhere and the patched string isn't recoverable
470 # either, we'll get another (unrecoverable) error, which makes the rss
471 # plugin unsable, just like it was if no recovery was attempted
472 # * if the string appears somewhere and the patched string is recoverable,
473 # we may get a b0rked feed, which is eventually overwritten by a clean
474 # one, so the worst thing that can happen is that a feed update spams
476 @registry.recovery = Proc.new { |val|
477 patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")
478 ret = Marshal.restore(patched)
479 ret.each_value { |blob|
485 @feeds = @registry[:feeds]
486 raise LoadError, "corrupted feed database" unless @feeds
488 @registry.recovery = nil
490 @feeds.keys.grep(/[A-Z]/) { |k|
491 @feeds[k.downcase] = @feeds[k]
511 @feeds.select { |h, f| f.watched? }
520 unparsed = Hash.new()
523 # we don't want to save the mutex
524 unparsed[k].mutex = nil
526 @registry[:feeds] = unparsed
529 def stop_watch(handle)
530 if @watch.has_key?(handle)
532 debug "Stopping watch #{handle}"
533 @bot.timer.remove(@watch[handle])
534 @watch.delete(handle)
535 rescue Exception => e
536 report_problem("Failed to stop watch for #{handle}", e, nil)
542 @watch.each_key { |k|
547 def help(plugin,topic="")
550 "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"
552 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
554 "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
555 when "who", "watches", "who watches"
556 "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
558 "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})"
560 "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}"
561 when /^(del(ete)?|rm)$/
562 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
564 "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"
566 "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})"
568 "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"
570 "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
571 when /who(?: watche?s?)?/
572 "rss who watches #{Bold}handle#{Bold}: lists watches for rss #{Bold}handle#{Bold}"
574 "rss rewatch : restart threads that watch for changes in watched rss"
576 "rss types : show the rss types for which an output format exist (all other types will use the default one)"
578 "manage RSS feeds: rss types|show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch|who watches"
582 def report_problem(report, e=nil, m=nil)
583 if m && m.respond_to?(:reply)
590 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
594 def show_rss(m, params)
595 handle = params[:handle]
596 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
597 debug lims.to_a.inspect
599 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
600 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
601 rev = lims[1].to_i > lims[2].to_i
604 ul = [[lims[1].to_i-1, 0].max, 14].min
608 feed = @feeds.fetch(handle.downcase, nil)
610 m.reply "I don't know any feeds named #{handle}"
614 m.reply "lemme fetch it..."
616 we_were_watching = false
618 if @watch.key?(feed.handle)
619 # If a feed is being watched, we run the watcher thread
620 # so that all watchers can be informed of changes to
621 # the feed. Before we do that, though, we remove the
622 # show requester from the watchlist, if present, lest
623 # he gets the update twice.
624 if feed.watched_by?(m.replyto)
625 we_were_watching = true
626 feed.rm_watch(m.replyto)
628 @bot.timer.reschedule(@watch[feed.handle], 0)
630 feed.add_watch(m.replyto)
633 fetched = fetchRss(feed, m, false)
635 return unless fetched or feed.xml
636 if fetched or not feed.items
637 parsed = parseRss(feed, m)
639 return unless feed.items
640 m.reply "using old data" unless fetched and parsed and parsed > 0
645 # We sort the feeds in freshness order (newer ones first)
646 items = freshness_sort(items)
650 m.reply "Channel : #{title}"
652 printFormattedRss(feed, item, {
653 :places => [m.replyto],
656 :announce_method => :say
661 def itemDate(item,ex=nil)
662 return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
663 return item.date if item.respond_to?(:date) and item.date
667 def freshness_sort(items)
670 itemDate(b, notime) <=> itemDate(a, notime)
674 def list_rss(m, params)
675 wanted = params[:handle]
678 wanted_rx = Regexp.new(wanted, true)
679 listed.reject! { |handle| !handle.match(wanted_rx) }
683 if @bot.config['send.max_lines'] > 0 and listed.size > @bot.config['send.max_lines']
684 reply = listed.inject([]) do |ar, handle|
685 feed = @feeds[handle]
687 (string << " (#{feed.type})") if feed.type
688 (string << " (watched)") if feed.watched_by?(m.replyto)
691 elsif listed.size > 0
692 reply = listed.inject([]) do |ar, handle|
693 feed = @feeds[handle]
694 string = "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
695 (string << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
696 (string << " (watched)") if feed.watched_by?(m.replyto)
700 reply = "no feeds found"
701 reply << " matching #{wanted}" if wanted
703 m.reply reply, :max_lines => 0
706 def watched_rss(m, params)
707 wanted = params[:handle]
708 chan = params[:chan] || m.replyto
710 watchlist.each { |handle, feed|
711 next if wanted and !handle.match(/#{wanted}/i)
712 next unless feed.watched_by?(chan)
713 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
714 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
718 reply = "no watched feeds"
719 reply << " matching #{wanted}" if wanted
724 def who_watches(m, params)
725 wanted = params[:handle]
727 watchlist.each { |handle, feed|
728 next if wanted and !handle.match(/#{wanted}/i)
729 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
730 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
731 reply << ": watched by #{feed.watchers.join(', ')}"
735 reply = "no watched feeds"
736 reply << " matching #{wanted}" if wanted
741 def add_rss(m, params, force=false)
742 handle = params[:handle]
744 unless url.match(/https?/)
745 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
749 if @feeds.fetch(handle.downcase, nil) && !force
750 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
754 m.reply "You must specify both a handle and an url to add an RSS feed"
757 @feeds[handle.downcase] = RssBlob.new(url,handle,type)
758 reply = "Added RSS #{url} named #{handle}"
760 reply << " (format: #{type})"
766 def change_rss(m, params)
767 handle = params[:handle].downcase
768 feed = @feeds.fetch(handle, nil)
770 m.reply "No such feed with handle #{handle}"
773 case params[:what].intern
775 new = params[:new].downcase
776 if @feeds.key?(new) and @feeds[new]
777 m.reply "There already is a feed with handle #{new}"
780 feed.mutex.synchronize do
782 @feeds.delete(handle)
789 feed.mutex.synchronize do
794 new = nil if new == 'default'
795 feed.mutex.synchronize do
799 new = params[:new].to_i
800 new = nil if new == 0
801 feed.mutex.synchronize do
802 feed.refresh_rate = new
805 m.reply "Don't know how to change #{params[:what]} for feeds"
808 m.reply "Feed changed:"
809 list_rss(m, {:handle => handle})
812 def del_rss(m, params, pass=false)
813 feed = unwatch_rss(m, params, true)
816 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
819 @feeds.delete(feed.handle.downcase)
824 def replace_rss(m, params)
825 handle = params[:handle]
826 if @feeds.key?(handle.downcase)
827 del_rss(m, {:handle => handle}, true)
829 if @feeds.key?(handle.downcase)
830 m.reply "can't replace #{feed.handle}"
832 add_rss(m, params, true)
836 def forcereplace_rss(m, params)
837 add_rss(m, params, true)
840 def watch_rss(m, params)
841 handle = params[:handle]
842 chan = params[:chan] || m.replyto
848 feed = @feeds.fetch(handle.downcase, nil)
850 if feed.add_watch(chan)
854 m.reply "Already watching #{feed.handle} in #{chan}"
857 m.reply "Couldn't watch feed #{handle} (no such feed found)"
861 def unwatch_rss(m, params, pass=false)
862 handle = params[:handle].downcase
863 chan = params[:chan] || m.replyto
864 unless @feeds.has_key?(handle)
865 m.reply("dunno that feed")
868 feed = @feeds[handle]
869 if feed.rm_watch(chan)
870 m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
872 m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
880 def rewatch_rss(m=nil, params=nil)
881 if params and handle = params[:handle]
882 feed = @feeds.fetch(handle.downcase, nil)
884 feed.http_cache = false
885 @bot.timer.reschedule(@watch[feed.handle], (params[:delay] || 0).to_f)
888 m.reply _("no such feed %{handle}") % { :handle => handle } if m
893 # Read watches from list.
894 watchlist.each{ |handle, feed|
902 def watchRss(feed, m=nil)
903 if @watch.has_key?(feed.handle)
904 # report_problem("watcher thread for #{feed.handle} is already running", nil, m)
908 status[:failures] = 0
911 tmout = feed.last_fetched + calculate_timeout(feed) - Time.now
912 tmout = 0 if tmout < 0
914 debug "scheduling a watcher for #{feed} in #{tmout} seconds"
915 @watch[feed.handle] = @bot.timer.add(tmout) {
916 debug "watcher for #{feed} wakes up"
917 failures = status[:failures]
919 debug "fetching #{feed}"
921 first_run = !feed.last_success
922 if (@bot.config['rss.announce_timeout'] > 0 &&
923 (Time.now - feed.last_success > @bot.config['rss.announce_timeout']))
924 debug "#{feed} wasn't polled for too long, supressing output"
927 oldxml = feed.xml ? feed.xml.dup : nil
928 unless fetchRss(feed, nil, feed.http_cache)
931 feed.http_cache = true
933 debug "first run for #{feed}, getting items"
935 elsif oldxml and oldxml == feed.xml
936 debug "xml for #{feed} didn't change"
937 failures -= 1 if failures > 0
939 # This one is used for debugging
945 # These are used for checking new items vs old ones
946 oids = Set.new feed.items.map { |item|
949 debug [uid, item].inspect
950 debug [uid, otxt.last].inspect
955 nitems = parseRss(feed)
959 debug "no items in feed #{feed}"
961 debug "Checking if new items are available for #{feed}"
962 failures -= 1 if failures > 0
968 dispItems = feed.items.reject { |item|
971 if oids.include?(uid)
972 debug "rejecting old #{uid} #{item.inspect}"
973 debug [uid, txt].inspect
976 debug "accepting new #{uid} #{item.inspect}"
977 debug [uid, txt].inspect
978 warning "same text! #{txt}" if otxt.include?(txt)
983 if dispItems.length > 0
984 max = @bot.config['rss.announce_max']
985 debug "Found #{dispItems.length} new items in #{feed}"
986 if max > 0 and dispItems.length > max
987 debug "showing only the latest #{dispItems.length}"
988 feed.watchers.each do |loc|
989 @bot.say loc, (_("feed %{feed} had %{num} updates, showing the latest %{max}") % {
990 :feed => feed.handle,
991 :num => dispItems.length,
995 dispItems.slice!(max..-1)
997 # When displaying watched feeds, publish them from older to newer
998 dispItems.reverse.each { |item|
999 printFormattedRss(feed, item)
1002 debug "No new items found in #{feed}"
1007 rescue Exception => e
1008 error "Error watching #{feed}: #{e.inspect}"
1009 debug e.backtrace.join("\n")
1013 status[:failures] = failures
1015 seconds = calculate_timeout(feed, failures)
1016 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
1018 @bot.timer.reschedule(@watch[feed.handle], seconds)
1020 warning "watcher for #{feed} failed to reschedule: #{$!.inspect}"
1023 debug "watcher for #{feed} added"
1026 def calculate_timeout(feed, failures = 0)
1027 seconds = @bot.config['rss.thread_sleep']
1028 feed.mutex.synchronize do
1029 seconds = feed.refresh_rate if feed.refresh_rate
1031 seconds *= failures + 1
1032 seconds += seconds * (rand(100)-50)/100
1037 if obj.kind_of? Time
1038 obj.strftime("%Y/%m/%d %H:%M")
1044 def printFormattedRss(feed, item, options={})
1047 :places => feed.watchers,
1048 :handle => feed.handle,
1050 :announce_method => @bot.config['rss.announce_method']
1053 places = opts[:places]
1054 announce_method = opts[:announce_method]
1056 handle = opts[:handle].to_s
1060 if item.respond_to?(:updated)
1061 make_date(item.updated.content)
1062 elsif item.respond_to?(:source) and item.source.respond_to?(:updated)
1063 make_date(item.source.updated.content)
1064 elsif item.respond_to?(:pubDate)
1065 make_date(item.pubDate)
1066 elsif item.respond_to?(:date)
1067 make_date(item.date)
1076 # Twitters don't need a cap on the title length since they have a hard
1077 # limit to 160 characters, and most of them are under 140 characters
1078 tit_opt[:limit] = @bot.config['rss.head_max'] unless feed.type == 'twitter'
1081 base_title = item.title.to_s.dup
1082 # git changesets are SHA1 hashes (40 hex digits), way too long, get rid of them, as they are
1083 # visible in the URL anyway
1084 # TODO make this optional?
1085 base_title.sub!(/^Changeset \[([\da-f]{40})\]:/) { |c| "(git commit)"} if feed.type == 'trac'
1086 title = base_title.ircify_html(tit_opt)
1090 desc_opt[:limit] = @bot.config['rss.text_max']
1091 desc_opt[:a_href] = :link_out if @bot.config['rss.show_links']
1093 # We prefer content_encoded here as it tends to provide more html formatting
1094 # for use with ircify_html.
1095 if item.respond_to?(:content_encoded) && item.content_encoded
1096 desc = item.content_encoded.ircify_html(desc_opt)
1097 elsif item.respond_to?(:description) && item.description
1098 desc = item.description.ircify_html(desc_opt)
1099 elsif item.respond_to?(:content) && item.content
1100 if item.content.type == "html"
1101 desc = item.content.content.ircify_html(desc_opt)
1103 desc = item.content.content
1104 if desc.size > desc_opt[:limit]
1105 desc = desc.slice(0, desc_opt[:limit]) + "#{Reverse}...#{Reverse}"
1115 category = item.category! || item.dc_subject!
1116 category.strip! if category
1117 author = item.dc_creator! || item.author!
1118 author.strip! if author
1123 at = ((item.title && item.link) ? ' @ ' : '')
1125 key = @bot.global_filter_name(feed.type, @outkey)
1126 key = @bot.global_filter_name(:default, @outkey) unless @bot.has_filter?(key)
1131 :handle_wrap => ['::', ':: '],
1133 :date_wrap => [nil, ' :: '],
1135 :title_wrap => Bold,
1136 :desc => desc, :link => link,
1137 :category => category, :author => author, :at => at
1139 output = @bot.filter(key, stream_hash)
1141 return output if places.empty?
1144 output.to_s.each_line { |line|
1145 @bot.__send__(announce_method, loc, line, :overlong => :truncate)
1150 def fetchRss(feed, m=nil, cache=true)
1151 feed.last_fetched = Time.now
1153 # Use 60 sec timeout, cause the default is too low
1154 xml = @bot.httputil.get(feed.url,
1155 :read_timeout => 60,
1156 :open_timeout => 60,
1158 rescue URI::InvalidURIError, URI::BadURIError => e
1159 report_problem("invalid rss feed #{feed.url}", e, m)
1162 report_problem("error getting #{feed.url}", e, m)
1165 debug "fetched #{feed}"
1167 report_problem("reading feed #{feed} failed", nil, m)
1170 # Ok, 0.9 feeds are not supported, maybe because
1171 # Netscape happily removed the DTD. So what we do is just to
1172 # reassign the 0.9 RDFs to 1.0, and hope it goes right.
1173 xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",
1174 "xmlns=\"http://purl.org/rss/1.0/\"")
1175 # make sure the parser doesn't double-convert in case the feed is not UTF-8
1176 xml.sub!(/<\?xml (.*?)\?>/) do |match|
1177 if /\bencoding=(['"])(.*?)\1/.match(match)
1178 match.sub!(/\bencoding=(['"])(?:.*?)\1/,'encoding="UTF-8"')
1182 feed.mutex.synchronize do
1184 feed.last_success = Time.now
1189 def parseRss(feed, m=nil)
1190 return nil unless feed.xml
1191 feed.mutex.synchronize do
1195 RSS::AVAILABLE_PARSERS.each do |parser|
1197 ## do validate parse
1198 rss = RSS::Parser.parse(xml, true, true, parser)
1199 debug "parsed and validated #{feed} with #{parser}"
1201 rescue RSS::InvalidRSSError
1203 ## do non validate parse for invalid RSS 1.0
1204 rss = RSS::Parser.parse(xml, false, true, parser)
1205 debug "parsed but not validated #{feed} with #{parser}"
1207 rescue RSS::Error => e
1208 errors << [parser, e, "parsing rss stream failed, whoops =("]
1210 rescue RSS::Error => e
1211 errors << [parser, e, "parsing rss stream failed, oioi"]
1213 errors << [parser, e, "processing error occured, sorry =("]
1216 unless errors.empty?
1218 self.send(:report_problem, errors.last[2], errors.last[1], m)
1219 return nil unless rss
1223 if xml.match(/xmlns\s*=\s*(['"])http:\/\/www.w3.org\/2005\/Atom\1/) and not defined?(RSS::Atom)
1224 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)
1226 report_problem("#{feed.handle} @ #{feed.url} doesn't seem to contain an RSS or Atom feed I can read", nil, m)
1231 rss.output_encoding = 'UTF-8'
1232 rescue RSS::UnknownConvertMethod => e
1233 report_problem("bah! something went wrong =(", e, m)
1236 if rss.respond_to? :channel
1237 rss.channel.title ||= "(?)"
1238 title = rss.channel.title
1240 title = rss.title.content
1242 rss.items.each do |item|
1243 item.title ||= "(?)"
1249 report_problem("no items found in the feed, maybe try weed?", e, m)
1251 feed.title = title.strip
1259 plugin = RSSFeedsPlugin.new
1261 plugin.default_auth( 'edit', false )
1262 plugin.default_auth( 'edit:add', true)
1264 plugin.map 'rss show :handle :limit',
1265 :action => 'show_rss',
1266 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
1267 :defaults => {:limit => 5}
1268 plugin.map 'rss list :handle',
1269 :action => 'list_rss',
1270 :defaults => {:handle => nil}
1271 plugin.map 'rss watched :handle [in :chan]',
1272 :action => 'watched_rss',
1273 :defaults => {:handle => nil}
1274 plugin.map 'rss who watches :handle',
1275 :action => 'who_watches',
1276 :defaults => {:handle => nil}
1277 plugin.map 'rss add :handle :url :type',
1278 :action => 'add_rss',
1279 :auth_path => 'edit',
1280 :defaults => {:type => nil}
1281 plugin.map 'rss change :what of :handle to :new',
1282 :action => 'change_rss',
1283 :auth_path => 'edit',
1284 :requirements => { :what => /handle|url|format|type|refresh/ }
1285 plugin.map 'rss change :what for :handle to :new',
1286 :action => 'change_rss',
1287 :auth_path => 'edit',
1288 :requirements => { :what => /handle|url|format|type|refesh/ }
1289 plugin.map 'rss del :handle',
1290 :auth_path => 'edit:rm!',
1291 :action => 'del_rss'
1292 plugin.map 'rss delete :handle',
1293 :auth_path => 'edit:rm!',
1294 :action => 'del_rss'
1295 plugin.map 'rss rm :handle',
1296 :auth_path => 'edit:rm!',
1297 :action => 'del_rss'
1298 plugin.map 'rss replace :handle :url :type',
1299 :auth_path => 'edit',
1300 :action => 'replace_rss',
1301 :defaults => {:type => nil}
1302 plugin.map 'rss forcereplace :handle :url :type',
1303 :auth_path => 'edit',
1304 :action => 'forcereplace_rss',
1305 :defaults => {:type => nil}
1306 plugin.map 'rss watch :handle [in :chan]',
1307 :action => 'watch_rss',
1308 :defaults => {:url => nil, :type => nil}
1309 plugin.map 'rss watch :handle :url :type [in :chan]',
1310 :action => 'watch_rss',
1311 :defaults => {:url => nil, :type => nil}
1312 plugin.map 'rss unwatch :handle [in :chan]',
1313 :action => 'unwatch_rss'
1314 plugin.map 'rss rmwatch :handle [in :chan]',
1315 :action => 'unwatch_rss'
1316 plugin.map 'rss rewatch [:handle] [:delay]',
1317 :action => 'rewatch_rss'
1318 plugin.map 'rss types',
1319 :action => 'rss_types'