Files
core/homeassistant/components/debug_console/websocket_api.py
T

280 lines
9.0 KiB
Python

"""Websocket API of the Debug console, running Python inside Home Assistant."""
import asyncio
from functools import wraps
from typing import Any
import probatio
from homeassistant.components import websocket_api
from homeassistant.components.websocket_api import (
ActiveConnection,
WebSocketCommandHandler,
)
from homeassistant.core import HomeAssistant, callback
from .completion import async_complete, signature_hint
from .execution import async_execute, is_incomplete
from .inspection import USER_CODE_ERRORS, format_error, get_attribute, inspect_children
from .safeguards import (
async_accept_warning,
async_log_execution,
async_log_inspection,
async_log_property_evaluation,
async_warning_required,
)
from .session import async_get_session, async_stop_executions
ERR_EXECUTION_STOPPED = "execution_stopped"
ERR_WARNING_NOT_ACCEPTED = "warning_not_accepted"
# Generated by the frontend, one per browser tab.
SESSION_ID = probatio.All(str, probatio.Length(min=1, max=64))
@callback
def async_register_websocket_commands(hass: HomeAssistant) -> None:
"""Register the websocket commands of the debug console."""
websocket_api.async_register_command(hass, handle_check_input)
websocket_api.async_register_command(hass, handle_clear)
websocket_api.async_register_command(hass, handle_complete)
websocket_api.async_register_command(hass, handle_execute)
websocket_api.async_register_command(hass, handle_get_attribute)
websocket_api.async_register_command(hass, handle_info)
websocket_api.async_register_command(hass, handle_inspect)
websocket_api.async_register_command(hass, handle_signature)
websocket_api.async_register_command(hass, handle_stop)
websocket_api.async_register_command(hass, handle_warning_accept)
def _require_accepted_warning(
func: WebSocketCommandHandler,
) -> WebSocketCommandHandler:
"""Refuse commands until the user accepted the warning, where required."""
@wraps(func)
def with_warning_check(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
if async_warning_required(hass, connection.user.id):
connection.send_error(
msg["id"],
ERR_WARNING_NOT_ACCEPTED,
"Accept the warning before using the debug console",
)
return
func(hass, connection, msg)
return with_warning_check
@websocket_api.websocket_command({probatio.Required("type"): "debug_console/info"})
@websocket_api.require_admin
@callback
def handle_info(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Return if the user has to accept the warning first."""
connection.send_result(
msg["id"],
{"warning_required": async_warning_required(hass, connection.user.id)},
)
@websocket_api.websocket_command(
{probatio.Required("type"): "debug_console/warning/accept"}
)
@websocket_api.require_admin
@websocket_api.async_response
async def handle_warning_accept(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Store that the user accepted the warning."""
await async_accept_warning(hass, connection.user.id)
connection.send_result(msg["id"])
@websocket_api.websocket_command(
{
probatio.Required("type"): "debug_console/execute",
probatio.Required("session_id"): SESSION_ID,
probatio.Required("code"): str,
}
)
@websocket_api.require_admin
@_require_accepted_warning
@websocket_api.async_response
async def handle_execute(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Execute Python code in the running Home Assistant instance."""
async_log_execution(connection, msg["code"])
session = async_get_session(hass, connection, msg["session_id"])
try:
result = await async_execute(hass, session, msg["code"])
except asyncio.CancelledError:
# Stopped by the user, or when Home Assistant stops.
connection.send_error(
msg["id"], ERR_EXECUTION_STOPPED, "The code was stopped before it finished"
)
raise
connection.send_result(msg["id"], result)
@websocket_api.websocket_command(
{
probatio.Required("type"): "debug_console/inspect",
probatio.Required("session_id"): SESSION_ID,
probatio.Required("object_id"): str,
}
)
@websocket_api.require_admin
@_require_accepted_warning
@callback
def handle_inspect(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Return the children of an object, such as items or attributes."""
session = async_get_session(hass, connection, msg["session_id"])
if (value := session.objects.get(msg["object_id"])) is None:
connection.send_error(
msg["id"], websocket_api.ERR_NOT_FOUND, "Object not found"
)
return
async_log_inspection(connection, value)
try:
result = inspect_children(session, value)
except USER_CODE_ERRORS as err:
connection.send_error(
msg["id"],
websocket_api.ERR_UNKNOWN_ERROR,
format_error(err),
)
return
connection.send_result(msg["id"], result)
@websocket_api.websocket_command(
{
probatio.Required("type"): "debug_console/get_attribute",
probatio.Required("session_id"): SESSION_ID,
probatio.Required("object_id"): str,
probatio.Required("attribute"): str,
}
)
@websocket_api.require_admin
@_require_accepted_warning
@callback
def handle_get_attribute(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Evaluate a property, which is deferred as it may have side effects."""
session = async_get_session(hass, connection, msg["session_id"])
if (value := session.objects.get(msg["object_id"])) is None:
connection.send_error(
msg["id"], websocket_api.ERR_NOT_FOUND, "Object not found"
)
return
async_log_property_evaluation(connection, value, msg["attribute"])
connection.send_result(msg["id"], get_attribute(session, value, msg["attribute"]))
@websocket_api.websocket_command(
{
probatio.Required("type"): "debug_console/complete",
probatio.Required("session_id"): SESSION_ID,
probatio.Required("code"): str,
}
)
@websocket_api.require_admin
@_require_accepted_warning
@websocket_api.async_response
async def handle_complete(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Return completions for the code being typed, up to the cursor."""
session = async_get_session(hass, connection, msg["session_id"])
connection.send_result(
msg["id"], await async_complete(hass, session.namespace, msg["code"])
)
@websocket_api.websocket_command(
{
probatio.Required("type"): "debug_console/signature",
probatio.Required("session_id"): SESSION_ID,
probatio.Required("code"): str,
}
)
@websocket_api.require_admin
@_require_accepted_warning
@callback
def handle_signature(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Return the signature of the call the cursor is in, if any."""
session = async_get_session(hass, connection, msg["session_id"])
connection.send_result(
msg["id"], {"signature": signature_hint(session.namespace, msg["code"])}
)
@websocket_api.websocket_command(
{
probatio.Required("type"): "debug_console/check_input",
probatio.Required("code"): str,
}
)
@websocket_api.require_admin
@_require_accepted_warning
@callback
def handle_check_input(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Return if code needs more input before it runs, like in the Python REPL.
Apart from running it, so the frontend can take code off the prompt before
it runs, which can take a while.
"""
connection.send_result(msg["id"], {"incomplete": is_incomplete(msg["code"])})
@websocket_api.websocket_command(
{
probatio.Required("type"): "debug_console/clear",
probatio.Required("session_id"): SESSION_ID,
}
)
@websocket_api.require_admin
@_require_accepted_warning
@callback
def handle_clear(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Release the objects kept alive for inspection, keeping the namespace."""
async_get_session(hass, connection, msg["session_id"]).release_objects()
connection.send_result(msg["id"])
@websocket_api.websocket_command(
{
probatio.Required("type"): "debug_console/stop",
probatio.Required("session_id"): SESSION_ID,
}
)
@websocket_api.require_admin
@_require_accepted_warning
@callback
def handle_stop(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Stop the code the session is running, which answers that it stopped."""
async_stop_executions(hass, connection, msg["session_id"])
connection.send_result(msg["id"])