Add ability to play plex media as the non-primary user (#122039)

* Adds ability to play media as the non-primary user

* Add return type for set function
This commit is contained in:
Ian 2024-09-08 06:42:26 -07:00 committed by GitHub
parent 99a50fe874
commit aa8c4a6eb7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 42 additions and 0 deletions

View File

@ -2,6 +2,7 @@
from __future__ import annotations
from copy import copy
import logging
import ssl
import time
@ -664,3 +665,14 @@ class PlexServer:
def sensor_attributes(self):
"""Return active session information for use in activity sensor."""
return {x.sensor_user: x.sensor_title for x in self.active_sessions.values()}
def set_plex_server(self, plex_server: PlexServer) -> None:
"""Set the PlexServer instance."""
self._plex_server = plex_server
def switch_user(self, username: str) -> PlexServer:
"""Return a shallow copy of a PlexServer as the provided user."""
new_server = copy(self)
new_server.set_plex_server(self.plex_server.switchUser(username))
return new_server

View File

@ -161,6 +161,11 @@ def process_plex_payload(
if not plex_server:
plex_server = get_plex_server(hass)
if isinstance(content, dict):
if plex_user := content.pop("username", None):
_LOGGER.debug("Switching to Plex user: %s", plex_user)
plex_server = plex_server.switch_user(plex_user)
if content_type == "station":
if not supports_playqueues:
raise HomeAssistantError("Plex stations are not supported on this device")

View File

@ -57,6 +57,31 @@ async def test_media_lookups(
)
assert "Media for key 123 not found" in str(excinfo.value)
# Search with a different specified username
with (
patch(
"plexapi.library.LibrarySection.search",
__qualname__="search",
) as search,
patch(
"plexapi.myplex.MyPlexAccount.user",
__qualname__="user",
) as plex_account_user,
):
plex_account_user.return_value.get_token.return_value = "token"
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: media_player_id,
ATTR_MEDIA_CONTENT_TYPE: MediaType.EPISODE,
ATTR_MEDIA_CONTENT_ID: '{"library_name": "TV Shows", "show_name": "TV Show", "username": "Kids"}',
},
True,
)
search.assert_called_with(**{"show.title": "TV Show", "libtype": "show"})
plex_account_user.assert_called_with("Kids")
# TV show searches
with pytest.raises(MediaNotFound) as excinfo:
await hass.services.async_call(