]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/messagemapper.rb
+ (plugins) :thread option for plugin.map makes an action automatically threaded
[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             if tmpl.options[:thread] || tmpl.options[:threaded]
153               Thread.new { @parent.send(action, m, options) }
154             else
155               @parent.send(action, m, options)
156             end
157
158             return true
159           end
160           debug "auth failed for #{auth}"
161           # if it's just an auth failure but otherwise the match is good,
162           # don't try any more handlers
163           return false
164         end
165       end
166       failures.each {|f, r|
167         debug "#{f.inspect} => #{r}"
168       }
169       debug "no handler found, trying fallback"
170       if @fallback && @parent.respond_to?(@fallback)
171         if m.bot.auth.allow?(@fallback, m.source, m.replyto)
172           @parent.send(@fallback, m, {})
173           return true
174         end
175       end
176       return false
177     end
178
179   end
180
181   # +MessageParameter+ is a class that collects all the necessary information
182   # about a message parameter (the :param or *param that can be found in a
183   # #map).
184   #
185   # It has a +name+ attribute, +multi+ and +optional+ booleans that tell if the
186   # parameter collects more than one word, and if it's optional (respectively).
187   # In the latter case, it can also have a default value.
188   #
189   # It is possible to assign a collector to a MessageParameter. This can be either
190   # a Regexp with captures or an Array or a Hash. The collector defines what the
191   # collect() method is supposed to return.
192   class MessageParameter
193     attr_reader :name
194     attr_writer :multi
195     attr_writer :optional
196     attr_accessor :default
197
198     def initialize(name)
199       self.name = name
200       @multi = false
201       @optional = false
202       @default = nil
203       @regexp = nil
204       @index = nil
205     end
206
207     def name=(val)
208       @name = val.to_sym
209     end
210
211     def multi?
212       @multi
213     end
214
215     def optional?
216       @optional
217     end
218
219     # This method is used to turn a matched item into the actual parameter value.
220     # It only does something when collector= set the @regexp to something. In
221     # this case, _val_ is matched against @regexp and then the match result
222     # specified in @index is selected. As a special case, when @index is nil
223     # the first non-nil captured group is returned.
224     def collect(val)
225       return val unless @regexp
226       mdata = @regexp.match(val)
227       if @index
228         return mdata[@index]
229       else
230         return mdata[1..-1].compact.first
231       end
232     end
233
234     # This method allow the plugin programmer to choose to only pick a subset of the
235     # string matched by a parameter. This is done by passing the collector=()
236     # method either a Regexp with captures or an Array or a Hash.
237     #
238     # When the method is passed a Regexp with captures, the collect() method will
239     # return the first non-nil captured group.
240     #
241     # When the method is passed an Array, it will grab a regexp from the first
242     # element, and possibly an index from the second element. The index can
243     # also be nil.
244     #
245     # When the method is passed a Hash, it will grab a regexp from the :regexp
246     # element, and possibly an index from the :index element. The index can
247     # also be nil.
248     def collector=(val)
249       return unless val
250       case val
251       when Regexp
252         return unless val.has_captures?
253         @regexp = val
254       when Array
255         warning "Collector #{val.inspect} is too long, ignoring extra entries" unless val.length <= 2
256         @regexp = val[0]
257         @index = val[1] rescue nil
258       when Hash
259         raise "Collector #{val.inspect} doesn't have a :regexp key" unless val.has_key?(:regexp)
260         @regexp = val[:regexp]
261         @index = val.fetch(:regexp, nil)
262       end
263       raise "The regexp of collector #{val.inspect} isn't a Regexp" unless @regexp.kind_of?(Regexp)
264       raise "The index of collector #{val.inspect} is present but not an integer " if @index and not @index.kind_of?(Fixnum)
265     end
266
267     def inspect
268       mul = multi? ? " multi" : " single"
269       opt = optional? ? " optional" : " needed"
270       if @regexp
271         reg = " regexp=%s index=%d" % [@regexp, @index]
272       else
273         reg = nil
274       end
275       "<%s %s%s%s%s>" % [self.class, name, mul, opt, reg]
276     end
277   end
278
279   class MessageTemplate
280     attr_reader :defaults # The defaults hash
281     attr_reader :options  # The options hash
282     attr_reader :template
283     attr_reader :items
284     attr_reader :regexp
285     attr_reader :botmodule
286
287     def initialize(botmodule, template, hash={})
288       raise ArgumentError, "Third argument must be a hash!" unless hash.kind_of?(Hash)
289       @defaults = hash[:defaults].kind_of?(Hash) ? hash.delete(:defaults) : {}
290       @requirements = hash[:requirements].kind_of?(Hash) ? hash.delete(:requirements) : {}
291       @template = template
292       case botmodule
293       when String
294         @botmodule = botmodule
295       when Plugins::BotModule
296         @botmodule = botmodule.name
297       else
298         raise ArgumentError, "#{botmodule.inspect} is not a botmodule nor a botmodule name"
299       end
300
301       self.items = template
302       # @dyn_items is an array of MessageParameters, except for the first entry
303       # which is the template
304       @dyn_items = @items.collect { |it|
305         if it.kind_of?(Symbol)
306           i = it.to_s
307           opt = MessageParameter.new(i)
308           if i.sub!(/^\*/,"")
309             opt.name = i
310             opt.multi = true
311           end
312           opt.default = @defaults[opt.name]
313           opt.collector = @requirements[opt.name]
314           opt
315         else
316           nil
317         end
318       }
319       @dyn_items.unshift(template).compact!
320       debug "Items: #{@items.inspect}; dyn items: #{@dyn_items.inspect}"
321
322       self.regexp = template
323       debug "Command #{template.inspect} in #{@botmodule} will match using #{@regexp}"
324
325       set_auth_path(hash)
326
327       unless hash.has_key?(:action)
328         hash[:action] = items[0]
329       end
330
331       @options = hash
332
333       # debug "Create template #{self.inspect}"
334     end
335
336     def set_auth_path(hash)
337       if hash.has_key?(:auth)
338         warning "Command #{@template.inspect} in #{@botmodule} uses old :auth syntax, please upgrade"
339       end
340       if hash.has_key?(:full_auth_path)
341         warning "Command #{@template.inspect} in #{@botmodule} sets :full_auth_path, please don't do this"
342       else
343         pre = @botmodule
344         words = items.reject{ |x|
345           x == pre || x.kind_of?(Symbol) || x =~ /\[|\]/
346         }
347         if words.empty?
348           post = nil
349         else
350           post = words.first
351         end
352         if hash.has_key?(:auth_path)
353           extra = hash[:auth_path]
354           if extra.sub!(/^:/, "")
355             pre += "::" + post
356             post = nil
357           end
358           if extra.sub!(/:$/, "")
359             if words.length > 1
360               post = [post,words[1]].compact.join("::")
361             end
362           end
363           pre = nil if extra.sub!(/^!/, "")
364           post = nil if extra.sub!(/!$/, "")
365         else
366           extra = nil
367         end
368         hash[:full_auth_path] = [pre,extra,post].compact.join("::")
369         debug "Command #{@template} in #{botmodule} will use authPath #{hash[:full_auth_path]}"
370         # TODO check if the full_auth_path is sane
371       end
372     end
373
374     def items=(str)
375       raise ArgumentError, "template #{str.inspect} should be a String" unless str.kind_of?(String)
376
377       # split and convert ':xyz' to symbols
378       items = str.strip.split(/\]?\s+\[?|\]?$/).collect { |c|
379         # there might be extra (non-alphanumeric) stuff (e.g. punctuation) after the symbol name
380         if /^(:|\*)(\w+)(.*)/ =~ c
381           sym = ($1 == ':' ) ? $2.intern : "*#{$2}".intern
382           if $3.empty?
383             sym
384           else
385             [sym, $3]
386           end
387         else
388           c
389         end
390       }.flatten
391       @items = items
392
393       raise ArgumentError, "Illegal template -- first component cannot be dynamic: #{str.inspect}" if @items.first.kind_of? Symbol
394
395       raise ArgumentError, "Illegal template -- first component cannot be optional: #{str.inspect}" if @items.first =~ /\[|\]/
396
397       # Verify uniqueness of each component.
398       @items.inject({}) do |seen, item|
399         if item.kind_of? Symbol
400           # We must remove the initial * when present,
401           # because the parameters hash will intern both :item and *item as :item
402           it = item.to_s.sub(/^\*/,"").intern
403           raise ArgumentError, "Illegal template -- duplicate item #{it} in #{str.inspect}" if seen.key? it
404           seen[it] = true
405         end
406         seen
407       end
408     end
409
410     def regexp=(str)
411       # debug "Original string: #{str.inspect}"
412       rx = Regexp.escape(str)
413       # debug "Escaped: #{rx.inspect}"
414       rx.gsub!(/((?:\\ )*)(:|\\\*)(\w+)/) { |m|
415         whites = $1
416         is_single = $2 == ":"
417         name = $3.intern
418
419         not_needed = @defaults.has_key?(name)
420
421         has_req = @requirements[name]
422         debug "Requirements for #{name}: #{has_req.inspect}"
423         case has_req
424         when nil
425           sub = is_single ? "\\S+" : ".*?"
426         when Regexp
427           # Remove captures and the ^ and $ that are sometimes placed in requirement regexps
428           sub = has_req.remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
429         when String
430           sub = Regexp.escape(has_req)
431         when Array
432           sub = has_req[0].remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
433         when Hash
434           sub = has_req[:regexp].remove_captures.source.sub(/^\^/,'').sub(/\$$/,'')
435         else
436           warning "Odd requirement #{has_req.inspect} of class #{has_req.class} for parameter '#{name}'"
437           sub = Regexp.escape(has_req.to_s) rescue "\\S+"
438         end
439         debug "Regexp for #{name}: #{sub.inspect}"
440         s = "#{not_needed ? "(?:" : ""}#{whites}(#{sub})#{ not_needed ? ")?" : ""}"
441       }
442       # debug "Replaced dyns: #{rx.inspect}"
443       rx.gsub!(/((?:\\ )*)\\\[/, "(?:\\1")
444       rx.gsub!(/\\\]/, ")?")
445       # debug "Delimited optionals: #{rx.inspect}"
446       rx.gsub!(/(?:\\ )+/, "\\s+")
447       # debug "Corrected spaces: #{rx.inspect}"
448       @regexp = Regexp.new("^#{rx}$")
449     end
450
451     # Recognize the provided string components, returning a hash of
452     # recognized values, or [nil, reason] if the string isn't recognized.
453     def recognize(m)
454
455       debug "Testing #{m.message.inspect} against #{self.inspect}"
456
457       # Early out
458       return nil, "template #{@template} is not configured for private messages" if @options.has_key?(:private) && !@options[:private] && m.private?
459       return nil, "template #{@template} is not configured for public messages" if @options.has_key?(:public) && !@options[:public] && !m.private?
460
461       options = {}
462
463       matching = @regexp.match(m.message)
464       return nil, "#{m.message.inspect} doesn't match #{@template} (#{@regexp})" unless matching
465       return nil, "#{m.message.inspect} only matches #{@template} (#{@regexp}) partially: #{matching[0].inspect}" unless matching[0] == m.message
466
467       debug_match = matching[1..-1].collect{ |d| d.inspect}.join(', ')
468       debug "#{m.message.inspect} matched #{@regexp} with #{debug_match}"
469       debug "Associating #{debug_match} with dyn items #{@dyn_items.join(', ')}"
470
471       @dyn_items.each_with_index { |it, i|
472         next if i == 0
473         item = it.name
474         debug "dyn item #{item} (multi-word: #{it.multi?.inspect})"
475         if it.multi?
476           if matching[i].nil?
477             default = it.default
478             case default
479             when Array
480               value = default.clone
481             when String
482               value = default.strip.split
483             when nil, false, []
484               value = []
485             else
486               warning "Unmanageable default #{default} detected for :*#{item.to_s}, using []"
487               value = []
488             end
489             case default
490             when String
491               value.instance_variable_set(:@string_value, default)
492             else
493               value.instance_variable_set(:@string_value, value.join(' '))
494             end
495           else
496             value = matching[i].split
497             value.instance_variable_set(:@string_value, matching[i])
498           end
499           def value.to_s
500             @string_value
501           end
502         else
503           if matching[i].nil?
504             warning "No default value for option #{item.inspect} specified" unless @defaults.has_key?(item)
505             value = it.default
506           else
507             value = it.collect(matching[i])
508           end
509         end
510         options[item] = value
511         debug "set #{item} to #{options[item].inspect}"
512       }
513
514       options.delete_if {|k, v| v.nil?} # Remove nil values.
515       return options, nil
516     end
517
518     def inspect
519       when_str = @requirements.empty? ? "" : " when #{@requirements.inspect}"
520       default_str = @defaults.empty? ? "" : " || #{@defaults.inspect}"
521       "<#{self.class.to_s} #{@items.map { |c| c.inspect }.join(' ').inspect}#{default_str}#{when_str}>"
522     end
523
524     def requirements_for(name)
525       name = name.to_s.sub(/^\*/,"").intern if (/^\*/ =~ name.inspect)
526       presence = (@defaults.key?(name) && @defaults[name].nil?)
527       requirement = case @requirements[name]
528         when nil then nil
529         when Regexp then "match #{@requirements[name].inspect}"
530         else "be equal to #{@requirements[name].inspect}"
531       end
532       if presence && requirement then "#{name} must be present and #{requirement}"
533       elsif presence || requirement then "#{name} must #{requirement || 'be present'}"
534       else "#{name} has no requirements"
535       end
536     end
537   end
538 end