Discover Plex clients using GDM (#39053)
This commit is contained in:
1 parent
72759d7501
commit
c63c253b7f
9 files changed
+207
-39
No files matched your search
@@ -1,10 +1,12 @@
|
||||
"""Support to embed Plex."""
|
||||
import asyncio
|
||||
import functools
|
||||
from functools import partial
|
||||
import json
|
||||
import logging
|
||||
|
||||
import plexapi.exceptions
|
||||
from plexapi.gdm import GDM
|
||||
from plexwebsocket import (
|
||||
SIGNAL_CONNECTION_STATE,
|
||||
SIGNAL_DATA,
|
||||
@@ -33,6 +35,7 @@ from homeassistant.core import callback
|
||||
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.helpers.debounce import Debouncer
|
||||
from homeassistant.helpers.dispatcher import (
|
||||
async_dispatcher_connect,
|
||||
async_dispatcher_send,
|
||||
@@ -43,6 +46,8 @@ from .const import (
|
||||
CONF_SERVER_IDENTIFIER,
|
||||
DISPATCHERS,
|
||||
DOMAIN as PLEX_DOMAIN,
|
||||
GDM_DEBOUNCER,
|
||||
GDM_SCANNER,
|
||||
PLATFORMS,
|
||||
PLATFORMS_COMPLETED,
|
||||
PLEX_SERVER_CONFIG,
|
||||
@@ -67,6 +72,16 @@ async def async_setup(hass, config):
|
||||
|
||||
await async_setup_services(hass)
|
||||
|
||||
gdm = hass.data[PLEX_DOMAIN][GDM_SCANNER] = GDM()
|
||||
|
||||
hass.data[PLEX_DOMAIN][GDM_DEBOUNCER] = Debouncer(
|
||||
hass,
|
||||
_LOGGER,
|
||||
cooldown=10,
|
||||
immediate=True,
|
||||
function=partial(gdm.scan, scan_for_clients=True),
|
||||
).async_call
|
||||
|
||||
return True
|
||||
|
||||
|
||||
@@ -143,10 +158,14 @@ async def async_setup_entry(hass, entry):
|
||||
|
||||
entry.add_update_listener(async_options_updated)
|
||||
|
||||
async def async_update_plex():
|
||||
await hass.data[PLEX_DOMAIN][GDM_DEBOUNCER]()
|
||||
await plex_server.async_update_platforms()
|
||||
|
||||
unsub = async_dispatcher_connect(
|
||||
hass,
|
||||
PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id),
|
||||
plex_server.async_update_platforms,
|
||||
async_update_plex,
|
||||
)
|
||||
hass.data[PLEX_DOMAIN][DISPATCHERS].setdefault(server_id, [])
|
||||
hass.data[PLEX_DOMAIN][DISPATCHERS][server_id].append(unsub)
|
||||
|
||||
@@ -13,6 +13,8 @@ PLEXTV_THROTTLE = 60
|
||||
|
||||
DEBOUNCE_TIMEOUT = 1
|
||||
DISPATCHERS = "dispatchers"
|
||||
GDM_DEBOUNCER = "gdm_debouncer"
|
||||
GDM_SCANNER = "gdm_scanner"
|
||||
PLATFORMS = frozenset(["media_player", "sensor"])
|
||||
PLATFORMS_COMPLETED = "platforms_completed"
|
||||
PLAYER_SOURCE = "player_source"
|
||||
|
||||
@@ -4,6 +4,7 @@ import ssl
|
||||
import time
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from plexapi.client import PlexClient
|
||||
from plexapi.exceptions import BadRequest, NotFound, Unauthorized
|
||||
import plexapi.myplex
|
||||
import plexapi.playqueue
|
||||
@@ -32,6 +33,8 @@ from .const import (
|
||||
CONF_USE_EPISODE_ART,
|
||||
DEBOUNCE_TIMEOUT,
|
||||
DEFAULT_VERIFY_SSL,
|
||||
DOMAIN,
|
||||
GDM_SCANNER,
|
||||
PLAYER_SOURCE,
|
||||
PLEX_NEW_MP_SIGNAL,
|
||||
PLEX_UPDATE_MEDIA_PLAYER_SIGNAL,
|
||||
@@ -84,7 +87,7 @@ class PlexServer:
|
||||
self._owner_username = None
|
||||
self._plextv_clients = None
|
||||
self._plextv_client_timestamp = 0
|
||||
self._plextv_device_cache = {}
|
||||
self._client_device_cache = {}
|
||||
self._use_plex_tv = self._token is not None
|
||||
self._version = None
|
||||
self.async_update_platforms = Debouncer(
|
||||
@@ -289,6 +292,9 @@ class PlexServer:
|
||||
return
|
||||
|
||||
def process_device(source, device):
|
||||
if device is None:
|
||||
return
|
||||
|
||||
self._known_idle.discard(device.machineIdentifier)
|
||||
available_clients.setdefault(device.machineIdentifier, {"device": device})
|
||||
available_clients[device.machineIdentifier].setdefault(
|
||||
@@ -321,13 +327,33 @@ class PlexServer:
|
||||
for device in devices:
|
||||
process_device("PMS", device)
|
||||
|
||||
def connect_to_client(source, baseurl, machine_identifier, name="Unknown"):
|
||||
"""Connect to a Plex client and return a PlexClient instance."""
|
||||
try:
|
||||
client = PlexClient(
|
||||
server=self._plex_server,
|
||||
baseurl=baseurl,
|
||||
token=self._plex_server.createToken(),
|
||||
)
|
||||
except requests.exceptions.ConnectionError:
|
||||
_LOGGER.error(
|
||||
"Direct client connection failed, will try again: %s (%s)",
|
||||
name,
|
||||
baseurl,
|
||||
)
|
||||
except Unauthorized:
|
||||
_LOGGER.error(
|
||||
"Direct client connection unauthorized, ignoring: %s (%s)",
|
||||
name,
|
||||
baseurl,
|
||||
)
|
||||
self._client_device_cache[machine_identifier] = None
|
||||
else:
|
||||
self._client_device_cache[client.machineIdentifier] = client
|
||||
process_device(source, client)
|
||||
|
||||
def connect_to_resource(resource):
|
||||
"""Connect to a plex.tv resource and return a Plex client."""
|
||||
client_id = resource.clientIdentifier
|
||||
if client_id in self._plextv_device_cache:
|
||||
return self._plextv_device_cache[client_id]
|
||||
|
||||
client = None
|
||||
try:
|
||||
client = resource.connect(timeout=3)
|
||||
_LOGGER.debug("plex.tv resource connection successful: %s", client)
|
||||
@@ -335,17 +361,33 @@ class PlexServer:
|
||||
_LOGGER.error("plex.tv resource connection failed: %s", resource.name)
|
||||
else:
|
||||
client.proxyThroughServer(value=False, server=self._plex_server)
|
||||
self._client_device_cache[client.machineIdentifier] = client
|
||||
process_device("plex.tv", client)
|
||||
|
||||
self._plextv_device_cache[client_id] = client
|
||||
return client
|
||||
def connect_new_clients():
|
||||
"""Create connections to newly discovered clients."""
|
||||
for gdm_entry in self.hass.data[DOMAIN][GDM_SCANNER].entries:
|
||||
machine_identifier = gdm_entry["data"]["Resource-Identifier"]
|
||||
if machine_identifier in self._client_device_cache:
|
||||
client = self._client_device_cache[machine_identifier]
|
||||
if client is not None:
|
||||
process_device("GDM", client)
|
||||
elif machine_identifier not in available_clients:
|
||||
baseurl = (
|
||||
f"http://{gdm_entry['from'][0]}:{gdm_entry['data']['Port']}"
|
||||
)
|
||||
name = gdm_entry["data"]["Name"]
|
||||
connect_to_client("GDM", baseurl, machine_identifier, name)
|
||||
|
||||
for plextv_client in plextv_clients:
|
||||
if plextv_client.clientIdentifier not in available_clients:
|
||||
device = await self.hass.async_add_executor_job(
|
||||
connect_to_resource, plextv_client
|
||||
)
|
||||
if device:
|
||||
process_device("plex.tv", device)
|
||||
for plextv_client in plextv_clients:
|
||||
if plextv_client.clientIdentifier in self._client_device_cache:
|
||||
client = self._client_device_cache[plextv_client.clientIdentifier]
|
||||
if client is not None:
|
||||
process_device("plex.tv", client)
|
||||
elif plextv_client.clientIdentifier not in available_clients:
|
||||
connect_to_resource(plextv_client)
|
||||
|
||||
await self.hass.async_add_executor_job(connect_new_clients)
|
||||
|
||||
for session in sessions:
|
||||
if session.TYPE == "photo":
|
||||
@@ -385,7 +427,7 @@ class PlexServer:
|
||||
for client_id in idle_clients:
|
||||
self.async_refresh_entity(client_id, None, None)
|
||||
self._known_idle.add(client_id)
|
||||
self._plextv_device_cache.pop(client_id, None)
|
||||
self._client_device_cache.pop(client_id, None)
|
||||
|
||||
if new_entity_configs:
|
||||
async_dispatcher_send(
|
||||
|
||||
Reference in new issue
Block a user