- patches/last-login.js: 最小 Redis RESP 客户端(touch/readMany) - patches/inject_last_login.py: 注入 login 路由两条成功分支写 u:<user>:last_login, admin/users 回填 last_login_at / created_at(含 est 标记),可重复执行 - patches/apply.sh: 新增 4h 步骤,重建 .next 后自动恢复 - public-live/user-admin.js: toDate 兼容毫秒时间戳与 ISO - patches/backfill_user_times.py: 默认演练(IDLETIME 在 Redis 重载后同值,会造假数据)
83 lines
2.8 KiB
Python
83 lines
2.8 KiB
Python
#!/usr/bin/env python3
|
||
"""回填用户时间字段(默认演练,不写入):
|
||
|
||
⚠️ 教训:Redis 重启/RDB 重载后所有键的 IDLETIME 会从加载时刻统一起算,
|
||
此时「用空闲时长估算上次登录」会把所有账号写成同一个时间(假数据)。
|
||
实测本机就是这种情况,因此不推荐实跑;last_login 由 inject_last_login.py 从此刻起真实记录。
|
||
|
||
- 缺失 created_at 的老账号:写入首次记录时间并标记 created_at_est=1(面板显示「约」)
|
||
- 缺失 last_login 的账号:用 u:<name>:pwd 的空闲时长估算,标记 last_login_est=1
|
||
|
||
用法:python3 backfill_user_times.py [--dry|--force] (默认 --dry)
|
||
环境变量:KAT_REDIS(默认 katelyatv-redis)
|
||
"""
|
||
import json
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
|
||
REDIS = os.environ.get("KAT_REDIS", "katelyatv-redis")
|
||
DRY = "--force" not in sys.argv
|
||
|
||
|
||
def rc(*args):
|
||
r = subprocess.run(
|
||
["docker", "exec", REDIS, "redis-cli", "--raw", *args],
|
||
capture_output=True, text=True,
|
||
)
|
||
return r.stdout.strip()
|
||
|
||
|
||
def main():
|
||
cfg_raw = rc("GET", "admin:config")
|
||
users = set()
|
||
try:
|
||
cfg = json.loads(cfg_raw)
|
||
for u in (cfg.get("UserConfig") or {}).get("Users") or []:
|
||
n = u.get("username")
|
||
if isinstance(n, dict):
|
||
n = n.get("username")
|
||
if n:
|
||
users.add(str(n))
|
||
except Exception as e:
|
||
print("读取 admin:config 失败,仅按 pwd 键回填:", e)
|
||
|
||
pwd_keys = [k for k in rc("KEYS", "u:*:pwd").splitlines() if k.strip()]
|
||
pwd_users = {}
|
||
for k in pwd_keys:
|
||
parts = k.split(":")
|
||
if len(parts) == 3:
|
||
pwd_users[parts[1]] = k
|
||
users |= set(pwd_users.keys())
|
||
|
||
now_ms = int(time.time() * 1000)
|
||
created = last = 0
|
||
for name in sorted(users):
|
||
# created_at
|
||
if not rc("GET", f"u:{name}:created_at"):
|
||
if not DRY:
|
||
rc("SET", f"u:{name}:created_at", str(now_ms))
|
||
rc("SET", f"u:{name}:created_at_est", "1")
|
||
created += 1
|
||
# last_login
|
||
if not rc("GET", f"u:{name}:last_login"):
|
||
key = pwd_users.get(name)
|
||
if key:
|
||
idle = rc("OBJECT", "IDLETIME", key)
|
||
try:
|
||
idle_s = int(idle)
|
||
except ValueError:
|
||
idle_s = None
|
||
if idle_s is not None and idle_s >= 0:
|
||
ts = now_ms - idle_s * 1000
|
||
if not DRY:
|
||
rc("SET", f"u:{name}:last_login", str(ts))
|
||
rc("SET", f"u:{name}:last_login_est", "1")
|
||
last += 1
|
||
print(f"users={len(users)} created_filled={created} last_login_filled={last} dry={DRY}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|