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