]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/utils.rb
New configuration option plugins.blacklist holding an array of plugins to be blacklis...
[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     # turn a number of seconds into a human readable string, e.g
10     # 2 days, 3 hours, 18 minutes, 10 seconds
11     def Utils.secs_to_string(secs)
12       ret = ""
13       days = (secs / (60 * 60 * 24)).to_i
14       secs = secs % (60 * 60 * 24)
15       hours = (secs / (60 * 60)).to_i
16       secs = (secs % (60 * 60))
17       mins = (secs / 60).to_i
18       secs = (secs % 60).to_i
19       ret += "#{days} days, " if days > 0
20       ret += "#{hours} hours, " if hours > 0 || days > 0
21       ret += "#{mins} minutes and " if mins > 0 || hours > 0 || days > 0
22       ret += "#{secs} seconds"
23       return ret
24     end
25
26
27     def Utils.safe_exec(command, *args)
28       IO.popen("-") {|p|
29         if(p)
30           return p.readlines.join("\n")
31         else
32           begin
33             $stderr = $stdout
34             exec(command, *args)
35           rescue Exception => e
36             puts "exec of #{command} led to exception: #{e.inspect}"
37             Kernel::exit! 0
38           end
39           puts "exec of #{command} failed"
40           Kernel::exit! 0
41         end
42       }
43     end
44
45     # returns a string containing the result of an HTTP GET on the uri
46     def Utils.http_get(uristr, readtimeout=8, opentimeout=4)
47
48       # ruby 1.7 or better needed for this (or 1.6 and debian unstable)
49       Net::HTTP.version_1_2
50       # (so we support the 1_1 api anyway, avoids problems)
51
52       uri = URI.parse uristr
53       query = uri.path
54       if uri.query
55         query += "?#{uri.query}"
56       end
57
58       proxy_host = nil
59       proxy_port = nil
60       if(ENV['http_proxy'] && proxy_uri = URI.parse(ENV['http_proxy']))
61         proxy_host = proxy_uri.host
62         proxy_port = proxy_uri.port
63       end
64
65       begin
66         http = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port)
67         http.open_timeout = opentimeout
68         http.read_timeout = readtimeout
69
70         http.start {|http|
71           resp = http.get(query)
72           if resp.code == "200"
73             return resp.body
74           end
75         }
76       rescue => e
77         # cheesy for now
78         error "Utils.http_get exception: #{e.inspect}, while trying to get #{uristr}"
79         return nil
80       end
81     end
82   end
83 end