This commit is contained in:
Paulus Schoutsen committed 2019-07-31 12:25:30 -07:00
1 parent da05dfe708
commit 4de97abc3a
2676 files changed
+163166 -140084

No files matched your search

+85 -54
View File
@@ -7,8 +7,12 @@ from homeassistant.auth.const import GROUP_ID_ADMIN
from homeassistant.components.alexa import const as alexa_const
from homeassistant.components.google_assistant import const as ga_c
from homeassistant.const import (
CONF_MODE, CONF_NAME, CONF_REGION, EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP)
CONF_MODE,
CONF_NAME,
CONF_REGION,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP,
)
from homeassistant.core import callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv, entityfilter
@@ -17,11 +21,23 @@ from homeassistant.util.aiohttp import MockRequest
from . import http_api
from .const import (
CONF_ACME_DIRECTORY_SERVER, CONF_ALEXA, CONF_ALIASES,
CONF_CLOUDHOOK_CREATE_URL, CONF_COGNITO_CLIENT_ID, CONF_ENTITY_CONFIG,
CONF_FILTER, CONF_GOOGLE_ACTIONS, CONF_GOOGLE_ACTIONS_SYNC_URL,
CONF_RELAYER, CONF_REMOTE_API_URL, CONF_SUBSCRIPTION_INFO_URL,
CONF_USER_POOL_ID, DOMAIN, MODE_DEV, MODE_PROD, CONF_ALEXA_ACCESS_TOKEN_URL
CONF_ACME_DIRECTORY_SERVER,
CONF_ALEXA,
CONF_ALIASES,
CONF_CLOUDHOOK_CREATE_URL,
CONF_COGNITO_CLIENT_ID,
CONF_ENTITY_CONFIG,
CONF_FILTER,
CONF_GOOGLE_ACTIONS,
CONF_GOOGLE_ACTIONS_SYNC_URL,
CONF_RELAYER,
CONF_REMOTE_API_URL,
CONF_SUBSCRIPTION_INFO_URL,
CONF_USER_POOL_ID,
DOMAIN,
MODE_DEV,
MODE_PROD,
CONF_ALEXA_ACCESS_TOKEN_URL,
)
from .prefs import CloudPreferences
@@ -29,53 +45,63 @@ _LOGGER = logging.getLogger(__name__)
DEFAULT_MODE = MODE_PROD
SERVICE_REMOTE_CONNECT = 'remote_connect'
SERVICE_REMOTE_DISCONNECT = 'remote_disconnect'
SERVICE_REMOTE_CONNECT = "remote_connect"
SERVICE_REMOTE_DISCONNECT = "remote_disconnect"
ALEXA_ENTITY_SCHEMA = vol.Schema({
vol.Optional(alexa_const.CONF_DESCRIPTION): cv.string,
vol.Optional(alexa_const.CONF_DISPLAY_CATEGORIES): cv.string,
vol.Optional(CONF_NAME): cv.string,
})
ALEXA_ENTITY_SCHEMA = vol.Schema(
{
vol.Optional(alexa_const.CONF_DESCRIPTION): cv.string,
vol.Optional(alexa_const.CONF_DISPLAY_CATEGORIES): cv.string,
vol.Optional(CONF_NAME): cv.string,
}
)
GOOGLE_ENTITY_SCHEMA = vol.Schema({
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_ALIASES): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(ga_c.CONF_ROOM_HINT): cv.string,
})
GOOGLE_ENTITY_SCHEMA = vol.Schema(
{
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_ALIASES): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(ga_c.CONF_ROOM_HINT): cv.string,
}
)
ASSISTANT_SCHEMA = vol.Schema({
vol.Optional(CONF_FILTER, default=dict): entityfilter.FILTER_SCHEMA,
})
ASSISTANT_SCHEMA = vol.Schema(
{vol.Optional(CONF_FILTER, default=dict): entityfilter.FILTER_SCHEMA}
)
ALEXA_SCHEMA = ASSISTANT_SCHEMA.extend({
vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: ALEXA_ENTITY_SCHEMA}
})
ALEXA_SCHEMA = ASSISTANT_SCHEMA.extend(
{vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: ALEXA_ENTITY_SCHEMA}}
)
GACTIONS_SCHEMA = ASSISTANT_SCHEMA.extend({
vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: GOOGLE_ENTITY_SCHEMA},
})
GACTIONS_SCHEMA = ASSISTANT_SCHEMA.extend(
{vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: GOOGLE_ENTITY_SCHEMA}}
)
# pylint: disable=no-value-for-parameter
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Optional(CONF_MODE, default=DEFAULT_MODE):
vol.In([MODE_DEV, MODE_PROD]),
vol.Optional(CONF_COGNITO_CLIENT_ID): str,
vol.Optional(CONF_USER_POOL_ID): str,
vol.Optional(CONF_REGION): str,
vol.Optional(CONF_RELAYER): str,
vol.Optional(CONF_GOOGLE_ACTIONS_SYNC_URL): vol.Url(),
vol.Optional(CONF_SUBSCRIPTION_INFO_URL): vol.Url(),
vol.Optional(CONF_CLOUDHOOK_CREATE_URL): vol.Url(),
vol.Optional(CONF_REMOTE_API_URL): vol.Url(),
vol.Optional(CONF_ACME_DIRECTORY_SERVER): vol.Url(),
vol.Optional(CONF_ALEXA): ALEXA_SCHEMA,
vol.Optional(CONF_GOOGLE_ACTIONS): GACTIONS_SCHEMA,
vol.Optional(CONF_ALEXA_ACCESS_TOKEN_URL): str,
}),
}, extra=vol.ALLOW_EXTRA)
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Optional(CONF_MODE, default=DEFAULT_MODE): vol.In(
[MODE_DEV, MODE_PROD]
),
vol.Optional(CONF_COGNITO_CLIENT_ID): str,
vol.Optional(CONF_USER_POOL_ID): str,
vol.Optional(CONF_REGION): str,
vol.Optional(CONF_RELAYER): str,
vol.Optional(CONF_GOOGLE_ACTIONS_SYNC_URL): vol.Url(),
vol.Optional(CONF_SUBSCRIPTION_INFO_URL): vol.Url(),
vol.Optional(CONF_CLOUDHOOK_CREATE_URL): vol.Url(),
vol.Optional(CONF_REMOTE_API_URL): vol.Url(),
vol.Optional(CONF_ACME_DIRECTORY_SERVER): vol.Url(),
vol.Optional(CONF_ALEXA): ALEXA_SCHEMA,
vol.Optional(CONF_GOOGLE_ACTIONS): GACTIONS_SCHEMA,
vol.Optional(CONF_ALEXA_ACCESS_TOKEN_URL): str,
}
)
},
extra=vol.ALLOW_EXTRA,
)
class CloudNotAvailable(HomeAssistantError):
@@ -93,8 +119,7 @@ def async_is_logged_in(hass) -> bool:
@callback
def async_active_subscription(hass) -> bool:
"""Test if user has an active subscription."""
return \
async_is_logged_in(hass) and not hass.data[DOMAIN].subscription_expired
return async_is_logged_in(hass) and not hass.data[DOMAIN].subscription_expired
@bind_hass
@@ -104,7 +129,7 @@ async def async_create_cloudhook(hass, webhook_id: str) -> str:
raise CloudNotAvailable
hook = await hass.data[DOMAIN].cloudhooks.async_create(webhook_id, True)
return hook['cloudhook_url']
return hook["cloudhook_url"]
@bind_hass
@@ -165,7 +190,8 @@ async def async_setup(hass, config):
if user is None:
user = await hass.auth.async_create_system_user(
'Home Assistant Cloud', [GROUP_ID_ADMIN])
"Home Assistant Cloud", [GROUP_ID_ADMIN]
)
await prefs.async_update(cloud_user=user.id)
# Initialize Cloud
@@ -195,9 +221,11 @@ async def async_setup(hass, config):
await prefs.async_update(remote_enabled=False)
hass.helpers.service.async_register_admin_service(
DOMAIN, SERVICE_REMOTE_CONNECT, _service_handler)
DOMAIN, SERVICE_REMOTE_CONNECT, _service_handler
)
hass.helpers.service.async_register_admin_service(
DOMAIN, SERVICE_REMOTE_DISCONNECT, _service_handler)
DOMAIN, SERVICE_REMOTE_DISCONNECT, _service_handler
)
loaded_binary_sensor = False
@@ -209,8 +237,11 @@ async def async_setup(hass, config):
return
loaded_binary_sensor = True
hass.async_create_task(hass.helpers.discovery.async_load_platform(
'binary_sensor', DOMAIN, {}, config))
hass.async_create_task(
hass.helpers.discovery.async_load_platform(
"binary_sensor", DOMAIN, {}, config
)
)
cloud.iot.register_on_connect(_on_connect)
+30 -23
View File
@@ -20,8 +20,11 @@ from homeassistant.components.alexa import (
from .const import (
CONF_ENTITY_CONFIG, CONF_FILTER, PREF_SHOULD_EXPOSE, DEFAULT_SHOULD_EXPOSE,
RequireRelink
CONF_ENTITY_CONFIG,
CONF_FILTER,
PREF_SHOULD_EXPOSE,
DEFAULT_SHOULD_EXPOSE,
RequireRelink,
)
_LOGGER = logging.getLogger(__name__)
@@ -49,7 +52,7 @@ class AlexaConfig(alexa_config.AbstractConfig):
prefs.async_listen_updates(self._async_prefs_updated)
hass.bus.async_listen(
entity_registry.EVENT_ENTITY_REGISTRY_UPDATED,
self._handle_entity_registry_updated
self._handle_entity_registry_updated,
)
@property
@@ -90,8 +93,7 @@ class AlexaConfig(alexa_config.AbstractConfig):
entity_configs = self._prefs.alexa_entity_configs
entity_config = entity_configs.get(entity_id, {})
return entity_config.get(
PREF_SHOULD_EXPOSE, DEFAULT_SHOULD_EXPOSE)
return entity_config.get(PREF_SHOULD_EXPOSE, DEFAULT_SHOULD_EXPOSE)
async def async_get_access_token(self):
"""Get an access token."""
@@ -102,13 +104,13 @@ class AlexaConfig(alexa_config.AbstractConfig):
body = await resp.json()
if resp.status == 400:
if body['reason'] in ('RefreshTokenNotFound', 'UnknownRegion'):
if body["reason"] in ("RefreshTokenNotFound", "UnknownRegion"):
if self.should_report_state:
await self._prefs.async_update(alexa_report_state=False)
self.hass.components.persistent_notification.async_create(
"There was an error reporting state to Alexa ({}). "
"Please re-link your Alexa skill via the Alexa app to "
"continue using it.".format(body['reason']),
"continue using it.".format(body["reason"]),
"Alexa state reporting disabled",
"cloud_alexa_report",
)
@@ -116,9 +118,9 @@ class AlexaConfig(alexa_config.AbstractConfig):
raise alexa_errors.NoTokenAvailable
self._token = body['access_token']
self._endpoint = body['event_endpoint']
self._token_valid = utcnow() + timedelta(seconds=body['expires_in'])
self._token = body["access_token"]
self._endpoint = body["event_endpoint"]
self._token_valid = utcnow() + timedelta(seconds=body["expires_in"])
return self._token
async def _async_prefs_updated(self, prefs):
@@ -136,15 +138,18 @@ class AlexaConfig(alexa_config.AbstractConfig):
# If entity prefs are the same or we have filter in config.yaml,
# don't sync.
if (self._cur_entity_prefs is prefs.alexa_entity_configs or
not self._config[CONF_FILTER].empty_filter):
if (
self._cur_entity_prefs is prefs.alexa_entity_configs
or not self._config[CONF_FILTER].empty_filter
):
return
if self._alexa_sync_unsub:
self._alexa_sync_unsub()
self._alexa_sync_unsub = async_call_later(
self.hass, SYNC_DELAY, self._sync_prefs)
self.hass, SYNC_DELAY, self._sync_prefs
)
async def _sync_prefs(self, _now):
"""Sync the updated preferences to Alexa."""
@@ -225,14 +230,16 @@ class AlexaConfig(alexa_config.AbstractConfig):
tasks = []
if to_update:
tasks.append(alexa_state_report.async_send_add_or_update_message(
self.hass, self, to_update
))
tasks.append(
alexa_state_report.async_send_add_or_update_message(
self.hass, self, to_update
)
)
if to_remove:
tasks.append(alexa_state_report.async_send_delete_message(
self.hass, self, to_remove
))
tasks.append(
alexa_state_report.async_send_delete_message(self.hass, self, to_remove)
)
try:
with async_timeout.timeout(10):
@@ -253,14 +260,14 @@ class AlexaConfig(alexa_config.AbstractConfig):
if not self.enabled or not self._cloud.is_logged_in:
return
action = event.data['action']
entity_id = event.data['entity_id']
action = event.data["action"]
entity_id = event.data["entity_id"]
to_update = []
to_remove = []
if action == 'create' and self.should_expose(entity_id):
if action == "create" and self.should_expose(entity_id):
to_update.append(entity_id)
elif action == 'remove' and self.should_expose(entity_id):
elif action == "remove" and self.should_expose(entity_id):
to_remove.append(entity_id)
try:
@@ -10,8 +10,7 @@ from .const import DISPATCHER_REMOTE_UPDATE, DOMAIN
WAIT_UNTIL_CHANGE = 3
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the cloud binary sensors."""
if discovery_info is None:
return
@@ -46,7 +45,7 @@ class CloudRemoteBinary(BinarySensorDevice):
@property
def device_class(self) -> str:
"""Return the class of this device, from component DEVICE_CLASSES."""
return 'connectivity'
return "connectivity"
@property
def available(self) -> bool:
@@ -60,13 +59,15 @@ class CloudRemoteBinary(BinarySensorDevice):
async def async_added_to_hass(self):
"""Register update dispatcher."""
async def async_state_update(data):
"""Update callback."""
await asyncio.sleep(WAIT_UNTIL_CHANGE)
self.async_schedule_update_ha_state()
self._unsub_dispatcher = async_dispatcher_connect(
self.hass, DISPATCHER_REMOTE_UPDATE, async_state_update)
self.hass, DISPATCHER_REMOTE_UPDATE, async_state_update
)
async def async_will_remove_from_hass(self):
"""Register update dispatcher."""
+31 -34
View File
@@ -28,10 +28,14 @@ _LOGGER = logging.getLogger(__name__)
class CloudClient(Interface):
"""Interface class for Home Assistant Cloud."""
def __init__(self, hass: HomeAssistantType, prefs: CloudPreferences,
websession: aiohttp.ClientSession,
alexa_user_config: Dict[str, Any],
google_user_config: Dict[str, Any]):
def __init__(
self,
hass: HomeAssistantType,
prefs: CloudPreferences,
websession: aiohttp.ClientSession,
alexa_user_config: Dict[str, Any],
google_user_config: Dict[str, Any],
):
"""Initialize client interface to Cloud."""
self._hass = hass
self._prefs = prefs
@@ -83,7 +87,8 @@ class CloudClient(Interface):
if self._alexa_config is None:
assert self.cloud is not None
self._alexa_config = alexa_config.AlexaConfig(
self._hass, self.alexa_user_config, self._prefs, self.cloud)
self._hass, self.alexa_user_config, self._prefs, self.cloud
)
return self._alexa_config
@@ -93,7 +98,8 @@ class CloudClient(Interface):
if not self._google_config:
assert self.cloud is not None
self._google_config = google_config.CloudGoogleConfig(
self.google_user_config, self._prefs, self.cloud)
self.google_user_config, self._prefs, self.cloud
)
return self._google_config
@@ -101,8 +107,7 @@ class CloudClient(Interface):
"""Initialize the client."""
self.cloud = cloud
if (not self.alexa_config.should_report_state or
not self.cloud.is_logged_in):
if not self.alexa_config.should_report_state or not self.cloud.is_logged_in:
return
try:
@@ -127,16 +132,13 @@ class CloudClient(Interface):
if identifier.startswith("remote_"):
async_dispatcher_send(self._hass, DISPATCHER_REMOTE_UPDATE, data)
async def async_alexa_message(
self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
async def async_alexa_message(self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
"""Process cloud alexa message to client."""
return await alexa_sh.async_handle_message(
self._hass, self.alexa_config, payload,
enabled=self._prefs.alexa_enabled
self._hass, self.alexa_config, payload, enabled=self._prefs.alexa_enabled
)
async def async_google_message(
self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
async def async_google_message(self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
"""Process cloud google message to client."""
if not self._prefs.google_enabled:
return ga.turned_off_response(payload)
@@ -145,44 +147,39 @@ class CloudClient(Interface):
self._hass, self.google_config, self.prefs.cloud_user, payload
)
async def async_webhook_message(
self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
async def async_webhook_message(self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
"""Process cloud webhook message to client."""
cloudhook_id = payload['cloudhook_id']
cloudhook_id = payload["cloudhook_id"]
found = None
for cloudhook in self._prefs.cloudhooks.values():
if cloudhook['cloudhook_id'] == cloudhook_id:
if cloudhook["cloudhook_id"] == cloudhook_id:
found = cloudhook
break
if found is None:
return {
'status': 200
}
return {"status": 200}
request = MockRequest(
content=payload['body'].encode('utf-8'),
headers=payload['headers'],
method=payload['method'],
query_string=payload['query'],
content=payload["body"].encode("utf-8"),
headers=payload["headers"],
method=payload["method"],
query_string=payload["query"],
)
response = await self._hass.components.webhook.async_handle_webhook(
found['webhook_id'], request)
found["webhook_id"], request
)
response_dict = utils.aiohttp_serialize_response(response)
body = response_dict.get('body')
body = response_dict.get("body")
return {
'body': body,
'status': response_dict['status'],
'headers': {
'Content-Type': response.content_type
}
"body": body,
"status": response_dict["status"],
"headers": {"Content-Type": response.content_type},
}
async def async_cloudhooks_update(
self, data: Dict[str, Dict[str, str]]) -> None:
async def async_cloudhooks_update(self, data: Dict[str, Dict[str, str]]) -> None:
"""Update local list of cloudhooks."""
await self._prefs.async_update(cloudhooks=data)
+29 -29
View File
@@ -1,43 +1,43 @@
"""Constants for the cloud component."""
DOMAIN = 'cloud'
DOMAIN = "cloud"
REQUEST_TIMEOUT = 10
PREF_ENABLE_ALEXA = 'alexa_enabled'
PREF_ENABLE_GOOGLE = 'google_enabled'
PREF_ENABLE_REMOTE = 'remote_enabled'
PREF_GOOGLE_SECURE_DEVICES_PIN = 'google_secure_devices_pin'
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'
PREF_ENABLE_ALEXA = "alexa_enabled"
PREF_ENABLE_GOOGLE = "google_enabled"
PREF_ENABLE_REMOTE = "remote_enabled"
PREF_GOOGLE_SECURE_DEVICES_PIN = "google_secure_devices_pin"
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'
CONF_COGNITO_CLIENT_ID = 'cognito_client_id'
CONF_ENTITY_CONFIG = 'entity_config'
CONF_FILTER = 'filter'
CONF_GOOGLE_ACTIONS = 'google_actions'
CONF_RELAYER = 'relayer'
CONF_USER_POOL_ID = 'user_pool_id'
CONF_GOOGLE_ACTIONS_SYNC_URL = 'google_actions_sync_url'
CONF_SUBSCRIPTION_INFO_URL = 'subscription_info_url'
CONF_CLOUDHOOK_CREATE_URL = 'cloudhook_create_url'
CONF_REMOTE_API_URL = 'remote_api_url'
CONF_ACME_DIRECTORY_SERVER = 'acme_directory_server'
CONF_ALEXA_ACCESS_TOKEN_URL = 'alexa_access_token_url'
CONF_ALEXA = "alexa"
CONF_ALIASES = "aliases"
CONF_COGNITO_CLIENT_ID = "cognito_client_id"
CONF_ENTITY_CONFIG = "entity_config"
CONF_FILTER = "filter"
CONF_GOOGLE_ACTIONS = "google_actions"
CONF_RELAYER = "relayer"
CONF_USER_POOL_ID = "user_pool_id"
CONF_GOOGLE_ACTIONS_SYNC_URL = "google_actions_sync_url"
CONF_SUBSCRIPTION_INFO_URL = "subscription_info_url"
CONF_CLOUDHOOK_CREATE_URL = "cloudhook_create_url"
CONF_REMOTE_API_URL = "remote_api_url"
CONF_ACME_DIRECTORY_SERVER = "acme_directory_server"
CONF_ALEXA_ACCESS_TOKEN_URL = "alexa_access_token_url"
MODE_DEV = "development"
MODE_PROD = "production"
DISPATCHER_REMOTE_UPDATE = 'cloud_remote_update'
DISPATCHER_REMOTE_UPDATE = "cloud_remote_update"
class InvalidTrustedNetworks(Exception):
@@ -3,8 +3,12 @@ from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES
from homeassistant.components.google_assistant.helpers import AbstractConfig
from .const import (
PREF_SHOULD_EXPOSE, DEFAULT_SHOULD_EXPOSE, CONF_ENTITY_CONFIG,
PREF_DISABLE_2FA, DEFAULT_DISABLE_2FA)
PREF_SHOULD_EXPOSE,
DEFAULT_SHOULD_EXPOSE,
CONF_ENTITY_CONFIG,
PREF_DISABLE_2FA,
DEFAULT_DISABLE_2FA,
)
class CloudGoogleConfig(AbstractConfig):
@@ -36,17 +40,15 @@ class CloudGoogleConfig(AbstractConfig):
if state.entity_id in CLOUD_NEVER_EXPOSED_ENTITIES:
return False
if not self._config['filter'].empty_filter:
return self._config['filter'](state.entity_id)
if not self._config["filter"].empty_filter:
return self._config["filter"](state.entity_id)
entity_configs = self._prefs.google_entity_configs
entity_config = entity_configs.get(state.entity_id, {})
return entity_config.get(
PREF_SHOULD_EXPOSE, DEFAULT_SHOULD_EXPOSE)
return entity_config.get(PREF_SHOULD_EXPOSE, DEFAULT_SHOULD_EXPOSE)
def should_2fa(self, state):
"""If an entity should be checked for 2FA."""
entity_configs = self._prefs.google_entity_configs
entity_config = entity_configs.get(state.entity_id, {})
return not entity_config.get(
PREF_DISABLE_2FA, DEFAULT_DISABLE_2FA)
return not entity_config.get(PREF_DISABLE_2FA, DEFAULT_DISABLE_2FA)
+213 -223
View File
@@ -10,8 +10,7 @@ import voluptuous as vol
from homeassistant.core import callback
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http.data_validator import (
RequestDataValidator)
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.components import websocket_api
from homeassistant.components.websocket_api import const as ws_const
from homeassistant.components.alexa import (
@@ -21,78 +20,76 @@ from homeassistant.components.alexa import (
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, PREF_ALEXA_REPORT_STATE, RequireRelink)
DOMAIN,
REQUEST_TIMEOUT,
PREF_ENABLE_ALEXA,
PREF_ENABLE_GOOGLE,
PREF_GOOGLE_SECURE_DEVICES_PIN,
InvalidTrustedNetworks,
InvalidTrustedProxies,
PREF_ALEXA_REPORT_STATE,
RequireRelink,
)
_LOGGER = logging.getLogger(__name__)
WS_TYPE_STATUS = 'cloud/status'
SCHEMA_WS_STATUS = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
vol.Required('type'): WS_TYPE_STATUS,
})
WS_TYPE_STATUS = "cloud/status"
SCHEMA_WS_STATUS = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend(
{vol.Required("type"): WS_TYPE_STATUS}
)
WS_TYPE_SUBSCRIPTION = 'cloud/subscription'
SCHEMA_WS_SUBSCRIPTION = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
vol.Required('type'): WS_TYPE_SUBSCRIPTION,
})
WS_TYPE_SUBSCRIPTION = "cloud/subscription"
SCHEMA_WS_SUBSCRIPTION = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend(
{vol.Required("type"): WS_TYPE_SUBSCRIPTION}
)
WS_TYPE_HOOK_CREATE = 'cloud/cloudhook/create'
SCHEMA_WS_HOOK_CREATE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
vol.Required('type'): WS_TYPE_HOOK_CREATE,
vol.Required('webhook_id'): str
})
WS_TYPE_HOOK_CREATE = "cloud/cloudhook/create"
SCHEMA_WS_HOOK_CREATE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend(
{vol.Required("type"): WS_TYPE_HOOK_CREATE, vol.Required("webhook_id"): str}
)
WS_TYPE_HOOK_DELETE = 'cloud/cloudhook/delete'
SCHEMA_WS_HOOK_DELETE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
vol.Required('type'): WS_TYPE_HOOK_DELETE,
vol.Required('webhook_id'): str
})
WS_TYPE_HOOK_DELETE = "cloud/cloudhook/delete"
SCHEMA_WS_HOOK_DELETE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend(
{vol.Required("type"): WS_TYPE_HOOK_DELETE, vol.Required("webhook_id"): str}
)
_CLOUD_ERRORS = {
InvalidTrustedNetworks:
(500, 'Remote UI not compatible with 127.0.0.1/::1'
' as a trusted network.'),
InvalidTrustedProxies:
(500, 'Remote UI not compatible with 127.0.0.1/::1'
' as trusted proxies.'),
InvalidTrustedNetworks: (
500,
"Remote UI not compatible with 127.0.0.1/::1" " as a trusted network.",
),
InvalidTrustedProxies: (
500,
"Remote UI not compatible with 127.0.0.1/::1" " as trusted proxies.",
),
}
async def async_setup(hass):
"""Initialize the HTTP API."""
hass.components.websocket_api.async_register_command(
WS_TYPE_STATUS, websocket_cloud_status,
SCHEMA_WS_STATUS
WS_TYPE_STATUS, websocket_cloud_status, SCHEMA_WS_STATUS
)
hass.components.websocket_api.async_register_command(
WS_TYPE_SUBSCRIPTION, websocket_subscription,
SCHEMA_WS_SUBSCRIPTION
WS_TYPE_SUBSCRIPTION, websocket_subscription, SCHEMA_WS_SUBSCRIPTION
)
hass.components.websocket_api.async_register_command(websocket_update_prefs)
hass.components.websocket_api.async_register_command(
WS_TYPE_HOOK_CREATE, websocket_hook_create, SCHEMA_WS_HOOK_CREATE
)
hass.components.websocket_api.async_register_command(
websocket_update_prefs)
hass.components.websocket_api.async_register_command(
WS_TYPE_HOOK_CREATE, websocket_hook_create,
SCHEMA_WS_HOOK_CREATE
WS_TYPE_HOOK_DELETE, websocket_hook_delete, SCHEMA_WS_HOOK_DELETE
)
hass.components.websocket_api.async_register_command(
WS_TYPE_HOOK_DELETE, websocket_hook_delete,
SCHEMA_WS_HOOK_DELETE
)
hass.components.websocket_api.async_register_command(
websocket_remote_connect)
hass.components.websocket_api.async_register_command(
websocket_remote_disconnect)
hass.components.websocket_api.async_register_command(websocket_remote_connect)
hass.components.websocket_api.async_register_command(websocket_remote_disconnect)
hass.components.websocket_api.async_register_command(
google_assistant_list)
hass.components.websocket_api.async_register_command(
google_assistant_update)
hass.components.websocket_api.async_register_command(google_assistant_list)
hass.components.websocket_api.async_register_command(google_assistant_update)
hass.components.websocket_api.async_register_command(alexa_list)
hass.components.websocket_api.async_register_command(alexa_update)
@@ -107,26 +104,22 @@ async def async_setup(hass):
from hass_nabucasa import auth
_CLOUD_ERRORS.update({
auth.UserNotFound:
(400, "User does not exist."),
auth.UserNotConfirmed:
(400, 'Email not confirmed.'),
auth.UserExists:
(400, 'An account with the given email already exists.'),
auth.Unauthenticated:
(401, 'Authentication failed.'),
auth.PasswordChangeRequired:
(400, 'Password change required.'),
asyncio.TimeoutError:
(502, 'Unable to reach the Home Assistant cloud.'),
aiohttp.ClientError:
(500, 'Error making internal request'),
})
_CLOUD_ERRORS.update(
{
auth.UserNotFound: (400, "User does not exist."),
auth.UserNotConfirmed: (400, "Email not confirmed."),
auth.UserExists: (400, "An account with the given email already exists."),
auth.Unauthenticated: (401, "Authentication failed."),
auth.PasswordChangeRequired: (400, "Password change required."),
asyncio.TimeoutError: (502, "Unable to reach the Home Assistant cloud."),
aiohttp.ClientError: (500, "Error making internal request"),
}
)
def _handle_cloud_errors(handler):
"""Webview decorator to handle auth errors."""
@wraps(handler)
async def error_handler(view, request, *args, **kwargs):
"""Handle exceptions that raise from the wrapped request handler."""
@@ -137,14 +130,15 @@ def _handle_cloud_errors(handler):
except Exception as err: # pylint: disable=broad-except
status, msg = _process_cloud_exception(err, request.path)
return view.json_message(
msg, status_code=status,
message_code=err.__class__.__name__.lower())
msg, status_code=status, message_code=err.__class__.__name__.lower()
)
return error_handler
def _ws_handle_cloud_errors(handler):
"""Websocket decorator to handle auth errors."""
@wraps(handler)
async def error_handler(hass, connection, msg):
"""Handle exceptions that raise from the wrapped handler."""
@@ -152,8 +146,8 @@ def _ws_handle_cloud_errors(handler):
return await handler(hass, connection, msg)
except Exception as err: # pylint: disable=broad-except
err_status, err_msg = _process_cloud_exception(err, msg['type'])
connection.send_error(msg['id'], err_status, err_msg)
err_status, err_msg = _process_cloud_exception(err, msg["type"])
connection.send_error(msg["id"], err_status, err_msg)
return error_handler
@@ -162,22 +156,21 @@ def _process_cloud_exception(exc, where):
"""Process a cloud exception."""
err_info = _CLOUD_ERRORS.get(exc.__class__)
if err_info is None:
_LOGGER.exception(
"Unexpected error processing request for %s", where)
err_info = (502, 'Unexpected error: {}'.format(exc))
_LOGGER.exception("Unexpected error processing request for %s", where)
err_info = (502, "Unexpected error: {}".format(exc))
return err_info
class GoogleActionsSyncView(HomeAssistantView):
"""Trigger a Google Actions Smart Home Sync."""
url = '/api/cloud/google_actions/sync'
name = 'api:cloud:google_actions/sync'
url = "/api/cloud/google_actions/sync"
name = "api:cloud:google_actions/sync"
@_handle_cloud_errors
async def post(self, request):
"""Trigger a Google Actions sync."""
hass = request.app['hass']
hass = request.app["hass"]
cloud = hass.data[DOMAIN]
websession = hass.helpers.aiohttp_client.async_get_clientsession()
@@ -186,9 +179,8 @@ class GoogleActionsSyncView(HomeAssistantView):
with async_timeout.timeout(REQUEST_TIMEOUT):
req = await websession.post(
cloud.google_actions_sync_url, headers={
'authorization': cloud.id_token
})
cloud.google_actions_sync_url, headers={"authorization": cloud.id_token}
)
return self.json({}, status_code=req.status)
@@ -196,110 +188,107 @@ class GoogleActionsSyncView(HomeAssistantView):
class CloudLoginView(HomeAssistantView):
"""Login to Home Assistant cloud."""
url = '/api/cloud/login'
name = 'api:cloud:login'
url = "/api/cloud/login"
name = "api:cloud:login"
@_handle_cloud_errors
@RequestDataValidator(vol.Schema({
vol.Required('email'): str,
vol.Required('password'): str,
}))
@RequestDataValidator(
vol.Schema({vol.Required("email"): str, vol.Required("password"): str})
)
async def post(self, request, data):
"""Handle login request."""
hass = request.app['hass']
hass = request.app["hass"]
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT):
await hass.async_add_job(cloud.auth.login, data['email'],
data['password'])
await hass.async_add_job(cloud.auth.login, data["email"], data["password"])
hass.async_add_job(cloud.iot.connect)
return self.json({'success': True})
return self.json({"success": True})
class CloudLogoutView(HomeAssistantView):
"""Log out of the Home Assistant cloud."""
url = '/api/cloud/logout'
name = 'api:cloud:logout'
url = "/api/cloud/logout"
name = "api:cloud:logout"
@_handle_cloud_errors
async def post(self, request):
"""Handle logout request."""
hass = request.app['hass']
hass = request.app["hass"]
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT):
await cloud.logout()
return self.json_message('ok')
return self.json_message("ok")
class CloudRegisterView(HomeAssistantView):
"""Register on the Home Assistant cloud."""
url = '/api/cloud/register'
name = 'api:cloud:register'
url = "/api/cloud/register"
name = "api:cloud:register"
@_handle_cloud_errors
@RequestDataValidator(vol.Schema({
vol.Required('email'): str,
vol.Required('password'): vol.All(str, vol.Length(min=6)),
}))
@RequestDataValidator(
vol.Schema(
{
vol.Required("email"): str,
vol.Required("password"): vol.All(str, vol.Length(min=6)),
}
)
)
async def post(self, request, data):
"""Handle registration request."""
hass = request.app['hass']
hass = request.app["hass"]
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT):
await hass.async_add_job(
cloud.auth.register, data['email'], data['password'])
cloud.auth.register, data["email"], data["password"]
)
return self.json_message('ok')
return self.json_message("ok")
class CloudResendConfirmView(HomeAssistantView):
"""Resend email confirmation code."""
url = '/api/cloud/resend_confirm'
name = 'api:cloud:resend_confirm'
url = "/api/cloud/resend_confirm"
name = "api:cloud:resend_confirm"
@_handle_cloud_errors
@RequestDataValidator(vol.Schema({
vol.Required('email'): str,
}))
@RequestDataValidator(vol.Schema({vol.Required("email"): str}))
async def post(self, request, data):
"""Handle resending confirm email code request."""
hass = request.app['hass']
hass = request.app["hass"]
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT):
await hass.async_add_job(
cloud.auth.resend_email_confirm, data['email'])
await hass.async_add_job(cloud.auth.resend_email_confirm, data["email"])
return self.json_message('ok')
return self.json_message("ok")
class CloudForgotPasswordView(HomeAssistantView):
"""View to start Forgot Password flow.."""
url = '/api/cloud/forgot_password'
name = 'api:cloud:forgot_password'
url = "/api/cloud/forgot_password"
name = "api:cloud:forgot_password"
@_handle_cloud_errors
@RequestDataValidator(vol.Schema({
vol.Required('email'): str,
}))
@RequestDataValidator(vol.Schema({vol.Required("email"): str}))
async def post(self, request, data):
"""Handle forgot password request."""
hass = request.app['hass']
hass = request.app["hass"]
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT):
await hass.async_add_job(
cloud.auth.forgot_password, data['email'])
await hass.async_add_job(cloud.auth.forgot_password, data["email"])
return self.json_message('ok')
return self.json_message("ok")
@callback
@@ -310,19 +299,23 @@ def websocket_cloud_status(hass, connection, msg):
"""
cloud = hass.data[DOMAIN]
connection.send_message(
websocket_api.result_message(msg['id'], _account_data(cloud)))
websocket_api.result_message(msg["id"], _account_data(cloud))
)
def _require_cloud_login(handler):
"""Websocket decorator that requires cloud to be logged in."""
@wraps(handler)
def with_cloud_auth(hass, connection, msg):
"""Require to be logged into the cloud."""
cloud = hass.data[DOMAIN]
if not cloud.is_logged_in:
connection.send_message(websocket_api.error_message(
msg['id'], 'not_logged_in',
'You need to be logged in to the cloud.'))
connection.send_message(
websocket_api.error_message(
msg["id"], "not_logged_in", "You need to be logged in to the cloud."
)
)
return
handler(hass, connection, msg)
@@ -335,22 +328,25 @@ def _require_cloud_login(handler):
async def websocket_subscription(hass, connection, msg):
"""Handle request for account info."""
from hass_nabucasa.const import STATE_DISCONNECTED
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT):
response = await cloud.fetch_subscription_info()
if response.status != 200:
connection.send_message(websocket_api.error_message(
msg['id'], 'request_failed', 'Failed to request subscription'))
connection.send_message(
websocket_api.error_message(
msg["id"], "request_failed", "Failed to request subscription"
)
)
data = await response.json()
# Check if a user is subscribed but local info is outdated
# In that case, let's refresh and reconnect
if data.get('provider') and not cloud.is_connected:
_LOGGER.debug(
"Found disconnected account with valid subscriotion, connecting")
if data.get("provider") and not cloud.is_connected:
_LOGGER.debug("Found disconnected account with valid subscriotion, connecting")
await hass.async_add_executor_job(cloud.auth.renew_access_token)
# Cancel reconnect in progress
@@ -359,25 +355,27 @@ async def websocket_subscription(hass, connection, msg):
hass.async_create_task(cloud.iot.connect())
connection.send_message(websocket_api.result_message(msg['id'], data))
connection.send_message(websocket_api.result_message(msg["id"], data))
@_require_cloud_login
@websocket_api.async_response
@websocket_api.websocket_command({
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),
})
@websocket_api.websocket_command(
{
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):
"""Handle request for account info."""
cloud = hass.data[DOMAIN]
changes = dict(msg)
changes.pop('id')
changes.pop('type')
changes.pop("id")
changes.pop("type")
# If we turn alexa linking on, validate that we can fetch access token
if changes.get(PREF_ALEXA_REPORT_STATE):
@@ -385,20 +383,22 @@ async def websocket_update_prefs(hass, connection, msg):
with async_timeout.timeout(10):
await cloud.client.alexa_config.async_get_access_token()
except asyncio.TimeoutError:
connection.send_error(msg['id'], 'alexa_timeout',
'Timeout validating Alexa access token.')
connection.send_error(
msg["id"], "alexa_timeout", "Timeout validating Alexa access token."
)
return
except (alexa_errors.NoTokenAvailable, RequireRelink):
connection.send_error(
msg['id'], 'alexa_relink',
'Please go to the Alexa app and re-link the Home Assistant '
'skill and then try to enable state reporting.'
msg["id"],
"alexa_relink",
"Please go to the Alexa app and re-link the Home Assistant "
"skill and then try to enable state reporting.",
)
return
await cloud.client.prefs.async_update(**changes)
connection.send_message(websocket_api.result_message(msg['id']))
connection.send_message(websocket_api.result_message(msg["id"]))
@_require_cloud_login
@@ -407,8 +407,8 @@ async def websocket_update_prefs(hass, connection, msg):
async def websocket_hook_create(hass, connection, msg):
"""Handle request for account info."""
cloud = hass.data[DOMAIN]
hook = await cloud.cloudhooks.async_create(msg['webhook_id'], False)
connection.send_message(websocket_api.result_message(msg['id'], hook))
hook = await cloud.cloudhooks.async_create(msg["webhook_id"], False)
connection.send_message(websocket_api.result_message(msg["id"], hook))
@_require_cloud_login
@@ -417,8 +417,8 @@ async def websocket_hook_create(hass, connection, msg):
async def websocket_hook_delete(hass, connection, msg):
"""Handle request for account info."""
cloud = hass.data[DOMAIN]
await cloud.cloudhooks.async_delete(msg['webhook_id'])
connection.send_message(websocket_api.result_message(msg['id']))
await cloud.cloudhooks.async_delete(msg["webhook_id"])
connection.send_message(websocket_api.result_message(msg["id"]))
def _account_data(cloud):
@@ -426,10 +426,7 @@ def _account_data(cloud):
from hass_nabucasa.const import STATE_DISCONNECTED
if not cloud.is_logged_in:
return {
'logged_in': False,
'cloud': STATE_DISCONNECTED,
}
return {"logged_in": False, "cloud": STATE_DISCONNECTED}
claims = cloud.claims
client = cloud.client
@@ -442,15 +439,15 @@ def _account_data(cloud):
certificate = None
return {
'logged_in': True,
'email': claims['email'],
'cloud': cloud.iot.state,
'prefs': client.prefs.as_dict(),
'google_entities': client.google_user_config['filter'].config,
'alexa_entities': client.alexa_user_config['filter'].config,
'remote_domain': remote.instance_domain,
'remote_connected': remote.is_connected,
'remote_certificate': certificate,
"logged_in": True,
"email": claims["email"],
"cloud": cloud.iot.state,
"prefs": client.prefs.as_dict(),
"google_entities": client.google_user_config["filter"].config,
"alexa_entities": client.alexa_user_config["filter"].config,
"remote_domain": remote.instance_domain,
"remote_connected": remote.is_connected,
"remote_certificate": certificate,
}
@@ -458,139 +455,133 @@ def _account_data(cloud):
@_require_cloud_login
@websocket_api.async_response
@_ws_handle_cloud_errors
@websocket_api.websocket_command({
'type': 'cloud/remote/connect'
})
@websocket_api.websocket_command({"type": "cloud/remote/connect"})
async def websocket_remote_connect(hass, connection, msg):
"""Handle request for connect remote."""
cloud = hass.data[DOMAIN]
await cloud.client.prefs.async_update(remote_enabled=True)
await cloud.remote.connect()
connection.send_result(msg['id'], _account_data(cloud))
connection.send_result(msg["id"], _account_data(cloud))
@websocket_api.require_admin
@_require_cloud_login
@websocket_api.async_response
@_ws_handle_cloud_errors
@websocket_api.websocket_command({
'type': 'cloud/remote/disconnect'
})
@websocket_api.websocket_command({"type": "cloud/remote/disconnect"})
async def websocket_remote_disconnect(hass, connection, msg):
"""Handle request for disconnect remote."""
cloud = hass.data[DOMAIN]
await cloud.client.prefs.async_update(remote_enabled=False)
await cloud.remote.disconnect()
connection.send_result(msg['id'], _account_data(cloud))
connection.send_result(msg["id"], _account_data(cloud))
@websocket_api.require_admin
@_require_cloud_login
@websocket_api.async_response
@_ws_handle_cloud_errors
@websocket_api.websocket_command({
'type': 'cloud/google_assistant/entities'
})
@websocket_api.websocket_command({"type": "cloud/google_assistant/entities"})
async def google_assistant_list(hass, connection, msg):
"""List all google assistant entities."""
cloud = hass.data[DOMAIN]
entities = google_helpers.async_get_entities(
hass, cloud.client.google_config
)
entities = google_helpers.async_get_entities(hass, cloud.client.google_config)
result = []
for entity in entities:
result.append({
'entity_id': entity.entity_id,
'traits': [trait.name for trait in entity.traits()],
'might_2fa': entity.might_2fa(),
})
result.append(
{
"entity_id": entity.entity_id,
"traits": [trait.name for trait in entity.traits()],
"might_2fa": entity.might_2fa(),
}
)
connection.send_result(msg['id'], result)
connection.send_result(msg["id"], result)
@websocket_api.require_admin
@_require_cloud_login
@websocket_api.async_response
@_ws_handle_cloud_errors
@websocket_api.websocket_command({
'type': 'cloud/google_assistant/entities/update',
'entity_id': str,
vol.Optional('should_expose'): bool,
vol.Optional('override_name'): str,
vol.Optional('aliases'): [str],
vol.Optional('disable_2fa'): bool,
})
@websocket_api.websocket_command(
{
"type": "cloud/google_assistant/entities/update",
"entity_id": str,
vol.Optional("should_expose"): bool,
vol.Optional("override_name"): str,
vol.Optional("aliases"): [str],
vol.Optional("disable_2fa"): bool,
}
)
async def google_assistant_update(hass, connection, msg):
"""Update google assistant config."""
cloud = hass.data[DOMAIN]
changes = dict(msg)
changes.pop('type')
changes.pop('id')
changes.pop("type")
changes.pop("id")
await cloud.client.prefs.async_update_google_entity_config(**changes)
connection.send_result(
msg['id'],
cloud.client.prefs.google_entity_configs.get(msg['entity_id']))
msg["id"], cloud.client.prefs.google_entity_configs.get(msg["entity_id"])
)
@websocket_api.require_admin
@_require_cloud_login
@websocket_api.async_response
@_ws_handle_cloud_errors
@websocket_api.websocket_command({
'type': 'cloud/alexa/entities'
})
@websocket_api.websocket_command({"type": "cloud/alexa/entities"})
async def alexa_list(hass, connection, msg):
"""List all alexa entities."""
cloud = hass.data[DOMAIN]
entities = alexa_entities.async_get_entities(
hass, cloud.client.alexa_config
)
entities = alexa_entities.async_get_entities(hass, cloud.client.alexa_config)
result = []
for entity in entities:
result.append({
'entity_id': entity.entity_id,
'display_categories': entity.default_display_categories(),
'interfaces': [ifc.name() for ifc in entity.interfaces()],
})
result.append(
{
"entity_id": entity.entity_id,
"display_categories": entity.default_display_categories(),
"interfaces": [ifc.name() for ifc in entity.interfaces()],
}
)
connection.send_result(msg['id'], result)
connection.send_result(msg["id"], result)
@websocket_api.require_admin
@_require_cloud_login
@websocket_api.async_response
@_ws_handle_cloud_errors
@websocket_api.websocket_command({
'type': 'cloud/alexa/entities/update',
'entity_id': str,
vol.Optional('should_expose'): bool,
})
@websocket_api.websocket_command(
{
"type": "cloud/alexa/entities/update",
"entity_id": str,
vol.Optional("should_expose"): bool,
}
)
async def alexa_update(hass, connection, msg):
"""Update alexa entity config."""
cloud = hass.data[DOMAIN]
changes = dict(msg)
changes.pop('type')
changes.pop('id')
changes.pop("type")
changes.pop("id")
await cloud.client.prefs.async_update_alexa_entity_config(**changes)
connection.send_result(
msg['id'],
cloud.client.prefs.alexa_entity_configs.get(msg['entity_id']))
msg["id"], cloud.client.prefs.alexa_entity_configs.get(msg["entity_id"])
)
@websocket_api.require_admin
@_require_cloud_login
@websocket_api.async_response
@websocket_api.websocket_command({
'type': 'cloud/alexa/sync',
})
@websocket_api.websocket_command({"type": "cloud/alexa/sync"})
async def alexa_sync(hass, connection, msg):
"""Sync with Alexa."""
cloud = hass.data[DOMAIN]
@@ -600,14 +591,13 @@ async def alexa_sync(hass, connection, msg):
success = await cloud.client.alexa_config.async_sync_entities()
except alexa_errors.NoTokenAvailable:
connection.send_error(
msg['id'], 'alexa_relink',
'Please go to the Alexa app and re-link the Home Assistant '
'skill.'
msg["id"],
"alexa_relink",
"Please go to the Alexa app and re-link the Home Assistant " "skill.",
)
return
if success:
connection.send_result(msg['id'])
connection.send_result(msg["id"])
else:
connection.send_error(
msg['id'], ws_const.ERR_UNKNOWN_ERROR, 'Unknown error')
connection.send_error(msg["id"], ws_const.ERR_UNKNOWN_ERROR, "Unknown error")
+70 -60
View File
@@ -5,12 +5,24 @@ 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)
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
STORAGE_VERSION = 1
@@ -50,23 +62,30 @@ class CloudPreferences:
"""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_report_state=_UNDEF):
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_report_state=_UNDEF,
):
"""Update user preferences."""
for key, value in (
(PREF_ENABLE_GOOGLE, google_enabled),
(PREF_ENABLE_ALEXA, alexa_enabled),
(PREF_ENABLE_REMOTE, remote_enabled),
(PREF_GOOGLE_SECURE_DEVICES_PIN, google_secure_devices_pin),
(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_ENABLE_GOOGLE, google_enabled),
(PREF_ENABLE_ALEXA, alexa_enabled),
(PREF_ENABLE_REMOTE, remote_enabled),
(PREF_GOOGLE_SECURE_DEVICES_PIN, google_secure_devices_pin),
(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),
):
if value is not _UNDEF:
self._prefs[key] = value
@@ -82,23 +101,27 @@ class CloudPreferences:
await self._store.async_save(self._prefs)
for listener in self._listeners:
self._hass.async_create_task(
async_create_catching_coro(listener(self))
)
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):
self,
*,
entity_id,
override_name=_UNDEF,
disable_2fa=_UNDEF,
aliases=_UNDEF,
should_expose=_UNDEF,
):
"""Update config for a Google entity."""
entities = self.google_entity_configs
entity = entities.get(entity_id, {})
changes = {}
for key, value in (
(PREF_OVERRIDE_NAME, override_name),
(PREF_DISABLE_2FA, disable_2fa),
(PREF_ALIASES, aliases),
(PREF_SHOULD_EXPOSE, should_expose),
(PREF_OVERRIDE_NAME, override_name),
(PREF_DISABLE_2FA, disable_2fa),
(PREF_ALIASES, aliases),
(PREF_SHOULD_EXPOSE, should_expose),
):
if value is not _UNDEF:
changes[key] = value
@@ -106,42 +129,29 @@ class CloudPreferences:
if not changes:
return
updated_entity = {
**entity,
**changes,
}
updated_entity = {**entity, **changes}
updated_entities = {
**entities,
entity_id: updated_entity,
}
updated_entities = {**entities, entity_id: updated_entity}
await self.async_update(google_entity_configs=updated_entities)
async def async_update_alexa_entity_config(
self, *, entity_id, should_expose=_UNDEF):
self, *, entity_id, should_expose=_UNDEF
):
"""Update config for an Alexa entity."""
entities = self.alexa_entity_configs
entity = entities.get(entity_id, {})
changes = {}
for key, value in (
(PREF_SHOULD_EXPOSE, should_expose),
):
for key, value in ((PREF_SHOULD_EXPOSE, should_expose),):
if value is not _UNDEF:
changes[key] = value
if not changes:
return
updated_entity = {
**entity,
**changes,
}
updated_entity = {**entity, **changes}
updated_entities = {
**entities,
entity_id: updated_entity,
}
updated_entities = {**entities, entity_id: updated_entity}
await self.async_update(alexa_entity_configs=updated_entities)
def as_dict(self):
@@ -179,8 +189,7 @@ class CloudPreferences:
@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)
return self._prefs.get(PREF_ALEXA_REPORT_STATE, DEFAULT_ALEXA_REPORT_STATE)
@property
def google_enabled(self):
@@ -215,11 +224,11 @@ class CloudPreferences:
@property
def _has_local_trusted_network(self) -> bool:
"""Return if we allow localhost to bypass auth."""
local4 = ip_address('127.0.0.1')
local6 = ip_address('::1')
local4 = ip_address("127.0.0.1")
local6 = ip_address("::1")
for prv in self._hass.auth.auth_providers:
if prv.type != 'trusted_networks':
if prv.type != "trusted_networks":
continue
for network in prv.trusted_networks:
@@ -231,14 +240,15 @@ class CloudPreferences:
@property
def _has_local_trusted_proxies(self) -> bool:
"""Return if we allow localhost to be a proxy and use its data."""
if not hasattr(self._hass, 'http'):
if not hasattr(self._hass, "http"):
return False
local4 = ip_address('127.0.0.1')
local6 = ip_address('::1')
local4 = ip_address("127.0.0.1")
local6 = ip_address("::1")
if any(local4 in nwk or local6 in nwk
for nwk in self._hass.http.trusted_proxies):
if any(
local4 in nwk or local6 in nwk for nwk in self._hass.http.trusted_proxies
):
return True
return False
+2 -6
View File
@@ -14,12 +14,8 @@ def aiohttp_serialize_response(response: web.Response) -> Dict[str, Any]:
# pylint: disable=protected-access
body = body._value.decode(body.encoding)
elif isinstance(body, bytes):
body = body.decode(response.charset or 'utf-8')
body = body.decode(response.charset or "utf-8")
else:
raise ValueError("Unknown payload encoding")
return {
'status': response.status,
'body': body,
'headers': dict(response.headers),
}
return {"status": response.status, "body": body, "headers": dict(response.headers)}