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 self.gsub(/<[^>]+>/, '').gsub(/&/,'&').gsub(/"/,'"').gsub(/</,'<').gsub(/>/,'>').gsub(/&ellip;/,'...').gsub(/'/, "'").gsub("\n",'')
\r
30 attr_accessor :handle
\r
34 attr_accessor :title
\r
35 attr_accessor :items
\r
36 attr_accessor :mutex
\r
38 def initialize(url,handle=nil,type=nil,watchers=[], xml=nil)
\r
51 sanitize_watchers(watchers)
\r
55 self.class.new(@url,
\r
57 @type ? @type.dup : nil,
\r
59 @xml ? @xml.dup : nil)
\r
62 # Downcase all watchers, possibly turning them into Strings if they weren't
\r
63 def sanitize_watchers(list=@watchers)
\r
75 def watched_by?(who)
\r
76 @watchers.include?(who.downcase)
\r
83 @watchers << who.downcase
\r
88 @watchers.delete(who.downcase)
\r
92 [@handle,@url,@type,@watchers]
\r
95 def to_s(watchers=false)
\r
97 a = self.to_a.flatten
\r
101 a.compact.join(" | ")
\r
105 class RSSFeedsPlugin < Plugin
\r
106 BotConfig.register BotConfigIntegerValue.new('rss.head_max',
\r
107 :default => 30, :validate => Proc.new{|v| v > 0 && v < 200},
\r
108 :desc => "How many characters to use of a RSS item header")
\r
110 BotConfig.register BotConfigIntegerValue.new('rss.text_max',
\r
111 :default => 90, :validate => Proc.new{|v| v > 0 && v < 400},
\r
112 :desc => "How many characters to use of a RSS item text")
\r
114 BotConfig.register BotConfigIntegerValue.new('rss.thread_sleep',
\r
115 :default => 300, :validate => Proc.new{|v| v > 30},
\r
116 :desc => "How many seconds to sleep before checking RSS feeds again")
\r
120 if @registry.has_key?(:feeds)
\r
121 @feeds = @registry[:feeds]
\r
122 @feeds.keys.grep(/[A-Z]/) { |k|
\r
123 @feeds[k.downcase] = @feeds[k]
\r
126 @feeds.each { |k, f|
\r
127 f.mutex = Mutex.new unless f.mutex
\r
128 f.sanitize_watchers
\r
129 parseRss(f) if f.xml
\r
143 @feeds.select { |h, f| f.watched? }
\r
151 unparsed = Hash.new()
\r
152 @feeds.each { |k, f|
\r
153 f.mutex.synchronize do
\r
154 unparsed[k] = f.dup
\r
157 unparsed.each { |k, f|
\r
160 @registry[:feeds] = unparsed
\r
163 def stop_watch(handle)
\r
164 if @watch.has_key?(handle)
\r
166 debug "Stopping watch #{handle}"
\r
167 @bot.timer.remove(@watch[handle])
\r
168 @watch.delete(handle)
\r
170 report_problem("Failed to stop watch for #{handle}", e, nil)
\r
176 @watch.each_key { |k|
\r
181 def help(plugin,topic="")
\r
184 "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
186 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
\r
188 "rss watched [#{Bold}handle#{Bold}] : list all watched rss feeds (matching #{Bold}handle#{Bold})"
\r
190 "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
192 "rss change #{Bold}what#{Bold} of #{Bold}handle#{Bold} to #{Bold}new#{Bold} : change the handle, url or type of rss called #{Bold}handle#{Bold} to value #{Bold}new#{Bold}"
\r
193 when /^(del(ete)?|rm)$/
\r
194 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
\r
196 "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
197 when "forcereplace"
\r
198 "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
200 "rss watch #{Bold}handle#{Bold} [#{Bold}url#{Bold} [#{Bold}type#{Bold}]] : watch rss #{Bold}handle#{Bold} for changes; when the other parameters are present, it will be created if it doesn't exist yet"
\r
201 when /(un|rm)watch/
\r
202 "rss unwatch|rmwatch #{Bold}handle#{Bold} : stop watching rss #{Bold}handle#{Bold} for changes"
\r
204 "rss rewatch : restart threads that watch for changes in watched rss"
\r
206 "manage RSS feeds: rss show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch"
\r
210 def report_problem(report, e=nil, m=nil)
\r
211 if m && m.respond_to?(:reply)
\r
218 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
\r
222 def show_rss(m, params)
\r
223 handle = params[:handle]
\r
224 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
\r
225 debug lims.to_a.inspect
\r
227 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
\r
228 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
\r
229 rev = lims[1].to_i > lims[2].to_i
\r
232 ul = [[lims[1].to_i-1, 0].max, 14].min
\r
236 feed = @feeds.fetch(handle.downcase, nil)
\r
238 m.reply "I don't know any feeds named #{handle}"
\r
242 m.reply "lemme fetch it..."
\r
243 title = items = nil
\r
244 fetched = fetchRss(feed, m)
\r
245 return unless fetched or feed.xml
\r
246 if not fetched and feed.items
\r
247 m.reply "using old data"
\r
249 parsed = parseRss(feed, m)
\r
250 m.reply "using old data" unless parsed
\r
252 return unless feed.items
\r
256 # We sort the feeds in freshness order (newer ones first)
\r
257 items = freshness_sort(items)
\r
258 disp = items[ll..ul]
\r
259 disp.reverse! if rev
\r
261 m.reply "Channel : #{title}"
\r
262 disp.each do |item|
\r
263 printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})
\r
267 def itemDate(item,ex=nil)
\r
268 return item.pubDate if item.respond_to?(:pubDate) and item.pubDate
\r
269 return item.date if item.respond_to?(:date) and item.date
\r
273 def freshness_sort(items)
\r
274 notime = Time.at(0)
\r
275 items.sort { |a, b|
\r
276 itemDate(b, notime) <=> itemDate(a, notime)
\r
280 def list_rss(m, params)
\r
281 wanted = params[:handle]
\r
283 @feeds.each { |handle, feed|
\r
284 next if wanted and !handle.match(/#{wanted}/i)
\r
285 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
286 (reply << " (watched)") if feed.watched_by?(m.replyto)
\r
290 reply = "no feeds found"
\r
291 reply << " matching #{wanted}" if wanted
\r
296 def watched_rss(m, params)
\r
297 wanted = params[:handle]
\r
299 watchlist.each { |handle, feed|
\r
300 next if wanted and !handle.match(/#{wanted}/i)
\r
301 next unless feed.watched_by?(m.replyto)
\r
302 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})\n"
\r
305 reply = "no watched feeds"
\r
306 reply << " matching #{wanted}" if wanted
\r
311 def add_rss(m, params, force=false)
\r
312 handle = params[:handle]
\r
314 unless url.match(/https?/)
\r
315 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
\r
318 type = params[:type]
\r
319 if @feeds.fetch(handle.downcase, nil) && !force
\r
320 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"
\r
324 m.reply "You must specify both a handle and an url to add an RSS feed"
\r
327 @feeds[handle.downcase] = RssBlob.new(url,handle,type)
\r
328 reply = "Added RSS #{url} named #{handle}"
\r
330 reply << " (format: #{type})"
\r
336 def change_rss(m, params)
\r
337 handle = params[:handle].downcase
\r
338 feed = @feeds.fetch(handle, nil)
\r
339 return m.reply "No such feed with handle #{handle}" unless feed
\r
340 case params[:what].intern
\r
342 new = params[:new].downcase
\r
343 if @feeds.key?(new) and @feeds[new]
\r
344 m.reply "There already is a feed with handle #{new}"
\r
348 @feeds.delete(handle)
\r
354 feed.mutex.synchronize do
\r
357 when :format, :type
\r
359 new = nil if new == 'default'
\r
360 feed.mutex.synchronize do
\r
364 m.reply "Don't know how to change #{params[:what]} for feeds"
\r
367 m.reply "Feed changed:"
\r
368 list_rss(m, {:handle => handle})
\r
371 def del_rss(m, params, pass=false)
\r
372 feed = unwatch_rss(m, params, true)
\r
374 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
\r
377 @feeds.delete(feed.handle.downcase)
\r
382 def replace_rss(m, params)
\r
383 handle = params[:handle]
\r
384 if @feeds.key?(handle.downcase)
\r
385 del_rss(m, {:handle => handle}, true)
\r
387 if @feeds.key?(handle.downcase)
\r
388 m.reply "can't replace #{feed.handle}"
\r
390 add_rss(m, params, true)
\r
394 def forcereplace_rss(m, params)
\r
395 add_rss(m, params, true)
\r
398 def watch_rss(m, params)
\r
399 handle = params[:handle]
\r
401 type = params[:type]
\r
405 feed = @feeds.fetch(handle.downcase, nil)
\r
407 if feed.add_watch(m.replyto)
\r
411 m.reply "Already watching #{feed.handle}"
\r
414 m.reply "Couldn't watch feed #{handle} (no such feed found)"
\r
418 def unwatch_rss(m, params, pass=false)
\r
419 handle = params[:handle].downcase
\r
420 unless @feeds.has_key?(handle)
\r
421 m.reply("dunno that feed")
\r
424 feed = @feeds[handle]
\r
425 if feed.rm_watch(m.replyto)
\r
426 m.reply "#{m.replyto} has been removed from the watchlist for #{feed.handle}"
\r
428 m.reply("#{m.replyto} wasn't watching #{feed.handle}") unless pass
\r
436 def rewatch_rss(m=nil, params=nil)
\r
439 # Read watches from list.
\r
440 watchlist.each{ |handle, feed|
\r
447 def watchRss(feed, m=nil)
\r
448 if @watch.has_key?(feed.handle)
\r
449 report_problem("watcher thread for #{feed.handle} is already running", nil, m)
\r
453 status[:failures] = 0
\r
454 @watch[feed.handle] = @bot.timer.add(0, status) {
\r
455 debug "watcher for #{feed} started"
\r
456 failures = status[:failures]
\r
458 debug "fetching #{feed}"
\r
459 oldxml = feed.xml ? feed.xml.dup : nil
\r
460 unless fetchRss(feed)
\r
463 if oldxml and oldxml == feed.xml
\r
464 debug "xml for #{feed} didn't change"
\r
465 failures -= 1 if failures > 0
\r
468 debug "no previous items in feed #{feed}"
\r
470 failures -= 1 if failures > 0
\r
472 otxt = feed.items.map { |item| item.to_s }
\r
473 unless parseRss(feed)
\r
474 debug "no items in feed #{feed}"
\r
477 debug "Checking if new items are available for #{feed}"
\r
478 failures -= 1 if failures > 0
\r
479 dispItems = feed.items.reject { |item|
\r
480 otxt.include?(item.to_s)
\r
482 if dispItems.length > 0
\r
483 debug "Found #{dispItems.length} new items in #{feed}"
\r
484 # When displaying watched feeds, publish them from older to newer
\r
485 dispItems.reverse.each { |item|
\r
486 printFormattedRss(feed, item)
\r
489 debug "No new items found in #{feed}"
\r
495 rescue Exception => e
\r
496 error "Error watching #{feed}: #{e.inspect}"
\r
497 debug e.backtrace.join("\n")
\r
501 status[:failures] = failures
\r
503 seconds = @bot.config['rss.thread_sleep'] * (failures + 1)
\r
504 seconds += seconds * (rand(100)-50)/100
\r
505 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
\r
506 @bot.timer.reschedule(@watch[feed.handle], seconds)
\r
508 debug "watcher for #{feed} added"
\r
511 def printFormattedRss(feed, item, opts=nil)
\r
512 places = feed.watchers
\r
513 handle = "::#{feed.handle}:: "
\r
516 places = opts[:places] if opts.key?(:places)
\r
517 handle = opts[:handle].to_s if opts.key?(:handle)
\r
518 if opts.key?(:date) && opts[:date]
\r
519 if item.respond_to?(:pubDate)
\r
520 if item.pubDate.class <= Time
\r
521 date = item.pubDate.strftime("%Y/%m/%d %H.%M.%S")
\r
523 date = item.pubDate.to_s
\r
525 elsif item.respond_to?(:date)
\r
526 if item.date.class <= Time
\r
527 date = item.date.strftime("%Y/%m/%d %H.%M.%S")
\r
529 date = item.date.to_s
\r
537 title = "#{Bold}#{item.title.chomp.riphtml}#{Bold}" if item.title
\r
538 desc = item.description.gsub(/\s+/,' ').strip.riphtml if item.description
\r
539 link = item.link.chomp if item.link
\r
544 line1 = "#{handle}#{date}#{item.category.content} blogged at #{link}"
\r
545 line2 = "#{handle}#{title} - #{desc}"
\r
547 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"
\r
549 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link} has been edited by #{item.dc_creator}. #{desc}"
\r
551 line1 = "#{handle}#{date}Message #{title} sent by #{item.dc_creator}. #{desc}"
\r
553 line1 = "#{handle}#{date}#{title} @ #{link}"
\r
554 unless item.title =~ /^Changeset \[(\d+)\]/
\r
555 line2 = "#{handle}#{date}#{desc}"
\r
558 line1 = "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"
\r
560 places.each { |loc|
\r
561 @bot.say loc, line1, :overlong => :truncate
\r
563 @bot.say loc, line2, :overlong => :truncate
\r
567 def fetchRss(feed, m=nil)
\r
569 # Use 60 sec timeout, cause the default is too low
\r
570 xml = @bot.httputil.get_cached(feed.url, 60, 60)
\r
571 rescue URI::InvalidURIError, URI::BadURIError => e
\r
572 report_problem("invalid rss feed #{feed.url}", e, m)
\r
575 report_problem("error getting #{feed.url}", e, m)
\r
578 debug "fetched #{feed}"
\r
580 report_problem("reading feed #{feed} failed", nil, m)
\r
583 feed.mutex.synchronize do
\r
589 def parseRss(feed, m=nil)
\r
590 return nil unless feed.xml
\r
591 feed.mutex.synchronize do
\r
594 ## do validate parse
\r
595 rss = RSS::Parser.parse(xml)
\r
596 debug "parsed #{feed}"
\r
597 rescue RSS::InvalidRSSError
\r
598 ## do non validate parse for invalid RSS 1.0
\r
600 rss = RSS::Parser.parse(xml, false)
\r
601 rescue RSS::Error => e
\r
602 report_problem("parsing rss stream failed, whoops =(", e, m)
\r
605 rescue RSS::Error => e
\r
606 report_problem("parsing rss stream failed, oioi", e, m)
\r
609 report_problem("processing error occured, sorry =(", e, m)
\r
614 report_problem("#{feed} does not include RSS 1.0 or 0.9x/2.0", nil, m)
\r
617 rss.output_encoding = 'UTF-8'
\r
618 rescue RSS::UnknownConvertMethod => e
\r
619 report_problem("bah! something went wrong =(", e, m)
\r
622 rss.channel.title ||= "Unknown"
\r
623 title = rss.channel.title
\r
624 rss.items.each do |item|
\r
625 item.title ||= "Unknown"
\r
631 report_problem("no items found in the feed, maybe try weed?", e, m)
\r
641 plugin = RSSFeedsPlugin.new
\r
643 plugin.map 'rss show :handle :limit',
\r
644 :action => 'show_rss',
\r
645 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
\r
646 :defaults => {:limit => 5}
\r
647 plugin.map 'rss list :handle',
\r
648 :action => 'list_rss',
\r
649 :defaults => {:handle => nil}
\r
650 plugin.map 'rss watched :handle',
\r
651 :action => 'watched_rss',
\r
652 :defaults => {:handle => nil}
\r
653 plugin.map 'rss add :handle :url :type',
\r
654 :action => 'add_rss',
\r
655 :defaults => {:type => nil}
\r
656 plugin.map 'rss change :what of :handle to :new',
\r
657 :action => 'change_rss',
\r
658 :requirements => { :what => /handle|url|format|type/ }
\r
659 plugin.map 'rss change :what for :handle to :new',
\r
660 :action => 'change_rss',
\r
661 :requirements => { :what => /handle|url|format|type/ }
\r
662 plugin.map 'rss del :handle',
\r
663 :action => 'del_rss'
\r
664 plugin.map 'rss delete :handle',
\r
665 :action => 'del_rss'
\r
666 plugin.map 'rss rm :handle',
\r
667 :action => 'del_rss'
\r
668 plugin.map 'rss replace :handle :url :type',
\r
669 :action => 'replace_rss',
\r
670 :defaults => {:type => nil}
\r
671 plugin.map 'rss forcereplace :handle :url :type',
\r
672 :action => 'forcereplace_rss',
\r
673 :defaults => {:type => nil}
\r
674 plugin.map 'rss watch :handle :url :type',
\r
675 :action => 'watch_rss',
\r
676 :defaults => {:url => nil, :type => nil}
\r
677 plugin.map 'rss unwatch :handle',
\r
678 :action => 'unwatch_rss'
\r
679 plugin.map 'rss rmwatch :handle',
\r
680 :action => 'unwatch_rss'
\r
681 plugin.map 'rss rewatch',
\r
682 :action => 'rewatch_rss'
\r