Deprecate entity_id template variable in camera services (#128592)

* Deprecate entity_id template variable in camera services

* Update snapshots

* Tiny lang tweak

* Fix translation

---------

Co-authored-by: Franck Nijhof <git@frenck.dev>
This commit is contained in:
Erik Montnemery 2024-10-21 19:38:02 +02:00 committed by GitHub
parent e08e8641cb
commit 8e5abcf5c2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 237 additions and 14 deletions

View File

@ -49,7 +49,7 @@ from homeassistant.const import (
)
from homeassistant.core import Event, HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers import config_validation as cv, issue_registry as ir
from homeassistant.helpers.deprecation import (
DeprecatedConstantEnum,
all_with_deprecated_constants,
@ -957,6 +957,46 @@ async def websocket_update_prefs(
connection.send_result(msg["id"], entity_prefs)
class _TemplateCameraEntity:
"""Class to warn when the `entity_id` template variable is accessed.
Can be removed in HA Core 2025.6.
"""
def __init__(self, camera: Camera, service: str) -> None:
"""Initialize."""
self._camera = camera
self._entity_id = camera.entity_id
self._hass = camera.hass
self._service = service
def _report_issue(self) -> None:
"""Create a repair issue."""
ir.async_create_issue(
self._hass,
DOMAIN,
f"deprecated_filename_template_{self._entity_id}_{self._service}",
breaks_in_ha_version="2025.6.0",
is_fixable=True,
severity=ir.IssueSeverity.WARNING,
translation_key="deprecated_filename_template",
translation_placeholders={
"entity_id": self._entity_id,
"service": f"{DOMAIN}.{self._service}",
},
)
def __getattr__(self, name: str) -> Any:
"""Forward to the camera entity."""
self._report_issue()
return getattr(self._camera, name)
def __str__(self) -> str:
"""Forward to the camera entity."""
self._report_issue()
return str(self._camera)
async def async_handle_snapshot_service(
camera: Camera, service_call: ServiceCall
) -> None:
@ -964,7 +1004,9 @@ async def async_handle_snapshot_service(
hass = camera.hass
filename: Template = service_call.data[ATTR_FILENAME]
snapshot_file = filename.async_render(variables={ATTR_ENTITY_ID: camera})
snapshot_file = filename.async_render(
variables={ATTR_ENTITY_ID: _TemplateCameraEntity(camera, SERVICE_SNAPSHOT)}
)
# check if we allow to access to that file
if not hass.config.is_allowed_path(snapshot_file):
@ -1040,7 +1082,9 @@ async def async_handle_record_service(
raise HomeAssistantError(f"{camera.entity_id} does not support record service")
filename = service_call.data[CONF_FILENAME]
video_path = filename.async_render(variables={ATTR_ENTITY_ID: camera})
video_path = filename.async_render(
variables={ATTR_ENTITY_ID: _TemplateCameraEntity(camera, SERVICE_RECORD)}
)
await stream.async_record(
video_path,

View File

@ -35,6 +35,19 @@
}
}
},
"issues": {
"deprecated_filename_template": {
"title": "Detected use of deprecated template variable",
"fix_flow": {
"step": {
"confirm": {
"title": "[%key:component::camera::issues::deprecated_filename_template::title%]",
"description": "The pre-defined template variable `entity_id` was used when performing action `{service}` targeting camera entity `{entity_id}`. The pre-defined template variable `entity_id` is being removed from the `filename` parameter of `{service}`.\n\nPlease update your automations and scripts to use a manually defined variable instead and select **Submit** to close this issue."
}
}
}
}
},
"services": {
"turn_off": {
"name": "[%key:common::action::turn_off%]",
@ -58,7 +71,7 @@
"fields": {
"filename": {
"name": "Filename",
"description": "Template of a filename. Variable available is `entity_id`."
"description": "Full path to filename."
}
}
},
@ -82,7 +95,7 @@
"fields": {
"filename": {
"name": "[%key:component::camera::services::snapshot::fields::filename::name%]",
"description": "Template of a filename. Variable available is `entity_id`. Must be mp4."
"description": "Full path to filename. Must be mp4."
},
"duration": {
"name": "Duration",

View File

@ -0,0 +1,127 @@
# serializer version: 1
# name: test_record_service[/test/recording_{{ entity_id }}.mpg-/test/recording_<entity camera.demo_camera=streaming>.mpg-expected_issues1]
IssueRegistryItemSnapshot({
'active': True,
'breaks_in_ha_version': '2025.6.0',
'created': <ANY>,
'data': None,
'dismissed_version': None,
'domain': 'camera',
'is_fixable': True,
'is_persistent': False,
'issue_domain': None,
'issue_id': 'deprecated_filename_template_camera.demo_camera_record',
'learn_more_url': None,
'severity': <IssueSeverity.WARNING: 'warning'>,
'translation_key': 'deprecated_filename_template',
'translation_placeholders': dict({
'entity_id': 'camera.demo_camera',
'service': 'camera.record',
}),
})
# ---
# name: test_record_service[/test/recording_{{ entity_id.entity_id }}.mpg-/test/recording_camera.demo_camera.mpg-expected_issues3]
IssueRegistryItemSnapshot({
'active': True,
'breaks_in_ha_version': '2025.6.0',
'created': <ANY>,
'data': None,
'dismissed_version': None,
'domain': 'camera',
'is_fixable': True,
'is_persistent': False,
'issue_domain': None,
'issue_id': 'deprecated_filename_template_camera.demo_camera_record',
'learn_more_url': None,
'severity': <IssueSeverity.WARNING: 'warning'>,
'translation_key': 'deprecated_filename_template',
'translation_placeholders': dict({
'entity_id': 'camera.demo_camera',
'service': 'camera.record',
}),
})
# ---
# name: test_record_service[/test/recording_{{ entity_id.name }}.mpg-/test/recording_Demo camera.mpg-expected_issues2]
IssueRegistryItemSnapshot({
'active': True,
'breaks_in_ha_version': '2025.6.0',
'created': <ANY>,
'data': None,
'dismissed_version': None,
'domain': 'camera',
'is_fixable': True,
'is_persistent': False,
'issue_domain': None,
'issue_id': 'deprecated_filename_template_camera.demo_camera_record',
'learn_more_url': None,
'severity': <IssueSeverity.WARNING: 'warning'>,
'translation_key': 'deprecated_filename_template',
'translation_placeholders': dict({
'entity_id': 'camera.demo_camera',
'service': 'camera.record',
}),
})
# ---
# name: test_snapshot_service[/test/snapshot_{{ entity_id }}.jpg-/test/snapshot_<entity camera.demo_camera=streaming>.jpg-expected_issues1]
IssueRegistryItemSnapshot({
'active': True,
'breaks_in_ha_version': '2025.6.0',
'created': <ANY>,
'data': None,
'dismissed_version': None,
'domain': 'camera',
'is_fixable': True,
'is_persistent': False,
'issue_domain': None,
'issue_id': 'deprecated_filename_template_camera.demo_camera_snapshot',
'learn_more_url': None,
'severity': <IssueSeverity.WARNING: 'warning'>,
'translation_key': 'deprecated_filename_template',
'translation_placeholders': dict({
'entity_id': 'camera.demo_camera',
'service': 'camera.snapshot',
}),
})
# ---
# name: test_snapshot_service[/test/snapshot_{{ entity_id.entity_id }}.jpg-/test/snapshot_camera.demo_camera.jpg-expected_issues3]
IssueRegistryItemSnapshot({
'active': True,
'breaks_in_ha_version': '2025.6.0',
'created': <ANY>,
'data': None,
'dismissed_version': None,
'domain': 'camera',
'is_fixable': True,
'is_persistent': False,
'issue_domain': None,
'issue_id': 'deprecated_filename_template_camera.demo_camera_snapshot',
'learn_more_url': None,
'severity': <IssueSeverity.WARNING: 'warning'>,
'translation_key': 'deprecated_filename_template',
'translation_placeholders': dict({
'entity_id': 'camera.demo_camera',
'service': 'camera.snapshot',
}),
})
# ---
# name: test_snapshot_service[/test/snapshot_{{ entity_id.name }}.jpg-/test/snapshot_Demo camera.jpg-expected_issues2]
IssueRegistryItemSnapshot({
'active': True,
'breaks_in_ha_version': '2025.6.0',
'created': <ANY>,
'data': None,
'dismissed_version': None,
'domain': 'camera',
'is_fixable': True,
'is_persistent': False,
'issue_domain': None,
'issue_id': 'deprecated_filename_template_camera.demo_camera_snapshot',
'learn_more_url': None,
'severity': <IssueSeverity.WARNING: 'warning'>,
'translation_key': 'deprecated_filename_template',
'translation_placeholders': dict({
'entity_id': 'camera.demo_camera',
'service': 'camera.snapshot',
}),
})
# ---

View File

@ -7,6 +7,7 @@ from types import ModuleType
from unittest.mock import ANY, AsyncMock, Mock, PropertyMock, mock_open, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components import camera
from homeassistant.components.camera.const import (
@ -23,7 +24,7 @@ from homeassistant.const import (
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
@ -227,22 +228,36 @@ async def test_get_image_fails(hass: HomeAssistant) -> None:
@pytest.mark.usefixtures("mock_camera")
@pytest.mark.parametrize(
("filename_template", "expected_filename"),
("filename_template", "expected_filename", "expected_issues"),
[
("/test/snapshot.jpg", "/test/snapshot.jpg"),
(
"/test/snapshot.jpg",
"/test/snapshot.jpg",
[],
),
(
"/test/snapshot_{{ entity_id }}.jpg",
"/test/snapshot_<entity camera.demo_camera=streaming>.jpg",
["deprecated_filename_template_camera.demo_camera_snapshot"],
),
(
"/test/snapshot_{{ entity_id.name }}.jpg",
"/test/snapshot_Demo camera.jpg",
["deprecated_filename_template_camera.demo_camera_snapshot"],
),
("/test/snapshot_{{ entity_id.name }}.jpg", "/test/snapshot_Demo camera.jpg"),
(
"/test/snapshot_{{ entity_id.entity_id }}.jpg",
"/test/snapshot_camera.demo_camera.jpg",
["deprecated_filename_template_camera.demo_camera_snapshot"],
),
],
)
async def test_snapshot_service(
hass: HomeAssistant, filename_template: str, expected_filename: str
hass: HomeAssistant,
filename_template: str,
expected_filename: str,
expected_issues: list,
snapshot: SnapshotAssertion,
) -> None:
"""Test snapshot service."""
mopen = mock_open()
@ -271,6 +286,13 @@ async def test_snapshot_service(
assert len(mock_write.mock_calls) == 1
assert mock_write.mock_calls[0][1][0] == b"Test"
issue_registry = ir.async_get(hass)
assert len(issue_registry.issues) == 1 + len(expected_issues)
for expected_issue in expected_issues:
issue = issue_registry.async_get_issue(DOMAIN, expected_issue)
assert issue is not None
assert issue == snapshot
@pytest.mark.usefixtures("mock_camera")
async def test_snapshot_service_not_allowed_path(hass: HomeAssistant) -> None:
@ -602,22 +624,32 @@ async def test_record_service_invalid_path(hass: HomeAssistant) -> None:
@pytest.mark.usefixtures("mock_camera", "mock_stream")
@pytest.mark.parametrize(
("filename_template", "expected_filename"),
("filename_template", "expected_filename", "expected_issues"),
[
("/test/recording.mpg", "/test/recording.mpg"),
("/test/recording.mpg", "/test/recording.mpg", []),
(
"/test/recording_{{ entity_id }}.mpg",
"/test/recording_<entity camera.demo_camera=streaming>.mpg",
["deprecated_filename_template_camera.demo_camera_record"],
),
(
"/test/recording_{{ entity_id.name }}.mpg",
"/test/recording_Demo camera.mpg",
["deprecated_filename_template_camera.demo_camera_record"],
),
("/test/recording_{{ entity_id.name }}.mpg", "/test/recording_Demo camera.mpg"),
(
"/test/recording_{{ entity_id.entity_id }}.mpg",
"/test/recording_camera.demo_camera.mpg",
["deprecated_filename_template_camera.demo_camera_record"],
),
],
)
async def test_record_service(
hass: HomeAssistant, filename_template: str, expected_filename: str
hass: HomeAssistant,
filename_template: str,
expected_filename: str,
expected_issues: list,
snapshot: SnapshotAssertion,
) -> None:
"""Test record service."""
with (
@ -646,6 +678,13 @@ async def test_record_service(
ANY, expected_filename, duration=30, lookback=0
)
issue_registry = ir.async_get(hass)
assert len(issue_registry.issues) == 1 + len(expected_issues)
for expected_issue in expected_issues:
issue = issue_registry.async_get_issue(DOMAIN, expected_issue)
assert issue is not None
assert issue == snapshot
@pytest.mark.usefixtures("mock_camera")
async def test_camera_proxy_stream(hass_client: ClientSessionGenerator) -> None: