]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/messagemapper.rb
f074dd20d319550124840ebdcec1ec3a8dfbe3fc
[user/henk/code/ruby/rbot.git] / lib / rbot / messagemapper.rb
1 module Irc
2
3   # +MessageMapper+ is a class designed to reduce the amount of regexps and
4   # string parsing plugins and bot modules need to do, in order to process
5   # and respond to messages.
6   #
7   # You add templates to the MessageMapper which are examined by the handle
8   # method when handling a message. The templates tell the mapper which
9   # method in its parent class (your class) to invoke for that message. The
10   # string is split, optionally defaulted and validated before being passed
11   # to the matched method.
12   #
13   # A template such as "foo :option :otheroption" will match the string "foo
14   # bar baz" and, by default, result in method +foo+ being called, if
15   # present, in the parent class. It will receive two parameters, the
16   # Message (derived from BasicUserMessage) and a Hash containing
17   #   {:option => "bar", :otheroption => "baz"}
18   # See the #map method for more details.
19   class MessageMapper
20     # used to set the method name used as a fallback for unmatched messages.
21     # The default fallback is a method called "usage".
22     attr_writer :fallback
23
24     # parent::   parent class which will receive mapped messages
25     #
26     # create a new MessageMapper with parent class +parent+. This class will
27     # receive messages from the mapper via the handle() method.
28     def initialize(parent)
29       @parent = parent
30       @templates = Array.new
31       @fallback = 'usage'
32     end
33
34     # args:: hash format containing arguments for this template
35     #
36     # map a template string to an action. example:
37     #   map 'myplugin :parameter1 :parameter2'
38     # (other examples follow). By default, maps a matched string to an
39     # action with the name of the first word in the template. The action is
40     # a method which takes a message and a parameter hash for arguments.
41     #
42     # The :action => 'method_name' option can be used to override this
43     # default behaviour. Example:
44     #   map 'myplugin :parameter1 :parameter2', :action => 'mymethod'
45     #
46     # By default whether a handler is fired depends on an auth check. The
47     # first component of the string is used for the auth check, unless
48     # overridden via the :auth => 'auth_name' option.
49     #
50     # Static parameters (not prefixed with ':' or '*') must match the
51     # respective component of the message exactly. Example:
52     #   map 'myplugin :foo is :bar'
53     # will only match messages of the form "myplugin something is
54     # somethingelse"
55     #
56     # Dynamic parameters can be specified by a colon ':' to match a single
57     # component (whitespace seperated), or a * to suck up all following
58     # parameters into an array. Example:
59     #   map 'myplugin :parameter1 *rest'
60     #
61     # You can provide defaults for dynamic components using the :defaults
62     # parameter. If a component has a default, then it is optional. e.g:
63     #   map 'myplugin :foo :bar', :defaults => {:bar => 'qux'}
64     # would match 'myplugin param param2' and also 'myplugin param'. In the
65     # latter case, :bar would be provided from the default.
66     #
67     # Components can be validated before being allowed to match, for
68     # example if you need a component to be a number:
69     #   map 'myplugin :param', :requirements => {:param => /^\d+$/}
70     # will only match strings of the form 'myplugin 1234' or some other
71     # number.
72     #
73     # Templates can be set not to match public or private messages using the
74     # :public or :private boolean options.
75     #
76     # Further examples:
77     #
78     #   # match 'karmastats' and call my stats() method
79     #   map 'karmastats', :action => 'stats'
80     #   # match 'karma' with an optional 'key' and call my karma() method
81     #   map 'karma :key', :defaults => {:key => false}
82     #   # match 'karma for something' and call my karma() method
83     #   map 'karma for :key'
84     #
85     #   # two matches, one for public messages in a channel, one for
86     #   # private messages which therefore require a channel argument
87     #   map 'urls search :channel :limit :string', :action => 'search',
88     #             :defaults => {:limit => 4},
89     #             :requirements => {:limit => /^\d+$/},
90     #             :public => false
91     #   plugin.map 'urls search :limit :string', :action => 'search',
92     #             :defaults => {:limit => 4},
93     #             :requirements => {:limit => /^\d+$/},
94     #             :private => false
95     #
96     def map(botmodule, *args)
97       @templates << Template.new(botmodule, *args)
98     end
99
100     def each
101       @templates.each {|tmpl| yield tmpl}
102     end
103
104     def last
105       @templates.last
106     end
107
108     # m::  derived from BasicUserMessage
109     #
110     # examine the message +m+, comparing it with each map()'d template to
111     # find and process a match. Templates are examined in the order they
112     # were map()'d - first match wins.
113     #
114     # returns +true+ if a match is found including fallbacks, +false+
115     # otherwise.
116     def handle(m)
117       return false if @templates.empty?
118       failures = []
119       @templates.each do |tmpl|
120         options, failure = tmpl.recognize(m)
121         if options.nil?
122           failures << [tmpl, failure]
123         else
124           action = tmpl.options[:action] ? tmpl.options[:action] : tmpl.items[0]
125           unless @parent.respond_to?(action)
126             failures << [tmpl, "class does not respond to action #{action}"]
127             next
128           end
129           auth = tmpl.options[:full_auth_path]
130           debug "checking auth for #{auth}"
131           if m.bot.auth.allow?(auth, m.source, m.replyto)
132             debug "template match found and auth'd: #{action.inspect} #{options.inspect}"
133             @parent.send(action, m, options)
134             return true
135           end
136           debug "auth failed for #{auth}"
137           # if it's just an auth failure but otherwise the match is good,
138           # don't try any more handlers
139           return false
140         end
141       end
142       failures.each {|f, r|
143         debug "#{f.inspect} => #{r}"
144       }
145       debug "no handler found, trying fallback"
146       if @fallback != nil && @parent.respond_to?(@fallback)
147         if m.bot.auth.allow?(@fallback, m.source, m.replyto)
148           @parent.send(@fallback, m, {})
149           return true
150         end
151       end
152       return false
153     end
154
155   end
156
157   class Template
158     attr_reader :defaults # The defaults hash
159     attr_reader :options  # The options hash
160     attr_reader :items
161     attr_reader :regexp
162
163     def initialize(botmodule, template, hash={})
164       raise ArgumentError, "Third argument must be a hash!" unless hash.kind_of?(Hash)
165       @defaults = hash[:defaults].kind_of?(Hash) ? hash.delete(:defaults) : {}
166       @requirements = hash[:requirements].kind_of?(Hash) ? hash.delete(:requirements) : {}
167       # The old way matching was done, this prepared the match items.
168       # Now we use for some preliminary syntax checking and to get the words used in the auth_path
169       self.items = template
170       self.regexp = template
171       debug "Command #{template.inspect} in #{botmodule} will match using #{@regexp}"
172       if hash.has_key?(:auth)
173         warning "Command #{template.inspect} in #{botmodule} uses old :auth syntax, please upgrade"
174       end
175       if hash.has_key?(:full_auth_path)
176         warning "Command #{template.inspect} in #{botmodule} sets :full_auth_path, please don't do this"
177       else
178         case botmodule
179         when String
180           pre = botmodule
181         when Plugins::BotModule
182           pre = botmodule.name
183         else
184           raise ArgumentError, "Can't find auth base in #{botmodule.inspect}"
185         end
186         words = items.reject{ |x|
187           x == pre || x.kind_of?(Symbol) || x =~ /\[|\]/
188         }
189         if words.empty?
190           post = nil
191         else
192           post = words.first
193         end
194         if hash.has_key?(:auth_path)
195           extra = hash[:auth_path]
196           if extra.sub!(/^:/, "")
197             pre += "::" + post
198             post = nil
199           end
200           if extra.sub!(/:$/, "")
201             if words.length > 1
202               post = [post,words[1]].compact.join("::")
203             end
204           end
205           pre = nil if extra.sub!(/^!/, "")
206           post = nil if extra.sub!(/!$/, "")
207         else
208           extra = nil
209         end
210         hash[:full_auth_path] = [pre,extra,post].compact.join("::")
211         debug "Command #{template} in #{botmodule} will use authPath #{hash[:full_auth_path]}"
212         # TODO check if the full_auth_path is sane
213       end
214
215       @options = hash
216
217       # @dyn_items is an array of arrays whose first entry is the Symbol
218       # (without the *, if any) of a dynamic item, and whose second entry is
219       # false if the Symbol refers to a single-word item, or true if it's
220       # multiword. @dyn_items.first will be the template.
221       @dyn_items = @items.collect { |it|
222         if it.kind_of?(Symbol)
223           i = it.to_s
224           if i.sub!(/^\*/,"")
225             [i.intern, true]
226           else
227             [i.intern, false]
228           end
229         else
230           nil
231         end
232       }
233       @dyn_items.unshift(template).compact!
234       debug "Items: #{@items.inspect}; dyn items: #{@dyn_items.inspect}"
235
236       # debug "Create template #{self.inspect}"
237     end
238
239     def items=(str)
240       raise ArgumentError, "template #{str.inspect} should be a String" unless str.kind_of?(String)
241
242       # split and convert ':xyz' to symbols
243       items = str.strip.split(/\]?\s+\[?/).collect { |c|
244         # there might be extra (non-alphanumeric) stuff (e.g. punctuation) after the symbol name
245         if /^(:|\*)(\w+)(.*)/ =~ c
246           sym = ($1 == ':' ) ? $2.intern : "*#{$2}".intern
247           if $3.empty?
248             sym
249           else
250             [sym, $3]
251           end
252         else
253           c
254         end
255       }.flatten
256       @items = items
257
258       raise ArgumentError, "Illegal template -- first component cannot be dynamic: #{str.inspect}" if @items.first.kind_of? Symbol
259
260       raise ArgumentError, "Illegal template -- first component cannot be optional: #{str.inspect}" if @items.first =~ /\[|\]/
261
262       # Verify uniqueness of each component.
263       @items.inject({}) do |seen, item|
264         if item.kind_of? Symbol
265           # We must remove the initial * when present,
266           # because the parameters hash will intern both :item and *item as :item
267           it = item.to_s.sub(/^\*/,"").intern
268           raise ArgumentError, "Illegal template -- duplicate item #{it} in #{str.inspect}" if seen.key? it
269           seen[it] = true
270         end
271         seen
272       end
273     end
274
275     def regexp=(str)
276       # debug "Original string: #{str.inspect}"
277       rx = Regexp.escape(str)
278       # debug "Escaped: #{rx.inspect}"
279       rx.gsub!(/((?:\\ )*)(:|\\\*)(\w+)/) { |m|
280         not_needed = @defaults.has_key?($3.intern)
281         s = "#{not_needed ? "(?:" : ""}#{$1}(#{$2 == ":" ? "\\S+" : ".*"})#{ not_needed ? ")?" : ""}"
282       }
283       # debug "Replaced dyns: #{rx.inspect}"
284       rx.gsub!(/((?:\\ )*)\\\[/, "(?:\\1")
285       rx.gsub!(/\\\]/, ")?")
286       # debug "Delimited optionals: #{rx.inspect}"
287       rx.gsub!(/(?:\\ )+/, "\\s+")
288       # debug "Corrected spaces: #{rx.inspect}"
289       @regexp = Regexp.new(rx)
290     end
291
292     # Recognize the provided string components, returning a hash of
293     # recognized values, or [nil, reason] if the string isn't recognized.
294     def recognize(m)
295
296       debug "Testing #{m.message.inspect} against #{self.inspect}"
297
298       # Early out
299       return nil, "template #{@dyn_items.first.inspect} is not configured for private messages" if @options.has_key?(:private) && !@options[:private] && m.private?
300       return nil, "template #{@dyn_items.first.inspect} is not configured for public messages" if @options.has_key?(:public) && !@options[:public] && !m.private?
301
302       options = {}
303
304       matching = @regexp.match(m.message)
305       return nil, "#{m.message.inspect} doesn't match #{@dyn_items.first.inspect} (#{@regexp})" unless matching
306       return nil, "#{m.message.inspect} only matches #{@dyn_items.first.inspect} (#{@regexp}) partially" unless matching[0] == m.message
307
308       debug_match = matching[1..-1].collect{ |d| d.inspect}.join(', ')
309       debug "#{m.message.inspect} matched #{@regexp} with #{debug_match}"
310       debug "Associating #{debug_match} with dyn items #{@dyn_items[1..-1].join(', ')}"
311
312       (@dyn_items.length - 1).downto 1 do |i|
313         it = @dyn_items[i]
314         item = it[0]
315         debug "dyn item #{item} (multi-word: #{it[1].inspect})"
316         if it[1]
317           if matching[i].nil?
318             default = @defaults[item]
319             case default
320             when Array
321               value = default.clone
322             when String
323               value = default.strip.split
324             when nil, false, []
325               value = []
326             else
327               value = []
328               warning "Unmanageable default #{default} detected for :*#{item.to_s}, using []"
329             end
330             case default
331             when String
332               value.instance_variable_set(:@string_value, default)
333             else
334               value.instance_variable_set(:@string_value, value.join(' '))
335             end
336           else
337             value = matching[i].split
338             value.instance_variable_set(:@string_value, matching[i])
339           end
340           def value.to_s
341             @string_value
342           end
343           options[item] = value
344           debug "set #{item} to #{value.inspect}"
345         else
346           if matching[i]
347             value = matching[i]
348             unless passes_requirements?(item, value)
349               # if @defaults.has_key?(item)
350               #   value = @defaults[item]
351               # else
352                 return nil, requirements_for(item)
353               # end
354             end
355           else
356             value = @defaults[item]
357             warning "No default value for option #{item.inspect} specified" unless @defaults.has_key?(item)
358           end
359           options[item] = value
360           debug "set #{item} to #{options[item].inspect}"
361         end
362       end
363
364       options.delete_if {|k, v| v.nil?} # Remove nil values.
365       return options, nil
366     end
367
368     def inspect
369       when_str = @requirements.empty? ? "" : " when #{@requirements.inspect}"
370       default_str = @defaults.empty? ? "" : " || #{@defaults.inspect}"
371       "<#{self.class.to_s} #{@items.map { |c| c.inspect }.join(' ').inspect}#{default_str}#{when_str}>"
372     end
373
374     # Verify that the given value passes this template's requirements
375     def passes_requirements?(name, value)
376       return @defaults.key?(name) && @defaults[name].nil? if value.nil? # Make sure it's there if it should be
377
378       case @requirements[name]
379         when nil then true
380         when Regexp then
381           value = value.to_s
382           match = @requirements[name].match(value)
383           match && match[0].length == value.length
384         else
385           @requirements[name] == value.to_s
386       end
387     end
388
389     def requirements_for(name)
390       name = name.to_s.sub(/^\*/,"").intern if (/^\*/ =~ name.inspect)
391       presence = (@defaults.key?(name) && @defaults[name].nil?)
392       requirement = case @requirements[name]
393         when nil then nil
394         when Regexp then "match #{@requirements[name].inspect}"
395         else "be equal to #{@requirements[name].inspect}"
396       end
397       if presence && requirement then "#{name} must be present and #{requirement}"
398       elsif presence || requirement then "#{name} must #{requirement || 'be present'}"
399       else "#{name} has no requirements"
400       end
401     end
402   end
403 end