from uuid import UUID, uuid4 import fastapi from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.templating import Jinja2Templates from pydantic import BaseModel import uvicorn app = fastapi.FastAPI(debug=True) templates = Jinja2Templates(directory="templates") calls = {} class CallPostResponse(BaseModel): call_id: UUID @app.post("/call") async def create_call() -> CallPostResponse: call_id = uuid4() calls[call_id] = {} return CallPostResponse(call_id=call_id) @app.get("/call", response_class=HTMLResponse) async def call(request: fastapi.Request, call_id: UUID = fastapi.Query(), session_id: UUID | None = fastapi.Cookie(None)): if not session_id: session_id = uuid4() response = RedirectResponse(f"/call?call_id={call_id}") response.set_cookie("session_id", str(session_id)) return response if call_id not in calls: return RedirectResponse("/") return templates.TemplateResponse( "call.html", context={"request": request} ) @app.websocket("/connect") async def connect(websocket: fastapi.WebSocket, call_id: UUID = fastapi.Query(), session_id: UUID | None = fastapi.Cookie(None)): await websocket.accept() calls[call_id][session_id] = websocket another_websocket: fastapi.WebSocket | None = None while True: data = await websocket.receive_bytes() print("RECEIVED") if not another_websocket: if len(calls[call_id]) == 1: continue for sess_id, ws in calls[call_id].items(): if sess_id != session_id: another_websocket = ws print("SENDING DATA") await another_websocket.send_bytes(data) @app.get("/", response_class=HTMLResponse) async def home(request: fastapi.Request): return templates.TemplateResponse( "index.html", context={"request": request} ) if __name__ == '__main__': uvicorn.run(app, host="0.0.0.0", port=1239)