4 # RSS feed plugin for RubyBot
\r
5 # (c) 2004 Stanislav Karchebny <berkus@madfire.net>
\r
6 # (c) 2005 Ian Monroe <ian@monroe.nu>
\r
7 # (c) 2005 Mark Kretschmann <markey@web.de>
\r
8 # (c) 2006 Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
\r
10 # Licensed under MIT License.
\r
12 require 'rss/parser'
\r
15 require 'rss/dublincore'
\r
17 # require 'rss/dublincore/2.0'
\r
19 # warning "Unable to load RSS libraries, RSS plugin functionality crippled"
\r
24 attr_accessor :handle
\r
27 attr_accessor :refresh_rate
\r
29 attr_accessor :title
\r
30 attr_accessor :items
\r
31 attr_accessor :mutex
\r
33 def initialize(url,handle=nil,type=nil,watchers=[], xml=nil)
\r
47 sanitize_watchers(watchers)
\r
51 self.class.new(@url,
\r
53 @type ? @type.dup : nil,
\r
55 @xml ? @xml.dup : nil)
\r
58 # Downcase all watchers, possibly turning them into Strings if they weren't
\r
59 def sanitize_watchers(list=@watchers)
\r
71 def watched_by?(who)
\r
72 @watchers.include?(who.downcase)
\r
79 @watchers << who.downcase
\r
84 @watchers.delete(who.downcase)
\r
88 [@handle,@url,@type,@refresh_rate,@watchers]
\r
91 def to_s(watchers=false)
\r
93 a = self.to_a.flatten
\r
97 a.compact.join(" | ")
\r
101 class RSSFeedsPlugin < Plugin
\r
102 BotConfig.register BotConfigIntegerValue.new('rss.head_max',
\r
103 :default => 30, :validate => Proc.new{|v| v > 0 && v < 200},
\r
104 :desc => "How many characters to use of a RSS item header")
\r
106 BotConfig.register BotConfigIntegerValue.new('rss.text_max',
\r
107 :default => 90, :validate => Proc.new{|v| v > 0 && v < 400},
\r
108 :desc => "How many characters to use of a RSS item text")
\r
110 BotConfig.register BotConfigIntegerValue.new('rss.thread_sleep',
\r
111 :default => 300, :validate => Proc.new{|v| v > 30},
\r
112 :desc => "How many seconds to sleep before checking RSS feeds again")
\r
116 if @registry.has_key?(:feeds)
\r
117 @feeds = @registry[:feeds]
\r
118 @feeds.keys.grep(/[A-Z]/) { |k|
\r
119 @feeds[k.downcase] = @feeds[k]
\r
122 @feeds.each { |k, f|
\r
123 f.mutex = Mutex.new unless f.mutex
\r
124 f.sanitize_watchers
\r
125 parseRss(f) if f.xml
\r
139 @feeds.select { |h, f| f.watched? }
\r
147 unparsed = Hash.new()
\r
148 @feeds.each { |k, f|
\r
149 f.mutex.synchronize do
\r
150 unparsed[k] = f.dup
\r
153 @registry[:feeds] = unparsed
\r
156 def stop_watch(handle)
\r
157 if @watch.has_key?(handle)
\r
159 debug "Stopping watch #{handle}"
\r
160 @bot.timer.remove(@watch[handle])
\r
161 @watch.delete(handle)
\r
163 report_problem("Failed to stop watch for #{handle}", e, nil)
\r
169 @watch.each_key { |k|
\r
174 def help(plugin,topic="")
\r
177 "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
179 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
\r
181 "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"
\r
182 when "who", "watches", "who watches"
\r
183 "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"
\r
185 "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
187 "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
188 when /^(del(ete)?|rm)$/
\r
189 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
\r
191 "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
192 when "forcereplace"
\r
193 "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
195 "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
196 when /(un|rm)watch/
\r
197 "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"
\r
199 "rss rewatch : restart threads that watch for changes in watched rss"
\r
201 "manage RSS feeds: rss show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch"
\r
205 def report_problem(report, e=nil, m=nil)
\r
206 if m && m.respond_to?(:reply)
\r
213 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
\r
217 def show_rss(m, params)
\r
218 handle = params[:handle]
\r
219 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
\r
220 debug lims.to_a.inspect
\r
222 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
\r
223 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
\r
224 rev = lims[1].to_i > lims[2].to_i
\r
227 ul = [[lims[1].to_i-1, 0].max, 14].min
\r
231 feed = @feeds.fetch(handle.downcase, nil)
\r
233 m.reply "I don't know any feeds named #{handle}"
\r
237 m.reply "lemme fetch it..."
\r
238 title = items = nil
\r
239 fetched = fetchRss(feed, m)
\r
240 return unless fetched or feed.xml
\r
241 if not fetched and feed.items
\r
242 m.reply "using old data"
\r
244 parsed = parseRss(feed, m)
\r
245 m.reply "using old data" unless parsed
\r
247 return unless feed.items
\r
251 # We sort the feeds in freshness order (newer ones first)
\r
252 items = freshness_sort(items)
\r
253 disp = items[ll..ul]
\r
254 disp.reverse! if rev
\r
256 m.reply "Channel : #{title}"
\r
257 disp.each do |item|
\r
258 printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})
\r
262 def itemDate(item,ex=nil)
\r
263 return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
\r
264 return item.date if item.respond_to?(:date) and item.date
\r
268 def freshness_sort(items)
\r
269 notime = Time.at(0)
\r
270 items.sort { |a, b|
\r
271 itemDate(b, notime) <=> itemDate(a, notime)
\r
275 def list_rss(m, params)
\r
276 wanted = params[:handle]
\r
278 @feeds.each { |handle, feed|
\r
279 next if wanted and !handle.match(/#{wanted}/i)
\r
280 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
281 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
282 (reply << " (watched)") if feed.watched_by?(m.replyto)
\r
286 reply = "no feeds found"
\r
287 reply << " matching #{wanted}" if wanted
\r
292 def watched_rss(m, params)
\r
293 wanted = params[:handle]
\r
294 chan = params[:chan] || m.replyto
\r
296 watchlist.each { |handle, feed|
\r
297 next if wanted and !handle.match(/#{wanted}/i)
\r
298 next unless feed.watched_by?(chan)
\r
299 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
300 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
304 reply = "no watched feeds"
\r
305 reply << " matching #{wanted}" if wanted
\r
310 def who_watches(m, params)
\r
311 wanted = params[:handle]
\r
313 watchlist.each { |handle, feed|
\r
314 next if wanted and !handle.match(/#{wanted}/i)
\r
315 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
316 (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate
\r
317 reply << ": watched by #{feed.watchers.join(', ')}"
\r
321 reply = "no watched feeds"
\r
322 reply << " matching #{wanted}" if wanted
\r
327 def add_rss(m, params, force=false)
\r
328 handle = params[:handle]
\r
330 unless url.match(/https?/)
\r
331 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
\r
334 type = params[:type]
\r
335 if @feeds.fetch(handle.downcase, nil) && !force
\r
336 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
\r
340 m.reply "You must specify both a handle and an url to add an RSS feed"
\r
343 @feeds[handle.downcase] = RssBlob.new(url,handle,type)
\r
344 reply = "Added RSS #{url} named #{handle}"
\r
346 reply << " (format: #{type})"
\r
352 def change_rss(m, params)
\r
353 handle = params[:handle].downcase
\r
354 feed = @feeds.fetch(handle, nil)
\r
356 m.reply "No such feed with handle #{handle}"
\r
359 case params[:what].intern
\r
361 new = params[:new].downcase
\r
362 if @feeds.key?(new) and @feeds[new]
\r
363 m.reply "There already is a feed with handle #{new}"
\r
366 feed.mutex.synchronize do
\r
368 @feeds.delete(handle)
\r
375 feed.mutex.synchronize do
\r
378 when :format, :type
\r
380 new = nil if new == 'default'
\r
381 feed.mutex.synchronize do
\r
385 new = params[:new].to_i
\r
386 new = nil if new == 0
\r
387 feed.mutex.synchronize do
\r
388 feed.refresh_rate = new
\r
391 m.reply "Don't know how to change #{params[:what]} for feeds"
\r
394 m.reply "Feed changed:"
\r
395 list_rss(m, {:handle => handle})
\r
398 def del_rss(m, params, pass=false)
\r
399 feed = unwatch_rss(m, params, true)
\r
401 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
\r
404 @feeds.delete(feed.handle.downcase)
\r
409 def replace_rss(m, params)
\r
410 handle = params[:handle]
\r
411 if @feeds.key?(handle.downcase)
\r
412 del_rss(m, {:handle => handle}, true)
\r
414 if @feeds.key?(handle.downcase)
\r
415 m.reply "can't replace #{feed.handle}"
\r
417 add_rss(m, params, true)
\r
421 def forcereplace_rss(m, params)
\r
422 add_rss(m, params, true)
\r
425 def watch_rss(m, params)
\r
426 handle = params[:handle]
\r
427 chan = params[:chan] || m.replyto
\r
429 type = params[:type]
\r
433 feed = @feeds.fetch(handle.downcase, nil)
\r
435 if feed.add_watch(chan)
\r
439 m.reply "Already watching #{feed.handle} in #{chan}"
\r
442 m.reply "Couldn't watch feed #{handle} (no such feed found)"
\r
446 def unwatch_rss(m, params, pass=false)
\r
447 handle = params[:handle].downcase
\r
448 chan = params[:chan] || m.replyto
\r
449 unless @feeds.has_key?(handle)
\r
450 m.reply("dunno that feed")
\r
453 feed = @feeds[handle]
\r
454 if feed.rm_watch(chan)
\r
455 m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"
\r
457 m.reply("#{chan} wasn't watching #{feed.handle}") unless pass
\r
465 def rewatch_rss(m=nil, params=nil)
\r
468 # Read watches from list.
\r
469 watchlist.each{ |handle, feed|
\r
476 def watchRss(feed, m=nil)
\r
477 if @watch.has_key?(feed.handle)
\r
478 report_problem("watcher thread for #{feed.handle} is already running", nil, m)
\r
482 status[:failures] = 0
\r
483 @watch[feed.handle] = @bot.timer.add(0, status) {
\r
484 debug "watcher for #{feed} started"
\r
485 failures = status[:failures]
\r
487 debug "fetching #{feed}"
\r
488 oldxml = feed.xml ? feed.xml.dup : nil
\r
489 unless fetchRss(feed)
\r
492 if oldxml and oldxml == feed.xml
\r
493 debug "xml for #{feed} didn't change"
\r
494 failures -= 1 if failures > 0
\r
497 debug "no previous items in feed #{feed}"
\r
499 failures -= 1 if failures > 0
\r
501 otxt = feed.items.map { |item| item.to_s }
\r
502 unless parseRss(feed)
\r
503 debug "no items in feed #{feed}"
\r
506 debug "Checking if new items are available for #{feed}"
\r
507 failures -= 1 if failures > 0
\r
508 dispItems = feed.items.reject { |item|
\r
509 otxt.include?(item.to_s)
\r
511 if dispItems.length > 0
\r
512 debug "Found #{dispItems.length} new items in #{feed}"
\r
513 # When displaying watched feeds, publish them from older to newer
\r
514 dispItems.reverse.each { |item|
\r
515 printFormattedRss(feed, item)
\r
518 debug "No new items found in #{feed}"
\r
524 rescue Exception => e
\r
525 error "Error watching #{feed}: #{e.inspect}"
\r
526 debug e.backtrace.join("\n")
\r
530 status[:failures] = failures
\r
532 feed.mutex.synchronize do
\r
533 seconds = (feed.refresh_rate || @bot.config['rss.thread_sleep']) * (failures + 1)
\r
534 seconds += seconds * (rand(100)-50)/100
\r
535 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
\r
536 @bot.timer.reschedule(@watch[feed.handle], seconds)
\r
539 debug "watcher for #{feed} added"
\r
542 def printFormattedRss(feed, item, opts=nil)
\r
543 places = feed.watchers
\r
544 handle = "::#{feed.handle}:: "
\r
547 places = opts[:places] if opts.key?(:places)
\r
548 handle = opts[:handle].to_s if opts.key?(:handle)
\r
549 if opts.key?(:date) && opts[:date]
\r
550 if item.respond_to?(:pubDate)
\r
551 if item.pubDate.class <= Time
\r
552 date = item.pubDate.strftime("%Y/%m/%d %H.%M.%S")
\r
554 date = item.pubDate.to_s
\r
556 elsif item.respond_to?(:date)
\r
557 if item.date.class <= Time
\r
558 date = item.date.strftime("%Y/%m/%d %H.%M.%S")
\r
560 date = item.date.to_s
\r
568 title = "#{Bold}#{item.title.chomp.riphtml}#{Bold}" if item.title
\r
569 desc = item.description.gsub(/\s+/,' ').strip.riphtml if item.description
\r
570 link = item.link.chomp if item.link
\r
575 line1 = "#{handle}#{date}#{item.category.content} blogged at #{link}"
\r
576 line2 = "#{handle}#{title} - #{desc}"
\r
578 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"
\r
580 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link} has been edited by #{item.dc_creator}. #{desc}"
\r
582 line1 = "#{handle}#{date}Message #{title} sent by #{item.dc_creator}. #{desc}"
\r
584 line1 = "#{handle}#{date}#{title} @ #{link}"
\r
585 unless item.title =~ /^Changeset \[(\d+)\]/
\r
586 line2 = "#{handle}#{date}#{desc}"
\r
589 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"
\r
591 places.each { |loc|
\r
592 @bot.say loc, line1, :overlong => :truncate
\r
594 @bot.say loc, line2, :overlong => :truncate
\r
598 def fetchRss(feed, m=nil)
\r
600 # Use 60 sec timeout, cause the default is too low
\r
601 xml = @bot.httputil.get_cached(feed.url, 60, 60)
\r
602 rescue URI::InvalidURIError, URI::BadURIError => e
\r
603 report_problem("invalid rss feed #{feed.url}", e, m)
\r
606 report_problem("error getting #{feed.url}", e, m)
\r
609 debug "fetched #{feed}"
\r
611 report_problem("reading feed #{feed} failed", nil, m)
\r
614 feed.mutex.synchronize do
\r
620 def parseRss(feed, m=nil)
\r
621 return nil unless feed.xml
\r
622 feed.mutex.synchronize do
\r
625 ## do validate parse
\r
626 rss = RSS::Parser.parse(xml)
\r
627 debug "parsed #{feed}"
\r
628 rescue RSS::InvalidRSSError
\r
629 ## do non validate parse for invalid RSS 1.0
\r
631 rss = RSS::Parser.parse(xml, false)
\r
632 rescue RSS::Error => e
\r
633 report_problem("parsing rss stream failed, whoops =(", e, m)
\r
636 rescue RSS::Error => e
\r
637 report_problem("parsing rss stream failed, oioi", e, m)
\r
640 report_problem("processing error occured, sorry =(", e, m)
\r
645 report_problem("#{feed} does not include RSS 1.0 or 0.9x/2.0", nil, m)
\r
648 rss.output_encoding = 'UTF-8'
\r
649 rescue RSS::UnknownConvertMethod => e
\r
650 report_problem("bah! something went wrong =(", e, m)
\r
653 rss.channel.title ||= "Unknown"
\r
654 title = rss.channel.title
\r
655 rss.items.each do |item|
\r
656 item.title ||= "Unknown"
\r
662 report_problem("no items found in the feed, maybe try weed?", e, m)
\r
672 plugin = RSSFeedsPlugin.new
\r
674 plugin.map 'rss show :handle :limit',
\r
675 :action => 'show_rss',
\r
676 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
\r
677 :defaults => {:limit => 5}
\r
678 plugin.map 'rss list :handle',
\r
679 :action => 'list_rss',
\r
680 :defaults => {:handle => nil}
\r
681 plugin.map 'rss watched :handle [in :chan]',
\r
682 :action => 'watched_rss',
\r
683 :defaults => {:handle => nil}
\r
684 plugin.map 'rss who watches :handle',
\r
685 :action => 'who_watches',
\r
686 :defaults => {:handle => nil}
\r
687 plugin.map 'rss add :handle :url :type',
\r
688 :action => 'add_rss',
\r
689 :defaults => {:type => nil}
\r
690 plugin.map 'rss change :what of :handle to :new',
\r
691 :action => 'change_rss',
\r
692 :requirements => { :what => /handle|url|format|type|refresh/ }
\r
693 plugin.map 'rss change :what for :handle to :new',
\r
694 :action => 'change_rss',
\r
695 :requirements => { :what => /handle|url|format|type|refesh/ }
\r
696 plugin.map 'rss del :handle',
\r
697 :action => 'del_rss'
\r
698 plugin.map 'rss delete :handle',
\r
699 :action => 'del_rss'
\r
700 plugin.map 'rss rm :handle',
\r
701 :action => 'del_rss'
\r
702 plugin.map 'rss replace :handle :url :type',
\r
703 :action => 'replace_rss',
\r
704 :defaults => {:type => nil}
\r
705 plugin.map 'rss forcereplace :handle :url :type',
\r
706 :action => 'forcereplace_rss',
\r
707 :defaults => {:type => nil}
\r
708 plugin.map 'rss watch :handle :url :type [in :chan]',
\r
709 :action => 'watch_rss',
\r
710 :defaults => {:url => nil, :type => nil}
\r
711 plugin.map 'rss unwatch :handle [in :chan]',
\r
712 :action => 'unwatch_rss'
\r
713 plugin.map 'rss rmwatch :handle [in :chan]',
\r
714 :action => 'unwatch_rss'
\r
715 plugin.map 'rss rewatch',
\r
716 :action => 'rewatch_rss'
\r