zammad.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://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 = ::Rails.cache.read(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. verify_ssl: true,
  24. },
  25. )
  26. if !response.success? && response.code.to_s !~ %r{^40.$}
  27. raise "#{response.code}/#{response.body}"
  28. end
  29. data = response.data
  30. # compat. map
  31. if data && data['country_code2']
  32. data['country_code'] = data['country_code2']
  33. end
  34. ::Rails.cache.write(cache_key, data, { expires_in: 90.days })
  35. rescue => e
  36. Rails.logger.error "#{host}#{url}: #{e.inspect}"
  37. ::Rails.cache.write(cache_key, data, { expires_in: 60.minutes })
  38. end
  39. data
  40. end
  41. end