Skip to content

Commit

Permalink
Ensure Reolink can start when privacy mode is enabled (home-assistant…
Browse files Browse the repository at this point in the history
…#136514)

* Allow startup when privacy mode is enabled

* Add tests

* remove duplicate privacy_mode

* fix tests

* Apply suggestions from code review

Co-authored-by: Robert Resch <[email protected]>

* Store in subfolder and cleanup when removed

* Add tests and fixes

* fix styling

* rename CONF_PRIVACY to CONF_SUPPORTS_PRIVACY_MODE

* use helper store

---------

Co-authored-by: Robert Resch <[email protected]>
  • Loading branch information
starkillerOG and edenhaus authored Jan 31, 2025
1 parent df59b1d commit 92dd18a
Show file tree
Hide file tree
Showing 8 changed files with 102 additions and 18 deletions.
34 changes: 24 additions & 10 deletions homeassistant/components/reolink/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import CONF_USE_HTTPS, DOMAIN
from .const import CONF_SUPPORTS_PRIVACY_MODE, CONF_USE_HTTPS, DOMAIN
from .exceptions import PasswordIncompatible, ReolinkException, UserNotAdmin
from .host import ReolinkHost
from .services import async_setup_services
from .util import ReolinkConfigEntry, ReolinkData, get_device_uid_and_ch
from .util import ReolinkConfigEntry, ReolinkData, get_device_uid_and_ch, get_store
from .views import PlaybackProxyView

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -67,7 +67,9 @@ async def async_setup_entry(
hass: HomeAssistant, config_entry: ReolinkConfigEntry
) -> bool:
"""Set up Reolink from a config entry."""
host = ReolinkHost(hass, config_entry.data, config_entry.options)
host = ReolinkHost(
hass, config_entry.data, config_entry.options, config_entry.entry_id
)

try:
await host.async_init()
Expand All @@ -92,21 +94,25 @@ async def async_setup_entry(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, host.stop)
)

# update the port info if needed for the next time
# update the config info if needed for the next time
if (
host.api.port != config_entry.data[CONF_PORT]
or host.api.use_https != config_entry.data[CONF_USE_HTTPS]
or host.api.supported(None, "privacy_mode")
!= config_entry.data.get(CONF_SUPPORTS_PRIVACY_MODE)
):
_LOGGER.warning(
"HTTP(s) port of Reolink %s, changed from %s to %s",
host.api.nvr_name,
config_entry.data[CONF_PORT],
host.api.port,
)
if host.api.port != config_entry.data[CONF_PORT]:
_LOGGER.warning(
"HTTP(s) port of Reolink %s, changed from %s to %s",
host.api.nvr_name,
config_entry.data[CONF_PORT],
host.api.port,
)
data = {
**config_entry.data,
CONF_PORT: host.api.port,
CONF_USE_HTTPS: host.api.use_https,
CONF_SUPPORTS_PRIVACY_MODE: host.api.supported(None, "privacy_mode"),
}
hass.config_entries.async_update_entry(config_entry, data=data)

Expand Down Expand Up @@ -248,6 +254,14 @@ async def async_unload_entry(
return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS)


async def async_remove_entry(
hass: HomeAssistant, config_entry: ReolinkConfigEntry
) -> None:
"""Handle removal of an entry."""
store = get_store(hass, config_entry.entry_id)
await store.async_remove()


async def async_remove_config_entry_device(
hass: HomeAssistant, config_entry: ReolinkConfigEntry, device: dr.DeviceEntry
) -> bool:
Expand Down
5 changes: 4 additions & 1 deletion homeassistant/components/reolink/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
from homeassistant.helpers.device_registry import format_mac
from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo

from .const import CONF_USE_HTTPS, DOMAIN
from .const import CONF_SUPPORTS_PRIVACY_MODE, CONF_USE_HTTPS, DOMAIN
from .exceptions import (
PasswordIncompatible,
ReolinkException,
Expand Down Expand Up @@ -287,6 +287,9 @@ async def async_step_user(
if not errors:
user_input[CONF_PORT] = host.api.port
user_input[CONF_USE_HTTPS] = host.api.use_https
user_input[CONF_SUPPORTS_PRIVACY_MODE] = host.api.supported(
None, "privacy_mode"
)

mac_address = format_mac(host.api.mac_address)
await self.async_set_unique_id(mac_address, raise_on_progress=False)
Expand Down
1 change: 1 addition & 0 deletions homeassistant/components/reolink/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
DOMAIN = "reolink"

CONF_USE_HTTPS = "use_https"
CONF_SUPPORTS_PRIVACY_MODE = "privacy_mode_supported"
30 changes: 27 additions & 3 deletions homeassistant/components/reolink/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,17 @@
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_call_later
from homeassistant.helpers.network import NoURLAvailableError, get_url
from homeassistant.helpers.storage import Store
from homeassistant.util.ssl import SSLCipherList

from .const import CONF_USE_HTTPS, DOMAIN
from .const import CONF_SUPPORTS_PRIVACY_MODE, CONF_USE_HTTPS, DOMAIN
from .exceptions import (
PasswordIncompatible,
ReolinkSetupException,
ReolinkWebhookException,
UserNotAdmin,
)
from .util import get_store

DEFAULT_TIMEOUT = 30
FIRST_TCP_PUSH_TIMEOUT = 10
Expand All @@ -64,9 +66,12 @@ def __init__(
hass: HomeAssistant,
config: Mapping[str, Any],
options: Mapping[str, Any],
config_entry_id: str | None = None,
) -> None:
"""Initialize Reolink Host. Could be either NVR, or Camera."""
self._hass: HomeAssistant = hass
self._config_entry_id = config_entry_id
self._config = config
self._unique_id: str = ""

def get_aiohttp_session() -> aiohttp.ClientSession:
Expand Down Expand Up @@ -150,6 +155,14 @@ async def async_init(self) -> None:
f"a-z, A-Z, 0-9 or {ALLOWED_SPECIAL_CHARS}"
)

store: Store[str] | None = None
if self._config_entry_id is not None:
store = get_store(self._hass, self._config_entry_id)
if self._config.get(CONF_SUPPORTS_PRIVACY_MODE):
data = await store.async_load()
if data:
self._api.set_raw_host_data(data)

await self._api.get_host_data()

if self._api.mac_address is None:
Expand All @@ -161,6 +174,19 @@ async def async_init(self) -> None:
f"'{self._api.user_level}', only admin users can change camera settings"
)

self.privacy_mode = self._api.baichuan.privacy_mode()

if (
store
and self._api.supported(None, "privacy_mode")
and not self.privacy_mode
):
_LOGGER.debug(
"Saving raw host data for next reload in case privacy mode is enabled"
)
data = self._api.get_raw_host_data()
await store.async_save(data)

onvif_supported = self._api.supported(None, "ONVIF")
self._onvif_push_supported = onvif_supported
self._onvif_long_poll_supported = onvif_supported
Expand Down Expand Up @@ -235,8 +261,6 @@ async def async_init(self) -> None:
self._hass, FIRST_TCP_PUSH_TIMEOUT, self._async_check_tcp_push
)

self.privacy_mode = self._api.baichuan.privacy_mode()

ch_list: list[int | None] = [None]
if self._api.is_nvr:
ch_list.extend(self._api.channels)
Expand Down
14 changes: 12 additions & 2 deletions homeassistant/components/reolink/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from collections.abc import Awaitable, Callable, Coroutine
from dataclasses import dataclass
from typing import Any
from typing import TYPE_CHECKING, Any

from reolink_aio.exceptions import (
ApiError,
Expand All @@ -26,10 +26,15 @@
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.storage import Store
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import DOMAIN
from .host import ReolinkHost

if TYPE_CHECKING:
from .host import ReolinkHost

STORAGE_VERSION = 1

type ReolinkConfigEntry = config_entries.ConfigEntry[ReolinkData]

Expand Down Expand Up @@ -64,6 +69,11 @@ def get_host(hass: HomeAssistant, config_entry_id: str) -> ReolinkHost:
return config_entry.runtime_data.host


def get_store(hass: HomeAssistant, config_entry_id: str) -> Store[str]:
"""Return the reolink store."""
return Store[str](hass, STORAGE_VERSION, f"{DOMAIN}.{config_entry_id}.json")


def get_device_uid_and_ch(
device: dr.DeviceEntry, host: ReolinkHost
) -> tuple[list[str], int | None, bool]:
Expand Down
13 changes: 12 additions & 1 deletion tests/components/reolink/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@
from reolink_aio.exceptions import ReolinkError

from homeassistant.components.reolink.config_flow import DEFAULT_PROTOCOL
from homeassistant.components.reolink.const import CONF_USE_HTTPS, DOMAIN
from homeassistant.components.reolink.const import (
CONF_SUPPORTS_PRIVACY_MODE,
CONF_USE_HTTPS,
DOMAIN,
)
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
Expand Down Expand Up @@ -43,6 +47,7 @@
TEST_ITEM_NUMBER = "P000"
TEST_CAM_MODEL = "RLC-123"
TEST_DUO_MODEL = "Reolink Duo PoE"
TEST_PRIVACY = True


@pytest.fixture
Expand All @@ -65,6 +70,7 @@ def reolink_connect_class() -> Generator[MagicMock]:
host_mock = host_mock_class.return_value
host_mock.get_host_data.return_value = None
host_mock.get_states.return_value = None
host_mock.supported.return_value = True
host_mock.check_new_firmware.return_value = False
host_mock.unsubscribe.return_value = True
host_mock.logout.return_value = True
Expand Down Expand Up @@ -113,6 +119,9 @@ def reolink_connect_class() -> Generator[MagicMock]:
host_mock.capabilities = {"Host": ["RTSP"], "0": ["motion_detection"]}
host_mock.checked_api_versions = {"GetEvents": 1}
host_mock.abilities = {"abilityChn": [{"aiTrack": {"permit": 0, "ver": 0}}]}
host_mock.get_raw_host_data.return_value = (
"{'host':'TEST_RESPONSE','channel':'TEST_RESPONSE'}"
)

# enums
host_mock.whiteled_mode.return_value = 1
Expand All @@ -128,6 +137,7 @@ def reolink_connect_class() -> Generator[MagicMock]:
host_mock.baichuan.events_active = False
host_mock.baichuan.privacy_mode.return_value = False
host_mock.baichuan.subscribe_events.side_effect = ReolinkError("Test error")

yield host_mock_class


Expand Down Expand Up @@ -158,6 +168,7 @@ def config_entry(hass: HomeAssistant) -> MockConfigEntry:
CONF_PASSWORD: TEST_PASSWORD,
CONF_PORT: TEST_PORT,
CONF_USE_HTTPS: TEST_USE_HTTPS,
CONF_SUPPORTS_PRIVACY_MODE: TEST_PRIVACY,
},
options={
CONF_PROTOCOL: DEFAULT_PROTOCOL,
Expand Down
11 changes: 10 additions & 1 deletion tests/components/reolink/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
from homeassistant import config_entries
from homeassistant.components.reolink import DEVICE_UPDATE_INTERVAL
from homeassistant.components.reolink.config_flow import DEFAULT_PROTOCOL
from homeassistant.components.reolink.const import CONF_USE_HTTPS, DOMAIN
from homeassistant.components.reolink.const import (
CONF_SUPPORTS_PRIVACY_MODE,
CONF_USE_HTTPS,
DOMAIN,
)
from homeassistant.components.reolink.exceptions import ReolinkWebhookException
from homeassistant.components.reolink.host import DEFAULT_TIMEOUT
from homeassistant.config_entries import ConfigEntryState
Expand All @@ -43,6 +47,7 @@
TEST_PASSWORD,
TEST_PASSWORD2,
TEST_PORT,
TEST_PRIVACY,
TEST_USE_HTTPS,
TEST_USERNAME,
TEST_USERNAME2,
Expand Down Expand Up @@ -82,6 +87,7 @@ async def test_config_flow_manual_success(
CONF_PASSWORD: TEST_PASSWORD,
CONF_PORT: TEST_PORT,
CONF_USE_HTTPS: TEST_USE_HTTPS,
CONF_SUPPORTS_PRIVACY_MODE: TEST_PRIVACY,
}
assert result["options"] == {
CONF_PROTOCOL: DEFAULT_PROTOCOL,
Expand Down Expand Up @@ -133,6 +139,7 @@ async def test_config_flow_privacy_success(
CONF_PASSWORD: TEST_PASSWORD,
CONF_PORT: TEST_PORT,
CONF_USE_HTTPS: TEST_USE_HTTPS,
CONF_SUPPORTS_PRIVACY_MODE: TEST_PRIVACY,
}
assert result["options"] == {
CONF_PROTOCOL: DEFAULT_PROTOCOL,
Expand Down Expand Up @@ -294,6 +301,7 @@ async def test_config_flow_errors(
CONF_PASSWORD: TEST_PASSWORD,
CONF_PORT: TEST_PORT,
CONF_USE_HTTPS: TEST_USE_HTTPS,
CONF_SUPPORTS_PRIVACY_MODE: TEST_PRIVACY,
}
assert result["options"] == {
CONF_PROTOCOL: DEFAULT_PROTOCOL,
Expand Down Expand Up @@ -465,6 +473,7 @@ async def test_dhcp_flow(hass: HomeAssistant, mock_setup_entry: MagicMock) -> No
CONF_PASSWORD: TEST_PASSWORD,
CONF_PORT: TEST_PORT,
CONF_USE_HTTPS: TEST_USE_HTTPS,
CONF_SUPPORTS_PRIVACY_MODE: TEST_PRIVACY,
}
assert result["options"] == {
CONF_PROTOCOL: DEFAULT_PROTOCOL,
Expand Down
12 changes: 12 additions & 0 deletions tests/components/reolink/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -859,3 +859,15 @@ def register_callback(

assert reolink_connect.get_states.call_count >= 1
assert hass.states.get(entity_id).state == STATE_ON


async def test_remove(
hass: HomeAssistant,
reolink_connect: MagicMock,
config_entry: MockConfigEntry,
) -> None:
"""Test removing of the reolink integration."""
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()

assert await hass.config_entries.async_remove(config_entry.entry_id)

0 comments on commit 92dd18a

Please sign in to comment.