feat: 管理后台(/admin) — 用户空间总览/文件管理/按日期批量清理/功能使用统计; usage事件记录; ADMIN_TOKEN鉴权

This commit is contained in:
personal82555 committed 2026-10-12 13:04:29 +08:00
1 parent 70e03feca6
commit ae2448aefb
4 files changed
+875

No files matched your search

+236
View File
@@ -706,6 +706,53 @@ def _auth_user(handler):
TURNSTILE_SECRET = os.environ.get("TURNSTILE_SECRET", "")
ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN", "")
USAGE_DB = os.environ.get("USAGE_DB", "/app/data/usage.db")
def _usage_db():
conn = sqlite3.connect(USAGE_DB)
conn.execute("CREATE TABLE IF NOT EXISTS usage (id INTEGER PRIMARY KEY AUTOINCREMENT, machine TEXT, username TEXT, tool TEXT, at REAL)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_usage_at ON usage(at)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_usage_tool ON usage(tool)")
conn.commit()
return conn
def log_usage(machine: str, tool: str):
"""record a tool usage event (best-effort, never blocks the request)"""
if not tool:
return
try:
username = ""
try:
conn = _db()
rows = conn.execute("SELECT username, bound_machines FROM users").fetchall()
conn.close()
for u, bm in rows:
if machine in json.loads(bm or "[]"):
username = u
break
except Exception:
pass
conn = _usage_db()
conn.execute("INSERT INTO usage (machine, username, tool, at) VALUES (?,?,?,?)",
(machine or "", username, tool, time.time()))
conn.commit()
conn.close()
except Exception:
pass
def _dir_size(path: str) -> int:
total = 0
for root, _dirs, files in os.walk(path):
for f in files:
try:
total += os.path.getsize(os.path.join(root, f))
except OSError:
pass
return total
def verify_turnstile(token: str) -> bool:
@@ -727,6 +774,169 @@ def verify_turnstile(token: str) -> bool:
USER_NAME_RE = re.compile(r"^[A-Za-z0-9_\u4e00-\u9fa5-]{3,32}$")
def _admin_auth(handler) -> bool:
if not ADMIN_TOKEN:
return False
tok = handler.headers.get("X-Admin-Token", "")
return bool(tok) and tok == ADMIN_TOKEN
def admin_api(method: str, sub: str, payload: dict, handler):
"""returns (status, body)"""
if not _admin_auth(handler):
return 403, {"code": 403, "message": "管理员令牌无效"}
if method == "GET" and sub == "/overview":
conn = _db()
users = conn.execute("SELECT username, created, card_key, bound_machines FROM users").fetchall()
conn.close()
out_users = []
total_files = 0
total_size = 0
for username, created, card_key, bm in users:
udir = os.path.join(USERS_ROOT, username)
fdir = os.path.join(udir, "files")
fcount = 0
fsize = 0
for root, _d, files in os.walk(fdir):
for f in files:
fcount += 1
try:
fsize += os.path.getsize(os.path.join(root, f))
except OSError:
pass
dsize = 0
dp = os.path.join(udir, "data.json")
if os.path.exists(dp):
try:
dsize = os.path.getsize(dp)
except OSError:
pass
total_files += fcount
total_size += fsize + dsize
try:
machines = json.loads(bm or "[]")
except Exception:
machines = []
out_users.append({
"username": username,
"created": int(created or 0),
"files": fcount,
"file_size": fsize,
"data_size": dsize,
"total_size": fsize + dsize,
"devices": len(machines),
"licensed": bool(card_key),
})
out_users.sort(key=lambda x: -x["total_size"])
return 200, {"code": 200, "message": "ok", "data": {
"users": out_users,
"totals": {"users": len(out_users), "files": total_files, "size": total_size},
}}
if method == "GET" and sub.startswith("/files"):
qs = parse.parse_qs(parse.urlparse(handler.path).query)
username = (qs.get("username") or [""])[0]
if not username or "/" in username or ".." in username:
return 400, {"code": 400, "message": "参数错误"}
fdir = os.path.join(_user_dir(username), "files")
files = []
total = 0
for root, _d, fs in os.walk(fdir):
kind = os.path.basename(root) if root != fdir else ""
for f in fs:
fp = os.path.join(root, f)
try:
st = os.stat(fp)
except OSError:
continue
total += st.st_size
files.append({"id": f, "name": f, "kind": kind, "size": st.st_size, "mtime": int(st.st_mtime)})
files.sort(key=lambda x: -x["mtime"])
return 200, {"code": 200, "message": "ok", "data": {"files": files, "total_size": total, "count": len(files)}}
if method == "POST" and sub == "/cleanup":
before = int(payload.get("before") or 0)
username = str(payload.get("username") or "")
if before <= 0:
return 400, {"code": 400, "message": "缺少时间参数"}
removed = 0
freed = 0
roots = []
if username:
roots.append((username, os.path.join(_user_dir(username), "files")))
else:
if os.path.isdir(USERS_ROOT):
for u in os.listdir(USERS_ROOT):
roots.append((u, os.path.join(USERS_ROOT, u, "files")))
for _u, fdir in roots:
if not os.path.isdir(fdir):
continue
for root, _d, fs in os.walk(fdir, topdown=False):
for f in fs:
fp = os.path.join(root, f)
try:
st = os.stat(fp)
except OSError:
continue
if st.st_mtime < before:
try:
freed += st.st_size
removed += 1
os.remove(fp)
except OSError:
pass
try:
if not os.listdir(root):
os.rmdir(root)
except OSError:
pass
return 200, {"code": 200, "message": "ok", "data": {"removed": removed, "freed": freed}}
if method == "POST" and sub == "/delete-file":
file_id = str(payload.get("id") or "")
username = str(payload.get("username") or "")
if not re.match(r"^[A-Za-z0-9_-]{8,64}$", file_id) or not username:
return 400, {"code": 400, "message": "参数错误"}
base = os.path.join(_user_dir(username), "files")
target = os.path.join(base, file_id)
if not os.path.exists(target):
# search kind subdirs
target = None
for d in os.listdir(base) if os.path.isdir(base) else []:
p2 = os.path.join(base, d, file_id)
if os.path.exists(p2):
target = p2
break
if not target or not os.path.exists(target):
return 404, {"code": 404, "message": "文件不存在"}
size = os.path.getsize(target)
os.remove(target)
conn = _db()
conn.execute("DELETE FROM files WHERE id=?", (file_id,))
conn.commit()
conn.close()
return 200, {"code": 200, "message": "ok", "data": {"freed": size}}
if method == "GET" and sub == "/usage":
qs = parse.parse_qs(parse.urlparse(handler.path).query)
days = _int_str((qs.get("days") or ["7"])[0], 1, 365, 7)
since = time.time() - days * 86400
conn = _usage_db()
by_tool = conn.execute("SELECT tool, COUNT(*) c FROM usage WHERE at>? GROUP BY tool ORDER BY c DESC LIMIT 30", (since,)).fetchall()
by_user = conn.execute("SELECT username, COUNT(*) c, MAX(at) last FROM usage WHERE at>? AND username!='' GROUP BY username ORDER BY c DESC LIMIT 50", (since,)).fetchall()
total = conn.execute("SELECT COUNT(*) FROM usage WHERE at>?", (since,)).fetchone()[0]
conn.close()
return 200, {"code": 200, "message": "ok", "data": {
"days": days,
"total": total,
"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],
}}
return 404, {"code": 404, "message": "unknown admin api"}
def _req_machine(handler):
return handler.headers.get("X-Machine-Id", "") if handler else ""
@@ -926,8 +1136,26 @@ class Handler(BaseHTTPRequestHandler):
return # response already sent (file download)
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
def _handle_admin(self, method):
parsed = parse.urlparse(self.path)
sub = parsed.path[len("/admin"):]
payload = {}
if method == "POST":
try:
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b"{}"
payload = json.loads(raw.decode("utf-8") or "{}")
except Exception:
self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json")
return
status, body = admin_api(method, sub, payload, self)
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
def do_GET(self):
parsed = parse.urlparse(self.path)
if parsed.path.startswith("/admin"):
self._handle_admin("GET")
return
if parsed.path.startswith("/user"):
self._handle_user("GET")
return
@@ -953,6 +1181,8 @@ class Handler(BaseHTTPRequestHandler):
machine = self.headers.get("X-Machine-Id", "")
tool = self.headers.get("X-Tool", "")
status = check(machine, tool)
if status == 200:
log_usage(machine, tool)
self._reply(status, b"ok" if status == 200 else b"forbidden")
return
@@ -987,6 +1217,7 @@ class Handler(BaseHTTPRequestHandler):
if status != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
log_usage(machine, "video-tools")
try:
ctype = self.headers.get("Content-Type", "")
length = int(self.headers.get("Content-Length") or 0)
@@ -1054,6 +1285,7 @@ class Handler(BaseHTTPRequestHandler):
if status != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
log_usage(machine, "audio-tools-tts")
try:
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b"{}"
@@ -1094,6 +1326,7 @@ class Handler(BaseHTTPRequestHandler):
if status != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
log_usage(machine, "audio-tools-asr")
workdir = None
try:
ctype = self.headers.get("Content-Type", "")
@@ -1136,6 +1369,9 @@ class Handler(BaseHTTPRequestHandler):
def do_POST(self):
parsed = parse.urlparse(self.path)
if parsed.path.startswith("/admin"):
self._handle_admin("POST")
return
if parsed.path.startswith("/user"):
self._handle_user("POST")
return