Media Source implementation for Chromecast (#39305)

* Implement local media finder and integrate into cast

* update to media source as a platform

* Tweak media source design

* fix websocket and local source

* fix websocket schema

* fix playing media

* Apply suggestions from code review

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Add resolve_media websocket

* Register that shit

* Square brackets

* Sign path

* add support for multiple media sources and address PR review

* fix lint

* fix tests from auto whitelisting config/media

* allow specifying a name on the media source

* add tests

* fix for python 3.7

* Apply suggestions from code review

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>

* add http back to cast and remove guess_type from executor as there is no i/o

Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
This commit is contained in:
authored and GitHub committed 2020-09-04 11:16:29 -04:00
1 parent f01a0f9151
commit f2b3e63ff6
18 files changed
+738 -6

No files matched your search

@@ -0,0 +1,124 @@
"""The media_source integration."""
from datetime import timedelta
from typing import Optional
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.components.http.auth import async_sign_path
from homeassistant.components.media_player.const import ATTR_MEDIA_CONTENT_ID
from homeassistant.components.media_player.errors import BrowseError
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.integration_platform import (
async_process_integration_platforms,
)
from homeassistant.loader import bind_hass
from . import local_source, models
from .const import DOMAIN, URI_SCHEME, URI_SCHEME_REGEX
from .error import Unresolvable
def is_media_source_id(media_content_id: str):
"""Test if identifier is a media source."""
return URI_SCHEME_REGEX.match(media_content_id) is not None
def generate_media_source_id(domain: str, identifier: str) -> str:
"""Generate a media source ID."""
uri = f"{URI_SCHEME}{domain or ''}"
if identifier:
uri += f"/{identifier}"
return uri
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the media_source component."""
hass.data[DOMAIN] = {}
hass.components.websocket_api.async_register_command(websocket_browse_media)
hass.components.websocket_api.async_register_command(websocket_resolve_media)
local_source.async_setup(hass)
await async_process_integration_platforms(
hass, DOMAIN, _process_media_source_platform
)
return True
async def _process_media_source_platform(hass, domain, platform):
"""Process a media source platform."""
hass.data[DOMAIN][domain] = await platform.async_get_media_source(hass)
@callback
def _get_media_item(
hass: HomeAssistant, media_content_id: Optional[str]
) -> models.MediaSourceItem:
"""Return media item."""
if media_content_id:
return models.MediaSourceItem.from_uri(hass, media_content_id)
# We default to our own domain if its only one registered
domain = None if len(hass.data[DOMAIN]) > 1 else DOMAIN
return models.MediaSourceItem(hass, domain, "")
@bind_hass
async def async_browse_media(
hass: HomeAssistant, media_content_id: str
) -> models.BrowseMedia:
"""Return media player browse media results."""
return await _get_media_item(hass, media_content_id).async_browse()
@bind_hass
async def async_resolve_media(
hass: HomeAssistant, media_content_id: str
) -> models.PlayMedia:
"""Get info to play media."""
return await _get_media_item(hass, media_content_id).async_resolve()
@websocket_api.websocket_command(
{
vol.Required("type"): "media_source/browse_media",
vol.Optional(ATTR_MEDIA_CONTENT_ID, default=""): str,
}
)
@websocket_api.async_response
async def websocket_browse_media(hass, connection, msg):
"""Browse available media."""
try:
media = await async_browse_media(hass, msg.get("media_content_id"))
connection.send_result(
msg["id"],
media.to_media_player_item(),
)
except BrowseError as err:
connection.send_error(msg["id"], "browse_media_failed", str(err))
@websocket_api.websocket_command(
{
vol.Required("type"): "media_source/resolve_media",
vol.Required(ATTR_MEDIA_CONTENT_ID): str,
vol.Optional("expires", default=30): int,
}
)
@websocket_api.async_response
async def websocket_resolve_media(hass, connection, msg):
"""Resolve media."""
try:
media = await async_resolve_media(hass, msg["media_content_id"])
url = media.url
except Unresolvable as err:
connection.send_error(msg["id"], "resolve_media_failed", str(err))
else:
if url[0] == "/":
url = async_sign_path(
hass,
connection.refresh_token_id,
url,
timedelta(seconds=msg["expires"]),
)
connection.send_result(msg["id"], {"url": url, "mime_type": media.mime_type})
@@ -0,0 +1,7 @@
"""Constants for the media_source integration."""
import re
DOMAIN = "media_source"
MEDIA_MIME_TYPES = ("audio", "video", "image")
URI_SCHEME = "media-source://"
URI_SCHEME_REGEX = re.compile(r"^media-source://(?P<domain>[^/]+)?(?P<identifier>.+)?")
@@ -0,0 +1,10 @@
"""Errors for media source."""
from homeassistant.exceptions import HomeAssistantError
class MediaSourceError(HomeAssistantError):
"""Base class for media source errors."""
class Unresolvable(MediaSourceError):
"""When media ID is not resolvable."""
@@ -0,0 +1,160 @@
"""Local Media Source Implementation."""
import mimetypes
from pathlib import Path
from typing import Tuple
from aiohttp import web
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.media_player.errors import BrowseError
from homeassistant.components.media_source.error import Unresolvable
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
@callback
def async_setup(hass: HomeAssistant):
"""Set up local media source."""
source = LocalSource(hass)
hass.data[DOMAIN][DOMAIN] = source
hass.http.register_view(LocalMediaView(hass))
@callback
def async_parse_identifier(item: MediaSourceItem) -> Tuple[str, str]:
"""Parse identifier."""
if not item.identifier:
source_dir_id = "media"
location = ""
else:
source_dir_id, location = item.identifier.lstrip("/").split("/", 1)
if source_dir_id != "media":
raise Unresolvable("Unknown source directory.")
if location != sanitize_path(location):
raise Unresolvable("Invalid path.")
return source_dir_id, location
class LocalSource(MediaSource):
"""Provide local directories as media sources."""
name: str = "Local Media"
def __init__(self, hass: HomeAssistant):
"""Initialize local source."""
super().__init__(DOMAIN)
self.hass = hass
@callback
def async_full_path(self, source_dir_id, location) -> Path:
"""Return full path."""
return self.hass.config.path("media", location)
async def async_resolve_media(self, item: MediaSourceItem) -> str:
"""Resolve media to a url."""
source_dir_id, location = async_parse_identifier(item)
mime_type, _ = mimetypes.guess_type(
self.async_full_path(source_dir_id, location)
)
return PlayMedia(item.identifier, mime_type)
async def async_browse_media(
self, item: MediaSourceItem, media_types: Tuple[str] = MEDIA_MIME_TYPES
) -> BrowseMedia:
"""Return media."""
try:
source_dir_id, location = async_parse_identifier(item)
except Unresolvable as err:
raise BrowseError(str(err)) from err
return await self.hass.async_add_executor_job(
self._browse_media, source_dir_id, location
)
def _browse_media(self, source_dir_id, location):
"""Browse media."""
full_path = Path(self.hass.config.path("media", location))
if not full_path.exists():
raise BrowseError("Path does not exist.")
if not full_path.is_dir():
raise BrowseError("Path is not a directory.")
return self._build_item_response(source_dir_id, full_path)
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,
)
# Make sure it's a file or directory
if not media.can_play and not media.can_expand:
return None
# Check that it's a media file
if media.can_play and (
not mime_type or mime_type.split("/")[0] not in MEDIA_MIME_TYPES
):
return None
if not media.can_expand:
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)
return media
class LocalMediaView(HomeAssistantView):
"""
Local Media Finder View.
Returns media files in config/media.
"""
url = "/media/{location:.*}"
name = "media"
def __init__(self, hass: HomeAssistant):
"""Initialize the media view."""
self.hass = hass
async def get(self, request: web.Request, location: str) -> web.FileResponse:
"""Start a GET request."""
if location != sanitize_path(location):
return web.HTTPNotFound()
media_path = Path(self.hass.config.path("media", location))
# Check that the file exists
if not media_path.is_file():
raise web.HTTPNotFound()
# Check that it's a media file
mime_type, _ = mimetypes.guess_type(str(media_path))
if not mime_type or mime_type.split("/")[0] not in MEDIA_MIME_TYPES:
raise web.HTTPNotFound()
return web.FileResponse(media_path)
@@ -0,0 +1,7 @@
{
"domain": "media_source",
"name": "Media Source",
"documentation": "https://www.home-assistant.io/integrations/media_source",
"dependencies": ["http"],
"codeowners": ["@hunterjm"]
}
@@ -0,0 +1,124 @@
"""Media Source models."""
from abc import ABC
from dataclasses import dataclass
from typing import List, Optional, Tuple
from homeassistant.core import HomeAssistant, callback
from .const import DOMAIN, URI_SCHEME, URI_SCHEME_REGEX
@dataclass
class PlayMedia:
"""Represents a playable media."""
url: str
mime_type: str
@dataclass
class BrowseMedia:
"""Represent a browsable media file."""
domain: str
identifier: str
name: str
can_play: bool = False
can_expand: bool = False
media_content_type: str = None
children: List = None
def to_uri(self):
"""Return URI of media."""
uri = f"{URI_SCHEME}{self.domain or ''}"
if self.identifier:
uri += f"/{self.identifier}"
return uri
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,
}
if self.children:
response["children"] = [
child.to_media_player_item() for child in self.children
]
return response
@dataclass
class MediaSourceItem:
"""A parsed media item."""
hass: HomeAssistant
domain: Optional[str]
identifier: str
async def async_browse(self) -> BrowseMedia:
"""Browse this item."""
if self.domain is None:
base = BrowseMedia(None, None, "Media Sources", False, True)
base.children = [
BrowseMedia(source.domain, None, source.name, False, True)
for source in self.hass.data[DOMAIN].values()
]
return base
return await self.async_media_source().async_browse_media(self)
async def async_resolve(self) -> PlayMedia:
"""Resolve to playable item."""
return await self.async_media_source().async_resolve_media(self)
@callback
def async_media_source(self) -> "MediaSource":
"""Return media source that owns this item."""
return self.hass.data[DOMAIN][self.domain]
@classmethod
def from_uri(cls, hass: HomeAssistant, uri: str) -> "MediaSourceItem":
"""Create an item from a uri."""
match = URI_SCHEME_REGEX.match(uri)
if not match:
raise ValueError("Invalid media source URI")
domain = match.group("domain")
identifier = match.group("identifier")
return cls(hass, domain, identifier)
class MediaSource(ABC):
"""Represents a source of media files."""
name: str = None
def __init__(self, domain: str):
"""Initialize a media source."""
self.domain = domain
if not self.name:
self.name = domain
async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia:
"""Resolve a media item to a playable item."""
raise NotImplementedError
async def async_browse_media(
self, item: MediaSourceItem, media_types: Tuple[str]
) -> BrowseMedia:
"""Browse media."""
raise NotImplementedError