Debian Codegraph @

hass_nabucasa/alexa_api.py

raw
1 """This module provides Alexa API functionalities."""
2
3 from __future__ import annotations
4
5 from typing import TypedDict, cast
6
7 from .api import ApiBase, CloudApiError, CloudApiRawResponse, api_exception_handler
8
9 _ALEXA_RELINK_REASONS = frozenset({"RefreshTokenNotFound", "UnknownRegion"})
10
11
12 class AlexaApiError(CloudApiError):
13 """Exception raised when handling Alexa API."""
14
15
16 class AlexaApiNeedsRelinkError(AlexaApiError):
17 """Exception raised when Alexa API needs to be re-linked."""
18
19
20 class AlexaApiNoTokenError(AlexaApiError):
21 """Exception raised when Alexa API access token is not available."""
22
23
24 class AlexaAccessTokenDetails(TypedDict):
25 """Alexa access token details from Alexa API."""
26
27 access_token: str
28 expires_in: int
29 event_endpoint: str
30
31
32 class AlexaAccessTokenError(TypedDict):
33 """Alexa access token error details from Alexa API."""
34
35 reason: str
36
37
38 class AlexaApi(ApiBase):
39 """Class to help communicate with the Alexa API."""
40
41 @api_exception_handler(AlexaApiError)
42 async def access_token(self) -> AlexaAccessTokenDetails:
43 """Get the Alexa API access token."""
44 details: CloudApiRawResponse = await self._call_cloud_api(
45 method="POST",
46 action="alexa_access_token",
47 raw_response=True,
48 )
49
50 if details.response.status == 400:
51 if (
52 isinstance(details.data, dict)
53 and (reason := details.data.get("reason"))
54 and reason in _ALEXA_RELINK_REASONS
55 ):
56 raise AlexaApiNeedsRelinkError(
57 reason,
58 reason=reason,
59 status=details.response.status,
60 ) from None
61
62 raise AlexaApiNoTokenError(
63 "No access token available",
64 status=details.response.status,
65 ) from None
66
67 if details.response.status >= 400:
68 raise CloudApiError(
69 f"Failed to fetch: ({details.response.status}) ",
70 status=details.response.status,
71 reason=(
72 details.data.get("reason")
73 if isinstance(details.data, dict)
74 else None
75 ),
76 )
77
78 return cast("AlexaAccessTokenDetails", details.data)