]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/utils.rb
Fri Jul 29 13:07:56 BST 2005 Tom Gilbert <tom@linuxbrit.co.uk>
[user/henk/code/ruby/rbot.git] / lib / rbot / utils.rb
1 require 'net/http'
2 require 'uri'
3
4 module Irc
5
6   # miscellaneous useful functions
7   module Utils
8
9     def Utils.safe_exec(command, *args)
10       IO.popen("-") {|p|
11         if(p)
12           return p.readlines.join("\n")
13         else
14           begin
15             $stderr = $stdout
16             exec(command, *args)
17           rescue Exception => e
18             puts "exec of #{command} led to exception: #{e}"
19             Kernel::exit! 0
20           end
21           puts "exec of #{command} failed"
22           Kernel::exit! 0
23         end
24       }
25     end
26
27     # returns a string containing the result of an HTTP GET on the uri
28     def Utils.http_get(uristr, readtimeout=8, opentimeout=4)
29
30       # ruby 1.7 or better needed for this (or 1.6 and debian unstable)
31       Net::HTTP.version_1_2
32       # (so we support the 1_1 api anyway, avoids problems)
33
34       uri = URI.parse uristr
35       query = uri.path
36       if uri.query
37         query += "?#{uri.query}"
38       end
39
40       proxy_host = nil
41       proxy_port = nil
42       if(ENV['http_proxy'] && proxy_uri = URI.parse(ENV['http_proxy']))
43         proxy_host = proxy_uri.host
44         proxy_port = proxy_uri.port
45       end
46
47       begin
48         http = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port)
49         http.open_timeout = opentimeout
50         http.read_timeout = readtimeout
51
52         http.start {|http|
53           resp = http.get(query)
54           if resp.code == "200"
55             return resp.body
56           end
57         }
58       rescue => e
59         # cheesy for now
60         $stderr.puts "Utils.http_get exception: #{e}, while trying to get #{uristr}"
61         return nil
62       end
63     end
64   end
65 end