| 1 | """Client library for RTSPtoWebRTC server.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import base64 |
| 6 | import logging |
| 7 | from typing import Any, List, Mapping, Optional |
| 8 | from urllib.parse import urljoin |
| 9 | |
| 10 | import aiohttp |
| 11 | |
| 12 | from .diagnostics import WEBRTC_DIAGNOSTICS as DIAGNOSTICS |
| 13 | from .exceptions import ClientError, ResponseError |
| 14 | from .interface import WebRTCClientInterface |
| 15 | |
| 16 | _LOGGER = logging.getLogger(__name__) |
| 17 | |
| 18 | STREAM_PATH = "/stream" |
| 19 | HEARTBEAT_PATH = "/static" |
| 20 | DATA_URL = "url" |
| 21 | DATA_SDP64 = "sdp64" |
| 22 | DATA_ERROR = "error" |
| 23 | |
| 24 | |
| 25 | class WebRTCClient(WebRTCClientInterface): |
| 26 | """Client for RTSPtoWebRTC server.""" |
| 27 | |
| 28 | def __init__( |
| 29 | self, websession: aiohttp.ClientSession, server_url: Optional[str] = None |
| 30 | ) -> None: |
| 31 | """Initialize Client.""" |
| 32 | self._session = websession |
| 33 | self._base_url = "" |
| 34 | if server_url: |
| 35 | self._base_url = urljoin(server_url, STREAM_PATH) |
| 36 | |
| 37 | async def offer(self, offer_sdp: str, rtsp_url: str) -> str: |
| 38 | """Send the WebRTC offer to the RTSPtoWebRTC server.""" |
| 39 | return await self.offer_stream_id("ignored", offer_sdp, rtsp_url) |
| 40 | |
| 41 | async def offer_stream_id( |
| 42 | self, |
| 43 | stream_id: str, |
| 44 | offer_sdp: str, |
| 45 | rtsp_url: str, |
| 46 | channel_data: dict[str, Any] | None = None, |
| 47 | ) -> str: |
| 48 | """Send the WebRTC offer to the RTSPtoWebRTC server.""" |
| 49 | _LOGGER.debug("rtsp_url=%s, offer=%s", rtsp_url, offer_sdp) |
| 50 | sdp64 = base64.b64encode(offer_sdp.encode("utf-8")).decode("utf-8") |
| 51 | if channel_data is None: |
| 52 | channel_data = {} |
| 53 | resp = await self._request( |
| 54 | "post", |
| 55 | STREAM_PATH, |
| 56 | data={ |
| 57 | DATA_URL: rtsp_url, |
| 58 | DATA_SDP64: sdp64, |
| 59 | **channel_data, |
| 60 | }, |
| 61 | label="stream", |
| 62 | ) |
| 63 | data = await resp.json() |
| 64 | if DATA_SDP64 not in data: |
| 65 | raise ResponseError( |
| 66 | f"RTSPtoWebRTC server response missing SDP Answer: {resp}" |
| 67 | ) |
| 68 | answer = base64.b64decode(data[DATA_SDP64]).decode("utf-8") |
| 69 | _LOGGER.debug("answer=%s", answer) |
| 70 | return answer |
| 71 | |
| 72 | async def heartbeat(self) -> None: |
| 73 | """Send a request to the server to determine if it is alive.""" |
| 74 | await self._request("get", HEARTBEAT_PATH, label="heartbeat") |
| 75 | |
| 76 | async def _request( |
| 77 | self, |
| 78 | method: str, |
| 79 | path: str, |
| 80 | **kwargs: Optional[Mapping[str, Any]] | str, |
| 81 | ) -> aiohttp.ClientResponse: |
| 82 | url = self._request_url(path) |
| 83 | |
| 84 | label = kwargs["label"] |
| 85 | kwargs.pop("label") |
| 86 | DIAGNOSTICS.increment(f"{label}.request") |
| 87 | |
| 88 | try: |
| 89 | resp = await self._session.request(method, url, **kwargs) |
| 90 | except aiohttp.ClientError as err: |
| 91 | DIAGNOSTICS.increment(f"{label}.client_error") |
| 92 | raise ClientError( |
| 93 | f"RTSPtoWebRTC server communication failure: {err}" |
| 94 | ) from err |
| 95 | |
| 96 | error_detail = await WebRTCClient._error_detail(resp) |
| 97 | try: |
| 98 | resp.raise_for_status() |
| 99 | except aiohttp.ClientResponseError as err: |
| 100 | DIAGNOSTICS.increment(f"{label}.response_error") |
| 101 | error_detail.insert(0, "RTSPtoWebRTC server failure") |
| 102 | error_detail.append(err.message) |
| 103 | raise ResponseError(": ".join(error_detail)) from err |
| 104 | |
| 105 | DIAGNOSTICS.increment(f"{label}.success") |
| 106 | return resp |
| 107 | |
| 108 | def _request_url(self, path: str) -> str: |
| 109 | """Return a request url for the specific path.""" |
| 110 | if not self._base_url: |
| 111 | return path |
| 112 | return urljoin(self._base_url, path) |
| 113 | |
| 114 | @staticmethod |
| 115 | async def _error_detail(resp: aiohttp.ClientResponse) -> List[str]: |
| 116 | """Returns an error message string from the APi response.""" |
| 117 | if resp.status < 400: |
| 118 | return [] |
| 119 | try: |
| 120 | result = await resp.json() |
| 121 | if DATA_ERROR in result: |
| 122 | return [result[DATA_ERROR]] |
| 123 | except aiohttp.ClientError: |
| 124 | return [] |
| 125 | return [] |