core: restart on SIGHUP
[rbot] / lib / rbot / messagemapper.rb
1 # First of all we add a method to the Regexp class
2 class Regexp
3
4   # a Regexp has captures when its source has open parenthesis which are
5   # preceded by an even number of slashes and not followed by a question mark
6   #
7   def has_captures?
8     self.source.match(/(?:^|[^\\])(?:\\\\)*\([^?]/)
9   end
10
11   # We may want to remove captures
12   def remove_captures
13     new = self.source.gsub(/(^|[^\\])((?:\\\\)*)\(([^?])/) {
14       "%s%s(?:%s" % [$1, $2, $3]
15     }
16     Regexp.new(new)
17   end
18 end
19
20 module Irc
21 class Bot
22
23   # MessageMapper is a class designed to reduce the amount of regexps and
24   # string parsing plugins and bot modules need to do, in order to process
25   # and respond to messages.
26   #
27   # You add templates to the MessageMapper which are examined by the handle
28   # method when handling a message. The templates tell the mapper which
29   # method in its parent class (your class) to invoke for that message. The
30   # string is split, optionally defaulted and validated before being passed
31   # to the matched method.
32   #
33   # A template such as "foo :option :otheroption" will match the string "foo
34   # bar baz" and, by default, result in method +foo+ being called, if
35   # present, in the parent class. It will receive two parameters, the
36   # message (derived from BasicUserMessage) and a Hash containing
37   #   {:option => "bar", :otheroption => "baz"}
38   # See the #map method for more details.
39   class MessageMapper
40     # used to set the method name used as a fallback for unmatched messages.
41     # The default fallback is a method called "usage".
42     attr_writer :fallback
43
44     # _parent_::   parent class which will receive mapped messages
45     #
46     # Create a new MessageMapper with parent class _parent_. This class will
47     # receive messages from the mapper via the handle() method.
48     def initialize(parent)
49       @parent = parent
50       @templates = Array.new
51       @fallback = :usage
52     end
53
54     # call-seq: map(botmodule, template, options)
55     #
56     # _botmodule_:: the BotModule which will handle this map
57     # _template_::  a String describing the messages to be matched
58     # _options_::   a Hash holding variouns options
59     #
60     # This method is used to register a new MessageTemplate that will map any
61     # BasicUserMessage matching the given _template_ to a corresponding action.
62     # A simple example:
63     #   plugin.map 'myplugin :parameter'
64     # (other examples follow).
65     #
66     # By default, the action to which the messages are mapped is a method named
67     # like the first word of the template. The
68     #   :action => 'method_name'
69     # option can be used to override this default behaviour. Example:
70     #   plugin.map 'myplugin :parameter', :action => 'mymethod'
71     #
72     # By default whether a handler is fired depends on an auth check. In rbot
73     # versions up to 0.9.10, the first component of the string was used for the
74     # auth check, unless overridden via the :auth => 'auth_name' option. Since
75     # version 0.9.11, a new auth method has been implemented. TODO document.
76     #
77     # Static parameters (not prefixed with ':' or '*') must match the
78     # respective component of the message exactly. Example:
79     #   plugin.map 'myplugin :foo is :bar'
80     # will only match messages of the form "myplugin something is
81     # somethingelse"
82     #
83     # Dynamic parameters can be specified by a colon ':' to match a single
84     # component (whitespace separated), or a * to suck up all following
85     # parameters into an array. Example:
86     #   plugin.map 'myplugin :parameter1 *rest'
87     #
88     # You can provide defaults for dynamic components using the :defaults
89     # parameter. If a component has a default, then it is optional. e.g:
90     #   plugin.map 'myplugin :foo :bar', :defaults => {:bar => 'qux'}
91     # would match 'myplugin param param2' and also 'myplugin param'. In the
92     # latter case, :bar would be provided from the default.
93     #
94     # Static and dynamic parameters can also be made optional by wrapping them
95     # in square brackets []. For example
96     #   plugin.map 'myplugin :foo [is] :bar'
97     # will match both 'myplugin something is somethingelse' and 'myplugin
98     # something somethingelse'.
99     #
100     # Components can be validated before being allowed to match, for
101     # example if you need a component to be a number:
102     #   plugin.map 'myplugin :param', :requirements => {:param => /^\d+$/}
103     # will only match strings of the form 'myplugin 1234' or some other
104     # number.
105     #
106     # Templates can be set not to match public or private messages using the
107     # :public or :private boolean options.
108     #
109     # Summary of recognized options:
110     #
111     # action::
112     #   method to call when the template is matched
113     # auth_path::
114     #   TODO document
115     # requirements::
116     #   a Hash whose keys are names of dynamic parameters and whose values are
117     #   regular expressions that the parameters must match
118     # defaults::
119     #   a Hash whose keys are names of dynamic parameters and whose values are
120     #   the values to be assigned to those parameters when they are missing from
121     #   the message. Any dynamic parameter appearing in the :defaults Hash is
122     #   therefore optional
123     # public::
124     #   a boolean (defaults to true) that determines whether the template should
125     #   match public (in channel) messages.
126     # private::
127     #   a boolean (defaults to true) that determines whether the template should
128     #   match private (not in channel) messages.
129     # threaded::
130     #   a boolean (defaults to false) that determines whether the action should be
131     #   called in a separate thread.
132     #   
133     #
134     # Further examples:
135     #
136     #   # match 'karmastats' and call my stats() method
137     #   plugin.map 'karmastats', :action => 'stats'
138     #   # match 'karma' with an optional 'key' and call my karma() method
139     #   plugin.map 'karma :key', :defaults => {:key => false}
140     #   # match 'karma for something' and call my karma() method
141     #   plugin.map 'karma for :key'
142     #
143     #   # two matches, one for public messages in a channel, one for
144     #   # private messages which therefore require a channel argument
145     #   plugin.map 'urls search :channel :limit :string',
146     #             :action => 'search',
147     #             :defaults => {:limit => 4},
148     #             :requirements => {:limit => /^\d+$/},
149     #             :public => false
150     #   plugin.map 'urls search :limit :string',
151     #             :action => 'search',
152     #             :defaults => {:limit => 4},
153     #             :requirements => {:limit => /^\d+$/},
154     #             :private => false
155     #
156     def map(botmodule, *args)
157       @templates << MessageTemplate.new(botmodule, *args)
158     end
159
160     # Iterate over each MessageTemplate handled.
161     def each
162       @templates.each {|tmpl| yield tmpl}
163     end
164
165     # Return the last added MessageTemplate
166     def last
167       @templates.last
168     end
169
170     # _m_::  derived from BasicUserMessage
171     #
172     # Examine the message _m_, comparing it with each map()'d template to
173     # find and process a match. Templates are examined in the order they
174     # were map()'d - first match wins.
175     #
176     # Returns +true+ if a match is found including fallbacks, +false+
177     # otherwise.
178     def handle(m)
179       return false if @templates.empty?
180       failures = []
181       @templates.each do |tmpl|
182         options, failure = tmpl.recognize(m)
183         if options.nil?
184           failures << [tmpl, failure]
185         else
186           action = tmpl.options[:action]
187           unless @parent.respond_to?(action)
188             failures << [tmpl, "class does not respond to action #{action}"]
189             next
190           end
191           auth = tmpl.options[:full_auth_path]
192           debug "checking auth for #{auth}"
193           if m.bot.auth.allow?(auth, m.source, m.replyto)
194             debug "template match found and auth'd: #{action.inspect} #{options.inspect}"
195             if tmpl.options[:thread] || tmpl.options[:threaded]
196               Thread.new do
197                 begin
198                   @parent.send(action, m, options)
199                 rescue Exception => e
200                   error "In threaded action: #{e.message}"
201                   debug e.backtrace.join("\n")
202                 end
203               end
204             else
205               @parent.send(action, m, options)
206             end
207
208             return true
209           end
210           debug "auth failed for #{auth}"
211           # if it's just an auth failure but otherwise the match is good,
212           # don't try any more handlers
213           return false
214         end
215       end
216       failures.each {|f, r|
217         debug "#{f.inspect} => #{r}"
218       }
219       debug "no handler found, trying fallback"
220       if @fallback && @parent.respond_to?(@fallback)
221         if m.bot.auth.allow?(@fallback, m.source, m.replyto)
222           @parent.send(@fallback, m, {})
223           return true
224         end
225       end
226       return false
227     end
228
229   end
230
231   # MessageParameter is a class that collects all the necessary information
232   # about a message (dynamic) parameter (the :param or *param that can be found
233   # in a #map).
234   #
235   # It has a +name+ attribute, +multi+ and +optional+ booleans that tell if the
236   # parameter collects more than one word, and if it's optional (respectively).
237   # In the latter case, it can also have a default value.
238   #
239   # It is possible to assign a collector to a MessageParameter. This can be either
240   # a Regexp with captures or an Array or a Hash. The collector defines what the
241   # collect() method is supposed to return.
242   class MessageParameter
243     attr_reader :name
244     attr_writer :multi
245     attr_writer :optional
246     attr_accessor :default
247
248     def initialize(name)
249       self.name = name
250       @multi = false
251       @optional = false
252       @default = nil
253       @regexp = nil
254       @index = nil
255     end
256
257     def name=(val)
258       @name = val.to_sym
259     end
260
261     def multi?
262       @multi
263     end
264
265     def optional?
266       @optional
267     end
268
269     # This method is used to turn a matched item into the actual parameter value.
270     # It only does something when collector= set the @regexp to something. In
271     # this case, _val_ is matched against @regexp and then the match result
272     # specified in @index is selected. As a special case, when @index is nil
273     # the first non-nil captured group is returned.
274     def collect(val)
275       return val unless @regexp
276       mdata = @regexp.match(val)
277       if @index
278         return mdata[@index]
279       else
280         return mdata[1..-1].compact.first
281       end
282     end
283
284     # This method allow the plugin programmer to choose to only pick a subset of the
285     # string matched by a parameter. This is done by passing the collector=()
286     # method either a Regexp with captures or an Array or a Hash.
287     #
288     # When the method is passed a Regexp with captures, the collect() method will
289     # return the first non-nil captured group.
290     #
291     # When the method is passed an Array, it will grab a regexp from the first
292     # element, and possibly an index from the second element. The index can
293     # also be nil.
294     #
295     # When the method is passed a Hash, it will grab a regexp from the :regexp
296     # element, and possibly an index from the :index element. The index can
297     # also be nil.
298     def collector=(val)
299       return unless val
300       case val
301       when Regexp
302         return unless val.has_captures?
303         @regexp = val
304       when Array
305         warning "Collector #{val.inspect} is too long, ignoring extra entries" unless val.length <= 2
306         @regexp = val[0]
307         @index = val[1] rescue nil
308       when Hash
309         raise "Collector #{val.inspect} doesn't have a :regexp key" unless val.has_key?(:regexp)
310         @regexp = val[:regexp]
311         @index = val.fetch(:regexp, nil)
312       end
313       raise "The regexp of collector #{val.inspect} isn't a Regexp" unless @regexp.kind_of?(Regexp)
314       raise "The index of collector #{val.inspect} is present but not an integer " if @index and not @index.kind_of?(Fixnum)
315     end
316
317     def inspect
318       mul = multi? ? " multi" : " single"
319       opt = optional? ? " optional" : " needed"
320       if @regexp
321         reg = " regexp=%s index=%d" % [@regexp, @index]
322       else
323         reg = nil
324       end
325       "<%s %s%s%s%s>" % [self.class, name, mul, opt, reg]
326     end
327   end
328
329   # MessageTemplate is the class that holds the actual message template map()'d
330   # by a BotModule and handled by a MessageMapper
331   #
332   class MessageTemplate
333     attr_reader :defaults  # the defaults hash
334     attr_reader :options   # the options hash
335     attr_reader :template  # the actual template string
336     attr_reader :items     # the collection of dynamic and static items in the template
337     attr_reader :regexp    # the Regexp corresponding to the template
338     attr_reader :botmodule # the BotModule that map()'d this MessageTemplate
339
340     # call-seq: initialize(botmodule, template, opts={})
341     #
342     # Create a new MessageTemplate associated to BotModule _botmodule_, with
343     # template _template_ and options _opts_
344     #
345     def initialize(botmodule, template, hash={})
346       raise ArgumentError, "Third argument must be a hash!" unless hash.kind_of?(Hash)
347       @defaults = hash[:defaults].kind_of?(Hash) ? hash.delete(:defaults) : {}
348       @requirements = hash[:requirements].kind_of?(Hash) ? hash.delete(:requirements) : {}
349       @template = template
350       case botmodule
351       when String
352         @botmodule = botmodule
353       when Plugins::BotModule
354         @botmodule = botmodule.name
355       else
356         raise ArgumentError, "#{botmodule.inspect} is not a botmodule nor a botmodule name"
357       end
358
359       self.items = template
360       # @dyn_items is an array of MessageParameters, except for the first entry
361       # which is the template
362       @dyn_items = @items.collect { |it|
363         if it.kind_of?(Symbol)
364           i = it.to_s
365           opt = MessageParameter.new(i)
366           if i.sub!(/^\*/,"")
367             opt.name = i
368             opt.multi = true
369           end
370           opt.default = @defaults[opt.name]
371           opt.collector = @requirements[opt.name]
372           opt
373         else
374           nil
375         end
376       }
377       @dyn_items.unshift(template).compact!
378       debug "Items: #{@items.inspect}; dyn items: #{@dyn_items.inspect}"
379
380       self.regexp = template
381       debug "Command #{template.inspect} in #{@botmodule} will match using #{@regexp}"
382
383       set_auth_path(hash)
384
385       unless hash.has_key?(:action)
386         hash[:action] = items[0]
387       end
388
389       @options = hash
390
391       # debug "Create template #{self.inspect}"
392     end
393
394     def set_auth_path(hash)
395       if hash.has_key?(:auth)
396         warning "Command #{@template.inspect} in #{@botmodule} uses old :auth syntax, please upgrade"
397       end
398       if hash.has_key?(:full_auth_path)
399         warning "Command #{@template.inspect} in #{@botmodule} sets :full_auth_path, please don't do this"
400       else
401         pre = @botmodule
402         words = items.reject{ |x|
403           x == pre || x.kind_of?(Symbol) || x =~ /\[|\]/
404         }
405         if words.empty?
406           post = nil
407         else
408           post = words.first
409         end
410         if hash.has_key?(:auth_path)
411           extra = hash[:auth_path]
412           if extra.sub!(/^:/, "")
413             pre += "::" + post
414             post = nil
415           end
416           if extra.sub!(/:$/, "")
417             if words.length > 1
418               post = [post,words[1]].compact.join("::")
419             end
420           end
421           pre = nil if extra.sub!(/^!/, "")
422           post = nil if extra.sub!(/!$/, "")
423           extra = nil if extra.empty?
424         else
425           extra = nil
426         end
427         hash[:full_auth_path] = [pre,extra,post].compact.join("::")
428         debug "Command #{@template} in #{botmodule} will use authPath #{hash[:full_auth_path]}"
429         # TODO check if the full_auth_path is sane
430       end
431     end
432
433     def items=(str)
434       raise ArgumentError, "template #{str.inspect} should be a String" unless str.kind_of?(String)
435
436       # split and convert ':xyz' to symbols
437       items = str.strip.split(/\]?\s+\[?|\]?$/).collect { |c|
438         # there might be extra (non-alphanumeric) stuff (e.g. punctuation) after the symbol name
439         if /^(:|\*)(\w+)(.*)/ =~ c
440           sym = ($1 == ':' ) ? $2.intern : "*#{$2}".intern
441           if $3.empty?
442             sym
443           else
444             [sym, $3]
445           end
446         else
447           c
448         end
449       }.flatten
450       @items = items
451
452       raise ArgumentError, "Illegal template -- first component cannot be dynamic: #{str.inspect}" if @items.first.kind_of? Symbol
453
454       raise ArgumentError, "Illegal template -- first component cannot be optional: #{str.inspect}" if @items.first =~ /\[|\]/
455
456       # Verify uniqueness of each component.
457       @items.inject({}) do |seen, item|
458         if item.kind_of? Symbol
459           # We must remove the initial * when present,
460           # because the parameters hash will intern both :item and *item as :item
461           it = item.to_s.sub(/^\*/,"").intern
462           raise ArgumentError, "Illegal template -- duplicate item #{it} in #{str.inspect}" if seen.key? it
463           seen[it] = true
464         end
465         seen
466       end
467     end
468
469     def regexp=(str)
470       # debug "Original string: #{str.inspect}"
471       rx = Regexp.escape(str)
472       # debug "Escaped: #{rx.inspect}"
473       rx.gsub!(/((?:\\ )*)(:|\\\*)(\w+)/) { |m|
474         whites = $1
475         is_single = $2 == ":"
476         name = $3.intern
477
478         not_needed = @defaults.has_key?(name)
479
480         has_req = @requirements[name]
481         debug "Requirements for #{name}: #{has_req.inspect}"
482         case has_req
483         when nil
484           sub = is_single ? "\\S+" : ".*?"
485         when Regexp
486           # Remove captures and the ^ and $ that are sometimes placed in requirement regexps
487           sub = has_req.remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
488         when String
489           sub = Regexp.escape(has_req)
490         when Array
491           sub = has_req[0].remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
492         when Hash
493           sub = has_req[:regexp].remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
494         else
495           warning "Odd requirement #{has_req.inspect} of class #{has_req.class} for parameter '#{name}'"
496           sub = Regexp.escape(has_req.to_s) rescue "\\S+"
497         end
498         debug "Regexp for #{name}: #{sub.inspect}"
499         s = "#{not_needed ? "(?:" : ""}#{whites}(#{sub})#{ not_needed ? ")?" : ""}"
500       }
501       # debug "Replaced dyns: #{rx.inspect}"
502       rx.gsub!(/((?:\\ )*)\\\[/, "(?:\\1")
503       rx.gsub!(/\\\]/, ")?")
504       # debug "Delimited optionals: #{rx.inspect}"
505       rx.gsub!(/(?:\\ )+/, "\\s+")
506       # debug "Corrected spaces: #{rx.inspect}"
507       @regexp = Regexp.new("^#{rx}$")
508     end
509
510     # Recognize the provided string components, returning a hash of
511     # recognized values, or [nil, reason] if the string isn't recognized.
512     def recognize(m)
513
514       debug "Testing #{m.message.inspect} against #{self.inspect}"
515
516       # Early out
517       return nil, "template #{@template} is not configured for private messages" if @options.has_key?(:private) && !@options[:private] && m.private?
518       return nil, "template #{@template} is not configured for public messages" if @options.has_key?(:public) && !@options[:public] && !m.private?
519
520       options = {}
521
522       matching = @regexp.match(m.message)
523       return nil, "#{m.message.inspect} doesn't match #{@template} (#{@regexp})" unless matching
524       return nil, "#{m.message.inspect} only matches #{@template} (#{@regexp}) partially: #{matching[0].inspect}" unless matching[0] == m.message
525
526       debug_match = matching[1..-1].collect{ |d| d.inspect}.join(', ')
527       debug "#{m.message.inspect} matched #{@regexp} with #{debug_match}"
528       debug "Associating #{debug_match} with dyn items #{@dyn_items.join(', ')}"
529
530       @dyn_items.each_with_index { |it, i|
531         next if i == 0
532         item = it.name
533         debug "dyn item #{item} (multi-word: #{it.multi?.inspect})"
534         if it.multi?
535           if matching[i].nil?
536             default = it.default
537             case default
538             when Array
539               value = default.clone
540             when String
541               value = default.strip.split
542             when nil, false, []
543               value = []
544             else
545               warning "Unmanageable default #{default} detected for :*#{item.to_s}, using []"
546               value = []
547             end
548             case default
549             when String
550               value.instance_variable_set(:@string_value, default)
551             else
552               value.instance_variable_set(:@string_value, value.join(' '))
553             end
554           else
555             value = matching[i].split
556             value.instance_variable_set(:@string_value, matching[i])
557           end
558           def value.to_s
559             @string_value
560           end
561         else
562           if matching[i].nil?
563             warning "No default value for option #{item.inspect} specified" unless @defaults.has_key?(item)
564             value = it.default
565           else
566             value = it.collect(matching[i])
567           end
568         end
569         options[item] = value
570         debug "set #{item} to #{options[item].inspect}"
571       }
572
573       options.delete_if {|k, v| v.nil?} # Remove nil values.
574       return options, nil
575     end
576
577     def inspect
578       when_str = @requirements.empty? ? "" : " when #{@requirements.inspect}"
579       default_str = @defaults.empty? ? "" : " || #{@defaults.inspect}"
580       "<#{self.class.to_s} #{@items.map { |c| c.inspect }.join(' ').inspect}#{default_str}#{when_str}>"
581     end
582
583     def requirements_for(name)
584       name = name.to_s.sub(/^\*/,"").intern if (/^\*/ =~ name.inspect)
585       presence = (@defaults.key?(name) && @defaults[name].nil?)
586       requirement = case @requirements[name]
587         when nil then nil
588         when Regexp then "match #{@requirements[name].inspect}"
589         else "be equal to #{@requirements[name].inspect}"
590       end
591       if presence && requirement then "#{name} must be present and #{requirement}"
592       elsif presence || requirement then "#{name} must #{requirement || 'be present'}"
593       else "#{name} has no requirements"
594       end
595     end
596   end
597 end
598 end