Files
o2o-castad-backend/app/traffic/detect/visit_detect.py
T

48 lines
1.9 KiB
Python

"""사람 방문 판별 — DB 를 모르는 순수 함수."""
import hashlib
import re
from datetime import datetime
from urllib.parse import urlsplit
from app.traffic.detect.crawler_detect import classify
from config import TIMEZONE
# 봇 목록에는 일부러 안 넣은 UA — 크롤링 통계에선 "사람" 쪽으로 빠지지만 방문으로 세면 숫자가 부풀려진다
_NOT_A_VISITOR = re.compile(r"HeadlessChrome|Lighthouse|PageSpeed", re.IGNORECASE)
_TABLET = re.compile(r"iPad|Tablet|Android(?!.*Mobile)", re.IGNORECASE)
_MOBILE = re.compile(r"Mobi|iPhone|iPod|Android", re.IGNORECASE)
def is_visitor(user_agent: str | None) -> bool:
if not user_agent:
return False
return classify(user_agent) is None and not _NOT_A_VISITOR.search(user_agent)
def device_of(user_agent: str) -> str:
if _TABLET.search(user_agent):
return "tablet"
if _MOBILE.search(user_agent):
return "mobile"
return "desktop"
def referrer_host(referrer: str | None) -> str | None:
"""referrer URL 의 호스트. 앞 `www.` 만 뗀다(m.search.naver.com 같은 하위 도메인은 유입 경로 정보다)."""
try:
host = (urlsplit(referrer or "").hostname or "").lower()
except ValueError:
# "http://[" 같은 값 — 손님 브라우저가 보낸 값이라 깨져 있어도 유입만 비울 뿐이다
return None
if not host or "." not in host:
return None
return (host[4:] if host.startswith("www.") else host)[:255]
def visitor_hash(secret: str, ip: str, user_agent: str, now: datetime) -> str:
"""쿠키 없이 방문자를 가르는 값. KST 달이 바뀌면 같은 사람도 새 값이 된다. IP 원문은 남지 않는다."""
kst = now.replace(tzinfo=TIMEZONE) if now.tzinfo is None else now.astimezone(TIMEZONE)
month = kst.strftime("%Y-%m")
return hashlib.sha256(f"{secret}|{ip}|{user_agent}|{month}".encode("utf-8")).hexdigest()