summaryrefslogtreecommitdiff
path: root/lib/rbot/core/utils/agent.rb
blob: 8949a5c83ffcdf7c217c9ec63aa3e32e0c46a44b (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
# encoding: UTF-8
#-- vim:sw=2:et
#++
#
# :title: Mechanize Agent Factory
#
# Author:: Matthias Hecker <apoc@sixserv.org>
#
# Central factory for Mechanize agent instances, creates
# pre-configured agents. The main goal of this is to have
# central proxy and user agent configuration for mechanize.
#
# plugins can just call @bot.agent.create to return
# a new unique mechanize agent.

require 'mechanize'

require 'digest/md5'
require 'uri'

module ::Irc
module Utils

class AgentFactory
  Bot::Config.register Bot::Config::IntegerValue.new('agent.max_redir',
    :default => 5,
    :desc => "Maximum number of redirections to be used when getting a document")
  Bot::Config.register Bot::Config::BooleanValue.new('agent.ssl_verify',
    :default => true,
    :desc => "Whether or not you want to validate SSL certificates")
  Bot::Config.register Bot::Config::BooleanValue.new('agent.proxy_use',
    :default => true,
    :desc => "Use HTTP proxy or not")
  Bot::Config.register Bot::Config::StringValue.new('agent.proxy_host',
    :default => '127.0.0.1',
    :desc => "HTTP proxy hostname")
  Bot::Config.register Bot::Config::IntegerValue.new('agent.proxy_port',
    :default => 8118,
    :desc => "HTTP proxy port")
  Bot::Config.register Bot::Config::StringValue.new('agent.proxy_username',
    :default => nil,
    :desc => "HTTP proxy username")
  Bot::Config.register Bot::Config::StringValue.new('agent.proxy_password',
    :default => nil,
    :desc => "HTTP proxy password")

  def initialize(bot)
    @bot = bot
  end

  def cleanup
  end

  # Returns a new, unique instance of Mechanize.
  def create(noproxy=false)
    agent = Mechanize.new
    agent.redirection_limit = @bot.config['agent.max_redir']
    if not @bot.config['agent.ssl_verify']
      agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
    if @bot.config['agent.proxy_use'] and not noproxy
      agent.set_proxy(
        @bot.config['agent.proxy_host'],
        @bot.config['agent.proxy_port'],
        @bot.config['agent.proxy_username'],
        @bot.config['agent.proxy_password']
      )
    end
    agent
  end
end

end # Utils
end # Irc

class AgentPlugin < CoreBotModule
  def initialize(*a)
    super(*a)
    debug 'initializing agent factory'
    @bot.agent = Irc::Utils::AgentFactory.new(@bot)
  end

  def cleanup
    debug 'shutting down agent factory'
    @bot.agent.cleanup
    @bot.agent = nil
    super
  end
end

AgentPlugin.new