cosmo/backend/app/api/terminal.py

175 lines
6.4 KiB
Python

"""
Terminal API routes - consumed by the ESP32-S3 terminal (no user session)
"""
import logging
from datetime import datetime
from typing import NamedTuple, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.models.db import TerminalDevice, User
from app.models.schemas.terminal import (
PairCodeRequest,
PairCodeResponse,
PairStatusResponse,
TerminalFollowsResponse,
)
from app.services.auth import decode_access_token
from app.services.terminal_icon import icon_file, render_rgb565
from app.services.terminal_service import PairingError, terminal_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/terminal", tags=["terminal"])
# auto_error=False so a missing header answers 401 instead of FastAPI's default 403
bearer_scheme = HTTPBearer(auto_error=False)
class TerminalContext(NamedTuple):
user: User
device: TerminalDevice
async def get_terminal_context(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer_scheme),
db: AsyncSession = Depends(get_db),
) -> TerminalContext:
"""Authenticate a terminal: device scoped long lived JWT + still-bound device row."""
unauthorized = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="终端令牌无效,请重新配对",
headers={"WWW-Authenticate": "Bearer"},
)
if credentials is None:
raise unauthorized
payload = decode_access_token(credentials.credentials)
if not payload or payload.get("typ") != "terminal":
raise unauthorized
user_id = payload.get("sub")
device_id = payload.get("did")
if not user_id or not device_id:
raise unauthorized
# The device row is the revocation list: unbinding clears it and kills the token.
device = await terminal_service.get_bound_device(db, device_id)
if device is None or device.user_id != int(user_id):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="设备已解绑,请在终端上重新获取配对码",
headers={"WWW-Authenticate": "Bearer"},
)
# The row says the device is bound, the stamp says to *this* binding: without it a
# token leaked before an unbind would come back to life as soon as someone re-binds.
session = device.bound_at.isoformat() if device.bound_at else None
if session is None or payload.get("bnd") != session:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="终端令牌已失效,请在终端上重新获取配对码",
headers={"WWW-Authenticate": "Bearer"},
)
user = await db.get(User, int(user_id))
if user is None or not user.is_active:
raise unauthorized
return TerminalContext(user=user, device=device)
@router.post("/pair/code", response_model=PairCodeResponse)
async def request_pair_code(
payload: PairCodeRequest,
db: AsyncSession = Depends(get_db),
):
"""
Ask for the 6 digit code to render on the terminal screen.
Idempotent: polling this endpoint keeps returning the same code until it expires.
An already bound device gets its owner back instead of a new code.
"""
try:
data = await terminal_service.issue_pairing_code(db, payload.device_id, payload.name)
except PairingError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
return PairCodeResponse(**data)
@router.get("/pair/status", response_model=PairStatusResponse)
async def poll_pair_status(
device_id: str = Query(..., min_length=4, max_length=50),
code: str = Query(..., min_length=6, max_length=6),
db: AsyncSession = Depends(get_db),
):
"""Poll while the code is on screen. Returns the long lived token once the user binds."""
data = await terminal_service.get_pair_status(db, device_id, code)
return PairStatusResponse(**data)
@router.get("/follows", response_model=TerminalFollowsResponse)
async def get_followed_bodies(
ctx: TerminalContext = Depends(get_terminal_context),
db: AsyncSession = Depends(get_db),
):
"""Followed bodies of the owner, newest position and nearest events, compact for a TFT."""
ctx.device.last_seen_at = datetime.utcnow()
await db.commit()
bodies = await terminal_service.build_follow_snapshot(db, ctx.user.id)
return TerminalFollowsResponse(
username=ctx.user.username,
device_id=ctx.device.id,
server_time=datetime.utcnow(),
follow_count=len(bodies),
bodies=bodies,
)
#: the terminal blits fixed size bitmaps: 40x40 in the list, 64x64 on the detail page
ICON_SIZES = (40, 64)
@router.get("/bodies/{body_id}/icon")
async def get_body_icon(
body_id: str,
size: int = Query(64, description="Edge length in pixels: 40 (list) or 64 (detail)"),
ctx: TerminalContext = Depends(get_terminal_context),
db: AsyncSession = Depends(get_db),
):
"""
The icon maintained for one body in 平台管理 -> 天体信息, as flat big endian RGB565.
The terminal has no image decoder and no alpha channel: it additive blends the bitmap
onto the framebuffer, so the answer is the finished pixel blob (size * size * 2 bytes)
rendered with the same pipeline as terminal/tools/gen_assets.py. 404 when the body has
no icon - the terminal then keeps its built in line art.
"""
if size not in ICON_SIZES:
raise HTTPException(status_code=400, detail="size must be 40 or 64")
icon = await terminal_service.get_body_icon(db, body_id)
if icon is None:
raise HTTPException(status_code=404, detail="该天体没有维护图标")
path = icon_file(icon.file_path)
if path is None:
logger.warning(f"icon row {icon.id} points at a missing file: {icon.file_path}")
raise HTTPException(status_code=404, detail="图标文件不存在")
try:
blob = render_rgb565(path, size)
except Exception as exc: # corrupt / unsupported upload
logger.error(f"Cannot render icon {icon.file_path} for {body_id}: {exc}")
raise HTTPException(status_code=502, detail="图标文件无法解码")
return Response(
content=blob,
media_type="application/octet-stream",
# the resource id is the version the terminal caches on
headers={"ETag": str(icon.id)},
)