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,44 @@
1
+ """Python Package for interacting with Ring devices."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("python_ring")
6
+
7
+ from python_ring.auth import Auth
8
+ from python_ring.chime import RingChime
9
+ from python_ring.const import RingCapability, RingEventKind
10
+ from python_ring.doorbot import RingDoorBell
11
+ from python_ring.event import RingEvent
12
+ from python_ring.exceptions import (
13
+ AuthenticationError,
14
+ Requires2FAError,
15
+ RingError,
16
+ RingTimeout,
17
+ )
18
+ from python_ring.generic import RingGeneric
19
+ from python_ring.group import RingLightGroup
20
+ from python_ring.listen import RingEventListener, RingEventListenerConfig
21
+ from python_ring.other import RingOther
22
+ from python_ring.ring import Ring, RingDevices
23
+ from python_ring.stickup_cam import RingStickUpCam
24
+
25
+ __all__ = [
26
+ "Auth",
27
+ "AuthenticationError",
28
+ "Requires2FAError",
29
+ "Ring",
30
+ "RingCapability",
31
+ "RingChime",
32
+ "RingDevices",
33
+ "RingDoorBell",
34
+ "RingError",
35
+ "RingEvent",
36
+ "RingEventKind",
37
+ "RingEventListener",
38
+ "RingEventListenerConfig",
39
+ "RingGeneric",
40
+ "RingLightGroup",
41
+ "RingOther",
42
+ "RingStickUpCam",
43
+ "RingTimeout",
44
+ ]
python_ring/auth.py ADDED
@@ -0,0 +1,283 @@
1
+ # vim:sw=4:ts=4:et:
2
+ """Python Ring Auth Class."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import uuid
7
+ from asyncio import TimeoutError
8
+ from functools import cached_property
9
+ from json import loads as json_loads
10
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar
11
+
12
+ from aiohttp import ClientError, ClientResponseError, ClientSession, encode_basic_auth
13
+ from oauthlib.common import urldecode
14
+ from oauthlib.oauth2 import (
15
+ LegacyApplicationClient,
16
+ MissingTokenError,
17
+ OAuth2Error,
18
+ TokenExpiredError,
19
+ )
20
+
21
+ from python_ring.const import NAMESPACE_UUID, TIMEOUT, OAuth
22
+ from python_ring.exceptions import (
23
+ AuthenticationError,
24
+ Requires2FAError,
25
+ RingError,
26
+ RingTimeout,
27
+ )
28
+ from python_ring.util import _DeprecatedSyncApiHandler
29
+
30
+
31
+ class Auth:
32
+ """A Python Auth class for Ring."""
33
+
34
+ def __init__(
35
+ self,
36
+ user_agent: str,
37
+ token: dict[str, Any] | None = None,
38
+ token_updater: Callable[[dict[str, Any]], None] | None = None,
39
+ hardware_id: str | None = None,
40
+ *,
41
+ http_client_session: ClientSession | None = None,
42
+ ) -> None:
43
+ """Initialise the auth class.
44
+
45
+ :type token: Optional[Dict[str, str]]
46
+ :type token_updater: Optional[Callable[[str], None]]
47
+ """
48
+ self.user_agent = user_agent
49
+
50
+ if hardware_id:
51
+ self.hardware_id = hardware_id
52
+ else:
53
+ # Generate a UUID that will stay the same
54
+ # for this physical device to prevent
55
+ # multiple auth entries in ring.com
56
+ self.hardware_id = str(
57
+ uuid.uuid5(uuid.UUID(NAMESPACE_UUID), str(uuid.getnode()) + user_agent)
58
+ )
59
+
60
+ self.device_model = "ring-doorbell:" + user_agent
61
+ self.token_updater = token_updater
62
+ self._token: dict[str, Any] = token or {}
63
+ self._local_session: ClientSession | None = None
64
+ self.http_client_session = http_client_session
65
+ self._oauth_client = LegacyApplicationClient(
66
+ client_id=OAuth.CLIENT_ID, token=token
67
+ )
68
+ self._auth_header = encode_basic_auth(OAuth.CLIENT_ID)
69
+
70
+ @property
71
+ def _session(self) -> ClientSession:
72
+ if self.http_client_session:
73
+ return self.http_client_session
74
+ if self._local_session is None:
75
+ self._local_session = ClientSession()
76
+ return self._local_session
77
+
78
+ async def async_fetch_token(
79
+ self, username: str, password: str, otp_code: str | None = None
80
+ ) -> dict[str, Any]:
81
+ """Fetch initial token with username/password & 2FA.
82
+
83
+ :type username: str
84
+ :type password: str
85
+ :type otp_code: str.
86
+ """
87
+ headers = {
88
+ "User-Agent": self.user_agent,
89
+ "hardware_id": self.hardware_id,
90
+ "Authorization": self._auth_header,
91
+ }
92
+
93
+ if otp_code:
94
+ headers["2fa-support"] = "true"
95
+ headers["2fa-code"] = otp_code
96
+
97
+ try:
98
+ body = self._oauth_client.prepare_request_body(
99
+ username, password, scope=OAuth.SCOPE, include_client_id=True
100
+ )
101
+ data = dict(urldecode(body))
102
+ resp = await self._session.request(
103
+ "POST",
104
+ OAuth.ENDPOINT,
105
+ data=data,
106
+ headers=headers,
107
+ )
108
+ async with resp:
109
+ text = await resp.text()
110
+ self._token = self._oauth_client.parse_request_body_response(
111
+ text, scope=OAuth.SCOPE
112
+ )
113
+ except MissingTokenError as ex:
114
+ raise Requires2FAError from ex
115
+ except OAuth2Error as ex:
116
+ raise AuthenticationError(ex) from ex
117
+
118
+ if self.token_updater is not None:
119
+ self.token_updater(self._token)
120
+
121
+ return self._token
122
+
123
+ async def async_refresh_tokens(self) -> dict[str, Any]:
124
+ """Refresh the auth tokens."""
125
+ try:
126
+ headers = {
127
+ "Accept": "application/json",
128
+ "Content-Type": ("application/x-www-form-urlencoded;charset=UTF-8"),
129
+ "Authorization": self._auth_header,
130
+ }
131
+ body = self._oauth_client.prepare_refresh_body(
132
+ refresh_token=self._token["refresh_token"]
133
+ )
134
+ data = dict(urldecode(body))
135
+ resp = await self._session.request(
136
+ "POST", OAuth.ENDPOINT, data=data, headers=headers
137
+ )
138
+ async with resp:
139
+ text = await resp.text()
140
+ self._token = self._oauth_client.parse_request_body_response(
141
+ text, scope=OAuth.SCOPE
142
+ )
143
+ except OAuth2Error as ex:
144
+ raise AuthenticationError(ex) from ex
145
+
146
+ if self.token_updater is not None:
147
+ self.token_updater(self._token)
148
+
149
+ return self._token
150
+
151
+ def get_hardware_id(self) -> str:
152
+ """Get hardware ID."""
153
+ return self.hardware_id
154
+
155
+ def get_device_model(self) -> str:
156
+ """Get device model."""
157
+ return self.device_model
158
+
159
+ async def async_close(self) -> None:
160
+ """Close aiohttp session."""
161
+ session = self._local_session
162
+ self._local_session = None
163
+ if session:
164
+ await session.close()
165
+
166
+ class Response:
167
+ """Class for returning responses."""
168
+
169
+ def __init__(self, content: bytes, status_code: int) -> None:
170
+ """Initialise thhe repsonse class."""
171
+ self.content = content
172
+ self.status_code = status_code
173
+
174
+ @property
175
+ def text(self) -> str:
176
+ """Response as text."""
177
+ return self.content.decode()
178
+
179
+ def json(self) -> Any:
180
+ """Response as loaded json."""
181
+ return json_loads(self.text)
182
+
183
+ async def async_query( # noqa: C901, PLR0913
184
+ self,
185
+ url: str,
186
+ method: str = "GET",
187
+ extra_params: dict[str, Any] | None = None,
188
+ data: bytes | None = None,
189
+ json: dict[Any, Any] | None = None,
190
+ timeout: float | None = None,
191
+ *,
192
+ raise_for_status: bool = True,
193
+ ) -> Auth.Response:
194
+ """Query data from Ring API."""
195
+ if timeout is None:
196
+ timeout = TIMEOUT
197
+
198
+ params = {}
199
+ if extra_params:
200
+ params.update(extra_params)
201
+
202
+ kwargs: dict[str, Any] = {
203
+ "params": params,
204
+ "timeout": timeout,
205
+ }
206
+ headers = {"User-Agent": self.user_agent, "hardware_id": self.get_hardware_id()}
207
+ # Ring servers started requiring a null json value for PUT requests in 2024-10
208
+ if json is not None or method == "PUT":
209
+ kwargs["json"] = json
210
+ headers["Content-Type"] = "application/json"
211
+
212
+ try:
213
+ try:
214
+ url, headers, data = self._oauth_client.add_token(
215
+ url,
216
+ http_method=method,
217
+ body=data,
218
+ headers=headers,
219
+ )
220
+
221
+ resp = await self._session.request(
222
+ method, url, headers=headers, data=data, **kwargs
223
+ )
224
+ except TokenExpiredError:
225
+ self._token = await self.async_refresh_tokens()
226
+ url, headers, data = self._oauth_client.add_token(
227
+ url,
228
+ http_method=method,
229
+ body=data,
230
+ headers=headers,
231
+ )
232
+ resp = await self._session.request(
233
+ method, url, headers=headers, data=data, **kwargs
234
+ )
235
+ except AuthenticationError:
236
+ raise # refresh_tokens will return this error if not valid
237
+ except TimeoutError as ex:
238
+ msg = f"Timeout error during query of url {url}: {ex}"
239
+ raise RingTimeout(msg) from ex
240
+ except ClientError as ex:
241
+ msg = f"aiohttp Client error during query of url {url}: {ex}"
242
+ raise RingError(msg) from ex
243
+ except Exception as ex:
244
+ msg = f"Unknown error during query of url {url}: {ex}"
245
+ raise RingError(msg) from ex
246
+
247
+ async with resp:
248
+ if resp.status == 401:
249
+ # Check whether there's an issue with the token grant
250
+ self._token = await self.async_refresh_tokens()
251
+
252
+ if raise_for_status:
253
+ try:
254
+ resp.raise_for_status()
255
+ except ClientResponseError as ex:
256
+ msg = (
257
+ f"HTTP error with status code {resp.status} "
258
+ f"during query of url {url}: {ex}"
259
+ )
260
+ raise RingError(msg) from ex
261
+
262
+ response_data = await resp.read()
263
+ return Auth.Response(response_data, resp.status)
264
+
265
+ @cached_property
266
+ def _dep_handler(self) -> _DeprecatedSyncApiHandler:
267
+ return _DeprecatedSyncApiHandler(self)
268
+
269
+ DEPRECATED_API_QUERIES: ClassVar = {
270
+ "fetch_token",
271
+ "refresh_tokens",
272
+ "close",
273
+ "query",
274
+ }
275
+
276
+ if not TYPE_CHECKING:
277
+
278
+ def __getattr__(self, name: str) -> Any:
279
+ """Get a deprecated attribute or raise an error."""
280
+ if name in self.DEPRECATED_API_QUERIES:
281
+ return self._dep_handler.get_api_query(self, name)
282
+ msg = f"{self.__class__.__name__} has no attribute {name!r}"
283
+ raise AttributeError(msg)
python_ring/chime.py ADDED
@@ -0,0 +1,135 @@
1
+ # vim:sw=4:ts=4:et:
2
+ """Python Ring Chime wrapper."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import logging
7
+ from typing import Any, ClassVar
8
+
9
+ from python_ring.const import (
10
+ CHIME_2ND_GEN_KINDS,
11
+ CHIME_DO_NOT_DISTURB_ENDPOINT,
12
+ CHIME_KINDS,
13
+ CHIME_PRO_KINDS,
14
+ CHIME_TEST_SOUND_KINDS,
15
+ CHIME_VOL_MAX,
16
+ CHIME_VOL_MIN,
17
+ CHIMES_ENDPOINT,
18
+ HEALTH_CHIMES_ENDPOINT,
19
+ LINKED_CHIMES_ENDPOINT,
20
+ MSG_SNOOZE_OUTBOUND,
21
+ MSG_VOL_OUTBOUND,
22
+ SNOOZE_MINUTES_MAX,
23
+ TESTSOUND_CHIME_ENDPOINT,
24
+ RingCapability,
25
+ RingEventKind,
26
+ )
27
+ from python_ring.exceptions import RingError
28
+ from python_ring.generic import RingGeneric
29
+
30
+ _LOGGER = logging.getLogger(__name__)
31
+
32
+
33
+ class RingChime(RingGeneric):
34
+ """Implementation for Ring Chime."""
35
+
36
+ @property
37
+ def family(self) -> str:
38
+ """Return Ring device family type."""
39
+ return "chimes"
40
+
41
+ async def async_update_health_data(self) -> None:
42
+ """Update health attrs."""
43
+ resp = await self._ring.async_query(
44
+ HEALTH_CHIMES_ENDPOINT.format(self.device_api_id)
45
+ )
46
+ self._health_attrs = resp.json().get("device_health", {})
47
+
48
+ @property
49
+ def model(self) -> str:
50
+ """Return Ring device model name."""
51
+ if self.kind in CHIME_KINDS:
52
+ return "Chime"
53
+ if self.kind in CHIME_PRO_KINDS:
54
+ return "Chime Pro"
55
+ if self.kind in CHIME_2ND_GEN_KINDS:
56
+ return "Chime (2nd Gen)"
57
+ return "Unknown Chime"
58
+
59
+ def has_capability(self, capability: RingCapability | str) -> bool:
60
+ """Return if device has specific capability."""
61
+ capability = (
62
+ capability
63
+ if isinstance(capability, RingCapability)
64
+ else RingCapability.from_name(capability)
65
+ )
66
+ return capability == RingCapability.VOLUME
67
+
68
+ @property
69
+ def volume(self) -> int:
70
+ """Return the chime volume."""
71
+ return self._attrs["settings"].get("volume", 0)
72
+
73
+ async def async_set_volume(self, value: int) -> None:
74
+ """Set the chime volume."""
75
+ if not ((isinstance(value, int)) and (CHIME_VOL_MIN <= value <= CHIME_VOL_MAX)):
76
+ raise RingError(MSG_VOL_OUTBOUND.format(CHIME_VOL_MIN, CHIME_VOL_MAX))
77
+
78
+ params = {
79
+ "chime[description]": self.name,
80
+ "chime[settings][volume]": str(value),
81
+ }
82
+ url = CHIMES_ENDPOINT.format(self.device_api_id)
83
+ await self._ring.async_query(url, extra_params=params, method="PUT")
84
+
85
+ @property
86
+ def do_not_disturb_seconds_left(self) -> int:
87
+ """Return the remaining do not disturb time in seconds."""
88
+ return int((self._attrs.get("do_not_disturb") or {}).get("seconds_left") or 0)
89
+
90
+ async def async_set_do_not_disturb(self, minutes: int) -> None:
91
+ """Silence the chime for the given number of minutes."""
92
+ if not (isinstance(minutes, int) and 1 <= minutes <= SNOOZE_MINUTES_MAX):
93
+ raise RingError(MSG_SNOOZE_OUTBOUND.format(SNOOZE_MINUTES_MAX))
94
+ url = CHIME_DO_NOT_DISTURB_ENDPOINT.format(self.device_api_id)
95
+ await self._ring.async_query(url, method="POST", json={"time": minutes})
96
+ self._attrs["do_not_disturb"] = {"seconds_left": minutes * 60}
97
+
98
+ async def async_clear_do_not_disturb(self) -> None:
99
+ """End do not disturb on the chime."""
100
+ url = CHIME_DO_NOT_DISTURB_ENDPOINT.format(self.device_api_id)
101
+ await self._ring.async_query(url, method="POST")
102
+ self._attrs["do_not_disturb"] = {"seconds_left": 0}
103
+
104
+ async def async_get_linked_tree(self) -> dict[str, Any]:
105
+ """Return doorbell data linked to chime."""
106
+ url = LINKED_CHIMES_ENDPOINT.format(self.device_api_id)
107
+ resp = await self._ring.async_query(url)
108
+ return resp.json()
109
+
110
+ async def async_test_sound(
111
+ self, kind: RingEventKind | str = RingEventKind.DING
112
+ ) -> bool:
113
+ """Play chime to test sound."""
114
+ kind_str = kind.value if isinstance(kind, RingEventKind) else kind
115
+ if kind_str not in CHIME_TEST_SOUND_KINDS:
116
+ return False
117
+ url = TESTSOUND_CHIME_ENDPOINT.format(self.device_api_id)
118
+ await self._ring.async_query(
119
+ url, method="POST", extra_params={"kind": kind_str}
120
+ )
121
+ return True
122
+
123
+ DEPRECATED_API_QUERIES: ClassVar = {
124
+ *RingGeneric.DEPRECATED_API_QUERIES,
125
+ "update_health_data",
126
+ "test_sound",
127
+ }
128
+ DEPRECATED_API_PROPERTY_GETTERS: ClassVar = {
129
+ *RingGeneric.DEPRECATED_API_PROPERTY_GETTERS,
130
+ "linked_tree",
131
+ }
132
+ DEPRECATED_API_PROPERTY_SETTERS: ClassVar = {
133
+ *RingGeneric.DEPRECATED_API_PROPERTY_SETTERS,
134
+ "volume",
135
+ }