| 1 |
"""Helpers to help with account linking.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
import logging |
| 7 |
from typing import TYPE_CHECKING, Any |
| 8 |
|
| 9 |
from aiohttp.client_ws import ClientWebSocketResponse |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
from . import Cloud, _ClientT |
| 13 |
|
| 14 |
_LOGGER = logging.getLogger(__name__) |
| 15 |
|
| 16 |
# Each function can only be called once. |
| 17 |
ERR_ALREADY_CONSUMED = "already_consumed" |
| 18 |
|
| 19 |
# If the specified service is not supported |
| 20 |
ERR_UNSUPORTED = "unsupported" |
| 21 |
|
| 22 |
# If authorizing is currently unavailable |
| 23 |
ERR_UNAVAILABLE = "unavailable" |
| 24 |
|
| 25 |
# If we try to get tokens without being connected. |
| 26 |
ERR_NOT_CONNECTED = "not_connected" |
| 27 |
|
| 28 |
# Unknown error |
| 29 |
ERR_UNKNOWN = "unknown" |
| 30 |
|
| 31 |
# This error will be converted to asyncio.TimeoutError |
| 32 |
ERR_TIMEOUT = "timeout" |
| 33 |
|
| 34 |
|
| 35 |
class AccountLinkException(Exception): |
| 36 |
"""Base exception for when account link errors happen.""" |
| 37 |
|
| 38 |
def __init__(self, code: str) -> None: |
| 39 |
"""Initialize the exception.""" |
| 40 |
super().__init__(code) |
| 41 |
self.code = code |
| 42 |
|
| 43 |
|
| 44 |
def _update_token_response(tokens: dict[str, str], service: str) -> None: |
| 45 |
"""Update token response in place.""" |
| 46 |
tokens["service"] = service |
| 47 |
|
| 48 |
|
| 49 |
class AuthorizeAccountHelper: |
| 50 |
"""Class to help the user authorize a third party account with Home Assistant.""" |
| 51 |
|
| 52 |
def __init__(self, cloud: Cloud[_ClientT], service: str) -> None: |
| 53 |
"""Initialize the authorize account helper.""" |
| 54 |
self.cloud = cloud |
| 55 |
self.service = service |
| 56 |
self._client: ClientWebSocketResponse | None = None |
| 57 |
|
| 58 |
async def async_get_authorize_url(self) -> str: |
| 59 |
"""Generate the url where the user can authorize Home Assistant.""" |
| 60 |
if self._client is not None: |
| 61 |
raise AccountLinkException(ERR_ALREADY_CONSUMED) |
| 62 |
|
| 63 |
_LOGGER.debug("Opening connection for %s", self.service) |
| 64 |
|
| 65 |
self._client = await self.cloud.client.websession.ws_connect( |
| 66 |
f"https://{self.cloud.account_link_server}/v1", |
| 67 |
) |
| 68 |
await self._client.send_json({"service": self.service}) |
| 69 |
|
| 70 |
try: |
| 71 |
response = await self._get_response() |
| 72 |
except asyncio.CancelledError: |
| 73 |
await self._client.close() |
| 74 |
self._client = None |
| 75 |
raise |
| 76 |
|
| 77 |
authorize_url: str = response["authorize_url"] |
| 78 |
return authorize_url |
| 79 |
|
| 80 |
async def async_get_tokens(self) -> dict[str, str]: |
| 81 |
"""Return the tokens when the user finishes authorizing.""" |
| 82 |
if self._client is None: |
| 83 |
raise AccountLinkException(ERR_NOT_CONNECTED) |
| 84 |
|
| 85 |
try: |
| 86 |
response = await self._get_response() |
| 87 |
finally: |
| 88 |
await self._client.close() |
| 89 |
self._client = None |
| 90 |
|
| 91 |
_LOGGER.debug("Received tokens for %s", self.service) |
| 92 |
tokens: dict[str, str] = response["tokens"] |
| 93 |
|
| 94 |
_update_token_response(tokens, self.service) |
| 95 |
return tokens |
| 96 |
|
| 97 |
async def _get_response(self) -> dict[str, Any]: |
| 98 |
"""Read a response from the connection and handle errors.""" |
| 99 |
assert self._client is not None |
| 100 |
response: dict[str, Any] = await self._client.receive_json() |
| 101 |
|
| 102 |
if "error" in response: |
| 103 |
if response["error"] == ERR_TIMEOUT: |
| 104 |
raise TimeoutError |
| 105 |
|
| 106 |
raise AccountLinkException(response["error"]) |
| 107 |
|
| 108 |
return response |
| 109 |
|
| 110 |
|
| 111 |
async def async_fetch_access_token( |
| 112 |
cloud: Cloud[_ClientT], |
| 113 |
service: str, |
| 114 |
refresh_token: str, |
| 115 |
) -> dict[str, str]: |
| 116 |
"""Fetch access tokens using a refresh token.""" |
| 117 |
_LOGGER.debug("Fetching tokens for %s", service) |
| 118 |
resp = await cloud.client.websession.post( |
| 119 |
f"https://{cloud.account_link_server}/refresh_token/{service}", |
| 120 |
json={"refresh_token": refresh_token}, |
| 121 |
) |
| 122 |
resp.raise_for_status() |
| 123 |
tokens: dict[str, str] = await resp.json() |
| 124 |
_update_token_response(tokens, service) |
| 125 |
return tokens |
| 126 |
|
| 127 |
|
| 128 |
async def async_fetch_available_services( |
| 129 |
cloud: Cloud[_ClientT], |
| 130 |
) -> list[dict[str, Any]]: |
| 131 |
"""Fetch available services.""" |
| 132 |
resp = await cloud.client.websession.get( |
| 133 |
f"https://{cloud.account_link_server}/services", |
| 134 |
) |
| 135 |
resp.raise_for_status() |
| 136 |
content: list[dict[str, Any]] = await resp.json() |
| 137 |
return content |