]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/messagemapper.rb
Inform users about plugins that failed to load; preserve the (supposedly) most intere...
[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(*args)
97       @templates << Template.new(*args)
98     end
99     
100     def each
101       @templates.each {|tmpl| yield tmpl}
102     end
103     def last
104       @templates.last
105     end
106     
107     # m::  derived from BasicUserMessage
108     #
109     # examine the message +m+, comparing it with each map()'d template to
110     # find and process a match. Templates are examined in the order they
111     # were map()'d - first match wins.
112     #
113     # returns +true+ if a match is found including fallbacks, +false+
114     # otherwise.
115     def handle(m)
116       return false if @templates.empty?
117       failures = []
118       @templates.each do |tmpl|
119         options, failure = tmpl.recognize(m)
120         if options.nil?
121           failures << [tmpl, failure]
122         else
123           action = tmpl.options[:action] ? tmpl.options[:action] : tmpl.items[0]
124           unless @parent.respond_to?(action)
125             failures << [tmpl, "class does not respond to action #{action}"]
126             next
127           end
128           auth = tmpl.options[:auth] ? tmpl.options[:auth] : tmpl.items[0]
129           debug "checking auth for #{auth}"
130           if m.bot.auth.allow?(auth, m.source, m.replyto)
131             debug "template match found and auth'd: #{action.inspect} #{options.inspect}"
132             @parent.send(action, m, options)
133             return true
134           end
135           debug "auth failed for #{auth}"
136           # if it's just an auth failure but otherwise the match is good,
137           # don't try any more handlers
138           return false
139         end
140       end
141       failures.each {|f, r|
142         debug "#{f.inspect} => #{r}"
143       }
144       debug "no handler found, trying fallback"
145       if @fallback != nil && @parent.respond_to?(@fallback)
146         if m.bot.auth.allow?(@fallback, m.source, m.replyto)
147           @parent.send(@fallback, m, {})
148           return true
149         end
150       end
151       return false
152     end
153
154   end
155
156   class Template
157     attr_reader :defaults # The defaults hash
158     attr_reader :options  # The options hash
159     attr_reader :items
160     def initialize(template, hash={})
161       raise ArgumentError, "Second argument must be a hash!" unless hash.kind_of?(Hash)
162       @defaults = hash[:defaults].kind_of?(Hash) ? hash.delete(:defaults) : {}
163       @requirements = hash[:requirements].kind_of?(Hash) ? hash.delete(:requirements) : {}
164       self.items = template
165       @options = hash
166     end
167     def items=(str)
168       items = str.split(/\s+/).collect {|c| (/^(:|\*)(\w+)$/ =~ c) ? (($1 == ':' ) ? $2.intern : "*#{$2}".intern) : c} if str.kind_of?(String) # split and convert ':xyz' to symbols
169       items.shift if items.first == ""
170       items.pop if items.last == ""
171       @items = items
172
173       if @items.first.kind_of? Symbol
174         raise ArgumentError, "Illegal template -- first component cannot be dynamic\n   #{str.inspect}"
175       end
176
177       # Verify uniqueness of each component.
178       @items.inject({}) do |seen, item|
179         if item.kind_of? Symbol
180           # We must remove the initial * when present,
181           # because the parameters hash will intern both :item and *item as :item
182           it = item.to_s.sub(/^\*/,"").intern
183           raise ArgumentError, "Illegal template -- duplicate item #{it} in #{str.inspect}" if seen.key? it
184           seen[it] = true
185         end
186         seen
187       end
188     end
189
190     # Recognize the provided string components, returning a hash of
191     # recognized values, or [nil, reason] if the string isn't recognized.
192     def recognize(m)
193       components = m.message.split(/\s+/)
194       options = {}
195
196       @items.each do |item|
197         if /^\*/ =~ item.to_s
198           if components.empty?
199             value = @defaults.has_key?(item) ? @defaults[item].clone : []
200           else
201             value = components.clone
202           end
203           components = []
204           def value.to_s() self.join(' ') end
205           options[item.to_s.sub(/^\*/,"").intern] = value
206         elsif item.kind_of? Symbol
207           value = components.shift || @defaults[item]
208           if passes_requirements?(item, value)
209             options[item] = value
210           else
211             if @defaults.has_key?(item)
212               options[item] = @defaults[item]
213               # push the test-failed component back on the stack
214               components.unshift value
215             else
216               return nil, requirements_for(item)
217             end
218           end
219         else
220           return nil, "No value available for component #{item.inspect}" if components.empty?
221           component = components.shift
222           return nil, "Value for component #{item.inspect} doesn't match #{component}" if component != item
223         end
224       end
225
226       return nil, "Unused components were left: #{components.join '/'}" unless components.empty?
227
228       return nil, "template is not configured for private messages" if @options.has_key?(:private) && !@options[:private] && m.private?
229       return nil, "template is not configured for public messages" if @options.has_key?(:public) && !@options[:public] && !m.private?
230       
231       options.delete_if {|k, v| v.nil?} # Remove nil values.
232       return options, nil
233     end
234
235     def inspect
236       when_str = @requirements.empty? ? "" : " when #{@requirements.inspect}"
237       default_str = @defaults.empty? ? "" : " || #{@defaults.inspect}"
238       "<#{self.class.to_s} #{@items.collect{|c| c.kind_of?(String) ? c : c.inspect}.join(' ').inspect}#{default_str}#{when_str}>"
239     end
240
241     # Verify that the given value passes this template's requirements
242     def passes_requirements?(name, value)
243       return @defaults.key?(name) && @defaults[name].nil? if value.nil? # Make sure it's there if it should be
244
245       case @requirements[name]
246         when nil then true
247         when Regexp then
248           value = value.to_s
249           match = @requirements[name].match(value)
250           match && match[0].length == value.length
251         else
252           @requirements[name] == value.to_s
253       end
254     end
255
256     def requirements_for(name)
257       name = name.to_s.sub(/^\*/,"").intern if (/^\*/ =~ name.inspect)
258       presence = (@defaults.key?(name) && @defaults[name].nil?)
259       requirement = case @requirements[name]
260         when nil then nil
261         when Regexp then "match #{@requirements[name].inspect}"
262         else "be equal to #{@requirements[name].inspect}"
263       end
264       if presence && requirement then "#{name} must be present and #{requirement}"
265       elsif presence || requirement then "#{name} must #{requirement || 'be present'}"
266       else "#{name} has no requirements"
267       end
268     end
269   end
270 end