Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
|
3 |
+
from fastapi.responses import HTMLResponse
|
4 |
+
from fastapi.staticfiles import StaticFiles
|
5 |
+
from fastrtc import RTCRoom, RTCRoomManager
|
6 |
+
from fastapi.templating import Jinja2Templates
|
7 |
+
import uuid
|
8 |
+
import json
|
9 |
+
|
10 |
+
app = FastAPI()
|
11 |
+
room_manager = RTCRoomManager()
|
12 |
+
|
13 |
+
app.mount("/static", StaticFiles(directory="static"), name="static") # Mount static files
|
14 |
+
templates = Jinja2Templates(directory="templates") # Mount templates
|
15 |
+
|
16 |
+
@app.get("/", response_class=HTMLResponse)
|
17 |
+
async def read_root(request: Request):
|
18 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
19 |
+
|
20 |
+
@app.websocket("/ws/{room_id}/{client_id}")
|
21 |
+
async def websocket_endpoint(websocket: WebSocket, room_id: str, client_id: str):
|
22 |
+
await websocket.accept()
|
23 |
+
room = room_manager.get_or_create_room(room_id)
|
24 |
+
peer = await room.join(client_id, websocket)
|
25 |
+
|
26 |
+
try:
|
27 |
+
while True:
|
28 |
+
message = await websocket.receive_text()
|
29 |
+
data = json.loads(message)
|
30 |
+
if data["type"] == "offer" or data["type"] == "answer" or data["type"] == "candidate":
|
31 |
+
await peer.handle_sdp(data)
|
32 |
+
else:
|
33 |
+
print(f"Received unknown message: {data}")
|
34 |
+
|
35 |
+
except WebSocketDisconnect:
|
36 |
+
await room.leave(client_id)
|
37 |
+
print(f"Client {client_id} disconnected from room {room_id}")
|