From 4500c8990424d68166fadc0ce6c632be9b790fb5 Mon Sep 17 00:00:00 2001 From: sjdonado Date: Sun, 23 Mar 2025 11:55:34 +0100 Subject: [PATCH] fix: convert IpLookup to struct and remove reader instance --- app/controllers/click.cr | 3 +-- app/lib/ip_lookup.cr | 28 +++++++++++----------------- 2 files changed, 12 insertions(+), 19 deletions(-) diff --git a/app/controllers/click.cr b/app/controllers/click.cr index 773c553..1665461 100644 --- a/app/controllers/click.cr +++ b/app/controllers/click.cr @@ -1,7 +1,6 @@ require "user_agent_parser" UserAgent.load_regexes(File.read("data/uap_core_regexes.yaml")) -IpLookup.load_mmdb("data/GeoLite2-Country.mmdb") module App::Controllers struct ClickController @@ -31,7 +30,7 @@ module App::Controllers click = App::Models::Click.new click.link_id = link_id - click.country = client_ip ? IpLookup.new(client_ip).try(&.country.try(&.code)) : nil + click.country = client_ip ? IpLookup.country(client_ip).try(&.code) : nil click.user_agent = user_agent_str click.browser = ua_parser.try(&.family) click.os = ua_parser.try(&.os.try(&.family)) diff --git a/app/lib/ip_lookup.cr b/app/lib/ip_lookup.cr index dbe7f6a..08f021b 100644 --- a/app/lib/ip_lookup.cr +++ b/app/lib/ip_lookup.cr @@ -1,38 +1,32 @@ require "maxminddb" +require "log" -class IpLookup - @@instance : MaxMindDB::Reader? = nil +struct IpLookup + MMDB_PATH = "data/GeoLite2-Country.mmdb" record Country, code : String? = nil, name : String? = nil - getter ip : String - getter country : Country? - - def self.load_mmdb(mmdb_file_path : String) - @@instance = MaxMindDB.open(mmdb_file_path) - end - - def initialize(ip_address : String) - @ip = ip_address - @country = nil - - return if @@instance.nil? || ip_address == "Unknown" || ip_address.empty? + def self.country(ip_address : String) : Country? + return nil if ip_address == "Unknown" || ip_address.empty? begin - lookup = @@instance.not_nil!.get(ip_address) + reader = MaxMindDB.open(MMDB_PATH) + lookup = reader.get(ip_address) country_code = lookup["country"]?.try &.["iso_code"]?.try &.as_s country_name = lookup["country"]?.try &.["names"]?.try &.["en"]?.try &.as_s if country_code || country_name - @country = Country.new( + Country.new( code: country_code, name: country_name ) + else + nil end rescue ex - # Silently handle lookup errors Log.error { "IP lookup failed: #{ex.message}" } + nil end end