zammad_geo_ip.rb 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # Copyright (C) 2012-2013 Zammad Foundation, http://zammad-foundation.org/
  2. require 'cache'
  3. class GeoIp::ZammadGeoIp
  4. def self.location(address)
  5. # check cache
  6. cache_key = "zammadgeoip::#{address}"
  7. cache = Cache.get( cache_key )
  8. return cache if cache
  9. # do lookup
  10. host = 'https://geo.zammad.com'
  11. url = "/lookup?ip=#{CGI.escape address}"
  12. data = {}
  13. begin
  14. response = UserAgent.get(
  15. "#{host}#{url}",
  16. {},
  17. {
  18. json: true,
  19. open_timeout: 2,
  20. read_timeout: 4,
  21. },
  22. )
  23. if !response.success? && response.code.to_s !~ /^40.$/
  24. fail "ERROR: #{response.code}/#{response.body}"
  25. end
  26. data = response.data
  27. # compat. map
  28. if data && data['country_code2']
  29. data['country_code'] = data['country_code2']
  30. end
  31. Cache.write( cache_key, data, { expires_in: 90.days } )
  32. rescue => e
  33. Rails.logger.error "#{host}#{url}: #{e.inspect}"
  34. Cache.write( cache_key, data, { expires_in: 60.minutes } )
  35. end
  36. data
  37. end
  38. end