From 853d9d3c8c33efbafd75749cf81d67008df036c0 Mon Sep 17 00:00:00 2001 From: jinghui <3970260761@qq.com> Date: Thu, 12 Nov 2026 12:52:51 +0800 Subject: [PATCH] =?UTF-8?q?feat(online):=20/relay/online=20=E7=AB=AF?= =?UTF-8?q?=E7=82=B9=20+=2090s=E5=86=85=E5=AD=98=E7=AA=97=E5=8F=A3=20+=20a?= =?UTF-8?q?dmin/usage=20=E8=BF=94=E5=9B=9Eonline?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/server.py b/server.py index 9d3b6a0..9d2a035 100644 --- a/server.py +++ b/server.py @@ -946,6 +946,41 @@ def usage_track(payload: dict, handler) -> tuple: return 200, {"code": 200, "message": "ok", "data": {"ok": 1}} +# ---- 在线统计:仅未登录访客,前端停留满 1 分钟才开始心跳 ---- +ONLINE_WINDOW = 90.0 # 心跳每 30s 一次(后台标签被节流为 60s),超 90s 无心跳判离线 +_ONLINE: dict = {} # machine_id -> 最近心跳时间戳(进程内存) +_ONLINE_LOCK = threading.Lock() + + +def online_beat(payload: dict) -> tuple: + """POST /online:访客在线心跳。 + + - guest=true(未登录)→ 记为在线;guest=false(已登录)→ 移出统计。 + - 「停留超过 1 分钟才算在线」由前端控制:打开满 60s 才发首次心跳。 + """ + machine = str(payload.get("machine_id") or "").strip() + if not machine or not MACHINE_RE.match(machine): + return 400, {"code": 400, "message": "无效 machine_id"} + guest = bool(payload.get("guest")) + now = time.time() + with _ONLINE_LOCK: + if guest: + _ONLINE[machine] = now + else: + _ONLINE.pop(machine, None) # 登录用户不统计 + if len(_ONLINE) > 5000: # 防内存膨胀:修剪过期 + for k in [k for k, t in _ONLINE.items() if now - t > ONLINE_WINDOW]: + _ONLINE.pop(k, None) + count = sum(1 for t in _ONLINE.values() if now - t <= ONLINE_WINDOW) + return 200, {"code": 200, "message": "ok", "data": {"online": count}} + + +def online_count() -> int: + now = time.time() + with _ONLINE_LOCK: + return sum(1 for t in _ONLINE.values() if now - t <= ONLINE_WINDOW) + + def _dir_size(path: str) -> int: total = 0 for root, _dirs, files in os.walk(path): @@ -1349,6 +1384,7 @@ def admin_api(method: str, sub: str, payload: dict, handler): "by_tool": [{"tool": t, "count": c} for t, c in by_tool], "by_user": [{"username": u, "count": c, "last": int(l or 0)} for u, c, l in by_user], "guest": {"count": int(g[0] or 0), "last": int(g[1] or 0)}, + "online": online_count(), }} return 404, {"code": 404, "message": "unknown admin api"} @@ -2840,6 +2876,11 @@ class Handler(BaseHTTPRequestHandler): status, body = usage_track(payload, self) self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") return + if parsed.path == "/online": + payload = self._read_payload() or {} + status, body = online_beat(payload) + self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") + return if parsed.path.startswith("/admin"): self._handle_admin("POST") return