mirror of
https://github.com/Matysh/houseplan-card
synced 2026-07-31 08:28:31 +00:00
feat v1.11.0: full English translation + en/ru UI localization
- All card UI strings moved to src/i18n.ts (en/ru); language follows the HA profile automatically, new 'language: en|ru' card option forces it; GUI editor localized and got the language dropdown; generated device names localized via BuildCtx.loc. - English-only codebase: comments, docstrings, test names, backend error messages and logs. Russian remains only in the ru dictionary, ru.json, iconFor regexes matching Russian device names (+their fixtures) and README.ru.md. - Docs English-first: README (EN) + README.ru.md, ARCHITECTURE/DEVELOPMENT/ ROADMAP/CHANGELOG fully translated; translations/en.json had Russian - fixed. - Removed obsolete RELEASE_NOTES_v1.9.3.md and scripts_publish.sh.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
"""House Plan: серверная конфигурация плана дома + раздача Lovelace-карточки."""
|
||||
"""House Plan: server-side house plan configuration + serving the Lovelace card."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
@@ -27,7 +27,7 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config) -> bool:
|
||||
"""Регистрируем WS-команды, HTTP-загрузку и хранилища на старте."""
|
||||
"""Register WS commands, the HTTP upload and the stores on startup."""
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
hass.data[DOMAIN]["store"] = Store(hass, STORAGE_VERSION, STORAGE_KEY)
|
||||
hass.data[DOMAIN]["config_store"] = Store(hass, STORAGE_VERSION, STORAGE_CONFIG_KEY)
|
||||
@@ -39,7 +39,7 @@ async def async_setup(hass: HomeAssistant, config) -> bool:
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Config entry: статика фронтенда и планов + авто-подключение JS."""
|
||||
"""Config entry: static frontend and plan files + auto-registration of the JS."""
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
hass.data[DOMAIN]["entry"] = entry
|
||||
entry.async_on_unload(entry.add_update_listener(_update_listener))
|
||||
@@ -60,20 +60,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
static_paths.append(StaticPathConfig(PLANS_URL, str(plans_path), cache_headers=True))
|
||||
static_paths.append(StaticPathConfig(FILES_URL, str(files_path), cache_headers=True))
|
||||
await hass.http.async_register_static_paths(static_paths)
|
||||
except ImportError: # старые версии HA
|
||||
except ImportError: # older HA versions
|
||||
if card_path.exists():
|
||||
hass.http.register_static_path(FRONTEND_URL, str(card_path), cache_headers=False)
|
||||
hass.http.register_static_path(PLANS_URL, str(plans_path), cache_headers=True)
|
||||
hass.http.register_static_path(FILES_URL, str(files_path), cache_headers=True)
|
||||
|
||||
if not card_path.exists():
|
||||
_LOGGER.warning("houseplan-card.js не найден рядом с интеграцией: %s", card_path)
|
||||
_LOGGER.warning("houseplan-card.js not found next to the integration: %s", card_path)
|
||||
return True
|
||||
|
||||
# Подключаем карточку. Предпочтительно — как Lovelace-ресурс (его фронтенд ДОЖИДАЕТСЯ
|
||||
# перед рендером дашбордов, поэтому карточка доступна даже на холодном старте мобильного
|
||||
# приложения). Если реестр ресурсов недоступен (YAML-режим Lovelace, старые версии) —
|
||||
# откатываемся на extra_module_url.
|
||||
# Register the card. Preferably as a Lovelace resource (the frontend WAITS for those
|
||||
# before rendering dashboards, so the card is available even on a cold start of the mobile
|
||||
# app). If the resource registry is unavailable (Lovelace YAML mode, older versions) —
|
||||
# fall back to extra_module_url.
|
||||
module_url = f"{FRONTEND_URL}?v={VERSION}"
|
||||
if not await _register_lovelace_resource(hass, module_url):
|
||||
add_extra_js_url(hass, module_url)
|
||||
@@ -81,10 +81,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
|
||||
|
||||
async def _register_lovelace_resource(hass: HomeAssistant, module_url: str) -> bool:
|
||||
"""Зарегистрировать (или обновить) карточку в реестре Lovelace-ресурсов.
|
||||
"""Register (or update) the card in the Lovelace resource registry.
|
||||
|
||||
Возвращает True при успехе. Пишем идемпотентно: если ресурс с нашим путём уже есть —
|
||||
обновляем URL при смене версии; отсутствует — создаём. Any-except → False (фолбэк на JS).
|
||||
Returns True on success. Writes idempotently: if a resource with our path already exists —
|
||||
update the URL on a version change; if absent — create it. Any-except → False (fallback to JS).
|
||||
"""
|
||||
try:
|
||||
lovelace = hass.data.get("lovelace")
|
||||
@@ -93,13 +93,13 @@ async def _register_lovelace_resource(hass: HomeAssistant, module_url: str) -> b
|
||||
resources = lovelace.get("resources")
|
||||
if resources is None:
|
||||
return False
|
||||
# реестр ресурсов должен быть загружен
|
||||
# the resource registry must be loaded
|
||||
if hasattr(resources, "loaded") and not resources.loaded:
|
||||
await resources.async_load()
|
||||
resources.loaded = True
|
||||
elif hasattr(resources, "async_get_info"):
|
||||
await resources.async_get_info()
|
||||
# только storage-режим позволяет создавать элементы
|
||||
# only storage mode allows creating items
|
||||
if not hasattr(resources, "async_create_item"):
|
||||
return False
|
||||
base = FRONTEND_URL
|
||||
@@ -113,10 +113,10 @@ async def _register_lovelace_resource(hass: HomeAssistant, module_url: str) -> b
|
||||
await resources.async_update_item(item["id"], {"url": module_url})
|
||||
return True
|
||||
await resources.async_create_item({"res_type": "module", "url": module_url})
|
||||
_LOGGER.debug("House Plan card зарегистрирована как Lovelace-ресурс: %s", module_url)
|
||||
_LOGGER.debug("House Plan card registered as a Lovelace resource: %s", module_url)
|
||||
return True
|
||||
except Exception as err: # noqa: BLE001 — любой сбой → фолбэк
|
||||
_LOGGER.debug("Не удалось зарегистрировать Lovelace-ресурс (%s), фолбэк на extra_module_url", err)
|
||||
except Exception as err: # noqa: BLE001 — any failure → fallback
|
||||
_LOGGER.debug("Failed to register the Lovelace resource (%s), falling back to extra_module_url", err)
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Config flow: одна запись без параметров."""
|
||||
"""Config flow: a single entry with no parameters."""
|
||||
from __future__ import annotations
|
||||
|
||||
import voluptuous as vol
|
||||
@@ -9,7 +9,7 @@ from .const import CONF_ADMIN_ONLY, DOMAIN
|
||||
|
||||
|
||||
class HouseplanConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
"""Установка в один шаг."""
|
||||
"""One-step setup."""
|
||||
|
||||
VERSION = 1
|
||||
|
||||
@@ -29,7 +29,7 @@ class HouseplanConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
|
||||
|
||||
class HouseplanOptionsFlow(config_entries.OptionsFlow):
|
||||
"""Опция: правка раскладки только администраторами."""
|
||||
"""Option: layout editing by administrators only."""
|
||||
|
||||
async def async_step_init(self, user_input=None):
|
||||
if user_input is not None:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Константы интеграции House Plan."""
|
||||
"""Constants of the House Plan integration."""
|
||||
|
||||
DOMAIN = "houseplan"
|
||||
STORAGE_KEY = f"{DOMAIN}.layout"
|
||||
@@ -6,11 +6,11 @@ STORAGE_CONFIG_KEY = f"{DOMAIN}.config"
|
||||
STORAGE_VERSION = 1
|
||||
FRONTEND_URL = "/houseplan_files/houseplan-card.js"
|
||||
PLANS_URL = "/houseplan_files/plans"
|
||||
PLANS_DIR = "houseplan/plans" # относительно каталога конфигурации HA
|
||||
PLANS_DIR = "houseplan/plans" # relative to the HA configuration directory
|
||||
FILES_URL = "/houseplan_files/files"
|
||||
FILES_DIR = "houseplan/files"
|
||||
CONF_ADMIN_ONLY = "admin_only"
|
||||
VERSION = "1.10.0"
|
||||
VERSION = "1.11.0"
|
||||
|
||||
DEFAULT_CONFIG: dict = {
|
||||
"spaces": [],
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,7 +1,7 @@
|
||||
"""HTTP-эндпоинт загрузки файлов-инструкций House Plan.
|
||||
"""HTTP endpoint for uploading House Plan manual files.
|
||||
|
||||
Файлы (PDF и т.п.) грузятся не через WebSocket (у него лимит размера сообщения —
|
||||
большой PDF рвёт соединение), а обычным multipart POST — как медиа в самом HA.
|
||||
Files (PDF and the like) are uploaded not over WebSocket (its message size limit
|
||||
breaks the connection on a large PDF) but via a plain multipart POST — like media in HA itself.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,9 +12,9 @@ from aiohttp import web
|
||||
|
||||
from homeassistant.components.http import HomeAssistantView
|
||||
|
||||
try: # KEY_HASS — современный доступ к hass из aiohttp-приложения
|
||||
try: # KEY_HASS — the modern way to access hass from the aiohttp application
|
||||
from homeassistant.components.http import KEY_HASS
|
||||
except ImportError: # старые версии HA
|
||||
except ImportError: # older HA versions
|
||||
KEY_HASS = "hass" # type: ignore[assignment]
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
@@ -33,7 +33,7 @@ _CHUNK = 64 * 1024
|
||||
|
||||
|
||||
class HouseplanUploadView(HomeAssistantView):
|
||||
"""POST /api/houseplan/upload — сохранить файл маркера, вернуть URL."""
|
||||
"""POST /api/houseplan/upload — save a marker file, return its URL."""
|
||||
|
||||
url = "/api/houseplan/upload"
|
||||
name = "api:houseplan:upload"
|
||||
@@ -59,7 +59,7 @@ class HouseplanUploadView(HomeAssistantView):
|
||||
marker_id = sanitize_marker_id(await part.text())
|
||||
elif part.name == "file":
|
||||
filename = part.filename or "file"
|
||||
# читаем чанками с обрывом по лимиту, а не весь файл в память
|
||||
# read in chunks, aborting at the limit, instead of loading the whole file into memory
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
while chunk := await part.read_chunk(_CHUNK):
|
||||
@@ -72,7 +72,7 @@ class HouseplanUploadView(HomeAssistantView):
|
||||
break
|
||||
blob = b"".join(chunks)
|
||||
except Exception as err: # noqa: BLE001
|
||||
_LOGGER.warning("House Plan upload: ошибка чтения multipart: %s", err)
|
||||
_LOGGER.warning("House Plan upload: multipart read error: %s", err)
|
||||
return web.json_response({"error": "bad_request"}, status=400)
|
||||
|
||||
if too_large:
|
||||
|
||||
@@ -15,5 +15,5 @@
|
||||
"iot_class": "local_push",
|
||||
"issue_tracker": "https://github.com/Matysh/houseplan-card/issues",
|
||||
"requirements": [],
|
||||
"version": "1.10.0"
|
||||
"version": "1.11.0"
|
||||
}
|
||||
@@ -3,15 +3,15 @@
|
||||
"step": {
|
||||
"user": {
|
||||
"title": "House Plan",
|
||||
"data": { "admin_only": "Правка раскладки только администраторами" }
|
||||
"data": { "admin_only": "Only administrators may edit the layout" }
|
||||
}
|
||||
},
|
||||
"abort": { "single_instance_allowed": "Уже настроено — допускается одна запись." }
|
||||
"abort": { "single_instance_allowed": "Already configured — only one entry is allowed." }
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"data": { "admin_only": "Правка раскладки только администраторами" }
|
||||
"data": { "admin_only": "Only administrators may edit the layout" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Чистая валидация и санитайзеры House Plan — без зависимостей от Home Assistant.
|
||||
"""Pure House Plan validation and sanitizers — no Home Assistant dependencies.
|
||||
|
||||
Вынесено отдельно, чтобы покрывать юнит-тестами (нужен только voluptuous).
|
||||
Kept separate so it can be covered by unit tests (only voluptuous is needed).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -8,7 +8,7 @@ import re
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
# ---------- лимиты и наборы расширений ----------
|
||||
# ---------- limits and extension sets ----------
|
||||
PLAN_EXTENSIONS = {"svg": "image/svg+xml", "png": "image/png", "jpg": "image/jpeg", "webp": "image/webp"}
|
||||
MAX_PLAN_BYTES = 8 * 1024 * 1024
|
||||
FILE_EXTENSIONS = {"pdf", "png", "jpg", "jpeg", "webp", "txt"}
|
||||
@@ -17,27 +17,27 @@ MAX_FILE_BYTES = 25 * 1024 * 1024
|
||||
SPACE_ID_RE = re.compile(r"^[a-z0-9_-]{1,64}$")
|
||||
_SAFE_NAME_RE = re.compile(r"[^A-Za-z0-9._-]+")
|
||||
|
||||
# ---------- санитайзеры ----------
|
||||
# ---------- sanitizers ----------
|
||||
|
||||
|
||||
def sanitize_marker_id(value: str) -> str:
|
||||
"""Безопасный идентификатор маркера для имени папки.
|
||||
"""Safe marker identifier for a folder name.
|
||||
|
||||
Убирает разделители путей и ведущие точки, чтобы исключить обход каталогов
|
||||
(напр. '..', '../x'); пустой/из одних точек результат → 'misc'.
|
||||
Strips path separators and leading dots to rule out directory traversal
|
||||
(e.g. '..', '../x'); an empty/dots-only result → 'misc'.
|
||||
"""
|
||||
cleaned = _SAFE_NAME_RE.sub("_", value).lstrip(".")[:64]
|
||||
return cleaned or "misc"
|
||||
|
||||
|
||||
def sanitize_filename(value: str) -> str:
|
||||
"""Отбросить путь и ведущие точки, оставить безопасное имя файла."""
|
||||
"""Drop the path and leading dots, keep a safe file name."""
|
||||
raw = value.rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
|
||||
return _SAFE_NAME_RE.sub("_", raw).lstrip(".")[:120] or "file"
|
||||
|
||||
|
||||
def file_ext(filename: str) -> str:
|
||||
"""Расширение файла в нижнем регистре ('' если нет)."""
|
||||
"""Lowercase file extension ('' if none)."""
|
||||
raw = filename.rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
|
||||
return raw.rsplit(".", 1)[-1].lower() if "." in raw else ""
|
||||
|
||||
@@ -46,10 +46,10 @@ def valid_space_id(value: str) -> bool:
|
||||
return bool(SPACE_ID_RE.match(value))
|
||||
|
||||
|
||||
# ---------- voluptuous-схемы ----------
|
||||
# ---------- voluptuous schemas ----------
|
||||
POS_SCHEMA = vol.Schema(
|
||||
{vol.Required("x"): vol.Coerce(float), vol.Required("y"): vol.Coerce(float)},
|
||||
extra=vol.ALLOW_EXTRA, # v2-записи несут ключ "s" (space id)
|
||||
extra=vol.ALLOW_EXTRA, # v2 records carry the "s" key (space id)
|
||||
)
|
||||
LAYOUT_SCHEMA = vol.Schema({str: POS_SCHEMA})
|
||||
|
||||
@@ -59,7 +59,7 @@ POINT = vol.All([vol.Coerce(float)], vol.Length(min=2, max=2))
|
||||
def _require_geometry(room: dict) -> dict:
|
||||
if "poly" in room or all(k in room for k in ("x", "y", "w", "h")):
|
||||
return room
|
||||
raise vol.Invalid("room: нужен poly или x/y/w/h")
|
||||
raise vol.Invalid("room: poly or x/y/w/h is required")
|
||||
|
||||
|
||||
ROOM_SCHEMA = vol.All(
|
||||
@@ -115,5 +115,5 @@ CONFIG_SCHEMA = vol.Schema(
|
||||
vol.Optional("markers", default=list): [MARKER_SCHEMA],
|
||||
vol.Optional("settings", default=dict): vol.Schema({}, extra=vol.ALLOW_EXTRA),
|
||||
},
|
||||
extra=vol.ALLOW_EXTRA, # неизвестные ключи (легаси) не ломают загрузку
|
||||
extra=vol.ALLOW_EXTRA, # unknown (legacy) keys do not break loading
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""WS-команды House Plan: раскладка, конфигурация пространств, загрузка планов."""
|
||||
"""House Plan WS commands: layout, space configuration, plan uploads."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -24,7 +24,7 @@ from .validation import (
|
||||
|
||||
@callback
|
||||
def async_register(hass: HomeAssistant) -> None:
|
||||
"""Регистрация WS-команд."""
|
||||
"""Register the WS commands."""
|
||||
websocket_api.async_register_command(hass, ws_layout_get)
|
||||
websocket_api.async_register_command(hass, ws_layout_set)
|
||||
websocket_api.async_register_command(hass, ws_layout_update)
|
||||
@@ -43,10 +43,10 @@ def _config_store(hass: HomeAssistant):
|
||||
|
||||
|
||||
def _write_lock(hass: HomeAssistant) -> asyncio.Lock:
|
||||
"""Единый лок на цикл load→modify→save обоих хранилищ.
|
||||
"""A single lock over the load→modify→save cycle of both stores.
|
||||
|
||||
Без него параллельные WS-вызовы теряют изменения (last-writer-wins),
|
||||
а проверка expected_rev неатомарна.
|
||||
Without it, parallel WS calls lose changes (last-writer-wins),
|
||||
and the expected_rev check is not atomic.
|
||||
"""
|
||||
return hass.data[DOMAIN].setdefault("write_lock", asyncio.Lock())
|
||||
|
||||
@@ -57,13 +57,13 @@ def _check_write(hass: HomeAssistant, connection) -> bool:
|
||||
return connection.user.is_admin if admin_only else True
|
||||
|
||||
|
||||
# ---------------- раскладка ----------------
|
||||
# ---------------- layout ----------------
|
||||
|
||||
|
||||
@websocket_api.websocket_command({vol.Required("type"): "houseplan/layout/get"})
|
||||
@websocket_api.async_response
|
||||
async def ws_layout_get(hass: HomeAssistant, connection, msg: dict[str, Any]) -> None:
|
||||
"""Вернуть сохранённую раскладку."""
|
||||
"""Return the saved layout."""
|
||||
data = await _store(hass).async_load() or {}
|
||||
connection.send_result(msg["id"], {"layout": data.get("layout", {})})
|
||||
|
||||
@@ -73,9 +73,9 @@ async def ws_layout_get(hass: HomeAssistant, connection, msg: dict[str, Any]) ->
|
||||
)
|
||||
@websocket_api.async_response
|
||||
async def ws_layout_set(hass: HomeAssistant, connection, msg: dict[str, Any]) -> None:
|
||||
"""Полностью заменить раскладку."""
|
||||
"""Replace the layout entirely."""
|
||||
if not _check_write(hass, connection):
|
||||
connection.send_error(msg["id"], "unauthorized", "Правка раскладки разрешена только администраторам")
|
||||
connection.send_error(msg["id"], "unauthorized", "Only administrators may edit the layout")
|
||||
return
|
||||
async with _write_lock(hass):
|
||||
await _store(hass).async_save({"layout": msg["layout"]})
|
||||
@@ -91,9 +91,9 @@ async def ws_layout_set(hass: HomeAssistant, connection, msg: dict[str, Any]) ->
|
||||
)
|
||||
@websocket_api.async_response
|
||||
async def ws_layout_update(hass: HomeAssistant, connection, msg: dict[str, Any]) -> None:
|
||||
"""Обновить позицию одного устройства."""
|
||||
"""Update the position of a single device."""
|
||||
if not _check_write(hass, connection):
|
||||
connection.send_error(msg["id"], "unauthorized", "Правка раскладки разрешена только администраторам")
|
||||
connection.send_error(msg["id"], "unauthorized", "Only administrators may edit the layout")
|
||||
return
|
||||
store = _store(hass)
|
||||
async with _write_lock(hass):
|
||||
@@ -112,9 +112,9 @@ async def ws_layout_update(hass: HomeAssistant, connection, msg: dict[str, Any])
|
||||
)
|
||||
@websocket_api.async_response
|
||||
async def ws_layout_delete(hass: HomeAssistant, connection, msg: dict[str, Any]) -> None:
|
||||
"""Удалить позицию одного устройства (чистка при удалении маркера)."""
|
||||
"""Delete the position of a single device (cleanup when a marker is removed)."""
|
||||
if not _check_write(hass, connection):
|
||||
connection.send_error(msg["id"], "unauthorized", "Правка раскладки разрешена только администраторам")
|
||||
connection.send_error(msg["id"], "unauthorized", "Only administrators may edit the layout")
|
||||
return
|
||||
store = _store(hass)
|
||||
async with _write_lock(hass):
|
||||
@@ -126,13 +126,13 @@ async def ws_layout_delete(hass: HomeAssistant, connection, msg: dict[str, Any])
|
||||
connection.send_result(msg["id"], {"ok": True})
|
||||
|
||||
|
||||
# ---------------- конфигурация пространств ----------------
|
||||
# ---------------- space configuration ----------------
|
||||
|
||||
|
||||
@websocket_api.websocket_command({vol.Required("type"): "houseplan/config/get"})
|
||||
@websocket_api.async_response
|
||||
async def ws_config_get(hass: HomeAssistant, connection, msg: dict[str, Any]) -> None:
|
||||
"""Вернуть конфигурацию и её ревизию."""
|
||||
"""Return the configuration and its revision."""
|
||||
data = await _config_store(hass).async_load() or {}
|
||||
config = {**DEFAULT_CONFIG, **data.get("config", {})}
|
||||
connection.send_result(msg["id"], {"config": config, "rev": data.get("rev", 0)})
|
||||
@@ -147,14 +147,14 @@ async def ws_config_get(hass: HomeAssistant, connection, msg: dict[str, Any]) ->
|
||||
)
|
||||
@websocket_api.async_response
|
||||
async def ws_config_set(hass: HomeAssistant, connection, msg: dict[str, Any]) -> None:
|
||||
"""Заменить конфигурацию с оптимистичной блокировкой (expected_rev).
|
||||
"""Replace the configuration with optimistic locking (expected_rev).
|
||||
|
||||
Защита от гонки нескольких открытых клиентов: если конфиг менялся с момента
|
||||
последнего чтения клиентом — возвращается ошибка conflict, клиент обязан
|
||||
перечитать конфиг и повторить правку поверх свежей версии.
|
||||
Protects against races between several open clients: if the config has changed since
|
||||
the client's last read — a conflict error is returned, and the client must
|
||||
re-read the config and re-apply its edit on top of the fresh version.
|
||||
"""
|
||||
if not _check_write(hass, connection):
|
||||
connection.send_error(msg["id"], "unauthorized", "Правка конфигурации разрешена только администраторам")
|
||||
connection.send_error(msg["id"], "unauthorized", "Only administrators may edit the configuration")
|
||||
return
|
||||
store = _config_store(hass)
|
||||
async with _write_lock(hass):
|
||||
@@ -163,7 +163,7 @@ async def ws_config_set(hass: HomeAssistant, connection, msg: dict[str, Any]) ->
|
||||
if "expected_rev" in msg and msg["expected_rev"] != current_rev:
|
||||
connection.send_error(
|
||||
msg["id"], "conflict",
|
||||
f"Конфигурация изменена в другом окне (rev {current_rev} != {msg['expected_rev']})",
|
||||
f"Configuration was changed in another window (rev {current_rev} != {msg['expected_rev']})",
|
||||
)
|
||||
return
|
||||
new_rev = current_rev + 1
|
||||
@@ -172,7 +172,7 @@ async def ws_config_set(hass: HomeAssistant, connection, msg: dict[str, Any]) ->
|
||||
connection.send_result(msg["id"], {"ok": True, "rev": new_rev})
|
||||
|
||||
|
||||
# ---------------- загрузка планов ----------------
|
||||
# ---------------- plan uploads ----------------
|
||||
|
||||
|
||||
@websocket_api.websocket_command(
|
||||
@@ -185,21 +185,21 @@ async def ws_config_set(hass: HomeAssistant, connection, msg: dict[str, Any]) ->
|
||||
)
|
||||
@websocket_api.async_response
|
||||
async def ws_plan_set(hass: HomeAssistant, connection, msg: dict[str, Any]) -> None:
|
||||
"""Сохранить файл плана пространства; вернуть URL для карточки."""
|
||||
"""Save a space plan file; return the URL for the card."""
|
||||
if not _check_write(hass, connection):
|
||||
connection.send_error(msg["id"], "unauthorized", "Загрузка планов разрешена только администраторам")
|
||||
connection.send_error(msg["id"], "unauthorized", "Only administrators may upload plans")
|
||||
return
|
||||
space_id = msg["space_id"]
|
||||
if not valid_space_id(space_id):
|
||||
connection.send_error(msg["id"], "invalid_space_id", "space_id: только [a-z0-9_-], до 64 символов")
|
||||
connection.send_error(msg["id"], "invalid_space_id", "space_id: only [a-z0-9_-], up to 64 characters")
|
||||
return
|
||||
try:
|
||||
raw = base64.b64decode(msg["data"], validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
connection.send_error(msg["id"], "invalid_data", "data должен быть корректным base64")
|
||||
connection.send_error(msg["id"], "invalid_data", "data must be valid base64")
|
||||
return
|
||||
if len(raw) > MAX_PLAN_BYTES:
|
||||
connection.send_error(msg["id"], "too_large", f"План больше {MAX_PLAN_BYTES // 1024 // 1024} МБ")
|
||||
connection.send_error(msg["id"], "too_large", f"Plan is larger than {MAX_PLAN_BYTES // 1024 // 1024} MB")
|
||||
return
|
||||
|
||||
plans_dir = Path(hass.config.path(PLANS_DIR))
|
||||
@@ -207,7 +207,7 @@ async def ws_plan_set(hass: HomeAssistant, connection, msg: dict[str, Any]) -> N
|
||||
|
||||
def _write() -> int:
|
||||
plans_dir.mkdir(parents=True, exist_ok=True)
|
||||
# убрать старые варианты с другим расширением
|
||||
# remove old variants with a different extension
|
||||
for old_ext in PLAN_EXTENSIONS:
|
||||
old = plans_dir / f"{space_id}.{old_ext}"
|
||||
if old_ext != msg["ext"] and old.exists():
|
||||
|
||||
Reference in New Issue
Block a user