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