4 # :title: RSS feed plugin for rbot
\r
6 # Author:: Stanislav Karchebny <berkus@madfire.net>
\r
7 # Author:: Ian Monroe <ian@monroe.nu>
\r
8 # Author:: Mark Kretschmann <markey@web.de>
\r
9 # Author:: Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
\r
11 # Copyright:: (C) 2004 Stanislav Karchebny
\r
12 # Copyright:: (C) 2005 Ian Monroe, Mark Kretschmann
\r
13 # Copyright:: (C) 2006-2007 Giuseppe Bilotta
\r
15 # License:: MIT license
\r
21 # Make an 'unique' ID for a given item, based on appropriate bot options
\r
22 # Currently only suppored is bot.config['rss.show_updated']: when true, the
\r
23 # description is included in the uid hashing, otherwise it's not
\r
25 def RSS.item_uid_for_bot(item, opts={})
\r
26 options = { :show_updated => true}.merge(opts)
\r
28 if options[:show_updated]
\r
29 desc = item.content.content rescue item.description rescue nil
\r
31 [(item.title.content rescue item.title rescue nil),
\r
32 (item.link.href rescue item.link),
\r
36 # Add support for Slashdot namespace in RDF. The code is just an adaptation
\r
37 # of the DublinCore code.
\r
38 unless defined?(SLASH_PREFIX)
\r
39 SLASH_PREFIX = 'slash'
\r
40 SLASH_URI = "http://purl.org/rss/1.0/modules/slash/"
\r
42 RDF.install_ns(SLASH_PREFIX, SLASH_URI)
\r
44 module BaseSlashModel
\r
45 def append_features(klass)
\r
48 return if klass.instance_of?(Module)
\r
49 SlashModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
\r
50 plural = plural_name || "#{name}s"
\r
51 full_name = "#{SLASH_PREFIX}_#{name}"
\r
52 full_plural_name = "#{SLASH_PREFIX}_#{plural}"
\r
53 klass_name = "Slash#{Utils.to_class_name(name)}"
\r
55 # This will fail with older version of the Ruby RSS module
\r
57 klass.install_have_children_element(name, SLASH_URI, "*",
\r
58 full_name, full_plural_name)
\r
59 klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI)
\r
60 rescue ArgumentError
\r
61 klass.module_eval("install_have_children_element(#{full_name.dump}, #{full_plural_name.dump})")
\r
64 klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0))
\r
65 remove_method :#{full_name} if method_defined? :#{full_name}
\r
66 remove_method :#{full_name}= if method_defined? :#{full_name}=
\r
67 remove_method :set_#{full_name} if method_defined? :set_#{full_name}
\r
70 @#{full_name}.first and @#{full_name}.first.value
\r
73 def #{full_name}=(new_value)
\r
74 @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value)
\r
76 alias set_#{full_name} #{full_name}=
\r
84 extend BaseSlashModel
\r
87 "department" => nil,
\r
93 ELEMENT_NAME_INFOS = SlashModel::TEXT_ELEMENTS.to_a
\r
95 ELEMENTS = TEXT_ELEMENTS.keys
\r
97 ELEMENTS.each do |name, plural_name|
\r
98 module_eval(<<-EOC, *get_file_and_line_from_caller(0))
\r
99 class Slash#{Utils.to_class_name(name)} < Element
\r
105 def required_prefix
\r
114 @tag_name = #{name.dump}
\r
116 alias_method(:value, :content)
\r
117 alias_method(:value=, :content=)
\r
119 def initialize(*args)
\r
121 if Utils.element_initialize_arguments?(args)
\r
125 self.content = args[0]
\r
127 # Older Ruby RSS module
\r
128 rescue NoMethodError
\r
130 self.content = args[0]
\r
135 tag_name_with_prefix(SLASH_PREFIX)
\r
138 def maker_target(target)
\r
142 def setup_maker_attributes(#{name})
\r
143 #{name}.content = content
\r
151 class Item; include SlashModel; end
\r
154 SlashModel::ELEMENTS.each do |name|
\r
155 class_name = Utils.to_class_name(name)
\r
156 BaseListener.install_class_name(SLASH_URI, name, "Slash#{class_name}")
\r
159 SlashModel::ELEMENTS.collect! {|name| "#{SLASH_PREFIX}_#{name}"}
\r
165 attr_accessor :url, :handle, :type, :refresh_rate, :xml, :title, :items,
\r
166 :mutex, :watchers, :last_fetched
\r
168 def initialize(url,handle=nil,type=nil,watchers=[], xml=nil, lf = nil)
\r
177 @refresh_rate = nil
\r
183 sanitize_watchers(watchers)
\r
187 @mutex.synchronize do
\r
188 self.class.new(@url,
\r
190 @type ? @type.dup : nil,
\r
192 @xml ? @xml.dup : nil,
\r
197 # Downcase all watchers, possibly turning them into Strings if they weren't
\r
198 def sanitize_watchers(list=@watchers)
\r
210 def watched_by?(who)
\r
211 @watchers.include?(who.downcase)
\r
215 if watched_by?(who)
\r
218 @mutex.synchronize do
\r
219 @watchers << who.downcase
\r
225 @mutex.synchronize do
\r
226 @watchers.delete(who.downcase)
\r
231 [@handle,@url,@type,@refresh_rate,@watchers]
\r
234 def to_s(watchers=false)
\r
236 a = self.to_a.flatten
\r
240 a.compact.join(" | ")
\r
244 class RSSFeedsPlugin < Plugin
\r
245 Config.register Config::IntegerValue.new('rss.head_max',
\r
246 :default => 100, :validate => Proc.new{|v| v > 0 && v < 200},
\r
247 :desc => "How many characters to use of a RSS item header")
\r
249 Config.register Config::IntegerValue.new('rss.text_max',
\r
250 :default => 200, :validate => Proc.new{|v| v > 0 && v < 400},
\r
251 :desc => "How many characters to use of a RSS item text")
\r
253 Config.register Config::IntegerValue.new('rss.thread_sleep',
\r
254 :default => 300, :validate => Proc.new{|v| v > 30},
\r
255 :desc => "How many seconds to sleep before checking RSS feeds again")
\r
257 Config.register Config::BooleanValue.new('rss.show_updated',
\r
259 :desc => "Whether feed items for which the description was changed should be shown as new")
\r
261 # We used to save the Mutex with the RssBlob, which was idiotic. And
\r
262 # since Mutexes dumped in one version might not be resotrable in another,
\r
263 # we need a few tricks to be able to restore data from other versions of Ruby
\r
265 # When migrating 1.8.6 => 1.8.5, all we need to do is define an empty
\r
266 # #marshal_load() method for Mutex. For 1.8.5 => 1.8.6 we need something
\r
267 # dirtier, as seen later on in the initialization code.
\r
268 unless Mutex.new.respond_to?(:marshal_load)
\r
270 def marshal_load(str)
\r
280 if @registry.has_key?(:feeds)
\r
281 # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the
\r
282 # data unrestorable. If this happens, we patch the data, thus allowing
\r
283 # the restore to work.
\r
285 # This is actually pretty safe for a number of reasons:
\r
286 # * the code is only called if standard marshalling fails
\r
287 # * the string we look for is quite unlikely to appear randomly
\r
288 # * if the string appears somewhere and the patched string isn't recoverable
\r
289 # either, we'll get another (unrecoverable) error, which makes the rss
\r
290 # plugin unsable, just like it was if no recovery was attempted
\r
291 # * if the string appears somewhere and the patched string is recoverable,
\r
292 # we may get a b0rked feed, which is eventually overwritten by a clean
\r
293 # one, so the worst thing that can happen is that a feed update spams
\r
294 # the watchers once
\r
295 @registry.recovery = Proc.new { |val|
\r
296 patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")
\r
297 ret = Marshal.restore(patched)
\r
298 ret.each_value { |blob|
\r
304 @feeds = @registry[:feeds]
\r
305 raise unless @feeds
\r
307 @registry.recovery = nil
\r
309 @feeds.keys.grep(/[A-Z]/) { |k|
\r
310 @feeds[k.downcase] = @feeds[k]
\r
313 @feeds.each { |k, f|
\r
314 f.mutex = Mutex.new
\r
315 f.sanitize_watchers
\r
316 parseRss(f) if f.xml
\r
330 @feeds.select { |h, f| f.watched? }
\r
339 unparsed = Hash.new()
\r
340 @feeds.each { |k, f|
\r
341 unparsed[k] = f.dup
\r
342 # we don't want to save the mutex
\r
343 unparsed[k].mutex = nil
\r
345 @registry[:feeds] = unparsed
\r
348 def stop_watch(handle)
\r
349 if @watch.has_key?(handle)
\r
351 debug "Stopping watch #{handle}"
\r
352 @bot.timer.remove(@watch[handle])
\r
353 @watch.delete(handle)
\r
354 rescue Exception => e
\r
355 report_problem("Failed to stop watch for #{handle}", e, nil)
\r
361 @watch.each_key { |k|
\r
366 def help(plugin,topic="")
\r
369 "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"
\r
371 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
\r
373 "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
\r
374 when "who", "watches", "who watches"
\r
375 "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
\r
377 "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})"
\r
379 "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}"
\r
380 when /^(del(ete)?|rm)$/
\r
381 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
\r
383 "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"
\r
384 when "forcereplace"
\r
385 "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})"
\r
387 "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"
\r
388 when /(un|rm)watch/
\r
389 "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
\r
390 when /who(?: watche?s?)?/
\r
391 "rss who watches #{Bold}handle#{Bold}: lists watches for rss #{Bold}handle#{Bold}"
\r
393 "rss rewatch : restart threads that watch for changes in watched rss"
\r
395 "manage RSS feeds: rss show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch|who watches"
\r
399 def report_problem(report, e=nil, m=nil)
\r
400 if m && m.respond_to?(:reply)
\r
407 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
\r
411 def show_rss(m, params)
\r
412 handle = params[:handle]
\r
413 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
\r
414 debug lims.to_a.inspect
\r
416 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
\r
417 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
\r
418 rev = lims[1].to_i > lims[2].to_i
\r
421 ul = [[lims[1].to_i-1, 0].max, 14].min
\r
425 feed = @feeds.fetch(handle.downcase, nil)
\r
427 m.reply "I don't know any feeds named #{handle}"
\r
431 m.reply "lemme fetch it..."
\r
432 title = items = nil
\r
433 we_were_watching = false
\r
435 if @watch.key?(feed.handle)
\r
436 # If a feed is being watched, we run the watcher thread
\r
437 # so that all watchers can be informed of changes to
\r
438 # the feed. Before we do that, though, we remove the
\r
439 # show requester from the watchlist, if present, lest
\r
440 # he gets the update twice.
\r
441 if feed.watched_by?(m.replyto)
\r
442 we_were_watching = true
\r
443 feed.rm_watch(m.replyto)
\r
445 @bot.timer.reschedule(@watch[feed.handle], 0)
\r
446 if we_were_watching
\r
447 feed.add_watch(m.replyto)
\r
450 fetched = fetchRss(feed, m, false)
\r
452 return unless fetched or feed.xml
\r
453 if not fetched and feed.items
\r
454 m.reply "using old data"
\r
456 parsed = parseRss(feed, m)
\r
457 m.reply "using old data" unless parsed
\r
459 return unless feed.items
\r
463 # We sort the feeds in freshness order (newer ones first)
\r
464 items = freshness_sort(items)
\r
465 disp = items[ll..ul]
\r
466 disp.reverse! if rev
\r
468 m.reply "Channel : #{title}"
\r
469 disp.each do |item|
\r
470 printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})
\r
474 def itemDate(item,ex=nil)
\r
475 return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
\r
476 return item.date if item.respond_to?(:date) and item.date
\r
480 def freshness_sort(items)
\r
481 notime = Time.at(0)
\r
482 items.sort { |a, b|
\r
483 itemDate(b, notime) <=> itemDate(a, notime)
\r
487 def list_rss(m, params)
\r
488 wanted = params[:handle]
\r
490 @feeds.each { |handle, feed|
\r
491 next if wanted and !handle.match(/#{wanted}/i)
\r
492 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
493 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
494 (reply << " (watched)") if feed.watched_by?(m.replyto)
\r
498 reply = "no feeds found"
\r
499 reply << " matching #{wanted}" if wanted
\r
501 m.reply reply, :max_lines => reply.length
\r
504 def watched_rss(m, params)
\r
505 wanted = params[:handle]
\r
506 chan = params[:chan] || m.replyto
\r
508 watchlist.each { |handle, feed|
\r
509 next if wanted and !handle.match(/#{wanted}/i)
\r
510 next unless feed.watched_by?(chan)
\r
511 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
512 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
516 reply = "no watched feeds"
\r
517 reply << " matching #{wanted}" if wanted
\r
522 def who_watches(m, params)
\r
523 wanted = params[:handle]
\r
525 watchlist.each { |handle, feed|
\r
526 next if wanted and !handle.match(/#{wanted}/i)
\r
527 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
528 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
529 reply << ": watched by #{feed.watchers.join(', ')}"
\r
533 reply = "no watched feeds"
\r
534 reply << " matching #{wanted}" if wanted
\r
539 def add_rss(m, params, force=false)
\r
540 handle = params[:handle]
\r
542 unless url.match(/https?/)
\r
543 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
\r
546 type = params[:type]
\r
547 if @feeds.fetch(handle.downcase, nil) && !force
\r
548 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
\r
552 m.reply "You must specify both a handle and an url to add an RSS feed"
\r
555 @feeds[handle.downcase] = RssBlob.new(url,handle,type)
\r
556 reply = "Added RSS #{url} named #{handle}"
\r
558 reply << " (format: #{type})"
\r
564 def change_rss(m, params)
\r
565 handle = params[:handle].downcase
\r
566 feed = @feeds.fetch(handle, nil)
\r
568 m.reply "No such feed with handle #{handle}"
\r
571 case params[:what].intern
\r
573 new = params[:new].downcase
\r
574 if @feeds.key?(new) and @feeds[new]
\r
575 m.reply "There already is a feed with handle #{new}"
\r
578 feed.mutex.synchronize do
\r
580 @feeds.delete(handle)
\r
587 feed.mutex.synchronize do
\r
590 when :format, :type
\r
592 new = nil if new == 'default'
\r
593 feed.mutex.synchronize do
\r
597 new = params[:new].to_i
\r
598 new = nil if new == 0
\r
599 feed.mutex.synchronize do
\r
600 feed.refresh_rate = new
\r
603 m.reply "Don't know how to change #{params[:what]} for feeds"
\r
606 m.reply "Feed changed:"
\r
607 list_rss(m, {:handle => handle})
\r
610 def del_rss(m, params, pass=false)
\r
611 feed = unwatch_rss(m, params, true)
\r
614 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
\r
617 @feeds.delete(feed.handle.downcase)
\r
622 def replace_rss(m, params)
\r
623 handle = params[:handle]
\r
624 if @feeds.key?(handle.downcase)
\r
625 del_rss(m, {:handle => handle}, true)
\r
627 if @feeds.key?(handle.downcase)
\r
628 m.reply "can't replace #{feed.handle}"
\r
630 add_rss(m, params, true)
\r
634 def forcereplace_rss(m, params)
\r
635 add_rss(m, params, true)
\r
638 def watch_rss(m, params)
\r
639 handle = params[:handle]
\r
640 chan = params[:chan] || m.replyto
\r
642 type = params[:type]
\r
646 feed = @feeds.fetch(handle.downcase, nil)
\r
648 if feed.add_watch(chan)
\r
652 m.reply "Already watching #{feed.handle} in #{chan}"
\r
655 m.reply "Couldn't watch feed #{handle} (no such feed found)"
\r
659 def unwatch_rss(m, params, pass=false)
\r
660 handle = params[:handle].downcase
\r
661 chan = params[:chan] || m.replyto
\r
662 unless @feeds.has_key?(handle)
\r
663 m.reply("dunno that feed")
\r
666 feed = @feeds[handle]
\r
667 if feed.rm_watch(chan)
\r
668 m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
\r
670 m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
\r
678 def rewatch_rss(m=nil, params=nil)
\r
679 if params and handle = params[:handle]
\r
680 feed = @feeds.fetch(handle.downcase, nil)
\r
682 @bot.timer.reschedule(@watch[feed.handle], 0)
\r
685 m.reply _("no such feed %{handle}") % { :handle => handle } if m
\r
690 # Read watches from list.
\r
691 watchlist.each{ |handle, feed|
\r
699 def watchRss(feed, m=nil)
\r
700 if @watch.has_key?(feed.handle)
\r
701 report_problem("watcher thread for #{feed.handle} is already running", nil, m)
\r
705 status[:failures] = 0
\r
707 if feed.last_fetched
\r
708 tmout = feed.last_fetched + calculate_timeout(feed) - Time.now
\r
709 tmout = 0 if tmout < 0
\r
711 debug "scheduling a watcher for #{feed} in #{tmout} seconds"
\r
712 @watch[feed.handle] = @bot.timer.add(tmout) {
\r
713 debug "watcher for #{feed} wakes up"
\r
714 failures = status[:failures]
\r
716 debug "fetching #{feed}"
\r
717 first_run = !feed.last_fetched
\r
718 oldxml = feed.xml ? feed.xml.dup : nil
\r
719 unless fetchRss(feed)
\r
723 debug "first run for #{feed}, getting items"
\r
725 elsif oldxml and oldxml == feed.xml
\r
726 debug "xml for #{feed} didn't change"
\r
727 failures -= 1 if failures > 0
\r
730 debug "no previous items in feed #{feed}"
\r
732 failures -= 1 if failures > 0
\r
734 # This one is used for debugging
\r
737 # These are used for checking new items vs old ones
\r
738 uid_opts = { :show_updated => @bot.config['rss.show_updated'] }
\r
739 oids = Set.new feed.items.map { |item|
\r
740 uid = RSS.item_uid_for_bot(item, uid_opts)
\r
742 debug [uid, item].inspect
\r
743 debug [uid, otxt.last].inspect
\r
747 unless parseRss(feed)
\r
748 debug "no items in feed #{feed}"
\r
751 debug "Checking if new items are available for #{feed}"
\r
752 failures -= 1 if failures > 0
\r
758 dispItems = feed.items.reject { |item|
\r
759 uid = RSS.item_uid_for_bot(item, uid_opts)
\r
761 if oids.include?(uid)
\r
762 debug "rejecting old #{uid} #{item.inspect}"
\r
763 debug [uid, txt].inspect
\r
766 debug "accepting new #{uid} #{item.inspect}"
\r
767 debug [uid, txt].inspect
\r
768 warning "same text! #{txt}" if otxt.include?(txt)
\r
773 if dispItems.length > 0
\r
774 debug "Found #{dispItems.length} new items in #{feed}"
\r
775 # When displaying watched feeds, publish them from older to newer
\r
776 dispItems.reverse.each { |item|
\r
777 printFormattedRss(feed, item)
\r
780 debug "No new items found in #{feed}"
\r
786 rescue Exception => e
\r
787 error "Error watching #{feed}: #{e.inspect}"
\r
788 debug e.backtrace.join("\n")
\r
792 status[:failures] = failures
\r
794 seconds = calculate_timeout(feed, failures)
\r
795 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
\r
797 @bot.timer.reschedule(@watch[feed.handle], seconds)
\r
799 warning "watcher for #{feed} failed to reschedule: #{$!.inspect}"
\r
802 debug "watcher for #{feed} added"
\r
805 def calculate_timeout(feed, failures = 0)
\r
806 seconds = @bot.config['rss.thread_sleep']
\r
807 feed.mutex.synchronize do
\r
808 seconds = feed.refresh_rate if feed.refresh_rate
\r
810 seconds *= failures + 1
\r
811 seconds += seconds * (rand(100)-50)/100
\r
815 def select_nonempty(*ar)
\r
817 ret = ar.map { |i| (i && i.empty?) ? nil : i }.compact.first
\r
818 (ret && ret.empty?) ? nil : ret
\r
821 def printFormattedRss(feed, item, opts=nil)
\r
823 places = feed.watchers
\r
824 handle = "::#{feed.handle}:: "
\r
827 places = opts[:places] if opts.key?(:places)
\r
828 handle = opts[:handle].to_s if opts.key?(:handle)
\r
829 if opts.key?(:date) && opts[:date]
\r
830 if item.respond_to?(:updated)
\r
831 if item.updated.content.class <= Time
\r
832 date = item.updated.content.strftime("%Y/%m/%d %H:%M")
\r
834 date = item.updated.content.to_s
\r
836 elsif item.respond_to?(:source) and item.source.respond_to?(:updated)
\r
837 if item.source.updated.content.class <= Time
\r
838 date = item.source.updated.content.strftime("%Y/%m/%d %H:%M")
\r
840 date = item.source.updated.content.to_s
\r
842 elsif item.respond_to?(:pubDate)
\r
843 if item.pubDate.class <= Time
\r
844 date = item.pubDate.strftime("%Y/%m/%d %H:%M")
\r
846 date = item.pubDate.to_s
\r
848 elsif item.respond_to?(:date)
\r
849 if item.date.class <= Time
\r
850 date = item.date.strftime("%Y/%m/%d %H:%M")
\r
852 date = item.date.to_s
\r
862 # Twitters don't need a cap on the title length since they have a hard
\r
863 # limit to 160 characters, and most of them are under 140 characters
\r
864 tit_opt[:limit] = @bot.config['rss.head_max'] unless feed.type == 'twitter'
\r
866 title = "#{Bold}#{item.title.to_s.ircify_html(tit_opt)}#{Bold}" if item.title
\r
869 :limit => @bot.config['rss.text_max'],
\r
870 :a_href => :link_out
\r
873 if item.respond_to? :description
\r
874 desc = item.description.ircify_html(desc_opt) if item.description
\r
876 if item.content.type == "html"
\r
877 desc = item.content.content.ircify_html(desc_opt)
\r
879 desc = item.content.content
\r
880 if desc.size > desc_opt[:limit]
\r
881 desc = desc.slice(0, desc_opt[:limit]) + "#{Reverse}...#{Reverse}"
\r
886 link = item.link.href rescue item.link.chomp rescue nil
\r
888 category = select_nonempty((item.category.content rescue nil), (idem.dc_subject rescue nil))
\r
889 author = select_nonempty((item.author.name.content rescue nil), (item.dc_creator rescue nil), (item.author rescue nil))
\r
894 at = ((item.title && item.link) ? ' @ ' : '')
\r
898 author += " " if author
\r
899 abt = category ? "about #{category} " : ""
\r
900 line1 = "#{handle}#{date}#{author}blogged #{abt}at #{link}"
\r
901 line2 = "#{handle}#{title} - #{desc}"
\r
903 author += " " if author
\r
904 line1 = "#{handle}#{date}#{author}commited #{title} @ #{link}"
\r
906 line1 = "#{handle}#{date}#{title}#{at}#{link}"
\r
908 line1 = "#{handle}#{date}#{title}#{at}#{link} has been edited by #{author}. #{desc}"
\r
910 line1 = "#{handle}#{date}Message #{title} sent by #{author}. #{desc}"
\r
912 line1 = "#{handle}#{date}#{title} @ #{link}"
\r
913 unless item.title =~ /^Changeset \[(\d+)\]/
\r
914 line2 = "#{handle}#{date}#{desc}"
\r
917 dept = "(from the #{item.slash_department} dept) " rescue nil
\r
918 sec = " in section #{item.slash_section}" rescue nil
\r
920 line1 = "#{handle}#{date}#{dept}#{title}#{at}#{link} (posted by #{author}#{sec})"
\r
922 line1 = "#{handle}#{date}#{title}#{at}#{link}"
\r
923 line1 << " (by #{author})" if author
\r
925 places.each { |loc|
\r
926 @bot.say loc, line1, :overlong => :truncate
\r
928 @bot.say loc, line2, :overlong => :truncate
\r
932 def fetchRss(feed, m=nil, cache=true)
\r
933 feed.last_fetched = Time.now
\r
935 # Use 60 sec timeout, cause the default is too low
\r
936 xml = @bot.httputil.get(feed.url,
\r
937 :read_timeout => 60,
\r
938 :open_timeout => 60,
\r
940 rescue URI::InvalidURIError, URI::BadURIError => e
\r
941 report_problem("invalid rss feed #{feed.url}", e, m)
\r
944 report_problem("error getting #{feed.url}", e, m)
\r
947 debug "fetched #{feed}"
\r
949 report_problem("reading feed #{feed} failed", nil, m)
\r
952 # Ok, 0.9 feeds are not supported, maybe because
\r
953 # Netscape happily removed the DTD. So what we do is just to
\r
954 # reassign the 0.9 RDFs to 1.0, and hope it goes right.
\r
955 xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",
\r
956 "xmlns=\"http://purl.org/rss/1.0/\"")
\r
957 feed.mutex.synchronize do
\r
963 def parseRss(feed, m=nil)
\r
964 return nil unless feed.xml
\r
965 feed.mutex.synchronize do
\r
968 ## do validate parse
\r
969 rss = RSS::Parser.parse(xml)
\r
970 debug "parsed and validated #{feed}"
\r
971 rescue RSS::InvalidRSSError
\r
972 ## do non validate parse for invalid RSS 1.0
\r
974 rss = RSS::Parser.parse(xml, false)
\r
975 debug "parsed but not validated #{feed}"
\r
976 rescue RSS::Error => e
\r
977 report_problem("parsing rss stream failed, whoops =(", e, m)
\r
980 rescue RSS::Error => e
\r
981 report_problem("parsing rss stream failed, oioi", e, m)
\r
984 report_problem("processing error occured, sorry =(", e, m)
\r
989 report_problem("#{feed} does not include RSS 1.0 or 0.9x/2.0", nil, m)
\r
992 rss.output_encoding = 'UTF-8'
\r
993 rescue RSS::UnknownConvertMethod => e
\r
994 report_problem("bah! something went wrong =(", e, m)
\r
997 if rss.respond_to? :channel
\r
998 rss.channel.title ||= "Unknown"
\r
999 title = rss.channel.title
\r
1001 title = rss.title.content
\r
1003 rss.items.each do |item|
\r
1004 item.title ||= "Unknown"
\r
1010 report_problem("no items found in the feed, maybe try weed?", e, m)
\r
1013 feed.title = title
\r
1014 feed.items = items
\r
1020 plugin = RSSFeedsPlugin.new
\r
1022 plugin.default_auth( 'edit', false )
\r
1023 plugin.default_auth( 'edit:add', true)
\r
1025 plugin.map 'rss show :handle :limit',
\r
1026 :action => 'show_rss',
\r
1027 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
\r
1028 :defaults => {:limit => 5}
\r
1029 plugin.map 'rss list :handle',
\r
1030 :action => 'list_rss',
\r
1031 :defaults => {:handle => nil}
\r
1032 plugin.map 'rss watched :handle [in :chan]',
\r
1033 :action => 'watched_rss',
\r
1034 :defaults => {:handle => nil}
\r
1035 plugin.map 'rss who watches :handle',
\r
1036 :action => 'who_watches',
\r
1037 :defaults => {:handle => nil}
\r
1038 plugin.map 'rss add :handle :url :type',
\r
1039 :action => 'add_rss',
\r
1040 :auth_path => 'edit',
\r
1041 :defaults => {:type => nil}
\r
1042 plugin.map 'rss change :what of :handle to :new',
\r
1043 :action => 'change_rss',
\r
1044 :auth_path => 'edit',
\r
1045 :requirements => { :what => /handle|url|format|type|refresh/ }
\r
1046 plugin.map 'rss change :what for :handle to :new',
\r
1047 :action => 'change_rss',
\r
1048 :auth_path => 'edit',
\r
1049 :requirements => { :what => /handle|url|format|type|refesh/ }
\r
1050 plugin.map 'rss del :handle',
\r
1051 :auth_path => 'edit:rm!',
\r
1052 :action => 'del_rss'
\r
1053 plugin.map 'rss delete :handle',
\r
1054 :auth_path => 'edit:rm!',
\r
1055 :action => 'del_rss'
\r
1056 plugin.map 'rss rm :handle',
\r
1057 :auth_path => 'edit:rm!',
\r
1058 :action => 'del_rss'
\r
1059 plugin.map 'rss replace :handle :url :type',
\r
1060 :auth_path => 'edit',
\r
1061 :action => 'replace_rss',
\r
1062 :defaults => {:type => nil}
\r
1063 plugin.map 'rss forcereplace :handle :url :type',
\r
1064 :auth_path => 'edit',
\r
1065 :action => 'forcereplace_rss',
\r
1066 :defaults => {:type => nil}
\r
1067 plugin.map 'rss watch :handle [in :chan]',
\r
1068 :action => 'watch_rss',
\r
1069 :defaults => {:url => nil, :type => nil}
\r
1070 plugin.map 'rss watch :handle :url :type [in :chan]',
\r
1071 :action => 'watch_rss',
\r
1072 :defaults => {:url => nil, :type => nil}
\r
1073 plugin.map 'rss unwatch :handle [in :chan]',
\r
1074 :action => 'unwatch_rss'
\r
1075 plugin.map 'rss rmwatch :handle [in :chan]',
\r
1076 :action => 'unwatch_rss'
\r
1077 plugin.map 'rss rewatch [:handle]',
\r
1078 :action => 'rewatch_rss'
\r