def library_payload(coordinator): """ Create response payload to describe contents of a specific library. Used by async_browse_media. """ library_info = BrowseMedia( media_class=MEDIA_CLASS_DIRECTORY, media_content_id="library", media_content_type="library", title="Media Library", can_play=False, can_expand=True, children=[], ) library = { MEDIA_TYPE_APPS: "Apps", MEDIA_TYPE_CHANNELS: "Channels", } for item in [{"title": name, "type": type_} for type_, name in library.items()]: if ( item["type"] == MEDIA_TYPE_CHANNELS and coordinator.data.info.device_type != "tv" ): continue library_info.children.append( item_payload( {"title": item["title"], "type": item["type"]}, coordinator, ) ) if all( child.media_content_type == MEDIA_TYPE_APPS for child in library_info.children ): library_info.children_media_class = MEDIA_CLASS_APP elif all( child.media_content_type == MEDIA_TYPE_CHANNELS for child in library_info.children ): library_info.children_media_class = MEDIA_CLASS_CHANNEL else: library_info.children_media_class = MEDIA_CLASS_DIRECTORY return library_info
def library_payload(*, can_play_artist): """ Create response payload to describe contents of a specific library. Used by async_browse_media. """ library_info = { "title": "Media Library", "media_class": MEDIA_CLASS_DIRECTORY, "media_content_id": "library", "media_content_type": MEDIA_PLAYER_PREFIX + "library", "can_play": False, "can_expand": True, "children": [], } for item in [{"name": n, "type": t} for t, n in LIBRARY_MAP.items()]: library_info["children"].append( item_payload( { "name": item["name"], "type": item["type"], "uri": item["type"] }, can_play_artist=can_play_artist, )) response = BrowseMedia(**library_info) response.children_media_class = MEDIA_CLASS_DIRECTORY return response
def playlists_payload(): """Create response payload for all available playlists.""" playlists_info = {**PLAYLISTS_BROWSE_PAYLOAD, "children": []} for playlist in entity.plex_server.playlists(): try: playlists_info["children"].append(item_payload(playlist)) except UnknownMediaType: continue response = BrowseMedia(**playlists_info) response.children_media_class = MEDIA_CLASS_PLAYLIST return response
async def build_item_response(media_library, payload): """Create response payload for the provided media query.""" # print(payload) search_id = payload["search_id"] search_type = payload["search_type"] hass = media_library._hass thumbnail = None title = None media = None media_class = MEDIA_CLASS_DIRECTORY can_play = False can_expand = True children = [] base_url = get_url(hass) is_library = 'library_' in search_type properties = ["thumbnail"] if is_library: # 读取配置目录 path = hass.config.path("media/ha_cloud_music") # 获取所有文件 music_list = media_library.api_music.get_local_media_list(search_type) for item in music_list: children.append( item_payload( { "label": item['name'], "type": 'music', "songid": item['url'] }, media_library)) title = search_type.replace('library_', '') media_class = MEDIA_CLASS_MUSIC can_play = True can_expand = False response = BrowseMedia( media_class=media_class, media_content_id=search_id, media_content_type=search_type, title=title, can_play=can_play, can_expand=can_expand, children=children, thumbnail=thumbnail, ) if is_library: response.children_media_class = MEDIA_CLASS_MUSIC else: response.calculate_children_class() return response
async def ais_spotify_library(hass, media_content_type, media_content_id) -> BrowseMedia: """Create response payload to describe contents of a specific library.""" if hass.services.has_service("ais_spotify_service", "get_favorites"): if media_content_id == "ais_spotify": library_info = { "title": "Spotify", "media_class": MEDIA_CLASS_DIRECTORY, "media_content_id": "ais_spotify", "media_content_type": "library", "can_play": False, "can_expand": True, "children": [], } for item in [{ "name": n, "type": t } for t, n in SPOTIFY_LIBRARY_MAP.items()]: library_info["children"].append( spotify_item_payload({ "name": item["name"], "type": item["type"], "uri": "ais_spotify/" + item["type"], })) response = BrowseMedia(**library_info) response.children_media_class = MEDIA_CLASS_DIRECTORY return response else: spotify_data = hass.data["ais_spotify_service"] spotify, user = spotify_data.refresh_spotify_instance() payload = { "media_content_type": media_content_type, "media_content_id": media_content_id, } return spotify_build_item_response(spotify=spotify, user=user, payload=payload) else: raise BrowseError( "AIS - dodaj Spotify zgodnie z instrukcją na stronie ai-speaker.com" )
def server_payload(plex_server): """Create response payload to describe libraries of the Plex server.""" server_info = BrowseMedia( title=plex_server.friendly_name, media_class=MEDIA_CLASS_DIRECTORY, media_content_id=plex_server.machine_identifier, media_content_type="server", can_play=False, can_expand=True, ) server_info.children = [] server_info.children_media_class = MEDIA_CLASS_DIRECTORY server_info.children.append(special_library_payload(server_info, "On Deck")) server_info.children.append(special_library_payload(server_info, "Recently Added")) for library in plex_server.library.sections(): if library.type == "photo": continue server_info.children.append(library_section_payload(library)) server_info.children.append(BrowseMedia(**PLAYLISTS_BROWSE_PAYLOAD)) return server_info
def playlists_payload(): """Create response payload for all available playlists.""" playlists_info = { "title": "Playlists", "media_class": MEDIA_CLASS_DIRECTORY, "media_content_id": generate_plex_uri(server_id, "all"), "media_content_type": "playlists", "can_play": False, "can_expand": True, "children": [], } for playlist in plex_server.playlists(): if playlist.playlistType != "audio" and platform == "sonos": continue try: playlists_info["children"].append(item_payload(playlist)) except UnknownMediaType: continue response = BrowseMedia(**playlists_info) response.children_media_class = MEDIA_CLASS_PLAYLIST return response
async def build_item_response(media_library, payload, get_thumbnail_url=None): """Create response payload for the provided media query.""" search_id = payload["search_id"] search_type = payload["search_type"] _, title, media = await get_media_info(media_library, search_id, search_type) thumbnail = await get_thumbnail_url(search_type, search_id) if media is None: return None children = await asyncio.gather( *[item_payload(item, get_thumbnail_url) for item in media]) if search_type in (MEDIA_TYPE_TVSHOW, MEDIA_TYPE_MOVIE) and search_id == "": children.sort(key=lambda x: x.title.replace("The ", "", 1), reverse=False) response = BrowseMedia( media_class=CONTAINER_TYPES_SPECIFIC_MEDIA_CLASS.get( search_type, MEDIA_CLASS_DIRECTORY), media_content_id=search_id, media_content_type=search_type, title=title, can_play=search_type in PLAYABLE_MEDIA_TYPES and search_id, can_expand=True, children=children, thumbnail=thumbnail, ) if search_type == "library_music": response.children_media_class = MEDIA_CLASS_MUSIC else: response.calculate_children_class() return response
async def build_item_response(media_library, payload): """Create response payload for the provided media query.""" search_id = payload["search_id"] search_type = payload["search_type"] thumbnail = None title = None media = None query = {"properties": ["thumbnail"]} # pylint: disable=protected-access if search_type == MEDIA_TYPE_ALBUM: if search_id: query.update({"filter": {"albumid": int(search_id)}}) query["properties"].extend( ["albumid", "artist", "duration", "album", "track"] ) album = await media_library._server.AudioLibrary.GetAlbumDetails( {"albumid": int(search_id), "properties": ["thumbnail"]} ) thumbnail = media_library.thumbnail_url( album["albumdetails"].get("thumbnail") ) title = album["albumdetails"]["label"] media = await media_library._server.AudioLibrary.GetSongs(query) media = media.get("songs") else: media = await media_library._server.AudioLibrary.GetAlbums(query) media = media.get("albums") title = "Albums" elif search_type == MEDIA_TYPE_ARTIST: if search_id: query.update({"filter": {"artistid": int(search_id)}}) media = await media_library._server.AudioLibrary.GetAlbums(query) media = media.get("albums") artist = await media_library._server.AudioLibrary.GetArtistDetails( {"artistid": int(search_id), "properties": ["thumbnail"]} ) thumbnail = media_library.thumbnail_url( artist["artistdetails"].get("thumbnail") ) title = artist["artistdetails"]["label"] else: media = await media_library._server.AudioLibrary.GetArtists(query) media = media.get("artists") title = "Artists" elif search_type == "library_music": library = {MEDIA_TYPE_ALBUM: "Albums", MEDIA_TYPE_ARTIST: "Artists"} media = [{"label": name, "type": type_} for type_, name in library.items()] title = "Music Library" elif search_type == MEDIA_TYPE_MOVIE: media = await media_library._server.VideoLibrary.GetMovies(query) media = media.get("movies") title = "Movies" elif search_type == MEDIA_TYPE_TVSHOW: if search_id: media = await media_library._server.VideoLibrary.GetSeasons( { "tvshowid": int(search_id), "properties": ["thumbnail", "season", "tvshowid"], } ) media = media.get("seasons") tvshow = await media_library._server.VideoLibrary.GetTVShowDetails( {"tvshowid": int(search_id), "properties": ["thumbnail"]} ) thumbnail = media_library.thumbnail_url( tvshow["tvshowdetails"].get("thumbnail") ) title = tvshow["tvshowdetails"]["label"] else: media = await media_library._server.VideoLibrary.GetTVShows(query) media = media.get("tvshows") title = "TV Shows" elif search_type == MEDIA_TYPE_SEASON: tv_show_id, season_id = search_id.split("/", 1) media = await media_library._server.VideoLibrary.GetEpisodes( { "tvshowid": int(tv_show_id), "season": int(season_id), "properties": ["thumbnail", "tvshowid", "seasonid"], } ) media = media.get("episodes") if media: season = await media_library._server.VideoLibrary.GetSeasonDetails( {"seasonid": int(media[0]["seasonid"]), "properties": ["thumbnail"]} ) thumbnail = media_library.thumbnail_url( season["seasondetails"].get("thumbnail") ) title = season["seasondetails"]["label"] elif search_type == MEDIA_TYPE_CHANNEL: media = await media_library._server.PVR.GetChannels( { "channelgroupid": "alltv", "properties": ["thumbnail", "channeltype", "channel", "broadcastnow"], } ) media = media.get("channels") title = "Channels" if media is None: return None children = [] for item in media: try: children.append(item_payload(item, media_library)) except UnknownMediaType: pass response = BrowseMedia( media_class=CONTAINER_TYPES_SPECIFIC_MEDIA_CLASS.get( search_type, MEDIA_CLASS_DIRECTORY ), media_content_id=search_id, media_content_type=search_type, title=title, can_play=search_type in PLAYABLE_MEDIA_TYPES and search_id, can_expand=True, children=children, thumbnail=thumbnail, ) if search_type == "library_music": response.children_media_class = MEDIA_CLASS_MUSIC else: response.calculate_children_class() return response
def _media_library_payload(self, payload): """Create response payload to describe contents of a specific library.""" source = None try: payload["media_content_type"] payload["media_content_id"] except KeyError as err: _LOGGER.error("Missing type or uri for media item payload: %s", payload) raise MissingMediaInformation from err library_info = dict( media_class=MEDIA_CLASS_DIRECTORY, media_content_id="library", media_content_type="library", title="Media Library", can_play=False, can_expand=True, children=[], ) library_info.update(payload) if payload["media_content_id"] == "library": library_items = self.client.library.browse(None) library_info["title"] = "Media Library" else: source = payload["media_content_id"].partition(":")[0] library_items = self.client.library.browse( payload["media_content_id"]) extra_info = fetch_media_info(payload["media_content_type"], payload["media_content_id"]) library_info.update(extra_info) image = self.client.library.get_images( [payload["media_content_id"]]) if (payload["media_content_id"] in image and len(image[payload["media_content_id"]]) > 0): library_info["thumbnail"] = self._media_item_image_url( source, image[payload["media_content_id"]][0].uri) children_uri = [] for item in library_items: library_info["children"].append( self._media_item_payload({ "name": item.name, "type": item.type, "uri": item.uri })) children_uri.append(item.uri) if source == "spotify": # Spotify thumbnail lookup is throttled s = 10 else: s = 1000 uri_set = [ children_uri[r * s:(r + 1) * s] for r in range((len(children_uri) + s - 1) // s) ] images = dict() for s in uri_set: images.update(self.client.library.get_images(s)) if len(images.keys()) > 0: for item in library_info["children"]: if (item.media_content_id in images and len(images[item.media_content_id]) > 0): item.thumbnail = self._media_item_image_url( source, images[item.media_content_id][0].uri) library_info["can_play"] = (library_info["media_content_type"] in PLAYABLE_MEDIA_TYPES) if payload["media_content_id"] in CACHE_ROSETTA: library_info["title"] = CACHE_ROSETTA[payload["media_content_id"]] r = BrowseMedia(**library_info) try: r.children_media_class = extra_info["children_media_class"] except: r.children_media_class = MEDIA_CLASS_DIRECTORY return r
async def build_item_response(ytmusicplayer, payload): """Create response payload for the provided media query.""" search_id = payload[SEARCH_ID] search_type = payload[SEARCH_TYPE] media_library = ytmusicplayer._api hass = ytmusicplayer.hass children = [] thumbnail = None title = None media = None sort_list = ytmusicplayer._sortBrowser p1 = datetime.datetime.now() _LOGGER.debug("- build_item_response for: " + search_type) if search_type == LIB_PLAYLIST: # playlist OVERVIEW -> lists playlists media = await hass.async_add_executor_job(media_library.get_library_playlists, BROWSER_LIMIT) title = LIB_PLAYLIST_TITLE # single playlist for item in media: children.append(BrowseMedia( title = f"{item['title']}", # noqa: E251 media_class = MEDIA_CLASS_PLAYLIST, # noqa: E251 media_content_type = MEDIA_TYPE_PLAYLIST, # noqa: E251 media_content_id = f"{item['playlistId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == MEDIA_TYPE_PLAYLIST: # single playlist -> lists tracks media = await hass.async_add_executor_job(media_library.get_playlist, search_id, BROWSER_LIMIT) title = media['title'] for item in media['tracks']: item_title = f"{item['title']}" if("artists" in item): artist = "" if(isinstance(item["artists"], str)): artist = item["artists"] elif(isinstance(item["artists"], list)): artist = item["artists"][0]["name"] if(artist): item_title = artist + " - " + item_title thumbnail = '' if 'thumbnails' in item: if isinstance(item['thumbnails'], list): thumbnail = item['thumbnails'][-1]['url'] children.append(BrowseMedia( title = item_title, # noqa: E251 media_class = MEDIA_CLASS_TRACK, # noqa: E251 media_content_type = MEDIA_TYPE_TRACK, # noqa: E251 media_content_id = f"{item['videoId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = thumbnail, # noqa: E251 )) elif search_type == LIB_ALBUM: # LIB! album OVERVIEW, not uploaded -> lists albums media = await hass.async_add_executor_job(media_library.get_library_albums, BROWSER_LIMIT) title = LIB_ALBUM_TITLE for item in media: children.append(BrowseMedia( title = f"{item['title']}", # noqa: E251 media_class = MEDIA_CLASS_ALBUM, # noqa: E251 media_content_type = MEDIA_TYPE_ALBUM, # noqa: E251 media_content_id = f"{item['browseId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == MEDIA_TYPE_ALBUM: # single album (NOT uploaded) -> lists tracks res = await hass.async_add_executor_job(media_library.get_album, search_id) media = res['tracks'] title = res['title'] thumbnail = res['thumbnails'][-1]['url'] # here to expose it also for the header for item in media: children.append(BrowseMedia( title = f"{item['title']}", # noqa: E251 media_class = MEDIA_CLASS_TRACK, # noqa: E251 media_content_type = MEDIA_TYPE_TRACK, # noqa: E251 media_content_id = f"{item['videoId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = thumbnail, # noqa: E251 )) elif search_type == LIB_TRACKS: # liked songs (direct list, NOT uploaded) -> lists tracks media = await hass.async_add_executor_job(lambda: media_library.get_library_songs(limit=BROWSER_LIMIT)) title = LIB_TRACKS_TITLE for item in media: item_title = f"{item['title']}" if("artists" in item): artist = "" if(isinstance(item["artists"], str)): artist = item["artists"] elif(isinstance(item["artists"], list)): artist = item["artists"][0]["name"] if(artist): item_title = artist + " - " + item_title children.append(BrowseMedia( title = item_title, # noqa: E251 media_class = MEDIA_CLASS_TRACK, # noqa: E251 media_content_type = MEDIA_TYPE_TRACK, # noqa: E251 media_content_id = f"{item['videoId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == HISTORY: # history songs (direct list) -> lists tracks media = await hass.async_add_executor_job(media_library.get_history) search_id = HISTORY title = HISTORY_TITLE for item in media: item_title = f"{item['title']}" if("artists" in item): artist = "" if(isinstance(item["artists"], str)): artist = item["artists"] elif(isinstance(item["artists"], list)): artist = item["artists"][0]["name"] if(artist): item_title = artist + " - " + item_title children.append(BrowseMedia( title = item_title, # noqa: E251 media_class = MEDIA_CLASS_TRACK, # noqa: E251 media_content_type = MEDIA_TYPE_TRACK, # noqa: E251 media_content_id = f"{item['videoId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == USER_TRACKS: # list all uploaded songs -> lists tracks media = await hass.async_add_executor_job(media_library.get_library_upload_songs, BROWSER_LIMIT) search_id = USER_TRACKS title = USER_TRACKS_TITLE for item in media: item_title = f"{item['title']}" if("artist" in item): artist = "" if(isinstance(item["artist"], str)): artist = item["artist"] elif(isinstance(item["artist"], list)): artist = item["artist"][0]["name"] if(artist): item_title = artist + " - " + item_title children.append(BrowseMedia( title = item_title, # noqa: E251 media_class = MEDIA_CLASS_TRACK, # noqa: E251 media_content_type = MEDIA_TYPE_TRACK, # noqa: E251 media_content_id = f"{item['videoId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == USER_ALBUMS: # uploaded album overview!! -> lists user albums media = await hass.async_add_executor_job(media_library.get_library_upload_albums, BROWSER_LIMIT) title = USER_ALBUMS_TITLE for item in media: children.append(BrowseMedia( title = f"{item['title']}", # noqa: E251 media_class = MEDIA_CLASS_ALBUM, # noqa: E251 media_content_type = USER_ALBUM, # noqa: E251 media_content_id = f"{item['browseId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == USER_ALBUM: # single uploaded album -> lists tracks res = await hass.async_add_executor_job(media_library.get_library_upload_album, search_id) media = res['tracks'] title = res['title'] for item in media: try: thumbnail = item['thumbnails'][-1]['url'] except: thumbnail = "" children.append(BrowseMedia( title = f"{item['title']}", # noqa: E251 media_class = MEDIA_CLASS_TRACK, # noqa: E251 media_content_type = MEDIA_TYPE_TRACK, # noqa: E251 media_content_id = f"{item['videoId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = thumbnail, # noqa: E251 )) elif search_type == USER_ARTISTS: # with S media = await hass.async_add_executor_job(media_library.get_library_upload_artists, BROWSER_LIMIT) title = USER_ARTISTS_TITLE for item in media: children.append(BrowseMedia( title = f"{item['artist']}", # noqa: E251 media_class = MEDIA_CLASS_ARTIST, # noqa: E251 media_content_type = USER_ARTIST, # noqa: E251 media_content_id = f"{item['browseId']}", # noqa: E251 can_play = False, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == USER_ARTISTS_2: # list all artists now, but follow up will be the albums of that artist media = await hass.async_add_executor_job(media_library.get_library_upload_artists, BROWSER_LIMIT) title = USER_ARTISTS_2_TITLE for item in media: children.append(BrowseMedia( title = f"{item['artist']}", # noqa: E251 media_class = MEDIA_CLASS_ARTIST, # noqa: E251 media_content_type = USER_ARTIST_2, # noqa: E251 media_content_id = f"{item['browseId']}", # noqa: E251 can_play = False, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == USER_ARTIST: # without S media = await hass.async_add_executor_job(media_library.get_library_upload_artist, search_id, BROWSER_LIMIT) title = USER_ARTIST_TITLE if(isinstance(media, list)): if('artist' in media[0]): if(isinstance(media[0]['artist'], list)): if('name' in media[0]['artist'][0]): title = media[0]['artist'][0]['name'] for item in media: if("artists" in item): artist = "" if(isinstance(item["artists"], str)): artist = item["artists"] elif(isinstance(item["artists"], list)): artist = item["artists"][0]["name"] if(artist): title = artist + " - " + title children.append(BrowseMedia( title = f"{item['title']}", # noqa: E251 media_class = MEDIA_CLASS_TRACK, # noqa: E251 media_content_type = MEDIA_TYPE_TRACK, # noqa: E251 media_content_id = f"{item['videoId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == USER_ARTIST_2: # list each album of an uploaded artists only once .. next will be uploaded album view 'USER_ALBUM' media_all = await hass.async_add_executor_job(media_library.get_library_upload_artist, search_id, BROWSER_LIMIT) title = USER_ARTIST_2_TITLE media = list() for item in media_all: if('album' in item): if('name' in item['album']): if(all(item['album']['name'] != a['title'] for a in media)): media.append({ 'type': 'user_album', 'browseId': item['album']['id'], 'title': item['album']['name'], 'thumbnails': item['thumbnails'] }) if('artist' in media_all[0]): if(isinstance(media_all[0]['artist'], list)): if('name' in media_all[0]['artist'][0]): title = "Uploaded albums of " + media_all[0]['artist'][0]['name'] for item in media: children.append(BrowseMedia( title = f"{item['title']}", # noqa: E251 media_class = MEDIA_CLASS_ALBUM, # noqa: E251 media_content_type = USER_ALBUM, # noqa: E251 media_content_id = f"{item['browseId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == SEARCH: title = SEARCH_TITLE if ytmusicplayer._search is not None: media_all = await hass.async_add_executor_job(lambda: media_library.search(query=ytmusicplayer._search.get('query', ""), filter=ytmusicplayer._search.get('filter', None), limit=int(ytmusicplayer._search.get('limit', 20)))) if(ytmusicplayer._search.get('filter', None) is not None): helper = {} else: helper = {'song': "Track: ", 'playlist': "Playlist: ", 'album': "Album: ", 'artist': "Artist"} for a in media_all: if(a['resultType'] == 'song'): children.append(BrowseMedia( title = helper.get(a['resultType'], "") + a['title'], # noqa: E251 media_class = MEDIA_CLASS_TRACK, # noqa: E251 media_content_type = MEDIA_TYPE_TRACK, # noqa: E251 media_content_id = a['videoId'], # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = a['thumbnails'][-1]['url'], # noqa: E251 )) elif(a['resultType'] == 'playlist'): children.append(BrowseMedia( title = helper.get(a['resultType'], "") + a['title'], # noqa: E251 media_class = MEDIA_CLASS_PLAYLIST, # noqa: E251 media_content_type = MEDIA_TYPE_PLAYLIST, # noqa: E251 media_content_id = f"{a['browseId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = a['thumbnails'][-1]['url'], # noqa: E251 )) elif(a['resultType'] == 'album'): children.append(BrowseMedia( title = helper.get(a['resultType'], "") + a['title'], # noqa: E251 media_class = MEDIA_CLASS_ALBUM, # noqa: E251 media_content_type = MEDIA_TYPE_ALBUM, # noqa: E251 media_content_id = f"{a['browseId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = a['thumbnails'][-1]['url'], # noqa: E251 )) elif(a['resultType'] == 'artist'): children.append(BrowseMedia( title = helper.get(a['resultType'], "") + a['artist'], # noqa: E251 media_class = MEDIA_CLASS_ARTIST, # noqa: E251 media_content_type = MEDIA_TYPE_ARTIST, # noqa: E251 media_content_id = f"{a['browseId']}", # noqa: E251 can_play = False, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = a['thumbnails'][-1]['url'], # noqa: E251 )) else: # video / artists / uploads are currently ignored continue # _LOGGER.debug("search entry end") elif search_type == MEDIA_TYPE_ARTIST: media_all = await hass.async_add_executor_job(media_library.get_artist, search_id) helper = {'song': "Track: ", 'playlist': "Playlist: ", 'album': "Album: ", 'artist': "Artist"} if('singles' in media_all): for a in media_all['singles']['results']: children.append(BrowseMedia( title = helper.get('song', "") + a['title'], # noqa: E251 media_class = MEDIA_CLASS_ALBUM, # noqa: E251 media_content_type = MEDIA_TYPE_ALBUM, # noqa: E251 media_content_id = a['browseId'], # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = a['thumbnails'][-1]['url'], # noqa: E251 )) if('albums' in media_all): for a in media_all['albums']['results']: children.append(BrowseMedia( title = helper.get('album', "") + a['title'], # noqa: E251 media_class = MEDIA_CLASS_ALBUM, # noqa: E251 media_content_type = MEDIA_TYPE_ALBUM, # noqa: E251 media_content_id = f"{a['browseId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = a['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == MOOD_OVERVIEW: media_all = await hass.async_add_executor_job(lambda: media_library.get_mood_categories()) title = MOOD_TITLE for cap in media_all: for e in media_all[cap]: children.append(BrowseMedia( title = f"{cap} - {e['title']}", # noqa: E251 media_class = MEDIA_CLASS_PLAYLIST, # noqa: E251 media_content_type = MOOD_PLAYLISTS, # noqa: E251 media_content_id = e['params'], # noqa: E251 can_play = False, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = "", # noqa: E251 )) elif search_type == MOOD_PLAYLISTS: media = await hass.async_add_executor_job(lambda: media_library.get_mood_playlists(search_id)) title = MOOD_TITLE for item in media: children.append(BrowseMedia( title = f"{item['title']}", # noqa: E251 media_class = MEDIA_CLASS_PLAYLIST, # noqa: E251 media_content_type = MEDIA_TYPE_PLAYLIST, # noqa: E251 media_content_id = f"{item['playlistId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = True, # noqa: E251 thumbnail = item['thumbnails'][-1]['url'], # noqa: E251 )) elif search_type == CONF_RECEIVERS: title = PLAYER_TITLE for e, f in ytmusicplayer._friendly_speakersList.items(): children.append(BrowseMedia( title = f, # noqa: E251 media_class = MEDIA_CLASS_TV_SHOW, # noqa: E251 media_content_type = CONF_RECEIVERS, # noqa: E251 media_content_id = e, # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = "", # noqa: E251 )) elif search_type == CUR_PLAYLIST: title = CUR_PLAYLIST_TITLE sort_list = False i = 1 for item in ytmusicplayer._tracks: item_title = item["title"] if("artists" in item): artist = "" if(isinstance(item["artists"], str)): artist = item["artists"] elif(isinstance(item["artists"], list)): artist = item["artists"][0]["name"] if(artist): item_title = artist + " - " + item_title item_thumbnail = "" if 'thumbnails' in item: item_thumbnail = item['thumbnails'][-1]['url'] children.append(BrowseMedia( title = item_title, # noqa: E251 media_class = MEDIA_CLASS_TRACK, # noqa: E251 media_content_type = CUR_PLAYLIST_COMMAND, # noqa: E251 media_content_id = i, # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = item_thumbnail, # noqa: E251 )) i += 1 elif search_type == ALBUM_OF_TRACK: try: res = await hass.async_add_executor_job(lambda: media_library.get_album(ytmusicplayer._track_album_id)) sort_list = False media = res['tracks'] title = res['title'] # children.append(BrowseMedia( # title = f"All tracks", # media_class = MEDIA_CLASS_ALBUM, # media_content_type = MEDIA_TYPE_ALBUM, # media_content_id = ytmusicplayer._track_album_id, # can_play = True, # can_expand = False, # thumbnail = "", # )) for item in media: try: thumbnail = item['thumbnails'][-1]['url'] except: thumbnail = "" children.append(BrowseMedia( title = f"{item['title']}", # noqa: E251 media_class = MEDIA_CLASS_TRACK, # noqa: E251 media_content_type = MEDIA_TYPE_TRACK, # noqa: E251 media_content_id = f"{item['videoId']}", # noqa: E251 can_play = True, # noqa: E251 can_expand = False, # noqa: E251 thumbnail = thumbnail # noqa: E251 )) except: pass # ########################################### END ############### if sort_list: children.sort(key=lambda x: x.title, reverse=False) response = BrowseMedia( media_class=CONTAINER_TYPES_SPECIFIC_MEDIA_CLASS.get( search_type, MEDIA_CLASS_DIRECTORY ), media_content_id=search_id, media_content_type=search_type, title=title, can_play=search_type in PLAYABLE_MEDIA_TYPES and search_id, can_expand=True, children=children, thumbnail=thumbnail, ) if search_type == "library_music": response.children_media_class = MEDIA_CLASS_MUSIC else: response.calculate_children_class() t = (datetime.datetime.now() - p1).total_seconds() _LOGGER.debug("- Calc / grab time: " + str(t) + " sec") return response
async def build_item_response(media_library, payload): """Create response payload for the provided media query.""" search_id = payload["search_id"] search_type = payload["search_type"] thumbnail = None title = None media = None properties = ["thumbnail"] if search_type == MEDIA_TYPE_ALBUM: if search_id: album = await media_library.get_album_details( album_id=int(search_id), properties=properties) thumbnail = media_library.thumbnail_url( album["albumdetails"].get("thumbnail")) title = album["albumdetails"]["label"] media = await media_library.get_songs( album_id=int(search_id), properties=[ "albumid", "artist", "duration", "album", "thumbnail", "track", ], ) media = media.get("songs") else: media = await media_library.get_albums(properties=properties) media = media.get("albums") title = "Albums" elif search_type == MEDIA_TYPE_ARTIST: if search_id: media = await media_library.get_albums(artist_id=int(search_id), properties=properties) media = media.get("albums") artist = await media_library.get_artist_details( artist_id=int(search_id), properties=properties) thumbnail = media_library.thumbnail_url( artist["artistdetails"].get("thumbnail")) title = artist["artistdetails"]["label"] else: media = await media_library.get_artists(properties) media = media.get("artists") title = "Artists" elif search_type == "library_music": library = {MEDIA_TYPE_ALBUM: "Albums", MEDIA_TYPE_ARTIST: "Artists"} media = [{ "label": name, "type": type_ } for type_, name in library.items()] title = "Music Library" elif search_type == MEDIA_TYPE_MOVIE: media = await media_library.get_movies(properties) media = media.get("movies") title = "Movies" elif search_type == MEDIA_TYPE_TVSHOW: if search_id: media = await media_library.get_seasons( tv_show_id=int(search_id), properties=["thumbnail", "season", "tvshowid"], ) media = media.get("seasons") tvshow = await media_library.get_tv_show_details( tv_show_id=int(search_id), properties=properties) thumbnail = media_library.thumbnail_url( tvshow["tvshowdetails"].get("thumbnail")) title = tvshow["tvshowdetails"]["label"] else: media = await media_library.get_tv_shows(properties) media = media.get("tvshows") title = "TV Shows" elif search_type == MEDIA_TYPE_SEASON: tv_show_id, season_id = search_id.split("/", 1) media = await media_library.get_episodes( tv_show_id=int(tv_show_id), season_id=int(season_id), properties=["thumbnail", "tvshowid", "seasonid"], ) media = media.get("episodes") if media: season = await media_library.get_season_details( season_id=int(media[0]["seasonid"]), properties=properties) thumbnail = media_library.thumbnail_url( season["seasondetails"].get("thumbnail")) title = season["seasondetails"]["label"] elif search_type == MEDIA_TYPE_CHANNEL: media = await media_library.get_channels( channel_group_id="alltv", properties=["thumbnail", "channeltype", "channel", "broadcastnow"], ) media = media.get("channels") title = "Channels" if media is None: return None children = [] for item in media: try: children.append(item_payload(item, media_library)) except UnknownMediaType: pass response = BrowseMedia( media_class=CONTAINER_TYPES_SPECIFIC_MEDIA_CLASS.get( search_type, MEDIA_CLASS_DIRECTORY), media_content_id=search_id, media_content_type=search_type, title=title, can_play=search_type in PLAYABLE_MEDIA_TYPES and search_id, can_expand=True, children=children, thumbnail=thumbnail, ) if search_type == "library_music": response.children_media_class = MEDIA_CLASS_MUSIC else: response.calculate_children_class() return response
def build_item_response(spotify, user, payload): """Create response payload for the provided media query.""" media_content_type = payload["media_content_type"] media_content_id = payload["media_content_id"] title = None image = None if media_content_type == "current_user_playlists": media = spotify.current_user_playlists(limit=BROWSE_LIMIT) items = media.get("items", []) elif media_content_type == "current_user_followed_artists": media = spotify.current_user_followed_artists(limit=BROWSE_LIMIT) items = media.get("artists", {}).get("items", []) elif media_content_type == "current_user_saved_albums": media = spotify.current_user_saved_albums(limit=BROWSE_LIMIT) items = [item["album"] for item in media.get("items", [])] elif media_content_type == "current_user_saved_tracks": media = spotify.current_user_saved_tracks(limit=BROWSE_LIMIT) items = [item["track"] for item in media.get("items", [])] elif media_content_type == "current_user_saved_shows": media = spotify.current_user_saved_shows(limit=BROWSE_LIMIT) items = [item["show"] for item in media.get("items", [])] elif media_content_type == "current_user_recently_played": media = spotify.current_user_recently_played(limit=BROWSE_LIMIT) items = [item["track"] for item in media.get("items", [])] elif media_content_type == "current_user_top_artists": media = spotify.current_user_top_artists(limit=BROWSE_LIMIT) items = media.get("items", []) elif media_content_type == "current_user_top_tracks": media = spotify.current_user_top_tracks(limit=BROWSE_LIMIT) items = media.get("items", []) elif media_content_type == "featured_playlists": media = spotify.featured_playlists(country=user["country"], limit=BROWSE_LIMIT) items = media.get("playlists", {}).get("items", []) elif media_content_type == "categories": media = spotify.categories(country=user["country"], limit=BROWSE_LIMIT) items = media.get("categories", {}).get("items", []) elif media_content_type == "category_playlists": media = spotify.category_playlists( category_id=media_content_id, country=user["country"], limit=BROWSE_LIMIT, ) category = spotify.category(media_content_id, country=user["country"]) title = category.get("name") image = fetch_image_url(category, key="icons") items = media.get("playlists", {}).get("items", []) elif media_content_type == "new_releases": media = spotify.new_releases(country=user["country"], limit=BROWSE_LIMIT) items = media.get("albums", {}).get("items", []) elif media_content_type == MEDIA_TYPE_PLAYLIST: media = spotify.playlist(media_content_id) items = [item["track"] for item in media.get("tracks", {}).get("items", [])] elif media_content_type == MEDIA_TYPE_ALBUM: media = spotify.album(media_content_id) items = media.get("tracks", {}).get("items", []) elif media_content_type == MEDIA_TYPE_ARTIST: media = spotify.artist_albums(media_content_id, limit=BROWSE_LIMIT) artist = spotify.artist(media_content_id) title = artist.get("name") image = fetch_image_url(artist) items = media.get("items", []) elif media_content_type == MEDIA_TYPE_SHOW: media = spotify.show_episodes(media_content_id, limit=BROWSE_LIMIT) show = spotify.show(media_content_id) title = show.get("name") image = fetch_image_url(show) items = media.get("items", []) else: media = None items = [] if media is None: return None try: media_class = CONTENT_TYPE_MEDIA_CLASS[media_content_type] except KeyError: _LOGGER.debug("Unknown media type received: %s", media_content_type) return None if media_content_type == "categories": media_item = BrowseMedia( title=LIBRARY_MAP.get(media_content_id), media_class=media_class, media_content_id=media_content_id, media_content_type=media_content_type, can_play=False, can_expand=True, children=[], ) for item in items: try: item_id = item["id"] except KeyError: _LOGGER.debug("Missing id for media item: %s", item) continue media_item.children.append( BrowseMedia( title=item.get("name"), media_class=MEDIA_CLASS_PLAYLIST, media_content_id=item_id, media_content_type="category_playlists", thumbnail=fetch_image_url(item, key="icons"), can_play=False, can_expand=True, ) ) media_item.children_media_class = MEDIA_CLASS_GENRE return media_item if title is None: if "name" in media: title = media.get("name") else: title = LIBRARY_MAP.get(payload["media_content_id"]) params = { "title": title, "media_class": media_class, "media_content_id": media_content_id, "media_content_type": media_content_type, "can_play": media_content_type in PLAYABLE_MEDIA_TYPES, "children": [], "can_expand": True, } for item in items: try: params["children"].append(item_payload(item)) except (MissingMediaInformation, UnknownMediaType): continue if "images" in media: params["thumbnail"] = fetch_image_url(media) elif image: params["thumbnail"] = image return BrowseMedia(**params)
async def build_item_response(hass, media_library, payload): """Create response payload for the provided media query.""" search_id = payload["search_id"] search_type = payload["search_type"] thumbnail = None title = None media = None if search_type == LIB_PLAYLIST: # playlist OVERVIEW media = await hass.async_add_executor_job( media_library.get_library_playlists, BROWSER_LIMIT) title = "Library Playlists" # single playlist elif search_type == MEDIA_TYPE_PLAYLIST: res = await hass.async_add_executor_job(media_library.get_playlist, search_id, BROWSER_LIMIT) media = res['tracks'] title = res['title'] elif search_type == LIB_ALBUM: # album OVERVIEW media = await hass.async_add_executor_job( media_library.get_library_albums, BROWSER_LIMIT) title = "Library Albums" elif search_type == MEDIA_TYPE_ALBUM: # single album (NOT uploaded) res = await hass.async_add_executor_job(media_library.get_album, search_id) media = res['tracks'] title = res['title'] elif search_type == LIB_TRACKS: # liked songs (direct list, NOT uploaded) media = await hass.async_add_executor_job( media_library.get_library_songs) title = "Library Songs" elif search_type == HISTORY: # history songs (direct list) media = await hass.async_add_executor_job(media_library.get_history) search_id = HISTORY title = "Last played songs" elif search_type == USER_TRACKS: media = await hass.async_add_executor_job( media_library.get_library_upload_songs, BROWSER_LIMIT) search_id = USER_TRACKS title = "Uploaded songs" elif search_type == USER_ALBUMS: media = await hass.async_add_executor_job( media_library.get_library_upload_albums, BROWSER_LIMIT) for i in media: i['type'] = USER_ALBUM title = "Uploaded Albums" elif search_type == USER_ALBUM: res = await hass.async_add_executor_job( media_library.get_library_upload_album, search_id) media = res['tracks'] title = res['title'] elif search_type == USER_ARTISTS: media = await hass.async_add_executor_job( media_library.get_library_upload_artists, BROWSER_LIMIT) title = "Uploaded Artists" elif search_type == USER_ARTIST: media = await hass.async_add_executor_job( media_library.get_library_upload_artist, search_id) title = "Uploaded Artist" if (isinstance(media, list)): if ('artist' in media[0]): if (isinstance(media[0]['artist'], list)): if ('name' in media[0]['artist'][0]): title = media[0]['artist'][0]['name'] if media is None: return None children = [] for item in media: try: children.append(item_payload(item, media_library, search_type)) except UnknownMediaType: pass response = BrowseMedia( media_class=CONTAINER_TYPES_SPECIFIC_MEDIA_CLASS.get( search_type, MEDIA_CLASS_DIRECTORY), media_content_id=search_id, media_content_type=search_type, title=title, can_play=search_type in PLAYABLE_MEDIA_TYPES and search_id, can_expand=True, children=children, thumbnail=thumbnail, ) if search_type == "library_music": response.children_media_class = MEDIA_CLASS_MUSIC else: response.calculate_children_class() return response
async def build_item_response(hass, media_library, payload): """Create response payload for the provided media query.""" search_id = payload["search_id"] search_type = payload["search_type"] thumbnail = None title = None media = None p1 = datetime.datetime.now() _LOGGER.debug("- build_item_response for: " + search_type) if search_type == LIB_PLAYLIST: # playlist OVERVIEW media = await hass.async_add_executor_job( media_library.get_library_playlists, BROWSER_LIMIT) title = "Library Playlists" # single playlist elif search_type == MEDIA_TYPE_PLAYLIST: res = await hass.async_add_executor_job(media_library.get_playlist, search_id, BROWSER_LIMIT) media = res['tracks'] title = res['title'] elif search_type == LIB_ALBUM: # album OVERVIEW media = await hass.async_add_executor_job( media_library.get_library_albums, BROWSER_LIMIT) title = "Library Albums" elif search_type == MEDIA_TYPE_ALBUM: # single album (NOT uploaded) res = await hass.async_add_executor_job(media_library.get_album, search_id) media = res['tracks'] title = res['title'] elif search_type == LIB_TRACKS: # liked songs (direct list, NOT uploaded) media = await hass.async_add_executor_job( media_library.get_library_songs) title = "Library Songs" elif search_type == HISTORY: # history songs (direct list) media = await hass.async_add_executor_job(media_library.get_history) search_id = HISTORY title = "Last played songs" elif search_type == USER_TRACKS: media = await hass.async_add_executor_job( media_library.get_library_upload_songs, BROWSER_LIMIT) search_id = USER_TRACKS title = "Uploaded songs" elif search_type == USER_ALBUMS: media = await hass.async_add_executor_job( media_library.get_library_upload_albums, BROWSER_LIMIT) for i in media: i['type'] = USER_ALBUM title = "Uploaded Albums" elif search_type == USER_ALBUM: res = await hass.async_add_executor_job( media_library.get_library_upload_album, search_id) media = res['tracks'] title = res['title'] elif search_type == USER_ARTISTS: media = await hass.async_add_executor_job( media_library.get_library_upload_artists, BROWSER_LIMIT) title = "Uploaded Artists" elif search_type == USER_ARTISTS_2: # list all artists now, but follow up will be the albums of that artist media = await hass.async_add_executor_job( media_library.get_library_upload_artists, BROWSER_LIMIT) title = "Uploaded Artists -> Album" elif search_type == USER_ARTIST: media = await hass.async_add_executor_job( media_library.get_library_upload_artist, search_id, BROWSER_LIMIT) title = "Uploaded Artist" if (isinstance(media, list)): if ('artist' in media[0]): if (isinstance(media[0]['artist'], list)): if ('name' in media[0]['artist'][0]): title = media[0]['artist'][0]['name'] elif search_type == USER_ARTIST_2: # list each album of an uploaded artists only once .. next will be uploaded album view 'USER_ALBUM' media_all = await hass.async_add_executor_job( media_library.get_library_upload_artist, search_id, BROWSER_LIMIT) media = list() for item in media_all: if ('album' in item): if ('name' in item['album']): if (all(item['album']['name'] != a['title'] for a in media)): media.append({ 'type': 'user_album', 'browseId': item['album']['id'], 'title': item['album']['name'], 'thumbnails': item['thumbnails'] }) title = "Uploaded Album" if ('artist' in media_all[0]): if (isinstance(media_all[0]['artist'], list)): if ('name' in media_all[0]['artist'][0]): title = "Uploaded albums of " + media_all[0]['artist'][0][ 'name'] search_type = USER_ALBUMS if media is None: return None children = [] for item in media: try: children.append(item_payload(item, media_library, search_type)) except UnknownMediaType: pass children.sort(key=lambda x: x.title, reverse=False) response = BrowseMedia( media_class=CONTAINER_TYPES_SPECIFIC_MEDIA_CLASS.get( search_type, MEDIA_CLASS_DIRECTORY), media_content_id=search_id, media_content_type=search_type, title=title, can_play=search_type in PLAYABLE_MEDIA_TYPES and search_id, can_expand=True, children=children, thumbnail=thumbnail, ) if search_type == "library_music": response.children_media_class = MEDIA_CLASS_MUSIC else: response.calculate_children_class() t = (datetime.datetime.now() - p1).total_seconds() _LOGGER.debug("- Calc / grab time: " + str(t) + " sec") return response