1 # RSS feed plugin for RubyBot
\r
2 # (c) 2004 Stanislav Karchebny <berkus@madfire.net>
\r
3 # (c) 2005 Ian Monroe <ian@monroe.nu>
\r
4 # (c) 2005 Mark Kretschmann <markey@web.de>
\r
5 # Licensed under MIT License.
\r
10 require 'rss/dublincore'
\r
12 # require 'rss/dublincore/2.0'
\r
14 # warning "Unable to load RSS libraries, RSS plugin functionality crippled"
\r
19 if self.length > limit
\r
20 self+". " =~ /^(.{#{limit}}[^.!;?]*[.!;?])/mi
\r
27 self.gsub(/<[^>]+>/, '').gsub(/&/,'&').gsub(/"/,'"').gsub(/</,'<').gsub(/>/,'>').gsub(/&ellip;/,'...').gsub(/'/, "'").gsub("\n",'')
\r
31 self.gsub(/'/, "''")
\r
41 def initialize(url,handle=nil,type=nil,watchers=[])
\r
49 @watchers = watchers
\r
56 def watched_by?(who)
\r
57 @watchers.include?(who)
\r
64 @watchers << who unless watched_by?(who)
\r
69 @watchers.delete(who)
\r
73 [@handle,@url,@type,@watchers]
\r
76 def to_s(watchers=false)
\r
78 a = self.to_a.flatten
\r
86 class RSSFeedsPlugin < Plugin
\r
87 BotConfig.register BotConfigIntegerValue.new('rss.head_max',
\r
88 :default => 30, :validate => Proc.new{|v| v > 0 && v < 200},
\r
89 :desc => "How many characters to use of a RSS item header")
\r
91 BotConfig.register BotConfigIntegerValue.new('rss.text_max',
\r
92 :default => 90, :validate => Proc.new{|v| v > 0 && v < 400},
\r
93 :desc => "How many characters to use of a RSS item text")
\r
95 BotConfig.register BotConfigIntegerValue.new('rss.thread_sleep',
\r
96 :default => 300, :validate => Proc.new{|v| v > 30},
\r
97 :desc => "How many characters to use of a RSS item text")
\r
99 @@watchThreads = Hash.new
\r
100 @@mutex = Mutex.new
\r
105 if @registry.has_key?(:feeds)
\r
106 @feeds = @registry[:feeds]
\r
114 @feeds.select { |h, f| f.watched? }
\r
122 @registry[:feeds] = @feeds
\r
126 @@mutex.synchronize {
\r
127 # Abort all running threads.
\r
128 @@watchThreads.each { |url, thread|
\r
129 debug "Killing thread for #{url}"
\r
132 @@watchThreads = Hash.new
\r
136 def help(plugin,topic="")
\r
139 "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
141 "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"
\r
143 "rss watched [#{Bold}handle#{Bold}] : list all watched rss feeds (matching #{Bold}handle#{Bold})"
\r
145 "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
146 when /^(del(ete)?|rm)$/
\r
147 "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"
\r
149 "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
150 when "forcereplace"
\r
151 "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
153 "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
154 when /(un|rm)watch/
\r
155 "rss unwatch|rmwatch #{Bold}handle#{Bold} : stop watching rss #{Bold}handle#{Bold} for changes"
\r
157 "rss rewatch : restart threads that watch for changes in watched rss"
\r
159 "manage RSS feeds: rss show|list|watched|add|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch"
\r
163 def report_problem(report, e=nil, m=nil)
\r
164 if m && m.respond_to?(:reply)
\r
171 debug e.backtrace.join("\n") if e.respond_to?(:backtrace)
\r
175 def show_rss(m, params)
\r
176 handle = params[:handle]
\r
177 lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)
\r
178 debug lims.to_a.inspect
\r
180 ll = [[lims[1].to_i-1,lims[2].to_i-1].min, 0].max
\r
181 ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min
\r
182 rev = lims[1].to_i > lims[2].to_i
\r
185 ul = [[lims[1].to_i-1, 1].max, 14].min
\r
189 feed = @feeds.fetch(handle, nil)
\r
191 m.reply "I don't know any feeds named #{handle}"
\r
195 m.reply "lemme fetch it..."
\r
196 title = items = nil
\r
197 @@mutex.synchronize {
\r
198 title, items = fetchRss(feed, m)
\r
200 return unless items
\r
202 # We sort the feeds in freshness order (newer ones first)
\r
203 items = freshness_sort(items)
\r
204 disp = items[ll..ul]
\r
205 disp.reverse! if rev
\r
207 m.reply "Channel : #{title}"
\r
208 disp.each do |item|
\r
209 printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})
\r
213 def itemDate(item,ex=nil)
\r
214 return item.pubDate if item.respond_to?(:pubDate)
\r
215 return item.date if item.respond_to?(:date)
\r
219 def freshness_sort(items)
\r
220 notime = Time.at(0)
\r
221 items.sort { |a, b|
\r
222 itemDate(b, notime) <=> itemDate(a, notime)
\r
226 def list_rss(m, params)
\r
227 wanted = params[:handle]
\r
229 @@mutex.synchronize {
\r
230 @feeds.each { |handle, feed|
\r
231 next if wanted and !handle.match(wanted)
\r
232 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"
\r
233 (reply << " (watched)") if feed.watched_by?(m.replyto)
\r
238 reply = "no feeds found"
\r
239 reply << " matching #{wanted}" if wanted
\r
244 def watched_rss(m, params)
\r
245 wanted = params[:handle]
\r
247 @@mutex.synchronize {
\r
248 watchlist.each { |handle, feed|
\r
249 next if wanted and !handle.match(wanted)
\r
250 next unless feed.watched_by?(m.replyto)
\r
251 reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})\n"
\r
255 reply = "no watched feeds"
\r
256 reply << " matching #{wanted}" if wanted
\r
261 def add_rss(m, params, force=false)
\r
262 handle = params[:handle]
\r
264 unless url.match(/https?/)
\r
265 m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"
\r
268 type = params[:type]
\r
269 if @feeds.fetch(handle, nil) && !force
\r
270 m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle].url})"
\r
274 m.reply "You must specify both a handle and an url to add an RSS feed"
\r
277 @@mutex.synchronize {
\r
278 @feeds[handle] = RssBlob.new(url,handle,type)
\r
280 reply = "Added RSS #{url} named #{handle}"
\r
282 reply << " (format: #{type})"
\r
288 def del_rss(m, params, pass=false)
\r
289 feed = unwatch_rss(m, params, true)
\r
291 m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"
\r
294 @@mutex.synchronize {
\r
295 @feeds.delete(feed.handle)
\r
301 def replace_rss(m, params)
\r
302 handle = params[:handle]
\r
303 if @feeds.key?(handle)
\r
304 del_rss(m, {:handle => handle}, true)
\r
306 if @feeds.key?(handle)
\r
307 m.reply "can't replace #{feed.handle}"
\r
309 add_rss(m, params, true)
\r
313 def forcereplace_rss(m, params)
\r
314 add_rss(m, params, true)
\r
317 def watch_rss(m, params)
\r
318 handle = params[:handle]
\r
320 type = params[:type]
\r
325 @@mutex.synchronize {
\r
326 feed = @feeds.fetch(handle, nil)
\r
329 @@mutex.synchronize {
\r
330 if feed.add_watch(m.replyto)
\r
334 m.reply "Already watching #{feed.handle}"
\r
338 m.reply "Couldn't watch feed #{handle} (no such feed found)"
\r
342 def unwatch_rss(m, params, pass=false)
\r
343 handle = params[:handle]
\r
344 unless @feeds.has_key?(handle)
\r
345 m.reply("dunno that feed")
\r
348 feed = @feeds[handle]
\r
349 if feed.rm_watch(m.replyto)
\r
350 m.reply "#{m.replyto} has been removed from the watchlist for #{feed.handle}"
\r
352 m.reply("#{m.replyto} wasn't watching #{feed.handle}") unless pass
\r
355 @@mutex.synchronize {
\r
356 if @@watchThreads[handle].kind_of? Thread
\r
357 @@watchThreads[handle].kill
\r
358 debug "rmwatch: Killed thread for #{handle}"
\r
359 @@watchThreads.delete(handle)
\r
366 def rewatch_rss(m=nil)
\r
369 # Read watches from list.
\r
370 watchlist.each{ |handle, feed|
\r
377 def watchRss(feed, m=nil)
\r
378 if @@watchThreads.has_key?(feed.handle)
\r
379 report_problem("watcher thread for #{feed.handle} is already running", nil, m)
\r
382 @@watchThreads[feed.handle] = Thread.new do
\r
383 debug "watcher for #{feed} started"
\r
389 debug "fetching #{feed}"
\r
390 title = newItems = nil
\r
391 @@mutex.synchronize {
\r
392 title, newItems = fetchRss(feed)
\r
395 debug "no items in feed #{feed}"
\r
398 debug "Checking if new items are available for #{feed}"
\r
400 debug "First run, we'll see next time"
\r
403 otxt = oldItems.map { |item| item.to_s }
\r
404 dispItems = newItems.reject { |item|
\r
405 otxt.include?(item.to_s)
\r
407 if dispItems.length > 0
\r
408 debug "Found #{dispItems.length} new items in #{feed}"
\r
409 dispItems.each { |item|
\r
410 @@mutex.synchronize {
\r
411 printFormattedRss(feed, item)
\r
415 debug "No new items found in #{feed}"
\r
418 oldItems = newItems.dup
\r
420 rescue Exception => e
\r
421 error "Error watching #{feed}: #{e.inspect}"
\r
422 debug e.backtrace.join("\n")
\r
426 seconds = @bot.config['rss.thread_sleep'] * (failures + 1)
\r
427 seconds += seconds * (rand(100)-50)/100
\r
428 debug "watcher for #{feed} going to sleep #{seconds} seconds.."
\r
434 def printFormattedRss(feed, item, opts=nil)
\r
435 places = feed.watchers
\r
436 handle = "::#{feed.handle}:: "
\r
439 places = opts[:places] if opts.key?(:places)
\r
440 handle = opts[:handle].to_s if opts.key?(:handle)
\r
441 if opts.key?(:date) && opts[:date]
\r
442 if item.respond_to?(:pubDate)
\r
443 if item.pubDate.class <= Time
\r
444 date = item.pubDate.strftime("%Y/%m/%d %H.%M.%S")
\r
446 date = item.pubDate.to_s
\r
448 elsif item.respond_to?(:date)
\r
449 if item.date.class <= Time
\r
450 date = item.date.strftime("%Y/%m/%d %H.%M.%S")
\r
452 date = item.date.to_s
\r
460 title = "#{Bold}#{item.title.chomp.riphtml}#{Bold}" if item.title
\r
461 desc = item.description.gsub(/\s+/,' ').strip.riphtml.shorten(@bot.config['rss.text_max']) if item.description
\r
462 link = item.link.chomp if item.link
\r
463 places.each { |loc|
\r
466 @bot.say loc, "#{handle}#{date}#{item.category.content} blogged at #{link}"
\r
467 @bot.say loc, "#{handle}#{title} - #{desc}"
\r
469 @bot.say loc, "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"
\r
471 @bot.say loc, "#{handle}#{date}#{item.title} has been edited by #{item.dc_creator}. #{desc} #{link}"
\r
473 @bot.say loc, "#{handle}#{date}Message #{title} sent by #{item.dc_creator}. #{desc}"
\r
475 @bot.say loc, "#{handle}#{date}#{title} @ #{link}"
\r
476 unless item.title =~ /^Changeset \[(\d+)\]/
\r
477 @bot.say loc, "#{handle}#{date}#{desc}"
\r
480 @bot.say loc, "#{handle}#{date}#{title}#{' @ ' if item.title && item.link}#{link}"
\r
485 def fetchRss(feed, m=nil)
\r
487 # Use 60 sec timeout, cause the default is too low
\r
488 xml = @bot.httputil.get_cached(feed.url,60,60)
\r
489 rescue URI::InvalidURIError, URI::BadURIError => e
\r
490 report_problem("invalid rss feed #{feed.url}", e, m)
\r
493 report_problem("error getting #{feed.url}", e, m)
\r
496 debug "fetched #{feed}"
\r
498 report_problem("reading feed #{feed} failed", nil, m)
\r
503 ## do validate parse
\r
504 rss = RSS::Parser.parse(xml)
\r
505 debug "parsed #{feed}"
\r
506 rescue RSS::InvalidRSSError
\r
507 ## do non validate parse for invalid RSS 1.0
\r
509 rss = RSS::Parser.parse(xml, false)
\r
510 rescue RSS::Error => e
\r
511 report_problem("parsing rss stream failed, whoops =(", e, m)
\r
514 rescue RSS::Error => e
\r
515 report_problem("parsing rss stream failed, oioi", e, m)
\r
518 report_problem("processing error occured, sorry =(", e, m)
\r
523 report_problem("#{feed} does not include RSS 1.0 or 0.9x/2.0", nil, m)
\r
526 rss.output_encoding = 'UTF-8'
\r
527 rescue RSS::UnknownConvertMethod => e
\r
528 report_problem("bah! something went wrong =(", e, m)
\r
531 rss.channel.title ||= "Unknown"
\r
532 title = rss.channel.title
\r
533 rss.items.each do |item|
\r
534 item.title ||= "Unknown"
\r
540 report_problem("no items found in the feed, maybe try weed?", e, m)
\r
543 return [title, items]
\r
547 plugin = RSSFeedsPlugin.new
\r
549 plugin.map 'rss show :handle :limit',
\r
550 :action => 'show_rss',
\r
551 :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},
\r
552 :defaults => {:limit => 5}
\r
553 plugin.map 'rss list :handle',
\r
554 :action => 'list_rss',
\r
555 :defaults => {:handle => nil}
\r
556 plugin.map 'rss watched :handle',
\r
557 :action => 'watched_rss',
\r
558 :defaults => {:handle => nil}
\r
559 plugin.map 'rss add :handle :url :type',
\r
560 :action => 'add_rss',
\r
561 :defaults => {:type => nil}
\r
562 plugin.map 'rss del :handle',
\r
563 :action => 'del_rss'
\r
564 plugin.map 'rss delete :handle',
\r
565 :action => 'del_rss'
\r
566 plugin.map 'rss rm :handle',
\r
567 :action => 'del_rss'
\r
568 plugin.map 'rss replace :handle :url :type',
\r
569 :action => 'replace_rss',
\r
570 :defaults => {:type => nil}
\r
571 plugin.map 'rss forcereplace :handle :url :type',
\r
572 :action => 'forcereplace_rss',
\r
573 :defaults => {:type => nil}
\r
574 plugin.map 'rss watch :handle :url :type',
\r
575 :action => 'watch_rss',
\r
576 :defaults => {:url => nil, :type => nil}
\r
577 plugin.map 'rss unwatch :handle',
\r
578 :action => 'unwatch_rss'
\r
579 plugin.map 'rss rmwatch :handle',
\r
580 :action => 'unwatch_rss'
\r
581 plugin.map 'rss rewatch :handle',
\r
582 :action => 'rewatch_rss'
\r