518 lines
19 KiB
Python
518 lines
19 KiB
Python
"""设备端接口 ``/device/v1``:配对码、换 token、资料、天气、星盘、固件升级。
|
||
|
||
约定:除 ``pair/*`` 外全部要求 ``Authorization: Bearer <device_id>:<secret>``。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import uuid
|
||
from datetime import datetime, timezone
|
||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||
|
||
from fastapi import APIRouter, HTTPException, Query, Request, status
|
||
from fastapi.responses import FileResponse
|
||
from pydantic import BaseModel
|
||
from sqlalchemy import select
|
||
|
||
from app.api.deps import CurrentDevice, SessionDep, user_of_device
|
||
from app.core.config import settings
|
||
from app.core.security import (
|
||
new_pair_code,
|
||
new_token,
|
||
new_web_login_code,
|
||
normalize_pair_code,
|
||
token_hash,
|
||
)
|
||
from app.models import Device, Firmware, MediaFile, User
|
||
from app.schemas.auth import (
|
||
PairClaimIn,
|
||
PairClaimOut,
|
||
PairCodeIn,
|
||
PairCodeOut,
|
||
PairStatusOut,
|
||
UserOut,
|
||
user_out,
|
||
)
|
||
from app.schemas.firmware import CheckOut
|
||
from app.services import catalog, firmware, fortune, media, redis_store, weather
|
||
|
||
router = APIRouter(prefix="/device/v1", tags=["device"])
|
||
|
||
|
||
def _now_iso() -> str:
|
||
return datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")
|
||
|
||
|
||
@router.post("/pair/code", response_model=PairCodeOut)
|
||
async def issue_pair_code(body: PairCodeIn, db: SessionDep) -> PairCodeOut:
|
||
"""设备开机进绑定页时调用:登记芯片指纹并拿到 6 位码。
|
||
|
||
码可以由设备自己生成(屏显逻辑在固件侧),也可以让服务端生成——
|
||
服务端生成的好处是不可预测、便于限流。
|
||
"""
|
||
chip_id = body.chip_id.strip().upper()
|
||
if len(chip_id) < 12:
|
||
raise HTTPException(400, "chip_id too short")
|
||
|
||
device = await db.scalar(select(Device).where(Device.chip_id == chip_id))
|
||
if device is None:
|
||
device = Device(chip_id=chip_id, model=body.model, fw_version=body.fw_version)
|
||
db.add(device)
|
||
await db.commit()
|
||
await db.refresh(device)
|
||
elif body.fw_version and device.fw_version != body.fw_version:
|
||
device.fw_version = body.fw_version
|
||
await db.commit()
|
||
|
||
if device.bound_user_id:
|
||
raise HTTPException(409, "device already bound; unbind it in the web portal first")
|
||
|
||
code = normalize_pair_code(body.code or "") or new_pair_code()
|
||
if len(code) != 6:
|
||
raise HTTPException(400, "pairing code must be 6 digits")
|
||
|
||
await redis_store.put_pair(
|
||
code,
|
||
{"device_id": str(device.id), "chip_id": chip_id},
|
||
ttl=settings.pair_code_ttl_seconds,
|
||
)
|
||
return PairCodeOut(code=code, expires_in=settings.pair_code_ttl_seconds, server_time=_now_iso())
|
||
|
||
|
||
@router.get("/pair/status", response_model=PairStatusOut)
|
||
async def pair_status(
|
||
code: str = Query(..., min_length=6, max_length=6),
|
||
chip_id: str = Query(...),
|
||
) -> PairStatusOut:
|
||
"""绑定页内每 5 秒检查一次(不属全局轮询)。"""
|
||
code = normalize_pair_code(code)
|
||
payload = await redis_store.get_pair(code)
|
||
if not payload:
|
||
# 码已经消费完(claim 之后)也算已绑定,但正常流程不会走到这里
|
||
return PairStatusOut(status="expired")
|
||
if payload.get("chip_id") and payload["chip_id"].upper() != chip_id.strip().upper():
|
||
raise HTTPException(403, "code does not belong to this device")
|
||
if payload.get("bound_user_id"):
|
||
return PairStatusOut(status="bound")
|
||
return PairStatusOut(status="waiting")
|
||
|
||
|
||
@router.post("/pair/claim", response_model=PairClaimOut)
|
||
async def pair_claim(body: PairClaimIn, db: SessionDep) -> PairClaimOut:
|
||
"""码被网页消费后 2 分钟内,设备凭码换长期 token。"""
|
||
code = normalize_pair_code(body.code)
|
||
payload = await redis_store.get_pair(code)
|
||
if not payload:
|
||
raise HTTPException(404, "code expired")
|
||
|
||
chip_id = body.chip_id.strip().upper()
|
||
if payload.get("chip_id", "").upper() != chip_id:
|
||
raise HTTPException(403, "code does not belong to this device")
|
||
|
||
user_id = payload.get("bound_user_id")
|
||
if not user_id:
|
||
raise HTTPException(status.HTTP_409_CONFLICT, "code not claimed by any account yet")
|
||
|
||
device = await db.get(Device, payload["device_id"])
|
||
if device is None:
|
||
raise HTTPException(404, "device not found")
|
||
|
||
user = await db.get(User, user_id)
|
||
if user is None or user.status != "active":
|
||
raise HTTPException(403, "account unavailable")
|
||
|
||
# 一码一机:换 token 同时作废旧 token
|
||
await redis_store.revoke_device_tokens(str(device.id))
|
||
secret = new_token()
|
||
await redis_store.save_device_token(str(device.id), token_hash(secret))
|
||
await redis_store.consume_pair(code)
|
||
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
|
||
return PairClaimOut(
|
||
token=f"{device.id}:{secret}",
|
||
device_id=device.id,
|
||
user=user_out(user, await catalog.zodiac_map(db)),
|
||
)
|
||
|
||
|
||
@router.get("/ping")
|
||
async def ping(device: CurrentDevice, db: SessionDep) -> dict:
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
return {"ok": True, "ts": _now_iso()}
|
||
|
||
|
||
@router.get("/profile", response_model=UserOut)
|
||
async def profile(device: CurrentDevice, db: SessionDep) -> UserOut:
|
||
user = await user_of_device(device, db)
|
||
if user is None:
|
||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "device not bound")
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
return user_out(user, await catalog.zodiac_map(db))
|
||
|
||
|
||
@router.get("/weather")
|
||
async def get_weather(
|
||
device: CurrentDevice,
|
||
db: SessionDep,
|
||
city: str | None = Query(default=None, description="不传则用账号资料里的出生城市"),
|
||
) -> dict:
|
||
user = await user_of_device(device, db)
|
||
if user is None:
|
||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "device not bound")
|
||
|
||
# 日常天气优先用居住地,没填再退到出生地
|
||
target = (city or user.residence_city or user.birth_city or settings.default_city).strip()
|
||
try:
|
||
data = await weather.now(db, target)
|
||
except weather.WeatherNotConfigured as exc:
|
||
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, str(exc)) from exc
|
||
except weather.WeatherUpstreamError as exc:
|
||
raise HTTPException(status.HTTP_502_BAD_GATEWAY, str(exc)) from exc
|
||
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
return data
|
||
|
||
|
||
async def _user_effective_tz(db, user: User) -> str:
|
||
"""「今天/本月」用哪个时区:用户显式设置 > 居住地码表时区 > 内地标准时。"""
|
||
if user.timezone:
|
||
return user.timezone
|
||
if user.residence_region_code:
|
||
_city, _place, tz = await catalog.resolve_place(db, user.residence_region_code)
|
||
return tz
|
||
return "Asia/Shanghai"
|
||
|
||
|
||
@router.get("/astro")
|
||
async def device_astro(
|
||
device: CurrentDevice,
|
||
db: SessionDep,
|
||
lang: str = Query(default="zh", pattern="^(zh|en)$"),
|
||
) -> dict:
|
||
"""星盘:太阳/月亮星座 + 当月运势。
|
||
|
||
「当月」按用户居住时区算,跨界(比如 12 月 31 日 23 点)不串月。
|
||
运势文案支持中英文,取值顺序:管理端指定年月 → 管理端通用月度 → 内置模板。
|
||
"""
|
||
user = await user_of_device(device, db)
|
||
if user is None:
|
||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "device not bound")
|
||
|
||
tz_name = await _user_effective_tz(db, user)
|
||
try:
|
||
tz = ZoneInfo(tz_name)
|
||
except ZoneInfoNotFoundError:
|
||
tz = ZoneInfo("Asia/Shanghai")
|
||
local_now = datetime.now(timezone.utc).astimezone(tz)
|
||
year, month = local_now.year, local_now.month
|
||
|
||
zmap = await catalog.zodiac_map(db)
|
||
lang = "en" if lang == "en" else "zh"
|
||
|
||
def pack(kind: str) -> dict | None:
|
||
code = getattr(user, f"{kind}_sign", None)
|
||
if not code:
|
||
return None
|
||
info = zmap.get(code, {})
|
||
name = info.get("name_en") if lang == "en" and info.get("name_en") else info.get("name_cn", code)
|
||
return {
|
||
"code": code,
|
||
"name": name,
|
||
"symbol": info.get("symbol", ""),
|
||
"element": info.get("element", ""),
|
||
"degree": float(getattr(user, f"{kind}_degree", 0) or 0),
|
||
"date_range": info.get("date_range", ""),
|
||
}
|
||
|
||
sun, moon = pack("sun"), pack("moon")
|
||
|
||
# 运势跟随月亮星座更准(月亮掌管情绪与内在),没月亮就退太阳
|
||
fortune_sign = user.moon_sign or user.sun_sign
|
||
f_data = await fortune.for_user(db, fortune_sign, year, month, lang)
|
||
if f_data is None and fortune_sign:
|
||
info = zmap.get(fortune_sign, {})
|
||
sign_name = info.get("name_en") if lang == "en" and info.get("name_en") else info.get("name_cn", fortune_sign)
|
||
f_data = fortune.generic_fortune(sign_name, info.get("element", ""), month, lang)
|
||
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
return {
|
||
"ok": True,
|
||
"lang": lang,
|
||
"timezone": tz_name,
|
||
"local_time": local_now.isoformat(timespec="seconds"),
|
||
"period": f"{year}-{month:02d}",
|
||
"sun": sun,
|
||
"moon": moon,
|
||
"fortune_sign": fortune_sign,
|
||
"fortune": f_data,
|
||
}
|
||
|
||
|
||
# ------------------------------------------------------------------ 固件升级
|
||
@router.get("/firmware/check", response_model=CheckOut)
|
||
async def check_firmware(
|
||
device: CurrentDevice,
|
||
db: SessionDep,
|
||
current: str | None = Query(default=None, description="设备当前版本,不传则用库里的 fw_version"),
|
||
lang: str = Query(default="zh", pattern="^(zh|en)$"),
|
||
) -> CheckOut:
|
||
"""设备开机/定时来问一句:我要不要升级。
|
||
|
||
``url`` 给的是**相对路径**——设备拼自己的 serverUrl,换域名/换端口都不用改库里数据。
|
||
"""
|
||
cur = (current or device.fw_version or "").strip()
|
||
if current and current != device.fw_version:
|
||
device.fw_version = current
|
||
await db.commit()
|
||
|
||
fw, forced = await firmware.resolve_for_device(db, device)
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
|
||
if fw is None or not fw.published:
|
||
return CheckOut(update=False)
|
||
|
||
# 自动更新只升不降;管理员点名时允许回滚
|
||
if not forced and firmware.compare(fw.version, cur) <= 0:
|
||
return CheckOut(update=False)
|
||
|
||
return CheckOut(
|
||
update=True,
|
||
version=fw.version,
|
||
size=fw.size_bytes,
|
||
sha256=fw.sha256,
|
||
notes=(fw.notes_en if lang == "en" and fw.notes_en else fw.notes),
|
||
url=f"/device/v1/firmware/{fw.id}/download",
|
||
mandatory=forced,
|
||
reason="forced" if forced else "newer",
|
||
)
|
||
|
||
|
||
@router.get("/firmware/{firmware_id}/download")
|
||
async def download_firmware(firmware_id: uuid.UUID, device: CurrentDevice, db: SessionDep):
|
||
"""下发 bin 本体。
|
||
|
||
只有已发布的包能下;下发给点名设备时,目标包即使下线了也放行——
|
||
否则管理员刚点了「下线」,设备正在下载就 404 了。
|
||
"""
|
||
fw = await db.get(Firmware, firmware_id)
|
||
if fw is None:
|
||
raise HTTPException(404, "firmware not found")
|
||
forced = device.target_firmware_id == fw.id
|
||
if not fw.published and not forced:
|
||
raise HTTPException(404, "firmware not published")
|
||
|
||
path = firmware.path_of(fw)
|
||
if not path.exists():
|
||
raise HTTPException(410, "firmware file missing on server")
|
||
|
||
fw.download_count += 1
|
||
device.upgrade_state = "downloading"
|
||
device.target_firmware_id = fw.id
|
||
device.target_version = fw.version
|
||
device.upgrade_at = datetime.now(timezone.utc)
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
|
||
return FileResponse(
|
||
path,
|
||
media_type="application/octet-stream",
|
||
filename=f"knob_os-{fw.version}.bin",
|
||
headers={"X-Firmware-Version": fw.version, "X-Firmware-Sha256": fw.sha256},
|
||
)
|
||
|
||
|
||
class ReportIn(BaseModel):
|
||
version: str
|
||
status: str = "success" # success | failed
|
||
error: str = ""
|
||
slot: str = ""
|
||
|
||
|
||
@router.post("/firmware/report")
|
||
async def report_firmware(body: ReportIn, device: CurrentDevice, db: SessionDep) -> dict:
|
||
"""设备升级完(或失败)回报一句,管理端据此判断这轮推没推成功。"""
|
||
ok = body.status == "success"
|
||
device.upgrade_state = "success" if ok else "failed"
|
||
device.upgrade_error = "" if ok else (body.error or "unknown")[:160]
|
||
device.upgrade_at = datetime.now(timezone.utc)
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
if body.slot:
|
||
device.boot_slot = body.slot[:8]
|
||
|
||
if ok:
|
||
if body.version and body.version != device.fw_version:
|
||
device.fw_version = body.version[:32]
|
||
device.fw_updated_at = datetime.now(timezone.utc)
|
||
# 任务完成即清目标,否则下次 check 还会把同一版再推一遍
|
||
device.target_firmware_id = None
|
||
device.target_version = ""
|
||
|
||
await db.commit()
|
||
return {"ok": True, "state": device.upgrade_state}
|
||
|
||
|
||
# ------------------------------------------------------------------ 扫码登录 Web
|
||
class WebLoginOut(BaseModel):
|
||
"""设备屏上的二维码内容:手机打开 url 即自动登录该设备的绑定账号。"""
|
||
|
||
code: str
|
||
url: str
|
||
expires_in: int
|
||
|
||
|
||
def _web_base(request: Request) -> str:
|
||
"""手机要打开的 Web 基地址。
|
||
|
||
不再单独配置:设备里配的「服务端地址」就是它请求我们的 Host,同域拼接天然
|
||
正确(正式部署 Web 与 API 同一个入口)。只有两种情况需要干预:
|
||
|
||
* 前后端分离开发:设备直连 API 端口(.env 的 ``BACKEND_PORT``,默认 8100),
|
||
页面在 ``FRONTEND_PORT``(默认 5174),按这两个端口换算;
|
||
* Web 与 API 真的不同域(CDN 等):用 .env 的 ``WEB_BASE_URL`` 覆盖。
|
||
"""
|
||
base = settings.web_base_url.strip()
|
||
if base:
|
||
return base.rstrip("/")
|
||
|
||
url = request.url
|
||
host = url.hostname or "127.0.0.1"
|
||
port = url.port
|
||
if port == settings.backend_port:
|
||
port = settings.frontend_port
|
||
if port and port not in (80, 443):
|
||
return f"{url.scheme}://{host}:{port}"
|
||
return f"{url.scheme}://{host}"
|
||
|
||
|
||
@router.post("/web-login/ticket", response_model=WebLoginOut)
|
||
async def web_login_ticket(device: CurrentDevice, request: Request, db: SessionDep) -> WebLoginOut:
|
||
"""「我的」页下拉时调用:拿一张一次性票据,编成二维码给手机扫。
|
||
|
||
票据只对当前设备的绑定账号有效、一码一用、5 分钟过期;屏幕上重新打开
|
||
二维码会换新码,旧码随之失效。
|
||
"""
|
||
user = await user_of_device(device, db)
|
||
if user is None or user.status != "active":
|
||
raise HTTPException(status.HTTP_409_CONFLICT, "device not bound to an active user")
|
||
|
||
code = new_web_login_code()
|
||
ttl = settings.web_login_ttl_seconds
|
||
await redis_store.put_web_login(code, str(user.id), str(device.id), ttl)
|
||
base = _web_base(request)
|
||
return WebLoginOut(code=code, url=f"{base}/qr?t={code}", expires_in=ttl)
|
||
|
||
|
||
# ------------------------------------------------------------------ TF 卡媒体同步
|
||
class ManifestItem(BaseModel):
|
||
id: uuid.UUID
|
||
kind: str
|
||
name: str
|
||
size: int
|
||
crc32: int
|
||
url: str
|
||
|
||
|
||
class MediaManifestOut(BaseModel):
|
||
rev: str
|
||
items: list[ManifestItem]
|
||
|
||
|
||
class MediaStateOut(BaseModel):
|
||
"""轻量状态:设备进入音乐/相册模块时查一次,决定要不要弹「同步」提示。
|
||
|
||
``rev`` 是服务端当前清单指纹,``synced_rev`` 是设备上次同步完回报的指纹;
|
||
设备拿它跟自己 TF 卡上的本地清单 rev 对比,清单变了(删除/改名)也会提示。
|
||
"""
|
||
|
||
seq: int # 兼容字段:网页触发时代的计数,设备侧同步不再依赖
|
||
ack: int # 兼容字段:同上
|
||
pending: int # 清单里有、设备还没同步的文件数(不分类型,总口径)
|
||
pending_pic: int = 0 # 其中图片数:相册弹窗只报这个,别把音乐混进去
|
||
pending_music: int = 0 # 其中音乐数:同上
|
||
rev: str = "" # 服务端当前清单指纹
|
||
synced_rev: str = "" # 设备上次同步时的清单指纹
|
||
|
||
|
||
@router.get("/media/pending", response_model=MediaStateOut)
|
||
async def media_pending(device: CurrentDevice, db: SessionDep) -> MediaStateOut:
|
||
"""设备进入音乐/相册时查:有没有文件要同步。
|
||
|
||
响应几百字节;``pending > 0`` 或 ``rev != synced_rev`` 都算「有待同步」,
|
||
设备据此弹确认框,用户同意才拉 manifest 开始同步。
|
||
"""
|
||
todo, files = await media.pending_for_device(db, device)
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
return MediaStateOut(
|
||
seq=device.media_sync_seq,
|
||
ack=device.media_sync_ack,
|
||
pending=len(todo),
|
||
pending_pic=sum(1 for f in todo if f.kind == "pic"),
|
||
pending_music=sum(1 for f in todo if f.kind == "music"),
|
||
rev=media.manifest_rev(files),
|
||
synced_rev=device.media_synced_rev,
|
||
)
|
||
|
||
|
||
@router.get("/media/manifest", response_model=MediaManifestOut)
|
||
async def media_manifest(device: CurrentDevice, db: SessionDep) -> MediaManifestOut:
|
||
"""设备要同步的媒体清单(绑定用户的全量库,设备自己 diff 增量)。
|
||
|
||
``rev`` 是整份清单的指纹:设备可以用它快速判断「清单变没变」,
|
||
没变就不用逐条比对了;同步完成后原样回报,服务端据此判断是否最新。
|
||
"""
|
||
files = await media.manifest_for_device(db, device)
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
|
||
items = [
|
||
ManifestItem(
|
||
id=mf.id,
|
||
kind=mf.kind,
|
||
name=mf.name,
|
||
size=mf.size,
|
||
crc32=mf.crc32,
|
||
url=f"/device/v1/media/{mf.id}/file",
|
||
)
|
||
for mf in files
|
||
]
|
||
return MediaManifestOut(rev=media.manifest_rev(files), items=items)
|
||
|
||
|
||
@router.get("/media/{media_id}/file")
|
||
async def media_download(media_id: uuid.UUID, device: CurrentDevice, db: SessionDep):
|
||
"""下发媒体文件本体。只放行绑定用户自己的库,防止跨账号拖文件。"""
|
||
mf = await db.get(MediaFile, media_id)
|
||
if mf is None or mf.owner_user_id != device.bound_user_id:
|
||
raise HTTPException(404, "media not found")
|
||
path = media.path_of(mf)
|
||
if not path.exists():
|
||
raise HTTPException(410, "file missing on server")
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
return FileResponse(path, media_type="application/octet-stream", filename=mf.name)
|
||
|
||
|
||
class MediaReportIn(BaseModel):
|
||
synced: list[uuid.UUID] = []
|
||
deleted: list[uuid.UUID] = []
|
||
# 这一轮处理的是第几次同步请求、清单指纹是什么——游标推进靠它们
|
||
seq: int = 0
|
||
rev: str = ""
|
||
|
||
|
||
@router.post("/media/report")
|
||
async def media_report(body: MediaReportIn, device: CurrentDevice, db: SessionDep) -> dict:
|
||
"""设备同步完(或删完)回报:网页端据此显示每台设备的同步状态。"""
|
||
await media.apply_report(db, device, body.synced, body.deleted, body.seq, body.rev)
|
||
device.last_active_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
return {"ok": True, "synced": len(body.synced), "deleted": len(body.deleted), "ack": device.media_sync_ack}
|