130 lines
4.7 KiB
Python
130 lines
4.7 KiB
Python
"""Web 侧设备管理:输入配对码绑定、设备列表、解绑。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import uuid
|
||
from datetime import datetime, timezone
|
||
|
||
from fastapi import APIRouter, HTTPException
|
||
from pydantic import BaseModel
|
||
from sqlalchemy import select
|
||
from sqlalchemy.orm import selectinload
|
||
|
||
from app.api.deps import CurrentUser, SessionDep
|
||
from app.core.security import normalize_pair_code
|
||
from app.models import Device, User
|
||
from app.schemas.auth import DeviceOut, OkOut, PairByCodeIn
|
||
from app.services import media, redis_store
|
||
|
||
router = APIRouter(tags=["devices"])
|
||
|
||
|
||
@router.post("/devices/pair", response_model=DeviceOut)
|
||
async def pair_device(body: PairByCodeIn, user: CurrentUser, db: SessionDep) -> DeviceOut:
|
||
code = normalize_pair_code(body.code)
|
||
if len(code) != 6:
|
||
raise HTTPException(400, "pairing code must be 6 digits")
|
||
|
||
# 防爆破:同一配对码 5 次/分钟
|
||
tries = await redis_store.bump_pair_try(code)
|
||
if tries > 5:
|
||
raise HTTPException(429, "too many attempts, wait a minute")
|
||
|
||
payload = await redis_store.get_pair(code)
|
||
if not payload:
|
||
raise HTTPException(404, "code expired or not found")
|
||
if payload.get("bound_user_id"):
|
||
raise HTTPException(409, "code already used")
|
||
|
||
device_id = payload["device_id"]
|
||
device = await db.get(Device, device_id)
|
||
if device is None:
|
||
raise HTTPException(404, "device not found")
|
||
if device.bound_user_id and device.bound_user_id != user.id:
|
||
raise HTTPException(409, "device already bound to another account")
|
||
|
||
device.bound_user_id = user.id
|
||
device.bound_at = datetime.now(timezone.utc)
|
||
await redis_store.mark_pair_bound(code, str(user.id))
|
||
await db.commit()
|
||
await db.refresh(device)
|
||
return DeviceOut.model_validate(device)
|
||
|
||
|
||
@router.get("/devices", response_model=list[DeviceOut])
|
||
async def list_devices(user: CurrentUser, db: SessionDep) -> list[DeviceOut]:
|
||
rows = (
|
||
await db.execute(
|
||
select(Device)
|
||
.where(Device.bound_user_id == user.id)
|
||
.order_by(Device.bound_at.desc().nulls_last())
|
||
)
|
||
).scalars()
|
||
return [DeviceOut.model_validate(d) for d in rows]
|
||
|
||
|
||
# ---------------------------------------------------------------- TF 卡媒体同步
|
||
# 用户进「TF 卡文件」模块时检查有没有待同步文件;点「立即同步」才下发任务。
|
||
# 设备侧每 15 秒只探一个几字节的状态(seq/ack),不做定时全量同步。
|
||
class MediaPendingItem(BaseModel):
|
||
id: uuid.UUID
|
||
kind: str
|
||
name: str
|
||
size: int
|
||
|
||
|
||
class MediaPendingOut(BaseModel):
|
||
device_id: uuid.UUID
|
||
seq: int
|
||
ack: int
|
||
pending: int # 待下载/更新的文件数
|
||
rev: str # 服务端清单指纹
|
||
synced_rev: str # 设备上次同步完的指纹(不同即有删除/更新)
|
||
items: list[MediaPendingItem]
|
||
|
||
|
||
@router.get("/devices/{device_id}/media/pending", response_model=MediaPendingOut)
|
||
async def media_pending_for_device(
|
||
device_id: uuid.UUID, user: CurrentUser, db: SessionDep
|
||
) -> MediaPendingOut:
|
||
device = await db.get(Device, device_id)
|
||
if device is None or device.bound_user_id != user.id:
|
||
raise HTTPException(404, "device not found")
|
||
|
||
todo, files = await media.pending_for_device(db, device)
|
||
return MediaPendingOut(
|
||
device_id=device.id,
|
||
seq=device.media_sync_seq,
|
||
ack=device.media_sync_ack,
|
||
pending=len(todo),
|
||
rev=media.manifest_rev(files),
|
||
synced_rev=device.media_synced_rev,
|
||
items=[MediaPendingItem(id=f.id, kind=f.kind, name=f.name, size=f.size) for f in todo],
|
||
)
|
||
|
||
|
||
@router.post("/devices/{device_id}/media/sync")
|
||
async def trigger_media_sync(device_id: uuid.UUID, user: CurrentUser, db: SessionDep) -> dict:
|
||
"""用户点了「立即同步」:seq +1,设备下一次探测(≤15 秒)就开始同步。"""
|
||
device = await db.get(Device, device_id)
|
||
if device is None or device.bound_user_id != user.id:
|
||
raise HTTPException(404, "device not found")
|
||
|
||
device.media_sync_seq += 1
|
||
await db.commit()
|
||
return {"ok": True, "seq": device.media_sync_seq}
|
||
|
||
|
||
@router.delete("/devices/{device_id}", response_model=OkOut)
|
||
async def unbind(device_id: uuid.UUID, user: CurrentUser, db: SessionDep) -> OkOut:
|
||
device = await db.get(Device, device_id)
|
||
if device is None or device.bound_user_id != user.id:
|
||
raise HTTPException(404, "device not found")
|
||
|
||
device.bound_user_id = None
|
||
device.bound_at = None
|
||
await db.commit()
|
||
# 立刻吊销:设备下次请求就 401,回落到未绑定态
|
||
n = await redis_store.revoke_device_tokens(str(device_id))
|
||
return OkOut(ok=True, detail=f"revoked {n} token(s)")
|