1 """API for persistent storage for the frontend."""
3 from __future__
import annotations
5 from collections.abc
import Callable, Coroutine
6 from functools
import wraps
9 import voluptuous
as vol
16 DATA_STORAGE =
"frontend_storage"
17 STORAGE_VERSION_USER_DATA = 1
22 """Set up frontend storage."""
23 if DATA_STORAGE
in hass.data:
25 hass.data[DATA_STORAGE] = ({}, {})
29 """Set up frontend storage."""
31 websocket_api.async_register_command(hass, websocket_set_user_data)
32 websocket_api.async_register_command(hass, websocket_get_user_data)
36 hass: HomeAssistant, user_id: str
37 ) -> tuple[Store, dict[str, Any]]:
38 """Access a user store."""
40 stores, data = hass.data[DATA_STORAGE]
41 if (store := stores.get(user_id))
is None:
42 store = stores[user_id] =
Store(
44 STORAGE_VERSION_USER_DATA,
45 f
"frontend.user_data_{user_id}",
48 if user_id
not in data:
49 data[user_id] = await store.async_load()
or {}
51 return store, data[user_id]
56 [HomeAssistant, ActiveConnection, dict[str, Any], Store, dict[str, Any]],
57 Coroutine[Any, Any,
None],
60 [HomeAssistant, ActiveConnection, dict[str, Any]], Coroutine[Any, Any,
None]
62 """Decorate function to provide data."""
65 async
def with_store_func(
66 hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
68 """Provide user specific data and store to function."""
69 user_id = connection.user.id
73 await orig_func(hass, connection, msg, store, user_data)
75 return with_store_func
78 @websocket_api.websocket_command(
{
vol.Required("type"):
"frontend/set_user_data",
79 vol.Required(
"key"): str,
80 vol.Required(
"value"): vol.Any(bool, str, int, float, dict, list,
None),
83 @websocket_api.async_response
87 connection: ActiveConnection,
92 """Handle set global data command.
96 data[msg[
"key"]] = msg[
"value"]
97 await store.async_save(data)
98 connection.send_message(websocket_api.result_message(msg[
"id"]))
101 @websocket_api.websocket_command(
{vol.Required("type"):
"frontend/get_user_data", vol.Optional(
"key"): str}
103 @websocket_api.async_response
107 connection: ActiveConnection,
110 data: dict[str, Any],
112 """Handle get global data command.
116 connection.send_message(
117 websocket_api.result_message(
118 msg[
"id"], {
"value": data.get(msg[
"key"])
if "key" in msg
else data}
121
None websocket_set_user_data(HomeAssistant hass, ActiveConnection connection, dict[str, Any] msg, Store store, dict[str, Any] data)
None websocket_get_user_data(HomeAssistant hass, ActiveConnection connection, dict[str, Any] msg, Store store, dict[str, Any] data)
tuple[Store, dict[str, Any]] async_user_store(HomeAssistant hass, str user_id)
None async_setup_frontend_storage(HomeAssistant hass)
None _initialize_frontend_storage(HomeAssistant hass)
Callable[[HomeAssistant, ActiveConnection, dict[str, Any]], Coroutine[Any, Any, None]] with_store(Callable[[HomeAssistant, ActiveConnection, dict[str, Any], Store, dict[str, Any]], Coroutine[Any, Any, None],] orig_func)