]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/messagemapper.rb
* (gettext) make us somewhat less dependent on gettext internals
[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)
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 && @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       "<%s %s%s%s%s>" % [self.class, 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     attr_reader :botmodule
281
282     def initialize(botmodule, template, hash={})
283       raise ArgumentError, "Third argument must be a hash!" unless hash.kind_of?(Hash)
284       @defaults = hash[:defaults].kind_of?(Hash) ? hash.delete(:defaults) : {}
285       @requirements = hash[:requirements].kind_of?(Hash) ? hash.delete(:requirements) : {}
286       @template = template
287       case botmodule
288       when String
289         @botmodule = botmodule
290       when Plugins::BotModule
291         @botmodule = botmodule.name
292       else
293         raise ArgumentError, "#{botmodule.inspect} is not a botmodule nor a botmodule name"
294       end
295
296       self.items = template
297       # @dyn_items is an array of MessageParameters, except for the first entry
298       # which is the template
299       @dyn_items = @items.collect { |it|
300         if it.kind_of?(Symbol)
301           i = it.to_s
302           opt = MessageParameter.new(i)
303           if i.sub!(/^\*/,"")
304             opt.name = i
305             opt.multi = true
306           end
307           opt.default = @defaults[opt.name]
308           opt.collector = @requirements[opt.name]
309           opt
310         else
311           nil
312         end
313       }
314       @dyn_items.unshift(template).compact!
315       debug "Items: #{@items.inspect}; dyn items: #{@dyn_items.inspect}"
316
317       self.regexp = template
318       debug "Command #{template.inspect} in #{@botmodule} will match using #{@regexp}"
319
320       set_auth_path(hash)
321
322       unless hash.has_key?(:action)
323         hash[:action] = items[0]
324       end
325
326       @options = hash
327
328       # debug "Create template #{self.inspect}"
329     end
330
331     def set_auth_path(hash)
332       if hash.has_key?(:auth)
333         warning "Command #{@template.inspect} in #{@botmodule} uses old :auth syntax, please upgrade"
334       end
335       if hash.has_key?(:full_auth_path)
336         warning "Command #{@template.inspect} in #{@botmodule} sets :full_auth_path, please don't do this"
337       else
338         pre = @botmodule
339         words = items.reject{ |x|
340           x == pre || x.kind_of?(Symbol) || x =~ /\[|\]/
341         }
342         if words.empty?
343           post = nil
344         else
345           post = words.first
346         end
347         if hash.has_key?(:auth_path)
348           extra = hash[:auth_path]
349           if extra.sub!(/^:/, "")
350             pre += "::" + post
351             post = nil
352           end
353           if extra.sub!(/:$/, "")
354             if words.length > 1
355               post = [post,words[1]].compact.join("::")
356             end
357           end
358           pre = nil if extra.sub!(/^!/, "")
359           post = nil if extra.sub!(/!$/, "")
360         else
361           extra = nil
362         end
363         hash[:full_auth_path] = [pre,extra,post].compact.join("::")
364         debug "Command #{@template} in #{botmodule} will use authPath #{hash[:full_auth_path]}"
365         # TODO check if the full_auth_path is sane
366       end
367     end
368
369     def items=(str)
370       raise ArgumentError, "template #{str.inspect} should be a String" unless str.kind_of?(String)
371
372       # split and convert ':xyz' to symbols
373       items = str.strip.split(/\]?\s+\[?|\]?$/).collect { |c|
374         # there might be extra (non-alphanumeric) stuff (e.g. punctuation) after the symbol name
375         if /^(:|\*)(\w+)(.*)/ =~ c
376           sym = ($1 == ':' ) ? $2.intern : "*#{$2}".intern
377           if $3.empty?
378             sym
379           else
380             [sym, $3]
381           end
382         else
383           c
384         end
385       }.flatten
386       @items = items
387
388       raise ArgumentError, "Illegal template -- first component cannot be dynamic: #{str.inspect}" if @items.first.kind_of? Symbol
389
390       raise ArgumentError, "Illegal template -- first component cannot be optional: #{str.inspect}" if @items.first =~ /\[|\]/
391
392       # Verify uniqueness of each component.
393       @items.inject({}) do |seen, item|
394         if item.kind_of? Symbol
395           # We must remove the initial * when present,
396           # because the parameters hash will intern both :item and *item as :item
397           it = item.to_s.sub(/^\*/,"").intern
398           raise ArgumentError, "Illegal template -- duplicate item #{it} in #{str.inspect}" if seen.key? it
399           seen[it] = true
400         end
401         seen
402       end
403     end
404
405     def regexp=(str)
406       # debug "Original string: #{str.inspect}"
407       rx = Regexp.escape(str)
408       # debug "Escaped: #{rx.inspect}"
409       rx.gsub!(/((?:\\ )*)(:|\\\*)(\w+)/) { |m|
410         whites = $1
411         is_single = $2 == ":"
412         name = $3.intern
413
414         not_needed = @defaults.has_key?(name)
415
416         has_req = @requirements[name]
417         debug "Requirements for #{name}: #{has_req.inspect}"
418         case has_req
419         when nil
420           sub = is_single ? "\\S+" : ".*?"
421         when Regexp
422           # Remove captures and the ^ and $ that are sometimes placed in requirement regexps
423           sub = has_req.remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
424         when String
425           sub = Regexp.escape(has_req)
426         when Array
427           sub = has_req[0].remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
428         when Hash
429           sub = has_req[:regexp].remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
430         else
431           warning "Odd requirement #{has_req.inspect} of class #{has_req.class} for parameter '#{name}'"
432           sub = Regexp.escape(has_req.to_s) rescue "\\S+"
433         end
434         debug "Regexp for #{name}: #{sub.inspect}"
435         s = "#{not_needed ? "(?:" : ""}#{whites}(#{sub})#{ not_needed ? ")?" : ""}"
436       }
437       # debug "Replaced dyns: #{rx.inspect}"
438       rx.gsub!(/((?:\\ )*)\\\[/, "(?:\\1")
439       rx.gsub!(/\\\]/, ")?")
440       # debug "Delimited optionals: #{rx.inspect}"
441       rx.gsub!(/(?:\\ )+/, "\\s+")
442       # debug "Corrected spaces: #{rx.inspect}"
443       @regexp = Regexp.new("^#{rx}$")
444     end
445
446     # Recognize the provided string components, returning a hash of
447     # recognized values, or [nil, reason] if the string isn't recognized.
448     def recognize(m)
449
450       debug "Testing #{m.message.inspect} against #{self.inspect}"
451
452       # Early out
453       return nil, "template #{@template} is not configured for private messages" if @options.has_key?(:private) && !@options[:private] && m.private?
454       return nil, "template #{@template} is not configured for public messages" if @options.has_key?(:public) && !@options[:public] && !m.private?
455
456       options = {}
457
458       matching = @regexp.match(m.message)
459       return nil, "#{m.message.inspect} doesn't match #{@template} (#{@regexp})" unless matching
460       return nil, "#{m.message.inspect} only matches #{@template} (#{@regexp}) partially: #{matching[0].inspect}" unless matching[0] == m.message
461
462       debug_match = matching[1..-1].collect{ |d| d.inspect}.join(', ')
463       debug "#{m.message.inspect} matched #{@regexp} with #{debug_match}"
464       debug "Associating #{debug_match} with dyn items #{@dyn_items.join(', ')}"
465
466       @dyn_items.each_with_index { |it, i|
467         next if i == 0
468         item = it.name
469         debug "dyn item #{item} (multi-word: #{it.multi?.inspect})"
470         if it.multi?
471           if matching[i].nil?
472             default = it.default
473             case default
474             when Array
475               value = default.clone
476             when String
477               value = default.strip.split
478             when nil, false, []
479               value = []
480             else
481               warning "Unmanageable default #{default} detected for :*#{item.to_s}, using []"
482               value = []
483             end
484             case default
485             when String
486               value.instance_variable_set(:@string_value, default)
487             else
488               value.instance_variable_set(:@string_value, value.join(' '))
489             end
490           else
491             value = matching[i].split
492             value.instance_variable_set(:@string_value, matching[i])
493           end
494           def value.to_s
495             @string_value
496           end
497         else
498           if matching[i].nil?
499             warning "No default value for option #{item.inspect} specified" unless @defaults.has_key?(item)
500             value = it.default
501           else
502             value = it.collect(matching[i])
503           end
504         end
505         options[item] = value
506         debug "set #{item} to #{options[item].inspect}"
507       }
508
509       options.delete_if {|k, v| v.nil?} # Remove nil values.
510       return options, nil
511     end
512
513     def inspect
514       when_str = @requirements.empty? ? "" : " when #{@requirements.inspect}"
515       default_str = @defaults.empty? ? "" : " || #{@defaults.inspect}"
516       "<#{self.class.to_s} #{@items.map { |c| c.inspect }.join(' ').inspect}#{default_str}#{when_str}>"
517     end
518
519     def requirements_for(name)
520       name = name.to_s.sub(/^\*/,"").intern if (/^\*/ =~ name.inspect)
521       presence = (@defaults.key?(name) && @defaults[name].nil?)
522       requirement = case @requirements[name]
523         when nil then nil
524         when Regexp then "match #{@requirements[name].inspect}"
525         else "be equal to #{@requirements[name].inspect}"
526       end
527       if presence && requirement then "#{name} must be present and #{requirement}"
528       elsif presence || requirement then "#{name} must #{requirement || 'be present'}"
529       else "#{name} has no requirements"
530       end
531     end
532   end
533 end