Files

49 lines
1.6 KiB
Python

import asyncio
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from server.services.downloads import downloads
from server.services.huangdou.client import client as huangdou_client
from server.services.huangdou.downloads import downloads as huangdou_downloads
from server.services.dramabox.client import client as dramabox_client
from server.services.dramabox.downloads import downloads as dramabox_downloads
from server.services.live import live
from server.services.sessions import sessions
router = APIRouter()
def _payload(platform: str) -> dict:
if platform == "huangdou":
return {
"downloads": huangdou_downloads.snapshot(),
"profile": huangdou_client.profile or None,
}
if platform == "dramabox":
return {
"downloads": dramabox_downloads.snapshot(),
"profile": dramabox_client.profile or None,
}
profile = sessions.snapshot()
return {
"downloads": downloads.snapshot(),
"profile": profile["profile"] if profile else None,
}
@router.websocket("/api/live")
async def live_socket(websocket: WebSocket):
await websocket.accept()
platform = (websocket.query_params.get("platform") or "rapt").strip() or "rapt"
seen = -1
try:
while True:
revision = await asyncio.to_thread(live.wait, seen, 20)
if revision != seen:
seen = revision
await websocket.send_json(_payload(platform))
else:
await websocket.send_json({"type": "ping"})
except WebSocketDisconnect:
return