]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/agent.rb
fix: TCPSocked.gethostbyname is deprecated
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / agent.rb
1 # encoding: UTF-8
2 #-- vim:sw=2:et
3 #++
4 #
5 # :title: Mechanize Agent Factory
6 #
7 # Author:: Matthias Hecker <apoc@sixserv.org>
8 #
9 # Central factory for Mechanize agent instances, creates
10 # pre-configured agents. The main goal of this is to have
11 # central proxy and user agent configuration for mechanize.
12 #
13 # plugins can just call @bot.agent.create to return
14 # a new unique mechanize agent.
15
16 require 'mechanize'
17
18 require 'digest/md5'
19 require 'uri'
20
21 module ::Irc
22 module Utils
23
24 class AgentFactory
25   Bot::Config.register Bot::Config::IntegerValue.new('agent.max_redir',
26     :default => 5,
27     :desc => "Maximum number of redirections to be used when getting a document")
28   Bot::Config.register Bot::Config::BooleanValue.new('agent.ssl_verify',
29     :default => true,
30     :desc => "Whether or not you want to validate SSL certificates")
31   Bot::Config.register Bot::Config::BooleanValue.new('agent.proxy_use',
32     :default => true,
33     :desc => "Use HTTP proxy or not")
34   Bot::Config.register Bot::Config::StringValue.new('agent.proxy_host',
35     :default => '127.0.0.1',
36     :desc => "HTTP proxy hostname")
37   Bot::Config.register Bot::Config::IntegerValue.new('agent.proxy_port',
38     :default => 8118,
39     :desc => "HTTP proxy port")
40   Bot::Config.register Bot::Config::StringValue.new('agent.proxy_username',
41     :default => nil,
42     :desc => "HTTP proxy username")
43   Bot::Config.register Bot::Config::StringValue.new('agent.proxy_password',
44     :default => nil,
45     :desc => "HTTP proxy password")
46
47   def initialize(bot)
48     @bot = bot
49   end
50
51   def cleanup
52   end
53
54   # Returns a new, unique instance of Mechanize.
55   def create
56     agent = Mechanize.new
57     agent.redirection_limit = @bot.config['agent.max_redir']
58     if not @bot.config['agent.ssl_verify']
59       agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE
60     end
61     if @bot.config['agent.proxy_use']
62       agent.set_proxy(
63         @bot.config['agent.proxy_host'],
64         @bot.config['agent.proxy_port'],
65         @bot.config['agent.proxy_username'],
66         @bot.config['agent.proxy_password']
67       )
68     end
69     agent
70   end
71 end
72
73 end # Utils
74 end # Irc
75
76 class AgentPlugin < CoreBotModule
77   def initialize(*a)
78     super(*a)
79     debug 'initializing agent factory'
80     @bot.agent = Irc::Utils::AgentFactory.new(@bot)
81   end
82
83   def cleanup
84     debug 'shutting down agent factory'
85     @bot.agent.cleanup
86     @bot.agent = nil
87     super
88   end
89 end
90
91 AgentPlugin.new
92