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
39 changes: 28 additions & 11 deletions ring_doorbell/listen/eventlistener.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class RingEventListener:
"""Class to connect to firebase cloud messaging."""

SESSION_REFRESH_INTERVAL = 60 * 60 * 12
SESSION_REFRESH_RETRY_INTERVAL = 60 * 5

def __init__(
self,
Expand Down Expand Up @@ -211,11 +212,18 @@ async def _periodic_session_refresh(self) -> None:

if since_refresh > self.SESSION_REFRESH_INTERVAL:
_logger.debug("Refreshing ring session")
await self._ring.async_create_session()
await self.add_subscription_to_ring(self.fcm_token)
break

sleep_for = 1 + time.monotonic() - self._ring.session_refresh_time
try:
await self._ring.async_create_session()
await self.add_subscription_to_ring(self.fcm_token)
except RingError:
_logger.exception(
"Error refreshing ring session, retrying in %s seconds",
self.SESSION_REFRESH_RETRY_INTERVAL,
)
await asyncio.sleep(self.SESSION_REFRESH_RETRY_INTERVAL)
continue

sleep_for = 1 + self.SESSION_REFRESH_INTERVAL - since_refresh
await asyncio.sleep(sleep_for)

def _get_ding_event(self, gcm_data: dict[str, Any]) -> RingEvent:
Expand All @@ -225,7 +233,7 @@ def _get_ding_event(self, gcm_data: dict[str, Any]) -> RingEvent:
if action.lower() == PUSH_ACTION_MOTION.lower():
kind = KIND_MOTION
state = subtype
elif action.lower == PUSH_ACTION_DING.lower():
elif action.lower() == PUSH_ACTION_DING.lower():
kind = KIND_DING
state = "ringing"
else:
Expand Down Expand Up @@ -290,11 +298,20 @@ def _on_notification(
obj: Any | None = None, # noqa: ARG002
) -> None:
msg_data = notification["data"]
if "gcmData" in msg_data:
gcm_data = json.loads(notification["data"]["gcmData"])
ring_event = self._get_legacy_ring_event(gcm_data)
else:
ring_event = self._get_ring_event(msg_data)
try:
if "gcmData" in msg_data:
gcm_data = json.loads(notification["data"]["gcmData"])
ring_event = self._get_legacy_ring_event(gcm_data)
else:
ring_event = self._get_ring_event(msg_data)
except Exception:
# Raising here counts towards the FcmPushClient error limit and
# an unparseable payload should not stop the listener.
_logger.exception(
"Unable to parse fcm message data. Full message is:\n%s",
json.dumps(msg_data),
)
return

if ring_event:
self._check_is_update(ring_event)
Expand Down
3 changes: 3 additions & 0 deletions ring_doorbell/listen/listenerconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,7 @@ def default_config() -> RingEventListenerConfig:
config.server_heartbeat_interval = 60
config.client_heartbeat_interval = 120
config.monitor_interval = 15
# Do not permanently shut down the push client after repeated errors,
# keep resetting the connection instead.
config.abort_on_sequential_error_count = None
return config
72 changes: 72 additions & 0 deletions tests/test_listen.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import datetime
import json
import time

import pytest
from freezegun.api import FrozenDateTimeFactory
Expand Down Expand Up @@ -193,3 +194,74 @@ async def test_listen_fcm_fail(auth, mocker, caplog):
)
== 1
)


async def test_legacy_ding_kind(auth, mocker):
ring = Ring(auth)
listener = RingEventListener(ring)
events = []
listener.add_notification_callback(events.append)

msg = load_alert_v1("doorbot_ding", 123456781)
listener._on_notification(msg, "12345671")

assert len(events) == 1
assert events[0].kind == "ding"
assert events[0].state == "ringing"


async def test_unparseable_notification_does_not_raise(auth, mocker, caplog):
ring = Ring(auth)
listener = RingEventListener(ring)
events = []
listener.add_notification_callback(events.append)

msg = load_alert_v2("camera_motion", 123456782)
data = json.loads(msg["data"]["data"])
del data["event"]["ding"]["id"]
msg["data"]["data"] = json.dumps(data)

listener._on_notification(msg, "12345671")

assert events == []
assert "Unable to parse fcm message data" in caplog.text

# The listener keeps processing subsequent valid notifications
listener._on_notification(load_alert_v2("camera_motion", 123456782), "12345672")
assert len(events) == 1


async def test_default_config_does_not_abort_on_errors(auth):
listener = RingEventListener(Ring(auth))
assert listener._config.abort_on_sequential_error_count is None


async def test_periodic_session_refresh_repeats(auth, mocker, caplog):
ring = Ring(auth)
listener = RingEventListener(ring)
listener.SESSION_REFRESH_INTERVAL = -1
listener.SESSION_REFRESH_RETRY_INTERVAL = 0
listener.started = True
listener.fcm_token = "foobar"
ring.session_refresh_time = time.monotonic()

calls = 0

async def _create_session() -> None:
nonlocal calls
calls += 1
if calls == 1:
msg = "Session error"
raise RingError(msg)
ring.session_refresh_time = time.monotonic()
if calls == 3:
listener.started = False

mocker.patch.object(ring, "async_create_session", side_effect=_create_session)
subscribe = mocker.patch.object(listener, "add_subscription_to_ring")

await listener._periodic_session_refresh()

assert calls == 3
assert subscribe.call_count == 2
assert "Error refreshing ring session" in caplog.text