2020-10-21 08:17:49 +00:00
|
|
|
"""Config flow to configure Nest.
|
|
|
|
|
|
|
|
This configuration flow supports two APIs:
|
|
|
|
- The new Device Access program and the Smart Device Management API
|
|
|
|
- The legacy nest API
|
|
|
|
|
|
|
|
NestFlowHandler is an implementation of AbstractOAuth2FlowHandler with
|
|
|
|
some overrides to support the old APIs auth flow. That is, for the new
|
|
|
|
API this class has hardly any special config other than url parameters,
|
|
|
|
and everything else custom is for the old api. When configured with the
|
|
|
|
new api via NestFlowHandler.register_sdm_api, the custom methods just
|
|
|
|
invoke the AbstractOAuth2FlowHandler methods.
|
|
|
|
"""
|
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
import asyncio
|
|
|
|
from collections import OrderedDict
|
|
|
|
import logging
|
2018-06-15 19:19:58 +00:00
|
|
|
import os
|
2020-10-21 08:17:49 +00:00
|
|
|
from typing import Dict
|
2018-06-13 15:14:52 +00:00
|
|
|
|
|
|
|
import async_timeout
|
|
|
|
import voluptuous as vol
|
|
|
|
|
2018-09-17 08:12:46 +00:00
|
|
|
from homeassistant import config_entries
|
2018-06-13 15:14:52 +00:00
|
|
|
from homeassistant.core import callback
|
|
|
|
from homeassistant.exceptions import HomeAssistantError
|
2020-10-21 08:17:49 +00:00
|
|
|
from homeassistant.helpers import config_entry_oauth2_flow
|
2018-06-13 15:14:52 +00:00
|
|
|
from homeassistant.util.json import load_json
|
|
|
|
|
2020-10-21 08:17:49 +00:00
|
|
|
from .const import DATA_SDM, DOMAIN, SDM_SCOPES
|
2018-06-13 15:14:52 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
DATA_FLOW_IMPL = "nest_flow_implementation"
|
2018-06-13 15:14:52 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
@callback
|
2019-07-31 19:25:30 +00:00
|
|
|
def register_flow_implementation(hass, domain, name, gen_authorize_url, convert_code):
|
2020-10-21 08:17:49 +00:00
|
|
|
"""Register a flow implementation for legacy api.
|
2018-06-13 15:14:52 +00:00
|
|
|
|
|
|
|
domain: Domain of the component responsible for the implementation.
|
|
|
|
name: Name of the component.
|
|
|
|
gen_authorize_url: Coroutine function to generate the authorize url.
|
|
|
|
convert_code: Coroutine function to convert a code to an access token.
|
|
|
|
"""
|
|
|
|
if DATA_FLOW_IMPL not in hass.data:
|
|
|
|
hass.data[DATA_FLOW_IMPL] = OrderedDict()
|
|
|
|
|
|
|
|
hass.data[DATA_FLOW_IMPL][domain] = {
|
2019-07-31 19:25:30 +00:00
|
|
|
"domain": domain,
|
|
|
|
"name": name,
|
|
|
|
"gen_authorize_url": gen_authorize_url,
|
|
|
|
"convert_code": convert_code,
|
2018-06-13 15:14:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
class NestAuthError(HomeAssistantError):
|
|
|
|
"""Base class for Nest auth errors."""
|
|
|
|
|
|
|
|
|
|
|
|
class CodeInvalid(NestAuthError):
|
|
|
|
"""Raised when invalid authorization code."""
|
|
|
|
|
|
|
|
|
2020-10-24 18:48:28 +00:00
|
|
|
class UnexpectedStateError(HomeAssistantError):
|
|
|
|
"""Raised when the config flow is invoked in a 'should not happen' case."""
|
|
|
|
|
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
@config_entries.HANDLERS.register(DOMAIN)
|
2020-10-21 08:17:49 +00:00
|
|
|
class NestFlowHandler(
|
|
|
|
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
|
|
|
|
):
|
|
|
|
"""Config flow to handle authentication for both APIs."""
|
2018-06-13 15:14:52 +00:00
|
|
|
|
2020-10-21 08:17:49 +00:00
|
|
|
DOMAIN = DOMAIN
|
2018-06-13 15:14:52 +00:00
|
|
|
VERSION = 1
|
2018-09-17 08:12:46 +00:00
|
|
|
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_PUSH
|
2018-06-13 15:14:52 +00:00
|
|
|
|
2020-12-20 00:41:29 +00:00
|
|
|
def __init__(self):
|
|
|
|
"""Initialize NestFlowHandler."""
|
|
|
|
super().__init__()
|
|
|
|
# When invoked for reauth, allows updating an existing config entry
|
|
|
|
self._reauth = False
|
|
|
|
|
2020-10-21 08:17:49 +00:00
|
|
|
@classmethod
|
|
|
|
def register_sdm_api(cls, hass):
|
|
|
|
"""Configure the flow handler to use the SDM API."""
|
|
|
|
if DOMAIN not in hass.data:
|
|
|
|
hass.data[DOMAIN] = {}
|
|
|
|
hass.data[DOMAIN][DATA_SDM] = {}
|
|
|
|
|
|
|
|
def is_sdm_api(self):
|
|
|
|
"""Return true if this flow is setup to use SDM API."""
|
|
|
|
return DOMAIN in self.hass.data and DATA_SDM in self.hass.data[DOMAIN]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def logger(self) -> logging.Logger:
|
|
|
|
"""Return logger."""
|
|
|
|
return logging.getLogger(__name__)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def extra_authorize_data(self) -> Dict[str, str]:
|
|
|
|
"""Extra data that needs to be appended to the authorize url."""
|
|
|
|
return {
|
|
|
|
"scope": " ".join(SDM_SCOPES),
|
|
|
|
# Add params to ensure we get back a refresh token
|
|
|
|
"access_type": "offline",
|
|
|
|
"prompt": "consent",
|
|
|
|
}
|
|
|
|
|
|
|
|
async def async_oauth_create_entry(self, data: dict) -> dict:
|
|
|
|
"""Create an entry for the SDM flow."""
|
2020-12-20 00:41:29 +00:00
|
|
|
assert self.is_sdm_api(), "Step only supported for SDM API"
|
2020-10-21 08:17:49 +00:00
|
|
|
data[DATA_SDM] = {}
|
2020-12-20 00:41:29 +00:00
|
|
|
await self.async_set_unique_id(DOMAIN)
|
|
|
|
# Update existing config entry when in the reauth flow. This
|
|
|
|
# integration only supports one config entry so remove any prior entries
|
|
|
|
# added before the "single_instance_allowed" check was added
|
|
|
|
existing_entries = self.hass.config_entries.async_entries(DOMAIN)
|
|
|
|
if existing_entries:
|
|
|
|
updated = False
|
|
|
|
for entry in existing_entries:
|
|
|
|
if updated:
|
|
|
|
await self.hass.config_entries.async_remove(entry.entry_id)
|
|
|
|
continue
|
|
|
|
updated = True
|
|
|
|
self.hass.config_entries.async_update_entry(
|
|
|
|
entry, data=data, unique_id=DOMAIN
|
|
|
|
)
|
|
|
|
await self.hass.config_entries.async_reload(entry.entry_id)
|
|
|
|
return self.async_abort(reason="reauth_successful")
|
|
|
|
|
2020-10-21 08:17:49 +00:00
|
|
|
return await super().async_oauth_create_entry(data)
|
2018-06-13 15:14:52 +00:00
|
|
|
|
2020-12-20 00:41:29 +00:00
|
|
|
async def async_step_reauth(self, user_input=None):
|
|
|
|
"""Perform reauth upon an API authentication error."""
|
|
|
|
assert self.is_sdm_api(), "Step only supported for SDM API"
|
|
|
|
self._reauth = True # Forces update of existing config entry
|
|
|
|
return await self.async_step_reauth_confirm()
|
|
|
|
|
|
|
|
async def async_step_reauth_confirm(self, user_input=None):
|
|
|
|
"""Confirm reauth dialog."""
|
|
|
|
assert self.is_sdm_api(), "Step only supported for SDM API"
|
|
|
|
if user_input is None:
|
|
|
|
return self.async_show_form(
|
|
|
|
step_id="reauth_confirm",
|
|
|
|
data_schema=vol.Schema({}),
|
|
|
|
)
|
|
|
|
return await self.async_step_user()
|
|
|
|
|
2018-08-09 11:24:14 +00:00
|
|
|
async def async_step_user(self, user_input=None):
|
|
|
|
"""Handle a flow initialized by the user."""
|
2020-10-21 08:17:49 +00:00
|
|
|
if self.is_sdm_api():
|
2020-12-20 00:41:29 +00:00
|
|
|
# Reauth will update an existing entry
|
|
|
|
if self.hass.config_entries.async_entries(DOMAIN) and not self._reauth:
|
|
|
|
return self.async_abort(reason="single_instance_allowed")
|
2020-10-21 08:17:49 +00:00
|
|
|
return await super().async_step_user(user_input)
|
2018-08-09 11:24:14 +00:00
|
|
|
return await self.async_step_init(user_input)
|
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
async def async_step_init(self, user_input=None):
|
|
|
|
"""Handle a flow start."""
|
2020-12-20 00:41:29 +00:00
|
|
|
assert not self.is_sdm_api(), "Step only supported for legacy API"
|
2020-10-21 08:17:49 +00:00
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
flows = self.hass.data.get(DATA_FLOW_IMPL, {})
|
|
|
|
|
|
|
|
if self.hass.config_entries.async_entries(DOMAIN):
|
2020-10-11 12:47:30 +00:00
|
|
|
return self.async_abort(reason="single_instance_allowed")
|
2018-06-13 15:14:52 +00:00
|
|
|
|
2018-07-23 08:16:05 +00:00
|
|
|
if not flows:
|
2020-10-11 12:47:30 +00:00
|
|
|
return self.async_abort(reason="missing_configuration")
|
2018-06-13 15:14:52 +00:00
|
|
|
|
2018-07-23 08:16:05 +00:00
|
|
|
if len(flows) == 1:
|
2018-06-13 15:14:52 +00:00
|
|
|
self.flow_impl = list(flows)[0]
|
|
|
|
return await self.async_step_link()
|
|
|
|
|
2018-07-23 08:16:05 +00:00
|
|
|
if user_input is not None:
|
2019-07-31 19:25:30 +00:00
|
|
|
self.flow_impl = user_input["flow_impl"]
|
2018-06-13 15:14:52 +00:00
|
|
|
return await self.async_step_link()
|
|
|
|
|
|
|
|
return self.async_show_form(
|
2019-07-31 19:25:30 +00:00
|
|
|
step_id="init",
|
|
|
|
data_schema=vol.Schema({vol.Required("flow_impl"): vol.In(list(flows))}),
|
2018-06-13 15:14:52 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
async def async_step_link(self, user_input=None):
|
|
|
|
"""Attempt to link with the Nest account.
|
|
|
|
|
|
|
|
Route the user to a website to authenticate with Nest. Depending on
|
|
|
|
implementation type we expect a pin or an external component to
|
|
|
|
deliver the authentication code.
|
|
|
|
"""
|
2020-12-20 00:41:29 +00:00
|
|
|
assert not self.is_sdm_api(), "Step only supported for legacy API"
|
2020-10-21 08:17:49 +00:00
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
flow = self.hass.data[DATA_FLOW_IMPL][self.flow_impl]
|
|
|
|
|
|
|
|
errors = {}
|
|
|
|
|
|
|
|
if user_input is not None:
|
|
|
|
try:
|
|
|
|
with async_timeout.timeout(10):
|
2019-07-31 19:25:30 +00:00
|
|
|
tokens = await flow["convert_code"](user_input["code"])
|
2018-06-13 15:14:52 +00:00
|
|
|
return self._entry_from_tokens(
|
2020-04-07 21:14:28 +00:00
|
|
|
f"Nest (via {flow['name']})", flow, tokens
|
2019-07-31 19:25:30 +00:00
|
|
|
)
|
2018-06-13 15:14:52 +00:00
|
|
|
|
|
|
|
except asyncio.TimeoutError:
|
2019-07-31 19:25:30 +00:00
|
|
|
errors["code"] = "timeout"
|
2018-06-13 15:14:52 +00:00
|
|
|
except CodeInvalid:
|
2020-10-11 12:47:30 +00:00
|
|
|
errors["code"] = "invalid_pin"
|
2018-06-13 15:14:52 +00:00
|
|
|
except NestAuthError:
|
2019-07-31 19:25:30 +00:00
|
|
|
errors["code"] = "unknown"
|
2018-06-13 15:14:52 +00:00
|
|
|
except Exception: # pylint: disable=broad-except
|
2019-07-31 19:25:30 +00:00
|
|
|
errors["code"] = "internal_error"
|
2018-06-13 15:14:52 +00:00
|
|
|
_LOGGER.exception("Unexpected error resolving code")
|
|
|
|
|
|
|
|
try:
|
|
|
|
with async_timeout.timeout(10):
|
2019-07-31 19:25:30 +00:00
|
|
|
url = await flow["gen_authorize_url"](self.flow_id)
|
2018-06-13 15:14:52 +00:00
|
|
|
except asyncio.TimeoutError:
|
2019-07-31 19:25:30 +00:00
|
|
|
return self.async_abort(reason="authorize_url_timeout")
|
2018-06-13 15:14:52 +00:00
|
|
|
except Exception: # pylint: disable=broad-except
|
|
|
|
_LOGGER.exception("Unexpected error generating auth url")
|
2020-11-24 17:00:16 +00:00
|
|
|
return self.async_abort(reason="unknown_authorize_url_generation")
|
2018-06-13 15:14:52 +00:00
|
|
|
|
|
|
|
return self.async_show_form(
|
2019-07-31 19:25:30 +00:00
|
|
|
step_id="link",
|
|
|
|
description_placeholders={"url": url},
|
|
|
|
data_schema=vol.Schema({vol.Required("code"): str}),
|
2018-06-13 15:14:52 +00:00
|
|
|
errors=errors,
|
|
|
|
)
|
|
|
|
|
|
|
|
async def async_step_import(self, info):
|
|
|
|
"""Import existing auth from Nest."""
|
2020-12-20 00:41:29 +00:00
|
|
|
assert not self.is_sdm_api(), "Step only supported for legacy API"
|
2020-10-21 08:17:49 +00:00
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
if self.hass.config_entries.async_entries(DOMAIN):
|
2020-10-11 12:47:30 +00:00
|
|
|
return self.async_abort(reason="single_instance_allowed")
|
2018-06-13 15:14:52 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
config_path = info["nest_conf_path"]
|
2018-06-15 19:19:58 +00:00
|
|
|
|
2020-10-16 11:31:16 +00:00
|
|
|
if not await self.hass.async_add_executor_job(os.path.isfile, config_path):
|
2018-06-15 19:19:58 +00:00
|
|
|
self.flow_impl = DOMAIN
|
|
|
|
return await self.async_step_link()
|
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
flow = self.hass.data[DATA_FLOW_IMPL][DOMAIN]
|
2020-10-16 11:31:16 +00:00
|
|
|
tokens = await self.hass.async_add_executor_job(load_json, config_path)
|
2018-06-13 15:14:52 +00:00
|
|
|
|
|
|
|
return self._entry_from_tokens(
|
2019-07-31 19:25:30 +00:00
|
|
|
"Nest (import from configuration.yaml)", flow, tokens
|
|
|
|
)
|
2018-06-13 15:14:52 +00:00
|
|
|
|
|
|
|
@callback
|
|
|
|
def _entry_from_tokens(self, title, flow, tokens):
|
|
|
|
"""Create an entry from tokens."""
|
|
|
|
return self.async_create_entry(
|
2019-07-31 19:25:30 +00:00
|
|
|
title=title, data={"tokens": tokens, "impl_domain": flow["domain"]}
|
2018-06-13 15:14:52 +00:00
|
|
|
)
|