From c3322b5d62e4ef8b48f0dd89bbe53e903ee3a429 Mon Sep 17 00:00:00 2001 From: Felipe Santos Date: Sun, 23 Apr 2023 14:28:12 -0300 Subject: [PATCH] Add `/api/webrtc/camera_stream_source` --- custom_components/webrtc/__init__.py | 27 ++++++++++++++++++++++++++ custom_components/webrtc/manifest.json | 3 ++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/custom_components/webrtc/__init__.py b/custom_components/webrtc/__init__.py index 6f488ef..d208700 100644 --- a/custom_components/webrtc/__init__.py +++ b/custom_components/webrtc/__init__.py @@ -10,6 +10,8 @@ import voluptuous as vol from aiohttp import web from aiohttp.web_exceptions import HTTPUnauthorized, HTTPGone, HTTPNotFound +from homeassistant.components.camera import Camera, CameraView +from homeassistant.components.camera.const import DOMAIN as CAMERA_DOMAIN from homeassistant.components.hassio.ingress import _websocket_forward from homeassistant.components.http import HomeAssistantView from homeassistant.config_entries import ConfigEntry @@ -19,6 +21,7 @@ CONF_URL, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.network import get_url from homeassistant.helpers.template import Template from homeassistant.helpers.typing import HomeAssistantType, ConfigType, ServiceCallType @@ -113,6 +116,15 @@ async def dash_cast(call: ServiceCallType): hass.services.async_register(DOMAIN, "create_link", create_link, CREATE_LINK_SCHEMA) hass.services.async_register(DOMAIN, "dash_cast", dash_cast, DASH_CAST_SCHEMA) + # 7. Serve camera_stream_source API + camera_component: EntityComponent[Camera] = hass.data[CAMERA_DOMAIN] + + if camera_component is None: + _LOGGER.error("Camera integration not initialized") + return False + + hass.http.register_view(CameraStreamSourceView(camera_component)) + return True @@ -266,3 +278,18 @@ async def get(self, request: web.Request, filename: str): body = await r.read() return web.Response(body=body, content_type=r.content_type) + + +class CameraStreamSourceView(CameraView): + """Camera view to get the stream source.""" + + url = "/api/webrtc/camera_stream_source/{entity_id}" + name = "api:webrtc:camera_stream_source" + requires_auth = True + + async def handle(self, request: web.Request, camera: Camera) -> web.Response: + """Return the camera stream source as plain text.""" + stream_source = await camera.stream_source() + if stream_source is None: + raise web.HTTPNotFound() + return web.Response(text=stream_source) diff --git a/custom_components/webrtc/manifest.json b/custom_components/webrtc/manifest.json index 202d42a..c93a639 100644 --- a/custom_components/webrtc/manifest.json +++ b/custom_components/webrtc/manifest.json @@ -9,7 +9,8 @@ ], "dependencies": [ "http", - "lovelace" + "lovelace", + "camera" ], "requirements": [], "version": "v3.3.0",