2015-03-22 10:46:05 +00:00
|
|
|
# Copyright (C) 2012-2013 Zammad Foundation, http://zammad-foundation.org/
|
|
|
|
|
|
|
|
require 'cache'
|
|
|
|
|
|
|
|
class GeoIp::ZammadGeoIp
|
|
|
|
def self.location(address)
|
|
|
|
|
|
|
|
# check cache
|
|
|
|
cache_key = "zammadgeoip::#{address}"
|
|
|
|
cache = Cache.get( cache_key )
|
|
|
|
return cache if cache
|
|
|
|
|
|
|
|
# do lookup
|
2015-04-27 13:20:16 +00:00
|
|
|
host = 'https://geo.zammad.com'
|
2015-03-22 10:46:05 +00:00
|
|
|
url = "/lookup?ip=#{CGI::escape address}"
|
|
|
|
data = {}
|
|
|
|
begin
|
2015-03-22 22:13:39 +00:00
|
|
|
response = UserAgent.get(
|
2015-03-22 10:46:05 +00:00
|
|
|
"#{host}#{url}",
|
2015-03-23 00:31:30 +00:00
|
|
|
{},
|
2015-03-22 10:46:05 +00:00
|
|
|
{
|
2015-03-23 00:31:30 +00:00
|
|
|
:json => true,
|
2015-03-22 10:46:05 +00:00
|
|
|
:open_timeout => 2,
|
|
|
|
:read_timeout => 4,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
if !response.success? && response.code.to_s !~ /^40.$/
|
|
|
|
raise "ERROR: #{response.code.to_s}/#{response.body}"
|
|
|
|
end
|
|
|
|
|
2015-03-23 00:31:30 +00:00
|
|
|
data = response.data
|
2015-03-22 12:23:05 +00:00
|
|
|
|
|
|
|
# compat. map
|
|
|
|
if data && data['country_code2']
|
|
|
|
data['country_code'] = data['country_code2']
|
|
|
|
end
|
|
|
|
|
2015-03-22 10:46:05 +00:00
|
|
|
Cache.write( cache_key, data, { :expires_in => 90.days } )
|
|
|
|
rescue => e
|
|
|
|
puts "ERROR: #{host}#{url}: " + e.inspect
|
|
|
|
Cache.write( cache_key, data, { :expires_in => 60.minutes } )
|
|
|
|
end
|
|
|
|
data
|
|
|
|
end
|
|
|
|
end
|