zammad.rb 1.1 KB

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