Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 29 additions & 21 deletions homeassistant/components/camera/media_source.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Expose cameras as media sources."""
from __future__ import annotations

import asyncio

from homeassistant.components.media_player import BrowseError, MediaClass
from homeassistant.components.media_source.error import Unresolvable
from homeassistant.components.media_source.models import (
Expand Down Expand Up @@ -71,36 +73,42 @@ async def async_browse_media(

can_stream_hls = "stream" in self.hass.config.components

# Root. List cameras.
component: EntityComponent[Camera] = self.hass.data[DOMAIN]
children = []
not_shown = 0
for camera in component.entities:
async def _media_source_for_camera(camera: Camera) -> BrowseMediaSource | None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think everything looks good to go here, but now i'm thinking about one more idea to further streamline this, but not positive it would work out: Could the scope of this function be to just filter out the not relevant cameras and leave the browse media source building all together how it was? It could just get the eligible cameras in one pass then build the sources in a simple loop together with building the root.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could return the camera instead of BrowseMediaSource, and then iterate over the results to build the sources, but I'm not sure I see why it would be better?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its possibly a style preference, but my thinking is: in general, reducing # of verical lines of inline functions or reducing the scope as much as possible seems positive. Having the BrowseMediaSource building closer together together seems logical as well. One exception may be if there is shared logic on both parts but i think the existing stream type filtering looks more complex than it needs to be

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a bit tricky because we also have to recalculate the content type (or return a tuple).
Arguably refactoring the creation of the BrowseMediaSource to a separate function would achieve a similar result (see my latest commit)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, that looks good. What do you think about gutting all the existing vertical whitespace? It seems like it makes this harder to follow given it has so many branches and is in an inline function. Collapsing vertically will also help make this simpler to grok quickly.

stream_type = camera.frontend_stream_type

if stream_type is None:
content_type = camera.content_type

elif can_stream_hls and stream_type == StreamType.HLS:
elif can_stream_hls:
content_type = FORMAT_CONTENT_TYPE[HLS_PROVIDER]

if stream_type != StreamType.HLS:
source = await camera.stream_source()
if not source:
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it work for this to be a single statement? (Given this is 3 levels of nested ifs in an inline function)

Suggested change
if stream_type != StreamType.HLS:
source = await camera.stream_source()
if not source:
return None
if stream_type != StreamType.HLS and not (source := await camera.stream_source())
return None

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took advantage of the ability to return early in a successful case to refactor a bit differently. Let me know what you think.

else:
not_shown += 1
continue

children.append(
BrowseMediaSource(
domain=DOMAIN,
identifier=camera.entity_id,
media_class=MediaClass.VIDEO,
media_content_type=content_type,
title=camera.name,
thumbnail=f"/api/camera_proxy/{camera.entity_id}",
can_play=True,
can_expand=False,
)
return None

return BrowseMediaSource(
domain=DOMAIN,
identifier=camera.entity_id,
media_class=MediaClass.VIDEO,
media_content_type=content_type,
title=camera.name,
thumbnail=f"/api/camera_proxy/{camera.entity_id}",
can_play=True,
can_expand=False,
)

# Root. List cameras.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe just drop this while we're here

Suggested change
# Root. List cameras.

component: EntityComponent[Camera] = self.hass.data[DOMAIN]
results = await asyncio.gather(
*(_media_source_for_camera(camera) for camera in component.entities),
return_exceptions=True,
)
children = [
result for result in results if isinstance(result, BrowseMediaSource)
]
not_shown = len(results) - len(children)
return BrowseMediaSource(
domain=DOMAIN,
identifier=None,
Expand Down
36 changes: 25 additions & 11 deletions tests/components/camera/test_media_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ async def setup_media_source(hass):


async def test_browsing_hls(hass: HomeAssistant, mock_camera_hls) -> None:
"""Test browsing camera media source."""
"""Test browsing HLS camera media source."""
item = await media_source.async_browse_media(hass, "media-source://camera")
assert item is not None
assert item.title == "Camera"
Expand All @@ -34,7 +34,7 @@ async def test_browsing_hls(hass: HomeAssistant, mock_camera_hls) -> None:


async def test_browsing_mjpeg(hass: HomeAssistant, mock_camera) -> None:
"""Test browsing camera media source."""
"""Test browsing MJPEG camera media source."""
item = await media_source.async_browse_media(hass, "media-source://camera")
assert item is not None
assert item.title == "Camera"
Expand All @@ -43,15 +43,29 @@ async def test_browsing_mjpeg(hass: HomeAssistant, mock_camera) -> None:
assert item.children[0].media_content_type == "image/jpg"


async def test_browsing_filter_web_rtc(
hass: HomeAssistant, mock_camera_web_rtc
) -> None:
"""Test browsing camera media source hides non-HLS cameras."""
item = await media_source.async_browse_media(hass, "media-source://camera")
assert item is not None
assert item.title == "Camera"
assert len(item.children) == 0
assert item.not_shown == 3
async def test_browsing_web_rtc(hass: HomeAssistant, mock_camera_web_rtc) -> None:
"""Test browsing WebRTC camera media source."""
# 3 cameras:
# one only supports WebRTC (no stream source)
# one raises when getting the source
# One has a stream source, and should be the only browsable one
with patch(
"homeassistant.components.camera.Camera.stream_source",
side_effect=["test", None, Exception],
):
item = await media_source.async_browse_media(hass, "media-source://camera")
assert item is not None
assert item.title == "Camera"
assert len(item.children) == 0
assert item.not_shown == 3

# Adding stream enables HLS camera
hass.config.components.add("stream")

item = await media_source.async_browse_media(hass, "media-source://camera")
assert item.not_shown == 2
assert len(item.children) == 1
assert item.children[0].media_content_type == FORMAT_CONTENT_TYPE["hls"]


async def test_resolving(hass: HomeAssistant, mock_camera_hls) -> None:
Expand Down