Black
This commit is contained in:
1 parent
da05dfe708
commit
4de97abc3a
2676 files changed
+163166
-140084
No files matched your search
@@ -6,7 +6,7 @@ from . import commands, connection, const, decorators, http, messages
|
||||
|
||||
DOMAIN = const.DOMAIN
|
||||
|
||||
DEPENDENCIES = ('http',)
|
||||
DEPENDENCIES = ("http",)
|
||||
|
||||
# Backwards compat / Make it easier to integrate
|
||||
# pylint: disable=invalid-name
|
||||
@@ -24,8 +24,7 @@ websocket_command = decorators.websocket_command
|
||||
|
||||
@bind_hass
|
||||
@callback
|
||||
def async_register_command(hass, command_or_handler, handler=None,
|
||||
schema=None):
|
||||
def async_register_command(hass, command_or_handler, handler=None, schema=None):
|
||||
"""Register a websocket command."""
|
||||
# pylint: disable=protected-access
|
||||
if handler is None:
|
||||
|
||||
@@ -3,49 +3,39 @@ import voluptuous as vol
|
||||
from voluptuous.humanize import humanize_error
|
||||
|
||||
from homeassistant.auth.providers import legacy_api_password
|
||||
from homeassistant.components.http.ban import (
|
||||
process_wrong_login,
|
||||
process_success_login,
|
||||
)
|
||||
from homeassistant.components.http.ban import process_wrong_login, process_success_login
|
||||
from homeassistant.const import __version__
|
||||
|
||||
from .connection import ActiveConnection
|
||||
from .error import Disconnect
|
||||
|
||||
TYPE_AUTH = 'auth'
|
||||
TYPE_AUTH_INVALID = 'auth_invalid'
|
||||
TYPE_AUTH_OK = 'auth_ok'
|
||||
TYPE_AUTH_REQUIRED = 'auth_required'
|
||||
TYPE_AUTH = "auth"
|
||||
TYPE_AUTH_INVALID = "auth_invalid"
|
||||
TYPE_AUTH_OK = "auth_ok"
|
||||
TYPE_AUTH_REQUIRED = "auth_required"
|
||||
|
||||
AUTH_MESSAGE_SCHEMA = vol.Schema({
|
||||
vol.Required('type'): TYPE_AUTH,
|
||||
vol.Exclusive('api_password', 'auth'): str,
|
||||
vol.Exclusive('access_token', 'auth'): str,
|
||||
})
|
||||
AUTH_MESSAGE_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required("type"): TYPE_AUTH,
|
||||
vol.Exclusive("api_password", "auth"): str,
|
||||
vol.Exclusive("access_token", "auth"): str,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def auth_ok_message():
|
||||
"""Return an auth_ok message."""
|
||||
return {
|
||||
'type': TYPE_AUTH_OK,
|
||||
'ha_version': __version__,
|
||||
}
|
||||
return {"type": TYPE_AUTH_OK, "ha_version": __version__}
|
||||
|
||||
|
||||
def auth_required_message():
|
||||
"""Return an auth_required message."""
|
||||
return {
|
||||
'type': TYPE_AUTH_REQUIRED,
|
||||
'ha_version': __version__,
|
||||
}
|
||||
return {"type": TYPE_AUTH_REQUIRED, "ha_version": __version__}
|
||||
|
||||
|
||||
def auth_invalid_message(message):
|
||||
"""Return an auth_invalid message."""
|
||||
return {
|
||||
'type': TYPE_AUTH_INVALID,
|
||||
'message': message,
|
||||
}
|
||||
return {"type": TYPE_AUTH_INVALID, "message": message}
|
||||
|
||||
|
||||
class AuthPhase:
|
||||
@@ -65,22 +55,22 @@ class AuthPhase:
|
||||
try:
|
||||
msg = AUTH_MESSAGE_SCHEMA(msg)
|
||||
except vol.Invalid as err:
|
||||
error_msg = 'Auth message incorrectly formatted: {}'.format(
|
||||
humanize_error(msg, err))
|
||||
error_msg = "Auth message incorrectly formatted: {}".format(
|
||||
humanize_error(msg, err)
|
||||
)
|
||||
self._logger.warning(error_msg)
|
||||
self._send_message(auth_invalid_message(error_msg))
|
||||
raise Disconnect
|
||||
|
||||
if 'access_token' in msg:
|
||||
if "access_token" in msg:
|
||||
self._logger.debug("Received access_token")
|
||||
refresh_token = \
|
||||
await self._hass.auth.async_validate_access_token(
|
||||
msg['access_token'])
|
||||
refresh_token = await self._hass.auth.async_validate_access_token(
|
||||
msg["access_token"]
|
||||
)
|
||||
if refresh_token is not None:
|
||||
return await self._async_finish_auth(
|
||||
refresh_token.user, refresh_token)
|
||||
return await self._async_finish_auth(refresh_token.user, refresh_token)
|
||||
|
||||
elif self._hass.auth.support_legacy and 'api_password' in msg:
|
||||
elif self._hass.auth.support_legacy and "api_password" in msg:
|
||||
self._logger.info(
|
||||
"Received api_password, it is going to deprecate, please use"
|
||||
" access_token instead. For instructions, see https://"
|
||||
@@ -88,20 +78,20 @@ class AuthPhase:
|
||||
".html#authentication-phase"
|
||||
)
|
||||
user = await legacy_api_password.async_validate_password(
|
||||
self._hass, msg['api_password'])
|
||||
self._hass, msg["api_password"]
|
||||
)
|
||||
if user is not None:
|
||||
return await self._async_finish_auth(user, None)
|
||||
|
||||
self._send_message(auth_invalid_message(
|
||||
'Invalid access token or password'))
|
||||
self._send_message(auth_invalid_message("Invalid access token or password"))
|
||||
await process_wrong_login(self._request)
|
||||
raise Disconnect
|
||||
|
||||
async def _async_finish_auth(self, user, refresh_token) \
|
||||
-> ActiveConnection:
|
||||
async def _async_finish_auth(self, user, refresh_token) -> ActiveConnection:
|
||||
"""Create an active connection."""
|
||||
self._logger.debug("Auth OK")
|
||||
await process_success_login(self._request)
|
||||
self._send_message(auth_ok_message())
|
||||
return ActiveConnection(
|
||||
self._logger, self._hass, self._send_message, user, refresh_token)
|
||||
self._logger, self._hass, self._send_message, user, refresh_token
|
||||
)
|
||||
@@ -2,11 +2,9 @@
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.auth.permissions.const import POLICY_READ
|
||||
from homeassistant.const import (
|
||||
MATCH_ALL, EVENT_TIME_CHANGED, EVENT_STATE_CHANGED)
|
||||
from homeassistant.const import MATCH_ALL, EVENT_TIME_CHANGED, EVENT_STATE_CHANGED
|
||||
from homeassistant.core import callback, DOMAIN as HASS_DOMAIN
|
||||
from homeassistant.exceptions import Unauthorized, ServiceNotFound, \
|
||||
HomeAssistantError
|
||||
from homeassistant.exceptions import Unauthorized, ServiceNotFound, HomeAssistantError
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.service import async_get_all_descriptions
|
||||
|
||||
@@ -27,17 +25,16 @@ def async_register_commands(hass, async_reg):
|
||||
|
||||
def pong_message(iden):
|
||||
"""Return a pong message."""
|
||||
return {
|
||||
'id': iden,
|
||||
'type': 'pong',
|
||||
}
|
||||
return {"id": iden, "type": "pong"}
|
||||
|
||||
|
||||
@callback
|
||||
@decorators.websocket_command({
|
||||
vol.Required('type'): 'subscribe_events',
|
||||
vol.Optional('event_type', default=MATCH_ALL): str,
|
||||
})
|
||||
@decorators.websocket_command(
|
||||
{
|
||||
vol.Required("type"): "subscribe_events",
|
||||
vol.Optional("event_type", default=MATCH_ALL): str,
|
||||
}
|
||||
)
|
||||
def handle_subscribe_events(hass, connection, msg):
|
||||
"""Handle subscribe events command.
|
||||
|
||||
@@ -45,154 +42,163 @@ def handle_subscribe_events(hass, connection, msg):
|
||||
"""
|
||||
from .permissions import SUBSCRIBE_WHITELIST
|
||||
|
||||
event_type = msg['event_type']
|
||||
event_type = msg["event_type"]
|
||||
|
||||
if (event_type not in SUBSCRIBE_WHITELIST and
|
||||
not connection.user.is_admin):
|
||||
if event_type not in SUBSCRIBE_WHITELIST and not connection.user.is_admin:
|
||||
raise Unauthorized
|
||||
|
||||
if event_type == EVENT_STATE_CHANGED:
|
||||
|
||||
@callback
|
||||
def forward_events(event):
|
||||
"""Forward state changed events to websocket."""
|
||||
if not connection.user.permissions.check_entity(
|
||||
event.data['entity_id'], POLICY_READ):
|
||||
event.data["entity_id"], POLICY_READ
|
||||
):
|
||||
return
|
||||
|
||||
connection.send_message(messages.event_message(msg['id'], event))
|
||||
connection.send_message(messages.event_message(msg["id"], event))
|
||||
|
||||
else:
|
||||
|
||||
@callback
|
||||
def forward_events(event):
|
||||
"""Forward events to websocket."""
|
||||
if event.event_type == EVENT_TIME_CHANGED:
|
||||
return
|
||||
|
||||
connection.send_message(messages.event_message(
|
||||
msg['id'], event.as_dict()
|
||||
))
|
||||
connection.send_message(messages.event_message(msg["id"], event.as_dict()))
|
||||
|
||||
connection.subscriptions[msg['id']] = hass.bus.async_listen(
|
||||
event_type, forward_events)
|
||||
connection.subscriptions[msg["id"]] = hass.bus.async_listen(
|
||||
event_type, forward_events
|
||||
)
|
||||
|
||||
connection.send_message(messages.result_message(msg['id']))
|
||||
connection.send_message(messages.result_message(msg["id"]))
|
||||
|
||||
|
||||
@callback
|
||||
@decorators.websocket_command({
|
||||
vol.Required('type'): 'unsubscribe_events',
|
||||
vol.Required('subscription'): cv.positive_int,
|
||||
})
|
||||
@decorators.websocket_command(
|
||||
{
|
||||
vol.Required("type"): "unsubscribe_events",
|
||||
vol.Required("subscription"): cv.positive_int,
|
||||
}
|
||||
)
|
||||
def handle_unsubscribe_events(hass, connection, msg):
|
||||
"""Handle unsubscribe events command.
|
||||
|
||||
Async friendly.
|
||||
"""
|
||||
subscription = msg['subscription']
|
||||
subscription = msg["subscription"]
|
||||
|
||||
if subscription in connection.subscriptions:
|
||||
connection.subscriptions.pop(subscription)()
|
||||
connection.send_message(messages.result_message(msg['id']))
|
||||
connection.send_message(messages.result_message(msg["id"]))
|
||||
else:
|
||||
connection.send_message(messages.error_message(
|
||||
msg['id'], const.ERR_NOT_FOUND, 'Subscription not found.'))
|
||||
connection.send_message(
|
||||
messages.error_message(
|
||||
msg["id"], const.ERR_NOT_FOUND, "Subscription not found."
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@decorators.async_response
|
||||
@decorators.websocket_command({
|
||||
vol.Required('type'): 'call_service',
|
||||
vol.Required('domain'): str,
|
||||
vol.Required('service'): str,
|
||||
vol.Optional('service_data'): dict
|
||||
})
|
||||
@decorators.websocket_command(
|
||||
{
|
||||
vol.Required("type"): "call_service",
|
||||
vol.Required("domain"): str,
|
||||
vol.Required("service"): str,
|
||||
vol.Optional("service_data"): dict,
|
||||
}
|
||||
)
|
||||
async def handle_call_service(hass, connection, msg):
|
||||
"""Handle call service command.
|
||||
|
||||
Async friendly.
|
||||
"""
|
||||
blocking = True
|
||||
if (msg['domain'] == HASS_DOMAIN and
|
||||
msg['service'] in ['restart', 'stop']):
|
||||
if msg["domain"] == HASS_DOMAIN and msg["service"] in ["restart", "stop"]:
|
||||
blocking = False
|
||||
|
||||
try:
|
||||
await hass.services.async_call(
|
||||
msg['domain'], msg['service'], msg.get('service_data'), blocking,
|
||||
connection.context(msg))
|
||||
connection.send_message(messages.result_message(msg['id']))
|
||||
msg["domain"],
|
||||
msg["service"],
|
||||
msg.get("service_data"),
|
||||
blocking,
|
||||
connection.context(msg),
|
||||
)
|
||||
connection.send_message(messages.result_message(msg["id"]))
|
||||
except ServiceNotFound as err:
|
||||
if err.domain == msg['domain'] and err.service == msg['service']:
|
||||
connection.send_message(messages.error_message(
|
||||
msg['id'], const.ERR_NOT_FOUND, 'Service not found.'))
|
||||
if err.domain == msg["domain"] and err.service == msg["service"]:
|
||||
connection.send_message(
|
||||
messages.error_message(
|
||||
msg["id"], const.ERR_NOT_FOUND, "Service not found."
|
||||
)
|
||||
)
|
||||
else:
|
||||
connection.send_message(messages.error_message(
|
||||
msg['id'], const.ERR_HOME_ASSISTANT_ERROR, str(err)))
|
||||
connection.send_message(
|
||||
messages.error_message(
|
||||
msg["id"], const.ERR_HOME_ASSISTANT_ERROR, str(err)
|
||||
)
|
||||
)
|
||||
except HomeAssistantError as err:
|
||||
connection.logger.exception(err)
|
||||
connection.send_message(messages.error_message(
|
||||
msg['id'], const.ERR_HOME_ASSISTANT_ERROR, str(err)))
|
||||
connection.send_message(
|
||||
messages.error_message(msg["id"], const.ERR_HOME_ASSISTANT_ERROR, str(err))
|
||||
)
|
||||
except Exception as err: # pylint: disable=broad-except
|
||||
connection.logger.exception(err)
|
||||
connection.send_message(messages.error_message(
|
||||
msg['id'], const.ERR_UNKNOWN_ERROR, str(err)))
|
||||
connection.send_message(
|
||||
messages.error_message(msg["id"], const.ERR_UNKNOWN_ERROR, str(err))
|
||||
)
|
||||
|
||||
|
||||
@callback
|
||||
@decorators.websocket_command({
|
||||
vol.Required('type'): 'get_states',
|
||||
})
|
||||
@decorators.websocket_command({vol.Required("type"): "get_states"})
|
||||
def handle_get_states(hass, connection, msg):
|
||||
"""Handle get states command.
|
||||
|
||||
Async friendly.
|
||||
"""
|
||||
if connection.user.permissions.access_all_entities('read'):
|
||||
if connection.user.permissions.access_all_entities("read"):
|
||||
states = hass.states.async_all()
|
||||
else:
|
||||
entity_perm = connection.user.permissions.check_entity
|
||||
states = [
|
||||
state for state in hass.states.async_all()
|
||||
if entity_perm(state.entity_id, 'read')
|
||||
state
|
||||
for state in hass.states.async_all()
|
||||
if entity_perm(state.entity_id, "read")
|
||||
]
|
||||
|
||||
connection.send_message(messages.result_message(
|
||||
msg['id'], states))
|
||||
connection.send_message(messages.result_message(msg["id"], states))
|
||||
|
||||
|
||||
@decorators.async_response
|
||||
@decorators.websocket_command({
|
||||
vol.Required('type'): 'get_services',
|
||||
})
|
||||
@decorators.websocket_command({vol.Required("type"): "get_services"})
|
||||
async def handle_get_services(hass, connection, msg):
|
||||
"""Handle get services command.
|
||||
|
||||
Async friendly.
|
||||
"""
|
||||
descriptions = await async_get_all_descriptions(hass)
|
||||
connection.send_message(
|
||||
messages.result_message(msg['id'], descriptions))
|
||||
connection.send_message(messages.result_message(msg["id"], descriptions))
|
||||
|
||||
|
||||
@callback
|
||||
@decorators.websocket_command({
|
||||
vol.Required('type'): 'get_config',
|
||||
})
|
||||
@decorators.websocket_command({vol.Required("type"): "get_config"})
|
||||
def handle_get_config(hass, connection, msg):
|
||||
"""Handle get config command.
|
||||
|
||||
Async friendly.
|
||||
"""
|
||||
connection.send_message(messages.result_message(
|
||||
msg['id'], hass.config.as_dict()))
|
||||
connection.send_message(messages.result_message(msg["id"], hass.config.as_dict()))
|
||||
|
||||
|
||||
@callback
|
||||
@decorators.websocket_command({
|
||||
vol.Required('type'): 'ping',
|
||||
})
|
||||
@decorators.websocket_command({vol.Required("type"): "ping"})
|
||||
def handle_ping(hass, connection, msg):
|
||||
"""Handle ping command.
|
||||
|
||||
Async friendly.
|
||||
"""
|
||||
connection.send_message(pong_message(msg['id']))
|
||||
connection.send_message(pong_message(msg["id"]))
|
||||
@@ -56,29 +56,36 @@ class ActiveConnection:
|
||||
|
||||
try:
|
||||
msg = messages.MINIMAL_MESSAGE_SCHEMA(msg)
|
||||
cur_id = msg['id']
|
||||
cur_id = msg["id"]
|
||||
except vol.Invalid:
|
||||
self.logger.error('Received invalid command', msg)
|
||||
self.send_message(messages.error_message(
|
||||
msg.get('id'), const.ERR_INVALID_FORMAT,
|
||||
'Message incorrectly formatted.'))
|
||||
self.logger.error("Received invalid command", msg)
|
||||
self.send_message(
|
||||
messages.error_message(
|
||||
msg.get("id"),
|
||||
const.ERR_INVALID_FORMAT,
|
||||
"Message incorrectly formatted.",
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
if cur_id <= self.last_id:
|
||||
self.send_message(messages.error_message(
|
||||
cur_id, const.ERR_ID_REUSE,
|
||||
'Identifier values have to increase.'))
|
||||
self.send_message(
|
||||
messages.error_message(
|
||||
cur_id, const.ERR_ID_REUSE, "Identifier values have to increase."
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
if msg['type'] not in handlers:
|
||||
self.logger.error(
|
||||
'Received invalid command: {}'.format(msg['type']))
|
||||
self.send_message(messages.error_message(
|
||||
cur_id, const.ERR_UNKNOWN_COMMAND,
|
||||
'Unknown command.'))
|
||||
if msg["type"] not in handlers:
|
||||
self.logger.error("Received invalid command: {}".format(msg["type"]))
|
||||
self.send_message(
|
||||
messages.error_message(
|
||||
cur_id, const.ERR_UNKNOWN_COMMAND, "Unknown command."
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
handler, schema = handlers[msg['type']]
|
||||
handler, schema = handlers[msg["type"]]
|
||||
|
||||
try:
|
||||
handler(self.hass, self, schema(msg))
|
||||
@@ -98,17 +105,16 @@ class ActiveConnection:
|
||||
"""Handle an exception while processing a handler."""
|
||||
if isinstance(err, Unauthorized):
|
||||
code = const.ERR_UNAUTHORIZED
|
||||
err_message = 'Unauthorized'
|
||||
err_message = "Unauthorized"
|
||||
elif isinstance(err, vol.Invalid):
|
||||
code = const.ERR_INVALID_FORMAT
|
||||
err_message = vol.humanize.humanize_error(msg, err)
|
||||
elif isinstance(err, asyncio.TimeoutError):
|
||||
code = const.ERR_TIMEOUT
|
||||
err_message = 'Timeout'
|
||||
err_message = "Timeout"
|
||||
else:
|
||||
code = const.ERR_UNKNOWN_ERROR
|
||||
err_message = 'Unknown error'
|
||||
err_message = "Unknown error"
|
||||
|
||||
self.logger.exception('Error handling message: %s', err_message)
|
||||
self.send_message(
|
||||
messages.error_message(msg['id'], code, err_message))
|
||||
self.logger.exception("Error handling message: %s", err_message)
|
||||
self.send_message(messages.error_message(msg["id"], code, err_message))
|
||||
@@ -5,20 +5,20 @@ from functools import partial
|
||||
import json
|
||||
from homeassistant.helpers.json import JSONEncoder
|
||||
|
||||
DOMAIN = 'websocket_api'
|
||||
URL = '/api/websocket'
|
||||
DOMAIN = "websocket_api"
|
||||
URL = "/api/websocket"
|
||||
MAX_PENDING_MSG = 512
|
||||
|
||||
ERR_ID_REUSE = 'id_reuse'
|
||||
ERR_INVALID_FORMAT = 'invalid_format'
|
||||
ERR_NOT_FOUND = 'not_found'
|
||||
ERR_HOME_ASSISTANT_ERROR = 'home_assistant_error'
|
||||
ERR_UNKNOWN_COMMAND = 'unknown_command'
|
||||
ERR_UNKNOWN_ERROR = 'unknown_error'
|
||||
ERR_UNAUTHORIZED = 'unauthorized'
|
||||
ERR_TIMEOUT = 'timeout'
|
||||
ERR_ID_REUSE = "id_reuse"
|
||||
ERR_INVALID_FORMAT = "invalid_format"
|
||||
ERR_NOT_FOUND = "not_found"
|
||||
ERR_HOME_ASSISTANT_ERROR = "home_assistant_error"
|
||||
ERR_UNKNOWN_COMMAND = "unknown_command"
|
||||
ERR_UNKNOWN_ERROR = "unknown_error"
|
||||
ERR_UNAUTHORIZED = "unauthorized"
|
||||
ERR_TIMEOUT = "timeout"
|
||||
|
||||
TYPE_RESULT = 'result'
|
||||
TYPE_RESULT = "result"
|
||||
|
||||
# Define the possible errors that occur when connections are cancelled.
|
||||
# Originally, this was just asyncio.CancelledError, but issue #9546 showed
|
||||
@@ -26,10 +26,10 @@ TYPE_RESULT = 'result'
|
||||
CANCELLATION_ERRORS = (asyncio.CancelledError, futures.CancelledError)
|
||||
|
||||
# Event types
|
||||
SIGNAL_WEBSOCKET_CONNECTED = 'websocket_connected'
|
||||
SIGNAL_WEBSOCKET_DISCONNECTED = 'websocket_disconnected'
|
||||
SIGNAL_WEBSOCKET_CONNECTED = "websocket_connected"
|
||||
SIGNAL_WEBSOCKET_DISCONNECTED = "websocket_disconnected"
|
||||
|
||||
# Data used to store the current connection list
|
||||
DATA_CONNECTIONS = DOMAIN + '.connections'
|
||||
DATA_CONNECTIONS = DOMAIN + ".connections"
|
||||
|
||||
JSON_DUMP = partial(json.dumps, cls=JSONEncoder, allow_nan=False)
|
||||
@@ -21,18 +21,19 @@ async def _handle_async_response(func, hass, connection, msg):
|
||||
|
||||
def async_response(func):
|
||||
"""Decorate an async function to handle WebSocket API messages."""
|
||||
|
||||
@callback
|
||||
@wraps(func)
|
||||
def schedule_handler(hass, connection, msg):
|
||||
"""Schedule the handler."""
|
||||
hass.async_create_task(
|
||||
_handle_async_response(func, hass, connection, msg))
|
||||
hass.async_create_task(_handle_async_response(func, hass, connection, msg))
|
||||
|
||||
return schedule_handler
|
||||
|
||||
|
||||
def require_admin(func):
|
||||
"""Websocket decorator to require user to be an admin."""
|
||||
|
||||
@wraps(func)
|
||||
def with_admin(hass, connection, msg):
|
||||
"""Check admin and call function."""
|
||||
@@ -47,50 +48,52 @@ def require_admin(func):
|
||||
|
||||
|
||||
def ws_require_user(
|
||||
only_owner=False, only_system_user=False, allow_system_user=True,
|
||||
only_active_user=True, only_inactive_user=False):
|
||||
only_owner=False,
|
||||
only_system_user=False,
|
||||
allow_system_user=True,
|
||||
only_active_user=True,
|
||||
only_inactive_user=False,
|
||||
):
|
||||
"""Decorate function validating login user exist in current WS connection.
|
||||
|
||||
Will write out error message if not authenticated.
|
||||
"""
|
||||
|
||||
def validator(func):
|
||||
"""Decorate func."""
|
||||
|
||||
@wraps(func)
|
||||
def check_current_user(hass, connection, msg):
|
||||
"""Check current user."""
|
||||
|
||||
def output_error(message_id, message):
|
||||
"""Output error message."""
|
||||
connection.send_message(messages.error_message(
|
||||
msg['id'], message_id, message))
|
||||
connection.send_message(
|
||||
messages.error_message(msg["id"], message_id, message)
|
||||
)
|
||||
|
||||
if connection.user is None:
|
||||
output_error('no_user', 'Not authenticated as a user')
|
||||
output_error("no_user", "Not authenticated as a user")
|
||||
return
|
||||
|
||||
if only_owner and not connection.user.is_owner:
|
||||
output_error('only_owner', 'Only allowed as owner')
|
||||
output_error("only_owner", "Only allowed as owner")
|
||||
return
|
||||
|
||||
if (only_system_user and
|
||||
not connection.user.system_generated):
|
||||
output_error('only_system_user',
|
||||
'Only allowed as system user')
|
||||
if only_system_user and not connection.user.system_generated:
|
||||
output_error("only_system_user", "Only allowed as system user")
|
||||
return
|
||||
|
||||
if (not allow_system_user
|
||||
and connection.user.system_generated):
|
||||
output_error('not_system_user', 'Not allowed as system user')
|
||||
if not allow_system_user and connection.user.system_generated:
|
||||
output_error("not_system_user", "Not allowed as system user")
|
||||
return
|
||||
|
||||
if (only_active_user and
|
||||
not connection.user.is_active):
|
||||
output_error('only_active_user',
|
||||
'Only allowed as active user')
|
||||
if only_active_user and not connection.user.is_active:
|
||||
output_error("only_active_user", "Only allowed as active user")
|
||||
return
|
||||
|
||||
if only_inactive_user and connection.user.is_active:
|
||||
output_error('only_inactive_user',
|
||||
'Not allowed as active user')
|
||||
output_error("only_inactive_user", "Not allowed as active user")
|
||||
return
|
||||
|
||||
return func(hass, connection, msg)
|
||||
@@ -102,7 +105,7 @@ def ws_require_user(
|
||||
|
||||
def websocket_command(schema):
|
||||
"""Tag a function as a websocket command."""
|
||||
command = schema['type']
|
||||
command = schema["type"]
|
||||
|
||||
def decorate(func):
|
||||
"""Decorate ws command function."""
|
||||
|
||||
@@ -11,9 +11,15 @@ from homeassistant.core import callback
|
||||
from homeassistant.components.http import HomeAssistantView
|
||||
|
||||
from .const import (
|
||||
MAX_PENDING_MSG, CANCELLATION_ERRORS, URL, ERR_UNKNOWN_ERROR,
|
||||
SIGNAL_WEBSOCKET_CONNECTED, SIGNAL_WEBSOCKET_DISCONNECTED,
|
||||
DATA_CONNECTIONS, JSON_DUMP)
|
||||
MAX_PENDING_MSG,
|
||||
CANCELLATION_ERRORS,
|
||||
URL,
|
||||
ERR_UNKNOWN_ERROR,
|
||||
SIGNAL_WEBSOCKET_CONNECTED,
|
||||
SIGNAL_WEBSOCKET_DISCONNECTED,
|
||||
DATA_CONNECTIONS,
|
||||
JSON_DUMP,
|
||||
)
|
||||
from .auth import AuthPhase, auth_required_message
|
||||
from .error import Disconnect
|
||||
from .messages import error_message
|
||||
@@ -28,8 +34,7 @@ class WebsocketAPIView(HomeAssistantView):
|
||||
|
||||
async def get(self, request):
|
||||
"""Handle an incoming websocket connection."""
|
||||
return await WebSocketHandler(
|
||||
request.app['hass'], request).async_handle()
|
||||
return await WebSocketHandler(request.app["hass"], request).async_handle()
|
||||
|
||||
|
||||
class WebSocketHandler:
|
||||
@@ -43,14 +48,12 @@ class WebSocketHandler:
|
||||
self._to_write = asyncio.Queue(maxsize=MAX_PENDING_MSG)
|
||||
self._handle_task = None
|
||||
self._writer_task = None
|
||||
self._logger = logging.getLogger(
|
||||
"{}.connection.{}".format(__name__, id(self)))
|
||||
self._logger = logging.getLogger("{}.connection.{}".format(__name__, id(self)))
|
||||
|
||||
async def _writer(self):
|
||||
"""Write outgoing messages."""
|
||||
# Exceptions if Socket disconnected or cancelled by connection handler
|
||||
with suppress(RuntimeError, ConnectionResetError,
|
||||
*CANCELLATION_ERRORS):
|
||||
with suppress(RuntimeError, ConnectionResetError, *CANCELLATION_ERRORS):
|
||||
while not self.wsock.closed:
|
||||
message = await self._to_write.get()
|
||||
if message is None:
|
||||
@@ -62,11 +65,14 @@ class WebSocketHandler:
|
||||
else:
|
||||
await self.wsock.send_json(message, dumps=JSON_DUMP)
|
||||
except (ValueError, TypeError) as err:
|
||||
self._logger.error('Unable to serialize to JSON: %s\n%s',
|
||||
err, message)
|
||||
await self.wsock.send_json(error_message(
|
||||
message['id'], ERR_UNKNOWN_ERROR,
|
||||
'Invalid JSON in response'))
|
||||
self._logger.error(
|
||||
"Unable to serialize to JSON: %s\n%s", err, message
|
||||
)
|
||||
await self.wsock.send_json(
|
||||
error_message(
|
||||
message["id"], ERR_UNKNOWN_ERROR, "Invalid JSON in response"
|
||||
)
|
||||
)
|
||||
|
||||
@callback
|
||||
def _send_message(self, message):
|
||||
@@ -79,8 +85,9 @@ class WebSocketHandler:
|
||||
try:
|
||||
self._to_write.put_nowait(message)
|
||||
except asyncio.QueueFull:
|
||||
self._logger.error("Client exceeded max pending messages [2]: %s",
|
||||
MAX_PENDING_MSG)
|
||||
self._logger.error(
|
||||
"Client exceeded max pending messages [2]: %s", MAX_PENDING_MSG
|
||||
)
|
||||
self._cancel()
|
||||
|
||||
@callback
|
||||
@@ -97,7 +104,7 @@ class WebSocketHandler:
|
||||
self._logger.debug("Connected")
|
||||
|
||||
# Py3.7+
|
||||
if hasattr(asyncio, 'current_task'):
|
||||
if hasattr(asyncio, "current_task"):
|
||||
# pylint: disable=no-member
|
||||
self._handle_task = asyncio.current_task()
|
||||
else:
|
||||
@@ -109,7 +116,8 @@ class WebSocketHandler:
|
||||
self._cancel()
|
||||
|
||||
unsub_stop = self.hass.bus.async_listen(
|
||||
EVENT_HOMEASSISTANT_STOP, handle_hass_stop)
|
||||
EVENT_HOMEASSISTANT_STOP, handle_hass_stop
|
||||
)
|
||||
|
||||
self._writer_task = self.hass.async_create_task(self._writer())
|
||||
|
||||
@@ -125,29 +133,30 @@ class WebSocketHandler:
|
||||
with async_timeout.timeout(10):
|
||||
msg = await wsock.receive()
|
||||
except asyncio.TimeoutError:
|
||||
disconnect_warn = \
|
||||
'Did not receive auth message within 10 seconds'
|
||||
disconnect_warn = "Did not receive auth message within 10 seconds"
|
||||
raise Disconnect
|
||||
|
||||
if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING):
|
||||
raise Disconnect
|
||||
|
||||
if msg.type != WSMsgType.TEXT:
|
||||
disconnect_warn = 'Received non-Text message.'
|
||||
disconnect_warn = "Received non-Text message."
|
||||
raise Disconnect
|
||||
|
||||
try:
|
||||
msg = msg.json()
|
||||
except ValueError:
|
||||
disconnect_warn = 'Received invalid JSON.'
|
||||
disconnect_warn = "Received invalid JSON."
|
||||
raise Disconnect
|
||||
|
||||
self._logger.debug("Received %s", msg)
|
||||
connection = await auth.async_handle(msg)
|
||||
self.hass.data[DATA_CONNECTIONS] = \
|
||||
self.hass.data[DATA_CONNECTIONS] = (
|
||||
self.hass.data.get(DATA_CONNECTIONS, 0) + 1
|
||||
)
|
||||
self.hass.helpers.dispatcher.async_dispatcher_send(
|
||||
SIGNAL_WEBSOCKET_CONNECTED)
|
||||
SIGNAL_WEBSOCKET_CONNECTED
|
||||
)
|
||||
|
||||
# Command phase
|
||||
while not wsock.closed:
|
||||
@@ -157,13 +166,13 @@ class WebSocketHandler:
|
||||
break
|
||||
|
||||
elif msg.type != WSMsgType.TEXT:
|
||||
disconnect_warn = 'Received non-Text message.'
|
||||
disconnect_warn = "Received non-Text message."
|
||||
break
|
||||
|
||||
try:
|
||||
msg = msg.json()
|
||||
except ValueError:
|
||||
disconnect_warn = 'Received invalid JSON.'
|
||||
disconnect_warn = "Received invalid JSON."
|
||||
break
|
||||
|
||||
self._logger.debug("Received %s", msg)
|
||||
@@ -201,6 +210,7 @@ class WebSocketHandler:
|
||||
if connection is not None:
|
||||
self.hass.data[DATA_CONNECTIONS] -= 1
|
||||
self.hass.helpers.dispatcher.async_dispatcher_send(
|
||||
SIGNAL_WEBSOCKET_DISCONNECTED)
|
||||
SIGNAL_WEBSOCKET_DISCONNECTED
|
||||
)
|
||||
|
||||
return wsock
|
||||
@@ -8,44 +8,30 @@ from . import const
|
||||
|
||||
|
||||
# Minimal requirements of a message
|
||||
MINIMAL_MESSAGE_SCHEMA = vol.Schema({
|
||||
vol.Required('id'): cv.positive_int,
|
||||
vol.Required('type'): cv.string,
|
||||
}, extra=vol.ALLOW_EXTRA)
|
||||
MINIMAL_MESSAGE_SCHEMA = vol.Schema(
|
||||
{vol.Required("id"): cv.positive_int, vol.Required("type"): cv.string},
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
|
||||
# Base schema to extend by message handlers
|
||||
BASE_COMMAND_MESSAGE_SCHEMA = vol.Schema({
|
||||
vol.Required('id'): cv.positive_int,
|
||||
})
|
||||
BASE_COMMAND_MESSAGE_SCHEMA = vol.Schema({vol.Required("id"): cv.positive_int})
|
||||
|
||||
|
||||
def result_message(iden, result=None):
|
||||
"""Return a success result message."""
|
||||
return {
|
||||
'id': iden,
|
||||
'type': const.TYPE_RESULT,
|
||||
'success': True,
|
||||
'result': result,
|
||||
}
|
||||
return {"id": iden, "type": const.TYPE_RESULT, "success": True, "result": result}
|
||||
|
||||
|
||||
def error_message(iden, code, message):
|
||||
"""Return an error result message."""
|
||||
return {
|
||||
'id': iden,
|
||||
'type': const.TYPE_RESULT,
|
||||
'success': False,
|
||||
'error': {
|
||||
'code': code,
|
||||
'message': message,
|
||||
},
|
||||
"id": iden,
|
||||
"type": const.TYPE_RESULT,
|
||||
"success": False,
|
||||
"error": {"code": code, "message": message},
|
||||
}
|
||||
|
||||
|
||||
def event_message(iden, event):
|
||||
"""Return an event message."""
|
||||
return {
|
||||
'id': iden,
|
||||
'type': 'event',
|
||||
'event': event,
|
||||
}
|
||||
return {"id": iden, "type": "event", "event": event}
|
||||
@@ -7,9 +7,11 @@ from homeassistant.const import (
|
||||
EVENT_SERVICE_REGISTERED,
|
||||
EVENT_SERVICE_REMOVED,
|
||||
EVENT_STATE_CHANGED,
|
||||
EVENT_THEMES_UPDATED)
|
||||
EVENT_THEMES_UPDATED,
|
||||
)
|
||||
from homeassistant.components.persistent_notification import (
|
||||
EVENT_PERSISTENT_NOTIFICATIONS_UPDATED)
|
||||
EVENT_PERSISTENT_NOTIFICATIONS_UPDATED,
|
||||
)
|
||||
from homeassistant.components.lovelace import EVENT_LOVELACE_UPDATED
|
||||
from homeassistant.helpers.area_registry import EVENT_AREA_REGISTRY_UPDATED
|
||||
from homeassistant.helpers.device_registry import EVENT_DEVICE_REGISTRY_UPDATED
|
||||
|
||||
@@ -4,12 +4,13 @@ from homeassistant.core import callback
|
||||
from homeassistant.helpers.entity import Entity
|
||||
|
||||
from .const import (
|
||||
SIGNAL_WEBSOCKET_CONNECTED, SIGNAL_WEBSOCKET_DISCONNECTED,
|
||||
DATA_CONNECTIONS)
|
||||
SIGNAL_WEBSOCKET_CONNECTED,
|
||||
SIGNAL_WEBSOCKET_DISCONNECTED,
|
||||
DATA_CONNECTIONS,
|
||||
)
|
||||
|
||||
|
||||
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 API streams platform."""
|
||||
entity = APICount()
|
||||
|
||||
@@ -26,9 +27,11 @@ class APICount(Entity):
|
||||
async def async_added_to_hass(self):
|
||||
"""Added to hass."""
|
||||
self.hass.helpers.dispatcher.async_dispatcher_connect(
|
||||
SIGNAL_WEBSOCKET_CONNECTED, self._update_count)
|
||||
SIGNAL_WEBSOCKET_CONNECTED, self._update_count
|
||||
)
|
||||
self.hass.helpers.dispatcher.async_dispatcher_connect(
|
||||
SIGNAL_WEBSOCKET_DISCONNECTED, self._update_count)
|
||||
SIGNAL_WEBSOCKET_DISCONNECTED, self._update_count
|
||||
)
|
||||
self._update_count()
|
||||
|
||||
@property
|
||||
|
||||
Reference in new issue
Block a user