""" Geolocation Utilities Utilities for IP address geolocation lookup. """ import logging from typing import Tuple, Optional import httpx logger = logging.getLogger(__name__) # Geolocation API settings GEOLOCATION_API_URL = "http://ip-api.com/json/{ip}?fields=status,country,regionName" GEOLOCATION_TIMEOUT = 2.0 # seconds async def get_geolocation(ip_address: str) -> Tuple[Optional[str], Optional[str]]: """ Get country and region for an IP address using ip-api.com. Args: ip_address: IPv4 or IPv6 address Returns: Tuple of (country, region) or (None, None) if lookup fails """ if not ip_address: return None, None # Skip geolocation for localhost/private IPs if ip_address in ("127.0.0.1", "::1", "localhost") or ip_address.startswith(("192.168.", "10.", "172.")): return None, None try: async with httpx.AsyncClient(timeout=GEOLOCATION_TIMEOUT) as client: response = await client.get(GEOLOCATION_API_URL.format(ip=ip_address)) if response.status_code == 200: data = response.json() if data.get("status") == "success": return data.get("country"), data.get("regionName") except Exception as e: logger.warning(f"Geolocation lookup failed for {ip_address}: {e}") return None, None