Exemplo n.º 1
0
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
Exemplo n.º 2
0
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
Exemplo n.º 3
0
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
Exemplo n.º 4
0
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
Exemplo n.º 5
0
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
Exemplo n.º 6
0
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
Exemplo n.º 7
0
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