zammad.rb 1.1 KB

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