2022-01-01 13:38:12 +00:00
|
|
|
# Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
|
2015-03-22 10:46:05 +00:00
|
|
|
|
2015-07-15 19:45:40 +00:00
|
|
|
class Service::GeoIp::Zammad
|
2015-03-22 10:46:05 +00:00
|
|
|
def self.location(address)
|
2017-09-25 20:45:21 +00:00
|
|
|
return {} if address == '127.0.0.1'
|
|
|
|
return {} if address == '::1'
|
2015-03-22 10:46:05 +00:00
|
|
|
|
|
|
|
# check cache
|
|
|
|
cache_key = "zammadgeoip::#{address}"
|
2021-05-31 13:05:54 +00:00
|
|
|
cache = ::Cache.read(cache_key)
|
2015-03-22 10:46:05 +00:00
|
|
|
return cache if cache
|
|
|
|
|
|
|
|
# do lookup
|
2015-04-27 13:20:16 +00:00
|
|
|
host = 'https://geo.zammad.com'
|
2015-05-05 14:25:28 +00:00
|
|
|
url = "/lookup?ip=#{CGI.escape address}"
|
2015-03-22 10:46:05 +00:00
|
|
|
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
|
|
|
{
|
2018-12-19 17:31:51 +00:00
|
|
|
json: true,
|
|
|
|
open_timeout: 2,
|
|
|
|
read_timeout: 4,
|
2016-01-21 01:07:50 +00:00
|
|
|
total_timeout: 4,
|
2021-07-20 13:31:46 +00:00
|
|
|
verify_ssl: true,
|
2015-03-22 10:46:05 +00:00
|
|
|
},
|
|
|
|
)
|
2021-05-12 11:37:44 +00:00
|
|
|
if !response.success? && response.code.to_s !~ %r{^40.$}
|
2020-03-12 08:23:19 +00:00
|
|
|
raise "#{response.code}/#{response.body}"
|
2015-03-22 10:46:05 +00:00
|
|
|
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
|
|
|
|
|
2018-04-26 08:55:53 +00:00
|
|
|
::Cache.write(cache_key, data, { expires_in: 90.days })
|
2015-03-22 10:46:05 +00:00
|
|
|
rescue => e
|
2015-05-05 08:26:53 +00:00
|
|
|
Rails.logger.error "#{host}#{url}: #{e.inspect}"
|
2018-04-26 08:55:53 +00:00
|
|
|
::Cache.write(cache_key, data, { expires_in: 60.minutes })
|
2015-03-22 10:46:05 +00:00
|
|
|
end
|
|
|
|
data
|
|
|
|
end
|
2015-04-27 14:15:29 +00:00
|
|
|
end
|