4 # :title: Geo IP Plugin
6 # Author:: Raine Virta <rane@kapsi.fi>
7 # Copyright:: (C) 2008 Raine Virta
10 # Resolves the geographic locations of users (network-wide) and IP addresses
13 class InvalidHostError < RuntimeError; end
14 class BadAPIError < RuntimeError; end
16 HOST_NAME_REGEX = /^[a-z0-9\-]+(?:\.[a-z0-9\-]+)*\.[a-z]{2,4}/i
18 def self.valid_host?(hostname)
19 hostname =~ HOST_NAME_REGEX ||
20 hostname =~ Resolv::IPv4::Regex && (hostname.split(".").map { |e| e.to_i }.max <= 255)
23 def self.geoiptool(bot, ip)
24 url = "http://www.geoiptool.com/en/?IP="
26 :country => %r{Country:.*?<a href=".*?" target="_blank"> (.*?)</a>}m,
27 :region => %r{Region:.*?<a href=".*?" target="_blank">(.*?)</a>}m,
28 :city => %r{City:.*?<td align="left" class="arial_bold">(.*?)</td>}m,
29 :lat => %r{Latitude:.*?<td align="left" class="arial_bold">(.*?)</td>}m,
30 :lon => %r{Longitude:.*?<td align="left" class="arial_bold">(.*?)</td>}m
33 raw = bot.httputil.get_response(url+ip)
34 raw = raw.decompress_body(raw.raw_body)
36 regexes.each { |key, regex| res[key] = raw.scan(regex).join('') }
41 IPINFODB_URL = "http://api.ipinfodb.com/v2/ip_query.php?key=%{key}&ip=%{ip}"
43 def self.ipinfodb(bot, ip)
44 key = bot.config['geoip.ipinfodb_key']
45 return if not key or key.empty?
46 url = IPINFODB_URL % {
50 debug "Requesting #{url}"
52 xml = bot.httputil.get(url)
55 obj = REXML::Document.new(xml)
58 :country => obj.elements["Response"].elements["CountryName"].text,
59 :city => obj.elements["Response"].elements["City"].text,
60 :region => obj.elements["Response"].elements["RegionName"].text,
62 debug "Returning #{newobj}"
65 raise InvalidHostError
70 "ipinfodb" => Proc.new { |bot, ip| ipinfodb(bot, ip) },
71 "geoiptool" => Proc.new { |bot, ip| geoiptool(bot, ip) },
74 def self.resolve(bot, hostname, api)
75 raise InvalidHostError unless valid_host?(hostname)
78 ip = Resolv.getaddress(hostname)
79 rescue Resolv::ResolvError
80 raise InvalidHostError
83 raise BadAPIError unless JUMP_TABLE.key?(api)
85 return JUMP_TABLE[api].call(bot, ip)
95 @hash[nick] = [] unless @hash[nick]
108 class GeoIpPlugin < Plugin
109 Config.register Config::ArrayValue.new('geoip.sources',
110 :default => [ "ipinfodb", "geoiptool" ],
111 :desc => "Which API to use for lookups. Supported values: ipinfodb, geoiptool")
112 Config.register Config::StringValue.new('geoip.ipinfodb_key',
114 :desc => "API key for the IPinfoDB geolocation service")
116 def help(plugin, topic="")
117 "geoip [<user|hostname|ip>] => returns the geographic location of whichever has been given -- note: user can be anyone on the network"
127 nick = m.whois[:nick].downcase
129 # need to see if the whois reply was invoked by this plugin
130 return unless @stack.has_nick?(nick)
133 msg = host2output(m.target.host, m.target.nick)
135 msg = "no such user on "+@bot.server.hostname.split(".")[-2]
137 @stack[nick].each do |source|
146 m.reply host2output(m.source.host, m.source.nick)
148 if m.replyto.class == Channel
150 # check if there is an user on the channel with nick same as input given
151 user = m.replyto.users.find { |usr| usr.nick == params[:input] }
154 m.reply host2output(user.host, user.nick)
159 # input is a host name or an IP
160 if GeoIP::valid_host?(params[:input])
161 m.reply host2output(params[:input])
163 # assume input is a nick
164 elsif params[:input] !~ /\./
165 nick = params[:input].downcase
167 @stack[nick] << m.replyto
170 m.reply "invalid input"
175 def host2output(host, nick=nil)
176 return "127.0.0.1 could not be res.. wait, what?" if host == "127.0.0.1"
178 geo = {:country => ""}
180 apis = @bot.config['geoip.sources']
181 apis.compact.each { |api|
182 geo = GeoIP::resolve(@bot, host, api)
183 if geo and geo[:country] != ""
187 rescue GeoIP::InvalidHostError, RuntimeError
189 return _("%{nick}'s location could not be resolved") % { :nick => nick }
191 return _("%{host} could not be resolved") % { :host => host }
193 rescue GeoIP::BadAPIError
194 return _("The owner configured me to use an API that doesn't exist, bug them!")
198 location << geo[:city] unless geo[:city].nil_or_empty?
199 location << geo[:region] unless geo[:region].nil_or_empty? or geo[:region] == geo[:city]
200 location << geo[:country] unless geo[:country].nil_or_empty?
203 res = _("%{nick} is from %{location}")
205 res = _("%{host} is located in %{location}")
211 :location => location.join(', ')
216 plugin = GeoIpPlugin.new
217 plugin.map "geoip [:input]", :action => 'geoip', :thread => true