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