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
17 # require 'rss/parser'
\r
20 # require 'rss/dublincore'
\r
22 # # require 'rss/dublincore/2.0'
\r
24 # # warning "Unable to load RSS libraries, RSS plugin functionality crippled"
\r
27 # GB: Let's just go for the simple stuff:
\r
33 attr_accessor :handle
\r
36 attr_accessor :refresh_rate
\r
38 attr_accessor :title
\r
39 attr_accessor :items
\r
40 attr_accessor :mutex
\r
42 def initialize(url,handle=nil,type=nil,watchers=[], xml=nil)
\r
56 sanitize_watchers(watchers)
\r
60 @mutex.synchronize do
\r
61 self.class.new(@url,
\r
63 @type ? @type.dup : nil,
\r
65 @xml ? @xml.dup : nil)
\r
69 # Downcase all watchers, possibly turning them into Strings if they weren't
\r
70 def sanitize_watchers(list=@watchers)
\r
82 def watched_by?(who)
\r
83 @watchers.include?(who.downcase)
\r
90 @mutex.synchronize do
\r
91 @watchers << who.downcase
\r
97 @mutex.synchronize do
\r
98 @watchers.delete(who.downcase)
\r
103 [@handle,@url,@type,@refresh_rate,@watchers]
\r
106 def to_s(watchers=false)
\r
108 a = self.to_a.flatten
\r
112 a.compact.join(" | ")
\r
116 class RSSFeedsPlugin < Plugin
\r
117 BotConfig.register BotConfigIntegerValue.new('rss.head_max',
\r
118 :default => 30, :validate => Proc.new{|v| v > 0 && v < 200},
\r
119 :desc => "How many characters to use of a RSS item header")
\r
121 BotConfig.register BotConfigIntegerValue.new('rss.text_max',
\r
122 :default => 90, :validate => Proc.new{|v| v > 0 && v < 400},
\r
123 :desc => "How many characters to use of a RSS item text")
\r
125 BotConfig.register BotConfigIntegerValue.new('rss.thread_sleep',
\r
126 :default => 300, :validate => Proc.new{|v| v > 30},
\r
127 :desc => "How many seconds to sleep before checking RSS feeds again")
\r
129 # We used to save the Mutex with the RssBlob, which was idiotic. And
\r
130 # since Mutexes dumped in one version might not be resotrable in another,
\r
131 # we need a few tricks to be able to restore data from other versions of Ruby
\r
133 # When migrating 1.8.6 => 1.8.5, all we need to do is define an empty
\r
134 # #marshal_load() method for Mutex. For 1.8.5 => 1.8.6 we need something
\r
135 # dirtier, as seen later on in the initialization code.
\r
136 unless Mutex.new.respond_to?(:marshal_load)
\r
138 def marshal_load(str)
\r
146 if @registry.has_key?(:feeds)
\r
147 # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the
\r
148 # data unrestorable. If this happens, we patch the data, thus allowing
\r
149 # the restore to work.
\r
151 # This is actually pretty safe for a number of reasons:
\r
152 # * the code is only called if standard marshalling fails
\r
153 # * the string we look for is quite unlikely to appear randomly
\r
154 # * if the string appears somewhere and the patched string isn't recoverable
\r
155 # either, we'll get another (unrecoverable) error, which makes the rss
\r
156 # plugin unsable, just like it was if no recovery was attempted
\r
157 # * if the string appears somewhere and the patched string is recoverable,
\r
158 # we may get a b0rked feed, which is eventually overwritten by a clean
\r
159 # one, so the worst thing that can happen is that a feed update spams
\r
160 # the watchers once
\r
161 @registry.recovery = Proc.new { |val|
\r
162 patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")
\r
163 ret = Marshal.restore(patched)
\r
164 ret.each_value { |blob|
\r
170 @feeds = @registry[:feeds]
\r
172 @registry.recovery = nil
\r
174 @feeds.keys.grep(/[A-Z]/) { |k|
\r
175 @feeds[k.downcase] = @feeds[k]
\r
178 @feeds.each { |k, f|
\r
179 f.mutex = Mutex.new unless f.mutex
\r
180 f.sanitize_watchers
\r
181 parseRss(f) if f.xml
\r
195 @feeds.select { |h, f| f.watched? }
\r
203 unparsed = Hash.new()
\r
204 @feeds.each { |k, f|
\r
205 unparsed[k] = f.dup
\r
206 # we don't want to save the mutex
\r
207 unparsed[k].mutex = nil
\r
209 @registry[:feeds] = unparsed
\r
212 def stop_watch(handle)
\r
213 if @watch.has_key?(handle)
\r
215 debug "Stopping watch #{handle}"
\r
216 @bot.timer.remove(@watch[handle])
\r
217 @watch.delete(handle)
\r
219 report_problem("Failed to stop watch for #{handle}", e, nil)
\r
225 @watch.each_key { |k|
\r
230 def help(plugin,topic="")
\r
233 "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
235 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
\r
237 "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
\r
238 when "who", "watches", "who watches"
\r
239 "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
\r
241 "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
243 "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
244 when /^(del(ete)?|rm)$/
\r
245 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
\r
247 "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
248 when "forcereplace"
\r
249 "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
251 "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
252 when /(un|rm)watch/
\r
253 "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
\r
255 "rss rewatch : restart threads that watch for changes in watched rss"
\r
257 "manage RSS feeds: rss show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch"
\r
261 def report_problem(report, e=nil, m=nil)
\r
262 if m && m.respond_to?(:reply)
\r
269 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
\r
273 def show_rss(m, params)
\r
274 handle = params[:handle]
\r
275 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
\r
276 debug lims.to_a.inspect
\r
278 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
\r
279 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
\r
280 rev = lims[1].to_i > lims[2].to_i
\r
283 ul = [[lims[1].to_i-1, 0].max, 14].min
\r
287 feed = @feeds.fetch(handle.downcase, nil)
\r
289 m.reply "I don't know any feeds named #{handle}"
\r
293 m.reply "lemme fetch it..."
\r
294 title = items = nil
\r
295 fetched = fetchRss(feed, m)
\r
296 return unless fetched or feed.xml
\r
297 if not fetched and feed.items
\r
298 m.reply "using old data"
\r
300 parsed = parseRss(feed, m)
\r
301 m.reply "using old data" unless parsed
\r
303 return unless feed.items
\r
307 # We sort the feeds in freshness order (newer ones first)
\r
308 items = freshness_sort(items)
\r
309 disp = items[ll..ul]
\r
310 disp.reverse! if rev
\r
312 m.reply "Channel : #{title}"
\r
313 disp.each do |item|
\r
314 printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})
\r
318 def itemDate(item,ex=nil)
\r
319 return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
\r
320 return item.date if item.respond_to?(:date) and item.date
\r
324 def freshness_sort(items)
\r
325 notime = Time.at(0)
\r
326 items.sort { |a, b|
\r
327 itemDate(b, notime) <=> itemDate(a, notime)
\r
331 def list_rss(m, params)
\r
332 wanted = params[:handle]
\r
334 @feeds.each { |handle, feed|
\r
335 next if wanted and !handle.match(/#{wanted}/i)
\r
336 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
337 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
338 (reply << " (watched)") if feed.watched_by?(m.replyto)
\r
342 reply = "no feeds found"
\r
343 reply << " matching #{wanted}" if wanted
\r
348 def watched_rss(m, params)
\r
349 wanted = params[:handle]
\r
350 chan = params[:chan] || m.replyto
\r
352 watchlist.each { |handle, feed|
\r
353 next if wanted and !handle.match(/#{wanted}/i)
\r
354 next unless feed.watched_by?(chan)
\r
355 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
356 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
360 reply = "no watched feeds"
\r
361 reply << " matching #{wanted}" if wanted
\r
366 def who_watches(m, params)
\r
367 wanted = params[:handle]
\r
369 watchlist.each { |handle, feed|
\r
370 next if wanted and !handle.match(/#{wanted}/i)
\r
371 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
372 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
373 reply << ": watched by #{feed.watchers.join(', ')}"
\r
377 reply = "no watched feeds"
\r
378 reply << " matching #{wanted}" if wanted
\r
383 def add_rss(m, params, force=false)
\r
384 handle = params[:handle]
\r
386 unless url.match(/https?/)
\r
387 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
\r
390 type = params[:type]
\r
391 if @feeds.fetch(handle.downcase, nil) && !force
\r
392 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
\r
396 m.reply "You must specify both a handle and an url to add an RSS feed"
\r
399 @feeds[handle.downcase] = RssBlob.new(url,handle,type)
\r
400 reply = "Added RSS #{url} named #{handle}"
\r
402 reply << " (format: #{type})"
\r
408 def change_rss(m, params)
\r
409 handle = params[:handle].downcase
\r
410 feed = @feeds.fetch(handle, nil)
\r
412 m.reply "No such feed with handle #{handle}"
\r
415 case params[:what].intern
\r
417 new = params[:new].downcase
\r
418 if @feeds.key?(new) and @feeds[new]
\r
419 m.reply "There already is a feed with handle #{new}"
\r
422 feed.mutex.synchronize do
\r
424 @feeds.delete(handle)
\r
431 feed.mutex.synchronize do
\r
434 when :format, :type
\r
436 new = nil if new == 'default'
\r
437 feed.mutex.synchronize do
\r
441 new = params[:new].to_i
\r
442 new = nil if new == 0
\r
443 feed.mutex.synchronize do
\r
444 feed.refresh_rate = new
\r
447 m.reply "Don't know how to change #{params[:what]} for feeds"
\r
450 m.reply "Feed changed:"
\r
451 list_rss(m, {:handle => handle})
\r
454 def del_rss(m, params, pass=false)
\r
455 feed = unwatch_rss(m, params, true)
\r
457 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
\r
460 @feeds.delete(feed.handle.downcase)
\r
465 def replace_rss(m, params)
\r
466 handle = params[:handle]
\r
467 if @feeds.key?(handle.downcase)
\r
468 del_rss(m, {:handle => handle}, true)
\r
470 if @feeds.key?(handle.downcase)
\r
471 m.reply "can't replace #{feed.handle}"
\r
473 add_rss(m, params, true)
\r
477 def forcereplace_rss(m, params)
\r
478 add_rss(m, params, true)
\r
481 def watch_rss(m, params)
\r
482 handle = params[:handle]
\r
483 chan = params[:chan] || m.replyto
\r
485 type = params[:type]
\r
489 feed = @feeds.fetch(handle.downcase, nil)
\r
491 if feed.add_watch(chan)
\r
495 m.reply "Already watching #{feed.handle} in #{chan}"
\r
498 m.reply "Couldn't watch feed #{handle} (no such feed found)"
\r
502 def unwatch_rss(m, params, pass=false)
\r
503 handle = params[:handle].downcase
\r
504 chan = params[:chan] || m.replyto
\r
505 unless @feeds.has_key?(handle)
\r
506 m.reply("dunno that feed")
\r
509 feed = @feeds[handle]
\r
510 if feed.rm_watch(chan)
\r
511 m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
\r
513 m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
\r
521 def rewatch_rss(m=nil, params=nil)
\r
524 # Read watches from list.
\r
525 watchlist.each{ |handle, feed|
\r
532 def watchRss(feed, m=nil)
\r
533 if @watch.has_key?(feed.handle)
\r
534 report_problem("watcher thread for #{feed.handle} is already running", nil, m)
\r
538 status[:failures] = 0
\r
539 @watch[feed.handle] = @bot.timer.add(0, status) {
\r
540 debug "watcher for #{feed} started"
\r
541 failures = status[:failures]
\r
543 debug "fetching #{feed}"
\r
544 oldxml = feed.xml ? feed.xml.dup : nil
\r
545 unless fetchRss(feed)
\r
548 if oldxml and oldxml == feed.xml
\r
549 debug "xml for #{feed} didn't change"
\r
550 failures -= 1 if failures > 0
\r
553 debug "no previous items in feed #{feed}"
\r
555 failures -= 1 if failures > 0
\r
557 otxt = feed.items.map { |item| item.to_s }
\r
558 unless parseRss(feed)
\r
559 debug "no items in feed #{feed}"
\r
562 debug "Checking if new items are available for #{feed}"
\r
563 failures -= 1 if failures > 0
\r
564 dispItems = feed.items.reject { |item|
\r
565 otxt.include?(item.to_s)
\r
567 if dispItems.length > 0
\r
568 debug "Found #{dispItems.length} new items in #{feed}"
\r
569 # When displaying watched feeds, publish them from older to newer
\r
570 dispItems.reverse.each { |item|
\r
571 printFormattedRss(feed, item)
\r
574 debug "No new items found in #{feed}"
\r
580 rescue Exception => e
\r
581 error "Error watching #{feed}: #{e.inspect}"
\r
582 debug e.backtrace.join("\n")
\r
586 status[:failures] = failures
\r
588 feed.mutex.synchronize do
\r
589 seconds = (feed.refresh_rate || @bot.config['rss.thread_sleep']) * (failures + 1)
\r
590 seconds += seconds * (rand(100)-50)/100
\r
591 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
\r
592 @bot.timer.reschedule(@watch[feed.handle], seconds)
\r
595 debug "watcher for #{feed} added"
\r
598 def printFormattedRss(feed, item, opts=nil)
\r
599 places = feed.watchers
\r
600 handle = "::#{feed.handle}:: "
\r
603 places = opts[:places] if opts.key?(:places)
\r
604 handle = opts[:handle].to_s if opts.key?(:handle)
\r
605 if opts.key?(:date) && opts[:date]
\r
606 if item.respond_to?(:pubDate)
\r
607 if item.pubDate.class <= Time
\r
608 date = item.pubDate.strftime("%Y/%m/%d %H.%M.%S")
\r
610 date = item.pubDate.to_s
\r
612 elsif item.respond_to?(:date)
\r
613 if item.date.class <= Time
\r
614 date = item.date.strftime("%Y/%m/%d %H.%M.%S")
\r
616 date = item.date.to_s
\r
624 title = "#{Bold}#{item.title.chomp.riphtml}#{Bold}" if item.title
\r
625 desc = item.description.gsub(/\s+/,' ').strip.riphtml if item.description
\r
626 link = item.link.chomp if item.link
\r
631 line1 = "#{handle}#{date}#{item.category.content} blogged at #{link}"
\r
632 line2 = "#{handle}#{title} - #{desc}"
\r
634 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"
\r
636 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link} has been edited by #{item.dc_creator}. #{desc}"
\r
638 line1 = "#{handle}#{date}Message #{title} sent by #{item.dc_creator}. #{desc}"
\r
640 line1 = "#{handle}#{date}#{title} @ #{link}"
\r
641 unless item.title =~ /^Changeset \[(\d+)\]/
\r
642 line2 = "#{handle}#{date}#{desc}"
\r
645 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"
\r
647 places.each { |loc|
\r
648 @bot.say loc, line1, :overlong => :truncate
\r
650 @bot.say loc, line2, :overlong => :truncate
\r
654 def fetchRss(feed, m=nil)
\r
656 # Use 60 sec timeout, cause the default is too low
\r
657 xml = @bot.httputil.get_cached(feed.url, 60, 60)
\r
658 rescue URI::InvalidURIError, URI::BadURIError => e
\r
659 report_problem("invalid rss feed #{feed.url}", e, m)
\r
662 report_problem("error getting #{feed.url}", e, m)
\r
665 debug "fetched #{feed}"
\r
667 report_problem("reading feed #{feed} failed", nil, m)
\r
670 # Ok, 0.9 feeds are not supported, maybe because
\r
671 # Netscape happily removed the DTD. So what we do is just to
\r
672 # reassign the 0.9 RDFs to 1.0, and hope it goes right.
\r
673 xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",
\r
674 "xmlns=\"http://purl.org/rss/1.0/\"")
\r
675 feed.mutex.synchronize do
\r
681 def parseRss(feed, m=nil)
\r
682 return nil unless feed.xml
\r
683 feed.mutex.synchronize do
\r
686 ## do validate parse
\r
687 rss = RSS::Parser.parse(xml)
\r
688 debug "parsed and validated #{feed}"
\r
689 rescue RSS::InvalidRSSError
\r
690 ## do non validate parse for invalid RSS 1.0
\r
692 rss = RSS::Parser.parse(xml, false)
\r
693 debug "parsed but not validated #{feed}"
\r
694 rescue RSS::Error => e
\r
695 report_problem("parsing rss stream failed, whoops =(", e, m)
\r
698 rescue RSS::Error => e
\r
699 report_problem("parsing rss stream failed, oioi", e, m)
\r
702 report_problem("processing error occured, sorry =(", e, m)
\r
707 report_problem("#{feed} does not include RSS 1.0 or 0.9x/2.0", nil, m)
\r
710 rss.output_encoding = 'UTF-8'
\r
711 rescue RSS::UnknownConvertMethod => e
\r
712 report_problem("bah! something went wrong =(", e, m)
\r
715 rss.channel.title ||= "Unknown"
\r
716 title = rss.channel.title
\r
717 rss.items.each do |item|
\r
718 item.title ||= "Unknown"
\r
724 report_problem("no items found in the feed, maybe try weed?", e, m)
\r
734 plugin = RSSFeedsPlugin.new
\r
736 plugin.map 'rss show :handle :limit',
\r
737 :action => 'show_rss',
\r
738 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
\r
739 :defaults => {:limit => 5}
\r
740 plugin.map 'rss list :handle',
\r
741 :action => 'list_rss',
\r
742 :defaults => {:handle => nil}
\r
743 plugin.map 'rss watched :handle [in :chan]',
\r
744 :action => 'watched_rss',
\r
745 :defaults => {:handle => nil}
\r
746 plugin.map 'rss who watches :handle',
\r
747 :action => 'who_watches',
\r
748 :defaults => {:handle => nil}
\r
749 plugin.map 'rss add :handle :url :type',
\r
750 :action => 'add_rss',
\r
751 :defaults => {:type => nil}
\r
752 plugin.map 'rss change :what of :handle to :new',
\r
753 :action => 'change_rss',
\r
754 :requirements => { :what => /handle|url|format|type|refresh/ }
\r
755 plugin.map 'rss change :what for :handle to :new',
\r
756 :action => 'change_rss',
\r
757 :requirements => { :what => /handle|url|format|type|refesh/ }
\r
758 plugin.map 'rss del :handle',
\r
759 :action => 'del_rss'
\r
760 plugin.map 'rss delete :handle',
\r
761 :action => 'del_rss'
\r
762 plugin.map 'rss rm :handle',
\r
763 :action => 'del_rss'
\r
764 plugin.map 'rss replace :handle :url :type',
\r
765 :action => 'replace_rss',
\r
766 :defaults => {:type => nil}
\r
767 plugin.map 'rss forcereplace :handle :url :type',
\r
768 :action => 'forcereplace_rss',
\r
769 :defaults => {:type => nil}
\r
770 plugin.map 'rss watch :handle :url :type [in :chan]',
\r
771 :action => 'watch_rss',
\r
772 :defaults => {:url => nil, :type => nil}
\r
773 plugin.map 'rss unwatch :handle [in :chan]',
\r
774 :action => 'unwatch_rss'
\r
775 plugin.map 'rss rmwatch :handle [in :chan]',
\r
776 :action => 'unwatch_rss'
\r
777 plugin.map 'rss rewatch',
\r
778 :action => 'rewatch_rss'
\r