2018-10-09 22:21:41 +08:00
|
|
|
require_dependency 'maxminddb'
|
|
|
|
|
|
|
|
class DiscourseIpInfo
|
|
|
|
include Singleton
|
|
|
|
|
|
|
|
def initialize
|
2018-10-25 18:54:01 +08:00
|
|
|
open_db(File.join(Rails.root, 'vendor', 'data'))
|
|
|
|
end
|
|
|
|
|
|
|
|
def open_db(path)
|
2018-10-09 22:21:41 +08:00
|
|
|
begin
|
2018-10-25 18:54:01 +08:00
|
|
|
@mmdb_filename = File.join(path, 'GeoLite2-City.mmdb')
|
2018-10-09 22:21:41 +08: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 18:54:01 +08:00
|
|
|
def lookup(ip, locale = :en)
|
2018-10-09 22:21:41 +08: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 18:54:01 +08:00
|
|
|
locale = locale.to_s.sub('_', '-')
|
|
|
|
|
2018-10-09 22:21:41 +08:00
|
|
|
{
|
2018-10-25 18:54:01 +08:00
|
|
|
country: result.country.name(locale) || result.country.name,
|
2018-10-09 22:21:41 +08:00
|
|
|
country_code: result.country.iso_code,
|
2018-10-25 18:54:01 +08:00
|
|
|
region: result.subdivisions.most_specific.name(locale) || result.subdivisions.most_specific.name,
|
|
|
|
city: result.city.name(locale) || result.city.name,
|
2018-10-09 22:21:41 +08:00
|
|
|
}
|
|
|
|
end
|
|
|
|
|
2018-10-25 18:54:01 +08:00
|
|
|
def get(ip, locale = :en)
|
2018-10-09 22:21:41 +08:00
|
|
|
return {} unless @mmdb
|
|
|
|
|
2018-10-25 17:45:31 +08:00
|
|
|
ip = ip.to_s
|
2018-10-25 18:54:01 +08:00
|
|
|
@cache["#{ip}-#{locale}"] ||= lookup(ip, locale)
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.open_db(path)
|
|
|
|
instance.open_db(path)
|
2018-10-09 22:21:41 +08:00
|
|
|
end
|
|
|
|
|
2018-10-25 18:54:01 +08:00
|
|
|
def self.get(ip, locale = :en)
|
|
|
|
instance.get(ip, locale)
|
2018-10-09 22:21:41 +08:00
|
|
|
end
|
|
|
|
end
|