]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/rss.rb
094b4571bf6b5ca56e28bae4e6cddf653d8807b5
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / rss.rb
1 #-- vim:sw=2:et\r
2 #++\r
3 #\r
4 # :title: RSS feed plugin for rbot\r
5 #\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
10 #\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
14 #\r
15 # License:: MIT license\r
16 \r
17 require 'rss'\r
18 \r
19 module ::RSS\r
20 \r
21   # Make an  'unique' ID for a given item, based on appropriate bot options\r
22   # Currently only suppored is bot.config['rss.show_updated']: when true, the\r
23   # description is included in the uid hashing, otherwise it's not\r
24   #\r
25   def RSS.item_uid_for_bot(item, opts={})\r
26     options = { :show_updated => true}.merge(opts)\r
27     desc = options[:show_updated] ? item.description : nil\r
28     [item.title, item.link, desc].hash\r
29   end\r
30 \r
31   # Add support for Slashdot namespace in RDF. The code is just an adaptation\r
32   # of the DublinCore code.\r
33   unless defined?(SLASH_PREFIX)\r
34     SLASH_PREFIX = 'slash'\r
35     SLASH_URI = "http://purl.org/rss/1.0/modules/slash/"\r
36 \r
37     RDF.install_ns(SLASH_PREFIX, SLASH_URI)\r
38 \r
39     module BaseSlashModel\r
40       def append_features(klass)\r
41         super\r
42 \r
43         return if klass.instance_of?(Module)\r
44         SlashModel::ELEMENT_NAME_INFOS.each do |name, plural_name|\r
45           plural = plural_name || "#{name}s"\r
46           full_name = "#{SLASH_PREFIX}_#{name}"\r
47           full_plural_name = "#{SLASH_PREFIX}_#{plural}"\r
48           klass_name = "Slash#{Utils.to_class_name(name)}"\r
49           klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI)\r
50           klass.install_have_children_element(name, SLASH_URI, "*",\r
51                                               full_name, full_plural_name)\r
52           klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0))\r
53           remove_method :#{full_name}\r
54           remove_method :#{full_name}=\r
55           remove_method :set_#{full_name}\r
56 \r
57           def #{full_name}\r
58             @#{full_name}.first and @#{full_name}.first.value\r
59           end\r
60 \r
61           def #{full_name}=(new_value)\r
62             @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value)\r
63           end\r
64           alias set_#{full_name} #{full_name}=\r
65         EOC\r
66         end\r
67       end\r
68     end\r
69 \r
70     module SlashModel\r
71       extend BaseModel\r
72       extend BaseSlashModel\r
73 \r
74       TEXT_ELEMENTS = {\r
75       "department" => nil,\r
76       "section" => nil,\r
77       "comments" =>  nil,\r
78       "hit_parade" => nil\r
79       }\r
80 \r
81       ELEMENT_NAME_INFOS = SlashModel::TEXT_ELEMENTS.to_a\r
82 \r
83       ELEMENTS = TEXT_ELEMENTS.keys\r
84 \r
85       ELEMENTS.each do |name, plural_name|\r
86         module_eval(<<-EOC, *get_file_and_line_from_caller(0))\r
87         class Slash#{Utils.to_class_name(name)} < Element\r
88           include RSS10\r
89 \r
90           content_setup\r
91 \r
92           class << self\r
93             def required_prefix\r
94               SLASH_PREFIX\r
95             end\r
96 \r
97             def required_uri\r
98               SLASH_URI\r
99             end\r
100           end\r
101 \r
102           @tag_name = #{name.dump}\r
103 \r
104           alias_method(:value, :content)\r
105           alias_method(:value=, :content=)\r
106 \r
107           def initialize(*args)\r
108             if Utils.element_initialize_arguments?(args)\r
109               super\r
110             else\r
111               super()\r
112               self.content = args[0]\r
113             end\r
114           end\r
115 \r
116           def full_name\r
117             tag_name_with_prefix(SLASH_PREFIX)\r
118           end\r
119 \r
120           def maker_target(target)\r
121             target.new_#{name}\r
122           end\r
123 \r
124           def setup_maker_attributes(#{name})\r
125             #{name}.content = content\r
126           end\r
127         end\r
128       EOC\r
129       end\r
130     end\r
131 \r
132     class RDF\r
133       class Item; include SlashModel; end\r
134     end\r
135 \r
136     SlashModel::ELEMENTS.each do |name|\r
137       class_name = Utils.to_class_name(name)\r
138       BaseListener.install_class_name(SLASH_URI, name, "Slash#{class_name}")\r
139     end\r
140 \r
141     SlashModel::ELEMENTS.collect! {|name| "#{SLASH_PREFIX}_#{name}"}\r
142   end\r
143 end\r
144 \r
145 \r
146 class ::RssBlob\r
147   attr_accessor :url\r
148   attr_accessor :handle\r
149   attr_accessor :type\r
150   attr :watchers\r
151   attr_accessor :refresh_rate\r
152   attr_accessor :xml\r
153   attr_accessor :title\r
154   attr_accessor :items\r
155   attr_accessor :mutex\r
156 \r
157   def initialize(url,handle=nil,type=nil,watchers=[], xml=nil)\r
158     @url = url\r
159     if handle\r
160       @handle = handle\r
161     else\r
162       @handle = url\r
163     end\r
164     @type = type\r
165     @watchers=[]\r
166     @refresh_rate = nil\r
167     @xml = xml\r
168     @title = nil\r
169     @items = nil\r
170     @mutex = Mutex.new\r
171     sanitize_watchers(watchers)\r
172   end\r
173 \r
174   def dup\r
175     @mutex.synchronize do\r
176       self.class.new(@url,\r
177                      @handle,\r
178                      @type ? @type.dup : nil,\r
179                      @watchers.dup,\r
180                      @xml ? @xml.dup : nil)\r
181     end\r
182   end\r
183 \r
184   # Downcase all watchers, possibly turning them into Strings if they weren't\r
185   def sanitize_watchers(list=@watchers)\r
186     ls = list.dup\r
187     @watchers.clear\r
188     ls.each { |w|\r
189       add_watch(w)\r
190     }\r
191   end\r
192 \r
193   def watched?\r
194     !@watchers.empty?\r
195   end\r
196 \r
197   def watched_by?(who)\r
198     @watchers.include?(who.downcase)\r
199   end\r
200 \r
201   def add_watch(who)\r
202     if watched_by?(who)\r
203       return nil\r
204     end\r
205     @mutex.synchronize do\r
206       @watchers << who.downcase\r
207     end\r
208     return who\r
209   end\r
210 \r
211   def rm_watch(who)\r
212     @mutex.synchronize do\r
213       @watchers.delete(who.downcase)\r
214     end\r
215   end\r
216 \r
217   def to_a\r
218     [@handle,@url,@type,@refresh_rate,@watchers]\r
219   end\r
220 \r
221   def to_s(watchers=false)\r
222     if watchers\r
223       a = self.to_a.flatten\r
224     else\r
225       a = self.to_a[0,3]\r
226     end\r
227     a.compact.join(" | ")\r
228   end\r
229 end\r
230 \r
231 class RSSFeedsPlugin < Plugin\r
232   BotConfig.register BotConfigIntegerValue.new('rss.head_max',\r
233     :default => 100, :validate => Proc.new{|v| v > 0 && v < 200},\r
234     :desc => "How many characters to use of a RSS item header")\r
235 \r
236   BotConfig.register BotConfigIntegerValue.new('rss.text_max',\r
237     :default => 200, :validate => Proc.new{|v| v > 0 && v < 400},\r
238     :desc => "How many characters to use of a RSS item text")\r
239 \r
240   BotConfig.register BotConfigIntegerValue.new('rss.thread_sleep',\r
241     :default => 300, :validate => Proc.new{|v| v > 30},\r
242     :desc => "How many seconds to sleep before checking RSS feeds again")\r
243 \r
244   BotConfig.register BotConfigBooleanValue.new('rss.show_updated',\r
245     :default => true,\r
246     :desc => "Whether feed items for which the description was changed should be shown as new")\r
247 \r
248   # We used to save the Mutex with the RssBlob, which was idiotic. And\r
249   # since Mutexes dumped in one version might not be resotrable in another,\r
250   # we need a few tricks to be able to restore data from other versions of Ruby\r
251   #\r
252   # When migrating 1.8.6 => 1.8.5, all we need to do is define an empty\r
253   # #marshal_load() method for Mutex. For 1.8.5 => 1.8.6 we need something\r
254   # dirtier, as seen later on in the initialization code.\r
255   unless Mutex.new.respond_to?(:marshal_load)\r
256     class ::Mutex\r
257       def marshal_load(str)\r
258         return\r
259       end\r
260     end\r
261   end\r
262 \r
263   attr_reader :feeds\r
264 \r
265   def initialize\r
266     super\r
267     if @registry.has_key?(:feeds)\r
268       # When migrating from Ruby 1.8.5 to 1.8.6, dumped Mutexes may render the\r
269       # data unrestorable. If this happens, we patch the data, thus allowing\r
270       # the restore to work.\r
271       #\r
272       # This is actually pretty safe for a number of reasons:\r
273       #  * the code is only called if standard marshalling fails\r
274       #  * the string we look for is quite unlikely to appear randomly\r
275       #  * if the string appears somewhere and the patched string isn't recoverable\r
276       #    either, we'll get another (unrecoverable) error, which makes the rss\r
277       #    plugin unsable, just like it was if no recovery was attempted\r
278       #  * if the string appears somewhere and the patched string is recoverable,\r
279       #    we may get a b0rked feed, which is eventually overwritten by a clean\r
280       #    one, so the worst thing that can happen is that a feed update spams\r
281       #    the watchers once\r
282       @registry.recovery = Proc.new { |val|\r
283         patched = val.sub(":\v@mutexo:\nMutex", ":\v@mutexo:\vObject")\r
284         ret = Marshal.restore(patched)\r
285         ret.each_value { |blob|\r
286           blob.mutex = nil\r
287           blob\r
288         }\r
289       }\r
290 \r
291       @feeds = @registry[:feeds]\r
292       raise unless @feeds\r
293 \r
294       @registry.recovery = nil\r
295 \r
296       @feeds.keys.grep(/[A-Z]/) { |k|\r
297         @feeds[k.downcase] = @feeds[k]\r
298         @feeds.delete(k)\r
299       }\r
300       @feeds.each { |k, f|\r
301         f.mutex = Mutex.new unless f.mutex\r
302         f.sanitize_watchers\r
303         parseRss(f) if f.xml\r
304       }\r
305     else\r
306       @feeds = Hash.new\r
307     end\r
308     @watch = Hash.new\r
309     rewatch_rss\r
310   end\r
311 \r
312   def name\r
313     "rss"\r
314   end\r
315 \r
316   def watchlist\r
317     @feeds.select { |h, f| f.watched? }\r
318   end\r
319 \r
320   def cleanup\r
321     stop_watches\r
322   end\r
323 \r
324   def save\r
325     unparsed = Hash.new()\r
326     @feeds.each { |k, f|\r
327       unparsed[k] = f.dup\r
328       # we don't want to save the mutex\r
329       unparsed[k].mutex = nil\r
330     }\r
331     @registry[:feeds] = unparsed\r
332   end\r
333 \r
334   def stop_watch(handle)\r
335     if @watch.has_key?(handle)\r
336       begin\r
337         debug "Stopping watch #{handle}"\r
338         @bot.timer.remove(@watch[handle])\r
339         @watch.delete(handle)\r
340       rescue Exception => e\r
341         report_problem("Failed to stop watch for #{handle}", e, nil)\r
342       end\r
343     end\r
344   end\r
345 \r
346   def stop_watches\r
347     @watch.each_key { |k|\r
348       stop_watch(k)\r
349     }\r
350   end\r
351 \r
352   def help(plugin,topic="")\r
353     case topic\r
354     when "show"\r
355       "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
356     when "list"\r
357       "rss list [#{Bold}handle#{Bold}] : list all rss feeds (matching #{Bold}handle#{Bold})"\r
358     when "watched"\r
359       "rss watched [#{Bold}handle#{Bold}] [in #{Bold}chan#{Bold}]: list all watched rss feeds (matching #{Bold}handle#{Bold}) (in channel #{Bold}chan#{Bold})"\r
360     when "who", "watches", "who watches"\r
361       "rss who watches [#{Bold}handle#{Bold}]]: list all watchers for rss feeds (matching #{Bold}handle#{Bold})"\r
362     when "add"\r
363       "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
364     when "change"\r
365       "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
366     when /^(del(ete)?|rm)$/\r
367       "rss del(ete)|rm #{Bold}handle#{Bold} : delete rss feed #{Bold}handle#{Bold}"\r
368     when "replace"\r
369       "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
370     when "forcereplace"\r
371       "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
372     when "watch"\r
373       "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
374     when /(un|rm)watch/\r
375       "rss unwatch|rmwatch #{Bold}handle#{Bold} [in #{Bold}chan#{Bold}]: stop watching rss #{Bold}handle#{Bold} (in channel #{Bold}chan#{Bold}) for changes"\r
376     when "rewatch"\r
377       "rss rewatch : restart threads that watch for changes in watched rss"\r
378     else\r
379       "manage RSS feeds: rss show|list|watched|add|change|del(ete)|rm|(force)replace|watch|unwatch|rmwatch|rewatch"\r
380     end\r
381   end\r
382 \r
383   def report_problem(report, e=nil, m=nil)\r
384     if m && m.respond_to?(:reply)\r
385       m.reply report\r
386     else\r
387       warning report\r
388     end\r
389     if e\r
390       debug e.inspect\r
391       debug e.backtrace.join("\n") if e.respond_to?(:backtrace)\r
392     end\r
393   end\r
394 \r
395   def show_rss(m, params)\r
396     handle = params[:handle]\r
397     lims = params[:limit].to_s.match(/(\d+)(?:..(\d+))?/)\r
398     debug lims.to_a.inspect\r
399     if lims[2]\r
400       ll = [[lims[1].to_i-1,lims[2].to_i-1].min,  0].max\r
401       ul = [[lims[1].to_i-1,lims[2].to_i-1].max, 14].min\r
402       rev = lims[1].to_i > lims[2].to_i\r
403     else\r
404       ll = 0\r
405       ul = [[lims[1].to_i-1, 0].max, 14].min\r
406       rev = false\r
407     end\r
408 \r
409     feed = @feeds.fetch(handle.downcase, nil)\r
410     unless feed\r
411       m.reply "I don't know any feeds named #{handle}"\r
412       return\r
413     end\r
414 \r
415     m.reply "lemme fetch it..."\r
416     title = items = nil\r
417     we_were_watching = false\r
418 \r
419     if @watch.key?(feed.handle)\r
420       # If a feed is being watched, we run the watcher thread\r
421       # so that all watchers can be informed of changes to\r
422       # the feed. Before we do that, though, we remove the\r
423       # show requester from the watchlist, if present, lest\r
424       # he gets the update twice.\r
425       if feed.watched_by?(m.replyto)\r
426         we_were_watching = true\r
427         feed.rm_watch(m.replyto)\r
428       end\r
429       @bot.timer.reschedule(@watch[feed.handle], 0)\r
430       if we_were_watching\r
431         feed.add_watch(m.replyto)\r
432       end\r
433     else\r
434       fetched = fetchRss(feed, m, false)\r
435     end\r
436     return unless fetched or feed.xml\r
437     if not fetched and feed.items\r
438       m.reply "using old data"\r
439     else\r
440       parsed = parseRss(feed, m)\r
441       m.reply "using old data" unless parsed\r
442     end\r
443     return unless feed.items\r
444     title = feed.title\r
445     items = feed.items\r
446 \r
447     # We sort the feeds in freshness order (newer ones first)\r
448     items = freshness_sort(items)\r
449     disp = items[ll..ul]\r
450     disp.reverse! if rev\r
451 \r
452     m.reply "Channel : #{title}"\r
453     disp.each do |item|\r
454       printFormattedRss(feed, item, {:places=>[m.replyto],:handle=>nil,:date=>true})\r
455     end\r
456   end\r
457 \r
458   def itemDate(item,ex=nil)\r
459     return item.pubDate if item.respond_to?(:pubDate) and item.pubDate\r
460     return item.date if item.respond_to?(:date) and item.date\r
461     return ex\r
462   end\r
463 \r
464   def freshness_sort(items)\r
465     notime = Time.at(0)\r
466     items.sort { |a, b|\r
467       itemDate(b, notime) <=> itemDate(a, notime)\r
468     }\r
469   end\r
470 \r
471   def list_rss(m, params)\r
472     wanted = params[:handle]\r
473     reply = String.new\r
474     @feeds.each { |handle, feed|\r
475       next if wanted and !handle.match(/#{wanted}/i)\r
476       reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"\r
477       (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate\r
478       (reply << " (watched)") if feed.watched_by?(m.replyto)\r
479       reply << "\n"\r
480     }\r
481     if reply.empty?\r
482       reply = "no feeds found"\r
483       reply << " matching #{wanted}" if wanted\r
484     end\r
485     m.reply reply, :max_lines => reply.length\r
486   end\r
487 \r
488   def watched_rss(m, params)\r
489     wanted = params[:handle]\r
490     chan = params[:chan] || m.replyto\r
491     reply = String.new\r
492     watchlist.each { |handle, feed|\r
493       next if wanted and !handle.match(/#{wanted}/i)\r
494       next unless feed.watched_by?(chan)\r
495       reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"\r
496       (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate\r
497       reply << "\n"\r
498     }\r
499     if reply.empty?\r
500       reply = "no watched feeds"\r
501       reply << " matching #{wanted}" if wanted\r
502     end\r
503     m.reply reply\r
504   end\r
505 \r
506   def who_watches(m, params)\r
507     wanted = params[:handle]\r
508     reply = String.new\r
509     watchlist.each { |handle, feed|\r
510       next if wanted and !handle.match(/#{wanted}/i)\r
511       reply << "#{feed.handle}: #{feed.url} (in format: #{feed.type ? feed.type : 'default'})"\r
512       (reply << " refreshing every #{Utils.secs_to_string(feed.refresh_rate)}") if feed.refresh_rate\r
513       reply << ": watched by #{feed.watchers.join(', ')}"\r
514       reply << "\n"\r
515     }\r
516     if reply.empty?\r
517       reply = "no watched feeds"\r
518       reply << " matching #{wanted}" if wanted\r
519     end\r
520     m.reply reply\r
521   end\r
522 \r
523   def add_rss(m, params, force=false)\r
524     handle = params[:handle]\r
525     url = params[:url]\r
526     unless url.match(/https?/)\r
527       m.reply "I only deal with feeds from HTTP sources, so I can't use #{url} (maybe you forgot the handle?)"\r
528       return\r
529     end\r
530     type = params[:type]\r
531     if @feeds.fetch(handle.downcase, nil) && !force\r
532       m.reply "There is already a feed named #{handle} (URL: #{@feeds[handle.downcase].url})"\r
533       return\r
534     end\r
535     unless url\r
536       m.reply "You must specify both a handle and an url to add an RSS feed"\r
537       return\r
538     end\r
539     @feeds[handle.downcase] = RssBlob.new(url,handle,type)\r
540     reply = "Added RSS #{url} named #{handle}"\r
541     if type\r
542       reply << " (format: #{type})"\r
543     end\r
544     m.reply reply\r
545     return handle\r
546   end\r
547 \r
548   def change_rss(m, params)\r
549     handle = params[:handle].downcase\r
550     feed = @feeds.fetch(handle, nil)\r
551     unless feed\r
552       m.reply "No such feed with handle #{handle}"\r
553       return\r
554     end\r
555     case params[:what].intern\r
556     when :handle\r
557       new = params[:new].downcase\r
558       if @feeds.key?(new) and @feeds[new]\r
559         m.reply "There already is a feed with handle #{new}"\r
560         return\r
561       else\r
562         feed.mutex.synchronize do\r
563           @feeds[new] = feed\r
564           @feeds.delete(handle)\r
565           feed.handle = new\r
566         end\r
567         handle = new\r
568       end\r
569     when :url\r
570       new = params[:new]\r
571       feed.mutex.synchronize do\r
572         feed.url = new\r
573       end\r
574     when :format, :type\r
575       new = params[:new]\r
576       new = nil if new == 'default'\r
577       feed.mutex.synchronize do\r
578         feed.type = new\r
579       end\r
580     when :refresh\r
581       new = params[:new].to_i\r
582       new = nil if new == 0\r
583       feed.mutex.synchronize do\r
584         feed.refresh_rate = new\r
585       end\r
586     else\r
587       m.reply "Don't know how to change #{params[:what]} for feeds"\r
588       return\r
589     end\r
590     m.reply "Feed changed:"\r
591     list_rss(m, {:handle => handle})\r
592   end\r
593 \r
594   def del_rss(m, params, pass=false)\r
595     feed = unwatch_rss(m, params, true)\r
596     return unless feed\r
597     if feed.watched?\r
598       m.reply "someone else is watching #{feed.handle}, I won't remove it from my list"\r
599       return\r
600     end\r
601     @feeds.delete(feed.handle.downcase)\r
602     m.okay unless pass\r
603     return\r
604   end\r
605 \r
606   def replace_rss(m, params)\r
607     handle = params[:handle]\r
608     if @feeds.key?(handle.downcase)\r
609       del_rss(m, {:handle => handle}, true)\r
610     end\r
611     if @feeds.key?(handle.downcase)\r
612       m.reply "can't replace #{feed.handle}"\r
613     else\r
614       add_rss(m, params, true)\r
615     end\r
616   end\r
617 \r
618   def forcereplace_rss(m, params)\r
619     add_rss(m, params, true)\r
620   end\r
621 \r
622   def watch_rss(m, params)\r
623     handle = params[:handle]\r
624     chan = params[:chan] || m.replyto\r
625     url = params[:url]\r
626     type = params[:type]\r
627     if url\r
628       add_rss(m, params)\r
629     end\r
630     feed = @feeds.fetch(handle.downcase, nil)\r
631     if feed\r
632       if feed.add_watch(chan)\r
633         watchRss(feed, m)\r
634         m.okay\r
635       else\r
636         m.reply "Already watching #{feed.handle} in #{chan}"\r
637       end\r
638     else\r
639       m.reply "Couldn't watch feed #{handle} (no such feed found)"\r
640     end\r
641   end\r
642 \r
643   def unwatch_rss(m, params, pass=false)\r
644     handle = params[:handle].downcase\r
645     chan = params[:chan] || m.replyto\r
646     unless @feeds.has_key?(handle)\r
647       m.reply("dunno that feed")\r
648       return\r
649     end\r
650     feed = @feeds[handle]\r
651     if feed.rm_watch(chan)\r
652       m.reply "#{chan} has been removed from the watchlist for #{feed.handle}"\r
653     else\r
654       m.reply("#{chan} wasn't watching #{feed.handle}") unless pass\r
655     end\r
656     if !feed.watched?\r
657       stop_watch(handle)\r
658     end\r
659     return feed\r
660   end\r
661 \r
662   def rewatch_rss(m=nil, params=nil)\r
663     stop_watches\r
664 \r
665     # Read watches from list.\r
666     watchlist.each{ |handle, feed|\r
667       watchRss(feed, m)\r
668     }\r
669     m.okay if m\r
670   end\r
671 \r
672   private\r
673   def watchRss(feed, m=nil)\r
674     if @watch.has_key?(feed.handle)\r
675       report_problem("watcher thread for #{feed.handle} is already running", nil, m)\r
676       return\r
677     end\r
678     status = Hash.new\r
679     status[:failures] = 0\r
680     status[:first_run] = true\r
681     @watch[feed.handle] = @bot.timer.add(0, status) {\r
682       debug "watcher for #{feed} started"\r
683       failures = status[:failures]\r
684       first_run = status.delete(:first_run)\r
685       begin\r
686         debug "fetching #{feed}"\r
687         oldxml = feed.xml ? feed.xml.dup : nil\r
688         unless fetchRss(feed)\r
689           failures += 1\r
690         else\r
691           if first_run\r
692             debug "first run for #{feed}, getting items"\r
693             parseRss(feed)\r
694           elsif oldxml and oldxml == feed.xml\r
695             debug "xml for #{feed} didn't change"\r
696             failures -= 1 if failures > 0\r
697           else\r
698             if not feed.items\r
699               debug "no previous items in feed #{feed}"\r
700               parseRss(feed)\r
701               failures -= 1 if failures > 0\r
702             else\r
703               # This one is used for debugging\r
704               otxt = []\r
705 \r
706               # These are used for checking new items vs old ones\r
707               uid_opts = { :show_updated => @bot.config['rss.show_updated'] }\r
708               oids = Set.new feed.items.map { |item|\r
709                 uid = RSS.item_uid_for_bot(item, uid_opts)\r
710                 otxt << item.to_s\r
711                 debug [uid, item].inspect\r
712                 debug [uid, otxt.last].inspect\r
713                 uid\r
714               }\r
715 \r
716               unless parseRss(feed)\r
717                 debug "no items in feed #{feed}"\r
718                 failures += 1\r
719               else\r
720                 debug "Checking if new items are available for #{feed}"\r
721                 failures -= 1 if failures > 0\r
722                 # debug "Old:"\r
723                 # debug oldxml\r
724                 # debug "New:"\r
725                 # debug feed.xml\r
726 \r
727                 dispItems = feed.items.reject { |item|\r
728                   uid = RSS.item_uid_for_bot(item, uid_opts)\r
729                   txt = item.to_s\r
730                   if oids.include?(uid)\r
731                     debug "rejecting old #{uid} #{item.inspect}"\r
732                     debug [uid, txt].inspect\r
733                     true\r
734                   else\r
735                     debug "accepting new #{uid} #{item.inspect}"\r
736                     debug [uid, txt].inspect\r
737                     warning "same text! #{txt}" if otxt.include?(txt)\r
738                     false\r
739                   end\r
740                 }\r
741 \r
742                 if dispItems.length > 0\r
743                   debug "Found #{dispItems.length} new items in #{feed}"\r
744                   # When displaying watched feeds, publish them from older to newer\r
745                   dispItems.reverse.each { |item|\r
746                     printFormattedRss(feed, item)\r
747                   }\r
748                 else\r
749                   debug "No new items found in #{feed}"\r
750                 end\r
751               end\r
752             end\r
753           end\r
754         end\r
755       rescue Exception => e\r
756         error "Error watching #{feed}: #{e.inspect}"\r
757         debug e.backtrace.join("\n")\r
758         failures += 1\r
759       end\r
760 \r
761       status[:failures] = failures\r
762 \r
763       feed.mutex.synchronize do\r
764         seconds = (feed.refresh_rate || @bot.config['rss.thread_sleep']) * (failures + 1)\r
765         seconds += seconds * (rand(100)-50)/100\r
766         debug "watcher for #{feed} going to sleep #{seconds} seconds.."\r
767         @bot.timer.reschedule(@watch[feed.handle], seconds)\r
768       end\r
769     }\r
770     debug "watcher for #{feed} added"\r
771   end\r
772 \r
773   def printFormattedRss(feed, item, opts=nil)\r
774     places = feed.watchers\r
775     handle = "::#{feed.handle}:: "\r
776     date = String.new\r
777     if opts\r
778       places = opts[:places] if opts.key?(:places)\r
779       handle = opts[:handle].to_s if opts.key?(:handle)\r
780       if opts.key?(:date) && opts[:date]\r
781         if item.respond_to?(:pubDate) \r
782           if item.pubDate.class <= Time\r
783             date = item.pubDate.strftime("%Y/%m/%d %H:%M")\r
784           else\r
785             date = item.pubDate.to_s\r
786           end\r
787         elsif  item.respond_to?(:date)\r
788           if item.date.class <= Time\r
789             date = item.date.strftime("%Y/%m/%d %H:%M")\r
790           else\r
791             date = item.date.to_s\r
792           end\r
793         else\r
794           date = "(no date)"\r
795         end\r
796         date += " :: "\r
797       end\r
798     end\r
799 \r
800     title = "#{Bold}#{item.title.ircify_html :limit => @bot.config['rss.head_max']}#{Bold}" if item.title\r
801 \r
802     desc = item.description.ircify_html(:limit => @bot.config['rss.text_max'], :a_href => :link_out) if item.description\r
803 \r
804     link = item.link.chomp if item.link\r
805 \r
806     debug item.inspect\r
807     category = item.dc_subject rescue item.category.content rescue nil\r
808     category = nil if category and category.empty?\r
809     author = item.dc_creator rescue item.author rescue nil\r
810     author = nil if author and author.empty?\r
811 \r
812     line1 = nil\r
813     line2 = nil\r
814 \r
815     at = ((item.title && item.link) ? ' @ ' : '')\r
816     case feed.type\r
817     when 'blog'\r
818       author << " " if author\r
819       abt = category ? "about #{category} " : ""\r
820       line1 = "#{handle}#{date}#{author}blogged #{abt}at #{link}"\r
821       line2 = "#{handle}#{title} - #{desc}"\r
822     when 'forum'\r
823       line1 = "#{handle}#{date}#{title}#{at}#{link}"\r
824     when 'wiki'\r
825       line1 = "#{handle}#{date}#{title}#{at}#{link} has been edited by #{author}. #{desc}"\r
826     when 'gmane'\r
827       line1 = "#{handle}#{date}Message #{title} sent by #{author}. #{desc}"\r
828     when 'trac'\r
829       line1 = "#{handle}#{date}#{title} @ #{link}"\r
830       unless item.title =~ /^Changeset \[(\d+)\]/\r
831         line2 = "#{handle}#{date}#{desc}"\r
832       end\r
833     when '/.'\r
834       dept = "(from the #{item.slash_department} dept) " rescue nil\r
835       sec = " in section #{item.slash_section}" rescue nil\r
836 \r
837       line1 = "#{handle}#{date}#{dept}#{title}#{at}#{link} (posted by #{author}#{sec})"\r
838     else\r
839       line1 = "#{handle}#{date}#{title}#{at}#{link}"\r
840     end\r
841     places.each { |loc|\r
842       @bot.say loc, line1, :overlong => :truncate\r
843       next unless line2\r
844       @bot.say loc, line2, :overlong => :truncate\r
845     }\r
846   end\r
847 \r
848   def fetchRss(feed, m=nil, cache=true)\r
849     begin\r
850       # Use 60 sec timeout, cause the default is too low\r
851       xml = @bot.httputil.get(feed.url,\r
852                               :read_timeout => 60,\r
853                               :open_timeout => 60,\r
854                               :cache => cache)\r
855     rescue URI::InvalidURIError, URI::BadURIError => e\r
856       report_problem("invalid rss feed #{feed.url}", e, m)\r
857       return nil\r
858     rescue => e\r
859       report_problem("error getting #{feed.url}", e, m)\r
860       return nil\r
861     end\r
862     debug "fetched #{feed}"\r
863     unless xml\r
864       report_problem("reading feed #{feed} failed", nil, m)\r
865       return nil\r
866     end\r
867     # Ok, 0.9 feeds are not supported, maybe because\r
868     # Netscape happily removed the DTD. So what we do is just to\r
869     # reassign the 0.9 RDFs to 1.0, and hope it goes right.\r
870     xml.gsub!("xmlns=\"http://my.netscape.com/rdf/simple/0.9/\"",\r
871               "xmlns=\"http://purl.org/rss/1.0/\"")\r
872     feed.mutex.synchronize do\r
873       feed.xml = xml\r
874     end\r
875     return true\r
876   end\r
877 \r
878   def parseRss(feed, m=nil)\r
879     return nil unless feed.xml\r
880     feed.mutex.synchronize do\r
881       xml = feed.xml\r
882       begin\r
883         ## do validate parse\r
884         rss = RSS::Parser.parse(xml)\r
885         debug "parsed and validated #{feed}"\r
886       rescue RSS::InvalidRSSError\r
887         ## do non validate parse for invalid RSS 1.0\r
888         begin\r
889           rss = RSS::Parser.parse(xml, false)\r
890           debug "parsed but not validated #{feed}"\r
891         rescue RSS::Error => e\r
892           report_problem("parsing rss stream failed, whoops =(", e, m)\r
893           return nil\r
894         end\r
895       rescue RSS::Error => e\r
896         report_problem("parsing rss stream failed, oioi", e, m)\r
897         return nil\r
898       rescue => e\r
899         report_problem("processing error occured, sorry =(", e, m)\r
900         return nil\r
901       end\r
902       items = []\r
903       if rss.nil?\r
904         report_problem("#{feed} does not include RSS 1.0 or 0.9x/2.0", nil, m)\r
905       else\r
906         begin\r
907           rss.output_encoding = 'UTF-8'\r
908         rescue RSS::UnknownConvertMethod => e\r
909           report_problem("bah! something went wrong =(", e, m)\r
910           return nil\r
911         end\r
912         rss.channel.title ||= "Unknown"\r
913         title = rss.channel.title\r
914         rss.items.each do |item|\r
915           item.title ||= "Unknown"\r
916           items << item\r
917         end\r
918       end\r
919 \r
920       if items.empty?\r
921         report_problem("no items found in the feed, maybe try weed?", e, m)\r
922         return nil\r
923       end\r
924       feed.title = title\r
925       feed.items = items\r
926       return true\r
927     end\r
928   end\r
929 end\r
930 \r
931 plugin = RSSFeedsPlugin.new\r
932 \r
933 plugin.map 'rss show :handle :limit',\r
934   :action => 'show_rss',\r
935   :requirements => {:limit => /^\d+(?:\.\.\d+)?$/},\r
936   :defaults => {:limit => 5}\r
937 plugin.map 'rss list :handle',\r
938   :action => 'list_rss',\r
939   :defaults => {:handle => nil}\r
940 plugin.map 'rss watched :handle [in :chan]',\r
941   :action => 'watched_rss',\r
942   :defaults => {:handle => nil}\r
943 plugin.map 'rss who watches :handle',\r
944   :action => 'who_watches',\r
945   :defaults => {:handle => nil}\r
946 plugin.map 'rss add :handle :url :type',\r
947   :action => 'add_rss',\r
948   :defaults => {:type => nil}\r
949 plugin.map 'rss change :what of :handle to :new',\r
950   :action => 'change_rss',\r
951   :requirements => { :what => /handle|url|format|type|refresh/ }\r
952 plugin.map 'rss change :what for :handle to :new',\r
953   :action => 'change_rss',\r
954   :requirements => { :what => /handle|url|format|type|refesh/ }\r
955 plugin.map 'rss del :handle',\r
956   :action => 'del_rss'\r
957 plugin.map 'rss delete :handle',\r
958   :action => 'del_rss'\r
959 plugin.map 'rss rm :handle',\r
960   :action => 'del_rss'\r
961 plugin.map 'rss replace :handle :url :type',\r
962   :action => 'replace_rss',\r
963   :defaults => {:type => nil}\r
964 plugin.map 'rss forcereplace :handle :url :type',\r
965   :action => 'forcereplace_rss',\r
966   :defaults => {:type => nil}\r
967 plugin.map 'rss watch :handle [in :chan]',\r
968   :action => 'watch_rss',\r
969   :defaults => {:url => nil, :type => nil}\r
970 plugin.map 'rss watch :handle :url :type [in :chan]',\r
971   :action => 'watch_rss',\r
972   :defaults => {:url => nil, :type => nil}\r
973 plugin.map 'rss unwatch :handle [in :chan]',\r
974   :action => 'unwatch_rss'\r
975 plugin.map 'rss rmwatch :handle [in :chan]',\r
976   :action => 'unwatch_rss'\r
977 plugin.map 'rss rewatch',\r
978   :action => 'rewatch_rss'\r
979 \r