From 42f08d176686eedcd70700a97f3ae49ee6213ff7 Mon Sep 17 00:00:00 2001 From: sigma67 Date: Sun, 11 Jul 2021 18:39:40 +0200 Subject: [PATCH] add get_charts (#213) --- tests/test.py | 16 +++- ytmusicapi/mixins/browsing.py | 85 ------------------- ytmusicapi/mixins/explore.py | 142 ++++++++++++++++++++++++++++++++ ytmusicapi/parsers/__init__.py | 5 ++ ytmusicapi/parsers/browsing.py | 12 +-- ytmusicapi/parsers/explore.py | 65 +++++++++++++++ ytmusicapi/parsers/library.py | 4 +- ytmusicapi/parsers/playlists.py | 4 +- ytmusicapi/parsers/uploads.py | 2 +- ytmusicapi/ytmusic.py | 7 +- 10 files changed, 240 insertions(+), 102 deletions(-) create mode 100644 ytmusicapi/mixins/explore.py create mode 100644 ytmusicapi/parsers/explore.py diff --git a/tests/test.py b/tests/test.py index 2aa6e9c..2f915ec 100644 --- a/tests/test.py +++ b/tests/test.py @@ -133,6 +133,14 @@ class TestYTMusic(unittest.TestCase): self.assertIsNone(playlist["lyrics"]) self.assertRaises(Exception, self.yt.get_lyrics, playlist["lyrics"]) + def test_get_signatureTimestamp(self): + signatureTimestamp = self.yt.get_signatureTimestamp() + self.assertIsNotNone(signatureTimestamp) + + ############### + # EXPLORE + ############### + def test_get_mood_playlists(self): categories = self.yt.get_mood_categories() self.assertGreater(len(list(categories)), 0) @@ -141,9 +149,11 @@ class TestYTMusic(unittest.TestCase): playlists = self.yt.get_mood_playlists(categories[cat][0]["params"]) self.assertGreater(len(playlists), 0) - def test_get_signatureTimestamp(self): - signatureTimestamp = self.yt.get_signatureTimestamp() - self.assertIsNotNone(signatureTimestamp) + def test_get_charts(self): + charts = self.yt_auth.get_charts() + self.assertEqual(len(charts), 4) + charts = self.yt.get_charts(country='BE') + self.assertEqual(len(charts), 4) ############### # WATCH diff --git a/ytmusicapi/mixins/browsing.py b/ytmusicapi/mixins/browsing.py index e1cfeba..9789cbd 100644 --- a/ytmusicapi/mixins/browsing.py +++ b/ytmusicapi/mixins/browsing.py @@ -749,91 +749,6 @@ class BrowsingMixin: return lyrics - def get_mood_categories(self) -> Dict: - """ - Fetch "Moods & Genres" categories from YouTube Music. - - :return: Dictionary of sections and categories. - - Example:: - - { - 'For you': [ - { - 'params': 'ggMPOg1uX1ZwN0pHT2NBT1Fk', - 'title': '1980s' - }, - { - 'params': 'ggMPOg1uXzZQbDB5eThLRTQ3', - 'title': 'Feel Good' - }, - ... - ], - 'Genres': [ - { - 'params': 'ggMPOg1uXzVLbmZnaWI4STNs', - 'title': 'Dance & Electronic' - }, - { - 'params': 'ggMPOg1uX3NjZllsNGVEMkZo', - 'title': 'Decades' - }, - ... - ], - 'Moods & moments': [ - { - 'params': 'ggMPOg1uXzVuc0dnZlhpV3Ba', - 'title': 'Chill' - }, - { - 'params': 'ggMPOg1uX2ozUHlwbWM3ajNq', - 'title': 'Commute' - }, - ... - ], - } - - """ - sections = {} - response = self._send_request('browse', {'browseId': 'FEmusic_moods_and_genres'}) - for section in nav(response, SINGLE_COLUMN_TAB + SECTION_LIST): - title = nav(section, GRID + ['header', 'gridHeaderRenderer'] + TITLE_TEXT) - sections[title] = [] - for category in nav(section, GRID_ITEMS): - sections[title].append({ - "title": nav(category, CATEGORY_TITLE), - "params": nav(category, CATEGORY_PARAMS) - }) - - return sections - - def get_mood_playlists(self, params: str) -> List[Dict]: - """ - Retrieve a list of playlists for a given "Moods & Genres" category. - - :param params: params obtained by :py:func:`get_mood_categories` - :return: List of playlists in the format of :py:func:`get_library_playlists` - - """ - playlists = [] - response = self._send_request('browse', { - 'browseId': 'FEmusic_moods_and_genres_category', - 'params': params - }) - for section in nav(response, SINGLE_COLUMN_TAB + SECTION_LIST): - path = [] - if 'gridRenderer' in section: - path = GRID_ITEMS - elif 'musicCarouselShelfRenderer' in section: - path = ['musicCarouselShelfRenderer', 'contents'] - elif 'musicImmersiveCarouselShelfRenderer' in section: - path = ['musicImmersiveCarouselShelfRenderer', 'contents'] - if len(path): - results = nav(section, path) - playlists += parse_content_list(results, parse_playlist) - - return playlists - def get_basejs_url(self): """ Extract the URL for the `base.js` script from YouTube Music. diff --git a/ytmusicapi/mixins/explore.py b/ytmusicapi/mixins/explore.py new file mode 100644 index 0000000..a9d1bd4 --- /dev/null +++ b/ytmusicapi/mixins/explore.py @@ -0,0 +1,142 @@ +from ytmusicapi.parsers.explore import * + + +class ExploreMixin: + def get_mood_categories(self) -> Dict: + """ + Fetch "Moods & Genres" categories from YouTube Music. + + :return: Dictionary of sections and categories. + + Example:: + + { + 'For you': [ + { + 'params': 'ggMPOg1uX1ZwN0pHT2NBT1Fk', + 'title': '1980s' + }, + { + 'params': 'ggMPOg1uXzZQbDB5eThLRTQ3', + 'title': 'Feel Good' + }, + ... + ], + 'Genres': [ + { + 'params': 'ggMPOg1uXzVLbmZnaWI4STNs', + 'title': 'Dance & Electronic' + }, + { + 'params': 'ggMPOg1uX3NjZllsNGVEMkZo', + 'title': 'Decades' + }, + ... + ], + 'Moods & moments': [ + { + 'params': 'ggMPOg1uXzVuc0dnZlhpV3Ba', + 'title': 'Chill' + }, + { + 'params': 'ggMPOg1uX2ozUHlwbWM3ajNq', + 'title': 'Commute' + }, + ... + ], + } + + """ + sections = {} + response = self._send_request('browse', {'browseId': 'FEmusic_moods_and_genres'}) + for section in nav(response, SINGLE_COLUMN_TAB + SECTION_LIST): + title = nav(section, GRID + ['header', 'gridHeaderRenderer'] + TITLE_TEXT) + sections[title] = [] + for category in nav(section, GRID_ITEMS): + sections[title].append({ + "title": nav(category, CATEGORY_TITLE), + "params": nav(category, CATEGORY_PARAMS) + }) + + return sections + + def get_mood_playlists(self, params: str) -> List[Dict]: + """ + Retrieve a list of playlists for a given "Moods & Genres" category. + + :param params: params obtained by :py:func:`get_mood_categories` + :return: List of playlists in the format of :py:func:`get_library_playlists` + + """ + playlists = [] + response = self._send_request('browse', { + 'browseId': 'FEmusic_moods_and_genres_category', + 'params': params + }) + for section in nav(response, SINGLE_COLUMN_TAB + SECTION_LIST): + path = [] + if 'gridRenderer' in section: + path = GRID_ITEMS + elif 'musicCarouselShelfRenderer' in section: + path = CAROUSEL_CONTENTS + elif 'musicImmersiveCarouselShelfRenderer' in section: + path = ['musicImmersiveCarouselShelfRenderer', 'contents'] + if len(path): + results = nav(section, path) + playlists += parse_content_list(results, parse_playlist) + + return playlists + + def get_charts(self, country: str = 'ZZ') -> Dict: + """ + Get latest charts data from YouTube Music. + + :param country: ISO 3166-1 Alpha-2 country code + :return: Dictionary containing chart songs (only if authenticated), chart videos, chart artists and + trending videos. + """ + body = {'browseId': 'FEmusic_charts'} + if country: + body['formData'] = {'selectedValues': [country]} + endpoint = 'browse' + response = self._send_request(endpoint, body) + results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST) + charts = {'countries': {}} + menu = nav( + results[0], MUSIC_SHELF + [ + 'subheaders', 0, 'musicSideAlignedItemRenderer', 'startItems', 0, + 'musicSortFilterButtonRenderer' + ]) + charts['countries']['selected'] = nav(menu, TITLE) + charts['countries']['options'] = list( + filter(None, [ + nav(m, ['payload', 'musicFormBooleanChoice', 'opaqueToken'], True) + for m in nav(response, FRAMEWORK_MUTATIONS) + ])) + charts_categories = ['videos', 'artists'] + + has_songs = bool(self.auth) + has_trending = bool(5 - len(results) - has_songs) + if has_songs: + charts_categories.insert(0, 'songs') + if has_trending: + charts_categories.append('trending') + + parse_chart = lambda i, parse_func, key: parse_content_list( + nav(results[i + has_songs], CAROUSEL_CONTENTS), parse_func, key) + for i, c in enumerate(charts_categories): + charts[c] = { + 'playlist': nav(results[1 + i], CAROUSEL + CAROUSEL_TITLE + NAVIGATION_BROWSE_ID, + True) + } + + if has_songs: + charts['songs'] = { + 'items': parse_chart(0, parse_chart_song, MRLIR) + } + charts['videos']['items'] = parse_chart(1, parse_video, MTRIR) + charts['artists']['items'] = parse_chart(2, parse_chart_artist, MRLIR) + if has_trending: + charts['trending']['items'] = parse_chart(3, parse_chart_trending, MRLIR) + + return charts diff --git a/ytmusicapi/parsers/__init__.py b/ytmusicapi/parsers/__init__.py index d421665..e60512a 100644 --- a/ytmusicapi/parsers/__init__.py +++ b/ytmusicapi/parsers/__init__.py @@ -22,11 +22,14 @@ NAVIGATION_PLAYLIST_ID = ['navigationEndpoint', 'watchEndpoint', 'playlistId'] NAVIGATION_WATCH_PLAYLIST_ID = ['navigationEndpoint', 'watchPlaylistEndpoint', 'playlistId'] HEADER_DETAIL = ['header', 'musicDetailHeaderRenderer'] DESCRIPTION = ['description'] + RUN_TEXT +CAROUSEL = ['musicCarouselShelfRenderer'] +CAROUSEL_CONTENTS = CAROUSEL + ['contents'] CAROUSEL_TITLE = ['header', 'musicCarouselShelfBasicHeaderRenderer', 'title', 'runs', 0] FRAMEWORK_MUTATIONS = ['frameworkUpdates', 'entityBatchUpdate', 'mutations'] TITLE = ['title', 'runs', 0] TITLE_TEXT = ['title'] + RUN_TEXT TEXT_RUN = ['text', 'runs', 0] +TEXT_RUN_TEXT = ['text', 'runs', 0, 'text'] SUBTITLE = ['subtitle'] + RUN_TEXT SUBTITLE2 = ['subtitle', 'runs', 2, 'text'] SUBTITLE3 = ['subtitle', 'runs', 4, 'text'] @@ -41,3 +44,5 @@ BADGE_LABEL = [ RELOAD_CONTINUATION = ['continuations', 0, 'reloadContinuationData', 'continuation'] CATEGORY_TITLE = ['musicNavigationButtonRenderer', 'buttonText'] + RUN_TEXT CATEGORY_PARAMS = ['musicNavigationButtonRenderer', 'clickCommand', 'browseEndpoint', 'params'] +MRLIR = 'musicResponsiveListItemRenderer' +MTRIR = 'musicTwoRowItemRenderer' \ No newline at end of file diff --git a/ytmusicapi/parsers/browsing.py b/ytmusicapi/parsers/browsing.py index d65dbed..8c8dc04 100644 --- a/ytmusicapi/parsers/browsing.py +++ b/ytmusicapi/parsers/browsing.py @@ -13,7 +13,7 @@ class Parser: search_results = [] default_offset = (not resultType) * 2 for result in results: - data = result['musicResponsiveListItemRenderer'] + data = result[MRLIR] search_result = {} if not resultType: resultType = get_item_text(data, 1).lower() @@ -72,7 +72,8 @@ class Parser: ] if flex_items[0]: search_result['videoId'] = nav(flex_items[0][0], NAVIGATION_VIDEO_ID, True) - search_result['playlistId'] = nav(flex_items[0][0], NAVIGATION_PLAYLIST_ID, True) + search_result['playlistId'] = nav(flex_items[0][0], NAVIGATION_PLAYLIST_ID, + True) if flex_items[1]: search_result.update(parse_song_runs(flex_items[1])) search_result['resultType'] = 'song' @@ -133,8 +134,7 @@ class Parser: data = [ r['musicCarouselShelfRenderer'] for r in results if 'musicCarouselShelfRenderer' in r - and nav(r['musicCarouselShelfRenderer'], - CAROUSEL_TITLE)['text'].lower() == categories_local[i] + and nav(r, CAROUSEL + CAROUSEL_TITLE)['text'].lower() == categories_local[i] ] if len(data) > 0: artist[category] = {'browseId': None, 'results': []} @@ -152,10 +152,10 @@ class Parser: return artist -def parse_content_list(results, parse_func): +def parse_content_list(results, parse_func, key=MTRIR): contents = [] for result in results: - contents.append(parse_func(result['musicTwoRowItemRenderer'])) + contents.append(parse_func(result[key])) return contents diff --git a/ytmusicapi/parsers/explore.py b/ytmusicapi/parsers/explore.py new file mode 100644 index 0000000..5e6f838 --- /dev/null +++ b/ytmusicapi/parsers/explore.py @@ -0,0 +1,65 @@ +from ytmusicapi.parsers.browsing import * + +TRENDS = {'ARROW_DROP_UP': 'up', 'ARROW_DROP_DOWN': 'down', 'ARROW_CHART_NEUTRAL': 'neutral'} + + +def parse_chart_song(data): + flex_0 = get_flex_column_item(data, 0) + parsed = { + 'title': nav(flex_0, TEXT_RUN_TEXT), + 'videoId': nav(flex_0, TEXT_RUN + NAVIGATION_VIDEO_ID), + 'artists': parse_song_artists(data, 1), + 'thumbnails': nav(data, THUMBNAILS), + 'isExplicit': nav(data, BADGE_LABEL, True) == 'Explicit' + } + flex_2 = get_flex_column_item(data, 2) + if flex_2 and 'navigationEndpoint' in nav(flex_2, TEXT_RUN): + parsed['album'] = { + 'name': nav(flex_2, TEXT_RUN_TEXT), + 'id': nav(flex_2, TEXT_RUN + NAVIGATION_BROWSE_ID) + } + else: + flex_1 = get_flex_column_item(data, 1) + parsed['views'] = nav(flex_1, ['text', 'runs', 2, 'text']).split(' ')[0] + parsed.update(parse_ranking(data)) + return parsed + + +def parse_chart_artist(data): + subscribers = get_flex_column_item(data, 1) + if subscribers: + subscribers = nav(subscribers, TEXT_RUN_TEXT).split(' ')[0] + + parsed = { + 'title': nav(get_flex_column_item(data, 0), TEXT_RUN_TEXT), + 'browseId': nav(data, NAVIGATION_BROWSE_ID), + 'subscribers': subscribers, + 'thumbnails': nav(data, THUMBNAILS), + } + parsed.update(parse_ranking(data)) + return parsed + + +def parse_chart_trending(data): + views = get_flex_column_item(data, 2) + if views: + views = views.split(' ')[0] + flex_0 = get_flex_column_item(data, 0) + return { + 'title': nav(flex_0, TEXT_RUN_TEXT), + 'videoId': nav(flex_0, TEXT_RUN + NAVIGATION_VIDEO_ID), + 'playlistId': nav(flex_0, TEXT_RUN + NAVIGATION_PLAYLIST_ID), + 'artists': parse_song_artists(data, 1), + 'thumbnails': nav(data, THUMBNAILS), + 'views': views + } + + +def parse_ranking(data): + return { + 'rank': + nav(data, ['customIndexColumn', 'musicCustomIndexColumnRenderer'] + TEXT_RUN_TEXT), + 'trend': + TRENDS[nav(data, + ['customIndexColumn', 'musicCustomIndexColumnRenderer', 'icon', 'iconType'])] + } diff --git a/ytmusicapi/parsers/library.py b/ytmusicapi/parsers/library.py index b011462..8e32b60 100644 --- a/ytmusicapi/parsers/library.py +++ b/ytmusicapi/parsers/library.py @@ -5,7 +5,7 @@ from .utils import * def parse_artists(results, uploaded=False): artists = [] for result in results: - data = result['musicResponsiveListItemRenderer'] + data = result[MRLIR] artist = {} artist['browseId'] = nav(data, NAVIGATION_BROWSE_ID) artist['artist'] = get_item_text(data, 0) @@ -43,7 +43,7 @@ def parse_library_albums(response, request_func, limit): def parse_albums(results): albums = [] for result in results: - data = result['musicTwoRowItemRenderer'] + data = result[MTRIR] album = {} album['browseId'] = nav(data, TITLE + NAVIGATION_BROWSE_ID) album['title'] = nav(data, TITLE_TEXT) diff --git a/ytmusicapi/parsers/playlists.py b/ytmusicapi/parsers/playlists.py index f58796e..b675f1e 100644 --- a/ytmusicapi/parsers/playlists.py +++ b/ytmusicapi/parsers/playlists.py @@ -8,9 +8,9 @@ def parse_playlist_items(results, menu_entries: List[List] = None): count = 1 for result in results: count += 1 - if 'musicResponsiveListItemRenderer' not in result: + if MRLIR not in result: continue - data = result['musicResponsiveListItemRenderer'] + data = result[MRLIR] try: videoId = setVideoId = None diff --git a/ytmusicapi/parsers/uploads.py b/ytmusicapi/parsers/uploads.py index 1eb3b0b..e785f46 100644 --- a/ytmusicapi/parsers/uploads.py +++ b/ytmusicapi/parsers/uploads.py @@ -5,7 +5,7 @@ from .songs import * def parse_uploaded_items(results): songs = [] for result in results: - data = result['musicResponsiveListItemRenderer'] + data = result[MRLIR] if 'menu' not in data: continue entityId = nav(data, MENU_ITEMS)[-1]['menuNavigationItemRenderer']['navigationEndpoint'][ diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index fa5b9bb..8b587d4 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -9,12 +9,13 @@ from ytmusicapi.parsers import browsing from ytmusicapi.setup import setup from ytmusicapi.mixins.browsing import BrowsingMixin from ytmusicapi.mixins.watch import WatchMixin +from ytmusicapi.mixins.explore import ExploreMixin from ytmusicapi.mixins.library import LibraryMixin from ytmusicapi.mixins.playlists import PlaylistsMixin from ytmusicapi.mixins.uploads import UploadsMixin -class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMixin): +class YTMusic(BrowsingMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin, UploadsMixin): """ Allows automated interactions with YouTube Music by emulating the YouTube web client's requests. Permits both authenticated and non-authenticated requests. @@ -77,8 +78,8 @@ class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMi except Exception as e: print( - "Failed loading provided credentials. Make sure to provide a string or a file path. " - "Reason: " + str(e)) + "Failed loading provided credentials. Make sure to provide a string or a file path. " + "Reason: " + str(e)) else: # no authentication self.headers = initialize_headers()