]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - rbot/httputil.rb
Add new httputil object to the bot object, to be used by plugins etc that
[user/henk/code/ruby/rbot.git] / rbot / httputil.rb
1 module Irc
2
3 require 'net/http'
4 Net::HTTP.version_1_2
5   
6 # class for making http requests easier (mainly for plugins to use)
7 # this class can check the bot proxy configuration to determine if a proxy
8 # needs to be used, which includes support for per-url proxy configuration.
9 class HttpUtil
10   def initialize(bot)
11     @bot = bot
12   end
13
14   # uri:: Uri to create a proxy for
15   #
16   # return a net/http Proxy object, which is configured correctly for
17   # proxying based on the bot's proxy configuration. 
18   # This will include per-url proxy configuration based on the bot config
19   # +http_proxy_include/exclude+ options.
20   def get_proxy(uri)
21     proxy = nil
22     if (ENV['http_proxy'])
23       proxy = URI.parse ENV['http_proxy']
24     end
25     if (@bot.config["http_proxy"])
26       proxy = URI.parse ENV['http_proxy']
27     end
28
29     # if http_proxy_include or http_proxy_exclude are set, then examine the
30     # uri to see if this is a proxied uri
31     if uri
32       if @bot.config["http_proxy_exclude"]
33         # TODO
34       end
35       if @bot.config["http_proxy_include"]
36       end
37     end
38     
39     proxy_host = nil
40     proxy_port = nil
41     proxy_user = nil
42     proxy_pass = nil
43     if @bot.config["http_proxy_user"]
44       proxy_user = @bot.config["http_proxy_user"]
45       if @bot.config["http_proxy_pass"]
46         proxy_pass = @bot.config["http_proxy_pass"]
47       end
48     end
49     if proxy
50       proxy_host = proxy.host
51       proxy_port = proxy.port
52     end
53     
54     return Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port, proxy_user, proxy_port)
55   end
56
57   # uri::         uri to query (Uri object)
58   # readtimeout:: timeout for reading the response
59   # opentimeout:: timeout for opening the connection
60   #
61   # simple get request, returns response body if the status code is 200 and
62   # the request doesn't timeout.
63   def get(uri, readtimeout=10, opentimeout=5)
64     proxy = get_proxy(uri)
65     proxy.open_timeout = opentimeout
66     proxy.read_timeout = readtimeout
67    
68     begin
69       proxy.start() {|http|
70         resp = http.get(uri)
71         if resp.code == "200"
72           return resp.body
73         end
74         return nil
75       }
76     rescue StandardError, Timeout::Error => e
77       $stderr.puts "HttpUtil.get exception: #{e}, while trying to get #{uri}"
78     end
79     return nil
80   end
81 end
82
83 end