#!/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.parse 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("/") # 可多主题:vip-hackrobot + hackrobot-oa(手机常只订了 OA 主题) _NTFY_TOPICS_RAW = (os.environ.get("NTFY_TOPICS") or NTFY_TOPIC or "").strip() NTFY_TOPICS = [] for _t in _NTFY_TOPICS_RAW.split(","): _t = _t.strip().strip("/") if _t and _t not in NTFY_TOPICS: NTFY_TOPICS.append(_t) if not NTFY_TOPICS and NTFY_TOPIC: NTFY_TOPICS = [NTFY_TOPIC] NTFY_TOKEN = (os.environ.get("NTFY_TOKEN") or "").strip() NTFY_USER = (os.environ.get("NTFY_USER") or "").strip() NTFY_PASS = (os.environ.get("NTFY_PASS") or "").strip() PB_URL = (os.environ.get("POCKETBASE_URL") or "http://127.0.0.1:8090").rstrip("/") PB_EMAIL = (os.environ.get("POCKETBASE_EMAIL") or "").strip() PB_PASSWORD = (os.environ.get("POCKETBASE_PASSWORD") or "").strip() OPS_CONTROL_URL = os.environ.get("OPS_CONTROL_URL", "http://127.0.0.1:4007/api/ops/control") _pb_token: dict[str, object] = {"token": "", "exp": 0.0} _profile_cache: dict[str, tuple[float, dict]] = {} _profile_lock = threading.Lock() # 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", } # 访问类:同会话只推 1 条(session_start 优先;page_view 仅在没有 session_start 时补推) VISIT_EVENTS = {"session_start", "page_view"} VISIT_PRIMARY = "session_start" 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 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, message, tags, priority, avatar — 详情尽量完整(含微信头像昵称)。""" role, role_cn = role_of(props, identity) crown = "👑会员" if role == "vip" else "👤访客" action = TITLE.get(ntfy_name, ntfy_name) 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() wechat_userid = str( props.get("wechat_userid") or (identity or {}).get("wechat_userid") or props.get("userid") or "" ).strip() wechat_nick = str( props.get("wechat_nick") or (identity or {}).get("wechat_nick") or "" ).strip() avatar = str( props.get("wechat_avatar") or props.get("avatar") or (identity or {}).get("wechat_avatar") or (identity or {}).get("avatar") or "" ).strip() nick = wechat_nick or name or "-" signature = str(props.get("signature") or (identity or {}).get("signature") or "").strip() gender_txt = str(props.get("gender_txt") or (identity or {}).get("gender_txt") or "").strip() region = str(props.get("region") or (identity or {}).get("region") or "").strip() follow_since = str(props.get("follow_since") or (identity or {}).get("follow_since") or "").strip() like_cnt = props.get("like_cnt") if props.get("like_cnt") is not None else (identity or {}).get("like_cnt") look_cnt = props.get("look_cnt") if props.get("look_cnt") is not None else (identity or {}).get("look_cnt") comment_cnt = ( props.get("comment_cnt") if props.get("comment_cnt") is not None else (identity or {}).get("comment_cnt") ) reward_amt = str(props.get("reward_amt") or (identity or {}).get("reward_amt") or "").strip() # 标题放昵称:通知栏预览优先看到是谁 title = "[WebVIP] %s · %s" % ((nick if nick != "-" else ("VIP" if role == "vip" else "访客")), action) 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() click_href = str(props.get("href") or "").strip() if ntfy_name == "btn_click" else "" el = str(props.get("el") or "").strip() ua = str(props.get("ua") or "").strip() alive = fmt_secs(props.get("alive_ms")) # 前三行专供通知栏预览(尽量短、信息密度高) head_bits = [nick] if gender_txt: head_bits.append(gender_txt) if region: head_bits.append(region) if signature: head_bits.append(signature[:40]) preview = " · ".join([b for b in head_bits if b]) stats = "赞%s / 在看%s / 留言%s" % ( like_cnt if like_cnt is not None else "-", look_cnt if look_cnt is not None else "-", comment_cnt if comment_cnt is not None else "-", ) if reward_amt: stats += " · 赞赏%s" % reward_amt lines = [ preview or ("%s · %s" % (crown, action)), "微信 %s" % (wechat_userid or openid or "-"), "%s%s" % (stats, (" · " + follow_since) if follow_since else ""), "%s · %s · paidType=%s" % (crown, role_cn, props.get("paid_type") or (identity or {}).get("paid_type") or "guest"), "邮箱 %s" % (email or "-"), "账号ID %s" % (user_id or "-"), "页面 %s · %s" % (page or "/", doc_title or label or "-"), ] if click_text and ntfy_name in ("btn_click", "pay_start", "login_submit"): lines.append("点击文案 %s" % click_text[:160]) if el: lines.append("元素 <%s>" % el) if click_href and ntfy_name == "btn_click": lines.append("链接 %s" % click_href[:160]) if href: lines.append("URL %s" % href[:180]) if ref: lines.append("来源 %s" % ref[:160]) lines.extend( [ "设备 %s / %s / %s" % (device, browser, screen), "语言 %s · 时区 %s" % (lang, tz), "IP %s" % (ip or "-"), "会话 %s" % (session or "-"), "停留 %s" % alive, ] ) if props.get("ms"): lines.append("性能 %sms(%s)" % (props.get("ms"), label or ntfy_name)) if ua: lines.append("UA %s" % ua[:160]) lines.append("时间 %s" % time.strftime("%Y-%m-%d %H:%M:%S")) 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"): # VIP 关键动作略抬优先级 try: pri = str(max(int(pri), 4)) except Exception: pass return title, "\n".join(lines), tags, pri, avatar 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_topics"] = list(NTFY_TOPICS) out["ntfy_token_set"] = bool(NTFY_TOKEN or (NTFY_USER and NTFY_PASS)) 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 _hdr_utf8(s: str) -> str: """Pass UTF-8 Title through urllib (latin-1 wire roundtrip).""" return s[:80].encode("utf-8", "ignore").decode("latin-1") def _pb_admin_token() -> str: now = time.time() tok = str(_pb_token.get("token") or "") exp = float(_pb_token.get("exp") or 0) if tok and exp > now + 30: return tok if not PB_EMAIL or not PB_PASSWORD: return "" body = json.dumps({"identity": PB_EMAIL, "password": PB_PASSWORD}).encode("utf-8") for path in ( "/api/collections/_superusers/auth-with-password", "/api/admins/auth-with-password", ): try: req = urllib.request.Request( PB_URL + path, data=body, headers={"Content-Type": "application/json"}, method="POST", ) with urllib.request.urlopen(req, timeout=6) as resp: data = json.loads(resp.read().decode("utf-8", "replace") or "{}") token = str(data.get("token") or "") if token: _pb_token["token"] = token _pb_token["exp"] = now + 10 * 60 return token except Exception: continue return "" def lookup_wechat_profile(userid: str) -> dict: """从 PB wechat_private_users 补昵称/头像(有缓存)。""" uid = (userid or "").strip() if not uid: return {} now = time.time() with _profile_lock: hit = _profile_cache.get(uid) if hit and now - hit[0] < 300: return dict(hit[1]) token = _pb_admin_token() if not token: return {} # filter userid= filt = 'userid="%s"' % uid.replace("\\", "\\\\").replace('"', '\\"') url = ( "%s/api/collections/wechat_private_users/records?page=1&perPage=1&filter=%s" % (PB_URL, urllib.parse.quote(filt)) ) try: req = urllib.request.Request(url, headers={"Authorization": "Bearer " + token}) with urllib.request.urlopen(req, timeout=6) as resp: data = json.loads(resp.read().decode("utf-8", "replace") or "{}") items = data.get("items") if isinstance(data, dict) else None if not items: with _profile_lock: _profile_cache[uid] = (now, {}) return {} it = items[0] if isinstance(items[0], dict) else {} rc = _as_dict(it.get("raw_contact")) nick = str(it.get("nick") or rc.get("nick") or "").strip() avatar = str(it.get("avatar") or rc.get("headImg") or rc.get("avatar") or "").strip() if avatar.startswith("http://"): avatar = "https://" + avatar[len("http://") :] out = { "wechat_userid": str(it.get("userid") or uid).strip(), "wechat_nick": nick, "wechat_avatar": avatar, "avatar": avatar, "name": nick, "signature": str(rc.get("signature") or "").strip(), "gender_txt": str(rc.get("gender_txt") or "").strip(), "region": str(rc.get("region") or "").strip(), "follow_since": str(rc.get("follow_since") or "").strip(), "like_cnt": rc.get("like_cnt"), "look_cnt": rc.get("look_cnt"), "comment_cnt": rc.get("comment_cnt"), "reward_amt": str(rc.get("reward_amt") or "").strip(), } # 补 oa_fans 详情(签名/互动) try: fans = _oa_fans_by_openids(token, [uid]).get(uid) or {} if fans: if fans.get("nickname") and not out["wechat_nick"]: out["wechat_nick"] = str(fans.get("nickname") or "").strip() out["name"] = out["wechat_nick"] if fans.get("avatar") and not out["wechat_avatar"]: av = str(fans.get("avatar") or "").strip() if av.startswith("http://"): av = "https://" + av[len("http://") :] out["wechat_avatar"] = av out["avatar"] = av for k in ("signature", "gender_txt", "region", "follow_since", "reward_amt"): if fans.get(k) and not out.get(k): out[k] = str(fans.get(k) or "").strip() for k in ("like_cnt", "look_cnt", "comment_cnt", "reward_cnt", "pay_cnt"): if fans.get(k) is not None and out.get(k) in (None, "", 0): out[k] = fans.get(k) except Exception: pass with _profile_lock: _profile_cache[uid] = (now, out) return dict(out) except Exception: return {} def enrich_identity(props: dict, identity: dict, openid: str) -> tuple[dict, dict, str]: """用 URL/埋点里的 wechat_userid 回填 PB 画像。""" props = dict(props or {}) identity = dict(identity or {}) uid = str( props.get("wechat_userid") or identity.get("wechat_userid") or props.get("userid") or openid or "" ).strip() # 忽略网站匿名 user1795…,那不是微信 openid if uid.startswith("user") and uid[4:].isdigit(): uid = str(props.get("wechat_userid") or identity.get("wechat_userid") or "").strip() if not uid or not uid.startswith("o"): # 仍尝试非 o 开头的真实 userid(少数渠道) if not uid or len(uid) < 8: return props, identity, openid prof = lookup_wechat_profile(uid) if not prof: if uid and not props.get("wechat_userid"): props["wechat_userid"] = uid identity["wechat_userid"] = uid return props, identity, openid or uid for k, v in prof.items(): if v and not props.get(k): props[k] = v if v and not identity.get(k): identity[k] = v if not openid or openid.startswith("user"): openid = uid return props, identity, openid def ops_token_ok(headers) -> bool: auth = (headers.get("Authorization") or "").strip() tok = "" if auth.lower().startswith("bearer "): tok = auth[7:].strip() if not tok: tok = (headers.get("X-Ops-Token") or "").strip() if not tok: return False try: req = urllib.request.Request( OPS_CONTROL_URL, headers={"Authorization": "Bearer " + tok, "Accept": "application/json"}, ) with urllib.request.urlopen(req, timeout=6) as resp: return 200 <= int(resp.status) < 300 except Exception: return False def _as_dict(v) -> dict: if isinstance(v, dict): return v if isinstance(v, str) and v.strip().startswith("{"): try: o = json.loads(v) return o if isinstance(o, dict) else {} except Exception: return {} return {} def _oa_fans_by_openids(token: str, openids: list[str]) -> dict[str, dict]: """批量拉 oa_fans 档案,按 openid 索引。""" out: dict[str, dict] = {} oids = [str(x).strip() for x in openids if str(x).strip()] if not token or not oids: return out # PB filter 过长会 400,分批 for i in range(0, len(oids), 40): chunk = oids[i : i + 40] parts = ['openid="%s"' % x.replace("\\", "\\\\").replace('"', '\\"') for x in chunk] filt = " || ".join(parts) url = ( "%s/api/collections/oa_fans/records?page=1&perPage=%d&filter=%s" % (PB_URL, len(chunk), urllib.parse.quote(filt)) ) try: req = urllib.request.Request(url, headers={"Authorization": "Bearer " + token}) with urllib.request.urlopen(req, timeout=12) as resp: data = json.loads(resp.read().decode("utf-8", "replace") or "{}") for it in data.get("items") or []: if not isinstance(it, dict): continue oid = str(it.get("openid") or "").strip() if oid: out[oid] = it except Exception: continue return out def _pick_num(*vals): for v in vals: if v is None or v == "": continue try: return int(v) except Exception: try: return int(float(v)) except Exception: continue return 0 def _https_avatar(url: str) -> str: av = (url or "").strip() if av.startswith("http://"): return "https://" + av[len("http://") :] return av def _merge_user_row(it: dict, fan: dict | None = None) -> dict: fan = fan or {} uid = str(it.get("userid") or "").strip() rc = _as_dict(it.get("raw_contact")) raw = _as_dict(fan.get("raw")) nick = str(it.get("nick") or rc.get("nick") or fan.get("nickname") or "").strip() avatar = _https_avatar( str(it.get("avatar") or rc.get("headImg") or rc.get("avatar") or fan.get("avatar") or "") ) signature = str(fan.get("signature") or raw.get("signature") or rc.get("signature") or "").strip() gender_txt = str(fan.get("gender_txt") or raw.get("gender_txt") or rc.get("gender_txt") or "").strip() region = str( fan.get("region") or rc.get("region") or " ".join( [ str(fan.get("country") or rc.get("country") or "").strip(), str(fan.get("province") or rc.get("province") or "").strip(), str(fan.get("city") or rc.get("city") or "").strip(), ] ).strip() ).strip() follow_since = str( fan.get("follow_since") or rc.get("follow_since") or raw.get("follow_since") or "" ).strip() return { "id": it.get("id"), "userid": uid, "nick": nick, "avatar": avatar, "signature": signature, "gender": _pick_num(fan.get("gender"), rc.get("gender"), raw.get("gender")), "gender_txt": gender_txt, "region": region, "country": str(fan.get("country") or rc.get("country") or "").strip(), "province": str(fan.get("province") or rc.get("province") or "").strip(), "city": str(fan.get("city") or rc.get("city") or "").strip(), "follow_since": follow_since, "follow_time": _pick_num(fan.get("follow_time"), rc.get("follow_time"), raw.get("follow_time")), "like_cnt": _pick_num(fan.get("like_cnt"), rc.get("like_cnt"), raw.get("like_cnt")), "look_cnt": _pick_num(fan.get("look_cnt"), rc.get("look_cnt"), raw.get("look_cnt")), "comment_cnt": _pick_num(fan.get("comment_cnt"), rc.get("comment_cnt"), raw.get("comment_cnt")), "reward_cnt": _pick_num(fan.get("reward_cnt"), rc.get("reward_cnt"), raw.get("reward_cnt")), "reward_amt": str(fan.get("reward_amt") or rc.get("reward_amt") or "").strip(), "pay_cnt": _pick_num(fan.get("pay_cnt"), rc.get("pay_cnt"), raw.get("pay_cnt")), "scene": str(fan.get("scene") or rc.get("scene") or "").strip(), "last_action": str(fan.get("last_action") or "").strip(), "remark": str(fan.get("remark") or rc.get("remark") or "").strip(), "identity_openid": str(fan.get("identity_openid") or rc.get("identity_openid") or "").strip(), "h5": str(rc.get("h5") or ("https://vip.hackrobot.cn/?userid=" + uid if uid else "")).strip(), "channel_id": it.get("channel_id") or rc.get("channelId") or "", "source_query": it.get("source_query") or "", "matched_last_msg": it.get("matched_last_msg") or "", "matched_last_msg_time": it.get("matched_last_msg_time") or "", "updated": it.get("updated") or "", "created": it.get("created") or "", "has_oa_fans": bool(fan), "raw_contact": rc, } def list_wechat_users(limit: int = 200, q: str = "", page: int = 1) -> dict: token = _pb_admin_token() if not token: return {"ok": False, "error": "pocketbase_unconfigured", "users": []} limit = max(1, min(int(limit or 200), 500)) page = max(1, int(page or 1)) q = (q or "").strip() if q: qq = q.replace("\\", "\\\\").replace('"', '\\"') filt = 'userid~"%s" || nick~"%s"' % (qq, qq) url = ( "%s/api/collections/wechat_private_users/records?page=%d&perPage=%d&sort=-updated&filter=%s" % (PB_URL, page, limit, urllib.parse.quote(filt)) ) else: url = ( "%s/api/collections/wechat_private_users/records?page=%d&perPage=%d&sort=-updated" % (PB_URL, page, limit) ) req = urllib.request.Request(url, headers={"Authorization": "Bearer " + token}) with urllib.request.urlopen(req, timeout=12) as resp: data = json.loads(resp.read().decode("utf-8", "replace") or "{}") items = data.get("items") if isinstance(data, dict) else [] openids = [str((it or {}).get("userid") or "").strip() for it in (items or []) if isinstance(it, dict)] fans_map = _oa_fans_by_openids(token, openids) users = [] for it in items or []: if not isinstance(it, dict): continue uid = str(it.get("userid") or "").strip() users.append(_merge_user_row(it, fans_map.get(uid))) total = int(data.get("totalItems") or len(users)) return { "ok": True, "total": total, "page": page, "perPage": limit, "totalPages": max(1, (total + limit - 1) // limit) if total else 1, "users": users, } def _pb_request(method: str, path: str, token: str, payload: dict | None = None) -> dict: body = None if payload is None else json.dumps(payload, ensure_ascii=False).encode("utf-8") req = urllib.request.Request( PB_URL + path, data=body, method=method, headers={ "Authorization": "Bearer " + token, "Content-Type": "application/json", }, ) try: with urllib.request.urlopen(req, timeout=12) as resp: raw = resp.read().decode("utf-8", "replace") or "{}" return json.loads(raw) if raw.strip() else {"ok": True} except urllib.error.HTTPError as e: detail = e.read().decode("utf-8", "replace")[:400] raise RuntimeError("%s %s" % (e.code, detail)) from e def get_wechat_user(record_id: str) -> dict: token = _pb_admin_token() if not token: return {"ok": False, "error": "pocketbase_unconfigured"} rid = (record_id or "").strip() if not rid: return {"ok": False, "error": "id required"} it = _pb_request("GET", "/api/collections/wechat_private_users/records/" + urllib.parse.quote(rid), token) uid = str(it.get("userid") or "").strip() fan = (_oa_fans_by_openids(token, [uid]).get(uid) if uid else None) or {} return {"ok": True, "user": _merge_user_row(it, fan)} def _build_vip_payload(body: dict, *, partial: bool = False) -> dict: body = body or {} userid = str(body.get("userid") or body.get("openid") or "").strip() if not partial and not userid: raise ValueError("userid required") def has(*keys: str) -> bool: return any(k in body for k in keys) payload: dict = {} if userid: payload["userid"] = userid if has("nick", "nickname") or not partial: payload["nick"] = str(body.get("nick") or body.get("nickname") or "").strip() if has("avatar") or not partial: payload["avatar"] = _https_avatar(str(body.get("avatar") or "").strip()) if has("channel_id") or not partial: payload["channel_id"] = str(body.get("channel_id") or "").strip() if has("source_query") or not partial: payload["source_query"] = str(body.get("source_query") or "admin:user-list").strip() if has("matched_last_msg") or not partial: payload["matched_last_msg"] = str(body.get("matched_last_msg") or "").strip() # raw_contact:partial 时只写提交的字段,避免空串覆盖原档案 rc_keys = ( "signature", "remark", "gender", "gender_txt", "country", "province", "city", "region", "follow_since", "follow_time", "like_cnt", "look_cnt", "comment_cnt", "reward_amt", "pay_cnt", "nick", "nickname", "avatar", "userid", "openid", ) if (not partial) or any(k in body for k in rc_keys): rc: dict = {"source": "admin_user_list"} if userid: rc["userId"] = userid rc["openid"] = userid rc["h5"] = "https://vip.hackrobot.cn/?userid=" + userid if has("nick", "nickname") or not partial: rc["nick"] = str(body.get("nick") or body.get("nickname") or "").strip() if has("avatar") or not partial: rc["headImg"] = _https_avatar(str(body.get("avatar") or "").strip()) for src, dst in ( ("signature", "signature"), ("remark", "remark"), ("gender", "gender"), ("gender_txt", "gender_txt"), ("country", "country"), ("province", "province"), ("city", "city"), ("region", "region"), ("follow_since", "follow_since"), ("follow_time", "follow_time"), ("like_cnt", "like_cnt"), ("look_cnt", "look_cnt"), ("comment_cnt", "comment_cnt"), ("reward_amt", "reward_amt"), ("pay_cnt", "pay_cnt"), ): if has(src) or not partial: val = body.get(src) if isinstance(val, str): val = val.strip() rc[dst] = val if val is not None else ("" if isinstance(body.get(src, ""), str) else None) if (not partial) and not rc.get("region"): rc["region"] = " ".join( [ str(rc.get("country") or "").strip(), str(rc.get("province") or "").strip(), str(rc.get("city") or "").strip(), ] ).strip() payload["raw_contact"] = rc return payload def create_wechat_user(body: dict) -> dict: token = _pb_admin_token() if not token: return {"ok": False, "error": "pocketbase_unconfigured"} try: payload = _build_vip_payload(body or {}, partial=False) except ValueError as e: return {"ok": False, "error": str(e)} userid = payload["userid"] # 已存在则改更新 filt = 'userid="%s"' % userid.replace("\\", "\\\\").replace('"', '\\"') url = ( "%s/api/collections/wechat_private_users/records?page=1&perPage=1&filter=%s" % (PB_URL, urllib.parse.quote(filt)) ) req = urllib.request.Request(url, headers={"Authorization": "Bearer " + token}) with urllib.request.urlopen(req, timeout=10) as resp: exist = json.loads(resp.read().decode("utf-8", "replace") or "{}") items = exist.get("items") or [] if items: rid = items[0].get("id") it = _pb_request( "PATCH", "/api/collections/wechat_private_users/records/" + urllib.parse.quote(str(rid)), token, payload, ) action = "updated" else: it = _pb_request("POST", "/api/collections/wechat_private_users/records", token, payload) action = "created" # 同步 oa_fans 基础字段(有则补) try: upsert_oa_fans_from_body(token, body, userid) except Exception: pass with _profile_lock: _profile_cache.pop(userid, None) fan = _oa_fans_by_openids(token, [userid]).get(userid) or {} return {"ok": True, "action": action, "user": _merge_user_row(it, fan)} def update_wechat_user(record_id: str, body: dict) -> dict: token = _pb_admin_token() if not token: return {"ok": False, "error": "pocketbase_unconfigured"} rid = (record_id or "").strip() if not rid: return {"ok": False, "error": "id required"} try: payload = _build_vip_payload(body or {}, partial=True) except ValueError as e: return {"ok": False, "error": str(e)} if not payload: return {"ok": False, "error": "empty patch"} # 保留原 raw_contact 合并 cur = _pb_request("GET", "/api/collections/wechat_private_users/records/" + urllib.parse.quote(rid), token) old_rc = _as_dict(cur.get("raw_contact")) if "raw_contact" in payload and old_rc: merged = dict(old_rc) merged.update(payload["raw_contact"] or {}) payload["raw_contact"] = merged it = _pb_request( "PATCH", "/api/collections/wechat_private_users/records/" + urllib.parse.quote(rid), token, payload, ) userid = str(it.get("userid") or body.get("userid") or "").strip() if userid: try: upsert_oa_fans_from_body(token, body, userid, partial=True) except Exception: pass with _profile_lock: _profile_cache.pop(userid, None) fan = (_oa_fans_by_openids(token, [userid]).get(userid) if userid else None) or {} return {"ok": True, "action": "updated", "user": _merge_user_row(it, fan)} def delete_wechat_user(record_id: str, *, also_oa_fans: bool = False) -> dict: token = _pb_admin_token() if not token: return {"ok": False, "error": "pocketbase_unconfigured"} rid = (record_id or "").strip() if not rid: return {"ok": False, "error": "id required"} cur = _pb_request("GET", "/api/collections/wechat_private_users/records/" + urllib.parse.quote(rid), token) userid = str(cur.get("userid") or "").strip() _pb_request("DELETE", "/api/collections/wechat_private_users/records/" + urllib.parse.quote(rid), token) deleted_oa = False if also_oa_fans and userid: fans = _oa_fans_by_openids(token, [userid]).get(userid) if fans and fans.get("id"): _pb_request( "DELETE", "/api/collections/oa_fans/records/" + urllib.parse.quote(str(fans.get("id"))), token, ) deleted_oa = True if userid: with _profile_lock: _profile_cache.pop(userid, None) return {"ok": True, "action": "deleted", "id": rid, "userid": userid, "oa_fans_deleted": deleted_oa} def refresh_wechat_user(record_id: str) -> dict: """用 oa_fans 档案回填 vip 用户头像/昵称/签名等。""" token = _pb_admin_token() if not token: return {"ok": False, "error": "pocketbase_unconfigured"} rid = (record_id or "").strip() if not rid: return {"ok": False, "error": "id required"} cur = _pb_request("GET", "/api/collections/wechat_private_users/records/" + urllib.parse.quote(rid), token) userid = str(cur.get("userid") or "").strip() if not userid: return {"ok": False, "error": "no userid"} fan = _oa_fans_by_openids(token, [userid]).get(userid) if not fan: return {"ok": False, "error": "oa_fans_not_found", "user": _merge_user_row(cur, {})} body = { "userid": userid, "nick": fan.get("nickname") or "", "avatar": fan.get("avatar") or "", "signature": fan.get("signature") or "", "remark": fan.get("remark") or "", "gender": fan.get("gender"), "gender_txt": fan.get("gender_txt") or "", "country": fan.get("country") or "", "province": fan.get("province") or "", "city": fan.get("city") or "", "region": fan.get("region") or "", "follow_since": fan.get("follow_since") or "", "follow_time": fan.get("follow_time"), "like_cnt": fan.get("like_cnt"), "look_cnt": fan.get("look_cnt"), "comment_cnt": fan.get("comment_cnt"), "reward_amt": fan.get("reward_amt"), "pay_cnt": fan.get("pay_cnt"), "source_query": "admin:refresh_oa_fans", } return update_wechat_user(rid, body) def upsert_oa_fans_from_body(token: str, body: dict, userid: str, *, partial: bool = False) -> None: userid = (userid or "").strip() if not userid: return payload: dict = {"openid": userid, "h5_userid": userid, "source": "admin_user_list"} mapping = { "nickname": ("nick", "nickname"), "avatar": ("avatar",), "signature": ("signature",), "remark": ("remark",), "gender": ("gender",), "gender_txt": ("gender_txt",), "country": ("country",), "province": ("province",), "city": ("city",), "region": ("region",), "follow_since": ("follow_since",), "follow_time": ("follow_time",), "like_cnt": ("like_cnt",), "look_cnt": ("look_cnt",), "comment_cnt": ("comment_cnt",), "reward_amt": ("reward_amt",), "pay_cnt": ("pay_cnt",), "identity_openid": ("identity_openid",), "scene": ("scene",), "last_action": ("last_action",), } for dest, keys in mapping.items(): val = None for k in keys: if k in body and body.get(k) not in (None, ""): val = body.get(k) break if val is None and not partial: # create 时 nick 映射 if dest == "nickname": val = body.get("nick") or body.get("nickname") or "" if val is not None: if dest == "avatar": val = _https_avatar(str(val)) payload[dest] = val if len(payload) <= 3 and partial: return exist = _oa_fans_by_openids(token, [userid]).get(userid) if exist and exist.get("id"): _pb_request( "PATCH", "/api/collections/oa_fans/records/" + urllib.parse.quote(str(exist.get("id"))), token, payload, ) else: _pb_request("POST", "/api/collections/oa_fans/records", token, payload) def _ntfy_auth_headers() -> dict[str, str]: if NTFY_TOKEN: return {"Authorization": "Bearer " + NTFY_TOKEN} if NTFY_USER and NTFY_PASS: import base64 raw = ("%s:%s" % (NTFY_USER, NTFY_PASS)).encode("utf-8") return {"Authorization": "Basic " + base64.b64encode(raw).decode("ascii")} return {} def _publish_one(url: str, body: bytes, headers: dict[str, str]) -> None: req = urllib.request.Request(url, data=body, headers=headers, method="POST") with urllib.request.urlopen(req, timeout=6) as resp: resp.read(64) def publish(title: str, message: str, tags: str, priority: str, avatar: str = "") -> bool: topics = list(NTFY_TOPICS) or ([NTFY_TOPIC] if NTFY_TOPIC else []) if not NTFY_BASE or not topics: return False # 正文不再重复贴 Title,避免通知里 [WebVIP] 刷两遍 body = message[:3500].encode("utf-8") headers = { "Title": _hdr_utf8(title), "Priority": str(priority or "3"), "Tags": tags, "Content-Type": "text/plain; charset=utf-8", } headers.update(_ntfy_auth_headers()) # ntfy Attach:把微信头像挂到通知卡片上(需公网 https) av = (avatar or "").strip() if av.startswith("https://") and len(av) < 500: headers["Attach"] = av headers["Filename"] = "avatar.jpg" ok_any = False last_err: Exception | None = None for topic in topics: url = "%s/%s" % (NTFY_BASE, topic) try: _publish_one(url, body, headers) ok_any = True continue except Exception as e: last_err = e # wx.qlogo 等外链 Attach 偶发被 ntfy 拉取失败时,降级为纯文本再发一次 if headers.get("Attach"): try: headers2 = dict(headers) headers2.pop("Attach", None) headers2.pop("Filename", None) _publish_one(url, body, headers2) ok_any = True continue except Exception as e2: last_err = e2 if ok_any: return True _stats["ntfy_fail"] += 1 if last_err is not None: _stats["last_ntfy_err"] = ("%s: %s" % (type(last_err).__name__, last_err))[: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, Authorization, X-Ops-Token", ) 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): raw_path = self.path or "/" path = raw_path.split("?", 1)[0] qs = "" if "?" in raw_path: qs = raw_path.split("?", 1)[1] params = {} for part in qs.split("&"): if "=" in part: k, v = part.split("=", 1) params[urllib.parse.unquote(k)] = urllib.parse.unquote(v) 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 # /wechat-users 或 /wechat-users/{id} if path in ("/wechat-users", "/api/wechat-users") or path.startswith( ("/wechat-users/", "/api/wechat-users/") ): if not ops_token_ok(self.headers): self._json(401, {"ok": False, "error": "未登录"}) return rid = "" for prefix in ("/api/wechat-users/", "/wechat-users/"): if path.startswith(prefix): rid = path[len(prefix) :].strip("/") break if rid and "/" not in rid: try: self._json(200, get_wechat_user(rid)) except Exception as e: self._json(404, {"ok": False, "error": str(e)[:200]}) return try: limit = int(params.get("limit") or params.get("perPage") or 50) except Exception: limit = 50 try: page = int(params.get("page") or 1) except Exception: page = 1 q = str(params.get("q") or "") try: self._json(200, list_wechat_users(limit=limit, q=q, page=page)) except Exception as e: self._json(500, {"ok": False, "error": str(e)[:200], "users": []}) return self._json(200, {"ok": True, "service": "vip-track"}) def _read_json_body(self) -> dict: 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 "{}") return body if isinstance(body, dict) else {} except Exception: return {} def _wechat_users_write(self, method: str): raw_path = self.path or "/" path = raw_path.split("?", 1)[0] if not ( path in ("/wechat-users", "/api/wechat-users") or path.startswith(("/wechat-users/", "/api/wechat-users/")) ): return False if not ops_token_ok(self.headers): self._json(401, {"ok": False, "error": "未登录"}) return True rid = "" action = "" for prefix in ("/api/wechat-users/", "/wechat-users/"): if path.startswith(prefix): rest = path[len(prefix) :].strip("/") parts = [p for p in rest.split("/") if p] if parts: rid = parts[0] if len(parts) >= 2: action = parts[1] break body = self._read_json_body() try: if method == "POST" and not rid: self._json(200, create_wechat_user(body)) return True if method == "POST" and rid and action == "refresh": self._json(200, refresh_wechat_user(rid)) return True if method == "POST" and rid and action == "delete": also = bool(body.get("also_oa_fans")) self._json(200, delete_wechat_user(rid, also_oa_fans=also)) return True if method == "PATCH" and rid: self._json(200, update_wechat_user(rid, body)) return True if method == "DELETE" and rid: qs = raw_path.split("?", 1)[1] if "?" in raw_path else "" also = "also_oa_fans=1" in qs or "also_oa_fans=true" in qs if isinstance(body, dict) and body.get("also_oa_fans"): also = True self._json(200, delete_wechat_user(rid, also_oa_fans=also)) return True self._json(400, {"ok": False, "error": "unsupported wechat-users route"}) except Exception as e: self._json(500, {"ok": False, "error": str(e)[:300]}) return True def do_POST(self): if self._wechat_users_write("POST"): return body = self._read_json_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", "wechat_userid", "wechat_nick", "wechat_avatar", "avatar", "signature", "gender_txt", "region", "follow_since", "like_cnt", "look_cnt", "comment_cnt", "reward_cnt", "reward_amt", "pay_cnt", ): if props.get(k) in (None, "") and identity.get(k) not in (None, ""): props[k] = identity.get(k) if not props.get("ua") and ua_hdr: props["ua"] = ua_hdr props, identity, openid = enrich_identity(props, identity, openid) 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: # 同一访客会话:访问首页只推 1 条,不再 session_start+page_view 各推一次 who = session or openid or ip or "-" visit_key = "visit|%s|%s" % (who, page or "/") if ntfy_name != VISIT_PRIMARY: # page_view:若本会话已推过访问,直接跳过;否则升格为「用户访问」 if not visit_dedup_ok(visit_key): ntfy_name = None else: ntfy_name = VISIT_PRIMARY else: if not visit_dedup_ok(visit_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, avatar = 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, avatar) 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}) def do_PATCH(self): if self._wechat_users_write("PATCH"): return self._json(404, {"ok": False, "error": "not found"}) def do_DELETE(self): if self._wechat_users_write("DELETE"): return self._json(404, {"ok": False, "error": "not found"}) if __name__ == "__main__": init_db() ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()