273 lines
10 KiB
Python
273 lines
10 KiB
Python
"""管理端:独立 token + IP 白名单。激活码生成/导出、用户管理、信号流水、测试信号。"""
|
||
from __future__ import annotations
|
||
|
||
import csv
|
||
import io
|
||
import secrets
|
||
from datetime import timedelta
|
||
|
||
from fastapi import APIRouter, Depends, Header, Request
|
||
from pydantic import BaseModel
|
||
from starlette.responses import StreamingResponse
|
||
|
||
from ..config import settings
|
||
from ..db import execute, query
|
||
from ..errors import BizError, ok
|
||
from ..security import gen_activation_code, now_dt, now_s, sha256
|
||
from ..services.activation import normalize
|
||
|
||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||
|
||
# 默认仅允许本机/内网;生产在 .env 配 XL_ADMIN_IPS
|
||
ALLOWED_IPS = {"127.0.0.1", "::1", "localhost", "testclient"} | {s.strip() for s in settings.admin_ips.split(",") if s.strip()}
|
||
|
||
|
||
def verify_admin(request: Request, x_admin_token: str | None = Header(default=None)):
|
||
ip = request.client.host if request.client else "?"
|
||
# "*" = 全放行(仅靠 token 鉴权);网段前缀:白名单条目以 . 结尾时按前缀匹配(如 "192.168.31.")
|
||
ok_ip = "*" in ALLOWED_IPS or any(
|
||
ip == w or (w.endswith(".") and ip.startswith(w))
|
||
for w in ALLOWED_IPS
|
||
)
|
||
if not ok_ip:
|
||
raise BizError(5000, f"管理端仅限内网访问(当前 IP: {ip},如需开放请配 XL_ADMIN_IPS)", http_status=403)
|
||
if not settings.admin_token or not secrets.compare_digest(x_admin_token or "", settings.admin_token):
|
||
raise BizError(5000, "管理员 Token 错误", http_status=403)
|
||
|
||
|
||
# ---- 濵活码 --------------------------------------------------------------------
|
||
|
||
class GenCodesIn(BaseModel):
|
||
days: int
|
||
count: int
|
||
batch: str | None = None
|
||
|
||
|
||
@router.post("/activation-codes")
|
||
def gen_codes(body: GenCodesIn, _: None = Depends(verify_admin)):
|
||
if body.days not in (30, 90, 365) or not (1 <= body.count <= 500):
|
||
raise BizError(5000, "days 仅支持 30/90/365,count ≤500")
|
||
batch = body.batch or now_dt().strftime("%Y%m%d%H%M")
|
||
card_expires = (now_dt() + timedelta(days=180)).strftime("%Y-%m-%d %H:%M:%S")
|
||
codes = []
|
||
for _ in range(body.count):
|
||
code = gen_activation_code()
|
||
execute(
|
||
"INSERT INTO activation_codes(code_hash, duration_days, status, created_at, expires_at, batch)"
|
||
" VALUES(?,?,?,?,?,?)",
|
||
(sha256(normalize(code)), body.days, "unused", now_s(), card_expires, batch),
|
||
)
|
||
codes.append({"code": code, "days": body.days, "batch": batch})
|
||
return ok({"batch": batch, "codes": codes})
|
||
|
||
|
||
@router.get("/activation-codes/export")
|
||
def export_codes(batch: str, _: None = Depends(verify_admin)):
|
||
"""明文导出仅一次:导出后删除创建时间信息不可逆(卡密本身可重复导出,明文只有生成时返回)。
|
||
|
||
这里导出的是「本批次 + 未使用」的码——明文无法从 hash 还原,
|
||
因此导出必须配合生成响应里的明文保存。此接口仅返回占位说明。
|
||
"""
|
||
rows = query(
|
||
"SELECT batch, duration_days, status, bound_user FROM activation_codes WHERE batch=?",
|
||
(batch,),
|
||
)
|
||
buf = io.StringIO()
|
||
w = csv.writer(buf)
|
||
w.writerow(["batch", "days", "status", "bound_user"])
|
||
for r in rows:
|
||
w.writerow([r["batch"], r["duration_days"], r["status"], r["bound_user"] or ""])
|
||
return StreamingResponse(iter([buf.getvalue()]), media_type="text/csv")
|
||
|
||
|
||
# ---- 用户管理 --------------------------------------------------------------------
|
||
|
||
@router.get("/users")
|
||
def list_users(q: str = "", limit: int = 50, _: None = Depends(verify_admin)):
|
||
if q:
|
||
rows = query(
|
||
"SELECT id, phone, nickname, is_active, active_until, is_banned, created_at, last_login "
|
||
"FROM users WHERE phone LIKE ? OR nickname LIKE ? ORDER BY id DESC LIMIT ?",
|
||
(f"%{q}%", f"%{q}%", limit),
|
||
)
|
||
else:
|
||
rows = query(
|
||
"SELECT id, phone, nickname, is_active, active_until, is_banned, created_at, last_login "
|
||
"FROM users ORDER BY id DESC LIMIT ?",
|
||
(limit,),
|
||
)
|
||
return ok([dict(r) for r in rows])
|
||
|
||
|
||
class BanIn(BaseModel):
|
||
banned: bool
|
||
|
||
|
||
@router.post("/users/{user_id}/ban")
|
||
def ban_user(user_id: int, body: BanIn, _: None = Depends(verify_admin)):
|
||
execute("UPDATE users SET is_banned=? WHERE id=?", (int(body.banned), user_id))
|
||
return ok({})
|
||
|
||
|
||
@router.post("/users/{user_id}/unbind-device")
|
||
def unbind(user_id: int, _: None = Depends(verify_admin)):
|
||
execute("UPDATE devices SET jpush_rid=NULL, rid_invalid=1 WHERE user_id=?", (user_id,))
|
||
return ok({})
|
||
|
||
|
||
# ---- 推送收发统计(2026-12-03) -------------------------------------------------
|
||
# 发送:每轮扫描每个用户一条聚合推送 = 一条 push_batches 记录
|
||
# 到达:客户端收到推送后带 receipt_token 回执,写 received_at
|
||
|
||
@router.get("/push-stats")
|
||
def push_stats(days: int = 7, _: None = Depends(verify_admin)):
|
||
days = max(1, min(days, 90))
|
||
since = (now_dt() - timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")
|
||
agg = query(
|
||
"SELECT COUNT(*) AS total,"
|
||
" SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) AS success,"
|
||
" SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) AS failed,"
|
||
" SUM(CASE WHEN received_at IS NOT NULL THEN 1 ELSE 0 END) AS received"
|
||
" FROM push_batches WHERE sent_at >= ?",
|
||
(since,),
|
||
)[0]
|
||
total = agg["total"] or 0
|
||
received = agg["received"] or 0
|
||
recent = query(
|
||
"SELECT b.id, b.user_id, u.phone, b.item_count, b.status, b.error, b.sent_at, b.received_at"
|
||
" FROM push_batches b LEFT JOIN users u ON u.id = b.user_id"
|
||
" WHERE b.sent_at >= ? ORDER BY b.id DESC LIMIT 50",
|
||
(since,),
|
||
)
|
||
return ok({
|
||
"days": days,
|
||
"total": total,
|
||
"success": agg["success"] or 0,
|
||
"failed": agg["failed"] or 0,
|
||
"received": received,
|
||
"rate": round(received * 100.0 / total, 1) if total else 0.0,
|
||
"recent": [dict(r) for r in recent],
|
||
})
|
||
|
||
|
||
# ---- 信号流水 --------------------------------------------------------------------
|
||
|
||
@router.get("/signals")
|
||
def list_signals(symbol: str = "", interval: str = "", date: str = "", limit: int = 100, _: None = Depends(verify_admin)):
|
||
conds, params = ["1=1"], []
|
||
if symbol:
|
||
conds.append("symbol LIKE ?")
|
||
params.append(f"%{symbol}%")
|
||
if interval:
|
||
conds.append("interval=?")
|
||
params.append(interval)
|
||
if date:
|
||
conds.append("divergence_time LIKE ?")
|
||
params.append(f"{date}%")
|
||
rows = query(
|
||
f"SELECT * FROM signals WHERE {' AND '.join(conds)} ORDER BY divergence_time DESC LIMIT ?",
|
||
tuple(params + [limit]),
|
||
)
|
||
return ok([dict(r) for r in rows])
|
||
|
||
|
||
# ---- 测试信号(联调用) ------------------------------------------------------------
|
||
# 纯测试推送:不读写行情K线、不产生信号/通知记录,直接把带【测试】文案的
|
||
# 自定义消息走真实闹钟链路(JPush message + signal_alarm extras)发到设备。
|
||
|
||
class TestSignalIn(BaseModel):
|
||
pass # 预留;测试信号只发给专属测试机,不再支持"发给全部设备"
|
||
|
||
|
||
def pick_test_devices(rows: list) -> list[str]:
|
||
"""从设备行里挑出专属测试机的极光注册ID。is_tester 为 NULL/0(旧版)一律不发。
|
||
|
||
行是 sqlite3.Row:只能用下标访问,没有 .get()(曾因此 500)。
|
||
"""
|
||
out: list[str] = []
|
||
for r in rows:
|
||
if r["is_tester"] == 1 and r["jpush_rid"]:
|
||
out.append(r["jpush_rid"])
|
||
return out
|
||
|
||
|
||
@router.post("/test-signal")
|
||
def test_signal(body: TestSignalIn, _: None = Depends(verify_admin)):
|
||
"""只发给标记为专属测试机的设备(2026-12-02)。
|
||
|
||
此前发给全部已注册推送的设备,联调一次会打扰所有用户。旧版客户端不上报
|
||
is_tester,该列为 0,永远收不到测试信号。
|
||
"""
|
||
from ..notify.push import push_test_signal
|
||
|
||
rows = query(
|
||
"SELECT user_id, jpush_rid, is_tester FROM devices "
|
||
"WHERE rid_invalid = 0 AND jpush_rid IS NOT NULL"
|
||
)
|
||
rids = list(dict.fromkeys(pick_test_devices(rows))) # 去重,同一注册ID只发一次
|
||
if not rids:
|
||
raise BizError(3002, "没有专属测试机在线登记,请先在测试机的新版 App 上登录")
|
||
result = push_test_signal(rids)
|
||
return ok({"devices": len(rids), "jpush": result})
|
||
|
||
|
||
# ---- App 版本管理(APK 上传托管 + 客户端自动更新) ----------------------------
|
||
|
||
import json as _json
|
||
from pathlib import Path as _Path
|
||
from fastapi import UploadFile as _UploadFile, File as _File, Form as _Form
|
||
|
||
from fastapi.responses import FileResponse as _FileResponse
|
||
|
||
_APK_DIR = _Path(settings.db_path).parent / "apk"
|
||
|
||
|
||
def _version_file() -> _Path:
|
||
return _APK_DIR / "version.json"
|
||
|
||
|
||
def read_version_meta() -> dict:
|
||
"""当前版本元信息(无上传时返回空表,config 接口兜底默认值)。"""
|
||
f = _version_file()
|
||
if f.exists():
|
||
try:
|
||
return _json.loads(f.read_text(encoding="utf-8"))
|
||
except Exception:
|
||
pass
|
||
return {}
|
||
|
||
|
||
@router.post("/app/upload")
|
||
def upload_app(
|
||
request: Request,
|
||
x_admin_token: str | None = Header(default=None),
|
||
apk: _UploadFile = _File(...),
|
||
|
||
version: str = _Form(...),
|
||
notes: str = _Form(default=""),
|
||
min_version: str = _Form(default=""), # 低于此版本强制更新;空=沿用 version
|
||
):
|
||
verify_admin(request, x_admin_token)
|
||
_APK_DIR.mkdir(parents=True, exist_ok=True)
|
||
fname = f"xuanlong-{version}.apk"
|
||
dest = _APK_DIR / fname
|
||
size = 0
|
||
with dest.open("wb") as out:
|
||
while chunk := apk.file.read(1 << 20):
|
||
size += len(chunk)
|
||
out.write(chunk)
|
||
meta = {
|
||
"latest_version": version,
|
||
"min_version": min_version, # 空=不强制(仅提示更新)
|
||
"notes": notes,
|
||
"filename": fname,
|
||
"size": size,
|
||
"uploaded_at": __import__("datetime").datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||
}
|
||
_version_file().write_text(_json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
|
||
# 只保留最新 3 个包
|
||
apks = sorted(_APK_DIR.glob("*.apk"), key=lambda p: p.stat().st_mtime, reverse=True)
|
||
for old in apks[3:]:
|
||
old.unlink(missing_ok=True)
|
||
return ok(meta, f"已上传 v{version}({size // 1048576}MB),客户端将收到更新提示")
|