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
131 if @registry.has_key?(:feeds)
\r
132 @feeds = @registry[:feeds]
\r
133 @feeds.keys.grep(/[A-Z]/) { |k|
\r
134 @feeds[k.downcase] = @feeds[k]
\r
137 @feeds.each { |k, f|
\r
138 f.mutex = Mutex.new unless f.mutex
\r
139 f.sanitize_watchers
\r
140 parseRss(f) if f.xml
\r
154 @feeds.select { |h, f| f.watched? }
\r
162 unparsed = Hash.new()
\r
163 @feeds.each { |k, f|
\r
164 unparsed[k] = f.dup
\r
166 @registry[:feeds] = unparsed
\r
169 def stop_watch(handle)
\r
170 if @watch.has_key?(handle)
\r
172 debug "Stopping watch #{handle}"
\r
173 @bot.timer.remove(@watch[handle])
\r
174 @watch.delete(handle)
\r
176 report_problem("Failed to stop watch for #{handle}", e, nil)
\r
182 @watch.each_key { |k|
\r
187 def help(plugin,topic="")
\r
190 "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
192 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
\r
194 "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
\r
195 when "who", "watches", "who watches"
\r
196 "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
\r
198 "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
200 "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
201 when /^(del(ete)?|rm)$/
\r
202 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
\r
204 "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
205 when "forcereplace"
\r
206 "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
208 "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
209 when /(un|rm)watch/
\r
210 "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
\r
212 "rss rewatch : restart threads that watch for changes in watched rss"
\r
214 "manage RSS feeds: rss show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch"
\r
218 def report_problem(report, e=nil, m=nil)
\r
219 if m && m.respond_to?(:reply)
\r
226 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
\r
230 def show_rss(m, params)
\r
231 handle = params[:handle]
\r
232 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
\r
233 debug lims.to_a.inspect
\r
235 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
\r
236 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
\r
237 rev = lims[1].to_i > lims[2].to_i
\r
240 ul = [[lims[1].to_i-1, 0].max, 14].min
\r
244 feed = @feeds.fetch(handle.downcase, nil)
\r
246 m.reply "I don't know any feeds named #{handle}"
\r
250 m.reply "lemme fetch it..."
\r
251 title = items = nil
\r
252 fetched = fetchRss(feed, m)
\r
253 return unless fetched or feed.xml
\r
254 if not fetched and feed.items
\r
255 m.reply "using old data"
\r
257 parsed = parseRss(feed, m)
\r
258 m.reply "using old data" unless parsed
\r
260 return unless feed.items
\r
264 # We sort the feeds in freshness order (newer ones first)
\r
265 items = freshness_sort(items)
\r
266 disp = items[ll..ul]
\r
267 disp.reverse! if rev
\r
269 m.reply "Channel : #{title}"
\r
270 disp.each do |item|
\r
271 printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})
\r
275 def itemDate(item,ex=nil)
\r
276 return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
\r
277 return item.date if item.respond_to?(:date) and item.date
\r
281 def freshness_sort(items)
\r
282 notime = Time.at(0)
\r
283 items.sort { |a, b|
\r
284 itemDate(b, notime) <=> itemDate(a, notime)
\r
288 def list_rss(m, params)
\r
289 wanted = params[:handle]
\r
291 @feeds.each { |handle, feed|
\r
292 next if wanted and !handle.match(/#{wanted}/i)
\r
293 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
294 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
295 (reply << " (watched)") if feed.watched_by?(m.replyto)
\r
299 reply = "no feeds found"
\r
300 reply << " matching #{wanted}" if wanted
\r
305 def watched_rss(m, params)
\r
306 wanted = params[:handle]
\r
307 chan = params[:chan] || m.replyto
\r
309 watchlist.each { |handle, feed|
\r
310 next if wanted and !handle.match(/#{wanted}/i)
\r
311 next unless feed.watched_by?(chan)
\r
312 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
313 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
317 reply = "no watched feeds"
\r
318 reply << " matching #{wanted}" if wanted
\r
323 def who_watches(m, params)
\r
324 wanted = params[:handle]
\r
326 watchlist.each { |handle, feed|
\r
327 next if wanted and !handle.match(/#{wanted}/i)
\r
328 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
329 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
330 reply << ": watched by #{feed.watchers.join(', ')}"
\r
334 reply = "no watched feeds"
\r
335 reply << " matching #{wanted}" if wanted
\r
340 def add_rss(m, params, force=false)
\r
341 handle = params[:handle]
\r
343 unless url.match(/https?/)
\r
344 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
\r
347 type = params[:type]
\r
348 if @feeds.fetch(handle.downcase, nil) && !force
\r
349 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
\r
353 m.reply "You must specify both a handle and an url to add an RSS feed"
\r
356 @feeds[handle.downcase] = RssBlob.new(url,handle,type)
\r
357 reply = "Added RSS #{url} named #{handle}"
\r
359 reply << " (format: #{type})"
\r
365 def change_rss(m, params)
\r
366 handle = params[:handle].downcase
\r
367 feed = @feeds.fetch(handle, nil)
\r
369 m.reply "No such feed with handle #{handle}"
\r
372 case params[:what].intern
\r
374 new = params[:new].downcase
\r
375 if @feeds.key?(new) and @feeds[new]
\r
376 m.reply "There already is a feed with handle #{new}"
\r
379 feed.mutex.synchronize do
\r
381 @feeds.delete(handle)
\r
388 feed.mutex.synchronize do
\r
391 when :format, :type
\r
393 new = nil if new == 'default'
\r
394 feed.mutex.synchronize do
\r
398 new = params[:new].to_i
\r
399 new = nil if new == 0
\r
400 feed.mutex.synchronize do
\r
401 feed.refresh_rate = new
\r
404 m.reply "Don't know how to change #{params[:what]} for feeds"
\r
407 m.reply "Feed changed:"
\r
408 list_rss(m, {:handle => handle})
\r
411 def del_rss(m, params, pass=false)
\r
412 feed = unwatch_rss(m, params, true)
\r
414 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
\r
417 @feeds.delete(feed.handle.downcase)
\r
422 def replace_rss(m, params)
\r
423 handle = params[:handle]
\r
424 if @feeds.key?(handle.downcase)
\r
425 del_rss(m, {:handle => handle}, true)
\r
427 if @feeds.key?(handle.downcase)
\r
428 m.reply "can't replace #{feed.handle}"
\r
430 add_rss(m, params, true)
\r
434 def forcereplace_rss(m, params)
\r
435 add_rss(m, params, true)
\r
438 def watch_rss(m, params)
\r
439 handle = params[:handle]
\r
440 chan = params[:chan] || m.replyto
\r
442 type = params[:type]
\r
446 feed = @feeds.fetch(handle.downcase, nil)
\r
448 if feed.add_watch(chan)
\r
452 m.reply "Already watching #{feed.handle} in #{chan}"
\r
455 m.reply "Couldn't watch feed #{handle} (no such feed found)"
\r
459 def unwatch_rss(m, params, pass=false)
\r
460 handle = params[:handle].downcase
\r
461 chan = params[:chan] || m.replyto
\r
462 unless @feeds.has_key?(handle)
\r
463 m.reply("dunno that feed")
\r
466 feed = @feeds[handle]
\r
467 if feed.rm_watch(chan)
\r
468 m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
\r
470 m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
\r
478 def rewatch_rss(m=nil, params=nil)
\r
481 # Read watches from list.
\r
482 watchlist.each{ |handle, feed|
\r
489 def watchRss(feed, m=nil)
\r
490 if @watch.has_key?(feed.handle)
\r
491 report_problem("watcher thread for #{feed.handle} is already running", nil, m)
\r
495 status[:failures] = 0
\r
496 @watch[feed.handle] = @bot.timer.add(0, status) {
\r
497 debug "watcher for #{feed} started"
\r
498 failures = status[:failures]
\r
500 debug "fetching #{feed}"
\r
501 oldxml = feed.xml ? feed.xml.dup : nil
\r
502 unless fetchRss(feed)
\r
505 if oldxml and oldxml == feed.xml
\r
506 debug "xml for #{feed} didn't change"
\r
507 failures -= 1 if failures > 0
\r
510 debug "no previous items in feed #{feed}"
\r
512 failures -= 1 if failures > 0
\r
514 otxt = feed.items.map { |item| item.to_s }
\r
515 unless parseRss(feed)
\r
516 debug "no items in feed #{feed}"
\r
519 debug "Checking if new items are available for #{feed}"
\r
520 failures -= 1 if failures > 0
\r
521 dispItems = feed.items.reject { |item|
\r
522 otxt.include?(item.to_s)
\r
524 if dispItems.length > 0
\r
525 debug "Found #{dispItems.length} new items in #{feed}"
\r
526 # When displaying watched feeds, publish them from older to newer
\r
527 dispItems.reverse.each { |item|
\r
528 printFormattedRss(feed, item)
\r
531 debug "No new items found in #{feed}"
\r
537 rescue Exception => e
\r
538 error "Error watching #{feed}: #{e.inspect}"
\r
539 debug e.backtrace.join("\n")
\r
543 status[:failures] = failures
\r
545 feed.mutex.synchronize do
\r
546 seconds = (feed.refresh_rate || @bot.config['rss.thread_sleep']) * (failures + 1)
\r
547 seconds += seconds * (rand(100)-50)/100
\r
548 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
\r
549 @bot.timer.reschedule(@watch[feed.handle], seconds)
\r
552 debug "watcher for #{feed} added"
\r
555 def printFormattedRss(feed, item, opts=nil)
\r
556 places = feed.watchers
\r
557 handle = "::#{feed.handle}:: "
\r
560 places = opts[:places] if opts.key?(:places)
\r
561 handle = opts[:handle].to_s if opts.key?(:handle)
\r
562 if opts.key?(:date) && opts[:date]
\r
563 if item.respond_to?(:pubDate)
\r
564 if item.pubDate.class <= Time
\r
565 date = item.pubDate.strftime("%Y/%m/%d %H.%M.%S")
\r
567 date = item.pubDate.to_s
\r
569 elsif item.respond_to?(:date)
\r
570 if item.date.class <= Time
\r
571 date = item.date.strftime("%Y/%m/%d %H.%M.%S")
\r
573 date = item.date.to_s
\r
581 title = "#{Bold}#{item.title.chomp.riphtml}#{Bold}" if item.title
\r
582 desc = item.description.gsub(/\s+/,' ').strip.riphtml if item.description
\r
583 link = item.link.chomp if item.link
\r
588 line1 = "#{handle}#{date}#{item.category.content} blogged at #{link}"
\r
589 line2 = "#{handle}#{title} - #{desc}"
\r
591 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"
\r
593 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link} has been edited by #{item.dc_creator}. #{desc}"
\r
595 line1 = "#{handle}#{date}Message #{title} sent by #{item.dc_creator}. #{desc}"
\r
597 line1 = "#{handle}#{date}#{title} @ #{link}"
\r
598 unless item.title =~ /^Changeset \[(\d+)\]/
\r
599 line2 = "#{handle}#{date}#{desc}"
\r
602 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"
\r
604 places.each { |loc|
\r
605 @bot.say loc, line1, :overlong => :truncate
\r
607 @bot.say loc, line2, :overlong => :truncate
\r
611 def fetchRss(feed, m=nil)
\r
613 # Use 60 sec timeout, cause the default is too low
\r
614 xml = @bot.httputil.get_cached(feed.url, 60, 60)
\r
615 rescue URI::InvalidURIError, URI::BadURIError => e
\r
616 report_problem("invalid rss feed #{feed.url}", e, m)
\r
619 report_problem("error getting #{feed.url}", e, m)
\r
622 debug "fetched #{feed}"
\r
624 report_problem("reading feed #{feed} failed", nil, m)
\r
627 # Ok, 0.9 feeds are not supported, maybe because
\r
628 # Netscape happily removed the DTD. So what we do is just to
\r
629 # reassign the 0.9 RDFs to 1.0, and hope it goes right.
\r
630 xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",
\r
631 "xmlns=\"http://purl.org/rss/1.0/\"")
\r
632 feed.mutex.synchronize do
\r
638 def parseRss(feed, m=nil)
\r
639 return nil unless feed.xml
\r
640 feed.mutex.synchronize do
\r
643 ## do validate parse
\r
644 rss = RSS::Parser.parse(xml)
\r
645 debug "parsed and validated #{feed}"
\r
646 rescue RSS::InvalidRSSError
\r
647 ## do non validate parse for invalid RSS 1.0
\r
649 rss = RSS::Parser.parse(xml, false)
\r
650 debug "parsed but not validated #{feed}"
\r
651 rescue RSS::Error => e
\r
652 report_problem("parsing rss stream failed, whoops =(", e, m)
\r
655 rescue RSS::Error => e
\r
656 report_problem("parsing rss stream failed, oioi", e, m)
\r
659 report_problem("processing error occured, sorry =(", e, m)
\r
664 report_problem("#{feed} does not include RSS 1.0 or 0.9x/2.0", nil, m)
\r
667 rss.output_encoding = 'UTF-8'
\r
668 rescue RSS::UnknownConvertMethod => e
\r
669 report_problem("bah! something went wrong =(", e, m)
\r
672 rss.channel.title ||= "Unknown"
\r
673 title = rss.channel.title
\r
674 rss.items.each do |item|
\r
675 item.title ||= "Unknown"
\r
681 report_problem("no items found in the feed, maybe try weed?", e, m)
\r
691 plugin = RSSFeedsPlugin.new
\r
693 plugin.map 'rss show :handle :limit',
\r
694 :action => 'show_rss',
\r
695 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
\r
696 :defaults => {:limit => 5}
\r
697 plugin.map 'rss list :handle',
\r
698 :action => 'list_rss',
\r
699 :defaults => {:handle => nil}
\r
700 plugin.map 'rss watched :handle [in :chan]',
\r
701 :action => 'watched_rss',
\r
702 :defaults => {:handle => nil}
\r
703 plugin.map 'rss who watches :handle',
\r
704 :action => 'who_watches',
\r
705 :defaults => {:handle => nil}
\r
706 plugin.map 'rss add :handle :url :type',
\r
707 :action => 'add_rss',
\r
708 :defaults => {:type => nil}
\r
709 plugin.map 'rss change :what of :handle to :new',
\r
710 :action => 'change_rss',
\r
711 :requirements => { :what => /handle|url|format|type|refresh/ }
\r
712 plugin.map 'rss change :what for :handle to :new',
\r
713 :action => 'change_rss',
\r
714 :requirements => { :what => /handle|url|format|type|refesh/ }
\r
715 plugin.map 'rss del :handle',
\r
716 :action => 'del_rss'
\r
717 plugin.map 'rss delete :handle',
\r
718 :action => 'del_rss'
\r
719 plugin.map 'rss rm :handle',
\r
720 :action => 'del_rss'
\r
721 plugin.map 'rss replace :handle :url :type',
\r
722 :action => 'replace_rss',
\r
723 :defaults => {:type => nil}
\r
724 plugin.map 'rss forcereplace :handle :url :type',
\r
725 :action => 'forcereplace_rss',
\r
726 :defaults => {:type => nil}
\r
727 plugin.map 'rss watch :handle :url :type [in :chan]',
\r
728 :action => 'watch_rss',
\r
729 :defaults => {:url => nil, :type => nil}
\r
730 plugin.map 'rss unwatch :handle [in :chan]',
\r
731 :action => 'unwatch_rss'
\r
732 plugin.map 'rss rmwatch :handle [in :chan]',
\r
733 :action => 'unwatch_rss'
\r
734 plugin.map 'rss rewatch',
\r
735 :action => 'rewatch_rss'
\r