From 959c3de5204a31efdd9185ea5660ac4b318ceaf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Motiejus=20Jak=C5=A1tys?= Date: Fri, 12 Jan 2024 01:31:38 +0200 Subject: [PATCH] fix geoip --- app/e11sync/settings.py | 4 +--- app/signup/admin.py | 4 ++-- app/signup/models.py | 19 ++++++++++++++----- flake.nix | 10 +++++----- 4 files changed, 22 insertions(+), 15 deletions(-) diff --git a/app/e11sync/settings.py b/app/e11sync/settings.py index 8964884..c56ba69 100644 --- a/app/e11sync/settings.py +++ b/app/e11sync/settings.py @@ -126,6 +126,4 @@ LOGGING = { }, } -#GEOIP_PATH = environ["GEOIP_PATH"] -#GEOIP_COUNTRY = "GeoIP.dat" -#GEOIP_CITY = "GeoIPCity.dat" +GEOIP_PATH = environ["GEOIP_PATH"] diff --git a/app/signup/admin.py b/app/signup/admin.py index 9e76a83..e077f43 100644 --- a/app/signup/admin.py +++ b/app/signup/admin.py @@ -7,7 +7,7 @@ class SignupAdmin(admin.ModelAdmin): _all_fields = ["email", "created_at", "anonymized_ip", "user_agent"] date_hierarchy = "created_at" - list_display = ["email", "created_at", "anonymized_ip", "user_agent"]# + ["country"] + list_display = ["email", "created_at", "anonymized_ip", "user_agent"] + ["country_code"] list_filter = ["email", "user_agent"] ordering = ["created_at"] - readonly_fields = _all_fields + readonly_fields = _all_fields + ["country_name"] diff --git a/app/signup/models.py b/app/signup/models.py index 1157761..0e09c42 100644 --- a/app/signup/models.py +++ b/app/signup/models.py @@ -1,6 +1,7 @@ -from django.db import models +import geoip2 -#from django.contrib.gis.geoip2 import GeoIP2 +from django.db import models +from django.contrib.gis.geoip2 import GeoIP2 class Signup(models.Model): email = models.EmailField() @@ -16,6 +17,14 @@ class Signup(models.Model): def __str__(self): return self.email - #def country(self): - # g = GeoIP2() - # return g.country(self.anonymized_ip) + def _country(self): + try: + return GeoIP2().country(self.anonymized_ip) + except geoip2.errors.AddressNotFoundError: + return {} + + def country_name(self): + return self._country().get("country_name", "??") + + def country_code(self): + return self._country().get("country_code", "??") diff --git a/flake.nix b/flake.nix index c96ba60..fad1549 100644 --- a/flake.nix +++ b/flake.nix @@ -41,21 +41,21 @@ libmaxminddb ]; geoip = pkgs.stdenv.mkDerivation { - name = geoip; + name = "geoip"; srcs = [geoip2-asn geoip2-city geoip2-country]; dontUnpack = true; installPhase = '' runHook preInstall mkdir -p $out - cp ${geoip2-asn} $out/ - cp ${geoip2-city} $out/ - cp ${geoip2-country} $out/ + cp ${geoip2-asn} $out/GeoLite2-ASN.mmdb + cp ${geoip2-city} $out/GeoLite2-City.mmdb + cp ${geoip2-country} $out/GeoLite2-Country.mmdb ''; }; in { devShells.default = pkgs.mkShell { LOCALE_ARCHIVE = "${pkgs.glibcLocales}/lib/locale/locale-archive"; - #GEOIP_PATH = "${geoip}"; + GEOIP_PATH = "${geoip}"; packages = devDeps ++ [geoip]; };