]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/plugins.rb
Add info about ignored plugins (blacklisted, disabled, already loaded) to help; clean...
[user/henk/code/ruby/rbot.git] / lib / rbot / plugins.rb
1 module Irc
2     BotConfig.register BotConfigArrayValue.new('plugins.blacklist',
3       :default => [], :wizard => false, :requires_restart => true,
4       :desc => "Plugins that should not be loaded")
5 module Plugins
6   require 'rbot/messagemapper'
7
8   # base class for all rbot plugins
9   # certain methods will be called if they are provided, if you define one of
10   # the following methods, it will be called as appropriate:
11   #
12   # map(template, options)::
13   # map!(template, options)::
14   #    map is the new, cleaner way to respond to specific message formats
15   #    without littering your plugin code with regexps. The difference
16   #    between map and map! is that map! will not register the new command
17   #    as an alternative name for the plugin.
18   #
19   #    Examples:
20   #
21   #      plugin.map 'karmastats', :action => 'karma_stats'
22   #
23   #      # while in the plugin...
24   #      def karma_stats(m, params)
25   #        m.reply "..."
26   #      end
27   #
28   #      # the default action is the first component
29   #      plugin.map 'karma'
30   #
31   #      # attributes can be pulled out of the match string
32   #      plugin.map 'karma for :key'
33   #      plugin.map 'karma :key'
34   #
35   #      # while in the plugin...
36   #      def karma(m, params)
37   #        item = params[:key]
38   #        m.reply 'karma for #{item}'
39   #      end
40   #
41   #      # you can setup defaults, to make parameters optional
42   #      plugin.map 'karma :key', :defaults => {:key => 'defaultvalue'}
43   #
44   #      # the default auth check is also against the first component
45   #      # but that can be changed
46   #      plugin.map 'karmastats', :auth => 'karma'
47   #
48   #      # maps can be restricted to public or private message:
49   #      plugin.map 'karmastats', :private false,
50   #      plugin.map 'karmastats', :public false,
51   #    end
52   #
53   # listen(UserMessage)::
54   #                        Called for all messages of any type. To
55   #                        differentiate them, use message.kind_of? It'll be
56   #                        either a PrivMessage, NoticeMessage, KickMessage,
57   #                        QuitMessage, PartMessage, JoinMessage, NickMessage,
58   #                        etc.
59   #
60   # privmsg(PrivMessage)::
61   #                        called for a PRIVMSG if the first word matches one
62   #                        the plugin register()d for. Use m.plugin to get
63   #                        that word and m.params for the rest of the message,
64   #                        if applicable.
65   #
66   # kick(KickMessage)::
67   #                        Called when a user (or the bot) is kicked from a
68   #                        channel the bot is in.
69   #
70   # join(JoinMessage)::
71   #                        Called when a user (or the bot) joins a channel
72   #
73   # part(PartMessage)::
74   #                        Called when a user (or the bot) parts a channel
75   #
76   # quit(QuitMessage)::
77   #                        Called when a user (or the bot) quits IRC
78   #
79   # nick(NickMessage)::
80   #                        Called when a user (or the bot) changes Nick
81   # topic(TopicMessage)::
82   #                        Called when a user (or the bot) changes a channel
83   #                        topic
84   #
85   # connect()::            Called when a server is joined successfully, but
86   #                        before autojoin channels are joined (no params)
87   #
88   # save::                 Called when you are required to save your plugin's
89   #                        state, if you maintain data between sessions
90   #
91   # cleanup::              called before your plugin is "unloaded", prior to a
92   #                        plugin reload or bot quit - close any open
93   #                        files/connections or flush caches here
94   class Plugin
95     attr_reader :bot   # the associated bot
96     # initialise your plugin. Always call super if you override this method,
97     # as important variables are set up for you
98     def initialize
99       @bot = Plugins.bot
100       @names = Array.new
101       @handler = MessageMapper.new(self)
102       @registry = BotRegistryAccessor.new(@bot, self.class.to_s.gsub(/^.*::/, ""))
103     end
104
105     def flush_registry
106       # debug "Flushing #{@registry}"
107       @registry.flush
108     end
109
110     def cleanup
111       # debug "Closing #{@registry}"
112       @registry.close
113     end
114
115     def map(*args)
116       @handler.map(*args)
117       # register this map
118       name = @handler.last.items[0]
119       self.register name
120       unless self.respond_to?('privmsg')
121         def self.privmsg(m)
122           @handler.handle(m)
123         end
124       end
125     end
126
127     def map!(*args)
128       @handler.map(*args)
129       # register this map
130       name = @handler.last.items[0]
131       self.register name, {:hidden => true}
132       unless self.respond_to?('privmsg')
133         def self.privmsg(m)
134           @handler.handle(m)
135         end
136       end
137     end
138
139     # return an identifier for this plugin, defaults to a list of the message
140     # prefixes handled (used for error messages etc)
141     def name
142       @names.join("|")
143     end
144
145     # return a help string for your module. for complex modules, you may wish
146     # to break your help into topics, and return a list of available topics if
147     # +topic+ is nil. +plugin+ is passed containing the matching prefix for
148     # this message - if your plugin handles multiple prefixes, make sure your
149     # return the correct help for the prefix requested
150     def help(plugin, topic)
151       "no help"
152     end
153
154     # register the plugin as a handler for messages prefixed +name+
155     # this can be called multiple times for a plugin to handle multiple
156     # message prefixes
157     def register(name,opts={})
158       raise ArgumentError, "Second argument must be a hash!" unless opts.kind_of?(Hash)
159       return if Plugins.plugins.has_key?(name)
160       Plugins.plugins[name] = self
161       @names << name unless opts.fetch(:hidden, false)
162     end
163
164     # default usage method provided as a utility for simple plugins. The
165     # MessageMapper uses 'usage' as its default fallback method.
166     def usage(m, params = {})
167       m.reply "incorrect usage, ask for help using '#{@bot.nick}: help #{m.plugin}'"
168     end
169
170   end
171
172   # class to manage multiple plugins and delegate messages to them for
173   # handling
174   class Plugins
175     # hash of registered message prefixes and associated plugins
176     @@plugins = Hash.new
177     # associated IrcBot class
178     @@bot = nil
179
180     # bot::     associated IrcBot class
181     # dirlist:: array of directories to scan (in order) for plugins
182     #
183     # create a new plugin handler, scanning for plugins in +dirlist+
184     def initialize(bot, dirlist)
185       @@bot = bot
186       @dirs = dirlist
187       scan
188     end
189
190     # access to associated bot
191     def Plugins.bot
192       @@bot
193     end
194
195     # access to list of plugins
196     def Plugins.plugins
197       @@plugins
198     end
199
200     # load plugins from pre-assigned list of directories
201     def scan
202       @blacklist = Array.new
203       @@bot.config['plugins.blacklist'].each { |p|
204         @blacklist << p+".rb"
205       }
206       @failed = Array.new
207       @ignored = Array.new
208       processed = Hash.new
209       @blacklist.each { |p|
210         processed[p.intern] = :blacklisted
211       }
212       dirs = Array.new
213       dirs << Config::datadir + "/plugins"
214       dirs += @dirs
215       dirs.reverse.each {|dir|
216         if(FileTest.directory?(dir))
217           d = Dir.new(dir)
218           d.sort.each {|file|
219             next if(file =~ /^\./)
220             if processed.has_key?(file.intern)
221               @ignored << {:name => file, :dir => dir, :reason => processed[file.intern]}
222               next
223             end
224             if(file =~ /^(.+\.rb)\.disabled$/)
225               # GB: Do we want to do this? This means that a disabled plugin in a directory
226               #     will disable in all subsequent directories. This was probably meant
227               #     to be used before plugins.blacklist was implemented, so I think
228               #     we don't need this anymore
229               processed[$1.intern] = :disabled
230               @ignored << {:name => $1, :dir => dir, :reason => processed[$1.intern]}
231               next
232             end
233             next unless(file =~ /\.rb$/)
234             tmpfilename = "#{dir}/#{file}"
235
236             # create a new, anonymous module to "house" the plugin
237             # the idea here is to prevent namespace pollution. perhaps there
238             # is another way?
239             plugin_module = Module.new
240
241             begin
242               plugin_string = IO.readlines(tmpfilename).join("")
243               debug "loading plugin #{tmpfilename}"
244               plugin_module.module_eval(plugin_string)
245               processed[file.intern] = :loaded
246             rescue Exception => err
247               # rescue TimeoutError, StandardError, NameError, LoadError, SyntaxError => err
248               warning "plugin #{tmpfilename} load failed\n" + err.inspect
249               debug err.backtrace.join("\n")
250               bt = err.backtrace.select { |line|
251                 line.match(/^(\(eval\)|#{tmpfilename}):\d+/)
252               }
253               bt.map! { |el|
254                 el.gsub(/^\(eval\)(:\d+)(:in `.*')?(:.*)?/) { |m|
255                   "#{tmpfilename}#{$1}#{$3}"
256                 }
257               }
258               msg = err.to_str.gsub(/^\(eval\)(:\d+)(:in `.*')?(:.*)?/) { |m|
259                 "#{tmpfilename}#{$1}#{$3}"
260               }
261               newerr = err.class.new(msg)
262               newerr.set_backtrace(bt)
263               # debug "Simplified error: " << newerr.inspect
264               # debug newerr.backtrace.join("\n")
265               @failed << { :name => file, :dir => dir, :reason => newerr }
266               # debug "Failures: #{@failed.inspect}"
267             end
268           }
269         end
270       }
271     end
272
273     # call the save method for each active plugin
274     def save
275       delegate 'flush_registry'
276       delegate 'save'
277     end
278
279     # call the cleanup method for each active plugin
280     def cleanup
281       delegate 'cleanup'
282     end
283
284     # drop all plugins and rescan plugins on disk
285     # calls save and cleanup for each plugin before dropping them
286     def rescan
287       save
288       cleanup
289       @@plugins = Hash.new
290       scan
291     end
292
293     # return list of help topics (plugin names)
294     def helptopics
295       # Active plugins first
296       if(@@plugins.length > 0)
297         list = " [#{length} plugin#{'s' if length > 1}: " + @@plugins.values.uniq.collect{|p| p.name}.sort.join(", ")
298       else
299         list = " [no plugins active"
300       end
301       # Ignored plugins next
302       list << "; #{Underline}#{@ignored.length} plugin#{'s' if @ignored.length > 1} ignored#{Underline}: use #{Bold}help ignored plugins#{Bold} to see why" unless @ignored.empty?
303       # Failed plugins next
304       list << "; #{Reverse}#{@failed.length} plugin#{'s' if @failed.length > 1} failed to load#{Reverse}: use #{Bold}help failed plugins#{Bold} to see why" unless @failed.empty?
305       list << "]"
306       return list
307     end
308
309     def length
310       @@plugins.values.uniq.length
311     end
312
313     # return help for +topic+ (call associated plugin's help method)
314     def help(topic="")
315       case topic
316       when /fail(?:ed)?\s*plugins?.*(trace(?:back)?s?)?/
317         # debug "Failures: #{@failed.inspect}"
318         return "no plugins failed to load" if @failed.empty?
319         return (@failed.inject(Array.new) { |list, p|
320           list << "#{Bold}#{p[:name]}#{Bold} in #{p[:dir]} failed"
321           list << "with error #{p[:reason].class}: #{p[:reason]}"
322           list << "at #{p[:reason].backtrace.join(', ')}" if $1 and not p[:reason].backtrace.empty?
323           list
324         }).join("\n")
325       when /ignored?\s*plugins?/
326         return "no plugins were ignored" if @ignored.empty?
327         return (@ignored.inject(Array.new) { |list, p|
328           case p[:reason]
329           when :loaded
330             list << "#{p[:name]} in #{p[:dir]} (overruled by previous)"
331           else
332             list << "#{p[:name]} in #{p[:dir]} (#{p[:reason].to_s})"
333           end
334           list
335         }).join(", ")
336       when /^(\S+)\s*(.*)$/
337         key = $1
338         params = $2
339         if(@@plugins.has_key?(key))
340           begin
341             return @@plugins[key].help(key, params)
342           rescue Exception => err
343             #rescue TimeoutError, StandardError, NameError, SyntaxError => err
344             error "plugin #{@@plugins[key].name} help() failed: #{err.class}: #{err}"
345             error err.backtrace.join("\n")
346           end
347         else
348           return false
349         end
350       end
351     end
352
353     # see if each plugin handles +method+, and if so, call it, passing
354     # +message+ as a parameter
355     def delegate(method, *args)
356       @@plugins.values.uniq.each {|p|
357         if(p.respond_to? method)
358           begin
359             p.send method, *args
360           rescue Exception => err
361             #rescue TimeoutError, StandardError, NameError, SyntaxError => err
362             error "plugin #{p.name} #{method}() failed: #{err.class}: #{err}"
363             error err.backtrace.join("\n")
364           end
365         end
366       }
367     end
368
369     # see if we have a plugin that wants to handle this message, if so, pass
370     # it to the plugin and return true, otherwise false
371     def privmsg(m)
372       return unless(m.plugin)
373       if (@@plugins.has_key?(m.plugin) &&
374           @@plugins[m.plugin].respond_to?("privmsg") &&
375           @@bot.auth.allow?(m.plugin, m.source, m.replyto))
376         begin
377           @@plugins[m.plugin].privmsg(m)
378         rescue Exception => err
379           #rescue TimeoutError, StandardError, NameError, SyntaxError => err
380           error "plugin #{@@plugins[m.plugin].name} privmsg() failed: #{err.class}: #{err}"
381           error err.backtrace.join("\n")
382         end
383         return true
384       end
385       return false
386     end
387   end
388
389 end
390 end