Websocket media browsing for Plex (#35590)

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
authored and GitHub committed 2020-08-24 12:41:01 +02:00
1 parent 3df67ff9e1
commit 6d95ee7a00
8 files changed
+323 -17

No files matched your search

@@ -0,0 +1,125 @@
"""Support to interface with the Plex API."""
import logging
from homeassistant.components.media_player.errors import BrowseError
from .const import DOMAIN
EXPANDABLES = ["album", "artist", "playlist", "season", "show"]
PLAYLISTS_BROWSE_PAYLOAD = {
"title": "Playlists",
"media_content_id": "all",
"media_content_type": "playlists",
"can_play": False,
"can_expand": True,
}
_LOGGER = logging.getLogger(__name__)
def browse_media(
entity_id, plex_server, media_content_type=None, media_content_id=None
):
"""Implement the websocket media browsing helper."""
def build_item_response(payload):
"""Create response payload for the provided media query."""
media = plex_server.lookup_media(**payload)
if media is None:
return None
media_info = item_payload(media)
if media_info.get("can_expand"):
media_info["children"] = []
for item in media:
media_info["children"].append(item_payload(item))
return media_info
if (
media_content_type == "server"
and media_content_id != plex_server.machine_identifier
):
raise BrowseError(
f"Plex server with ID '{media_content_id}' is not associated with {entity_id}"
)
if media_content_type in ["server", None]:
return server_payload(plex_server)
if media_content_type == "library":
return library_payload(plex_server, media_content_id)
if media_content_type == "playlists":
return playlists_payload(plex_server)
payload = {
"media_type": DOMAIN,
"plex_key": int(media_content_id),
}
response = build_item_response(payload)
if response is None:
raise BrowseError(f"Media not found: {media_content_type} / {media_content_id}")
return response
def item_payload(item):
"""Create response payload for a single media item."""
payload = {
"title": item.title,
"media_content_id": str(item.ratingKey),
"media_content_type": item.type,
"can_play": True,
}
if hasattr(item, "thumbUrl"):
payload["thumbnail"] = item.thumbUrl
if item.type in EXPANDABLES:
payload["can_expand"] = True
return payload
def library_section_payload(section):
"""Create response payload for a single library section."""
return {
"title": section.title,
"media_content_id": section.key,
"media_content_type": "library",
"can_play": False,
"can_expand": True,
}
def server_payload(plex_server):
"""Create response payload to describe libraries of the Plex server."""
server_info = {
"title": plex_server.friendly_name,
"media_content_id": plex_server.machine_identifier,
"media_content_type": "server",
"can_play": False,
"can_expand": True,
}
server_info["children"] = []
for library in plex_server.library.sections():
if library.type == "photo":
continue
server_info["children"].append(library_section_payload(library))
server_info["children"].append(PLAYLISTS_BROWSE_PAYLOAD)
return server_info
def library_payload(plex_server, library_id):
"""Create response payload to describe contents of a specific library."""
library = plex_server.library.sectionByID(library_id)
library_info = library_section_payload(library)
library_info["children"] = []
for item in library.all():
library_info["children"].append(item_payload(item))
return library_info
def playlists_payload(plex_server):
"""Create response payload for all available playlists."""
playlists_info = {**PLAYLISTS_BROWSE_PAYLOAD, "children": []}
for playlist in plex_server.playlists():
playlists_info["children"].append(item_payload(playlist))
return playlists_info
+21 -1
View File
@@ -11,6 +11,7 @@ from homeassistant.components.media_player.const import (
MEDIA_TYPE_MUSIC,
MEDIA_TYPE_TVSHOW,
MEDIA_TYPE_VIDEO,
SUPPORT_BROWSE_MEDIA,
SUPPORT_NEXT_TRACK,
SUPPORT_PAUSE,
SUPPORT_PLAY,
@@ -36,8 +37,16 @@ from .const import (
PLEX_UPDATE_MEDIA_PLAYER_SIGNAL,
SERVERS,
)
from .media_browser import browse_media
LIVE_TV_SECTION = "-4"
PLAYLISTS_BROWSE_PAYLOAD = {
"title": "Playlists",
"media_content_id": "all",
"media_content_type": "playlists",
"can_play": False,
"can_expand": True,
}
_LOGGER = logging.getLogger(__name__)
@@ -489,9 +498,10 @@ class PlexMediaPlayer(MediaPlayerEntity):
| SUPPORT_PLAY
| SUPPORT_PLAY_MEDIA
| SUPPORT_VOLUME_MUTE
| SUPPORT_BROWSE_MEDIA
)
return SUPPORT_PLAY_MEDIA
return SUPPORT_BROWSE_MEDIA | SUPPORT_PLAY_MEDIA
def set_volume_level(self, volume):
"""Set volume level, range 0..1."""
@@ -611,3 +621,13 @@ class PlexMediaPlayer(MediaPlayerEntity):
"sw_version": self._device_version,
"via_device": (PLEX_DOMAIN, self.plex_server.machine_identifier),
}
async def async_browse_media(self, media_content_type=None, media_content_id=None):
"""Implement the websocket media browsing helper."""
return await self.hass.async_add_executor_job(
browse_media,
self.entity_id,
self.plex_server,
media_content_type,
media_content_id,
)
+5 -2
View File
@@ -31,7 +31,6 @@ from .const import (
CONF_USE_EPISODE_ART,
DEBOUNCE_TIMEOUT,
DEFAULT_VERIFY_SSL,
DOMAIN,
PLAYER_SOURCE,
PLEX_NEW_MP_SIGNAL,
PLEX_UPDATE_MEDIA_PLAYER_SIGNAL,
@@ -449,6 +448,10 @@ class PlexServer:
"""Return playlist from server object."""
return self._plex_server.playlist(title)
def playlists(self):
"""Return available playlists from server object."""
return self._plex_server.playlists()
def create_playqueue(self, media, **kwargs):
"""Create playqueue on Plex server."""
return plexapi.playqueue.PlayQueue.create(self._plex_server, media, **kwargs)
@@ -461,7 +464,7 @@ class PlexServer:
"""Lookup a piece of media."""
media_type = media_type.lower()
if media_type == DOMAIN:
if isinstance(kwargs.get("plex_key"), int):
key = kwargs["plex_key"]
try:
return self.fetch_item(key)