mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 11:33:11 -04:00
Expose image collections in the media browser (#195425)
Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
co-authored by
Paulus Schoutsen
parent
5d6edaeb98
commit
3a552e28b0
@@ -42,9 +42,11 @@ async def _async_validate_media(
|
||||
found_pictures = False
|
||||
|
||||
for user_media in user_input[CONF_MEDIA]:
|
||||
if user_media["media_content_id"] == IMAGE_MEDIA_URI:
|
||||
media_id = user_media["media_content_id"]
|
||||
# A collection must not include itself through another collection.
|
||||
if media_id == IMAGE_MEDIA_URI or media_id.startswith(f"{URI_SCHEME}{DOMAIN}/"):
|
||||
errors[CONF_MEDIA] = "invalid_selection"
|
||||
placeholders["error"] = IMAGE_MEDIA_URI
|
||||
placeholders["error"] = media_id
|
||||
break
|
||||
|
||||
try:
|
||||
|
||||
@@ -12,16 +12,10 @@ from homeassistant.components.image import (
|
||||
valid_image_content_type,
|
||||
)
|
||||
from homeassistant.components.media_player import (
|
||||
BrowseError,
|
||||
BrowseMedia,
|
||||
MediaClass,
|
||||
async_process_play_media_url,
|
||||
)
|
||||
from homeassistant.components.media_source import (
|
||||
Unresolvable,
|
||||
async_browse_media,
|
||||
async_resolve_media,
|
||||
)
|
||||
from homeassistant.components.media_source import Unresolvable, async_resolve_media
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
@@ -31,7 +25,8 @@ from homeassistant.helpers.start import async_at_started
|
||||
from homeassistant.helpers.typing import Undefined
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from .const import CONF_MEDIA, DOMAIN
|
||||
from .const import DOMAIN
|
||||
from .media import async_collection_images
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -42,21 +37,7 @@ async def async_setup_entry(
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up the Collection Image image entities."""
|
||||
media = entry.data[CONF_MEDIA]
|
||||
if isinstance(media, dict):
|
||||
content_ids = [media["media_content_id"]]
|
||||
else:
|
||||
content_ids = [item["media_content_id"] for item in media]
|
||||
async_add_entities(
|
||||
[
|
||||
CollectionImageImageEntity(
|
||||
name=entry.title,
|
||||
media_content_ids=content_ids,
|
||||
unique_id=entry.entry_id,
|
||||
hass=hass,
|
||||
)
|
||||
]
|
||||
)
|
||||
async_add_entities([CollectionImageImageEntity(hass, entry)])
|
||||
|
||||
|
||||
class CollectionImageImageEntity(ImageEntity):
|
||||
@@ -65,19 +46,13 @@ class CollectionImageImageEntity(ImageEntity):
|
||||
path: Path | None
|
||||
_current_image_id: str | None = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
media_content_ids: list[str],
|
||||
unique_id: str,
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
"""Initialize the entity."""
|
||||
super().__init__(hass)
|
||||
self.path = None
|
||||
self._attr_unique_id = unique_id
|
||||
self._attr_name = name
|
||||
self.media_content_ids = media_content_ids
|
||||
self._attr_unique_id = entry.entry_id
|
||||
self._attr_name = entry.title
|
||||
self._entry = entry
|
||||
|
||||
def set_unavailable(self) -> None:
|
||||
"""Set the entity to unavailable state."""
|
||||
@@ -95,29 +70,7 @@ class CollectionImageImageEntity(ImageEntity):
|
||||
async def get_valid_images(self) -> list[BrowseMedia]:
|
||||
"""Given the configured media directory for the entity, get a list of all child images."""
|
||||
|
||||
images: list[BrowseMedia] = []
|
||||
|
||||
for media_content_id in self.media_content_ids:
|
||||
try:
|
||||
media = await async_browse_media(self.hass, media_content_id)
|
||||
except BrowseError as err:
|
||||
_LOGGER.warning("%s: %s", self.entity_id, str(err))
|
||||
continue
|
||||
|
||||
directory_images = [
|
||||
item
|
||||
for item in (media.children or [])
|
||||
if item.media_class == MediaClass.IMAGE
|
||||
]
|
||||
if directory_images:
|
||||
images.extend(directory_images)
|
||||
else:
|
||||
_LOGGER.warning(
|
||||
"%s: No valid images in %s",
|
||||
self.entity_id,
|
||||
media_content_id,
|
||||
)
|
||||
|
||||
images = await async_collection_images(self.hass, self._entry)
|
||||
if not images:
|
||||
self.set_unavailable()
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Browse the images in a collection."""
|
||||
|
||||
import logging
|
||||
|
||||
from homeassistant.components.media_player import BrowseError, BrowseMedia, MediaClass
|
||||
from homeassistant.components.media_source import async_browse_media
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .const import CONF_MEDIA
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_collection_images(
|
||||
hass: HomeAssistant, entry: ConfigEntry
|
||||
) -> list[BrowseMedia]:
|
||||
"""List images in the order supplied by the configured directories."""
|
||||
media = entry.data[CONF_MEDIA]
|
||||
directories = [media] if isinstance(media, dict) else media
|
||||
images: list[BrowseMedia] = []
|
||||
for directory in directories:
|
||||
media_id = directory["media_content_id"]
|
||||
try:
|
||||
folder = await async_browse_media(hass, media_id)
|
||||
except BrowseError as err:
|
||||
_LOGGER.warning("%s: %s", entry.title, err)
|
||||
continue
|
||||
|
||||
children = [
|
||||
child
|
||||
for child in folder.children or ()
|
||||
if child.media_class == MediaClass.IMAGE
|
||||
]
|
||||
if not children:
|
||||
_LOGGER.warning("%s: No valid images in %s", entry.title, media_id)
|
||||
images.extend(children)
|
||||
return images
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Expose image collections in the media browser."""
|
||||
|
||||
from typing import override
|
||||
|
||||
from homeassistant.components.media_player import BrowseError, MediaClass
|
||||
from homeassistant.components.media_source import (
|
||||
BrowseMediaSource,
|
||||
MediaSource,
|
||||
MediaSourceItem,
|
||||
PlayMedia,
|
||||
Unresolvable,
|
||||
)
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .const import DOMAIN
|
||||
from .media import async_collection_images
|
||||
|
||||
|
||||
async def async_get_media_source(hass: HomeAssistant) -> MediaSource:
|
||||
"""Set up the Collections media source."""
|
||||
return CollectionMediaSource(DOMAIN)
|
||||
|
||||
|
||||
def _collection_folder(entry: ConfigEntry) -> BrowseMediaSource:
|
||||
return BrowseMediaSource(
|
||||
domain=DOMAIN,
|
||||
identifier=entry.entry_id,
|
||||
media_class=MediaClass.DIRECTORY,
|
||||
media_content_type="",
|
||||
title=entry.title,
|
||||
can_expand=True,
|
||||
can_play=False,
|
||||
children_media_class=MediaClass.IMAGE,
|
||||
)
|
||||
|
||||
|
||||
class CollectionMediaSource(MediaSource):
|
||||
"""Provide folders for configured image collections."""
|
||||
|
||||
name = "Collections"
|
||||
|
||||
@override
|
||||
async def async_browse_media(self, item: MediaSourceItem) -> BrowseMediaSource:
|
||||
"""Browse collections or the images in a collection."""
|
||||
entries = item.hass.config_entries.async_loaded_entries(DOMAIN)
|
||||
if not item.identifier:
|
||||
return BrowseMediaSource(
|
||||
domain=DOMAIN,
|
||||
identifier=None,
|
||||
media_class=MediaClass.APP,
|
||||
media_content_type="",
|
||||
title=self.name,
|
||||
can_expand=True,
|
||||
can_play=False,
|
||||
children_media_class=MediaClass.DIRECTORY,
|
||||
children=[_collection_folder(entry) for entry in entries],
|
||||
)
|
||||
|
||||
for entry in entries:
|
||||
if entry.entry_id == item.identifier:
|
||||
folder = _collection_folder(entry)
|
||||
folder.children = await async_collection_images(item.hass, entry)
|
||||
return folder
|
||||
raise BrowseError(
|
||||
translation_domain=DOMAIN, translation_key="collection_not_found"
|
||||
)
|
||||
|
||||
@override
|
||||
async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia:
|
||||
"""Only the images inside a collection are playable."""
|
||||
raise Unresolvable(
|
||||
translation_domain=DOMAIN, translation_key="collection_not_playable"
|
||||
)
|
||||
@@ -5,9 +5,7 @@ rules:
|
||||
status: exempt
|
||||
comment: Integration does not poll.
|
||||
brands: done
|
||||
common-modules:
|
||||
status: exempt
|
||||
comment: No common modules exist, only a single platform.
|
||||
common-modules: done
|
||||
config-flow-test-coverage: done
|
||||
config-flow: done
|
||||
dependency-transparency:
|
||||
|
||||
@@ -30,6 +30,12 @@
|
||||
}
|
||||
},
|
||||
"exceptions": {
|
||||
"collection_not_found": {
|
||||
"message": "The image collection could not be found."
|
||||
},
|
||||
"collection_not_playable": {
|
||||
"message": "Select an image from the collection to play."
|
||||
},
|
||||
"invalid_media_type": {
|
||||
"message": "Selected media {id} has type {mime_type}, which is not an image, and cannot be shown by {entity}."
|
||||
},
|
||||
|
||||
@@ -149,7 +149,7 @@ def mock_media_source(
|
||||
new=AsyncMock(side_effect=browse_side_effect),
|
||||
) as config_flow_browse,
|
||||
patch(
|
||||
"homeassistant.components.collection_image.image.async_browse_media",
|
||||
"homeassistant.components.collection_image.media.async_browse_media",
|
||||
new=AsyncMock(side_effect=browse_side_effect),
|
||||
) as image_browse,
|
||||
patch(
|
||||
|
||||
@@ -88,6 +88,11 @@ async def test_config_flow(hass: HomeAssistant, uris: list[str]) -> None:
|
||||
"failed_browse",
|
||||
{"error": "Mock directory failed to browse"},
|
||||
),
|
||||
(
|
||||
["media-source://collection_image/family"],
|
||||
"invalid_selection",
|
||||
{"error": "media-source://collection_image/family"},
|
||||
),
|
||||
(
|
||||
[MOCK_MEDIA_DIR_URI_1, IMAGE_MEDIA_URI],
|
||||
"invalid_selection",
|
||||
|
||||
@@ -234,17 +234,17 @@ async def test_image_url(
|
||||
[
|
||||
(
|
||||
MOCK_MEDIA_DIR_URI_EMPTY,
|
||||
[f"image.random_image: No valid images in {MOCK_MEDIA_DIR_URI_EMPTY}"],
|
||||
[f"Random Image: No valid images in {MOCK_MEDIA_DIR_URI_EMPTY}"],
|
||||
),
|
||||
(
|
||||
[MOCK_MEDIA_DIR_URI_BROWSE_ERROR],
|
||||
["image.random_image: Mock directory failed to browse"],
|
||||
["Random Image: Mock directory failed to browse"],
|
||||
),
|
||||
(
|
||||
[MOCK_MEDIA_DIR_URI_EMPTY, MOCK_MEDIA_DIR_URI_BROWSE_ERROR],
|
||||
[
|
||||
f"image.random_image: No valid images in {MOCK_MEDIA_DIR_URI_EMPTY}",
|
||||
"image.random_image: Mock directory failed to browse",
|
||||
f"Random Image: No valid images in {MOCK_MEDIA_DIR_URI_EMPTY}",
|
||||
"Random Image: Mock directory failed to browse",
|
||||
],
|
||||
),
|
||||
],
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Tests for browsing image collections."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import media_source
|
||||
from homeassistant.components.media_player import BrowseError
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from .helpers import config_entry_from_uri
|
||||
|
||||
COLLECTIONS = "media-source://collection_image"
|
||||
LOCAL = "media-source://media_source/local"
|
||||
|
||||
|
||||
async def test_browse_collection(hass: HomeAssistant, tmp_path: Path) -> None:
|
||||
"""Browse a collection and open a photo through its original source."""
|
||||
hass.config.media_dirs["local"] = str(tmp_path)
|
||||
for name in ("summer", "spring"):
|
||||
folder = tmp_path / name
|
||||
folder.mkdir()
|
||||
(folder / "photo.png").touch()
|
||||
(folder / "track.mp3").touch()
|
||||
|
||||
assert await async_setup_component(hass, "media_source", {})
|
||||
entry = config_entry_from_uri([f"{LOCAL}/summer", f"{LOCAL}/spring"])
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
root = await media_source.async_browse_media(hass, None)
|
||||
assert any(child.media_content_id == COLLECTIONS for child in root.children)
|
||||
collections = await media_source.async_browse_media(hass, COLLECTIONS)
|
||||
assert collections.title == "Collections"
|
||||
[collection] = collections.children
|
||||
assert collection.title == entry.title
|
||||
assert collection.can_expand
|
||||
assert not collection.can_play
|
||||
|
||||
current_image = hass.states.get("image.random_image")
|
||||
album = await media_source.async_browse_media(hass, collection.media_content_id)
|
||||
assert [photo.media_content_id for photo in album.children] == [
|
||||
f"{LOCAL}/summer/photo.png",
|
||||
f"{LOCAL}/spring/photo.png",
|
||||
]
|
||||
photo = album.children[0]
|
||||
assert photo.can_play
|
||||
resolved = await media_source.async_resolve_media(
|
||||
hass, photo.media_content_id, None
|
||||
)
|
||||
assert resolved.path == tmp_path / "summer" / "photo.png"
|
||||
assert hass.states.get("image.random_image") is current_image
|
||||
|
||||
with pytest.raises(media_source.Unresolvable):
|
||||
await media_source.async_resolve_media(hass, collection.media_content_id, None)
|
||||
|
||||
assert await hass.config_entries.async_unload(entry.entry_id)
|
||||
collections = await media_source.async_browse_media(hass, COLLECTIONS)
|
||||
assert collections.children == []
|
||||
with pytest.raises(BrowseError, match="The image collection could not be found"):
|
||||
await media_source.async_browse_media(hass, collection.media_content_id)
|
||||
Reference in New Issue
Block a user