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