Black
This commit is contained in:
1 parent
da05dfe708
commit
4de97abc3a
2676 files changed
+163166
-140084
No files matched your search
@@ -6,14 +6,27 @@ import logging
|
||||
import requests
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.media_player import (
|
||||
MediaPlayerDevice, PLATFORM_SCHEMA)
|
||||
from homeassistant.components.media_player import MediaPlayerDevice, PLATFORM_SCHEMA
|
||||
from homeassistant.components.media_player.const import (
|
||||
MEDIA_TYPE_MOVIE, MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW,
|
||||
SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PREVIOUS_TRACK,
|
||||
SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET)
|
||||
MEDIA_TYPE_MOVIE,
|
||||
MEDIA_TYPE_MUSIC,
|
||||
MEDIA_TYPE_TVSHOW,
|
||||
SUPPORT_NEXT_TRACK,
|
||||
SUPPORT_PAUSE,
|
||||
SUPPORT_PLAY,
|
||||
SUPPORT_PREVIOUS_TRACK,
|
||||
SUPPORT_STOP,
|
||||
SUPPORT_TURN_OFF,
|
||||
SUPPORT_VOLUME_MUTE,
|
||||
SUPPORT_VOLUME_SET,
|
||||
)
|
||||
from homeassistant.const import (
|
||||
DEVICE_DEFAULT_NAME, STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING)
|
||||
DEVICE_DEFAULT_NAME,
|
||||
STATE_IDLE,
|
||||
STATE_OFF,
|
||||
STATE_PAUSED,
|
||||
STATE_PLAYING,
|
||||
)
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.event import track_time_interval
|
||||
from homeassistant.util import dt as dt_util
|
||||
@@ -22,22 +35,25 @@ from homeassistant.util.json import load_json, save_json
|
||||
_CONFIGURING = {}
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
NAME_FORMAT = 'Plex {}'
|
||||
PLEX_CONFIG_FILE = 'plex.conf'
|
||||
PLEX_DATA = 'plex'
|
||||
NAME_FORMAT = "Plex {}"
|
||||
PLEX_CONFIG_FILE = "plex.conf"
|
||||
PLEX_DATA = "plex"
|
||||
|
||||
CONF_USE_EPISODE_ART = 'use_episode_art'
|
||||
CONF_SHOW_ALL_CONTROLS = 'show_all_controls'
|
||||
CONF_REMOVE_UNAVAILABLE_CLIENTS = 'remove_unavailable_clients'
|
||||
CONF_CLIENT_REMOVE_INTERVAL = 'client_remove_interval'
|
||||
CONF_USE_EPISODE_ART = "use_episode_art"
|
||||
CONF_SHOW_ALL_CONTROLS = "show_all_controls"
|
||||
CONF_REMOVE_UNAVAILABLE_CLIENTS = "remove_unavailable_clients"
|
||||
CONF_CLIENT_REMOVE_INTERVAL = "client_remove_interval"
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_USE_EPISODE_ART, default=False): cv.boolean,
|
||||
vol.Optional(CONF_SHOW_ALL_CONTROLS, default=False): cv.boolean,
|
||||
vol.Optional(CONF_REMOVE_UNAVAILABLE_CLIENTS, default=True): cv.boolean,
|
||||
vol.Optional(CONF_CLIENT_REMOVE_INTERVAL, default=timedelta(seconds=600)):
|
||||
vol.All(cv.time_period, cv.positive_timedelta),
|
||||
})
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
||||
{
|
||||
vol.Optional(CONF_USE_EPISODE_ART, default=False): cv.boolean,
|
||||
vol.Optional(CONF_SHOW_ALL_CONTROLS, default=False): cv.boolean,
|
||||
vol.Optional(CONF_REMOVE_UNAVAILABLE_CLIENTS, default=True): cv.boolean,
|
||||
vol.Optional(
|
||||
CONF_CLIENT_REMOVE_INTERVAL, default=timedelta(seconds=600)
|
||||
): vol.All(cv.time_period, cv.positive_timedelta),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities_callback, discovery_info=None):
|
||||
@@ -51,22 +67,22 @@ def setup_platform(hass, config, add_entities_callback, discovery_info=None):
|
||||
if file_config:
|
||||
# Setup a configured PlexServer
|
||||
host, host_config = file_config.popitem()
|
||||
token = host_config['token']
|
||||
token = host_config["token"]
|
||||
try:
|
||||
has_ssl = host_config['ssl']
|
||||
has_ssl = host_config["ssl"]
|
||||
except KeyError:
|
||||
has_ssl = False
|
||||
try:
|
||||
verify_ssl = host_config['verify']
|
||||
verify_ssl = host_config["verify"]
|
||||
except KeyError:
|
||||
verify_ssl = True
|
||||
|
||||
# Via discovery
|
||||
elif discovery_info is not None:
|
||||
# Parse discovery data
|
||||
host = discovery_info.get('host')
|
||||
port = discovery_info.get('port')
|
||||
host = '%s:%s' % (host, port)
|
||||
host = discovery_info.get("host")
|
||||
port = discovery_info.get("port")
|
||||
host = "%s:%s" % (host, port)
|
||||
_LOGGER.info("Discovered PLEX server: %s", host)
|
||||
|
||||
if host in _CONFIGURING:
|
||||
@@ -78,31 +94,33 @@ def setup_platform(hass, config, add_entities_callback, discovery_info=None):
|
||||
return
|
||||
|
||||
setup_plexserver(
|
||||
host, token, has_ssl, verify_ssl,
|
||||
hass, config, add_entities_callback
|
||||
host, token, has_ssl, verify_ssl, hass, config, add_entities_callback
|
||||
)
|
||||
|
||||
|
||||
def setup_plexserver(
|
||||
host, token, has_ssl, verify_ssl, hass, config, add_entities_callback):
|
||||
host, token, has_ssl, verify_ssl, hass, config, add_entities_callback
|
||||
):
|
||||
"""Set up a plexserver based on host parameter."""
|
||||
import plexapi.server
|
||||
import plexapi.exceptions
|
||||
|
||||
cert_session = None
|
||||
http_prefix = 'https' if has_ssl else 'http'
|
||||
http_prefix = "https" if has_ssl else "http"
|
||||
if has_ssl and (verify_ssl is False):
|
||||
_LOGGER.info("Ignoring SSL verification")
|
||||
cert_session = requests.Session()
|
||||
cert_session.verify = False
|
||||
try:
|
||||
plexserver = plexapi.server.PlexServer(
|
||||
'%s://%s' % (http_prefix, host),
|
||||
token, cert_session
|
||||
"%s://%s" % (http_prefix, host), token, cert_session
|
||||
)
|
||||
_LOGGER.info("Discovery configuration done (no token needed)")
|
||||
except (plexapi.exceptions.BadRequest, plexapi.exceptions.Unauthorized,
|
||||
plexapi.exceptions.NotFound) as error:
|
||||
except (
|
||||
plexapi.exceptions.BadRequest,
|
||||
plexapi.exceptions.Unauthorized,
|
||||
plexapi.exceptions.NotFound,
|
||||
) as error:
|
||||
_LOGGER.info(error)
|
||||
# No token or wrong token
|
||||
request_configuration(host, hass, config, add_entities_callback)
|
||||
@@ -117,18 +135,15 @@ def setup_plexserver(
|
||||
|
||||
# Save config
|
||||
save_json(
|
||||
hass.config.path(PLEX_CONFIG_FILE), {host: {
|
||||
'token': token,
|
||||
'ssl': has_ssl,
|
||||
'verify': verify_ssl,
|
||||
}})
|
||||
hass.config.path(PLEX_CONFIG_FILE),
|
||||
{host: {"token": token, "ssl": has_ssl, "verify": verify_ssl}},
|
||||
)
|
||||
|
||||
_LOGGER.info('Connected to: %s://%s', http_prefix, host)
|
||||
_LOGGER.info("Connected to: %s://%s", http_prefix, host)
|
||||
|
||||
plex_clients = hass.data[PLEX_DATA]
|
||||
plex_sessions = {}
|
||||
track_time_interval(
|
||||
hass, lambda now: update_devices(), timedelta(seconds=10))
|
||||
track_time_interval(hass, lambda now: update_devices(), timedelta(seconds=10))
|
||||
|
||||
def update_devices():
|
||||
"""Update the devices objects."""
|
||||
@@ -139,27 +154,28 @@ def setup_plexserver(
|
||||
return
|
||||
except requests.exceptions.RequestException as ex:
|
||||
_LOGGER.warning(
|
||||
"Could not connect to plex server at http://%s (%s)", host, ex)
|
||||
"Could not connect to plex server at http://%s (%s)", host, ex
|
||||
)
|
||||
return
|
||||
|
||||
new_plex_clients = []
|
||||
available_client_ids = []
|
||||
for device in devices:
|
||||
# For now, let's allow all deviceClass types
|
||||
if device.deviceClass in ['badClient']:
|
||||
if device.deviceClass in ["badClient"]:
|
||||
continue
|
||||
|
||||
available_client_ids.append(device.machineIdentifier)
|
||||
|
||||
if device.machineIdentifier not in plex_clients:
|
||||
new_client = PlexClient(
|
||||
config, device, None, plex_sessions, update_devices)
|
||||
config, device, None, plex_sessions, update_devices
|
||||
)
|
||||
plex_clients[device.machineIdentifier] = new_client
|
||||
_LOGGER.debug("New device: %s", device.machineIdentifier)
|
||||
new_plex_clients.append(new_client)
|
||||
else:
|
||||
_LOGGER.debug("Refreshing device: %s",
|
||||
device.machineIdentifier)
|
||||
_LOGGER.debug("Refreshing device: %s", device.machineIdentifier)
|
||||
plex_clients[device.machineIdentifier].refresh(device, None)
|
||||
|
||||
# add devices with a session and no client (ex. PlexConnect Apple TV's)
|
||||
@@ -170,7 +186,8 @@ def setup_plexserver(
|
||||
return
|
||||
except requests.exceptions.RequestException as ex:
|
||||
_LOGGER.warning(
|
||||
"Could not connect to plex server at http://%s (%s)", host, ex)
|
||||
"Could not connect to plex server at http://%s (%s)", host, ex
|
||||
)
|
||||
return
|
||||
|
||||
plex_sessions.clear()
|
||||
@@ -181,14 +198,16 @@ def setup_plexserver(
|
||||
for machine_identifier, (session, player) in plex_sessions.items():
|
||||
if machine_identifier in available_client_ids:
|
||||
# Avoid using session if already added as a device.
|
||||
_LOGGER.debug("Skipping session, device exists: %s",
|
||||
machine_identifier)
|
||||
_LOGGER.debug("Skipping session, device exists: %s", machine_identifier)
|
||||
continue
|
||||
|
||||
if (machine_identifier not in plex_clients
|
||||
and machine_identifier is not None):
|
||||
if (
|
||||
machine_identifier not in plex_clients
|
||||
and machine_identifier is not None
|
||||
):
|
||||
new_client = PlexClient(
|
||||
config, player, session, plex_sessions, update_devices)
|
||||
config, player, session, plex_sessions, update_devices
|
||||
)
|
||||
plex_clients[machine_identifier] = new_client
|
||||
_LOGGER.debug("New session: %s", machine_identifier)
|
||||
new_plex_clients.append(new_client)
|
||||
@@ -202,20 +221,20 @@ def setup_plexserver(
|
||||
if client.session is None:
|
||||
client.force_idle()
|
||||
|
||||
client.set_availability(client.machine_identifier
|
||||
in available_client_ids
|
||||
or client.machine_identifier
|
||||
in plex_sessions)
|
||||
client.set_availability(
|
||||
client.machine_identifier in available_client_ids
|
||||
or client.machine_identifier in plex_sessions
|
||||
)
|
||||
|
||||
if client not in new_plex_clients:
|
||||
client.schedule_update_ha_state()
|
||||
|
||||
if not config.get(CONF_REMOVE_UNAVAILABLE_CLIENTS) \
|
||||
or client.available:
|
||||
if not config.get(CONF_REMOVE_UNAVAILABLE_CLIENTS) or client.available:
|
||||
continue
|
||||
|
||||
if (dt_util.utcnow() - client.marked_unavailable) >= \
|
||||
(config.get(CONF_CLIENT_REMOVE_INTERVAL)):
|
||||
if (dt_util.utcnow() - client.marked_unavailable) >= (
|
||||
config.get(CONF_CLIENT_REMOVE_INTERVAL)
|
||||
):
|
||||
hass.add_job(client.async_remove())
|
||||
clients_to_remove.append(client.machine_identifier)
|
||||
|
||||
@@ -231,48 +250,44 @@ def request_configuration(host, hass, config, add_entities_callback):
|
||||
configurator = hass.components.configurator
|
||||
# We got an error if this method is called while we are configuring
|
||||
if host in _CONFIGURING:
|
||||
configurator.notify_errors(_CONFIGURING[host],
|
||||
'Failed to register, please try again.')
|
||||
configurator.notify_errors(
|
||||
_CONFIGURING[host], "Failed to register, please try again."
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
def plex_configuration_callback(data):
|
||||
"""Handle configuration changes."""
|
||||
setup_plexserver(
|
||||
host, data.get('token'),
|
||||
cv.boolean(data.get('has_ssl')),
|
||||
cv.boolean(data.get('do_not_verify')),
|
||||
hass, config, add_entities_callback
|
||||
host,
|
||||
data.get("token"),
|
||||
cv.boolean(data.get("has_ssl")),
|
||||
cv.boolean(data.get("do_not_verify")),
|
||||
hass,
|
||||
config,
|
||||
add_entities_callback,
|
||||
)
|
||||
|
||||
_CONFIGURING[host] = configurator.request_config(
|
||||
'Plex Media Server',
|
||||
"Plex Media Server",
|
||||
plex_configuration_callback,
|
||||
description='Enter the X-Plex-Token',
|
||||
entity_picture='/static/images/logo_plex_mediaserver.png',
|
||||
submit_caption='Confirm',
|
||||
fields=[{
|
||||
'id': 'token',
|
||||
'name': 'X-Plex-Token',
|
||||
'type': ''
|
||||
}, {
|
||||
'id': 'has_ssl',
|
||||
'name': 'Use SSL',
|
||||
'type': ''
|
||||
}, {
|
||||
'id': 'do_not_verify_ssl',
|
||||
'name': 'Do not verify SSL',
|
||||
'type': ''
|
||||
}])
|
||||
description="Enter the X-Plex-Token",
|
||||
entity_picture="/static/images/logo_plex_mediaserver.png",
|
||||
submit_caption="Confirm",
|
||||
fields=[
|
||||
{"id": "token", "name": "X-Plex-Token", "type": ""},
|
||||
{"id": "has_ssl", "name": "Use SSL", "type": ""},
|
||||
{"id": "do_not_verify_ssl", "name": "Do not verify SSL", "type": ""},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class PlexClient(MediaPlayerDevice):
|
||||
"""Representation of a Plex device."""
|
||||
|
||||
def __init__(self, config, device, session, plex_sessions,
|
||||
update_devices):
|
||||
def __init__(self, config, device, session, plex_sessions, update_devices):
|
||||
"""Initialize the Plex device."""
|
||||
self._app_name = ''
|
||||
self._app_name = ""
|
||||
self._device = None
|
||||
self._available = False
|
||||
self._marked_unavailable = None
|
||||
@@ -281,9 +296,9 @@ class PlexClient(MediaPlayerDevice):
|
||||
self._is_player_available = False
|
||||
self._player = None
|
||||
self._machine_identifier = None
|
||||
self._make = ''
|
||||
self._make = ""
|
||||
self._name = None
|
||||
self._player_state = 'idle'
|
||||
self._player_state = "idle"
|
||||
self._previous_volume_level = 1 # Used in fake muting
|
||||
self._session = None
|
||||
self._session_type = None
|
||||
@@ -335,7 +350,7 @@ class PlexClient(MediaPlayerDevice):
|
||||
self._media_series_title = None
|
||||
|
||||
# Clear library Name
|
||||
self._app_name = ''
|
||||
self._app_name = ""
|
||||
|
||||
def refresh(self, device, session):
|
||||
"""Refresh key device data."""
|
||||
@@ -351,29 +366,32 @@ class PlexClient(MediaPlayerDevice):
|
||||
try:
|
||||
device_url = self._device.url("/")
|
||||
except plexapi.exceptions.BadRequest:
|
||||
device_url = '127.0.0.1'
|
||||
device_url = "127.0.0.1"
|
||||
if "127.0.0.1" in device_url:
|
||||
self._device.proxyThroughServer()
|
||||
self._session = None
|
||||
self._machine_identifier = self._device.machineIdentifier
|
||||
self._name = NAME_FORMAT.format(self._device.title or
|
||||
DEVICE_DEFAULT_NAME)
|
||||
self._device_protocol_capabilities = (
|
||||
self._device.protocolCapabilities)
|
||||
self._name = NAME_FORMAT.format(self._device.title or DEVICE_DEFAULT_NAME)
|
||||
self._device_protocol_capabilities = self._device.protocolCapabilities
|
||||
|
||||
# set valid session, preferring device session
|
||||
if self._device.machineIdentifier in self.plex_sessions:
|
||||
self._session = self.plex_sessions.get(
|
||||
self._device.machineIdentifier, [None, None])[0]
|
||||
self._device.machineIdentifier, [None, None]
|
||||
)[0]
|
||||
|
||||
if self._session:
|
||||
if self._device is not None and\
|
||||
self._device.machineIdentifier is not None and \
|
||||
self._session.players:
|
||||
if (
|
||||
self._device is not None
|
||||
and self._device.machineIdentifier is not None
|
||||
and self._session.players
|
||||
):
|
||||
self._is_player_available = True
|
||||
self._player = [p for p in self._session.players
|
||||
if p.machineIdentifier ==
|
||||
self._device.machineIdentifier][0]
|
||||
self._player = [
|
||||
p
|
||||
for p in self._session.players
|
||||
if p.machineIdentifier == self._device.machineIdentifier
|
||||
][0]
|
||||
self._name = NAME_FORMAT.format(self._player.title)
|
||||
self._player_state = self._player.state
|
||||
self._session_username = self._session.usernames[0]
|
||||
@@ -385,10 +403,9 @@ class PlexClient(MediaPlayerDevice):
|
||||
position = int(self._session.viewOffset / 1000)
|
||||
now = dt_util.utcnow()
|
||||
if self._media_position is not None:
|
||||
pos_diff = (position - self._media_position)
|
||||
pos_diff = position - self._media_position
|
||||
time_diff = now - self._media_position_updated_at
|
||||
if (pos_diff != 0 and
|
||||
abs(time_diff.total_seconds() - pos_diff) > 5):
|
||||
if pos_diff != 0 and abs(time_diff.total_seconds() - pos_diff) > 5:
|
||||
self._media_position_updated_at = now
|
||||
self._media_position = position
|
||||
else:
|
||||
@@ -396,8 +413,7 @@ class PlexClient(MediaPlayerDevice):
|
||||
self._media_position = position
|
||||
|
||||
self._media_content_id = self._session.ratingKey
|
||||
self._media_content_rating = getattr(
|
||||
self._session, 'contentRating', None)
|
||||
self._media_content_rating = getattr(self._session, "contentRating", None)
|
||||
|
||||
self._set_player_state()
|
||||
|
||||
@@ -408,21 +424,27 @@ class PlexClient(MediaPlayerDevice):
|
||||
self._media_title = self._session.title
|
||||
# media type
|
||||
self._set_media_type()
|
||||
self._app_name = self._session.section().title \
|
||||
if self._session.section() is not None else ''
|
||||
self._app_name = (
|
||||
self._session.section().title
|
||||
if self._session.section() is not None
|
||||
else ""
|
||||
)
|
||||
self._set_media_image()
|
||||
else:
|
||||
self._session_type = None
|
||||
|
||||
def _set_media_image(self):
|
||||
thumb_url = self._session.thumbUrl
|
||||
if (self.media_content_type is MEDIA_TYPE_TVSHOW
|
||||
and not self.config.get(CONF_USE_EPISODE_ART)):
|
||||
if self.media_content_type is MEDIA_TYPE_TVSHOW and not self.config.get(
|
||||
CONF_USE_EPISODE_ART
|
||||
):
|
||||
thumb_url = self._session.url(self._session.grandparentThumb)
|
||||
|
||||
if thumb_url is None:
|
||||
_LOGGER.debug("Using media art because media thumb "
|
||||
"was not found: %s", self.entity_id)
|
||||
_LOGGER.debug(
|
||||
"Using media art because media thumb " "was not found: %s",
|
||||
self.entity_id,
|
||||
)
|
||||
thumb_url = self.session.url(self._session.art)
|
||||
|
||||
self._media_image_url = thumb_url
|
||||
@@ -439,10 +461,10 @@ class PlexClient(MediaPlayerDevice):
|
||||
self._available = available
|
||||
|
||||
def _set_player_state(self):
|
||||
if self._player_state == 'playing':
|
||||
if self._player_state == "playing":
|
||||
self._is_player_active = True
|
||||
self._state = STATE_PLAYING
|
||||
elif self._player_state == 'paused':
|
||||
elif self._player_state == "paused":
|
||||
self._is_player_active = True
|
||||
self._state = STATE_PAUSED
|
||||
elif self.device:
|
||||
@@ -453,13 +475,12 @@ class PlexClient(MediaPlayerDevice):
|
||||
self._state = STATE_OFF
|
||||
|
||||
def _set_media_type(self):
|
||||
if self._session_type in ['clip', 'episode']:
|
||||
if self._session_type in ["clip", "episode"]:
|
||||
self._media_content_type = MEDIA_TYPE_TVSHOW
|
||||
|
||||
# season number (00)
|
||||
if callable(self._session.season):
|
||||
self._media_season = str(
|
||||
(self._session.season()).index).zfill(2)
|
||||
self._media_season = str((self._session.season()).index).zfill(2)
|
||||
elif self._session.parentIndex is not None:
|
||||
self._media_season = self._session.parentIndex.zfill(2)
|
||||
else:
|
||||
@@ -470,13 +491,12 @@ class PlexClient(MediaPlayerDevice):
|
||||
if self._session.index is not None:
|
||||
self._media_episode = str(self._session.index).zfill(2)
|
||||
|
||||
elif self._session_type == 'movie':
|
||||
elif self._session_type == "movie":
|
||||
self._media_content_type = MEDIA_TYPE_MOVIE
|
||||
if self._session.year is not None and \
|
||||
self._media_title is not None:
|
||||
self._media_title += ' (' + str(self._session.year) + ')'
|
||||
if self._session.year is not None and self._media_title is not None:
|
||||
self._media_title += " (" + str(self._session.year) + ")"
|
||||
|
||||
elif self._session_type == 'track':
|
||||
elif self._session_type == "track":
|
||||
self._media_content_type = MEDIA_TYPE_MUSIC
|
||||
self._media_album_name = self._session.parentTitle
|
||||
self._media_album_artist = self._session.grandparentTitle
|
||||
@@ -484,8 +504,10 @@ class PlexClient(MediaPlayerDevice):
|
||||
self._media_artist = self._session.originalTitle
|
||||
# use album artist if track artist is missing
|
||||
if self._media_artist is None:
|
||||
_LOGGER.debug("Using album artist because track artist "
|
||||
"was not found: %s", self.entity_id)
|
||||
_LOGGER.debug(
|
||||
"Using album artist because track artist " "was not found: %s",
|
||||
self.entity_id,
|
||||
)
|
||||
self._media_artist = self._media_album_artist
|
||||
|
||||
def force_idle(self):
|
||||
@@ -548,9 +570,9 @@ class PlexClient(MediaPlayerDevice):
|
||||
def _active_media_plexapi_type(self):
|
||||
"""Get the active media type required by PlexAPI commands."""
|
||||
if self.media_content_type is MEDIA_TYPE_MUSIC:
|
||||
return 'music'
|
||||
return "music"
|
||||
|
||||
return 'video'
|
||||
return "video"
|
||||
|
||||
@property
|
||||
def media_content_id(self):
|
||||
@@ -560,15 +582,17 @@ class PlexClient(MediaPlayerDevice):
|
||||
@property
|
||||
def media_content_type(self):
|
||||
"""Return the content type of current playing media."""
|
||||
if self._session_type == 'clip':
|
||||
_LOGGER.debug("Clip content type detected, "
|
||||
"compatibility may vary: %s", self.entity_id)
|
||||
if self._session_type == "clip":
|
||||
_LOGGER.debug(
|
||||
"Clip content type detected, " "compatibility may vary: %s",
|
||||
self.entity_id,
|
||||
)
|
||||
return MEDIA_TYPE_TVSHOW
|
||||
if self._session_type == 'episode':
|
||||
if self._session_type == "episode":
|
||||
return MEDIA_TYPE_TVSHOW
|
||||
if self._session_type == 'movie':
|
||||
if self._session_type == "movie":
|
||||
return MEDIA_TYPE_MOVIE
|
||||
if self._session_type == 'track':
|
||||
if self._session_type == "track":
|
||||
return MEDIA_TYPE_MUSIC
|
||||
|
||||
return None
|
||||
@@ -646,10 +670,16 @@ class PlexClient(MediaPlayerDevice):
|
||||
|
||||
# force show all controls
|
||||
if self.config.get(CONF_SHOW_ALL_CONTROLS):
|
||||
return (SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK |
|
||||
SUPPORT_NEXT_TRACK | SUPPORT_STOP |
|
||||
SUPPORT_VOLUME_SET | SUPPORT_PLAY |
|
||||
SUPPORT_TURN_OFF | SUPPORT_VOLUME_MUTE)
|
||||
return (
|
||||
SUPPORT_PAUSE
|
||||
| SUPPORT_PREVIOUS_TRACK
|
||||
| SUPPORT_NEXT_TRACK
|
||||
| SUPPORT_STOP
|
||||
| SUPPORT_VOLUME_SET
|
||||
| SUPPORT_PLAY
|
||||
| SUPPORT_TURN_OFF
|
||||
| SUPPORT_VOLUME_MUTE
|
||||
)
|
||||
|
||||
# only show controls when we know what device is connecting
|
||||
if not self._make:
|
||||
@@ -657,42 +687,57 @@ class PlexClient(MediaPlayerDevice):
|
||||
# no mute support
|
||||
if self.make.lower() == "shield android tv":
|
||||
_LOGGER.debug(
|
||||
"Shield Android TV client detected, disabling mute "
|
||||
"controls: %s", self.entity_id)
|
||||
return (SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK |
|
||||
SUPPORT_NEXT_TRACK | SUPPORT_STOP |
|
||||
SUPPORT_VOLUME_SET | SUPPORT_PLAY |
|
||||
SUPPORT_TURN_OFF)
|
||||
"Shield Android TV client detected, disabling mute " "controls: %s",
|
||||
self.entity_id,
|
||||
)
|
||||
return (
|
||||
SUPPORT_PAUSE
|
||||
| SUPPORT_PREVIOUS_TRACK
|
||||
| SUPPORT_NEXT_TRACK
|
||||
| SUPPORT_STOP
|
||||
| SUPPORT_VOLUME_SET
|
||||
| SUPPORT_PLAY
|
||||
| SUPPORT_TURN_OFF
|
||||
)
|
||||
# Only supports play,pause,stop (and off which really is stop)
|
||||
if self.make.lower().startswith("tivo"):
|
||||
_LOGGER.debug(
|
||||
"Tivo client detected, only enabling pause, play, "
|
||||
"stop, and off controls: %s", self.entity_id)
|
||||
return (SUPPORT_PAUSE | SUPPORT_PLAY | SUPPORT_STOP |
|
||||
SUPPORT_TURN_OFF)
|
||||
"stop, and off controls: %s",
|
||||
self.entity_id,
|
||||
)
|
||||
return SUPPORT_PAUSE | SUPPORT_PLAY | SUPPORT_STOP | SUPPORT_TURN_OFF
|
||||
# Not all devices support playback functionality
|
||||
# Playback includes volume, stop/play/pause, etc.
|
||||
if self.device and 'playback' in self._device_protocol_capabilities:
|
||||
return (SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK |
|
||||
SUPPORT_NEXT_TRACK | SUPPORT_STOP |
|
||||
SUPPORT_VOLUME_SET | SUPPORT_PLAY |
|
||||
SUPPORT_TURN_OFF | SUPPORT_VOLUME_MUTE)
|
||||
if self.device and "playback" in self._device_protocol_capabilities:
|
||||
return (
|
||||
SUPPORT_PAUSE
|
||||
| SUPPORT_PREVIOUS_TRACK
|
||||
| SUPPORT_NEXT_TRACK
|
||||
| SUPPORT_STOP
|
||||
| SUPPORT_VOLUME_SET
|
||||
| SUPPORT_PLAY
|
||||
| SUPPORT_TURN_OFF
|
||||
| SUPPORT_VOLUME_MUTE
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
def set_volume_level(self, volume):
|
||||
"""Set volume level, range 0..1."""
|
||||
if self.device and 'playback' in self._device_protocol_capabilities:
|
||||
self.device.setVolume(
|
||||
int(volume * 100), self._active_media_plexapi_type)
|
||||
if self.device and "playback" in self._device_protocol_capabilities:
|
||||
self.device.setVolume(int(volume * 100), self._active_media_plexapi_type)
|
||||
self._volume_level = volume # store since we can't retrieve
|
||||
self.update_devices()
|
||||
|
||||
@property
|
||||
def volume_level(self):
|
||||
"""Return the volume level of the client (0..1)."""
|
||||
if (self._is_player_active and self.device and
|
||||
'playback' in self._device_protocol_capabilities):
|
||||
if (
|
||||
self._is_player_active
|
||||
and self.device
|
||||
and "playback" in self._device_protocol_capabilities
|
||||
):
|
||||
return self._volume_level
|
||||
|
||||
@property
|
||||
@@ -708,8 +753,7 @@ class PlexClient(MediaPlayerDevice):
|
||||
- On mute, store volume and set volume to 0
|
||||
- On unmute, set volume to previously stored volume
|
||||
"""
|
||||
if not (self.device and
|
||||
'playback' in self._device_protocol_capabilities):
|
||||
if not (self.device and "playback" in self._device_protocol_capabilities):
|
||||
return
|
||||
|
||||
self._volume_muted = mute
|
||||
@@ -721,19 +765,19 @@ class PlexClient(MediaPlayerDevice):
|
||||
|
||||
def media_play(self):
|
||||
"""Send play command."""
|
||||
if self.device and 'playback' in self._device_protocol_capabilities:
|
||||
if self.device and "playback" in self._device_protocol_capabilities:
|
||||
self.device.play(self._active_media_plexapi_type)
|
||||
self.update_devices()
|
||||
|
||||
def media_pause(self):
|
||||
"""Send pause command."""
|
||||
if self.device and 'playback' in self._device_protocol_capabilities:
|
||||
if self.device and "playback" in self._device_protocol_capabilities:
|
||||
self.device.pause(self._active_media_plexapi_type)
|
||||
self.update_devices()
|
||||
|
||||
def media_stop(self):
|
||||
"""Send stop command."""
|
||||
if self.device and 'playback' in self._device_protocol_capabilities:
|
||||
if self.device and "playback" in self._device_protocol_capabilities:
|
||||
self.device.stop(self._active_media_plexapi_type)
|
||||
self.update_devices()
|
||||
|
||||
@@ -744,62 +788,67 @@ class PlexClient(MediaPlayerDevice):
|
||||
|
||||
def media_next_track(self):
|
||||
"""Send next track command."""
|
||||
if self.device and 'playback' in self._device_protocol_capabilities:
|
||||
if self.device and "playback" in self._device_protocol_capabilities:
|
||||
self.device.skipNext(self._active_media_plexapi_type)
|
||||
self.update_devices()
|
||||
|
||||
def media_previous_track(self):
|
||||
"""Send previous track command."""
|
||||
if self.device and 'playback' in self._device_protocol_capabilities:
|
||||
if self.device and "playback" in self._device_protocol_capabilities:
|
||||
self.device.skipPrevious(self._active_media_plexapi_type)
|
||||
self.update_devices()
|
||||
|
||||
def play_media(self, media_type, media_id, **kwargs):
|
||||
"""Play a piece of media."""
|
||||
if not (self.device and
|
||||
'playback' in self._device_protocol_capabilities):
|
||||
if not (self.device and "playback" in self._device_protocol_capabilities):
|
||||
return
|
||||
|
||||
src = json.loads(media_id)
|
||||
|
||||
media = None
|
||||
if media_type == 'MUSIC':
|
||||
media = self.device.server.library.section(
|
||||
src['library_name']).get(src['artist_name']).album(
|
||||
src['album_name']).get(src['track_name'])
|
||||
elif media_type == 'EPISODE':
|
||||
if media_type == "MUSIC":
|
||||
media = (
|
||||
self.device.server.library.section(src["library_name"])
|
||||
.get(src["artist_name"])
|
||||
.album(src["album_name"])
|
||||
.get(src["track_name"])
|
||||
)
|
||||
elif media_type == "EPISODE":
|
||||
media = self._get_tv_media(
|
||||
src['library_name'], src['show_name'],
|
||||
src['season_number'], src['episode_number'])
|
||||
elif media_type == 'PLAYLIST':
|
||||
media = self.device.server.playlist(src['playlist_name'])
|
||||
elif media_type == 'VIDEO':
|
||||
media = self.device.server.library.section(
|
||||
src['library_name']).get(src['video_name'])
|
||||
src["library_name"],
|
||||
src["show_name"],
|
||||
src["season_number"],
|
||||
src["episode_number"],
|
||||
)
|
||||
elif media_type == "PLAYLIST":
|
||||
media = self.device.server.playlist(src["playlist_name"])
|
||||
elif media_type == "VIDEO":
|
||||
media = self.device.server.library.section(src["library_name"]).get(
|
||||
src["video_name"]
|
||||
)
|
||||
|
||||
import plexapi.playlist
|
||||
if (media and media_type == 'EPISODE' and
|
||||
isinstance(media, plexapi.playlist.Playlist)):
|
||||
# delete episode playlist after being loaded into a play queue
|
||||
self._client_play_media(media=media, delete=True,
|
||||
shuffle=src['shuffle'])
|
||||
elif media:
|
||||
self._client_play_media(media=media, shuffle=src['shuffle'])
|
||||
|
||||
def _get_tv_media(self, library_name, show_name, season_number,
|
||||
episode_number):
|
||||
if (
|
||||
media
|
||||
and media_type == "EPISODE"
|
||||
and isinstance(media, plexapi.playlist.Playlist)
|
||||
):
|
||||
# delete episode playlist after being loaded into a play queue
|
||||
self._client_play_media(media=media, delete=True, shuffle=src["shuffle"])
|
||||
elif media:
|
||||
self._client_play_media(media=media, shuffle=src["shuffle"])
|
||||
|
||||
def _get_tv_media(self, library_name, show_name, season_number, episode_number):
|
||||
"""Find TV media and return a Plex media object."""
|
||||
target_season = None
|
||||
target_episode = None
|
||||
|
||||
show = self.device.server.library.section(library_name).get(
|
||||
show_name)
|
||||
show = self.device.server.library.section(library_name).get(show_name)
|
||||
|
||||
if not season_number:
|
||||
playlist_name = "{} - {} Episodes".format(
|
||||
self.entity_id, show_name)
|
||||
return self.device.server.createPlaylist(
|
||||
playlist_name, show.episodes())
|
||||
playlist_name = "{} - {} Episodes".format(self.entity_id, show_name)
|
||||
return self.device.server.createPlaylist(playlist_name, show.episodes())
|
||||
|
||||
for season in show.seasons():
|
||||
if int(season.seasonNumber) == int(season_number):
|
||||
@@ -807,16 +856,21 @@ class PlexClient(MediaPlayerDevice):
|
||||
break
|
||||
|
||||
if target_season is None:
|
||||
_LOGGER.error("Season not found: %s\\%s - S%sE%s", library_name,
|
||||
show_name,
|
||||
str(season_number).zfill(2),
|
||||
str(episode_number).zfill(2))
|
||||
_LOGGER.error(
|
||||
"Season not found: %s\\%s - S%sE%s",
|
||||
library_name,
|
||||
show_name,
|
||||
str(season_number).zfill(2),
|
||||
str(episode_number).zfill(2),
|
||||
)
|
||||
else:
|
||||
if not episode_number:
|
||||
playlist_name = "{} - {} Season {} Episodes".format(
|
||||
self.entity_id, show_name, str(season_number))
|
||||
self.entity_id, show_name, str(season_number)
|
||||
)
|
||||
return self.device.server.createPlaylist(
|
||||
playlist_name, target_season.episodes())
|
||||
playlist_name, target_season.episodes()
|
||||
)
|
||||
|
||||
for episode in target_season.episodes():
|
||||
if int(episode.index) == int(episode_number):
|
||||
@@ -824,47 +878,57 @@ class PlexClient(MediaPlayerDevice):
|
||||
break
|
||||
|
||||
if target_episode is None:
|
||||
_LOGGER.error("Episode not found: %s\\%s - S%sE%s",
|
||||
library_name, show_name,
|
||||
str(season_number).zfill(2),
|
||||
str(episode_number).zfill(2))
|
||||
_LOGGER.error(
|
||||
"Episode not found: %s\\%s - S%sE%s",
|
||||
library_name,
|
||||
show_name,
|
||||
str(season_number).zfill(2),
|
||||
str(episode_number).zfill(2),
|
||||
)
|
||||
|
||||
return target_episode
|
||||
|
||||
def _client_play_media(self, media, delete=False, **params):
|
||||
"""Instruct Plex client to play a piece of media."""
|
||||
if not (self.device and
|
||||
'playback' in self._device_protocol_capabilities):
|
||||
if not (self.device and "playback" in self._device_protocol_capabilities):
|
||||
_LOGGER.error("Client cannot play media: %s", self.entity_id)
|
||||
return
|
||||
|
||||
import plexapi.playqueue
|
||||
|
||||
playqueue = plexapi.playqueue.PlayQueue.create(
|
||||
self.device.server, media, **params)
|
||||
self.device.server, media, **params
|
||||
)
|
||||
|
||||
# Delete dynamic playlists used to build playqueue (ex. play tv season)
|
||||
if delete:
|
||||
media.delete()
|
||||
|
||||
server_url = self.device.server.baseurl.split(':')
|
||||
self.device.sendCommand('playback/playMedia', **dict({
|
||||
'machineIdentifier': self.device.server.machineIdentifier,
|
||||
'address': server_url[1].strip('/'),
|
||||
'port': server_url[-1],
|
||||
'key': media.key,
|
||||
'containerKey':
|
||||
'/playQueues/{}?window=100&own=1'.format(
|
||||
playqueue.playQueueID),
|
||||
}, **params))
|
||||
server_url = self.device.server.baseurl.split(":")
|
||||
self.device.sendCommand(
|
||||
"playback/playMedia",
|
||||
**dict(
|
||||
{
|
||||
"machineIdentifier": self.device.server.machineIdentifier,
|
||||
"address": server_url[1].strip("/"),
|
||||
"port": server_url[-1],
|
||||
"key": media.key,
|
||||
"containerKey": "/playQueues/{}?window=100&own=1".format(
|
||||
playqueue.playQueueID
|
||||
),
|
||||
},
|
||||
**params,
|
||||
),
|
||||
)
|
||||
self.update_devices()
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the scene state attributes."""
|
||||
attr = {
|
||||
'media_content_rating': self._media_content_rating,
|
||||
'session_username': self._session_username,
|
||||
'media_library_name': self._app_name
|
||||
"media_content_rating": self._media_content_rating,
|
||||
"session_username": self._session_username,
|
||||
"media_library_name": self._app_name,
|
||||
}
|
||||
|
||||
return attr
|
||||
@@ -5,35 +5,44 @@ import voluptuous as vol
|
||||
|
||||
from homeassistant.components.switch import PLATFORM_SCHEMA
|
||||
from homeassistant.const import (
|
||||
CONF_NAME, CONF_USERNAME, CONF_PASSWORD, CONF_HOST, CONF_PORT, CONF_TOKEN,
|
||||
CONF_SSL, CONF_VERIFY_SSL)
|
||||
CONF_NAME,
|
||||
CONF_USERNAME,
|
||||
CONF_PASSWORD,
|
||||
CONF_HOST,
|
||||
CONF_PORT,
|
||||
CONF_TOKEN,
|
||||
CONF_SSL,
|
||||
CONF_VERIFY_SSL,
|
||||
)
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONF_SERVER = 'server'
|
||||
CONF_SERVER = "server"
|
||||
|
||||
DEFAULT_HOST = 'localhost'
|
||||
DEFAULT_NAME = 'Plex'
|
||||
DEFAULT_HOST = "localhost"
|
||||
DEFAULT_NAME = "Plex"
|
||||
DEFAULT_PORT = 32400
|
||||
DEFAULT_SSL = False
|
||||
DEFAULT_VERIFY_SSL = True
|
||||
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
vol.Optional(CONF_PASSWORD): cv.string,
|
||||
vol.Optional(CONF_TOKEN): cv.string,
|
||||
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
|
||||
vol.Optional(CONF_SERVER): cv.string,
|
||||
vol.Optional(CONF_USERNAME): cv.string,
|
||||
vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean,
|
||||
vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean,
|
||||
})
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
||||
{
|
||||
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
vol.Optional(CONF_PASSWORD): cv.string,
|
||||
vol.Optional(CONF_TOKEN): cv.string,
|
||||
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
|
||||
vol.Optional(CONF_SERVER): cv.string,
|
||||
vol.Optional(CONF_USERNAME): cv.string,
|
||||
vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean,
|
||||
vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
@@ -46,17 +55,32 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
plex_port = config.get(CONF_PORT)
|
||||
plex_token = config.get(CONF_TOKEN)
|
||||
|
||||
plex_url = '{}://{}:{}'.format('https' if config.get(CONF_SSL) else 'http',
|
||||
plex_host, plex_port)
|
||||
plex_url = "{}://{}:{}".format(
|
||||
"https" if config.get(CONF_SSL) else "http", plex_host, plex_port
|
||||
)
|
||||
|
||||
import plexapi.exceptions
|
||||
|
||||
try:
|
||||
add_entities([PlexSensor(
|
||||
name, plex_url, plex_user, plex_password, plex_server,
|
||||
plex_token, config.get(CONF_VERIFY_SSL))], True)
|
||||
except (plexapi.exceptions.BadRequest, plexapi.exceptions.Unauthorized,
|
||||
plexapi.exceptions.NotFound) as error:
|
||||
add_entities(
|
||||
[
|
||||
PlexSensor(
|
||||
name,
|
||||
plex_url,
|
||||
plex_user,
|
||||
plex_password,
|
||||
plex_server,
|
||||
plex_token,
|
||||
config.get(CONF_VERIFY_SSL),
|
||||
)
|
||||
],
|
||||
True,
|
||||
)
|
||||
except (
|
||||
plexapi.exceptions.BadRequest,
|
||||
plexapi.exceptions.Unauthorized,
|
||||
plexapi.exceptions.NotFound,
|
||||
) as error:
|
||||
_LOGGER.error(error)
|
||||
return
|
||||
|
||||
@@ -64,8 +88,16 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
class PlexSensor(Entity):
|
||||
"""Representation of a Plex now playing sensor."""
|
||||
|
||||
def __init__(self, name, plex_url, plex_user, plex_password,
|
||||
plex_server, plex_token, verify_ssl):
|
||||
def __init__(
|
||||
self,
|
||||
name,
|
||||
plex_url,
|
||||
plex_user,
|
||||
plex_password,
|
||||
plex_server,
|
||||
plex_token,
|
||||
verify_ssl,
|
||||
):
|
||||
"""Initialize the sensor."""
|
||||
from plexapi.myplex import MyPlexAccount
|
||||
from plexapi.server import PlexServer
|
||||
@@ -121,7 +153,7 @@ class PlexSensor(Entity):
|
||||
now_playing_user = "{0} - {1}".format(user, device)
|
||||
now_playing_title = ""
|
||||
|
||||
if sess.TYPE == 'episode':
|
||||
if sess.TYPE == "episode":
|
||||
# example:
|
||||
# "Supernatural (2005) - S01 · E13 - Route 666"
|
||||
season_title = sess.grandparentTitle
|
||||
@@ -131,18 +163,18 @@ class PlexSensor(Entity):
|
||||
if sess.index is not None:
|
||||
season_episode += " · E{0}".format(sess.index)
|
||||
episode_title = sess.title
|
||||
now_playing_title = "{0} - {1} - {2}".format(season_title,
|
||||
season_episode,
|
||||
episode_title)
|
||||
elif sess.TYPE == 'track':
|
||||
now_playing_title = "{0} - {1} - {2}".format(
|
||||
season_title, season_episode, episode_title
|
||||
)
|
||||
elif sess.TYPE == "track":
|
||||
# example:
|
||||
# "Billy Talent - Afraid of Heights - Afraid of Heights"
|
||||
track_artist = sess.grandparentTitle
|
||||
track_album = sess.parentTitle
|
||||
track_title = sess.title
|
||||
now_playing_title = "{0} - {1} - {2}".format(track_artist,
|
||||
track_album,
|
||||
track_title)
|
||||
now_playing_title = "{0} - {1} - {2}".format(
|
||||
track_artist, track_album, track_title
|
||||
)
|
||||
else:
|
||||
# example:
|
||||
# "picture_of_last_summer_camp (2015)"
|
||||
|
||||
Reference in new issue
Block a user