Fix CORS: proxy WebRTC requests through backend
This commit is contained in:
41
app/main.py
41
app/main.py
@@ -7,14 +7,18 @@ import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import AsyncGenerator
|
||||
|
||||
import httpx
|
||||
import aiomqtt
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from fastapi.responses import HTMLResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
|
||||
from .config import settings
|
||||
|
||||
# HTTP client for proxying to go2rtc
|
||||
http_client = httpx.AsyncClient(timeout=10.0)
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -139,6 +143,41 @@ async def events() -> StreamingResponse:
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/webrtc")
|
||||
async def webrtc_proxy(request: Request, src: str):
|
||||
"""Proxy WebRTC offers to go2rtc to avoid CORS issues"""
|
||||
try:
|
||||
body = await request.body()
|
||||
response = await http_client.post(
|
||||
f"http://{settings.GO2RTC_HOST}/api/webrtc?src={src}",
|
||||
content=body,
|
||||
headers={"Content-Type": "application/sdp"}
|
||||
)
|
||||
return Response(
|
||||
content=response.content,
|
||||
status_code=response.status_code,
|
||||
media_type="application/sdp"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"WebRTC proxy error for {src}: {e}")
|
||||
return Response(content=str(e), status_code=500)
|
||||
|
||||
|
||||
@app.get("/api/streams")
|
||||
async def streams_proxy():
|
||||
"""Proxy streams list from go2rtc"""
|
||||
try:
|
||||
response = await http_client.get(f"http://{settings.GO2RTC_HOST}/api/streams")
|
||||
return Response(
|
||||
content=response.content,
|
||||
status_code=response.status_code,
|
||||
media_type="application/json"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Streams proxy error: {e}")
|
||||
return Response(content=str(e), status_code=500)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
"""Health check endpoint"""
|
||||
|
||||
Reference in New Issue
Block a user