python-ring 0.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,449 @@
1
+ """Module for listening to firebase cloud messages and updating dings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import logging
8
+ import time
9
+ from contextlib import suppress
10
+ from typing import TYPE_CHECKING, Any, Callable
11
+
12
+ from async_timeout import timeout as asyncio_timeout
13
+ from firebase_messaging import FcmPushClient, FcmRegisterConfig
14
+
15
+ from python_ring.const import (
16
+ API_URI,
17
+ API_VERSION,
18
+ DEFAULT_LISTEN_EVENT_EXPIRES_IN,
19
+ FCM_API_KEY,
20
+ FCM_APP_ID,
21
+ FCM_PROJECT_ID,
22
+ FCM_RING_SENDER_ID,
23
+ KIND_DING,
24
+ KIND_INTERCOM_UNLOCK,
25
+ KIND_MOTION,
26
+ PUSH_ACTION_DING,
27
+ PUSH_ACTION_INTERCOM_UNLOCK,
28
+ PUSH_ACTION_MOTION,
29
+ PUSH_NOTIFICATION_KINDS,
30
+ SUBSCRIPTION_ENDPOINT,
31
+ )
32
+ from python_ring.event import RingEvent, RingEventKey
33
+ from python_ring.exceptions import RingError
34
+ from python_ring.util import parse_datetime
35
+
36
+ from .listenerconfig import RingEventListenerConfig
37
+
38
+ if TYPE_CHECKING:
39
+ from python_ring.ring import Ring
40
+
41
+ _logger = logging.getLogger(__name__)
42
+
43
+ OnNotificationCallable = Callable[[RingEvent], None]
44
+ CredentialsUpdatedCallable = Callable[[dict[str, Any]], None]
45
+
46
+
47
+ class RingEventListener:
48
+ """Class to connect to firebase cloud messaging."""
49
+
50
+ SESSION_REFRESH_INTERVAL = 60 * 60 * 12
51
+ SESSION_REFRESH_RETRY_INTERVAL = 60 * 5
52
+
53
+ def __init__(
54
+ self,
55
+ ring: Ring,
56
+ credentials: dict[str, Any] | None = None,
57
+ credentials_updated_callback: CredentialsUpdatedCallable | None = None,
58
+ *,
59
+ config: RingEventListenerConfig | None = None,
60
+ ) -> None:
61
+ """Initialise the event listener with credentials.
62
+
63
+ Provide a callback for when credentials are updated by FCM.
64
+ """
65
+ self._ring = ring
66
+
67
+ self._callbacks: dict[int, OnNotificationCallable] = {}
68
+ self.subscribed = False
69
+ self._started = False
70
+ self._device_model = self._ring.auth.get_device_model()
71
+
72
+ self._credentials = credentials
73
+ self._credentials_updated_callback = credentials_updated_callback
74
+
75
+ self._receiver: FcmPushClient | None = None
76
+ self._receiver_start_called = False
77
+ self._lifecycle_lock = asyncio.Lock()
78
+ self._default_callback_id: int | None = None
79
+ self._config: RingEventListenerConfig = (
80
+ config or RingEventListenerConfig.default_config()
81
+ )
82
+
83
+ self._subscription_counter = 1
84
+ self._intercom_unlock_counter: dict[int, int] = {}
85
+
86
+ self.session_refresh_task: asyncio.Task | None = None
87
+ self.fcm_token: str | None = None
88
+
89
+ self._seen_events: set[RingEventKey] = set()
90
+
91
+ @property
92
+ def started(self) -> bool:
93
+ """Return whether the push receiver is logged in and listening."""
94
+ return bool(self._started and self._receiver and self._receiver.is_started())
95
+
96
+ def _credentials_updated_cb(self, creds: dict[str, Any]) -> None:
97
+ self._credentials = creds
98
+ if self._credentials_updated_callback:
99
+ self._credentials_updated_callback(creds)
100
+
101
+ async def add_subscription_to_ring(self, token: str) -> None:
102
+ """Add subscription to ring."""
103
+ if not self._ring.session:
104
+ await self._ring.async_create_session()
105
+
106
+ session_patch_data = {
107
+ "device": {
108
+ "metadata": {
109
+ "api_version": API_VERSION,
110
+ "device_model": self._device_model,
111
+ "pn_dict_version": "2.0.0",
112
+ "pn_service": "fcm",
113
+ },
114
+ "os": "android",
115
+ "push_notification_token": token,
116
+ }
117
+ }
118
+ resp = await self._ring.auth.async_query(
119
+ API_URI + SUBSCRIPTION_ENDPOINT,
120
+ method="PATCH",
121
+ json=session_patch_data,
122
+ raise_for_status=False,
123
+ )
124
+ if resp.status_code != 204:
125
+ _logger.error(
126
+ "Unable to checkin to listen service, "
127
+ "response was %s %s, event listener not started",
128
+ resp.status_code,
129
+ resp.text,
130
+ )
131
+ self.subscribed = False
132
+ return
133
+
134
+ self.subscribed = True
135
+ # Update devices for the intercom unlock events
136
+ if not self._ring.devices_data:
137
+ await self._ring.async_update_devices()
138
+
139
+ def add_notification_callback(self, callback: OnNotificationCallable) -> int:
140
+ """Add a callback to be notified on event."""
141
+ sub_id = self._subscription_counter
142
+
143
+ self._callbacks[sub_id] = callback
144
+ self._subscription_counter += 1
145
+
146
+ return sub_id
147
+
148
+ def remove_notification_callback(self, subscription_id: int) -> None:
149
+ """Remove a notification callback by id."""
150
+ if subscription_id == self._default_callback_id:
151
+ msg = (
152
+ "Cannot remove the default callback for python-ring with value "
153
+ f"{subscription_id}"
154
+ )
155
+ raise RingError(msg)
156
+
157
+ if subscription_id not in self._callbacks:
158
+ msg = f"ID {subscription_id} is not a valid callback id"
159
+ raise RingError(msg)
160
+
161
+ del self._callbacks[subscription_id]
162
+
163
+ async def stop(self) -> None:
164
+ """Stop the listener."""
165
+ async with self._lifecycle_lock:
166
+ await self._stop_locked(clear_callbacks=True)
167
+
168
+ async def _stop_locked(self, *, clear_callbacks: bool) -> None:
169
+ """Stop the listener while holding the lifecycle lock."""
170
+ self._started = False
171
+ receiver = self._receiver
172
+ self._receiver = None
173
+
174
+ try:
175
+ if receiver and self._receiver_start_called:
176
+ await receiver.stop()
177
+ finally:
178
+ self._receiver_start_called = False
179
+
180
+ refresh_task = self.session_refresh_task
181
+ self.session_refresh_task = None
182
+ if refresh_task and not refresh_task.done():
183
+ refresh_task.cancel()
184
+ if refresh_task is not asyncio.current_task():
185
+ with suppress(asyncio.CancelledError):
186
+ await refresh_task
187
+
188
+ if self._default_callback_id is not None:
189
+ self._callbacks.pop(self._default_callback_id, None)
190
+ self._default_callback_id = None
191
+ if clear_callbacks:
192
+ self._callbacks = {}
193
+ self._subscription_counter = 1
194
+
195
+ self.subscribed = False
196
+ self.fcm_token = None
197
+
198
+ async def start(
199
+ self,
200
+ *,
201
+ timeout: int = 10,
202
+ ) -> bool:
203
+ """Start the listener."""
204
+ async with self._lifecycle_lock:
205
+ return await self._start_locked(timeout)
206
+
207
+ async def _start_locked(self, timeout: int) -> bool:
208
+ """Start the listener while holding the lifecycle lock."""
209
+ _logger.debug("Starting event listener")
210
+ if self.started:
211
+ return True
212
+
213
+ if self._receiver:
214
+ await self._stop_locked(clear_callbacks=False)
215
+
216
+ receiver = self._create_receiver()
217
+ if not await self._checkin_and_subscribe(receiver):
218
+ return False
219
+
220
+ try:
221
+ async with asyncio_timeout(timeout):
222
+ self._receiver_start_called = True
223
+ await receiver.start()
224
+ while not receiver.is_started(): # noqa: ASYNC110
225
+ await asyncio.sleep(0.05)
226
+ except BaseException:
227
+ await self._stop_locked(clear_callbacks=False)
228
+ raise
229
+
230
+ self._default_callback_id = self.add_notification_callback(
231
+ self._ring._add_event_to_dings_data # noqa: SLF001
232
+ )
233
+ self._started = True
234
+ self.session_refresh_task = asyncio.create_task(
235
+ self._periodic_session_refresh()
236
+ )
237
+ _logger.debug("Started event listener")
238
+ return self.started
239
+
240
+ def _create_receiver(self) -> FcmPushClient:
241
+ """Create the FCM receiver for this listener."""
242
+ fcm_config = FcmRegisterConfig(
243
+ FCM_PROJECT_ID, FCM_APP_ID, FCM_API_KEY, FCM_RING_SENDER_ID
244
+ )
245
+ self._receiver = FcmPushClient(
246
+ self._on_notification,
247
+ fcm_config,
248
+ self._credentials,
249
+ self._credentials_updated_cb,
250
+ config=self._config,
251
+ http_client_session=self._ring.auth._session, # noqa: SLF001
252
+ )
253
+ return self._receiver
254
+
255
+ async def _checkin_and_subscribe(self, receiver: FcmPushClient) -> bool:
256
+ """Register the FCM client and subscribe its token with Ring."""
257
+ try:
258
+ self.fcm_token = await receiver.checkin_or_register()
259
+ except BaseException:
260
+ await self._stop_locked(clear_callbacks=False)
261
+ raise
262
+ if not self.fcm_token:
263
+ _logger.error(
264
+ "Ring listener unable to check in to fcm, event listener not started"
265
+ )
266
+ await self._stop_locked(clear_callbacks=False)
267
+ return False
268
+
269
+ try:
270
+ if not self.subscribed:
271
+ await self.add_subscription_to_ring(self.fcm_token)
272
+ except BaseException:
273
+ await self._stop_locked(clear_callbacks=False)
274
+ raise
275
+ if not self.subscribed:
276
+ await self._stop_locked(clear_callbacks=False)
277
+ return False
278
+ return True
279
+
280
+ async def _periodic_session_refresh(self) -> None:
281
+ while self._started:
282
+ now = time.monotonic()
283
+ if TYPE_CHECKING:
284
+ assert self._ring.session_refresh_time
285
+ assert self.fcm_token
286
+ since_refresh = now - self._ring.session_refresh_time
287
+
288
+ if since_refresh > self.SESSION_REFRESH_INTERVAL:
289
+ _logger.debug("Refreshing ring session")
290
+ try:
291
+ await self._ring.async_create_session()
292
+ await self.add_subscription_to_ring(self.fcm_token)
293
+ except RingError:
294
+ _logger.exception(
295
+ "Error refreshing ring session, retrying in %s seconds",
296
+ self.SESSION_REFRESH_RETRY_INTERVAL,
297
+ )
298
+ await asyncio.sleep(self.SESSION_REFRESH_RETRY_INTERVAL)
299
+ continue
300
+
301
+ sleep_for = 1 + self.SESSION_REFRESH_INTERVAL - since_refresh
302
+ await asyncio.sleep(sleep_for)
303
+
304
+ def _get_ding_event(self, gcm_data: dict[str, Any]) -> RingEvent:
305
+ ding = gcm_data["ding"]
306
+ action = gcm_data["action"]
307
+ subtype = gcm_data["subtype"]
308
+ if action.lower() == PUSH_ACTION_MOTION.lower():
309
+ kind = KIND_MOTION
310
+ state = subtype
311
+ elif action.lower() == PUSH_ACTION_DING.lower():
312
+ kind = KIND_DING
313
+ state = "ringing"
314
+ else:
315
+ kind = action
316
+ state = subtype
317
+
318
+ created_at = ding["created_at"]
319
+ create_seconds = parse_datetime(created_at).timestamp()
320
+ return RingEvent(
321
+ id=ding["id"],
322
+ kind=kind,
323
+ doorbot_id=ding["doorbot_id"],
324
+ device_name=ding["device_name"],
325
+ device_kind=ding["device_kind"],
326
+ now=create_seconds,
327
+ expires_in=DEFAULT_LISTEN_EVENT_EXPIRES_IN,
328
+ state=state,
329
+ )
330
+
331
+ def _get_intercom_unlock_event(self, gcm_data: dict[str, Any]) -> RingEvent | None:
332
+ device_api_id = gcm_data["alarm_meta"]["device_zid"]
333
+ if (device := self._ring.get_device_by_api_id(device_api_id)) is None:
334
+ _logger.debug("Event received for unknown device id: %s", device_api_id)
335
+ return None
336
+
337
+ if device_api_id not in self._intercom_unlock_counter:
338
+ self._intercom_unlock_counter[device_api_id] = 0
339
+ self._intercom_unlock_counter[device_api_id] += 1
340
+ return RingEvent(
341
+ id=self._intercom_unlock_counter[device_api_id],
342
+ kind=KIND_INTERCOM_UNLOCK,
343
+ doorbot_id=device_api_id,
344
+ device_name=device.name,
345
+ device_kind=device.kind,
346
+ now=time.time(),
347
+ expires_in=DEFAULT_LISTEN_EVENT_EXPIRES_IN,
348
+ state="unlock",
349
+ )
350
+
351
+ def _check_is_update(self, ring_event: RingEvent) -> None:
352
+ """Battery doorbells send two events.
353
+
354
+ First without an image and the second with an image.
355
+ """
356
+ now = time.time()
357
+ seen_events = {
358
+ key
359
+ for key in self._seen_events
360
+ if (now - key.now) < DEFAULT_LISTEN_EVENT_EXPIRES_IN
361
+ }
362
+ event_key = ring_event.get_key()
363
+ if event_key in seen_events:
364
+ ring_event.is_update = True
365
+ else:
366
+ seen_events.add(event_key)
367
+ self._seen_events = seen_events
368
+
369
+ def _on_notification(
370
+ self,
371
+ notification: dict[str, dict[str, str]],
372
+ persistent_id: str, # noqa: ARG002
373
+ obj: Any | None = None, # noqa: ARG002
374
+ ) -> None:
375
+ msg_data = notification["data"]
376
+ try:
377
+ if "gcmData" in msg_data:
378
+ gcm_data = json.loads(notification["data"]["gcmData"])
379
+ ring_event = self._get_legacy_ring_event(gcm_data)
380
+ else:
381
+ ring_event = self._get_ring_event(msg_data)
382
+ except Exception:
383
+ # Raising here counts towards the FcmPushClient error limit and
384
+ # an unparseable payload should not stop the listener.
385
+ _logger.exception(
386
+ "Unable to parse fcm message data. Full message is:\n%s",
387
+ json.dumps(msg_data),
388
+ )
389
+ return
390
+
391
+ if ring_event:
392
+ self._check_is_update(ring_event)
393
+ _logger.debug("Event received %s", ring_event)
394
+ for callback in self._callbacks.values():
395
+ callback(ring_event)
396
+ else:
397
+ _logger.debug("Unknown event received %s", msg_data)
398
+
399
+ def _get_ring_event(self, msg_data: dict) -> RingEvent | None:
400
+ if (android_config_str := msg_data.get("android_config")) is None or (
401
+ data_str := msg_data.get("data")
402
+ ) is None:
403
+ _logger.debug(
404
+ "Unexpected alert type in fcm message data. Full message is:\n%s",
405
+ json.dumps(msg_data),
406
+ )
407
+ return None
408
+
409
+ android_config = json.loads(android_config_str)
410
+ data = json.loads(data_str)
411
+ event_category = android_config["category"]
412
+ event_kind = PUSH_NOTIFICATION_KINDS.get(event_category, "Unknown")
413
+ device = data["device"]
414
+ event = data["event"]
415
+ ding = event["ding"]
416
+ created_at = ding["created_at"]
417
+ create_seconds = parse_datetime(created_at).timestamp()
418
+ # Some FCM payloads omit ding.id; created_at remains stable across updates.
419
+ event_id_value = ding.get("id")
420
+ event_id = (
421
+ int(event_id_value)
422
+ if event_id_value is not None
423
+ else int(create_seconds * 1000)
424
+ )
425
+ return RingEvent(
426
+ event_id,
427
+ device["id"],
428
+ device_name=device.get("name"),
429
+ device_kind=device.get("kind"),
430
+ kind=event_kind,
431
+ now=create_seconds,
432
+ expires_in=DEFAULT_LISTEN_EVENT_EXPIRES_IN,
433
+ state=ding["subtype"],
434
+ detection_type=ding.get("detection_type"),
435
+ )
436
+
437
+ def _get_legacy_ring_event(self, gcm_data: dict) -> RingEvent | None:
438
+ re: RingEvent | None = None
439
+ if "ding" in gcm_data:
440
+ re = self._get_ding_event(gcm_data)
441
+ elif gcm_data.get("action") == PUSH_ACTION_INTERCOM_UNLOCK:
442
+ re = self._get_intercom_unlock_event(gcm_data)
443
+ elif "community_alert" not in gcm_data:
444
+ _logger.debug(
445
+ "Unexpected alert type in gcmData. Full message is:\n%s",
446
+ json.dumps(gcm_data),
447
+ )
448
+ return None
449
+ return re
@@ -0,0 +1,21 @@
1
+ """Module for RingEventListenerConfig."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from firebase_messaging import FcmPushClientConfig
6
+
7
+
8
+ class RingEventListenerConfig(FcmPushClientConfig):
9
+ """Configuration class for event listener."""
10
+
11
+ @staticmethod
12
+ def default_config() -> RingEventListenerConfig:
13
+ """Get an instance of the default config."""
14
+ config = RingEventListenerConfig()
15
+ config.server_heartbeat_interval = 60
16
+ config.client_heartbeat_interval = 120
17
+ config.monitor_interval = 15
18
+ # Do not permanently shut down the push client after repeated errors,
19
+ # keep resetting the connection instead.
20
+ config.abort_on_sequential_error_count = None
21
+ return config