"""사람 방문 비콘의 판별 — DB 를 모르는 순수 함수.""" import hashlib import re from datetime import datetime, timedelta, timezone from urllib.parse import urlsplit from services.crawler_detect import classify _KST = timezone(timedelta(hours=9)) # 봇 목록에는 일부러 안 넣은 UA — 우리 목업 검증 스크립트가 이걸로 돈다(crawler_detect 주석). # 크롤러 통계에선 "사람" 쪽으로 빠지지만, 방문으로 세면 숫자가 부풀려진다. _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_human(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_domain(referrer: str | None) -> str | None: try: host = (urlsplit(referrer or "").hostname or "").lower() except ValueError: # "http://[" 같은 값 — 손님 브라우저가 보낸 값이라 깨져 있어도 유입만 비울 뿐이다. return None if not host or "." not in host: return None # www. 만 걷는다 — m.search.naver.com 같은 하위 도메인은 유입 경로를 가르는 정보다. return (host[4:] if host.startswith("www.") else host)[:255] def visitor_hash(secret: str, ip: str, user_agent: str, now: datetime) -> str: month = now.astimezone(_KST).strftime("%Y-%m") return hashlib.sha256(f"{secret}|{ip}|{user_agent}|{month}".encode("utf-8")).hexdigest()