Add thumbnails to Reolink recordings in the media browser (#190104)

Co-authored-by: starkillerOG <starkiller.og@gmail.com>
This commit is contained in:
Michał Jonik
2026-11-16 10:49:54 +01:00
committed by GitHub
co-authored by starkillerOG
parent d501515b3e
commit 7eae24dbad
6 changed files with 429 additions and 4 deletions
+2 -1
View File
@@ -55,7 +55,7 @@ from .exceptions import (
from .host import ReolinkHost
from .services import async_setup_services
from .util import ReolinkConfigEntry, ReolinkData, get_device_uid_and_ch, get_store
from .views import PlaybackProxyView
from .views import PlaybackProxyView, ThumbnailView
_LOGGER = logging.getLogger(__name__)
@@ -264,6 +264,7 @@ async def async_setup_entry(
migrate_entity_ids(hass, config_entry.entry_id, host)
hass.http.register_view(PlaybackProxyView(hass))
hass.http.register_view(ThumbnailView(hass))
await register_callbacks(host, device_coordinator, hass)
@@ -22,11 +22,12 @@ from homeassistant.helpers import device_registry as dr, entity_registry as er
from .const import DOMAIN
from .util import get_host
from .views import async_generate_playback_proxy_url
from .views import async_generate_playback_proxy_url, async_generate_thumbnail_url
_LOGGER = logging.getLogger(__name__)
VOD_SPLIT_TIME = dt.timedelta(minutes=5)
THUMBNAIL_OFFSET = dt.timedelta(seconds=5)
async def async_get_media_source(hass: HomeAssistant) -> ReolinkVODMediaSource:
@@ -408,12 +409,20 @@ class ReolinkVODMediaSource(MediaSource):
for trigger in triggers
)
# A battery camera starts recording at the event, without pre-recording.
thumbnail_offset = (
dt.timedelta()
if host.api.supported(channel, "battery")
else THUMBNAIL_OFFSET
)
for file in vod_files:
file_name = f"{file.start_time.time()} {file.duration}"
if file.triggers != file.triggers.NONE:
file_name += " " + " ".join(
str(trigger.name).title() for trigger in file.triggers
)
thumbnail_time = file.start_time + min(thumbnail_offset, file.duration / 2)
children.append(
BrowseMediaSource(
@@ -424,6 +433,12 @@ class ReolinkVODMediaSource(MediaSource):
title=file_name,
can_play=True,
can_expand=False,
thumbnail=async_generate_thumbnail_url(
config_entry_id,
channel,
stream,
thumbnail_time.strftime("%Y%m%d%H%M%S"),
),
)
)
+5 -1
View File
@@ -60,7 +60,11 @@ def get_host(hass: HomeAssistant, config_entry_id: str) -> ReolinkHost:
config_entry: ReolinkConfigEntry | None = hass.config_entries.async_get_entry(
config_entry_id
)
if config_entry is None or config_entry.domain != DOMAIN:
if (
config_entry is None
or config_entry.domain != DOMAIN
or config_entry.state is not config_entries.ConfigEntryState.LOADED
):
raise Unresolvable(
translation_domain=DOMAIN,
translation_key="config_entry_not_found",
+101
View File
@@ -2,6 +2,7 @@
import asyncio
from base64 import urlsafe_b64decode, urlsafe_b64encode
from collections import defaultdict
from contextlib import aclosing
from datetime import datetime
from http import HTTPStatus
@@ -24,6 +25,11 @@ from .util import get_host
_LOGGER = logging.getLogger(__name__)
# Each thumbnail costs a Baichuan request and an ffmpeg decode.
MAX_PARALLEL_THUMBNAILS = 2
THUMBNAIL_STREAMS = {"sub", "telephoto_sub"}
TELEPHOTO_PREFIXES = ("autotrack_", "telephoto_")
@callback
def async_generate_playback_proxy_url(
@@ -41,6 +47,19 @@ def async_generate_playback_proxy_url(
)
@callback
def async_generate_thumbnail_url(
config_entry_id: str, channel: int, stream: str, time_id: str
) -> str:
"""Generate URL for the thumbnail of a recording."""
return ThumbnailView.url.format(
config_entry_id=config_entry_id,
channel=channel,
stream="telephoto_sub" if stream.startswith(TELEPHOTO_PREFIXES) else "sub",
time_id=time_id,
)
class PlaybackProxyView(HomeAssistantView):
"""View to proxy playback video from Reolink."""
@@ -283,3 +302,85 @@ class PlaybackProxyView(HomeAssistantView):
finally:
if self._mp4_streams.get(host.unique_id) is task:
del self._mp4_streams[host.unique_id]
class ThumbnailView(HomeAssistantView):
"""View to get a thumbnail of a Reolink recording."""
requires_auth = True
url = "/api/reolink/thumbnail/{config_entry_id}/{channel}/{stream}/{time_id}"
name = "api:reolink_thumbnail"
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize a thumbnail view."""
self.hass = hass
self._semaphores: defaultdict[str, asyncio.Semaphore] = defaultdict(
lambda: asyncio.Semaphore(MAX_PARALLEL_THUMBNAILS)
)
async def get(
self,
request: web.Request,
config_entry_id: str,
channel: str,
stream: str,
time_id: str,
) -> web.Response:
"""Get the key frame at a moment in a recording as JPEG."""
try:
get_host(self.hass, config_entry_id)
except Unresolvable:
return self._unknown_config_entry(config_entry_id)
try:
ch = int(channel)
time = datetime.strptime(time_id, "%Y%m%d%H%M%S")
except ValueError:
err_str = f"Reolink thumbnail invalid channel {channel} or time {time_id}"
return web.Response(body=err_str, status=HTTPStatus.BAD_REQUEST)
if stream not in THUMBNAIL_STREAMS:
err_str = f"Reolink thumbnail invalid stream {stream}"
return web.Response(body=err_str, status=HTTPStatus.BAD_REQUEST)
async with self._semaphores[config_entry_id]:
# The config entry can be unloaded or reloaded while waiting.
try:
host = get_host(self.hass, config_entry_id)
except Unresolvable:
return self._unknown_config_entry(config_entry_id)
if not host.api.supported(ch, "sub"):
stream = stream.replace("sub", "main")
try:
image = await host.api.baichuan.snapshot_past(
ch,
time,
stream,
get_ffmpeg_manager(self.hass).binary,
)
except ReolinkError as err:
_LOGGER.debug(
"Error getting thumbnail of channel %s at %s: %s",
ch,
time_id,
err,
)
return web.Response(body=str(err), status=HTTPStatus.BAD_REQUEST)
# Recordings do not change, so the thumbnail can be cached.
return web.Response(
body=image,
content_type="image/jpeg",
headers={"Cache-Control": "private, max-age=2592000"},
)
@staticmethod
def _unknown_config_entry(config_entry_id: str) -> web.Response:
"""Return the response for an unknown or unloaded config entry."""
_LOGGER.debug(
"Thumbnail requested for unknown config entry %s", config_entry_id
)
err_str = f"Reolink thumbnail could not find config entry id: {config_entry_id}"
return web.Response(body=err_str, status=HTTPStatus.BAD_REQUEST)
@@ -56,6 +56,8 @@ TEST_END = f"{TEST_YEAR}{TEST_MONTH}{TEST_DAY}{TEST_HOUR}{TEST_MINUTE + 5}"
TEST_START_TIME = datetime(TEST_YEAR, TEST_MONTH, TEST_DAY, 0, 0)
TEST_END_TIME = datetime(TEST_YEAR, TEST_MONTH, TEST_DAY, 23, 59, 59)
TEST_FILE_NAME = f"{TEST_START}00"
TEST_THUMBNAIL_TIME = f"{TEST_YEAR}{TEST_MONTH}{TEST_DAY}000005"
TEST_THUMBNAIL_TIME_BATTERY = f"{TEST_YEAR}{TEST_MONTH}{TEST_DAY}000000"
TEST_FILE_NAME_MP4 = f"{TEST_START}00.mp4"
TEST_STREAM = "main"
TEST_CHANNEL = "0"
@@ -249,6 +251,9 @@ async def test_browsing(
)
assert browse.identifier == browse_files_id
assert browse.children[0].identifier == browse_file_id
assert browse.children[0].thumbnail == (
f"/api/reolink/thumbnail/{entry_id}/{TEST_CHANNEL}/sub/{TEST_THUMBNAIL_TIME_BATTERY}"
)
reolink_host.request_vod_files.assert_called_with(
int(TEST_CHANNEL),
TEST_START_TIME,
@@ -293,6 +298,60 @@ async def test_browsing(
)
@pytest.mark.parametrize(
("stream", "duration", "battery", "thumbnail_time"),
[
("autotrack_sub", timedelta(minutes=5), False, TEST_THUMBNAIL_TIME),
("autotrack_main", timedelta(minutes=5), False, TEST_THUMBNAIL_TIME),
# a short recording uses the middle of the recording
(
"autotrack_sub",
timedelta(seconds=6),
False,
f"{TEST_YEAR}{TEST_MONTH}{TEST_DAY}000003",
),
# a battery camera uses the start of the recording
("autotrack_sub", timedelta(minutes=5), True, TEST_THUMBNAIL_TIME_BATTERY),
],
)
async def test_browsing_autotrack_thumbnail(
hass: HomeAssistant,
reolink_host: MagicMock,
config_entry: MockConfigEntry,
stream: str,
duration: timedelta,
battery: bool,
thumbnail_time: str,
) -> None:
"""Test recordings of an autotrack stream have a telephoto thumbnail."""
entry_id = config_entry.entry_id
reolink_host.is_nvr = False
with patch("homeassistant.components.reolink.PLATFORMS", [Platform.CAMERA]):
assert await hass.config_entries.async_setup(entry_id) is True
await hass.async_block_till_done()
mock_vod_file = MagicMock()
mock_vod_file.start_time = TEST_START_TIME
mock_vod_file.start_time_id = TEST_START
mock_vod_file.end_time_id = TEST_END
mock_vod_file.duration = duration
mock_vod_file.file_name = TEST_FILE_NAME
mock_vod_file.triggers = VOD_trigger.PERSON
reolink_host.request_vod_files.return_value = ([], [mock_vod_file])
reolink_host.supported.side_effect = lambda ch, key: battery or key != "battery"
browse_day_id = (
f"DAY|{entry_id}|{TEST_CHANNEL}|{stream}|{TEST_YEAR}|{TEST_MONTH}|{TEST_DAY}"
)
browse = await async_browse_media(hass, f"{URI_SCHEME}{DOMAIN}/{browse_day_id}")
assert browse.children[0].thumbnail == (
f"/api/reolink/thumbnail/{entry_id}/{TEST_CHANNEL}"
f"/telephoto_sub/{thumbnail_time}"
)
async def test_browsing_h265_encoding(
hass: HomeAssistant,
reolink_host: MagicMock,
+246 -1
View File
@@ -14,7 +14,12 @@ from pytest_homeassistant.typing import ClientSessionGenerator
from reolink_aio.enums import VodRequestType
from reolink_aio.exceptions import ReolinkError, UnexpectedDataError
from homeassistant.components.reolink.views import async_generate_playback_proxy_url
from homeassistant.components.reolink.util import get_host
from homeassistant.components.reolink.views import (
MAX_PARALLEL_THUMBNAILS,
async_generate_playback_proxy_url,
async_generate_thumbnail_url,
)
from homeassistant.core import HomeAssistant
TEST_YEAR = 2023
@@ -38,6 +43,8 @@ TEST_NVR_START = "20231114131200"
TEST_NVR_END = "20231114131700"
TEST_NVR_FILE_NAME = f"{TEST_NVR_START}_{TEST_NVR_END}"
TEST_NVR_VOD_TYPE = VodRequestType.NVR_DOWNLOAD.value
TEST_TIME_ID = "20231114131200"
TEST_IMAGE = b"jpeg"
def get_mock_session(
@@ -497,3 +504,241 @@ async def test_playback_service_unavailable(
assert await response.read() == b"testtest"
assert unavailable_session.get.call_args.kwargs["headers"]["Range"] == "bytes=0-"
successful_response.release.assert_called_once_with()
@pytest.mark.parametrize(
("stream", "thumbnail_stream"),
[
("sub", "sub"),
("main", "sub"),
("autotrack_sub", "telephoto_sub"),
("autotrack_main", "telephoto_sub"),
("telephoto_sub", "telephoto_sub"),
("telephoto_main", "telephoto_sub"),
],
)
async def test_thumbnail(
hass: HomeAssistant,
reolink_host: MagicMock,
config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
stream: str,
thumbnail_stream: str,
) -> None:
"""Test getting the thumbnail of a recording."""
reolink_host.baichuan.snapshot_past = AsyncMock(return_value=TEST_IMAGE)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
thumbnail_url = async_generate_thumbnail_url(
config_entry.entry_id, int(TEST_CHANNEL), stream, TEST_TIME_ID
)
http_client = await hass_client()
response = await http_client.get(thumbnail_url)
assert response.status == 200
assert response.content_type == "image/jpeg"
assert await response.content.read() == TEST_IMAGE
reolink_host.baichuan.snapshot_past.assert_called_once()
args = reolink_host.baichuan.snapshot_past.call_args.args
assert args[0] == int(TEST_CHANNEL)
assert args[1] == datetime(2023, 11, 14, 13, 12, 0)
assert args[2] == thumbnail_stream
@pytest.mark.parametrize(
("stream", "thumbnail_stream"),
[
("main", "main"),
("autotrack_main", "telephoto_main"),
("telephoto_main", "telephoto_main"),
],
)
async def test_thumbnail_no_sub_stream(
hass: HomeAssistant,
reolink_host: MagicMock,
config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
stream: str,
thumbnail_stream: str,
) -> None:
"""Test the thumbnail of a camera without a sub stream uses the main stream."""
reolink_host.baichuan.snapshot_past = AsyncMock(return_value=TEST_IMAGE)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
reolink_host.supported.side_effect = lambda ch, key: key != "sub"
http_client = await hass_client()
response = await http_client.get(
async_generate_thumbnail_url(
config_entry.entry_id, int(TEST_CHANNEL), stream, TEST_TIME_ID
)
)
assert response.status == 200
assert await response.content.read() == TEST_IMAGE
assert reolink_host.baichuan.snapshot_past.call_args.args[2] == thumbnail_stream
@pytest.mark.parametrize(
(
"config_entry_id",
"channel",
"stream",
"time_id",
"side_effect",
"body",
),
[
pytest.param(
"wrong_config_id",
TEST_CHANNEL,
TEST_STREAM,
TEST_TIME_ID,
None,
"Reolink thumbnail could not find config entry id: wrong_config_id",
id="unknown_config_entry",
),
pytest.param(
None,
"abc",
TEST_STREAM,
TEST_TIME_ID,
None,
f"Reolink thumbnail invalid channel abc or time {TEST_TIME_ID}",
id="invalid_channel",
),
pytest.param(
None,
TEST_CHANNEL,
TEST_STREAM,
"invalid",
None,
f"Reolink thumbnail invalid channel {TEST_CHANNEL} or time invalid",
id="invalid_time",
),
pytest.param(
None,
TEST_CHANNEL,
"main",
TEST_TIME_ID,
None,
"Reolink thumbnail invalid stream main",
id="invalid_stream",
),
pytest.param(
None,
TEST_CHANNEL,
TEST_STREAM,
TEST_TIME_ID,
ReolinkError(TEST_ERROR),
TEST_ERROR,
id="camera_error",
),
],
)
async def test_thumbnail_errors(
hass: HomeAssistant,
reolink_host: MagicMock,
config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
config_entry_id: str | None,
channel: str,
stream: str,
time_id: str,
side_effect: Exception | None,
body: str,
) -> None:
"""Test errors while getting the thumbnail of a recording."""
reolink_host.baichuan.snapshot_past = AsyncMock(
return_value=TEST_IMAGE, side_effect=side_effect
)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
http_client = await hass_client()
response = await http_client.get(
f"/api/reolink/thumbnail/{config_entry_id or config_entry.entry_id}"
f"/{channel}/{stream}/{time_id}"
)
assert response.status == HTTPStatus.BAD_REQUEST
assert await response.content.read() == bytes(body, "utf-8")
async def test_thumbnail_unloaded_config_entry(
hass: HomeAssistant,
reolink_host: MagicMock,
config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
) -> None:
"""Test getting a thumbnail after the config entry has been unloaded."""
reolink_host.baichuan.snapshot_past = AsyncMock(return_value=TEST_IMAGE)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert await hass.config_entries.async_unload(config_entry.entry_id)
await hass.async_block_till_done()
http_client = await hass_client()
response = await http_client.get(
async_generate_thumbnail_url(
config_entry.entry_id, int(TEST_CHANNEL), TEST_STREAM, TEST_TIME_ID
)
)
assert response.status == HTTPStatus.BAD_REQUEST
reolink_host.baichuan.snapshot_past.assert_not_called()
async def test_thumbnail_unloaded_while_queued(
hass: HomeAssistant,
reolink_host: MagicMock,
config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
) -> None:
"""Test a queued thumbnail request after the config entry has been unloaded."""
release = asyncio.Event()
async def snapshot_past(*args: Any) -> bytes:
await release.wait()
return TEST_IMAGE
reolink_host.baichuan.snapshot_past = AsyncMock(side_effect=snapshot_past)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
http_client = await hass_client()
thumbnail_url = async_generate_thumbnail_url(
config_entry.entry_id, int(TEST_CHANNEL), TEST_STREAM, TEST_TIME_ID
)
with patch(
"homeassistant.components.reolink.views.get_host", wraps=get_host
) as mock_get_host:
requests = [
asyncio.create_task(http_client.get(thumbnail_url))
for _ in range(MAX_PARALLEL_THUMBNAILS)
]
while reolink_host.baichuan.snapshot_past.call_count < MAX_PARALLEL_THUMBNAILS:
await asyncio.sleep(0)
checks = mock_get_host.call_count
requests.append(asyncio.create_task(http_client.get(thumbnail_url)))
# Past its first config entry check, the request waits for the semaphore.
while mock_get_host.call_count == checks:
await asyncio.sleep(0)
assert await hass.config_entries.async_unload(config_entry.entry_id)
release.set()
responses = await asyncio.gather(*requests)
assert sorted(response.status for response in responses) == [
*[HTTPStatus.OK] * MAX_PARALLEL_THUMBNAILS,
HTTPStatus.BAD_REQUEST,
]
assert reolink_host.baichuan.snapshot_past.call_count == MAX_PARALLEL_THUMBNAILS