feat: backoffice 사이트 트래픽 통계(방문·봇 크롤링) 추가

This commit is contained in:
skkim committed 2026-10-20 13:51:33 +09:00
1 parent 3854aef320
commit 01dd8e7522
33 files changed
+2253 -57

No files matched your search

View File
Whitespace-only changes.
+44
View File
@@ -0,0 +1,44 @@
"""AI 답변 엔진에서 들어온 방문 판별.
표는 AEORanking(frontend/src/lib/analytics/ai-referral.ts)과 같다. referrer 를 지우고 링크에
utm_source 만 붙이는 앱(ChatGPT 는 utm_source=chatgpt.com)이 있어 utm 도 본다.
referrer·utm 이 모두 없는 AI 유입은 직접 유입으로 잡히므로 이 수치는 최소치다.
"""
from dataclasses import dataclass
@dataclass(frozen=True)
class AiReferral:
engine: str
#: 어떤 신호로 판별했나: referrer 호스트 또는 utm_source
signal: str
_SOURCES: tuple[tuple[str, tuple[str, ...], tuple[str, ...]], ...] = (
("chatgpt", ("chatgpt.com", "chat.openai.com"), ("chatgpt.com", "chatgpt")),
("perplexity", ("perplexity.ai",), ("perplexity.ai", "perplexity")),
("gemini", ("gemini.google.com", "bard.google.com"), ("gemini.google.com", "gemini")),
("claude", ("claude.ai",), ("claude.ai", "claude")),
("copilot", ("copilot.microsoft.com",), ("copilot.microsoft.com", "copilot")),
)
def _matches_host(host: str, domain: str) -> bool:
return host == domain or host.endswith(f".{domain}")
def classify_ai_referral(referrer_host: str | None, utm_source: str | None) -> AiReferral | None:
if referrer_host:
host = referrer_host.lower()
for engine, hosts, _ in _SOURCES:
if any(_matches_host(host, d) for d in hosts):
return AiReferral(engine, "referrer")
utm = (utm_source or "").strip().lower()
if utm:
for engine, _, utm_sources in _SOURCES:
if utm in utm_sources:
return AiReferral(engine, "utm")
return None
+74
View File
@@ -0,0 +1,74 @@
"""자칭 크롤러 판별 — UA 만 본다.
UA 는 위조할 수 있다. 여기서 세는 것은 "자칭 크롤러"이고 IP 대역으로 진위를 확인하지 않는다.
AI 봇·검색엔진 목록은 AEORanking(king:/mnt/data2/AEORankingPlatform/frontend/src/lib/analytics/ai-crawlers.ts),
web4ai(solution/backend/services/crawler_detect.py)와 같게 둔다 — 세 서비스의 통계를 나란히 볼 때
분류가 갈리면 비교가 안 된다. `preview` 는 공유 링크가 많은 ADO2 에만 있는 용도다.
"""
import re
from dataclasses import dataclass
# training: 모델 학습 수집 · search: AI 답변 엔진 색인 · user-fetch: 사용자가 물어서 그 자리에서 여는 요청
# search-engine: 전통 검색 크롤러(AI 답변에도 쓰인다) · preview: 메신저·SNS 링크 미리보기
# other: 목록 밖이지만 스스로 봇이라 밝힌 것
AI_PURPOSES = ("training", "search", "user-fetch")
@dataclass(frozen=True)
class CrawlerMatch:
bot: str | None
company: str | None
purpose: str
_KNOWN: tuple[tuple[str, str, str, re.Pattern[str]], ...] = tuple(
(bot, company, purpose, re.compile(pattern, re.IGNORECASE))
for bot, company, purpose, pattern in (
("GPTBot", "OpenAI", "training", r"\bGPTBot\b"),
("OAI-SearchBot", "OpenAI", "search", r"\bOAI-SearchBot\b"),
("ChatGPT-User", "OpenAI", "user-fetch", r"\bChatGPT-User\b"),
("ClaudeBot", "Anthropic", "training", r"\bClaudeBot\b"),
("Claude-SearchBot", "Anthropic", "search", r"\bClaude-SearchBot\b"),
("Claude-User", "Anthropic", "user-fetch", r"\bClaude-User\b"),
("PerplexityBot", "Perplexity", "search", r"\bPerplexityBot\b"),
("Perplexity-User", "Perplexity", "user-fetch", r"\bPerplexity-User\b"),
("meta-externalagent", "Meta", "training", r"\bmeta-externalagent\b"),
("meta-externalfetcher", "Meta", "user-fetch", r"\bmeta-externalfetcher\b"),
("MistralAI-User", "Mistral", "user-fetch", r"\bMistralAI-User\b"),
("DuckAssistBot", "DuckDuckGo", "search", r"\bDuckAssistBot\b"),
("Amazonbot", "Amazon", "search", r"\bAmazonbot\b"),
("Bytespider", "ByteDance", "training", r"\bBytespider\b"),
("CCBot", "Common Crawl", "training", r"\bCCBot\b"),
("Googlebot", "Google", "search-engine", r"\bGooglebot\b"),
("bingbot", "Microsoft", "search-engine", r"\bbingbot\b"),
("Applebot", "Apple", "search-engine", r"\bApplebot\b"),
("Yeti", "Naver", "search-engine", r"\bYeti/"),
# 카카오 스크래퍼는 UA 에 facebookexternalhit 을 함께 달고 오므로 facebookexternalhit 보다 먼저 둔다
("kakaotalk-scrap", "Kakao", "preview", r"\bkakaotalk-scrap\b"),
("facebookexternalhit", "Meta", "preview", r"\bfacebookexternalhit\b"),
# 텔레그램 UA 는 "TelegramBot (like TwitterBot)" 이라 Twitterbot 보다 먼저 둔다
("TelegramBot", "Telegram", "preview", r"\bTelegramBot\b"),
("Twitterbot", "X", "preview", r"\bTwitterbot\b"),
("Slackbot", "Slack", "preview", r"\bSlackbot\b"),
("Discordbot", "Discord", "preview", r"\bDiscordbot\b"),
)
)
# 목록에 없는 새 봇을 놓치지 않으려고 둔다 — 쌓인 UA 를 보고 목록에 올린다.
# HeadlessChrome 은 일부러 안 넣는다(web4ai 와 동일). 방문 통계에서는 visit_detect 가 따로 거른다.
_GENERIC = re.compile(r"bot|crawl|spider|slurp|externalhit|fetch", re.IGNORECASE)
_OTHER = CrawlerMatch(None, None, "other")
def classify(user_agent: str | None) -> CrawlerMatch | None:
"""UA 로 봇을 고른다. 사람(또는 판별 불가)이면 None."""
if not user_agent:
return None
for bot, company, purpose, pattern in _KNOWN:
if pattern.search(user_agent):
return CrawlerMatch(bot, company, purpose)
if _GENERIC.search(user_agent):
return _OTHER
return None
+124
View File
@@ -0,0 +1,124 @@
"""경로 분류 — 비콘 경로와 nginx 접근 로그 경로를 우리 페이지 종류로 바꾼다.
SPA 라우트는 프론트 `src/App.tsx` 의 pathname 분기와 같게 둔다. 라우트를 추가하면 여기도 고친다.
공유 페이지는 백엔드가 HTML 로 응답하며, 외부에서는 nginx 의 `/api` 접두사가 붙어 들어온다.
"""
import re
from dataclasses import dataclass
_MAX_PATH = 512
#: (콘텐츠 종류, SPA 상세 경로)
_CONTENT_PAGES: tuple[tuple[str, re.Pattern[str]], ...] = (
("video", re.compile(r"^/video/(\d+)$")),
("ssul", re.compile(r"^/ssul/(\d+)$")),
("p2v_f1", re.compile(r"^/p2v/f1/(\d+)$")),
("p2v_playreel", re.compile(r"^/p2v/playreel/(\d+)$")),
)
#: (콘텐츠 종류, 공유 HTML 경로 — /api 접두사는 있어도 없어도 된다)
_SHARE_PAGES: tuple[tuple[str, re.Pattern[str]], ...] = (
("video", re.compile(r"^(?:/api)?/video/share/(\d+)$")),
("ssul", re.compile(r"^(?:/api)?/ssul/share/(\d+)$")),
("p2v_f1", re.compile(r"^(?:/api)?/p2v/f1/share/(\d+)$")),
("p2v_playreel", re.compile(r"^(?:/api)?/p2v/playreel/share/(\d+)$")),
)
_STATIC_HTML = frozenset({"/faq.html", "/privacy.html", "/terms.html"})
_ROOT_FILES = {"/robots.txt": "robots", "/sitemap.xml": "sitemap", "/llms.txt": "llms"}
#: 통계에서 아예 빼는 경로 — OAuth 콜백 화면, 관리자
#: `/admin.php` · `/administrator` 같은 스캐너 요청까지 버리지 않도록 `/admin` 은 정확히 또는 `/admin/` 아래만 뺀다
_EXCLUDED_PREFIXES = ("/social/", "/admin/")
#: 접근 로그에서 버리는 정적 자원. 확장자 전체를 버리지 않는 이유: /.env · /wp-login.php 같은 스캐너 요청은 남겨야 한다
_ASSET_EXT = re.compile(
r"\.(?:js|mjs|css|map|png|jpe?g|gif|svg|webp|avif|ico|bmp|woff2?|ttf|otf|eot|mp4|webm|mp3|wav|m4a)$",
re.IGNORECASE,
)
@dataclass(frozen=True)
class PageInfo:
"""비콘 한 건의 페이지 종류."""
#: landing · video · ssul · p2v_f1 · p2v_playreel · static · other
page_kind: str
content_type: str | None
content_id: int | None
@dataclass(frozen=True)
class RequestInfo:
"""접근 로그 한 줄의 요청 종류."""
#: page · share · static_html · robots · sitemap · llms · other
kind: str
path: str
content_type: str | None
content_id: int | None
def normalize_path(raw: str) -> str:
"""쿼리·해시를 떼고, 끝 `/` 를 떼고(루트 제외), 512자로 자른다.
urlsplit 을 쓰지 않는다: 스캐너가 보내는 `//evil/x` 같은 값을 호스트로 읽어 경로를 잃는다.
"""
path = (raw or "").split("?", 1)[0].split("#", 1)[0] or "/"
if len(path) > 1:
path = path.rstrip("/") or "/"
return path[:_MAX_PATH]
def _is_excluded(path: str) -> bool:
return path == "/admin" or any(path.startswith(p) for p in _EXCLUDED_PREFIXES)
def _match_content(path: str, table: tuple[tuple[str, re.Pattern[str]], ...]) -> tuple[str, int] | None:
for content_type, pattern in table:
m = pattern.match(path)
if m:
return content_type, int(m.group(1))
return None
def page_of(path: str) -> PageInfo | None:
"""비콘 경로 → 페이지 종류. 통계에서 빼는 경로면 None."""
if _is_excluded(path):
return None
if path == "/":
return PageInfo("landing", None, None)
content = _match_content(path, _CONTENT_PAGES)
if content:
return PageInfo(content[0], content[0], content[1])
if path in _STATIC_HTML:
return PageInfo("static", None, None)
return PageInfo("other", None, None)
def request_of(uri: str) -> RequestInfo | None:
"""접근 로그의 `$request_uri` → 요청 종류. 정적 자원·API·관리자 요청이면 None."""
if not uri.startswith("/") or uri.startswith("//"):
# 프록시 시도(`http://evil.com/`)·`*`·깨진 요청 줄 — 스캐너로 남긴다
return RequestInfo("other", (uri or "-")[:_MAX_PATH], None, None)
path = normalize_path(uri)
share = _match_content(path, _SHARE_PAGES)
if share:
return RequestInfo("share", path, share[0], share[1])
if path.startswith("/api/") or path == "/api" or _is_excluded(path):
return None
if path in _ROOT_FILES:
return RequestInfo(_ROOT_FILES[path], path, None, None)
if path.startswith("/assets/") or _ASSET_EXT.search(path):
return None
page = page_of(path)
if page is None:
return None
if page.page_kind == "static":
return RequestInfo("static_html", path, None, None)
if page.page_kind == "other":
return RequestInfo("other", path, None, None)
return RequestInfo("page", path, page.content_type, page.content_id)
+47
View File
@@ -0,0 +1,47 @@
"""사람 방문 판별 — 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()