2021-10-13 09:44:02 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
import ipaddress
|
2023-07-24 03:52:25 +00:00
|
|
|
import os
|
2021-10-13 09:44:02 +00:00
|
|
|
|
|
|
|
import geoip2.database
|
|
|
|
from django.conf import settings
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
from geoip2.errors import GeoIP2Error
|
2021-10-13 09:44:02 +00:00
|
|
|
|
2022-05-16 04:18:23 +00:00
|
|
|
__all__ = ['get_ip_city_by_geoip']
|
2021-10-13 09:44:02 +00:00
|
|
|
reader = None
|
|
|
|
|
|
|
|
|
2022-05-16 04:18:23 +00:00
|
|
|
def get_ip_city_by_geoip(ip):
|
2021-10-13 09:44:02 +00:00
|
|
|
global reader
|
|
|
|
if reader is None:
|
|
|
|
path = os.path.join(os.path.dirname(__file__), 'GeoLite2-City.mmdb')
|
|
|
|
reader = geoip2.database.Reader(path)
|
|
|
|
|
|
|
|
try:
|
|
|
|
is_private = ipaddress.ip_address(ip.strip()).is_private
|
|
|
|
if is_private:
|
|
|
|
return _('LAN')
|
|
|
|
except ValueError:
|
|
|
|
return _("Invalid ip")
|
|
|
|
|
|
|
|
try:
|
|
|
|
response = reader.city(ip)
|
|
|
|
except GeoIP2Error:
|
2022-05-24 04:31:16 +00:00
|
|
|
return _("Unknown")
|
2021-10-13 09:44:02 +00:00
|
|
|
|
2022-05-16 04:18:23 +00:00
|
|
|
city_names = response.city.names or {}
|
|
|
|
lang = settings.LANGUAGE_CODE[:2]
|
|
|
|
if lang == 'zh':
|
|
|
|
lang = 'zh-CN'
|
|
|
|
city = city_names.get(lang, _("Unknown"))
|
|
|
|
return city
|