summaryrefslogtreecommitdiff
path: root/lib/rbot/config.rb
blob: 44f169189a155df8f2525ba8fcb0e7765b1ceb5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
module Irc

  require 'yaml'
  require 'rbot/messagemapper'

  unless YAML.respond_to?(:load_file)
      def YAML.load_file( filepath )
        File.open( filepath ) do |f|
          YAML::load( f )
        end
      end
  end

  class BotConfigValue
    # allow the definition order to be preserved so that sorting by
    # definition order is possible. The BotConfigWizard does this to allow
    # the :wizard questions to be in a sensible order.
    @@order = 0
    attr_reader :type
    attr_reader :desc
    attr_reader :key
    attr_reader :wizard
    attr_reader :requires_restart
    attr_reader :order
    def initialize(key, params)
      # Keys must be in the form 'module.name'.
      # They will be internally passed around as symbols,
      # but we accept them both in string and symbol form.
      unless key.to_s =~ /^.+\..+$/
        raise ArgumentError,"key must be of the form 'module.name'"
      end
      @order = @@order
      @@order += 1
      @key = key.intern
      if params.has_key? :default
        @default = params[:default]
      else
        @default = false
      end
      @desc = params[:desc]
      @type = params[:type] || String
      @on_change = params[:on_change]
      @validate = params[:validate]
      @wizard = params[:wizard]
      @requires_restart = params[:requires_restart]
    end
    def default
      if @default.instance_of?(Proc)
        @default.call
      else
        @default
      end
    end
    def get
      return BotConfig.config[@key] if BotConfig.config.has_key?(@key)
      return @default
    end
    alias :value :get
    def set(value, on_change = true)
      BotConfig.config[@key] = value
      @on_change.call(BotConfig.bot, value) if on_change && @on_change
    end
    def unset
      BotConfig.config.delete(@key)
    end

    # set string will raise ArgumentErrors on failed parse/validate
    def set_string(string, on_change = true)
      value = parse string
      if validate value
        set value, on_change
      else
        raise ArgumentError, "invalid value: #{string}"
      end
    end
    
    # override this. the default will work for strings only
    def parse(string)
      string
    end

    def to_s
      get.to_s
    end

    private
    def validate(value)
      return true unless @validate
      if @validate.instance_of?(Proc)
        return @validate.call(value)
      elsif @validate.instance_of?(Regexp)
        raise ArgumentError, "validation via Regexp only supported for strings!" unless value.instance_of? String
        return @validate.match(value)
      else
        raise ArgumentError, "validation type #{@validate.class} not supported"
      end
    end
  end

  class BotConfigStringValue < BotConfigValue
  end
  class BotConfigBooleanValue < BotConfigValue
    def parse(string)
      return true if string == "true"
      return false if string == "false"
      raise ArgumentError, "#{string} does not match either 'true' or 'false'"
    end
  end
  class BotConfigIntegerValue < BotConfigValue
    def parse(string)
      raise ArgumentError, "not an integer: #{string}" unless string =~ /^-?\d+$/
      string.to_i
    end
  end
  class BotConfigFloatValue < BotConfigValue
    def parse(string)
      raise ArgumentError, "not a float #{string}" unless string =~ /^-?[\d.]+$/
      string.to_f
    end
  end
  class BotConfigArrayValue < BotConfigValue
    def parse(string)
      string.split(/,\s+/)
    end
    def to_s
      get.join(", ")
    end
  end
  class BotConfigEnumValue < BotConfigValue
    def initialize(key, params)
      super
      @values = params[:values]
    end
    def values
      if @values.instance_of?(Proc)
        return @values.call(BotConfig.bot)
      else
        return @values
      end
    end
    def parse(string)
      unless values.include?(string)
        raise ArgumentError, "invalid value #{string}, allowed values are: " + values.join(", ")
      end
      string
    end
    def desc
      "#{@desc} [valid values are: " + values.join(", ") + "]"
    end
  end

  # container for bot configuration
  class BotConfig
    # Array of registered BotConfigValues for defaults, types and help
    @@items = Hash.new
    def BotConfig.items
      @@items
    end
    # Hash containing key => value pairs for lookup and serialisation
    @@config = Hash.new(false)
    def BotConfig.config
      @@config
    end
    def BotConfig.bot
      @@bot
    end
    
    def BotConfig.register(item)
      unless item.kind_of?(BotConfigValue)
        raise ArgumentError,"item must be a BotConfigValue"
      end
      @@items[item.key] = item
    end

    # currently we store values in a hash but this could be changed in the
    # future. We use hash semantics, however.
    # components that register their config keys and setup defaults are
    # supported via []
    def [](key)
      return @@items[key].value if @@items.has_key?(key)
      return @@items[key.intern].value if @@items.has_key?(key.intern)
      # try to still support unregistered lookups
      # but warn about them
      if @@config.has_key?(key)
        warning "Unregistered lookup #{key.inspect}"
        return @@config[key]
      end
      if @@config.has_key?(key.intern)
        warning "Unregistered lookup #{key.intern.inspect}"
        return @@config[key.intern]
      end
      return false
    end

    # TODO should I implement this via BotConfigValue or leave it direct?
    #    def []=(key, value)
    #    end
    
    # pass everything else through to the hash
    def method_missing(method, *args, &block)
      return @@config.send(method, *args, &block)
    end

    def handle_list(m, params)
      modules = []
      if params[:module]
        @@items.each_key do |key|
          mod, name = key.to_s.split('.')
          next unless mod == params[:module]
          modules.push key unless modules.include?(name)
        end
        if modules.empty?
          m.reply "no such module #{params[:module]}"
        else
          m.reply modules.join(", ")
        end
      else
        @@items.each_key do |key|
          name = key.to_s.split('.').first
          modules.push name unless modules.include?(name)
        end
        m.reply "modules: " + modules.join(", ")
      end
    end

    def handle_get(m, params)
      key = params[:key].to_s.intern
      unless @@items.has_key?(key)
        m.reply "no such config key #{key}"
        return
      end
      value = @@items[key].to_s
      m.reply "#{key}: #{value}"
    end

    def handle_desc(m, params)
      key = params[:key].to_s.intern
      unless @@items.has_key?(key)
        m.reply "no such config key #{key}"
      end
      puts @@items[key].inspect
      m.reply "#{key}: #{@@items[key].desc}"
    end

    def handle_unset(m, params)
      key = params[:key].to_s.intern
      unless @@items.has_key?(key)
        m.reply "no such config key #{key}"
      end
      @@items[key].unset
      handle_get(m, params)
    end

    def handle_set(m, params)
      key = params[:key].to_s.intern
      value = params[:value].to_s
      unless @@items.has_key?(key)
        m.reply "no such config key #{key}"
        return
      end
      begin
        @@items[key].set_string(value)
      rescue ArgumentError => e
        m.reply "failed to set #{key}: #{e.message}"
        return
      end
      if @@items[key].requires_restart
        m.reply "this config change will take effect on the next restart"
      else
        m.okay
      end
    end

    def handle_help(m, params)
      topic = params[:topic]
      case topic
      when false
        m.reply "config module - bot configuration. usage: list, desc, get, set, unset"
      when "list"
        m.reply "config list => list configuration modules, config list <module> => list configuration keys for module <module>"
      when "get"
        m.reply "config get <key> => get configuration value for key <key>"
      when "unset"
        m.reply "reset key <key> to the default"
      when "set"
        m.reply "config set <key> <value> => set configuration value for key <key> to <value>"
      when "desc"
        m.reply "config desc <key> => describe what key <key> configures"
      else
        m.reply "no help for config #{topic}"
      end
    end
    def usage(m,params)
      m.reply "incorrect usage, try '#{@@bot.nick}: help config'"
    end

    # bot:: parent bot class
    # create a new config hash from #{botclass}/conf.rbot
    def initialize(bot)
      @@bot = bot

      # respond to config messages, to provide runtime configuration
      # management
      # messages will be:
      #  get
      #  set
      #  unset
      #  desc
      #  and for arrays:
      #    add TODO
      #    remove TODO
      @handler = MessageMapper.new(self)
      @handler.map 'config list :module', :action => 'handle_list',
                   :defaults => {:module => false}
      @handler.map 'config get :key', :action => 'handle_get'
      @handler.map 'config desc :key', :action => 'handle_desc'
      @handler.map 'config describe :key', :action => 'handle_desc'
      @handler.map 'config set :key *value', :action => 'handle_set'
      @handler.map 'config unset :key', :action => 'handle_unset'
      @handler.map 'config help :topic', :action => 'handle_help',
                   :defaults => {:topic => false}
      @handler.map 'help config :topic', :action => 'handle_help',
                   :defaults => {:topic => false}
      
      if(File.exist?("#{@@bot.botclass}/conf.yaml"))
        begin
          newconfig = YAML::load_file("#{@@bot.botclass}/conf.yaml")
          newconfig.each { |key, val|
            @@config[key.intern] = val
          }
          return
        rescue
          error "failed to read conf.yaml: #{$!}"
        end
      end
      # if we got here, we need to run the first-run wizard
      BotConfigWizard.new(@@bot).run
      # save newly created config
      save
    end

    # write current configuration to #{botclass}/conf.yaml
    def save
      begin
        debug "Writing new conf.yaml ..."
        File.open("#{@@bot.botclass}/conf.yaml.new", "w") do |file|
          savehash = {}
          @@config.each { |key, val|
            savehash[key.to_s] = val
          }
          file.puts savehash.to_yaml
        end
        debug "Officializing conf.yaml ..."
        File.rename("#{@@bot.botclass}/conf.yaml.new",
                    "#{@@bot.botclass}/conf.yaml")
      rescue => e
        error "failed to write configuration file conf.yaml! #{$!}"
        error "#{e.class}: #{e}"
        error e.backtrace.join("\n")
      end
    end

    def privmsg(m)
      @handler.handle(m)
    end
  end

  class BotConfigWizard
    def initialize(bot)
      @bot = bot
      @questions = BotConfig.items.values.find_all {|i| i.wizard }
    end
    
    def run()
      puts "First time rbot configuration wizard"
      puts "===================================="
      puts "This is the first time you have run rbot with a config directory of:"
      puts @bot.botclass
      puts "This wizard will ask you a few questions to get you started."
      puts "The rest of rbot's configuration can be manipulated via IRC once"
      puts "rbot is connected and you are auth'd."
      puts "-----------------------------------"

      return unless @questions
      @questions.sort{|a,b| a.order <=> b.order }.each do |q|
        puts q.desc
        begin
          print q.key.to_s + " [#{q.to_s}]: "
          response = STDIN.gets
          response.chop!
          unless response.empty?
            q.set_string response, false
          end
          puts "configured #{q.key} => #{q.to_s}"
          puts "-----------------------------------"
        rescue ArgumentError => e
          puts "failed to set #{q.key}: #{e.message}"
          retry
        end
      end
    end
  end
end