discourse/lib/discourse_ip_info.rb
Bianca Nenciu e1e392f15b DEV: Use DiscourseIpInfo for all IP queries. (#6482)
* DEV: Use DiscourseIpInfo for all IP queries.

* UX: Use latitude and longitude for more precision.
2018-10-30 22:08:57 +00:00

84 lines
2.2 KiB
Ruby

require_dependency 'maxminddb'
require_dependency 'resolv'
class DiscourseIpInfo
include Singleton
def initialize
open_db(File.join(Rails.root, 'vendor', 'data'))
end
def open_db(path)
@loc_mmdb = mmdb_load(File.join(path, 'GeoLite2-City.mmdb'))
@asn_mmdb = mmdb_load(File.join(path, 'GeoLite2-ASN.mmdb'))
@cache = LruRedux::ThreadSafeCache.new(1000)
end
def mmdb_load(filepath)
begin
MaxMindDB.new(filepath, MaxMindDB::LOW_MEMORY_FILE_READER)
rescue Errno::ENOENT => e
Rails.logger.warn("MaxMindDB could not be found: #{e}")
rescue
Rails.logger.warn("MaxMindDB could not be loaded.")
end
end
def lookup(ip, locale = :en)
ret = {}
if @loc_mmdb
begin
result = @loc_mmdb.lookup(ip)
if result&.found?
ret[:country] = result.country.name(locale) || result.country.name
ret[:country_code] = result.country.iso_code
ret[:region] = result.subdivisions.most_specific.name(locale) || result.subdivisions.most_specific.name
ret[:city] = result.city.name(locale) || result.city.name
ret[:latitude] = result.location.latitude
ret[:longitude] = result.location.longitude
ret[:location] = [ret[:city], ret[:region], ret[:country]].reject(&:blank?).join(", ")
end
rescue
Rails.logger.error("IP #{ip} could not be looked up in MaxMind GeoLite2-City database.")
end
end
if @asn_mmdb
begin
result = @asn_mmdb.lookup(ip)
if result&.found?
result = result.to_hash
ret[:asn] = result["autonomous_system_number"]
ret[:organization] = result["autonomous_system_organization"]
end
rescue
Rails.logger.error("IP #{ip} could not be looked up in MaxMind GeoLite2-ASN database.")
end
end
begin
result = Resolv::DNS.new.getname(ip)
ret[:hostname] = result&.to_s
rescue Resolv::ResolvError
end
ret
end
def get(ip, locale = :en)
ip = ip.to_s
locale = locale.to_s.sub('_', '-')
@cache["#{ip}-#{locale}"] ||= lookup(ip, locale)
end
def self.open_db(path)
instance.open_db(path)
end
def self.get(ip, locale = :en)
instance.get(ip, locale)
end
end