Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 3 additions & 82 deletions ring_doorbell/doorbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
DOORBELLS_ENDPOINT,
FILE_EXISTS,
HEALTH_DOORBELL_ENDPOINT,
ICE_SERVERS,
LIVE_STREAMING_ENDPOINT,
MSG_ALLOWED_VALUES,
MSG_BOOLEAN_REQUIRED,
Expand All @@ -50,12 +49,12 @@
)
from ring_doorbell.exceptions import RingError
from ring_doorbell.generic import RingGeneric
from ring_doorbell.webrtcstream import RingWebRtcMessageCallback, RingWebRtcStream
from ring_doorbell.webrtcdevice import RingWebRtcMixin

_LOGGER = logging.getLogger(__name__)


class RingDoorBell(RingGeneric):
class RingDoorBell(RingWebRtcMixin, RingGeneric):
"""Implementation for Ring Doorbell."""

if TYPE_CHECKING:
Expand All @@ -65,7 +64,7 @@ def __init__(self, ring: Ring, device_api_id: int, *, shared: bool = False) -> N
"""Initialise the doorbell."""
super().__init__(ring, device_api_id)
self.shared = shared
self._webrtc_streams: dict[str, RingWebRtcStream] = {}
self._webrtc_streams = {}

@property
def family(self) -> str:
Expand Down Expand Up @@ -453,84 +452,6 @@ async def async_set_motion_detection(self, state: bool) -> None: # noqa: FBT001

await self._ring.async_query(url, method="PATCH", json=payload)

async def generate_webrtc_stream(
self, sdp_offer: str, *, keep_alive_timeout: int | None = 30
) -> str:
"""Generate the rtc stream."""
if session_id := RingWebRtcStream.get_sdp_session_id(sdp_offer):

async def _close_callback() -> None:
await self.close_webrtc_stream(session_id)

stream = RingWebRtcStream(
self._ring,
self.device_api_id,
keep_alive_timeout=keep_alive_timeout,
on_close_callback=_close_callback,
)
sdp_answer = await stream.generate(sdp_offer)
# generate will raise if no sdp answer as no callback passed
assert sdp_answer # noqa: S101
self._webrtc_streams[session_id] = stream
return sdp_answer
msg = "Unable to generate the stream, could not extract session id from offer."
raise RingError(msg)

async def generate_async_webrtc_stream(
self,
sdp_offer: str,
session_id: str,
on_message_callback: RingWebRtcMessageCallback,
*,
keep_alive_timeout: int | None = 60 * 5,
) -> None:
"""Generate the rtc stream. Will callback with answers and ICE candidates."""

async def _close_callback() -> None:
await self.close_webrtc_stream(session_id)

stream = RingWebRtcStream(
self._ring,
self.device_api_id,
on_message_callback=on_message_callback,
keep_alive_timeout=keep_alive_timeout,
on_close_callback=_close_callback,
)
self._webrtc_streams[session_id] = stream
await stream.generate(sdp_offer)

async def on_webrtc_candidate(
self, session_id: str, candidate: str, multi_line_index: int
) -> None:
"""Send an ICE candidate."""
if stream := self._webrtc_streams.get(session_id):
await stream.on_ice_candidate(candidate, multi_line_index)
else:
msg = "Ice candidate received before stream has been created."
raise RingError(msg)

async def close_webrtc_stream(self, session_id: str) -> None:
"""Close the rtc stream."""
stream = self._webrtc_streams.pop(session_id, None)
if stream:
await stream.close()

def sync_close_webrtc_stream(self, session_id: str) -> None:
"""Close the rtc stream."""
stream = self._webrtc_streams.pop(session_id, None)
if stream:
stream.sync_close()

async def keep_alive_webrtc_stream(self, sdp_session_id: str) -> None:
"""Keep alive the rtc stream."""
stream = self._webrtc_streams.get(sdp_session_id, None)
if stream:
await stream.keep_alive()

def get_ice_servers(self) -> list[str]:
"""Return the ICE servers."""
return ICE_SERVERS

DEPRECATED_API_QUERIES: ClassVar = {
*RingGeneric.DEPRECATED_API_QUERIES,
"update_health_data",
Expand Down
4 changes: 3 additions & 1 deletion ring_doorbell/other.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@
)
from ring_doorbell.exceptions import RingError
from ring_doorbell.generic import RingGeneric
from ring_doorbell.webrtcdevice import RingWebRtcMixin

_LOGGER = logging.getLogger(__name__)


class RingOther(RingGeneric):
class RingOther(RingWebRtcMixin, RingGeneric):
"""Implementation for Ring Intercom."""

if TYPE_CHECKING:
Expand All @@ -42,6 +43,7 @@ def __init__(self, ring: Ring, device_api_id: int, *, shared: bool = False) -> N
"""Initialise the other devices."""
super().__init__(ring, device_api_id)
self.shared = shared
self._webrtc_streams = {}

@property
def family(self) -> str:
Expand Down
106 changes: 106 additions & 0 deletions ring_doorbell/webrtcdevice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""WebRTC live-stream support shared by Ring devices that offer live view."""

from __future__ import annotations

from typing import TYPE_CHECKING

from ring_doorbell.const import ICE_SERVERS
from ring_doorbell.exceptions import RingError
from ring_doorbell.webrtcstream import RingWebRtcMessageCallback, RingWebRtcStream

if TYPE_CHECKING:
from ring_doorbell.ring import Ring


class RingWebRtcMixin:
"""WebRTC stream management for devices that support live view.

Used by doorbells/cameras and by intercoms (``RingOther``), which use the
same signalling as cameras.
"""

_ring: Ring
device_api_id: int
_webrtc_streams: dict[str, RingWebRtcStream]

async def generate_webrtc_stream(
self, sdp_offer: str, *, keep_alive_timeout: int | None = 30
) -> str:
"""Generate the rtc stream."""
if session_id := RingWebRtcStream.get_sdp_session_id(sdp_offer):

async def _close_callback() -> None:
# The stream is already closing itself; only forget it.
self._webrtc_streams.pop(session_id, None)

stream = RingWebRtcStream(
self._ring,
self.device_api_id,
keep_alive_timeout=keep_alive_timeout,
on_close_callback=_close_callback,
)
sdp_answer = await stream.generate(sdp_offer)
# generate will raise if no sdp answer as no callback passed
assert sdp_answer # noqa: S101
self._webrtc_streams[session_id] = stream
return sdp_answer
msg = "Unable to generate the stream, could not extract session id from offer."
raise RingError(msg)

async def generate_async_webrtc_stream(
self,
sdp_offer: str,
session_id: str,
on_message_callback: RingWebRtcMessageCallback,
*,
keep_alive_timeout: int | None = 60 * 5,
) -> None:
"""Generate the rtc stream. Will callback with answers and ICE candidates."""

async def _close_callback() -> None:
# Called from the stream's own reader task when Ring ends the
# session. The stream is already closing itself, so only forget
# it: calling close() again would re-enter _close().
self._webrtc_streams.pop(session_id, None)

stream = RingWebRtcStream(
self._ring,
self.device_api_id,
on_message_callback=on_message_callback,
keep_alive_timeout=keep_alive_timeout,
on_close_callback=_close_callback,
)
self._webrtc_streams[session_id] = stream
await stream.generate(sdp_offer)

async def on_webrtc_candidate(
self, session_id: str, candidate: str, multi_line_index: int
) -> None:
"""Send an ICE candidate."""
if stream := self._webrtc_streams.get(session_id):
await stream.on_ice_candidate(candidate, multi_line_index)
else:
msg = "Ice candidate received before stream has been created."
raise RingError(msg)

async def close_webrtc_stream(self, session_id: str) -> None:
"""Close the rtc stream."""
stream = self._webrtc_streams.pop(session_id, None)
if stream:
await stream.close()

def sync_close_webrtc_stream(self, session_id: str) -> None:
"""Close the rtc stream."""
stream = self._webrtc_streams.pop(session_id, None)
if stream:
stream.sync_close()

async def keep_alive_webrtc_stream(self, sdp_session_id: str) -> None:
"""Keep alive the rtc stream."""
stream = self._webrtc_streams.get(sdp_session_id, None)
if stream:
await stream.keep_alive()

def get_ice_servers(self) -> list[str]:
"""Return the ICE servers."""
return ICE_SERVERS
4 changes: 3 additions & 1 deletion ring_doorbell/webrtcstream.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,9 @@ async def _close(self, *, closed_by_self: bool) -> None:
await websocket.close()
if read_task := self.read_task:
self.read_task = None
if not read_task.done():
# When Ring ends the session, _close() runs inside the reader
# task itself; it exits on its own once the websocket is closed.
if not read_task.done() and read_task is not asyncio.current_task():
await read_task

async def handle_message(self, message_str: str) -> None: # noqa: C901, PLR0912
Expand Down
54 changes: 54 additions & 0 deletions tests/test_webrtc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""Tests for WebRTC stream handling shared by doorbells and intercoms."""

import asyncio
from unittest.mock import AsyncMock, MagicMock

from ring_doorbell.doorbot import RingDoorBell
from ring_doorbell.other import RingOther
from ring_doorbell.webrtcdevice import RingWebRtcMixin
from ring_doorbell.webrtcstream import RingWebRtcMessage, RingWebRtcStream


def test_intercom_has_webrtc_methods():
for cls in (RingDoorBell, RingOther):
assert issubclass(cls, RingWebRtcMixin)
for name in (
"generate_webrtc_stream",
"generate_async_webrtc_stream",
"on_webrtc_candidate",
"close_webrtc_stream",
"sync_close_webrtc_stream",
"keep_alive_webrtc_stream",
"get_ice_servers",
):
assert callable(getattr(cls, name))


async def test_server_close_does_not_await_reader_from_itself():
"""Ring's close message is handled inside the reader task.

_close() must not await read_task from within it, and the close reason
must reach the message callback.
"""
messages: list[RingWebRtcMessage] = []
other = RingOther(MagicMock(), 1)
stream = RingWebRtcStream(MagicMock(), 1, on_message_callback=messages.append)

async def _close_callback() -> None:
other._webrtc_streams.pop("session", None)

stream._on_close_callback = _close_callback
stream.websocket = AsyncMock()
stream.is_alive = True
other._webrtc_streams["session"] = stream

async def reader() -> None:
await stream.handle_close_message(
{"body": {"reason": {"code": 1, "text": "bye"}}}
)

stream.read_task = asyncio.create_task(reader())
await stream.read_task

assert "session" not in other._webrtc_streams
assert [(m.error_code, m.error_message) for m in messages] == [(1, "bye")]