Cloud: Add Alexa report state (#24536)

* Cloud: Add Alexa report state

* Lint

* Lint

* Only track state changes when we are logged in
This commit is contained in:
Paulus Schoutsen authored and GitHub committed 2019-06-17 13:50:01 -07:00
1 parent 5ab1996d3f
commit a02b69db38
17 files changed
+207 -33

No files matched your search

+70 -4
View File
@@ -2,8 +2,11 @@
import asyncio
from pathlib import Path
from typing import Any, Dict
from datetime import timedelta
import logging
import aiohttp
from hass_nabucasa import cloud_api
from hass_nabucasa.client import CloudClient as Interface
from homeassistant.core import callback
@@ -17,22 +20,41 @@ from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.util.aiohttp import MockRequest
from homeassistant.util.dt import utcnow
from . import utils
from .const import (
CONF_ENTITY_CONFIG, CONF_FILTER, DOMAIN, DISPATCHER_REMOTE_UPDATE,
PREF_SHOULD_EXPOSE, DEFAULT_SHOULD_EXPOSE,
PREF_DISABLE_2FA, DEFAULT_DISABLE_2FA)
PREF_DISABLE_2FA, DEFAULT_DISABLE_2FA, RequireRelink)
from .prefs import CloudPreferences
_LOGGER = logging.getLogger(__name__)
class AlexaConfig(alexa_config.AbstractConfig):
"""Alexa Configuration."""
def __init__(self, config, prefs):
def __init__(self, hass, config, prefs, cloud):
"""Initialize the Alexa config."""
super().__init__(hass)
self._config = config
self._prefs = prefs
self._cloud = cloud
self._token = None
self._token_valid = None
prefs.async_listen_updates(self.async_prefs_updated)
@property
def supports_auth(self):
"""Return if config supports auth."""
return True
@property
def should_report_state(self):
"""Return if states should be proactively reported."""
return self._prefs.alexa_report_state
@property
def endpoint(self):
@@ -57,6 +79,34 @@ class AlexaConfig(alexa_config.AbstractConfig):
return entity_config.get(
PREF_SHOULD_EXPOSE, DEFAULT_SHOULD_EXPOSE)
async def async_get_access_token(self):
"""Get an access token."""
if self._token_valid is not None and self._token_valid < utcnow():
return self._token
resp = await cloud_api.async_alexa_access_token(self._cloud)
body = await resp.json()
if resp.status == 400:
if body['reason'] in ('RefreshTokenNotFound', 'UnknownRegion'):
raise RequireRelink
return None
self._token = body['access_token']
self._token_valid = utcnow() + timedelta(seconds=body['expires_in'])
return self._token
async def async_prefs_updated(self, prefs):
"""Handle updated preferences."""
if self.should_report_state == self.is_reporting_states:
return
if self.should_report_state:
await self.async_enable_proactive_mode()
else:
await self.async_disable_proactive_mode()
class CloudClient(Interface):
"""Interface class for Home Assistant Cloud."""
@@ -70,9 +120,9 @@ class CloudClient(Interface):
self._websession = websession
self.google_user_config = google_config
self.alexa_user_config = alexa_cfg
self.alexa_config = AlexaConfig(alexa_cfg, prefs)
self._alexa_config = None
self._google_config = None
self.cloud = None
@property
def base_path(self) -> Path:
@@ -109,6 +159,15 @@ class CloudClient(Interface):
"""Return true if we want start a remote connection."""
return self._prefs.remote_enabled
@property
def alexa_config(self) -> AlexaConfig:
"""Return Alexa config."""
if self._alexa_config is None:
self._alexa_config = AlexaConfig(
self._hass, self.alexa_user_config, self._prefs, self.cloud)
return self._alexa_config
@property
def google_config(self) -> ga_h.Config:
"""Return Google config."""
@@ -151,6 +210,13 @@ class CloudClient(Interface):
return self._google_config
async def async_initialize(self, cloud) -> None:
"""Initialize the client."""
self.cloud = cloud
if self.alexa_config.should_report_state and self.cloud.is_logged_in:
await self.alexa_config.async_enable_proactive_mode()
async def cleanups(self) -> None:
"""Cleanup some stuff after logout."""
self._google_config = None
+6
View File
@@ -10,12 +10,14 @@ PREF_CLOUDHOOKS = 'cloudhooks'
PREF_CLOUD_USER = 'cloud_user'
PREF_GOOGLE_ENTITY_CONFIGS = 'google_entity_configs'
PREF_ALEXA_ENTITY_CONFIGS = 'alexa_entity_configs'
PREF_ALEXA_REPORT_STATE = 'alexa_report_state'
PREF_OVERRIDE_NAME = 'override_name'
PREF_DISABLE_2FA = 'disable_2fa'
PREF_ALIASES = 'aliases'
PREF_SHOULD_EXPOSE = 'should_expose'
DEFAULT_SHOULD_EXPOSE = True
DEFAULT_DISABLE_2FA = False
DEFAULT_ALEXA_REPORT_STATE = False
CONF_ALEXA = 'alexa'
CONF_ALIASES = 'aliases'
@@ -43,3 +45,7 @@ class InvalidTrustedNetworks(Exception):
class InvalidTrustedProxies(Exception):
"""Raised when invalid trusted proxies config."""
class RequireRelink(Exception):
"""The skill needs to be relinked."""
+2 -2
View File
@@ -19,7 +19,7 @@ from homeassistant.components.google_assistant import helpers as google_helpers
from .const import (
DOMAIN, REQUEST_TIMEOUT, PREF_ENABLE_ALEXA, PREF_ENABLE_GOOGLE,
PREF_GOOGLE_SECURE_DEVICES_PIN, InvalidTrustedNetworks,
InvalidTrustedProxies)
InvalidTrustedProxies, PREF_ALEXA_REPORT_STATE)
_LOGGER = logging.getLogger(__name__)
@@ -363,6 +363,7 @@ async def websocket_subscription(hass, connection, msg):
vol.Required('type'): 'cloud/update_prefs',
vol.Optional(PREF_ENABLE_GOOGLE): bool,
vol.Optional(PREF_ENABLE_ALEXA): bool,
vol.Optional(PREF_ALEXA_REPORT_STATE): bool,
vol.Optional(PREF_GOOGLE_SECURE_DEVICES_PIN): vol.Any(None, str),
})
async def websocket_update_prefs(hass, connection, msg):
@@ -424,7 +425,6 @@ def _account_data(cloud):
'prefs': client.prefs.as_dict(),
'google_entities': client.google_user_config['filter'].config,
'alexa_entities': client.alexa_user_config['filter'].config,
'alexa_domains': list(alexa_entities.ENTITY_ADAPTERS),
'remote_domain': remote.instance_domain,
'remote_connected': remote.is_connected,
'remote_certificate': certificate,
+1 -1
View File
@@ -3,7 +3,7 @@
"name": "Cloud",
"documentation": "https://www.home-assistant.io/components/cloud",
"requirements": [
"hass-nabucasa==0.14"
"hass-nabucasa==0.15"
],
"dependencies": [
"http",
+27 -1
View File
@@ -1,11 +1,15 @@
"""Preference management for cloud."""
from ipaddress import ip_address
from homeassistant.core import callback
from homeassistant.util.logging import async_create_catching_coro
from .const import (
DOMAIN, PREF_ENABLE_ALEXA, PREF_ENABLE_GOOGLE, PREF_ENABLE_REMOTE,
PREF_GOOGLE_SECURE_DEVICES_PIN, PREF_CLOUDHOOKS, PREF_CLOUD_USER,
PREF_GOOGLE_ENTITY_CONFIGS, PREF_OVERRIDE_NAME, PREF_DISABLE_2FA,
PREF_ALIASES, PREF_SHOULD_EXPOSE, PREF_ALEXA_ENTITY_CONFIGS,
PREF_ALEXA_REPORT_STATE, DEFAULT_ALEXA_REPORT_STATE,
InvalidTrustedNetworks, InvalidTrustedProxies)
STORAGE_KEY = DOMAIN
@@ -21,6 +25,7 @@ class CloudPreferences:
self._hass = hass
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
self._prefs = None
self._listeners = []
async def async_initialize(self):
"""Finish initializing the preferences."""
@@ -40,11 +45,17 @@ class CloudPreferences:
self._prefs = prefs
@callback
def async_listen_updates(self, listener):
"""Listen for updates to the preferences."""
self._listeners.append(listener)
async def async_update(self, *, google_enabled=_UNDEF,
alexa_enabled=_UNDEF, remote_enabled=_UNDEF,
google_secure_devices_pin=_UNDEF, cloudhooks=_UNDEF,
cloud_user=_UNDEF, google_entity_configs=_UNDEF,
alexa_entity_configs=_UNDEF):
alexa_entity_configs=_UNDEF,
alexa_report_state=_UNDEF):
"""Update user preferences."""
for key, value in (
(PREF_ENABLE_GOOGLE, google_enabled),
@@ -55,18 +66,26 @@ class CloudPreferences:
(PREF_CLOUD_USER, cloud_user),
(PREF_GOOGLE_ENTITY_CONFIGS, google_entity_configs),
(PREF_ALEXA_ENTITY_CONFIGS, alexa_entity_configs),
(PREF_ALEXA_REPORT_STATE, alexa_report_state),
):
if value is not _UNDEF:
self._prefs[key] = value
if remote_enabled is True and self._has_local_trusted_network:
self._prefs[PREF_ENABLE_REMOTE] = False
raise InvalidTrustedNetworks
if remote_enabled is True and self._has_local_trusted_proxies:
self._prefs[PREF_ENABLE_REMOTE] = False
raise InvalidTrustedProxies
await self._store.async_save(self._prefs)
for listener in self._listeners:
self._hass.async_create_task(
async_create_catching_coro(listener(self))
)
async def async_update_google_entity_config(
self, *, entity_id, override_name=_UNDEF, disable_2fa=_UNDEF,
aliases=_UNDEF, should_expose=_UNDEF):
@@ -134,6 +153,7 @@ class CloudPreferences:
PREF_GOOGLE_SECURE_DEVICES_PIN: self.google_secure_devices_pin,
PREF_GOOGLE_ENTITY_CONFIGS: self.google_entity_configs,
PREF_ALEXA_ENTITY_CONFIGS: self.alexa_entity_configs,
PREF_ALEXA_REPORT_STATE: self.alexa_report_state,
PREF_CLOUDHOOKS: self.cloudhooks,
PREF_CLOUD_USER: self.cloud_user,
}
@@ -156,6 +176,12 @@ class CloudPreferences:
"""Return if Alexa is enabled."""
return self._prefs[PREF_ENABLE_ALEXA]
@property
def alexa_report_state(self):
"""Return if Alexa report state is enabled."""
return self._prefs.get(PREF_ALEXA_REPORT_STATE,
DEFAULT_ALEXA_REPORT_STATE)
@property
def google_enabled(self):
"""Return if Google is enabled."""