File: api.py

package info (click to toggle)
simplisafe-python 2024.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,268 kB
  • sloc: python: 5,252; sh: 50; makefile: 19
file content (507 lines) | stat: -rw-r--r-- 18,627 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
"""Define functionality for interacting with the SimpliSafe API."""
from __future__ import annotations

import asyncio
import sys
from collections.abc import Awaitable, Callable
from datetime import datetime
from json.decoder import JSONDecodeError
from typing import Any, cast

import backoff
from aiohttp import ClientSession
from aiohttp.client_exceptions import ClientResponseError

from simplipy.const import DEFAULT_USER_AGENT, LOGGER
from simplipy.errors import (
    InvalidCredentialsError,
    RequestError,
    SimplipyError,
    raise_on_data_error,
)
from simplipy.system.v2 import SystemV2
from simplipy.system.v3 import SystemV3
from simplipy.util import execute_callback
from simplipy.util.auth import (
    AUTH_URL_BASE,
    AUTH_URL_HOSTNAME,
    DEFAULT_CLIENT_ID,
    DEFAULT_REDIRECT_URI,
)
from simplipy.util.dt import utcnow
from simplipy.websocket import WebsocketClient

API_URL_HOSTNAME = "api.simplisafe.com"
API_URL_BASE = f"https://{API_URL_HOSTNAME}/v1"

DEFAULT_REQUEST_RETRIES = 4
DEFAULT_MEDIA_RETRIES = 4
DEFAULT_TIMEOUT = 10
DEFAULT_TOKEN_EXPIRATION_WINDOW = 5


class API:  # pylint: disable=too-many-instance-attributes
    """An API object to interact with the SimpliSafe cloud.

    Note that this class shouldn't be instantiated directly; instead, the
    :meth:`simplipy.api.API.async_from_auth` and
    :meth:`simplipy.api.API.async_from_refresh_token` methods should be used.

    Args:
        session: session: An optional ``aiohttp`` ``ClientSession``.
        request_retries: The default number of request retries to use.
        media_retries: The default number of request retries to use to
            fetch media files.
    """

    def __init__(
        self,
        *,
        request_retries: int = DEFAULT_REQUEST_RETRIES,
        media_retries: int = DEFAULT_MEDIA_RETRIES,
        session: ClientSession,
    ) -> None:
        """Initialize.

        Args:
            session: An optional ``aiohttp`` ``ClientSession``.
            request_retries: The default number of request retries to use.
        """
        self._refresh_token_callbacks: list[
            Callable[[str], Awaitable[None] | None]
        ] = []
        self._request_retries = request_retries
        self._media_retries = media_retries
        self.session: ClientSession = session

        # These will get filled in after initial authentication:
        self._backoff_refresh_lock = asyncio.Lock()
        self._token_last_refreshed: datetime | None = None
        self.access_token: str | None = None
        self.refresh_token: str | None = None
        self.subscription_data: dict[int, Any] = {}
        self.user_id: int | None = None
        self.websocket: WebsocketClient | None = None

        self.async_request = self._wrap_request_method(
            request_retries=self._request_retries,
            retry_codes=[401, 409],
            request_func=self._async_api_request,
        )
        self._async_media_data = self._wrap_request_method(
            request_retries=self._media_retries,
            retry_codes=[401, 404, 409],
            request_func=self._async_media_request,
        )

    @classmethod
    async def async_from_auth(
        cls,
        authorization_code: str,
        code_verifier: str,
        *,
        request_retries: int = DEFAULT_REQUEST_RETRIES,
        session: ClientSession,
    ) -> API:
        """Get an authenticated API object from an Authorization Code and Code Verifier.

        Args:
            authorization_code: The Authorization Code.
            code_verifier: The Code Verifier.
            request_retries: The default number of request retries to use.
            session: An optional ``aiohttp`` ``ClientSession``.

        Returns:
            An authenticated API object.

        Raises:
            InvalidCredentialsError: Raised on invalid username/password.
            RequestError: Raised on general HTTP error.
            SimplipyError: Raised on an unknown error.
        """
        api = cls(session=session, request_retries=request_retries)

        try:
            token_data = await api._async_api_request(
                "post",
                "oauth/token",
                url_base=AUTH_URL_BASE,
                headers={"Host": AUTH_URL_HOSTNAME},
                json={
                    "grant_type": "authorization_code",
                    "client_id": DEFAULT_CLIENT_ID,
                    "code_verifier": code_verifier,
                    "code": authorization_code,
                    "redirect_uri": DEFAULT_REDIRECT_URI,
                },
            )
        except ClientResponseError as err:
            if err.status in (401, 403):
                raise InvalidCredentialsError("Invalid credentials") from err
            raise RequestError(err) from err
        except Exception as err:  # pylint: disable=broad-except
            raise SimplipyError(err) from err

        api._save_token_data_from_response(token_data)
        await api._async_post_init()
        return api

    @classmethod
    async def async_from_refresh_token(
        cls,
        refresh_token: str,
        *,
        request_retries: int = DEFAULT_REQUEST_RETRIES,
        session: ClientSession,
    ) -> API:
        """Get an authenticated API object from a refresh token.

        Args:
            refresh_token: A refresh token.
            request_retries: The default number of request retries to use.
            session: An optional ``aiohttp`` ``ClientSession``.

        Returns:
            An authenticated API object.
        """
        api = cls(session=session, request_retries=request_retries)
        api.refresh_token = refresh_token
        await api.async_refresh_access_token()
        await api._async_post_init()
        return api

    async def _async_handle_on_backoff(self, _: dict[str, Any]) -> None:
        """Handle a backoff retry."""
        err_info = sys.exc_info()
        err: ClientResponseError = err_info[1].with_traceback(  # type: ignore
            err_info[2]
        )

        LOGGER.debug("Error during request attempt: %s", err)

        if err.status == 401 and self._token_last_refreshed:
            # Calculate the window between now and the last time the token was
            # refreshed:
            window = (utcnow() - self._token_last_refreshed).total_seconds()

            # Since we might have multiple requests (each running their own retry
            # sequence) land here, we only refresh the access token if it hasn't
            # been refreshed within the window (and we lock the attempt so other
            # requests can't try it at the same time):
            async with self._backoff_refresh_lock:
                if window < DEFAULT_TOKEN_EXPIRATION_WINDOW:
                    LOGGER.debug("Skipping refresh attempt since window hasn't busted")
                    return

                LOGGER.info("401 detected; attempting refresh token")
                await self.async_refresh_access_token()

    async def _async_post_init(self) -> None:
        """Perform some post-init actions."""
        auth_check_resp = await self._async_api_request("get", "api/authCheck")
        self.user_id = auth_check_resp["userId"]
        self.websocket = WebsocketClient(self)

    async def _async_api_request(
        self, method: str, endpoint: str, url_base: str = API_URL_BASE, **kwargs: Any
    ) -> dict[str, Any]:
        """Make an API request.

        Args:
            method: An HTTP method.
            endpoint: A relative API endpoint.
            url_base: The base URL of the API.
            **kwargs: Additional kwargs to send with the request.

        Returns:
            An API response payload.
        """
        kwargs.setdefault("headers", {})
        kwargs["headers"].setdefault("Host", API_URL_HOSTNAME)
        kwargs["headers"]["Content-Type"] = "application/json; charset=utf-8"
        kwargs["headers"]["User-Agent"] = DEFAULT_USER_AGENT
        if self.access_token:
            kwargs["headers"]["Authorization"] = f"Bearer {self.access_token}"

        data: dict[str, Any] | str = {}
        async with self.session.request(
            method, f"{url_base}/{endpoint}", **kwargs
        ) as resp:
            try:
                data = await resp.json(content_type=None)
            except JSONDecodeError:
                message = await resp.text()
                data = {"type": "DataParsingError", "message": message}

            if isinstance(data, str):
                # In some cases, the SimpliSafe API will return a quoted string
                # in its response body (e.g., "\"Unauthorized\""), which is
                # technically valid JSON. Additionally, SimpliSafe sets that
                # response's Content-Type header to application/json (#smh).
                # Together, these factors will allow a non-true-JSON  payload to
                # escape the try/except above. So, if we get here, we use the
                # string value (with quotes removed) to raise an error:
                message = data.replace('"', "")
                data = {"error": message}

            LOGGER.debug("Data received from /%s: %s", endpoint, data)

            raise_on_data_error(data)
            resp.raise_for_status()

        return data

    async def async_media(self, url: str) -> bytes | None:
        """Fetch a media file and return raw bytes to caller.

        Args:
            url: An absolute url for the media file.

        Returns:
            The raw bytes of the media file.
        """
        data = await self._async_media_data(url)
        return cast(bytes, data["bytes"])

    async def _async_media_request(self, url: str) -> dict[str, Any]:
        """Fetch a media file.

        Args:
            url: An absolute url for the media file.

        Returns:
            A dict that looks like { "bytes": <raw-bytes> }.
        """
        async with self.session.request(
            "get",
            url,
            headers={
                "User-Agent": DEFAULT_USER_AGENT,
                "Authorization": f"Bearer {self.access_token}",
            },
        ) as resp:
            resp.raise_for_status()
            return {"bytes": await resp.read()}

    @staticmethod
    def _handle_on_giveup(_: dict[str, Any]) -> None:
        """Handle a give up after retries are exhausted.

        Raises:
            RequestError: Raised upon an underlying HTTP error.
        """
        err_info = sys.exc_info()
        err = err_info[1].with_traceback(err_info[2])  # type: ignore
        raise RequestError(err) from err

    def _save_token_data_from_response(self, token_data: dict[str, Any]) -> None:
        """Save token data from a token response.

        Args:
            token_data: An API response payload.
        """
        self._token_last_refreshed = utcnow()
        self.access_token = token_data["access_token"]
        if refresh_token := token_data.get("refresh_token"):
            self.refresh_token = refresh_token

    @staticmethod
    def is_fatal_error(
        retriable_error_codes: list[int],
    ) -> Callable[[ClientResponseError], bool]:
        """Determine whether a ClientResponseError is fatal and shouldn't be retried.

        When sending general API requests:

        1. 401: We catch this, refresh the access token, and retry the original request.
        2. 409: SimpliSafe base stations regular synchronize themselves with the API,
                which is where this error can occur; we can't control when/how that
                happens (e.g., we might query the API in the middle of a base station
                update), so it should be viewed as retryable.

        But when fetching media files:

        3. 404: When fetching media files, you may get a 404 if the media file is not
                yet available to read. Keep trying however, and it will eventually
                return a 200.

        Args:
            retriable_error_codes: A list of retriable error status codes.

        Returns:
            A callable function used by backoff to check for errors.
        """

        def check(err: ClientResponseError) -> bool:
            """Perform the check.

            Args:
                err: An ``aiohttp`` ``ClientResponseError``

            Returns:
                Whether the error is a fatal one.
            """
            if err.status in retriable_error_codes:
                return False
            return 400 <= err.status < 500

        return check

    def _wrap_request_method(
        self,
        request_retries: int,
        retry_codes: list[int],
        request_func: Callable[..., Awaitable[dict[str, Any]]],
    ) -> Callable[..., Awaitable[dict[str, Any]]]:
        """Wrap a request method in backoff/retry logic.

        Args:
            request_retries: The number of retries to give a failed request.
            retry_codes: A list of HTTP status codes that cause the retry
                loop to continue.
            request_func: A function that performs the request.

        Returns:
            A version of the request callable that can do retries.
        """
        return backoff.on_exception(
            backoff.expo,
            ClientResponseError,
            giveup=self.is_fatal_error(retry_codes),  # type: ignore[arg-type]
            jitter=backoff.random_jitter,
            logger=LOGGER,
            max_tries=request_retries,
            on_backoff=self._async_handle_on_backoff,  # type: ignore[arg-type]
            on_giveup=self._handle_on_giveup,  # type: ignore[arg-type]
        )(request_func)

    def disable_request_retries(self) -> None:
        """Disable the request retry mechanism."""
        self.async_request = self._wrap_request_method(
            request_retries=1,
            retry_codes=[401, 409],
            request_func=self._async_api_request,
        )
        self._async_media_data = self._wrap_request_method(
            request_retries=1,
            retry_codes=[401, 404, 409],
            request_func=self._async_media_request,
        )

    def enable_request_retries(self) -> None:
        """Enable the request retry mechanism."""
        self.async_request = self._wrap_request_method(
            request_retries=self._request_retries,
            retry_codes=[401, 409],
            request_func=self._async_api_request,
        )
        self._async_media_data = self._wrap_request_method(
            request_retries=self._media_retries,
            retry_codes=[401, 404, 409],
            request_func=self._async_media_request,
        )

    def add_refresh_token_callback(
        self, callback: Callable[[str], Awaitable[None] | None]
    ) -> Callable[[], None]:
        """Add a callback that should be triggered when tokens are refreshed.

        Note that callbacks should expect to receive a refresh token as a parameter.

        Args:
            callback: The callback to execute.

        Returns:
            A callable to cancel the callback.
        """
        self._refresh_token_callbacks.append(callback)

        def remove() -> None:
            """Remove the callback."""
            self._refresh_token_callbacks.remove(callback)

        return remove

    async def async_get_systems(self) -> dict[int, SystemV2 | SystemV3]:
        """Get systems associated to the associated SimpliSafe account.

        In the dict that is returned, the keys are the subscription ID and the values
        are actual ``System`` objects.

        Returns:
            A dictionary of system IDs to System objects.
        """
        systems: dict[int, SystemV2 | SystemV3] = {}

        await self.async_update_subscription_data()

        for sid, subscription in self.subscription_data.items():
            if not subscription["status"]["hasBaseStation"]:
                LOGGER.info("Skipping inactive subscription: %s", sid)
                continue

            if not subscription["location"].get("system"):
                LOGGER.error("Skipping subscription with missing system data: %s", sid)
                continue

            system: SystemV2 | SystemV3
            if subscription["location"]["system"]["version"] == 2:
                system = SystemV2(self, sid)
            else:
                system = SystemV3(self, sid)

            # Update the system, but don't include subscription data itself, since it
            # will already have been fetched when the API was first queried:
            await system.async_update(include_subscription=False)
            system.generate_device_objects()
            systems[sid] = system

        return systems

    async def async_refresh_access_token(self) -> None:
        """Initiate a refresh of the access/refresh tokens.

        Note that this will execute any callbacks added via add_refresh_token_callback.

        Raises:
            InvalidCredentialsError: Raised on invalid username/password.
            RequestError: Raised on general HTTP error.
            SimplipyError: Raised on an unknown error.
        """
        try:
            token_data = await self._async_api_request(
                "post",
                "oauth/token",
                url_base=AUTH_URL_BASE,
                headers={"Host": AUTH_URL_HOSTNAME},
                json={
                    "grant_type": "refresh_token",
                    "client_id": DEFAULT_CLIENT_ID,
                    "refresh_token": self.refresh_token,
                },
            )
        except ClientResponseError as err:
            if err.status in (401, 403):
                raise InvalidCredentialsError("Invalid refresh token") from err
            raise RequestError(
                f"Request error while attempting to refresh access token: {err}"
            ) from err
        except Exception as err:  # pylint: disable-broad-except
            raise SimplipyError(
                f"Error while attempting to refresh access token: {err}"
            ) from err

        self._save_token_data_from_response(token_data)

        for callback in self._refresh_token_callbacks:
            execute_callback(callback, self.refresh_token)

    async def async_update_subscription_data(self) -> None:
        """Get the latest subscription data."""
        subscription_resp = await self.async_request(
            "get", f"users/{self.user_id}/subscriptions", params={"activeOnly": "true"}
        )
        self.subscription_data = {
            subscription["sid"]: subscription
            for subscription in subscription_resp["subscriptions"]
        }