feat: add geolocation to download logs (country, city via ip-api.com)
This commit is contained in:
@@ -63,18 +63,42 @@ def _client_ip(request: Request) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
async def _geo_lookup(ip: str) -> tuple[str, str, str]:
|
||||
"""Return (country_code, country, city) via ip-api.com. Falls back to empty strings."""
|
||||
if not ip or ip in ("127.0.0.1", "::1"):
|
||||
return "", "", ""
|
||||
try:
|
||||
import httpx
|
||||
async with httpx.AsyncClient(timeout=5) as client:
|
||||
res = await client.get(
|
||||
f"http://ip-api.com/json/{ip}",
|
||||
params={"fields": "status,countryCode,country,city"},
|
||||
)
|
||||
data = res.json()
|
||||
if data.get("status") == "success":
|
||||
return data.get("countryCode", ""), data.get("country", ""), data.get("city", "")
|
||||
except Exception as e:
|
||||
logger.debug(f"Geo lookup failed for {ip}: {e}")
|
||||
return "", "", ""
|
||||
|
||||
|
||||
async def _log_download(video_id: int, request: Request):
|
||||
"""Write a DownloadLog entry (fire-and-forget)."""
|
||||
"""Write a DownloadLog entry with geo info (fire-and-forget)."""
|
||||
try:
|
||||
ua = request.headers.get("user-agent", "")
|
||||
browser, device = _parse_ua(ua)
|
||||
ip = _client_ip(request)
|
||||
country_code, country, city = await _geo_lookup(ip)
|
||||
async with async_session() as db:
|
||||
db.add(DownloadLog(
|
||||
video_id=video_id,
|
||||
ip=_client_ip(request),
|
||||
ip=ip,
|
||||
user_agent=ua[:512],
|
||||
browser=browser,
|
||||
device=device,
|
||||
country_code=country_code,
|
||||
country=country,
|
||||
city=city,
|
||||
downloaded_at=datetime.utcnow(),
|
||||
))
|
||||
await db.commit()
|
||||
|
||||
Reference in New Issue
Block a user