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