edge_api.py 7.18 KB
"""门店取数端接口 /api/edge/v1/*(请求头 X-Edge-Token = 设备令牌)。门店电脑主动连出,云端不需要能连进门店。

  GET  /config                        取数端全部配置:门店、厂商账号(含密码)、运行参数、配置版本号
  POST /heartbeat                     心跳(每 20 秒;响应带 config_version,变了就重新拉 /config)
  GET  /tasks/next?wait=25            长轮询领任务
  POST /tasks/{id}/progress           步骤进度 {step, status: start|ok|failed|timeout, detail, timeout, error}
  POST /tasks/{id}/result             结果 {ok, result, error, error_code}
  POST /tasks/{id}/file?name=&kind=   文件(截图 / 请求响应快照 / 导出文件)原始字节
  POST /captcha/recognize             验证码图片识别 {image: base64, text_length, mime} → {text, error, image_evidence_id, ...}
  POST /captcha/outcome               回报要求验证码的那次登录结果 {result_evidence_id, outcome, tip, how}
  POST /logs                          日志批量上传 {lines: [{seq, ts, level, logger, task_id, msg}]}
  GET  /releases/latest               查询最新的取数端版本 {version, build, sha256, size, notes}(门店 update.bat 用)
  GET  /releases/{version}/download   下载取数端更新包(sys.update 任务 / update.bat 用,取数端按 sha256 校验)
"""
from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import FileResponse
from pydantic import BaseModel

from ..core.types import EdgeError
from ..services import captcha, edge, releases, stores
from .deps import client_ip

router = APIRouter(prefix="/api/edge/v1", tags=["edge"])
MAX_FILE = 200 * 1024 * 1024


def device_auth(request: Request) -> dict:
    d = edge.device_by_token(request.headers.get("x-edge-token", ""))
    if not d:
        raise HTTPException(401, "取数端令牌不正确(X-Edge-Token)")
    if d["status"] != "enabled":
        raise HTTPException(403, "该取数端已被停用")
    row = stores.store_row(d["store_id"])
    if not row or row["status"] != "active":
        raise HTTPException(403, "门店已停用")
    request.state.device = d
    return d


class ProgressIn(BaseModel):
    step: str
    status: str
    detail: str = ""
    timeout: float | None = None
    error: str = ""


class ResultIn(BaseModel):
    ok: bool
    result: dict = {}
    error: str = ""
    error_code: str = ""


class LogsIn(BaseModel):
    lines: list[dict]


class CaptchaIn(BaseModel):
    image: str                        # base64(可带 dataURL 前缀)
    text_length: int | None = None    # 可选:验证码字符数提示
    mime: str = ""                    # 图片 MIME(不传按魔数判断),证据保存用


MAX_CAPTCHA = 2 * 1024 * 1024         # 验证码图片一般几 KB,超过 2MB 肯定不对


@router.get("/config")
def config(d: dict = Depends(device_auth)):
    return edge.config_payload(d)


@router.post("/captcha/recognize")
def captcha_recognize(body: CaptchaIn, d: dict = Depends(device_auth)):
    """验证码图片识别(取数端登录遇到验证码时调用)。识别不碰 DMS、不触发风控;图片和结果作为证据保存,并写日志。
    识别失败也返回 200(带 error),让取数端换一张图再试;只有请求本身不对才报 4xx。"""
    import base64 as b64
    import binascii

    raw = body.image.strip()
    if raw.startswith("data:") and "," in raw:          # 去掉 dataURL 前缀(data:image/png;base64,xxxx)
        raw = raw.split(",", 1)[1]
    try:
        image = b64.b64decode(raw, validate=True)
    except (binascii.Error, ValueError):
        raise HTTPException(400, "image 不是合法的 base64")
    if not image or len(image) > MAX_CAPTCHA:
        raise HTTPException(400, "验证码图片为空或超过 2MB")
    return captcha.recognize_and_record(d["store_id"], d, image, body.text_length, body.mime)


class CaptchaOutcomeIn(BaseModel):
    result_evidence_id: int
    outcome: str                      # ok / captcha_wrong / rejected / not_submitted / failed
    tip: str = ""
    how: str = "api"                  # api / ui / probe_recognize / probe_wrong


@router.post("/captcha/outcome")
def captcha_outcome(body: CaptchaOutcomeIn, d: dict = Depends(device_auth)):
    """取数端回报:要求验证码的那次登录最后怎样了(写进识别记录,后台能看到「登录结果」)。"""
    try:
        return captcha.record_outcome(d["store_id"], d, body.result_evidence_id, body.outcome, body.tip, body.how)
    except ValueError as e:
        raise HTTPException(400, str(e))


@router.post("/heartbeat")
async def heartbeat(body: dict, request: Request, d: dict = Depends(device_auth)):
    return await edge.heartbeat(d, body, client_ip(request))


@router.get("/tasks/next")
async def next_task(request: Request, wait: float = 25, d: dict = Depends(device_auth)):
    return {"task": await edge.next_task(d, wait, client_ip(request))}


@router.post("/tasks/{tid}/progress")
def progress(tid: str, body: ProgressIn, d: dict = Depends(device_auth)):
    if body.status not in ("start", "ok", "failed", "timeout", "note"):
        raise HTTPException(400, "status 只能是 start / ok / failed / timeout")
    try:
        edge.progress(d, tid, body.step[:60], body.status, body.detail, body.timeout, body.error)
    except EdgeError as e:
        raise HTTPException(404, str(e))
    return {"ok": True}


@router.post("/tasks/{tid}/result")
def result(tid: str, body: ResultIn, d: dict = Depends(device_auth)):
    try:
        edge.on_result(d, tid, body.ok, body.result, body.error, body.error_code)
    except EdgeError as e:
        raise HTTPException(404, str(e))
    return {"ok": True}


@router.post("/tasks/{tid}/file")
async def upload_file(tid: str, request: Request, name: str = "file.bin", kind: str = "file",
                      d: dict = Depends(device_auth)):
    data = await request.body()
    if not data or len(data) > MAX_FILE:
        raise HTTPException(400, "文件为空或超过 200MB")
    try:
        return edge.on_file(d, tid, name, data, kind)
    except EdgeError as e:
        raise HTTPException(400, str(e))


@router.post("/logs")
def logs(body: LogsIn, d: dict = Depends(device_auth)):
    return {"ok": True, "saved": edge.save_logs(d, body.lines)}


@router.get("/releases/latest")
def latest_release(d: dict = Depends(device_auth)):
    """云端版本库里最新的取数端版本(门店 update.bat 查询用);没有任何版本时 version = null。"""
    v = releases.latest_version()
    r = releases.get(v) if v else None
    if not r:
        return {"version": None}
    return {"version": r["version"], "build": r["build"], "sha256": r["sha256"], "size": r["size"],
            "notes": r["notes"], "source": r["source"], "created_at": str(r["created_at"] or "")}


@router.get("/releases/{version}/download")
def download_release(version: str, d: dict = Depends(device_auth)):
    r = releases.get(version)
    if not r:
        raise HTTPException(404, f"云端没有版本 {version}")
    return FileResponse(r["abs_path"], media_type="application/zip", filename=f"edge_update_{version}.zip",
                        headers={"X-Sha256": r["sha256"]})