2020-10-21 08:17:49 +00:00
|
|
|
"""Config flow to configure Nest.
|
|
|
|
|
2021-11-04 22:56:16 +00:00
|
|
|
This configuration flow supports the following:
|
|
|
|
- SDM API with Installed app flow where user enters an auth code manually
|
|
|
|
- SDM API with Web OAuth flow with redirect back to Home Assistant
|
|
|
|
- Legacy Nest API auth flow with where user enters an auth code manually
|
2020-10-21 08:17:49 +00:00
|
|
|
|
|
|
|
NestFlowHandler is an implementation of AbstractOAuth2FlowHandler with
|
2021-11-30 06:41:29 +00:00
|
|
|
some overrides to support installed app and old APIs auth flow, reauth,
|
|
|
|
and other custom steps inserted in the middle of the flow.
|
|
|
|
|
|
|
|
The notable config flow steps are:
|
|
|
|
- user: To dispatch between API versions
|
|
|
|
- auth: Inserted to add a hook for the installed app flow to accept a token
|
|
|
|
- async_oauth_create_entry: Overridden to handle when OAuth is complete. This
|
|
|
|
does not actually create the entry, but holds on to the OAuth token data
|
|
|
|
for later
|
|
|
|
- pubsub: Configure the pubsub subscription. Note that subscriptions created
|
|
|
|
by the config flow are deleted when removed.
|
|
|
|
- finish: Handles creating a new configuration entry or updating the existing
|
|
|
|
configuration entry for reauth.
|
|
|
|
|
|
|
|
The SDM API config flow supports a hybrid of configuration.yaml (used as defaults)
|
|
|
|
and config flow.
|
2020-10-21 08:17:49 +00:00
|
|
|
"""
|
2021-03-18 12:21:46 +00:00
|
|
|
from __future__ import annotations
|
2020-10-21 08:17:49 +00:00
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
import asyncio
|
|
|
|
from collections import OrderedDict
|
2022-01-05 03:23:20 +00:00
|
|
|
from collections.abc import Iterable
|
2022-01-04 15:33:17 +00:00
|
|
|
from enum import Enum
|
2018-06-13 15:14:52 +00:00
|
|
|
import logging
|
2018-06-15 19:19:58 +00:00
|
|
|
import os
|
2021-07-20 15:41:48 +00:00
|
|
|
from typing import Any
|
2018-06-13 15:14:52 +00:00
|
|
|
|
|
|
|
import async_timeout
|
2021-11-30 06:41:29 +00:00
|
|
|
from google_nest_sdm.exceptions import (
|
2022-01-05 03:23:20 +00:00
|
|
|
ApiException,
|
2021-11-30 06:41:29 +00:00
|
|
|
AuthException,
|
|
|
|
ConfigurationException,
|
2022-01-02 17:54:56 +00:00
|
|
|
SubscriberException,
|
2021-11-30 06:41:29 +00:00
|
|
|
)
|
2022-01-05 03:23:20 +00:00
|
|
|
from google_nest_sdm.structure import InfoTrait, Structure
|
2018-06-13 15:14:52 +00:00
|
|
|
import voluptuous as vol
|
|
|
|
|
2021-11-30 06:41:29 +00:00
|
|
|
from homeassistant.config_entries import ConfigEntry
|
2022-01-18 06:17:23 +00:00
|
|
|
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
|
2021-07-20 15:41:48 +00:00
|
|
|
from homeassistant.core import HomeAssistant, callback
|
2021-07-20 05:59:31 +00:00
|
|
|
from homeassistant.data_entry_flow import FlowResult
|
2018-06-13 15:14:52 +00:00
|
|
|
from homeassistant.exceptions import HomeAssistantError
|
2020-10-21 08:17:49 +00:00
|
|
|
from homeassistant.helpers import config_entry_oauth2_flow
|
2022-01-18 06:17:23 +00:00
|
|
|
from homeassistant.helpers.typing import ConfigType
|
2021-11-30 06:41:29 +00:00
|
|
|
from homeassistant.util import get_random_string
|
2018-06-13 15:14:52 +00:00
|
|
|
from homeassistant.util.json import load_json
|
|
|
|
|
2022-01-18 06:17:23 +00:00
|
|
|
from . import api, auth
|
2021-11-30 06:41:29 +00:00
|
|
|
from .const import (
|
|
|
|
CONF_CLOUD_PROJECT_ID,
|
|
|
|
CONF_PROJECT_ID,
|
|
|
|
CONF_SUBSCRIBER_ID,
|
|
|
|
DATA_NEST_CONFIG,
|
|
|
|
DATA_SDM,
|
|
|
|
DOMAIN,
|
|
|
|
OOB_REDIRECT_URI,
|
|
|
|
SDM_SCOPES,
|
|
|
|
)
|
2018-06-13 15:14:52 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
DATA_FLOW_IMPL = "nest_flow_implementation"
|
2021-11-30 06:41:29 +00:00
|
|
|
SUBSCRIPTION_FORMAT = "projects/{cloud_project_id}/subscriptions/home-assistant-{rnd}"
|
|
|
|
SUBSCRIPTION_RAND_LENGTH = 10
|
|
|
|
CLOUD_CONSOLE_URL = "https://console.cloud.google.com/home/dashboard"
|
2018-06-13 15:14:52 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2022-01-04 15:33:17 +00:00
|
|
|
class ConfigMode(Enum):
|
|
|
|
"""Integration configuration mode."""
|
|
|
|
|
|
|
|
SDM = 1 # SDM api with configuration.yaml
|
|
|
|
LEGACY = 2 # "Works with Nest" API
|
|
|
|
|
|
|
|
|
|
|
|
def get_config_mode(hass: HomeAssistant) -> ConfigMode:
|
|
|
|
"""Return the integration configuration mode."""
|
|
|
|
if DOMAIN not in hass.data:
|
|
|
|
return ConfigMode.SDM
|
|
|
|
config = hass.data[DOMAIN][DATA_NEST_CONFIG]
|
|
|
|
if CONF_PROJECT_ID in config:
|
|
|
|
return ConfigMode.SDM
|
|
|
|
return ConfigMode.LEGACY
|
|
|
|
|
|
|
|
|
2021-11-30 06:41:29 +00:00
|
|
|
def _generate_subscription_id(cloud_project_id: str) -> str:
|
|
|
|
"""Create a new subscription id."""
|
|
|
|
rnd = get_random_string(SUBSCRIPTION_RAND_LENGTH)
|
|
|
|
return SUBSCRIPTION_FORMAT.format(cloud_project_id=cloud_project_id, rnd=rnd)
|
|
|
|
|
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
@callback
|
2021-07-26 23:43:52 +00:00
|
|
|
def register_flow_implementation(
|
|
|
|
hass: HomeAssistant,
|
|
|
|
domain: str,
|
|
|
|
name: str,
|
|
|
|
gen_authorize_url: str,
|
|
|
|
convert_code: str,
|
|
|
|
) -> None:
|
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
|
|
|
}
|
|
|
|
|
|
|
|
|
2022-01-18 06:17:23 +00:00
|
|
|
def register_flow_implementation_from_config(
|
|
|
|
hass: HomeAssistant,
|
|
|
|
config: ConfigType,
|
|
|
|
) -> None:
|
|
|
|
"""Register auth implementations for SDM API from configuration yaml."""
|
|
|
|
NestFlowHandler.async_register_implementation(
|
|
|
|
hass,
|
|
|
|
auth.InstalledAppAuth(
|
|
|
|
hass,
|
|
|
|
config[DOMAIN][CONF_CLIENT_ID],
|
|
|
|
config[DOMAIN][CONF_CLIENT_SECRET],
|
|
|
|
config[DOMAIN][CONF_PROJECT_ID],
|
|
|
|
),
|
|
|
|
)
|
|
|
|
NestFlowHandler.async_register_implementation(
|
|
|
|
hass,
|
|
|
|
auth.WebAuth(
|
|
|
|
hass,
|
|
|
|
config[DOMAIN][CONF_CLIENT_ID],
|
|
|
|
config[DOMAIN][CONF_CLIENT_SECRET],
|
|
|
|
config[DOMAIN][CONF_PROJECT_ID],
|
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
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."""
|
|
|
|
|
|
|
|
|
2022-01-05 03:23:20 +00:00
|
|
|
def generate_config_title(structures: Iterable[Structure]) -> str | None:
|
|
|
|
"""Pick a user friendly config title based on the Google Home name(s)."""
|
|
|
|
names: list[str] = []
|
|
|
|
for structure in structures:
|
|
|
|
if (trait := structure.traits.get(InfoTrait.NAME)) and trait.custom_name:
|
|
|
|
names.append(trait.custom_name)
|
|
|
|
if not names:
|
|
|
|
return None
|
|
|
|
return ", ".join(names)
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
2021-07-26 23:43:52 +00:00
|
|
|
def __init__(self) -> None:
|
2020-12-20 00:41:29 +00:00
|
|
|
"""Initialize NestFlowHandler."""
|
|
|
|
super().__init__()
|
2022-01-02 20:43:50 +00:00
|
|
|
self._reauth = False
|
2021-11-30 06:41:29 +00:00
|
|
|
self._data: dict[str, Any] = {DATA_SDM: {}}
|
2022-01-05 03:23:20 +00:00
|
|
|
# Possible name to use for config entry based on the Google Home name
|
|
|
|
self._structure_config_title: str | None = None
|
2020-12-20 00:41:29 +00:00
|
|
|
|
2022-01-04 15:33:17 +00:00
|
|
|
@property
|
|
|
|
def config_mode(self) -> ConfigMode:
|
|
|
|
"""Return the configuration type for this flow."""
|
|
|
|
return get_config_mode(self.hass)
|
2020-10-21 08:17:49 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def logger(self) -> logging.Logger:
|
|
|
|
"""Return logger."""
|
|
|
|
return logging.getLogger(__name__)
|
|
|
|
|
|
|
|
@property
|
2021-03-18 12:21:46 +00:00
|
|
|
def extra_authorize_data(self) -> dict[str, str]:
|
2020-10-21 08:17:49 +00:00
|
|
|
"""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",
|
|
|
|
}
|
|
|
|
|
2021-07-20 15:41:48 +00:00
|
|
|
async def async_oauth_create_entry(self, data: dict[str, Any]) -> FlowResult:
|
2021-11-30 06:41:29 +00:00
|
|
|
"""Complete OAuth setup and finish pubsub or finish."""
|
2022-01-04 15:33:17 +00:00
|
|
|
assert self.config_mode != ConfigMode.LEGACY, "Step only supported for SDM API"
|
2021-11-30 06:41:29 +00:00
|
|
|
self._data.update(data)
|
|
|
|
if not self._configure_pubsub():
|
|
|
|
_LOGGER.debug("Skipping Pub/Sub configuration")
|
|
|
|
return await self.async_step_finish()
|
|
|
|
return await self.async_step_pubsub()
|
2018-06-13 15:14:52 +00:00
|
|
|
|
2021-07-20 15:41:48 +00:00
|
|
|
async def async_step_reauth(
|
|
|
|
self, user_input: dict[str, Any] | None = None
|
|
|
|
) -> FlowResult:
|
2020-12-20 00:41:29 +00:00
|
|
|
"""Perform reauth upon an API authentication error."""
|
2022-01-04 15:33:17 +00:00
|
|
|
assert self.config_mode != ConfigMode.LEGACY, "Step only supported for SDM API"
|
2021-11-30 06:41:29 +00:00
|
|
|
if user_input is None:
|
|
|
|
_LOGGER.error("Reauth invoked with empty config entry data")
|
|
|
|
return self.async_abort(reason="missing_configuration")
|
2022-01-02 20:43:50 +00:00
|
|
|
self._reauth = True
|
2021-11-30 06:41:29 +00:00
|
|
|
self._data.update(user_input)
|
2020-12-20 00:41:29 +00:00
|
|
|
return await self.async_step_reauth_confirm()
|
|
|
|
|
2021-07-20 15:41:48 +00:00
|
|
|
async def async_step_reauth_confirm(
|
|
|
|
self, user_input: dict[str, Any] | None = None
|
|
|
|
) -> FlowResult:
|
2020-12-20 00:41:29 +00:00
|
|
|
"""Confirm reauth dialog."""
|
2022-01-04 15:33:17 +00:00
|
|
|
assert self.config_mode != ConfigMode.LEGACY, "Step only supported for SDM API"
|
2020-12-20 00:41:29 +00:00
|
|
|
if user_input is None:
|
2022-03-04 15:42:02 +00:00
|
|
|
return self.async_show_form(step_id="reauth_confirm")
|
2021-11-04 22:56:16 +00:00
|
|
|
existing_entries = self._async_current_entries()
|
|
|
|
if existing_entries:
|
|
|
|
# Pick an existing auth implementation for Reauth if present. Note
|
|
|
|
# only one ConfigEntry is allowed so its safe to pick the first.
|
|
|
|
entry = next(iter(existing_entries))
|
|
|
|
if "auth_implementation" in entry.data:
|
|
|
|
data = {"implementation": entry.data["auth_implementation"]}
|
|
|
|
return await self.async_step_user(data)
|
2020-12-20 00:41:29 +00:00
|
|
|
return await self.async_step_user()
|
|
|
|
|
2021-07-20 15:41:48 +00:00
|
|
|
async def async_step_user(
|
|
|
|
self, user_input: dict[str, Any] | None = None
|
|
|
|
) -> FlowResult:
|
2018-08-09 11:24:14 +00:00
|
|
|
"""Handle a flow initialized by the user."""
|
2022-01-04 15:33:17 +00:00
|
|
|
if self.config_mode == ConfigMode.SDM:
|
2020-12-20 00:41:29 +00:00
|
|
|
# Reauth will update an existing entry
|
2022-01-02 20:43:50 +00:00
|
|
|
if self._async_current_entries() and not self._reauth:
|
2020-12-20 00:41:29 +00:00
|
|
|
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)
|
|
|
|
|
2021-11-04 22:56:16 +00:00
|
|
|
async def async_step_auth(
|
|
|
|
self, user_input: dict[str, Any] | None = None
|
|
|
|
) -> FlowResult:
|
|
|
|
"""Create an entry for auth."""
|
|
|
|
if self.flow_impl.domain == "nest.installed":
|
|
|
|
# The default behavior from the parent class is to redirect the
|
|
|
|
# user with an external step. When using installed app auth, we
|
|
|
|
# instead prompt the user to sign in and copy/paste and
|
|
|
|
# authentication code back into this form.
|
|
|
|
# Note: This is similar to the Legacy API flow below, but it is
|
|
|
|
# simpler to reuse the OAuth logic in the parent class than to
|
|
|
|
# reuse SDM code with Legacy API code.
|
|
|
|
if user_input is not None:
|
|
|
|
self.external_data = {
|
|
|
|
"code": user_input["code"],
|
|
|
|
"state": {"redirect_uri": OOB_REDIRECT_URI},
|
|
|
|
}
|
|
|
|
return await super().async_step_creation(user_input)
|
|
|
|
|
|
|
|
result = await super().async_step_auth()
|
|
|
|
return self.async_show_form(
|
|
|
|
step_id="auth",
|
|
|
|
description_placeholders={"url": result["url"]},
|
|
|
|
data_schema=vol.Schema({vol.Required("code"): str}),
|
|
|
|
)
|
|
|
|
return await super().async_step_auth(user_input)
|
|
|
|
|
2021-11-30 06:41:29 +00:00
|
|
|
def _configure_pubsub(self) -> bool:
|
|
|
|
"""Return True if the config flow should configure Pub/Sub."""
|
2022-01-02 20:43:50 +00:00
|
|
|
if self._reauth:
|
|
|
|
# Just refreshing tokens and preserving existing subscriber id
|
|
|
|
return False
|
2021-11-30 06:41:29 +00:00
|
|
|
if CONF_SUBSCRIBER_ID in self.hass.data[DOMAIN][DATA_NEST_CONFIG]:
|
|
|
|
# Hard coded configuration.yaml skips pubsub in config flow
|
|
|
|
return False
|
|
|
|
# No existing subscription configured, so create in config flow
|
|
|
|
return True
|
|
|
|
|
|
|
|
async def async_step_pubsub(
|
|
|
|
self, user_input: dict[str, Any] | None = None
|
|
|
|
) -> FlowResult:
|
|
|
|
"""Configure and create Pub/Sub subscriber."""
|
|
|
|
# Populate data from the previous config entry during reauth, then
|
|
|
|
# overwrite with the user entered values.
|
|
|
|
data = {}
|
2022-01-02 20:43:50 +00:00
|
|
|
if self._reauth:
|
|
|
|
data.update(self._data)
|
2021-11-30 06:41:29 +00:00
|
|
|
if user_input:
|
|
|
|
data.update(user_input)
|
2022-01-20 08:13:49 +00:00
|
|
|
cloud_project_id = data.get(CONF_CLOUD_PROJECT_ID, "").strip()
|
2021-11-30 06:41:29 +00:00
|
|
|
|
|
|
|
errors = {}
|
|
|
|
config = self.hass.data[DOMAIN][DATA_NEST_CONFIG]
|
|
|
|
if cloud_project_id == config[CONF_PROJECT_ID]:
|
|
|
|
_LOGGER.error(
|
|
|
|
"Wrong Project ID. Device Access Project ID used, but expected Cloud Project ID"
|
|
|
|
)
|
|
|
|
errors[CONF_CLOUD_PROJECT_ID] = "wrong_project_id"
|
|
|
|
|
|
|
|
if user_input is not None and not errors:
|
|
|
|
# Create the subscriber id and/or verify it already exists. Note that
|
|
|
|
# the existing id is used, and create call below is idempotent
|
2022-02-19 16:19:46 +00:00
|
|
|
if not (subscriber_id := data.get(CONF_SUBSCRIBER_ID, "")):
|
2021-11-30 06:41:29 +00:00
|
|
|
subscriber_id = _generate_subscription_id(cloud_project_id)
|
|
|
|
_LOGGER.debug("Creating subscriber id '%s'", subscriber_id)
|
|
|
|
# Create a placeholder ConfigEntry to use since with the auth we've already created.
|
|
|
|
entry = ConfigEntry(
|
|
|
|
version=1, domain=DOMAIN, title="", data=self._data, source=""
|
|
|
|
)
|
|
|
|
subscriber = await api.new_subscriber_with_impl(
|
|
|
|
self.hass, entry, subscriber_id, self.flow_impl
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
await subscriber.create_subscription()
|
|
|
|
except AuthException as err:
|
|
|
|
_LOGGER.error("Subscriber authentication error: %s", err)
|
|
|
|
return self.async_abort(reason="invalid_access_token")
|
|
|
|
except ConfigurationException as err:
|
|
|
|
_LOGGER.error("Configuration error creating subscription: %s", err)
|
|
|
|
errors[CONF_CLOUD_PROJECT_ID] = "bad_project_id"
|
2022-01-02 17:54:56 +00:00
|
|
|
except SubscriberException as err:
|
2021-11-30 06:41:29 +00:00
|
|
|
_LOGGER.error("Error creating subscription: %s", err)
|
|
|
|
errors[CONF_CLOUD_PROJECT_ID] = "subscriber_error"
|
|
|
|
if not errors:
|
2022-01-05 03:23:20 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
device_manager = await subscriber.async_get_device_manager()
|
|
|
|
except ApiException as err:
|
|
|
|
# Generating a user friendly home name is best effort
|
|
|
|
_LOGGER.debug("Error fetching structures: %s", err)
|
|
|
|
else:
|
|
|
|
self._structure_config_title = generate_config_title(
|
|
|
|
device_manager.structures.values()
|
|
|
|
)
|
|
|
|
|
2021-11-30 06:41:29 +00:00
|
|
|
self._data.update(
|
|
|
|
{
|
|
|
|
CONF_SUBSCRIBER_ID: subscriber_id,
|
|
|
|
CONF_CLOUD_PROJECT_ID: cloud_project_id,
|
|
|
|
}
|
|
|
|
)
|
|
|
|
return await self.async_step_finish()
|
|
|
|
|
|
|
|
return self.async_show_form(
|
|
|
|
step_id="pubsub",
|
|
|
|
data_schema=vol.Schema(
|
|
|
|
{
|
|
|
|
vol.Required(CONF_CLOUD_PROJECT_ID, default=cloud_project_id): str,
|
|
|
|
}
|
|
|
|
),
|
|
|
|
description_placeholders={"url": CLOUD_CONSOLE_URL},
|
|
|
|
errors=errors,
|
|
|
|
)
|
|
|
|
|
|
|
|
async def async_step_finish(self, data: dict[str, Any] | None = None) -> FlowResult:
|
|
|
|
"""Create an entry for the SDM flow."""
|
2022-01-04 15:33:17 +00:00
|
|
|
assert self.config_mode != ConfigMode.LEGACY, "Step only supported for SDM API"
|
2021-11-30 06: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._async_current_entries()
|
|
|
|
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=self._data, unique_id=DOMAIN
|
|
|
|
)
|
|
|
|
await self.hass.config_entries.async_reload(entry.entry_id)
|
|
|
|
return self.async_abort(reason="reauth_successful")
|
2022-01-05 03:23:20 +00:00
|
|
|
title = self.flow_impl.name
|
|
|
|
if self._structure_config_title:
|
|
|
|
title = self._structure_config_title
|
|
|
|
return self.async_create_entry(title=title, data=self._data)
|
2021-11-30 06:41:29 +00:00
|
|
|
|
2021-07-20 15:41:48 +00:00
|
|
|
async def async_step_init(
|
|
|
|
self, user_input: dict[str, Any] | None = None
|
|
|
|
) -> FlowResult:
|
2018-06-13 15:14:52 +00:00
|
|
|
"""Handle a flow start."""
|
2022-01-04 15:33:17 +00:00
|
|
|
assert (
|
|
|
|
self.config_mode == ConfigMode.LEGACY
|
|
|
|
), "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, {})
|
|
|
|
|
2021-05-12 10:47:06 +00:00
|
|
|
if self._async_current_entries():
|
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
|
|
|
)
|
|
|
|
|
2021-07-20 15:41:48 +00:00
|
|
|
async def async_step_link(
|
|
|
|
self, user_input: dict[str, Any] | None = None
|
|
|
|
) -> FlowResult:
|
2018-06-13 15:14:52 +00:00
|
|
|
"""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.
|
|
|
|
"""
|
2022-01-04 15:33:17 +00:00
|
|
|
assert (
|
|
|
|
self.config_mode == ConfigMode.LEGACY
|
|
|
|
), "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:
|
2021-11-04 15:07:50 +00:00
|
|
|
async 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:
|
2021-11-04 15:07:50 +00:00
|
|
|
async 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,
|
|
|
|
)
|
|
|
|
|
2021-07-20 15:41:48 +00:00
|
|
|
async def async_step_import(self, info: dict[str, Any]) -> FlowResult:
|
2018-06-13 15:14:52 +00:00
|
|
|
"""Import existing auth from Nest."""
|
2022-01-04 15:33:17 +00:00
|
|
|
assert (
|
|
|
|
self.config_mode == ConfigMode.LEGACY
|
|
|
|
), "Step only supported for legacy API"
|
2020-10-21 08:17:49 +00:00
|
|
|
|
2021-05-12 10:47:06 +00:00
|
|
|
if self._async_current_entries():
|
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):
|
2022-02-18 08:41:12 +00:00
|
|
|
self.flow_impl = DOMAIN # type: ignore[assignment]
|
2018-06-15 19:19:58 +00:00
|
|
|
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
|
2021-07-20 15:41:48 +00:00
|
|
|
def _entry_from_tokens(
|
|
|
|
self, title: str, flow: dict[str, Any], tokens: list[Any] | dict[Any, Any]
|
|
|
|
) -> FlowResult:
|
2018-06-13 15:14:52 +00:00
|
|
|
"""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
|
|
|
)
|