|
|
|
|
|
from fastapi import FastAPI, WebSocket, WebSocketDisconnect |
|
|
from fastapi.middleware.cors import CORSMiddleware |
|
|
|
|
|
import json |
|
|
import re |
|
|
|
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.websocket("/ws") |
|
|
async def websocket_endpoint(websocket: WebSocket): |
|
|
await websocket.accept() |
|
|
print("β
WebSocket connected for RPC") |
|
|
|
|
|
try: |
|
|
while True: |
|
|
|
|
|
message = await websocket.receive_text() |
|
|
print("π© Received:", message) |
|
|
|
|
|
try: |
|
|
rpc = json.loads(message) |
|
|
result = handle_rpc(rpc) |
|
|
|
|
|
response = json.dumps({ |
|
|
"jsonrpc": "2.0", |
|
|
"id": rpc["id"], |
|
|
"result": result, |
|
|
}) |
|
|
|
|
|
|
|
|
await websocket.send_text(response) |
|
|
|
|
|
except json.JSONDecodeError: |
|
|
print(f"Error decoding RPC message: {message}") |
|
|
|
|
|
except WebSocketDisconnect: |
|
|
print("π WebSocket disconnected.") |
|
|
|
|
|
|
|
|
|
|
|
def handle_rpc(rpc): |
|
|
method = rpc.get("method") |
|
|
params = rpc.get("params", {}) |
|
|
|
|
|
if method == "echo": |
|
|
return params.get("message", "") |
|
|
|
|
|
elif method == "process": |
|
|
message = params.get("message", "").lower() |
|
|
|
|
|
|
|
|
match = re.match(r"add (\d+) and (\d+)", message) |
|
|
if match: |
|
|
x, y = map(int, match.groups()) |
|
|
return x + y |
|
|
|
|
|
|
|
|
match = re.match(r"subtract (\d+) from (\d+)", message) |
|
|
if match: |
|
|
y, x = map(int, match.groups()) |
|
|
return x - y |
|
|
|
|
|
|
|
|
match = re.match(r"multiply (\d+) and (\d+)", message) |
|
|
if match: |
|
|
x, y = map(int, match.groups()) |
|
|
return x * y |
|
|
|
|
|
|
|
|
match = re.match(r"divide (\d+) by (\d+)", message) |
|
|
if match: |
|
|
x, y = map(int, match.groups()) |
|
|
return round(x / y, 2) if y != 0 else "Division by zero" |
|
|
|
|
|
return "Unknown command" |
|
|
|
|
|
else: |
|
|
return "Unknown method" |
|
|
|
|
|
|
|
|
print("β
FastAPI WebRTC backend with TURN is ready") |
|
|
|