Skip to content

Commit

Permalink
Add support HLS mode
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexxIT committed Jul 11, 2023
1 parent 20a1670 commit 4da0e50
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
36 changes: 35 additions & 1 deletion custom_components/webrtc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@

LINKS = {} # 2 3 4

# DDoS protection against requests to HLS proxy
# streams are additionally protected by a random playlist identifier
HLS_COOKIE = "webrtc-hls-session"
HLS_SESSION = str(uuid.uuid4())


async def async_setup(hass: HomeAssistantType, config: ConfigType):
# 1. Serve lovelace card
Expand All @@ -68,7 +73,10 @@ async def async_setup(hass: HomeAssistantType, config: ConfigType):
# 4. Serve WebSocket API
hass.http.register_view(WebSocketView)

# 5. Register webrtc.create_link and webrtc.dash_cast services:
# 5. Serve HLS proxy
hass.http.register_view(HLSView)

# 6. Register webrtc.create_link and webrtc.dash_cast services:

async def create_link(call: ServiceCallType):
link_id = call.data["link_id"]
Expand Down Expand Up @@ -201,6 +209,7 @@ async def get(self, request: web.Request):
raise HTTPUnauthorized()

ws_server = web.WebSocketResponse(autoclose=False, autoping=False)
ws_server.set_cookie(HLS_COOKIE, HLS_SESSION)
await ws_server.prepare(request)

try:
Expand Down Expand Up @@ -235,3 +244,28 @@ async def get(self, request: web.Request):
await ws_server.send_json({"type": "error", "value": str(e)})

return ws_server


class HLSView(HomeAssistantView):
url = "/api/webrtc/hls/{filename}"
name = "api:webrtc:hls"
requires_auth = False

async def get(self, request: web.Request, filename: str):
if request.cookies.get(HLS_COOKIE) != HLS_SESSION:
raise HTTPUnauthorized()

if filename not in ("playlist.m3u8", "init.mp4", "segment.m4s", "segment.ts"):
raise HTTPNotFound()

hass: HomeAssistantType = request.app["hass"]
entry = hass.data[DOMAIN]
url = "http://localhost:1984/" if isinstance(entry, Server) else entry
url = urljoin(url, "api/hls/" + filename) + "?" + request.query_string

async with async_get_clientsession(hass).get(url) as r:
if not r.ok:
raise HTTPNotFound()

body = await r.read()
return web.Response(body=body, content_type=r.content_type)
1 change: 1 addition & 0 deletions custom_components/webrtc/www/webrtc-camera.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ class WebRTCCamera extends VideoRTC {
this.setStatus('error', msg.value);
break;
case 'mse':
case 'hls':
case 'mp4':
case 'mjpeg':
this.setStatus(msg.type.toUpperCase(), this.config.title || '');
Expand Down

0 comments on commit 4da0e50

Please sign in to comment.