Browse media class (#39698)

This commit is contained in:
Paulus Schoutsen authored and GitHub committed 2020-09-06 15:52:59 +02:00
1 parent 13a6aaa6ff
commit df8daf561e
14 files changed
+342 -235

No files matched your search

@@ -68,7 +68,7 @@ def _get_media_item(
@bind_hass
async def async_browse_media(
hass: HomeAssistant, media_content_id: str
) -> models.BrowseMedia:
) -> models.BrowseMediaSource:
"""Return media player browse media results."""
return await _get_media_item(hass, media_content_id).async_browse()
@@ -94,7 +94,7 @@ async def websocket_browse_media(hass, connection, msg):
media = await async_browse_media(hass, msg.get("media_content_id"))
connection.send_result(
msg["id"],
media.to_media_player_item(),
media.as_dict(),
)
except BrowseError as err:
connection.send_error(msg["id"], "browse_media_failed", str(err))
@@ -12,7 +12,7 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.util import sanitize_path
from .const import DOMAIN, MEDIA_MIME_TYPES
from .models import BrowseMedia, MediaSource, MediaSourceItem, PlayMedia
from .models import BrowseMediaSource, MediaSource, MediaSourceItem, PlayMedia
@callback
@@ -67,7 +67,7 @@ class LocalSource(MediaSource):
async def async_browse_media(
self, item: MediaSourceItem, media_types: Tuple[str] = MEDIA_MIME_TYPES
) -> BrowseMedia:
) -> BrowseMediaSource:
"""Return media."""
try:
source_dir_id, location = async_parse_identifier(item)
@@ -92,37 +92,41 @@ class LocalSource(MediaSource):
def _build_item_response(self, source_dir_id: str, path: Path, is_child=False):
mime_type, _ = mimetypes.guess_type(str(path))
media = BrowseMedia(
DOMAIN,
f"{source_dir_id}/{path.relative_to(self.hass.config.path('media'))}",
path.name,
path.is_file(),
path.is_dir(),
mime_type,
)
is_file = path.is_file()
is_dir = path.is_dir()
# Make sure it's a file or directory
if not media.can_play and not media.can_expand:
if not is_file and not is_dir:
return None
# Check that it's a media file
if media.can_play and (
if is_file and (
not mime_type or mime_type.split("/")[0] not in MEDIA_MIME_TYPES
):
return None
if not media.can_expand:
title = path.name
if is_dir:
title += "/"
media = BrowseMediaSource(
domain=DOMAIN,
identifier=f"{source_dir_id}/{path.relative_to(self.hass.config.path('media'))}",
media_content_type="directory",
title=title,
can_play=is_file,
can_expand=is_dir,
)
if is_file or is_child:
return media
media.name += "/"
# Append first level children
if not is_child:
media.children = []
for child_path in path.iterdir():
child = self._build_item_response(source_dir_id, child_path, True)
if child:
media.children.append(child)
media.children = []
for child_path in path.iterdir():
child = self._build_item_response(source_dir_id, child_path, True)
if child:
media.children.append(child)
return media
+33 -42
View File
@@ -3,6 +3,11 @@ from abc import ABC
from dataclasses import dataclass
from typing import List, Optional, Tuple
from homeassistant.components.media_player import BrowseMedia
from homeassistant.components.media_player.const import (
MEDIA_TYPE_CHANNEL,
MEDIA_TYPE_CHANNELS,
)
from homeassistant.core import HomeAssistant, callback
from .const import DOMAIN, URI_SCHEME, URI_SCHEME_REGEX
@@ -16,49 +21,21 @@ class PlayMedia:
mime_type: str
@dataclass
class BrowseMedia:
class BrowseMediaSource(BrowseMedia):
"""Represent a browsable media file."""
domain: str
identifier: str
children: Optional[List["BrowseMediaSource"]]
name: str
can_play: bool = False
can_expand: bool = False
media_content_type: str = None
children: List = None
thumbnail: str = None
def __init__(self, *, domain: Optional[str], identifier: Optional[str], **kwargs):
"""Initialize media source browse media."""
media_content_id = f"{URI_SCHEME}{domain or ''}"
if identifier:
media_content_id += f"/{identifier}"
def to_uri(self):
"""Return URI of media."""
uri = f"{URI_SCHEME}{self.domain or ''}"
if self.identifier:
uri += f"/{self.identifier}"
return uri
super().__init__(media_content_id=media_content_id, **kwargs)
def to_media_player_item(self):
"""Convert Media class to browse media dictionary."""
content_type = self.media_content_type
if content_type is None:
content_type = "folder" if self.can_expand else "file"
response = {
"title": self.name,
"media_content_type": content_type,
"media_content_id": self.to_uri(),
"can_play": self.can_play,
"can_expand": self.can_expand,
"thumbnail": self.thumbnail,
}
if self.children:
response["children"] = [
child.to_media_player_item() for child in self.children
]
return response
self.domain = domain
self.identifier = identifier
@dataclass
@@ -69,12 +46,26 @@ class MediaSourceItem:
domain: Optional[str]
identifier: str
async def async_browse(self) -> BrowseMedia:
async def async_browse(self) -> BrowseMediaSource:
"""Browse this item."""
if self.domain is None:
base = BrowseMedia(None, None, "Media Sources", False, True)
base = BrowseMediaSource(
domain=None,
identifier=None,
media_content_type=MEDIA_TYPE_CHANNELS,
title="Media Sources",
can_play=False,
can_expand=True,
)
base.children = [
BrowseMedia(source.domain, None, source.name, False, True)
BrowseMediaSource(
domain=source.domain,
identifier=None,
media_content_type=MEDIA_TYPE_CHANNEL,
title=source.name,
can_play=False,
can_expand=True,
)
for source in self.hass.data[DOMAIN].values()
]
return base
@@ -121,6 +112,6 @@ class MediaSource(ABC):
async def async_browse_media(
self, item: MediaSourceItem, media_types: Tuple[str]
) -> BrowseMedia:
) -> BrowseMediaSource:
"""Browse media."""
raise NotImplementedError