diff --git a/homeassistant/components/reolink/__init__.py b/homeassistant/components/reolink/__init__.py index 19450419abd2..d6b186d2f081 100644 --- a/homeassistant/components/reolink/__init__.py +++ b/homeassistant/components/reolink/__init__.py @@ -46,7 +46,12 @@ from .const import ( DOMAIN, ) from .coordinator import ReolinkDeviceCoordinator, ReolinkFirmwareCoordinator -from .exceptions import PasswordIncompatible, ReolinkException, UserNotAdmin +from .exceptions import ( + PasswordIncompatible, + ReolinkException, + ReolinkSetupException, + UserNotAdmin, +) from .host import ReolinkHost from .services import async_setup_services from .util import ReolinkConfigEntry, ReolinkData, get_device_uid_and_ch, get_store @@ -87,10 +92,27 @@ async def async_setup_entry( try: await host.async_init() - except (UserNotAdmin, CredentialsInvalidError, PasswordIncompatible) as err: + except (UserNotAdmin, PasswordIncompatible) as err: await host.stop() - # pylint: disable-next=home-assistant-exception-not-translated - raise ConfigEntryAuthFailed(err) from err + raise ConfigEntryAuthFailed( + translation_domain=DOMAIN, + translation_key=err.translation_key, + translation_placeholders=err.translation_placeholders, + ) from err + except ReolinkSetupException as err: + await host.stop() + raise ConfigEntryNotReady( + translation_domain=DOMAIN, + translation_key=err.translation_key, + translation_placeholders=err.translation_placeholders, + ) from err + except CredentialsInvalidError as err: + await host.stop() + raise ConfigEntryAuthFailed( + translation_domain=DOMAIN, + translation_key="authentication_failed", + translation_placeholders={"host": host.api.host}, + ) from err except LoginAccountDeviceError as err: await host.stop() raise ConfigEntryError( diff --git a/homeassistant/components/reolink/config_flow.py b/homeassistant/components/reolink/config_flow.py index d5856a544ede..017eaa3491f7 100644 --- a/homeassistant/components/reolink/config_flow.py +++ b/homeassistant/components/reolink/config_flow.py @@ -50,6 +50,7 @@ from .const import ( from .exceptions import ( PasswordIncompatible, ReolinkException, + ReolinkSetupException, ReolinkWebhookException, UserNotAdmin, ) @@ -305,6 +306,8 @@ class ReolinkFlowHandler(ConfigFlow, domain=DOMAIN): "https://www.home-assistant.io/more-info/no-url-available/#configuring-the-instance-url" ) errors["base"] = "webhook_exception" + except ReolinkSetupException: + errors[CONF_HOST] = "no_mac_address" except (ReolinkError, ReolinkException) as err: placeholders["error"] = str(err) errors[CONF_HOST] = "cannot_connect" diff --git a/homeassistant/components/reolink/coordinator.py b/homeassistant/components/reolink/coordinator.py index 3df46c2ff62f..da765f7d5a6e 100644 --- a/homeassistant/components/reolink/coordinator.py +++ b/homeassistant/components/reolink/coordinator.py @@ -6,9 +6,12 @@ import logging from typing import TYPE_CHECKING, override from reolink_aio.exceptions import ( + ApiError, CredentialsInvalidError, LoginPrivacyModeError, + ReolinkConnectionError, ReolinkError, + ReolinkTimeoutError, ) from homeassistant.config_entries import ConfigEntryState @@ -16,6 +19,7 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed +from .const import DOMAIN from .host import ReolinkHost if TYPE_CHECKING: @@ -28,6 +32,12 @@ NUM_CRED_ERRORS = 3 DEVICE_UPDATE_INTERVAL_MIN = timedelta(seconds=60) DEVICE_UPDATE_INTERVAL_PER_CAM = timedelta(seconds=10) +_UPDATE_ERROR_TRANSLATION_KEY: dict[type[ReolinkError], str] = { + ApiError: "update_api_error", + ReolinkConnectionError: "update_connection_error", + ReolinkTimeoutError: "update_timeout", +} + class ReolinkCoordinator(DataUpdateCoordinator[None]): """Coordinator for Reolink.""" @@ -93,16 +103,33 @@ class ReolinkDeviceCoordinator(ReolinkCoordinator): self._host.credential_errors += 1 if self._host.credential_errors >= NUM_CRED_ERRORS: await self._host.stop() - # pylint: disable-next=home-assistant-exception-not-translated - raise ConfigEntryAuthFailed(err) from err - # pylint: disable-next=home-assistant-exception-not-translated - raise UpdateFailed(str(err)) from err + raise ConfigEntryAuthFailed( + translation_domain=DOMAIN, + translation_key="authentication_failed", + translation_placeholders={"host": self._host.api.host}, + ) from err + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="authentication_failed", + translation_placeholders={"host": self._host.api.host}, + ) from err except LoginPrivacyModeError: pass # HTTP API is shutdown when privacy mode is active except ReolinkError as err: self._host.credential_errors = 0 - # pylint: disable-next=home-assistant-exception-not-translated - raise UpdateFailed(str(err)) from err + translation_key = next( + ( + key + for err_type, key in _UPDATE_ERROR_TRANSLATION_KEY.items() + if isinstance(err, err_type) + ), + "update_failed", + ) + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key=translation_key, + translation_placeholders={"host": self._host.api.host}, + ) from err self._host.credential_errors = 0 @@ -176,12 +203,10 @@ class ReolinkFirmwareCoordinator(ReolinkCoordinator): ) return - # pylint: disable-next=home-assistant-exception-not-translated raise UpdateFailed( - "Error checking Reolink firmware update" - f" from {self._host.api.nvr_name}, " - "if the camera is blocked from accessing the internet, " - "disable the update entity" + translation_domain=DOMAIN, + translation_key="firmware_check_failed", + translation_placeholders={"name": self._host.api.nvr_name}, ) from err finally: self._host.starting = False diff --git a/homeassistant/components/reolink/host.py b/homeassistant/components/reolink/host.py index 50ef7aa7b42d..42a4851a6d83 100644 --- a/homeassistant/components/reolink/host.py +++ b/homeassistant/components/reolink/host.py @@ -184,12 +184,10 @@ class ReolinkHost: translation_placeholders={"name": self._config_entry.title}, ) - # pylint: disable-next=home-assistant-exception-not-translated raise PasswordIncompatible( - "Reolink password contains incompatible special character or " - "is too long, please change the password to only contain characters: " - f"a-z, A-Z, 0-9 or {ALLOWED_SPECIAL_CHARS} " - "and not be longer than 31 characters" + translation_domain=DOMAIN, + translation_key="password_incompatible", + translation_placeholders={"special_chars": ALLOWED_SPECIAL_CHARS}, ) store: Store[str] | None = None @@ -206,14 +204,19 @@ class ReolinkHost: await self._api.get_host_data() if self._api.mac_address is None: - # pylint: disable-next=home-assistant-exception-not-translated - raise ReolinkSetupException("Could not get mac address") + raise ReolinkSetupException( + translation_domain=DOMAIN, + translation_key="no_mac_address", + ) if not self._api.is_admin: - # pylint: disable-next=home-assistant-exception-not-translated raise UserNotAdmin( - f"User '{self._api.username}' has authorization level " - f"'{self._api.user_level}', only admin users can change camera settings" + translation_domain=DOMAIN, + translation_key="user_not_admin", + translation_placeholders={ + "username": self._api.username, + "userlevel": self._api.user_level, + }, ) self.privacy_mode = self._api.baichuan.privacy_mode() diff --git a/homeassistant/components/reolink/media_source.py b/homeassistant/components/reolink/media_source.py index 6a47a035cfa6..6af6dbc20f39 100644 --- a/homeassistant/components/reolink/media_source.py +++ b/homeassistant/components/reolink/media_source.py @@ -64,8 +64,11 @@ class ReolinkVODMediaSource(MediaSource): if item.identifier is not None: identifier = item.identifier.split("|", 6) if identifier[0] != "FILE": - # pylint: disable-next=home-assistant-exception-not-translated - raise Unresolvable(f"Unknown media item '{item.identifier}'.") + raise Unresolvable( + translation_domain=DOMAIN, + translation_key="unknown_media_item", + translation_placeholders={"identifier": str(item.identifier)}, + ) _, config_entry_id, channel_str, stream_res, filename, start_time, end_time = ( identifier @@ -175,8 +178,11 @@ class ReolinkVODMediaSource(MediaSource): event, ) - # pylint: disable-next=home-assistant-exception-not-translated - raise Unresolvable(f"Unknown media item '{item.identifier}' during browsing.") + raise Unresolvable( + translation_domain=DOMAIN, + translation_key="unknown_media_item", + translation_placeholders={"identifier": str(item.identifier)}, + ) async def _async_generate_root(self) -> BrowseMediaSource: """Return all available reolink cameras as root browsing structure.""" diff --git a/homeassistant/components/reolink/strings.json b/homeassistant/components/reolink/strings.json index 7dab3410ffbb..00e2d68ebaad 100644 --- a/homeassistant/components/reolink/strings.json +++ b/homeassistant/components/reolink/strings.json @@ -9,6 +9,7 @@ "api_error": "API error occurred", "cannot_connect": "Failed to connect, check the IP address of the camera", "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", + "no_mac_address": "Could not get the MAC address of the device", "not_admin": "User needs to be admin, user \"{username}\" has authorization level \"{userlevel}\"", "password_incompatible": "Password contains incompatible special character or is too long, maximum 31 characters and only these characters are allowed: a-z, A-Z, 0-9 or {special_chars}. The streaming protocols necessitate these additional password restrictions.", "unknown": "[%key:common::config_flow::error::unknown%]", @@ -934,12 +935,21 @@ "api_error": { "message": "The device responded with an error: {err}" }, + "authentication_failed": { + "message": "Authentication failed for {host}" + }, + "config_entry_not_found": { + "message": "Could not find Reolink config entry ID \"{config_entry_id}\"" + }, "config_entry_not_ready": { "message": "Error while trying to set up {host}: {err}" }, "connection_error": { "message": "Could not connect to the device: {err}" }, + "firmware_check_failed": { + "message": "Error checking Reolink firmware update from {name}, if the camera is blocked from accessing the internet, disable the update entity" + }, "firmware_install_error": { "message": "Error trying to update Reolink firmware: {err}" }, @@ -964,9 +974,15 @@ "no_data": { "message": "Device returned no data: {err}" }, + "no_mac_address": { + "message": "Could not get the MAC address of the device" + }, "not_supported": { "message": "Function not supported by this device: {err}" }, + "password_incompatible": { + "message": "Reolink password contains an incompatible special character or is too long; please change the password to only contain characters a-z, A-Z, 0-9, or {special_chars} and not be longer than 31 characters" + }, "service_not_chime": { "message": "Reolink play_chime error: {device_name} is not a Chime" }, @@ -985,9 +1001,27 @@ "unexpected_data": { "message": "Device returned unexpected data: {err}" }, + "unknown_media_item": { + "message": "Unknown media item \"{identifier}\"" + }, "update_already_running": { "message": "Reolink firmware update already running, wait on completion before starting another" }, + "update_api_error": { + "message": "The device {host} responded with an error while updating its state" + }, + "update_connection_error": { + "message": "Could not connect to {host} while updating its state" + }, + "update_failed": { + "message": "Error updating the state of {host}" + }, + "update_timeout": { + "message": "Timeout while updating the state of {host}" + }, + "user_not_admin": { + "message": "User \"{username}\" has authorization level \"{userlevel}\", only admin users can change camera settings" + }, "webhook_no_url": { "message": "Error registering URL for webhook {event_id}: Home Assistant URL is not available" } diff --git a/homeassistant/components/reolink/util.py b/homeassistant/components/reolink/util.py index a71bbff148bc..f8338b409a8e 100644 --- a/homeassistant/components/reolink/util.py +++ b/homeassistant/components/reolink/util.py @@ -61,9 +61,10 @@ def get_host(hass: HomeAssistant, config_entry_id: str) -> ReolinkHost: config_entry_id ) if config_entry is None: - # pylint: disable-next=home-assistant-exception-not-translated raise Unresolvable( - f"Could not find Reolink config entry id '{config_entry_id}'." + translation_domain=DOMAIN, + translation_key="config_entry_not_found", + translation_placeholders={"config_entry_id": config_entry_id}, ) return config_entry.runtime_data.host diff --git a/tests/components/reolink/test_config_flow.py b/tests/components/reolink/test_config_flow.py index f9f01bfc9f68..ea7cc9a9c3fb 100644 --- a/tests/components/reolink/test_config_flow.py +++ b/tests/components/reolink/test_config_flow.py @@ -254,6 +254,23 @@ async def test_config_flow_errors(hass: HomeAssistant, reolink_host: MagicMock) assert result["step_id"] == "user" assert result["errors"] == {CONF_HOST: "cannot_connect"} + reolink_host.get_host_data.side_effect = None + reolink_host.mac_address = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + CONF_USERNAME: TEST_USERNAME, + CONF_PASSWORD: TEST_PASSWORD, + CONF_HOST: TEST_HOST, + }, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {CONF_HOST: "no_mac_address"} + assert result["description_placeholders"]["error"] == "" + + reolink_host.mac_address = TEST_MAC reolink_host.get_host_data.side_effect = ReolinkWebhookException("Test error") result = await hass.config_entries.flow.async_configure( result["flow_id"], diff --git a/tests/components/reolink/test_init.py b/tests/components/reolink/test_init.py index effb1af84a42..b6cd0e623230 100644 --- a/tests/components/reolink/test_init.py +++ b/tests/components/reolink/test_init.py @@ -9,10 +9,13 @@ from unittest.mock import AsyncMock, MagicMock, Mock, patch from freezegun.api import FrozenDateTimeFactory import pytest from reolink_aio.exceptions import ( + ApiError, CredentialsInvalidError, LoginAccountDeviceError, LoginPrivacyModeError, + ReolinkConnectionError, ReolinkError, + ReolinkTimeoutError, ) from homeassistant.components.reolink import FIRMWARE_UPDATE_INTERVAL @@ -27,7 +30,7 @@ from homeassistant.components.reolink.coordinator import ( DEVICE_UPDATE_INTERVAL_MIN, NUM_CRED_ERRORS, ) -from homeassistant.config_entries import ConfigEntryState +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, @@ -146,6 +149,101 @@ async def test_failures_parametrized( assert config_entry.state is expected +@pytest.mark.parametrize( + ("attr", "value", "translation_key"), + [ + pytest.param("is_admin", False, "user_not_admin", id="user_not_admin"), + pytest.param( + "valid_password", + MagicMock(return_value=False), + "password_incompatible", + id="password_incompatible", + ), + pytest.param( + "get_host_data", + AsyncMock(side_effect=CredentialsInvalidError("Test error")), + "authentication_failed", + id="credentials_invalid", + ), + ], +) +async def test_setup_auth_failed_reason( + hass: HomeAssistant, + reolink_host: MagicMock, + config_entry: MockConfigEntry, + attr: str, + value: Any, + translation_key: str, +) -> None: + """Test the setup error keeps the reason of the authentication failure.""" + setattr(reolink_host, attr, value) + assert not await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + assert config_entry.state is ConfigEntryState.SETUP_ERROR + assert config_entry.error_reason_translation_key == translation_key + assert any(config_entry.async_get_active_flows(hass, {SOURCE_REAUTH})) + + +async def test_setup_no_mac_address( + hass: HomeAssistant, + reolink_host: MagicMock, + config_entry: MockConfigEntry, +) -> None: + """Test the setup retry keeps the reason when the MAC address is missing.""" + reolink_host.mac_address = None + assert not await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + assert config_entry.state is ConfigEntryState.SETUP_RETRY + assert config_entry.error_reason_translation_key == "no_mac_address" + + +@pytest.mark.parametrize( + ("side_effect", "translation_key"), + [ + pytest.param(ApiError("Test error"), "update_api_error", id="api_error"), + pytest.param( + ReolinkConnectionError("Test error"), + "update_connection_error", + id="connection_error", + ), + pytest.param(ReolinkTimeoutError("Test error"), "update_timeout", id="timeout"), + pytest.param(ReolinkError("Test error"), "update_failed", id="other"), + pytest.param( + CredentialsInvalidError("Test error"), + "authentication_failed", + id="credentials_invalid", + ), + ], +) +async def test_update_failed_translation_key( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + reolink_host: MagicMock, + config_entry: MockConfigEntry, + side_effect: ReolinkError, + translation_key: str, +) -> None: + """Test the device update failure uses a key per error type.""" + with patch("homeassistant.components.reolink.PLATFORMS", [Platform.SWITCH]): + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + assert config_entry.state is ConfigEntryState.LOADED + + reolink_host.get_states.side_effect = side_effect + freezer.tick(DEVICE_UPDATE_INTERVAL_MIN) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + coordinator = config_entry.runtime_data.device_coordinator + assert not coordinator.last_update_success + assert coordinator.last_exception.translation_key == translation_key + assert coordinator.last_exception.translation_placeholders == { + "host": reolink_host.host + } + + async def test_firmware_error_twice( hass: HomeAssistant, freezer: FrozenDateTimeFactory,