"""Our existing UI, forwarded to Deck's native backend; no Docker socket or GPU.""" import asyncio,os from pathlib import Path import httpx from fastapi import FastAPI,Request,WebSocket from fastapi.responses import Response,JSONResponse from fastapi.staticfiles import StaticFiles from websockets.asyncio.client import connect app=FastAPI();BASE='http://127.0.0.1:8134';KEY=Path('/run/secrets/applio-bridge') def headers():return {'X-Applio-Bridge':KEY.read_text().strip()} @app.api_route('/api/{path:path}',methods=['GET','POST','DELETE','PUT','PATCH']) async def proxy(path:str,request:Request): if path.startswith('deck/'):return JSONResponse({'detail':'Interne Deck-Aktion.'},status_code=403) if request.method!='GET': origin=request.headers.get('origin','') if origin and origin.split('://',1)[-1]!=request.headers.get('host'):return JSONResponse({'detail':'Fremder Ursprung.'},status_code=403) if request.headers.get('X-Applio-UI')!='1':return JSONResponse({'detail':'Same-origin control required.'},status_code=403) try: async with httpx.AsyncClient(timeout=180) as client: h=headers() if request.headers.get('content-type'):h['Content-Type']=request.headers['content-type'] body=await request.body() if len(body)>512*1024**2:return JSONResponse({'detail':'Upload zu groß.'},status_code=413) r=await client.request(request.method,BASE+'/api/'+path,params=request.query_params,headers=h,content=body) return Response(r.content,status_code=r.status_code,media_type=r.headers.get('content-type','application/json'),headers={'Cache-Control':'no-store'}) except (OSError,httpx.HTTPError):return JSONResponse({'detail':'Applio-Laufzeit in Athena Deck einrichten; Backend noch nicht erreichbar.'},status_code=503) @app.websocket('/api/realtime/audio') async def realtime(ws:WebSocket): origin=ws.headers.get('origin','') if origin and origin.split('://',1)[-1]!=ws.headers.get('host'):await ws.close(code=1008);return await ws.accept() try: async with connect('ws://127.0.0.1:8134/api/realtime/audio',additional_headers=headers(),max_size=16*1024**2) as upstream: async def incoming(): while True: message=await ws.receive() if message['type']=='websocket.disconnect':return await upstream.send(message.get('bytes') if message.get('bytes') is not None else message.get('text','')) async def outgoing(): async for message in upstream: if isinstance(message,bytes):await ws.send_bytes(message) else:await ws.send_text(message) tasks=[asyncio.create_task(incoming()),asyncio.create_task(outgoing())] try:await asyncio.wait(tasks,return_when=asyncio.FIRST_COMPLETED) finally: for task in tasks:task.cancel() await asyncio.gather(*tasks,return_exceptions=True) except Exception: try:await ws.send_json({'type':'error','value':'Deck-Live-Verbindung unterbrochen.'});await ws.close() except RuntimeError:pass app.mount('/',StaticFiles(directory='/ui/frontend',html=True),name='frontend')