2018-10-09 10:21:41 -04:00
|
|
|
require_dependency 'maxminddb'
|
|
|
|
|
|
|
|
class DiscourseIpInfo
|
|
|
|
include Singleton
|
|
|
|
|
|
|
|
def initialize
|
2018-10-25 06:54:01 -04:00
|
|
|
open_db(File.join(Rails.root, 'vendor', 'data'))
|
|
|
|
end
|
|
|
|
|
|
|
|
def open_db(path)
|
2018-10-09 10:21:41 -04:00
|
|
|
begin
|
2018-10-25 06:54:01 -04:00
|
|
|
@mmdb_filename = File.join(path, 'GeoLite2-City.mmdb')
|
2018-10-09 10:21:41 -04:00
|
|
|
@mmdb = MaxMindDB.new(@mmdb_filename, MaxMindDB::LOW_MEMORY_FILE_READER)
|
|
|
|
@cache = LruRedux::ThreadSafeCache.new(1000)
|
|
|
|
rescue Errno::ENOENT => e
|
|
|
|
Rails.logger.warn("MaxMindDB could not be found: #{e}")
|
|
|
|
rescue
|
|
|
|
Rails.logger.warn("MaxMindDB could not be loaded.")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-10-25 06:54:01 -04:00
|
|
|
def lookup(ip, locale = :en)
|
2018-10-09 10:21:41 -04:00
|
|
|
return {} unless @mmdb
|
|
|
|
|
|
|
|
begin
|
|
|
|
result = @mmdb.lookup(ip)
|
|
|
|
rescue
|
|
|
|
Rails.logger.error("IP #{ip} could not be looked up in MaxMindDB.")
|
|
|
|
end
|
|
|
|
|
|
|
|
return {} if !result || !result.found?
|
|
|
|
|
2018-10-25 06:54:01 -04:00
|
|
|
locale = locale.to_s.sub('_', '-')
|
|
|
|
|
2018-10-09 10:21:41 -04:00
|
|
|
{
|
2018-10-25 06:54:01 -04:00
|
|
|
country: result.country.name(locale) || result.country.name,
|
2018-10-09 10:21:41 -04:00
|
|
|
country_code: result.country.iso_code,
|
2018-10-25 06:54:01 -04:00
|
|
|
region: result.subdivisions.most_specific.name(locale) || result.subdivisions.most_specific.name,
|
|
|
|
city: result.city.name(locale) || result.city.name,
|
2018-10-09 10:21:41 -04:00
|
|
|
}
|
|
|
|
end
|
|
|
|
|
2018-10-25 06:54:01 -04:00
|
|
|
def get(ip, locale = :en)
|
2018-10-09 10:21:41 -04:00
|
|
|
return {} unless @mmdb
|
|
|
|
|
2018-10-25 05:45:31 -04:00
|
|
|
ip = ip.to_s
|
2018-10-25 06:54:01 -04:00
|
|
|
@cache["#{ip}-#{locale}"] ||= lookup(ip, locale)
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.open_db(path)
|
|
|
|
instance.open_db(path)
|
2018-10-09 10:21:41 -04:00
|
|
|
end
|
|
|
|
|
2018-10-25 06:54:01 -04:00
|
|
|
def self.get(ip, locale = :en)
|
|
|
|
instance.get(ip, locale)
|
2018-10-09 10:21:41 -04:00
|
|
|
end
|
|
|
|
end
|