#!/usr/bin/env python3 """vip.hackrobot.cn track sidecar — SQLite + ntfy, isolated from VIP business.""" from __future__ import annotations import json import os import sqlite3 import threading import time import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path PORT = int(os.environ.get("VIP_TRACK_PORT", "4011")) BASE_DIR = Path(os.environ.get("VIP_TRACK_DIR", "/opt/vip-track")) DB_PATH = Path(os.environ.get("VIP_TRACK_DB", str(BASE_DIR / "events.db"))) ENV_FILE = BASE_DIR / "ntfy.env" def _load_env_file() -> None: if not ENV_FILE.exists(): return try: for line in ENV_FILE.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue k, v = line.split("=", 1) k, v = k.strip(), v.strip().strip('"').strip("'") if k and k not in os.environ: os.environ[k] = v except Exception: pass _load_env_file() NTFY_BASE = os.environ.get("NTFY_BASE_URL", "https://ntfy.nomadro.cn").rstrip("/") NTFY_TOPIC = (os.environ.get("NTFY_TOPIC") or "vip-hackrobot").strip().strip("/") NTFY_TOKEN = (os.environ.get("NTFY_TOKEN") or "").strip() # health_down/up 只由 cron healthcheck.sh 推一次,避免 sidecar 再推「用户 ·」重复刷屏 NTFY_EVENTS = { "session_start", "page_view", "btn_click", "pay_start", "pay_success", "pay_cancel", "pay_fail", "pay_pending", "login_ok", "login_fail", "login_submit", "error", "web_vital_slow", } # 访问类:会话内去重,避免同人刷屏 VISIT_EVENTS = {"session_start", "page_view"} TITLE = { "session_start": "用户访问", "page_view": "浏览页面", "btn_click": "点击", "pay_start": "拉起支付", "pay_success": "支付成功", "pay_cancel": "取消支付", "pay_fail": "支付失败", "pay_pending": "支付确认中", "login_ok": "登录成功", "login_fail": "登录失败", "login_submit": "提交登录", "error": "前端异常", "health_down": "站点异常", "health_up": "站点恢复", "web_vital_slow": "性能偏慢", } TAGS = { "session_start": "eyes,globe_with_meridians", "page_view": "eyes,globe_with_meridians", "btn_click": "point_right,globe_with_meridians", "pay_start": "credit_card,globe_with_meridians", "pay_success": "moneybag,tada,globe_with_meridians", "pay_cancel": "wave,globe_with_meridians", "pay_fail": "warning,x,globe_with_meridians", "pay_pending": "hourglass,globe_with_meridians", "login_ok": "key,globe_with_meridians", "login_fail": "key,warning,globe_with_meridians", "login_submit": "key,globe_with_meridians", "error": "rotating_light,globe_with_meridians", "health_down": "rotating_light,skull", "health_up": "white_check_mark,tada", "web_vital_slow": "snail,chart_with_downwards_trend", } PRIORITY = { "pay_success": "5", "pay_fail": "5", "health_down": "5", "pay_start": "4", "login_fail": "4", "error": "4", "session_start": "3", "page_view": "2", "btn_click": "2", "health_up": "3", "web_vital_slow": "3", } _times: list[float] = [] _visit_times: list[float] = [] _seen_visit: dict[str, float] = {} MAX_PER_MIN = 40 MAX_VISIT_PER_MIN = 20 VISIT_DEDUP_SEC = 600 # 同 session+事件+页 10 分钟内只推一次 _db_lock = threading.Lock() _stats = {"received": 0, "stored": 0, "notified": 0, "ntfy_fail": 0, "started": time.time(), "last_ntfy_err": ""} def budget_ok(visit: bool = False) -> bool: now = time.time() while _times and _times[0] < now - 60: _times.pop(0) if len(_times) >= MAX_PER_MIN: return False if visit: while _visit_times and _visit_times[0] < now - 60: _visit_times.pop(0) if len(_visit_times) >= MAX_VISIT_PER_MIN: return False _visit_times.append(now) _times.append(now) return True def visit_dedup_ok(key: str) -> bool: now = time.time() # prune dead = [k for k, t in _seen_visit.items() if now - t > VISIT_DEDUP_SEC] for k in dead: _seen_visit.pop(k, None) if key in _seen_visit: return False _seen_visit[key] = now return True def short_uid(u: str) -> str: u = (u or "").strip() if not u: return "-" return ("…" + u[-8:]) if len(u) > 10 else u def role_of(props: dict, identity: dict | None = None) -> tuple[str, str]: """Return (role_key, role_cn). Prefer props from browser localStorage paidType.""" identity = identity or {} role = str(props.get("role") or identity.get("role") or "").strip().lower() paid = str(props.get("paid_type") or identity.get("paid_type") or "").strip().lower() role_cn = str(props.get("role_cn") or identity.get("role_cn") or "").strip() if role == "vip" or paid == "vip": return "vip", role_cn or "会员VIP" return "guest", role_cn or "普通访客" def fmt_secs(ms) -> str: try: v = int(ms or 0) except Exception: v = 0 if v <= 0: return "-" s = v // 1000 if s < 60: return "%ds" % s return "%dm%ds" % (s // 60, s % 60) def _md_esc(v: object, limit: int = 160) -> str: s = str(v if v is not None else "-").replace("|", "\\|").replace("\n", " ").strip() return s[:limit] or "-" def build_rich_message( *, ntfy_name: str, openid: str, session: str, page: str, label: str, props: dict, ip: str, identity: dict | None, ) -> tuple[str, str, str, str, str]: """title, markdown message, tags, priority, click_url — 详情尽量完整。""" role, role_cn = role_of(props, identity) crown = "👑会员" if role == "vip" else "👤访客" action = TITLE.get(ntfy_name, ntfy_name) who = "VIP" if role == "vip" else "访客" title = "[WebVIP] / [%s] %s" % (who, action) email = str(props.get("email") or (identity or {}).get("email") or "").strip() name = str(props.get("name") or (identity or {}).get("name") or "").strip() user_id = str(props.get("user_id") or (identity or {}).get("user_id") or openid or "").strip() device = str(props.get("device") or "-") browser = str(props.get("browser") or "-") screen = str(props.get("screen") or "-") lang = str(props.get("lang") or "-") tz = str(props.get("tz") or "-") href = str(props.get("href") or "").strip() ref = str(props.get("ref") or "").strip() doc_title = str(props.get("title") or "").strip() click_text = str(props.get("text") or label or "").strip() el = str(props.get("el") or "").strip() ua = str(props.get("ua") or "").strip() alive = fmt_secs(props.get("alive_ms")) paid = props.get("paid_type") or (identity or {}).get("paid_type") or "guest" lines = [ "### %s · %s" % (crown, _md_esc(action, 80)), "", "- **站点** `vip.hackrobot.cn`", "- **身份** `%s` · paidType=`%s`" % (_md_esc(role_cn, 40), _md_esc(paid, 40)), "- **用户ID** `%s`" % _md_esc(user_id or "-"), "- **昵称** `%s`" % _md_esc(name or "-"), "- **邮箱** `%s`" % _md_esc(email or "-"), "- **页面** `%s`" % _md_esc(page or "/"), "- **标题** %s" % _md_esc(doc_title or "-"), "- **动作** %s" % _md_esc(label or "-"), "- **时间** `%s`" % time.strftime("%Y-%m-%d %H:%M:%S"), "", "| 字段 | 值 |", "| --- | --- |", "| 设备 | `%s / %s / %s` |" % (_md_esc(device, 40), _md_esc(browser, 40), _md_esc(screen, 40)), "| 语言/时区 | `%s` / `%s` |" % (_md_esc(lang, 40), _md_esc(tz, 40)), "| IP | `%s` |" % _md_esc(ip or "-", 64), "| 会话 | `%s` |" % _md_esc(session or "-", 48), "| 停留 | `%s` |" % _md_esc(alive, 24), ] if click_text and ntfy_name in ("btn_click", "pay_start", "login_submit"): lines.append("| 点击文案 | %s |" % _md_esc(click_text, 120)) if el: lines.append("| 元素 | `<%s>` |" % _md_esc(el, 40)) if href: lines.append("| URL | %s |" % _md_esc(href, 160)) lines.append("") lines.append("[打开来源页](%s)" % href[:400]) if ref: lines.append("| 来源 | %s |" % _md_esc(ref, 140)) if props.get("ms"): lines.append("| 性能 | `%sms` |" % _md_esc(props.get("ms"), 24)) if ua: lines.append("| UA | `%s` |" % _md_esc(ua, 140)) tags = TAGS.get(ntfy_name, "bar_chart,globe_with_meridians") if role == "vip": tags = "crown," + tags else: tags = "bust_in_silhouette," + tags pri = PRIORITY.get(ntfy_name, "3") if role == "vip" and ntfy_name in ("pay_start", "pay_success", "session_start"): try: pri = str(max(int(pri), 4)) except Exception: pass click = href if href.startswith("http") else "https://vip.hackrobot.cn/" return title, "\n".join(lines), tags, pri, click def init_db() -> None: BASE_DIR.mkdir(parents=True, exist_ok=True) with _db_lock: con = sqlite3.connect(str(DB_PATH)) try: con.execute( """ CREATE TABLE IF NOT EXISTS events ( id INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL NOT NULL, name TEXT NOT NULL, page TEXT, label TEXT, openid TEXT, session TEXT, client TEXT, props TEXT, ip TEXT, notified INTEGER DEFAULT 0 ) """ ) con.execute("CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts)") con.execute("CREATE INDEX IF NOT EXISTS idx_events_name ON events(name)") con.commit() finally: con.close() def store_event( *, name: str, page: str, label: str, openid: str, session: str, client: str, props: dict, ip: str, notified: int, ) -> None: with _db_lock: con = sqlite3.connect(str(DB_PATH), timeout=2) try: con.execute( "INSERT INTO events(ts,name,page,label,openid,session,client,props,ip,notified) VALUES(?,?,?,?,?,?,?,?,?,?)", ( time.time(), name, page, label, openid, session, client, json.dumps(props, ensure_ascii=False)[:2000], ip, notified, ), ) con.commit() _stats["stored"] += 1 except Exception: pass finally: con.close() def stats_summary() -> dict: out = dict(_stats) out["uptime_s"] = int(time.time() - _stats["started"]) out["ntfy_base"] = NTFY_BASE out["ntfy_topic"] = NTFY_TOPIC out["ntfy_token_set"] = bool(NTFY_TOKEN) with _db_lock: con = sqlite3.connect(str(DB_PATH), timeout=2) try: row = con.execute("SELECT COUNT(*) FROM events").fetchone() out["events_total"] = int(row[0] if row else 0) recent = con.execute( "SELECT name, COUNT(*) FROM events WHERE ts > ? GROUP BY name ORDER BY COUNT(*) DESC LIMIT 12", (time.time() - 86400,), ).fetchall() out["last_24h"] = {k: v for k, v in recent} except Exception as e: out["db_error"] = str(e)[:120] finally: con.close() return out def publish( title: str, message: str, tags: str, priority: str, click: str = "", ) -> bool: if not NTFY_BASE or not NTFY_TOPIC: return False url = "%s/" % NTFY_BASE.rstrip("/") try: pri = max(1, min(5, int(priority or 3))) except Exception: pri = 3 click_url = (click or "").strip()[:512] payload = { "topic": NTFY_TOPIC.strip().strip("/"), "title": (title or "WebVIP")[:200], "message": (message or "")[:3900], "priority": pri, "markdown": True, "tags": [t.strip() for t in (tags or "").split(",") if t.strip()][:12], "icon": "https://nomadro.com/icon-192.png", } if click_url: payload["click"] = click_url payload["actions"] = [ {"action": "view", "label": "打开页面", "url": click_url, "clear": True}, { "action": "view", "label": "VIP 首页", "url": "https://vip.hackrobot.cn/", "clear": True, }, ] body = json.dumps(payload, ensure_ascii=False).encode("utf-8") headers = {"Content-Type": "application/json"} if NTFY_TOKEN: headers["Authorization"] = "Bearer " + NTFY_TOKEN req = urllib.request.Request(url, data=body, headers=headers, method="POST") try: with urllib.request.urlopen(req, timeout=6) as resp: resp.read(64) return True except Exception as e: _stats["ntfy_fail"] += 1 _stats["last_ntfy_err"] = ("%s: %s" % (type(e).__name__, e))[:200] return False def maybe_ntfy_name(name: str, props: dict) -> str | None: if name in NTFY_EVENTS: return name # promote slow vitals if name == "web_vital" and (props.get("slow") in (1, "1", True) or int(props.get("ms") or 0) > 4000): return "web_vital_slow" return None class H(BaseHTTPRequestHandler): def log_message(self, fmt, *args): return def _cors(self): self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS") self.send_header("Access-Control-Allow-Headers", "Content-Type") def _json(self, code: int, obj: dict): data = json.dumps(obj, ensure_ascii=False).encode("utf-8") self.send_response(code) self._cors() self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def do_OPTIONS(self): self.send_response(204) self._cors() self.end_headers() def do_GET(self): path = (self.path or "/").split("?", 1)[0] if path in ("/stats", "/api/track/stats"): # localhost-ish only ip = self.client_address[0] if self.client_address else "" if ip not in ("127.0.0.1", "::1"): self._json(403, {"ok": False, "error": "local only"}) return self._json(200, {"ok": True, "stats": stats_summary()}) return if path in ("/health", "/api/track/health"): self._json(200, {"ok": True, "service": "vip-track", "uptime_s": int(time.time() - _stats["started"])}) return self._json(200, {"ok": True, "service": "vip-track"}) def do_POST(self): try: n = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(max(0, min(n, 65536))) if n else b"{}" body = json.loads(raw.decode("utf-8", "replace") or "{}") except Exception: body = {} events = body.get("events") if isinstance(body, dict) else None if not isinstance(events, list): events = [] openid = str((body or {}).get("openid") or "")[:64] if isinstance(body, dict) else "" session = str((body or {}).get("session") or "")[:64] if isinstance(body, dict) else "" client = str((body or {}).get("client") or "vip_web")[:32] if isinstance(body, dict) else "vip_web" identity = (body or {}).get("identity") if isinstance(body, dict) else None if not isinstance(identity, dict): identity = {} ip = self.headers.get("X-Real-IP") or self.headers.get("X-Forwarded-For") or ( self.client_address[0] if self.client_address else "" ) ip = str(ip).split(",")[0].strip()[:64] ua_hdr = (self.headers.get("User-Agent") or "")[:140] notified = 0 stored = 0 for raw_ev in events[:20]: if not isinstance(raw_ev, dict): continue name = str(raw_ev.get("name") or "").strip()[:64] if not name: continue _stats["received"] += 1 page = str(raw_ev.get("page") or "")[:64] label = str(raw_ev.get("label") or "")[:160] props = raw_ev.get("props") if isinstance(raw_ev.get("props"), dict) else {} # merge identity defaults into props for storage/ntfy for k in ("role", "role_cn", "paid_type", "email", "name", "user_id"): if not props.get(k) and identity.get(k): props[k] = identity.get(k) if not props.get("ua") and ua_hdr: props["ua"] = ua_hdr ntfy_name = maybe_ntfy_name(name, props) did_notify = 0 if client in ("healthcheck", "probe", "deploy"): ntfy_name = None is_visit = ntfy_name in VISIT_EVENTS if ntfy_name else False if ntfy_name and is_visit: dedup_key = "%s|%s|%s|%s" % (ntfy_name, session or openid or ip, page, label[:40]) if not visit_dedup_ok(dedup_key): ntfy_name = None # 同类点击短去重(30s),保留详情但不刷屏 if ntfy_name == "btn_click": ck = "btn|%s|%s|%s" % (session or openid or ip, page, label[:60]) now = time.time() last = _seen_visit.get(ck) if last and now - last < 30: ntfy_name = None else: _seen_visit[ck] = now if ntfy_name and budget_ok(visit=is_visit): title, message, tags, pri, click = build_rich_message( ntfy_name=ntfy_name, openid=openid, session=session, page=page, label=label, props=props, ip=ip, identity=identity, ) ok = publish(title, message, tags, pri, click=click) if ok: notified += 1 did_notify = 1 _stats["notified"] += 1 # persist role into props for analytics store_props = dict(props) store_props["_role"] = role_of(props, identity)[0] store_event( name=name, page=page, label=label, openid=openid, session=session, client=client, props=store_props, ip=ip, notified=did_notify, ) stored += 1 self._json(200, {"ok": True, "notified": notified, "stored": stored}) if __name__ == "__main__": init_db() ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()