File: api_async.py

package info (click to toggle)
python-yalexs 9.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,120 kB
  • sloc: python: 7,916; makefile: 3; sh: 2
file content (560 lines) | stat: -rw-r--r-- 19,532 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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
"""Api calls for sync."""

from __future__ import annotations

import asyncio
import logging
from http import HTTPStatus
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from .capabilities import CapabilitiesResponse

from aiohttp import (
    ClientConnectionError,
    ClientOSError,
    ClientResponse,
    ClientResponseError,
    ClientSession,
    ClientSSLError,
    ServerDisconnectedError,
)

from .activity import ActivityTypes
from .alarm import Alarm, AlarmDevice, ArmState
from .api_common import (
    API_EXCEPTION_RETRY_TIME,
    API_LOCK_ASYNC_URL,
    API_LOCK_URL,
    API_RETRY_ATTEMPTS,
    API_RETRY_TIME,
    API_STATUS_ASYNC_URL,
    API_UNLATCH_ASYNC_URL,
    API_UNLATCH_URL,
    API_UNLOCK_ASYNC_URL,
    API_UNLOCK_URL,
    HEADER_ACCEPT_VERSION,
    HYPER_BRIDGE_PARAM,
    ApiCommon,
    _api_headers,
    _convert_lock_result_to_activities,
    _process_activity_json,
    _process_alarm_devices_json,
    _process_alarms_json,
    _process_doorbells_json,
    _process_locks_json,
)
from .const import DEFAULT_BRAND, HEADER_ACCESS_TOKEN, HEADER_AUGUST_ACCESS_TOKEN
from .doorbell import Doorbell, DoorbellDetail
from .exceptions import InvalidAuth, YaleApiError
from .lock import (
    Lock,
    LockDetail,
    LockDoorStatus,
    LockStatus,
    determine_door_state,
    determine_lock_status,
)
from .pin import Pin

_LOGGER = logging.getLogger(__name__)


def _obscure_payload(payload: dict[str, Any]) -> dict[str, Any]:
    """Obscure the payload for logging."""
    if payload is None:
        return None
    if "password" in payload:
        payload = payload.copy()
        payload["password"] = "****"  # nosec
    return payload


def _obscure_headers(headers: dict[str, Any]) -> dict[str, Any]:
    """Obscure the headers for logging."""
    if headers is None:
        return None
    for obscure_header in (
        "x-august-access-token",
        "x-access-token",
        "x-august-api-key",
        "x-api-key",
    ):
        if obscure_header in headers:
            headers = headers.copy()
            headers[obscure_header] = "****"
    return headers


class ApiAsync(ApiCommon):
    """Async api."""

    def __init__(
        self,
        aiohttp_session: ClientSession,
        timeout=10,
        command_timeout=60,
        brand=DEFAULT_BRAND,
    ) -> None:
        self._timeout = timeout
        self._command_timeout = command_timeout
        self._aiohttp_session = aiohttp_session
        super().__init__(brand)

    async def async_get_session(
        self, install_id: str, identifier: str, password: str
    ) -> ClientResponse:
        return await self._async_dict_to_api(
            self._build_get_session_request(install_id, identifier, password)
        )

    async def async_send_verification_code(
        self, access_token: str, login_method: str, username: str
    ) -> ClientResponse:
        return await self._async_dict_to_api(
            self._build_send_verification_code_request(
                access_token, login_method, username
            )
        )

    async def async_validate_verification_code(
        self,
        access_token: str,
        login_method: str,
        username: str,
        verification_code: str,
    ) -> ClientResponse:
        return await self._async_dict_to_api(
            self._build_validate_verification_code_request(
                access_token, login_method, username, verification_code
            )
        )

    async def async_get_doorbells(self, access_token: str) -> list[Doorbell]:
        if not self.brand_supports_doorbells:
            return []
        response = await self._async_dict_to_api(
            self._build_get_doorbells_request(access_token)
        )
        return _process_doorbells_json(await response.json())

    async def async_get_doorbell_detail(
        self, access_token: str, doorbell_id: str
    ) -> DoorbellDetail:
        response = await self._async_dict_to_api(
            self._build_get_doorbell_detail_request(access_token, doorbell_id)
        )
        return DoorbellDetail(await response.json())

    async def async_wakeup_doorbell(
        self, access_token: str, doorbell_id: str
    ) -> ClientResponse:
        await self._async_dict_to_api(
            self._build_wakeup_doorbell_request(access_token, doorbell_id)
        )
        return True

    async def async_get_user(self, access_token: str) -> dict[str, Any]:
        response = await self._async_dict_to_api(
            self._build_get_user_request(access_token)
        )
        return await response.json()

    async def async_get_houses(self, access_token: str) -> ClientResponse:
        return await self._async_dict_to_api(
            self._build_get_houses_request(access_token)
        )

    async def async_get_house(self, access_token: str, house_id: str) -> dict[str, Any]:
        response = await self._async_dict_to_api(
            self._build_get_house_request(access_token, house_id)
        )
        return await response.json()

    async def async_get_house_activities(
        self, access_token: str, house_id: str, limit: int = 8
    ) -> list[ActivityTypes]:
        response = await self._async_dict_to_api(
            self._build_get_house_activities_request(
                access_token, house_id, limit=limit
            )
        )
        return _process_activity_json(await response.json())

    async def async_get_locks(self, access_token: str) -> list[Lock]:
        response = await self._async_dict_to_api(
            self._build_get_locks_request(access_token)
        )
        return _process_locks_json(await response.json())

    async def async_get_operable_locks(self, access_token: str) -> list[Lock]:
        locks = await self.async_get_locks(access_token)

        return [lock for lock in locks if lock.is_operable]

    async def async_get_lock_detail(
        self, access_token: str, lock_id: str
    ) -> LockDetail:
        response = await self._async_dict_to_api(
            self._build_get_lock_detail_request(access_token, lock_id)
        )
        return LockDetail(await response.json())

    async def async_get_lock_status(
        self, access_token: str, lock_id: str, door_status=False
    ) -> LockStatus:
        response = await self._async_dict_to_api(
            self._build_get_lock_status_request(access_token, lock_id)
        )
        json_dict = await response.json()

        if door_status:
            return (
                determine_lock_status(json_dict.get("status")),
                determine_door_state(json_dict.get("doorState")),
            )

        return determine_lock_status(json_dict.get("status"))

    async def async_get_lock_door_status(
        self, access_token: str, lock_id: str, lock_status=False
    ) -> LockDoorStatus | tuple[LockDoorStatus, LockStatus]:
        response = await self._async_dict_to_api(
            self._build_get_lock_status_request(access_token, lock_id)
        )
        json_dict = await response.json()

        if lock_status:
            return (
                determine_door_state(json_dict.get("doorState")),
                determine_lock_status(json_dict.get("status")),
            )

        return determine_door_state(json_dict.get("doorState"))

    async def async_get_pins(self, access_token: str, lock_id: str) -> list[Pin]:
        response = await self._async_dict_to_api(
            self._build_get_pins_request(access_token, lock_id)
        )
        json_dict = await response.json()

        return [Pin(pin_json) for pin_json in json_dict.get("loaded", [])]

    async def async_get_lock_capabilities(
        self, access_token: str, serial_number: str
    ) -> CapabilitiesResponse:
        response = await self._async_dict_to_api(
            self._build_get_capabilities_request(access_token, serial_number)
        )
        return await response.json()

    async def _async_call_lock_operation(
        self, url_str: str, access_token: str, lock_id: str
    ) -> dict[str, Any]:
        response = await self._async_dict_to_api(
            self._build_call_lock_operation_request(
                url_str, access_token, lock_id, self._command_timeout
            )
        )
        return await response.json()

    async def _async_call_async_lock_operation(
        self, url_str: str, access_token: str, lock_id: str
    ) -> str:
        """Call an operation that will queue."""
        response = await self._async_dict_to_api(
            self._build_call_lock_operation_request(
                url_str, access_token, lock_id, self._command_timeout
            )
        )
        return await response.text()

    async def _async_lock(self, access_token: str, lock_id: str) -> str:
        return await self._async_call_lock_operation(
            API_LOCK_URL, access_token, lock_id
        )

    async def async_lock(self, access_token: str, lock_id: str) -> str:
        """Execute a remote lock operation.

        Returns a LockStatus state.
        """
        return determine_lock_status(
            (await self._async_lock(access_token, lock_id)).get("status")
        )

    async def async_lock_async(
        self, access_token: str, lock_id: str, hyper_bridge=True
    ) -> str:
        """Queue a remote lock operation and get the response via pubnub."""
        if hyper_bridge:
            return await self._async_call_async_lock_operation(
                f"{API_LOCK_ASYNC_URL}{HYPER_BRIDGE_PARAM}", access_token, lock_id
            )
        return await self._async_call_async_lock_operation(
            API_LOCK_ASYNC_URL, access_token, lock_id
        )

    async def async_lock_return_activities(
        self, access_token: str, lock_id: str
    ) -> list[ActivityTypes]:
        """Execute a remote lock operation.

        Returns an array of one or more yalexs.activity.Activity objects

        If the lock supports door sense one of the activities
        will include the current door state.
        """
        return _convert_lock_result_to_activities(
            await self._async_lock(access_token, lock_id)
        )

    async def _async_unlatch(self, access_token: str, lock_id: str) -> dict[str, Any]:
        return await self._async_call_lock_operation(
            API_UNLATCH_URL, access_token, lock_id
        )

    async def async_unlatch(self, access_token: str, lock_id: str) -> LockStatus:
        """Execute a remote unlatch operation.

        Returns a LockStatus state.
        """
        return determine_lock_status(
            (await self._async_unlatch(access_token, lock_id)).get("status")
        )

    async def async_unlatch_async(
        self, access_token: str, lock_id: str, hyper_bridge=True
    ) -> str:
        """Queue a remote unlatch operation and get the response via pubnub."""
        if hyper_bridge:
            return await self._async_call_async_lock_operation(
                f"{API_UNLATCH_ASYNC_URL}{HYPER_BRIDGE_PARAM}", access_token, lock_id
            )
        return await self._async_call_async_lock_operation(
            API_UNLATCH_ASYNC_URL, access_token, lock_id
        )

    async def async_unlatch_return_activities(
        self, access_token: str, lock_id: str
    ) -> list[ActivityTypes]:
        """Execute a remote lock operation.

        Returns an array of one or more yalexs.activity.Activity objects

        If the lock supports door sense one of the activities
        will include the current door state.
        """
        return _convert_lock_result_to_activities(
            await self._async_unlatch(access_token, lock_id)
        )

    async def _async_unlock(self, access_token: str, lock_id: str) -> dict[str, Any]:
        return await self._async_call_lock_operation(
            API_UNLOCK_URL, access_token, lock_id
        )

    async def async_unlock(self, access_token: str, lock_id: str) -> LockStatus:
        """Execute a remote unlock operation.

        Returns a LockStatus state.
        """
        return determine_lock_status(
            (await self._async_unlock(access_token, lock_id)).get("status")
        )

    async def async_unlock_async(
        self, access_token: str, lock_id: str, hyper_bridge=True
    ) -> str:
        """Queue a remote unlock operation and get the response via pubnub."""
        if hyper_bridge:
            return await self._async_call_async_lock_operation(
                f"{API_UNLOCK_ASYNC_URL}{HYPER_BRIDGE_PARAM}", access_token, lock_id
            )
        return await self._async_call_async_lock_operation(
            API_UNLOCK_ASYNC_URL, access_token, lock_id
        )

    async def async_unlock_return_activities(
        self, access_token: str, lock_id: str
    ) -> list[ActivityTypes]:
        """Execute a remote lock operation.

        Returns an array of one or more yalexs.activity.Activity objects

        If the lock supports door sense one of the activities
        will include the current door state.
        """
        return _convert_lock_result_to_activities(
            await self._async_unlock(access_token, lock_id)
        )

    async def async_status_async(
        self, access_token: str, lock_id: str, hyper_bridge=True
    ) -> str:
        """Queue a remote unlock operation and get the status via pubnub."""
        if hyper_bridge:
            return await self._async_call_async_lock_operation(
                f"{API_STATUS_ASYNC_URL}{HYPER_BRIDGE_PARAM}", access_token, lock_id
            )
        return await self._async_call_async_lock_operation(
            API_STATUS_ASYNC_URL, access_token, lock_id
        )

    async def async_get_alarms(self, access_token: str) -> list[Alarm]:
        if not self.brand_supports_alarms:
            return []
        response = await self._async_dict_to_api(
            self._build_get_alarms_request(access_token)
        )
        return _process_alarms_json(await response.json())

    async def async_get_alarm_devices(
        self, access_token: str, alarm: Alarm
    ) -> list[AlarmDevice]:
        if not self.brand_supports_alarms:
            return []
        response = await self._async_dict_to_api(
            self._build_get_alarm_devices_request(
                access_token, alarm_id=alarm.device_id
            )
        )
        return _process_alarm_devices_json(await response.json())

    async def async_arm_alarm(
        self, access_token: str, alarm: Alarm, arm_state: ArmState
    ):
        if not self.brand_supports_alarms:
            return {}
        response = await self._async_dict_to_api(
            self._build_call_alarm_state_request(access_token, alarm, arm_state)
        )
        return await response.json()

    async def async_refresh_access_token(self, access_token: str) -> str:
        """Obtain a new api token."""
        response = await self._async_dict_to_api(
            self._build_refresh_access_token_request(access_token)
        )
        response_headers = response.headers
        return (
            response_headers.get(HEADER_ACCESS_TOKEN)
            or response_headers[HEADER_AUGUST_ACCESS_TOKEN]
        )

    async def async_add_websocket_subscription(
        self, access_token: str
    ) -> dict[str, Any]:
        """Add a websocket subscription."""
        response = await self._async_dict_to_api(
            self._build_websocket_subscribe_request(access_token)
        )
        return await response.json()

    async def async_get_websocket_subscriptions(self, access_token: str) -> str:
        """Get websocket subscriptions."""
        response = await self._async_dict_to_api(
            self._build_websocket_get_request(access_token)
        )
        return await response.text()

    async def _async_dict_to_api(self, api_dict: dict[str, Any]) -> ClientResponse:
        url = api_dict.pop("url")
        method = api_dict.pop("method")
        access_token = api_dict.pop("access_token", None)
        payload = api_dict.get("params") or api_dict.get("json")

        if "headers" not in api_dict:
            api_dict["headers"] = _api_headers(
                access_token=access_token, brand=self.brand
            )

        if "version" in api_dict:
            api_dict["headers"][HEADER_ACCEPT_VERSION] = api_dict["version"]
            del api_dict["version"]

        if "timeout" not in api_dict:
            api_dict["timeout"] = self._timeout

        debug_enabled = _LOGGER.isEnabledFor(logging.DEBUG)

        if debug_enabled:
            _LOGGER.debug(
                "About to call %s with header=%s and payload=%s",
                url,
                _obscure_headers(api_dict["headers"]),
                _obscure_payload(payload),
            )

        attempts = 0
        while attempts < API_RETRY_ATTEMPTS:
            attempts += 1
            try:
                response = await self._aiohttp_session.request(method, url, **api_dict)
            except (
                ClientOSError,
                ClientSSLError,
                ServerDisconnectedError,
                ClientConnectionError,
            ) as ex:
                # Try again if we get disconnected
                # We may get [Errno 104] Connection reset by peer or a
                # transient disconnect/SSL error
                if attempts == API_RETRY_ATTEMPTS:
                    raise YaleApiError(
                        f"Failed to connect to August API: {ex}", ex
                    ) from ex
                await asyncio.sleep(API_EXCEPTION_RETRY_TIME)
                continue
            if debug_enabled:
                _LOGGER.debug(
                    "Received API response from url: %s, code: %s, headers: %s, content: %s",
                    url,
                    response.status,
                    _obscure_headers(response.headers),
                    await response.read(),
                )
            if response.status in (429, 502):
                # 429 - rate limited
                # 502 - bad gateway
                _LOGGER.debug(
                    "API sent a %s (attempt: %d), sleeping and trying again",
                    response.status,
                    attempts,
                )
                await asyncio.sleep(API_RETRY_TIME)
                continue
            break

        _raise_response_exceptions(response)

        return response


def _raise_response_exceptions(response: ClientResponse) -> None:
    """Raise exceptions for known error codes."""
    try:
        response.raise_for_status()
    except ClientResponseError as err:
        if err.status in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN):
            raise InvalidAuth(
                f"Authentication failed: Verify brand is correct: {err.message}", err
            ) from err
        if err.status == 422:
            raise YaleApiError(
                f"The operation failed because the bridge (connect) is offline: {err.message}",
                err,
            ) from err
        if err.status == 423:
            raise YaleApiError(
                f"The operation failed because the bridge (connect) is in use: {err.message}",
                err,
            ) from err
        if err.status == 408:
            raise YaleApiError(
                f"The operation timed out because the bridge (connect) failed to respond: {err.message}",
                err,
            ) from err
        raise YaleApiError(
            f"The operation failed with error code {err.status}: {err.message}.", err
        ) from err