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.
python_ring/ring.py ADDED
@@ -0,0 +1,476 @@
1
+ # vim:sw=4:ts=4:et:
2
+ """Python Ring Doorbell module."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import logging
7
+ import time
8
+ from itertools import chain
9
+ from typing import TYPE_CHECKING, Any, ClassVar
10
+
11
+ from python_ring import RingEvent
12
+ from python_ring.chime import RingChime
13
+ from python_ring.doorbot import RingDoorBell
14
+ from python_ring.exceptions import RingError
15
+ from python_ring.group import RingLightGroup
16
+ from python_ring.other import RingOther
17
+ from python_ring.stickup_cam import RingStickUpCam
18
+
19
+ from .const import (
20
+ API_URI,
21
+ API_VERSION,
22
+ DEVICES_ENDPOINT,
23
+ DINGS_ENDPOINT,
24
+ GROUPS_ENDPOINT,
25
+ INTERCOM_KINDS,
26
+ NEW_SESSION_ENDPOINT,
27
+ )
28
+
29
+ if TYPE_CHECKING:
30
+ from collections.abc import Iterator, Mapping, Sequence
31
+
32
+ from python_ring.auth import Auth
33
+ from python_ring.generic import RingGeneric
34
+
35
+ _logger = logging.getLogger(__name__)
36
+
37
+
38
+ class Ring:
39
+ """A Python Abstraction object to Ring Door Bell."""
40
+
41
+ def __init__(self, auth: Auth) -> None:
42
+ """Initialize the Ring object."""
43
+ self.auth: Auth = auth
44
+ self.session = None
45
+ self.subscription = None
46
+ self.devices_data: dict[str, dict[int, dict[str, Any]]] = {}
47
+ self._devices: RingDevices | None = None
48
+ self.chime_health_data = None
49
+ self.doorbell_health_data = None
50
+ self.dings_data: dict[Any, Any] = {}
51
+ self.push_dings_data: list[RingEvent] = []
52
+ self.groups_data: dict[str, dict[str, Any]] = {}
53
+ self.init_loop = None
54
+ self.session_refresh_time: float | None = None
55
+
56
+ async def async_update_data(self) -> None:
57
+ """Update all data."""
58
+ await self._async_update_data()
59
+
60
+ async def _async_update_data(self) -> None:
61
+ if self.session is None:
62
+ await self.async_create_session()
63
+
64
+ await self.async_update_devices()
65
+
66
+ await self.async_update_dings()
67
+
68
+ await self.async_update_groups()
69
+
70
+ def _add_event_to_dings_data(self, ring_event: RingEvent) -> None:
71
+ # Purge expired push_dings
72
+ now = time.time()
73
+ self.push_dings_data = [
74
+ re for re in self.push_dings_data if now < re.now + re.expires_in
75
+ ]
76
+ self.push_dings_data.append(ring_event)
77
+
78
+ async def async_create_session(self) -> None:
79
+ """Create a new Ring session."""
80
+ session_post_data = {
81
+ "device": {
82
+ "hardware_id": self.auth.get_hardware_id(),
83
+ "metadata": {
84
+ "api_version": API_VERSION,
85
+ "device_model": self.auth.get_device_model(),
86
+ },
87
+ "os": "android",
88
+ }
89
+ }
90
+ resp = await self._async_query(
91
+ NEW_SESSION_ENDPOINT,
92
+ method="POST",
93
+ json=session_post_data,
94
+ )
95
+ self.session = resp.json()
96
+ self.session_refresh_time = time.monotonic()
97
+
98
+ async def async_update_devices(self) -> None:
99
+ """Update device data."""
100
+ if self.session is None:
101
+ await self.async_create_session()
102
+
103
+ resp = await self._async_query(DEVICES_ENDPOINT)
104
+ data: dict[Any, Any] = resp.json()
105
+
106
+ # Index data by device ID.
107
+ self.devices_data = {
108
+ device_type: {obj["id"]: obj for obj in devices}
109
+ for device_type, devices in data.items()
110
+ }
111
+
112
+ async def async_update_dings(self) -> None:
113
+ """Update dings data."""
114
+ if self.session is None:
115
+ await self.async_create_session()
116
+
117
+ resp = await self._async_query(DINGS_ENDPOINT)
118
+ self.dings_data = resp.json()
119
+
120
+ async def async_update_groups(self) -> None:
121
+ """Update groups data."""
122
+ if self.session is None:
123
+ await self.async_create_session()
124
+ # Get all locations
125
+ locations = set()
126
+ devices = self.devices()
127
+ for device_type in devices:
128
+ for dev in devices[device_type]:
129
+ if dev.location_id is not None:
130
+ locations.add(dev.location_id)
131
+
132
+ # Query for groups
133
+ self.groups_data = {}
134
+ for location in locations:
135
+ resp = await self._async_query(GROUPS_ENDPOINT.format(location))
136
+ data = resp.json()
137
+ if data["device_groups"]:
138
+ for group in data["device_groups"]:
139
+ self.groups_data[group["device_group_id"]] = group
140
+
141
+ async def async_query( # noqa: PLR0913
142
+ self,
143
+ url: str,
144
+ method: str = "GET",
145
+ extra_params: dict[str, Any] | None = None,
146
+ data: bytes | None = None,
147
+ json: dict[Any, Any] | None = None,
148
+ timeout: float | None = None,
149
+ base_uri: str = API_URI,
150
+ ) -> Auth.Response:
151
+ """Query data from Ring API."""
152
+ if self.session is None:
153
+ await self.async_create_session()
154
+ return await self._async_query(
155
+ url, method, extra_params, data, json, timeout, base_uri
156
+ )
157
+
158
+ async def _async_query( # noqa: PLR0913
159
+ self,
160
+ url: str,
161
+ method: str = "GET",
162
+ extra_params: dict[str, Any] | None = None,
163
+ data: bytes | None = None,
164
+ json: dict[Any, Any] | None = None,
165
+ timeout: float | None = None,
166
+ base_uri: str = API_URI,
167
+ ) -> Auth.Response:
168
+ _logger.debug(
169
+ "url: %s\nmethod: %s\njson: %s\ndata: %s\n extra_params: %s",
170
+ url,
171
+ method,
172
+ json,
173
+ data,
174
+ extra_params,
175
+ )
176
+ return await self.auth.async_query(
177
+ base_uri + url,
178
+ method=method,
179
+ extra_params=extra_params,
180
+ data=data,
181
+ json=json,
182
+ timeout=timeout,
183
+ )
184
+
185
+ def devices(self) -> RingDevices:
186
+ """Get all devices."""
187
+ if not self._devices:
188
+ self._devices = RingDevices(self, self.devices_data)
189
+ return self._devices
190
+
191
+ def get_device_list(self) -> Sequence[RingGeneric]:
192
+ """Get a combined list of all devices."""
193
+ devices = self.devices()
194
+ return list(
195
+ chain(
196
+ devices["doorbots"],
197
+ devices["authorized_doorbots"],
198
+ devices["stickup_cams"],
199
+ devices["chimes"],
200
+ devices["other"],
201
+ )
202
+ )
203
+
204
+ def get_device_by_name(self, device_name: str) -> RingGeneric | None:
205
+ """Return a device using it's name."""
206
+ all_devices = self.get_device_list()
207
+ names_to_idx = {device.name: idx for (idx, device) in enumerate(all_devices)}
208
+ return (
209
+ None
210
+ if device_name not in names_to_idx
211
+ else all_devices[names_to_idx[device_name]]
212
+ )
213
+
214
+ def get_video_device_by_name(self, device_name: str) -> RingDoorBell | None:
215
+ """Return a device using it's name."""
216
+ video_devices = self.video_devices()
217
+ names_to_idx = {device.name: idx for (idx, device) in enumerate(video_devices)}
218
+ return (
219
+ None
220
+ if device_name not in names_to_idx
221
+ else video_devices[names_to_idx[device_name]]
222
+ )
223
+
224
+ def get_device_by_api_id(self, device_api_id: int) -> RingGeneric | None:
225
+ """Return a device using it's id."""
226
+ all_devices = self.get_device_list()
227
+ api_id_to_idx = {
228
+ device.device_api_id: idx for (idx, device) in enumerate(all_devices)
229
+ }
230
+ return (
231
+ None
232
+ if device_api_id not in api_id_to_idx
233
+ else all_devices[api_id_to_idx[device_api_id]]
234
+ )
235
+
236
+ def video_devices(self) -> Sequence[RingDoorBell]:
237
+ """Get all devices."""
238
+ devices = self.devices()
239
+ return list(
240
+ chain(devices.doorbots, devices.authorized_doorbots, devices.stickup_cams)
241
+ )
242
+
243
+ def groups(self) -> Mapping[str, RingLightGroup]:
244
+ """Get all groups."""
245
+ groups = {}
246
+
247
+ for group_id in self.groups_data:
248
+ groups[group_id] = RingLightGroup(self, group_id)
249
+
250
+ return groups
251
+
252
+ def active_alerts(self) -> Sequence[RingEvent]:
253
+ """Get active alerts."""
254
+ now = time.time()
255
+ # Purge expired push_dings
256
+ self.push_dings_data = [
257
+ re for re in self.push_dings_data if now < re.now + re.expires_in
258
+ ]
259
+ # Get unique id dictionary
260
+ alerts: dict[tuple[int, int, str], RingEvent] = {}
261
+ for re in self.push_dings_data:
262
+ key = (re.doorbot_id, re.id, re.kind)
263
+ if key not in alerts or re.now > alerts[key].now:
264
+ alerts[key] = re
265
+
266
+ for ding_data in self.dings_data:
267
+ expires_at = ding_data.get("now") + ding_data.get("expires_in")
268
+
269
+ if now < expires_at:
270
+ re = RingEvent(
271
+ id=ding_data["id"],
272
+ doorbot_id=ding_data["doorbot_id"],
273
+ device_name=ding_data["doorbot_description"],
274
+ device_kind=ding_data["device_kind"],
275
+ now=ding_data["now"],
276
+ expires_in=ding_data["expires_in"],
277
+ kind=ding_data["kind"],
278
+ state=ding_data["state"],
279
+ )
280
+ key = (re.doorbot_id, re.id, re.kind)
281
+ if key not in alerts or re.now > alerts[key].now:
282
+ alerts[key] = re
283
+
284
+ return list(alerts.values())
285
+
286
+ DEPRECATED_API_QUERIES: ClassVar = {
287
+ "update_devices",
288
+ "update_data",
289
+ "update_dings",
290
+ "update_groups",
291
+ "create_session",
292
+ "query",
293
+ }
294
+
295
+ if not TYPE_CHECKING:
296
+
297
+ def __getattr__(self, name: str) -> Any:
298
+ """Get a deprecated attribute or raise an error."""
299
+ if name in self.DEPRECATED_API_QUERIES:
300
+ return self.auth._dep_handler.get_api_query(self, name) # noqa: SLF001
301
+ msg = f"{self.__class__.__name__} has no attribute {name!r}"
302
+ raise AttributeError(msg)
303
+
304
+
305
+ class RingDevices:
306
+ """Class to represent collection of devices."""
307
+
308
+ def __init__(
309
+ self, ring: Ring, devices_data: dict[str, dict[int, dict[str, Any]]]
310
+ ) -> None:
311
+ """Initialise the devices from the api response."""
312
+ self._stickup_cams: list[RingStickUpCam] = []
313
+ self._chimes: list[RingChime] = []
314
+ self._doorbots: list[RingDoorBell] = []
315
+ self._authorized_doorbots: list[RingDoorBell] = []
316
+ self._other: list[RingOther] = []
317
+
318
+ for device_type, devices in devices_data.items():
319
+ if device_type == "stickup_cams":
320
+ self._stickup_cams = [
321
+ RingStickUpCam(ring, device_id) for device_id in devices
322
+ ]
323
+ if device_type == "chimes":
324
+ self._chimes = [RingChime(ring, device_id) for device_id in devices]
325
+ if device_type == "doorbots":
326
+ self._doorbots = [
327
+ RingDoorBell(ring, device_id) for device_id in devices
328
+ ]
329
+ if device_type == "authorized_doorbots":
330
+ self._authorized_doorbots = [
331
+ RingDoorBell(ring, device_id, shared=True) for device_id in devices
332
+ ]
333
+ if device_type == "other":
334
+ self._other = [
335
+ RingOther(ring, device_id, shared=True)
336
+ for device_id, device in devices.items()
337
+ if (device_kind := device.get("kind"))
338
+ and device_kind in INTERCOM_KINDS
339
+ ]
340
+ self._all_devices = {
341
+ device.id: device
342
+ for device in chain(
343
+ self._stickup_cams,
344
+ self._chimes,
345
+ self._doorbots,
346
+ self._authorized_doorbots,
347
+ self._other,
348
+ )
349
+ }
350
+
351
+ def __getitem__(self, device_type: str) -> Sequence[RingGeneric]:
352
+ """Get a generic device by type."""
353
+ if device_type == "stickup_cams":
354
+ return self._stickup_cams
355
+ if device_type == "chimes":
356
+ return self._chimes
357
+ if device_type == "doorbots":
358
+ return self._doorbots
359
+ if device_type == "authorized_doorbots":
360
+ return self._authorized_doorbots
361
+ if device_type == "other":
362
+ return self._other
363
+ if device_type == "intercoms":
364
+ return self._other
365
+ msg = f"Invalid device_type {device_type}"
366
+ raise RingError(msg)
367
+
368
+ def __iter__(self) -> Iterator[str]:
369
+ """Device type iterator."""
370
+ return iter(
371
+ ["stickup_cams", "chimes", "doorbots", "authorized_doorbots", "other"]
372
+ )
373
+
374
+ @property
375
+ def stickup_cams(self) -> Sequence[RingStickUpCam]:
376
+ """The stickup cams."""
377
+ return self._stickup_cams
378
+
379
+ @property
380
+ def chimes(self) -> Sequence[RingChime]:
381
+ """The chimes."""
382
+ return self._chimes
383
+
384
+ @property
385
+ def doorbots(self) -> Sequence[RingDoorBell]:
386
+ """The doorbots."""
387
+ return self._doorbots
388
+
389
+ @property
390
+ def authorized_doorbots(self) -> Sequence[RingDoorBell]:
391
+ """The authorized_doorbots."""
392
+ return self._authorized_doorbots
393
+
394
+ @property
395
+ def doorbells(self) -> Sequence[RingDoorBell]:
396
+ """The doorbells, i.e. doorbots and authorized_doorbots combined."""
397
+ return self._doorbots + self._authorized_doorbots
398
+
399
+ @property
400
+ def other(self) -> Sequence[RingOther]:
401
+ """The other devices, i.e. intercoms."""
402
+ return self._other
403
+
404
+ @property
405
+ def all_devices(self) -> Sequence[RingGeneric]:
406
+ """All devices combined."""
407
+ return list(self._all_devices.values())
408
+
409
+ @property
410
+ def video_devices(self) -> Sequence[RingDoorBell]:
411
+ """The video devices, i.e. doorbells and stickup_cams."""
412
+ return [*self._doorbots, *self._authorized_doorbots, *self._stickup_cams]
413
+
414
+ def get_device(self, device_api_id: int) -> RingGeneric:
415
+ """Get device by api id."""
416
+ if device := self._all_devices.get(device_api_id):
417
+ return device
418
+ msg = f"device with id {device_api_id} not found"
419
+ raise RingError(msg)
420
+
421
+ def get_doorbell(self, device_api_id: int) -> RingDoorBell:
422
+ """Get doorbell by api id."""
423
+ if (
424
+ (device := self._all_devices.get(device_api_id))
425
+ and isinstance(device, RingDoorBell)
426
+ and not issubclass(device.__class__, RingDoorBell)
427
+ ):
428
+ return device
429
+ msg = f"doorbell with id {device_api_id} not found"
430
+ raise RingError(msg)
431
+
432
+ def get_stickup_cam(self, device_api_id: int) -> RingStickUpCam:
433
+ """Get stickup_cam by api id."""
434
+ if (device := self._all_devices.get(device_api_id)) and isinstance(
435
+ device, RingStickUpCam
436
+ ):
437
+ return device
438
+ msg = f"stickup_cam with id {device_api_id} not found"
439
+ raise RingError(msg)
440
+
441
+ def get_chime(self, device_api_id: int) -> RingChime:
442
+ """Get chime by api id."""
443
+ if (device := self._all_devices.get(device_api_id)) and isinstance(
444
+ device, RingChime
445
+ ):
446
+ return device
447
+ msg = f"chime with id {device_api_id} not found"
448
+ raise RingError(msg)
449
+
450
+ def get_other(self, device_api_id: int) -> RingOther:
451
+ """Get other device by api id."""
452
+ if (device := self._all_devices.get(device_api_id)) and isinstance(
453
+ device, RingOther
454
+ ):
455
+ return device
456
+ msg = f"other device with id {device_api_id} not found"
457
+ raise RingError(msg)
458
+
459
+ def get_video_device(self, device_api_id: int) -> RingDoorBell:
460
+ """Get video capable device by api id."""
461
+ if (device := self._all_devices.get(device_api_id)) and isinstance(
462
+ device, RingDoorBell
463
+ ):
464
+ return device
465
+ msg = f"video capable device with id {device_api_id} not found"
466
+ raise RingError(msg)
467
+
468
+ def __str__(self) -> str:
469
+ """Get string representation of devices."""
470
+ d = {dev_type: self.__getitem__(dev_type) for dev_type in self.__iter__()}
471
+ return "{" + "\n".join(f"{k!r}: {v!r}," for k, v in d.items()) + "}"
472
+
473
+ def __repr__(self) -> str:
474
+ """Return repr of devices."""
475
+ d = {dev_type: self.__getitem__(dev_type) for dev_type in self.__iter__()}
476
+ return repr(d)