trabajo-afectivo/lib/service/geo_ip/zammad.rb

48 lines
1.2 KiB
Ruby
Raw Permalink Normal View History

2022-01-01 13:38:12 +00:00
# Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
class Service::GeoIp::Zammad
def self.location(address)
return {} if address == '127.0.0.1'
return {} if address == '::1'
# check cache
cache_key = "zammadgeoip::#{address}"
cache = ::Cache.read(cache_key)
return cache if cache
# do lookup
host = 'https://geo.zammad.com'
url = "/lookup?ip=#{CGI.escape address}"
data = {}
begin
2015-03-22 22:13:39 +00:00
response = UserAgent.get(
"#{host}#{url}",
{},
{
json: true,
open_timeout: 2,
read_timeout: 4,
total_timeout: 4,
verify_ssl: true,
},
)
if !response.success? && response.code.to_s !~ %r{^40.$}
raise "#{response.code}/#{response.body}"
end
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
::Cache.write(cache_key, data, { expires_in: 90.days })
rescue => e
2015-05-05 08:26:53 +00:00
Rails.logger.error "#{host}#{url}: #{e.inspect}"
::Cache.write(cache_key, data, { expires_in: 60.minutes })
end
data
end
end