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