add get_charts (#213)

This commit is contained in:
sigma67 2021-07-11 18:39:40 +02:00
commit 42f08d1766
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
10 changed files with 240 additions and 102 deletions

View file

@ -133,6 +133,14 @@ class TestYTMusic(unittest.TestCase):
self.assertIsNone(playlist["lyrics"]) self.assertIsNone(playlist["lyrics"])
self.assertRaises(Exception, self.yt.get_lyrics, 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): def test_get_mood_playlists(self):
categories = self.yt.get_mood_categories() categories = self.yt.get_mood_categories()
self.assertGreater(len(list(categories)), 0) self.assertGreater(len(list(categories)), 0)
@ -141,9 +149,11 @@ class TestYTMusic(unittest.TestCase):
playlists = self.yt.get_mood_playlists(categories[cat][0]["params"]) playlists = self.yt.get_mood_playlists(categories[cat][0]["params"])
self.assertGreater(len(playlists), 0) self.assertGreater(len(playlists), 0)
def test_get_signatureTimestamp(self): def test_get_charts(self):
signatureTimestamp = self.yt.get_signatureTimestamp() charts = self.yt_auth.get_charts()
self.assertIsNotNone(signatureTimestamp) self.assertEqual(len(charts), 4)
charts = self.yt.get_charts(country='BE')
self.assertEqual(len(charts), 4)
############### ###############
# WATCH # WATCH

View file

@ -749,91 +749,6 @@ class BrowsingMixin:
return lyrics 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): def get_basejs_url(self):
""" """
Extract the URL for the `base.js` script from YouTube Music. Extract the URL for the `base.js` script from YouTube Music.

View file

@ -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

View file

@ -22,11 +22,14 @@ NAVIGATION_PLAYLIST_ID = ['navigationEndpoint', 'watchEndpoint', 'playlistId']
NAVIGATION_WATCH_PLAYLIST_ID = ['navigationEndpoint', 'watchPlaylistEndpoint', 'playlistId'] NAVIGATION_WATCH_PLAYLIST_ID = ['navigationEndpoint', 'watchPlaylistEndpoint', 'playlistId']
HEADER_DETAIL = ['header', 'musicDetailHeaderRenderer'] HEADER_DETAIL = ['header', 'musicDetailHeaderRenderer']
DESCRIPTION = ['description'] + RUN_TEXT DESCRIPTION = ['description'] + RUN_TEXT
CAROUSEL = ['musicCarouselShelfRenderer']
CAROUSEL_CONTENTS = CAROUSEL + ['contents']
CAROUSEL_TITLE = ['header', 'musicCarouselShelfBasicHeaderRenderer', 'title', 'runs', 0] CAROUSEL_TITLE = ['header', 'musicCarouselShelfBasicHeaderRenderer', 'title', 'runs', 0]
FRAMEWORK_MUTATIONS = ['frameworkUpdates', 'entityBatchUpdate', 'mutations'] FRAMEWORK_MUTATIONS = ['frameworkUpdates', 'entityBatchUpdate', 'mutations']
TITLE = ['title', 'runs', 0] TITLE = ['title', 'runs', 0]
TITLE_TEXT = ['title'] + RUN_TEXT TITLE_TEXT = ['title'] + RUN_TEXT
TEXT_RUN = ['text', 'runs', 0] TEXT_RUN = ['text', 'runs', 0]
TEXT_RUN_TEXT = ['text', 'runs', 0, 'text']
SUBTITLE = ['subtitle'] + RUN_TEXT SUBTITLE = ['subtitle'] + RUN_TEXT
SUBTITLE2 = ['subtitle', 'runs', 2, 'text'] SUBTITLE2 = ['subtitle', 'runs', 2, 'text']
SUBTITLE3 = ['subtitle', 'runs', 4, 'text'] SUBTITLE3 = ['subtitle', 'runs', 4, 'text']
@ -41,3 +44,5 @@ BADGE_LABEL = [
RELOAD_CONTINUATION = ['continuations', 0, 'reloadContinuationData', 'continuation'] RELOAD_CONTINUATION = ['continuations', 0, 'reloadContinuationData', 'continuation']
CATEGORY_TITLE = ['musicNavigationButtonRenderer', 'buttonText'] + RUN_TEXT CATEGORY_TITLE = ['musicNavigationButtonRenderer', 'buttonText'] + RUN_TEXT
CATEGORY_PARAMS = ['musicNavigationButtonRenderer', 'clickCommand', 'browseEndpoint', 'params'] CATEGORY_PARAMS = ['musicNavigationButtonRenderer', 'clickCommand', 'browseEndpoint', 'params']
MRLIR = 'musicResponsiveListItemRenderer'
MTRIR = 'musicTwoRowItemRenderer'

View file

@ -13,7 +13,7 @@ class Parser:
search_results = [] search_results = []
default_offset = (not resultType) * 2 default_offset = (not resultType) * 2
for result in results: for result in results:
data = result['musicResponsiveListItemRenderer'] data = result[MRLIR]
search_result = {} search_result = {}
if not resultType: if not resultType:
resultType = get_item_text(data, 1).lower() resultType = get_item_text(data, 1).lower()
@ -72,7 +72,8 @@ class Parser:
] ]
if flex_items[0]: if flex_items[0]:
search_result['videoId'] = nav(flex_items[0][0], NAVIGATION_VIDEO_ID, True) 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]: if flex_items[1]:
search_result.update(parse_song_runs(flex_items[1])) search_result.update(parse_song_runs(flex_items[1]))
search_result['resultType'] = 'song' search_result['resultType'] = 'song'
@ -133,8 +134,7 @@ class Parser:
data = [ data = [
r['musicCarouselShelfRenderer'] for r in results r['musicCarouselShelfRenderer'] for r in results
if 'musicCarouselShelfRenderer' in r if 'musicCarouselShelfRenderer' in r
and nav(r['musicCarouselShelfRenderer'], and nav(r, CAROUSEL + CAROUSEL_TITLE)['text'].lower() == categories_local[i]
CAROUSEL_TITLE)['text'].lower() == categories_local[i]
] ]
if len(data) > 0: if len(data) > 0:
artist[category] = {'browseId': None, 'results': []} artist[category] = {'browseId': None, 'results': []}
@ -152,10 +152,10 @@ class Parser:
return artist return artist
def parse_content_list(results, parse_func): def parse_content_list(results, parse_func, key=MTRIR):
contents = [] contents = []
for result in results: for result in results:
contents.append(parse_func(result['musicTwoRowItemRenderer'])) contents.append(parse_func(result[key]))
return contents return contents

View file

@ -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'])]
}

View file

@ -5,7 +5,7 @@ from .utils import *
def parse_artists(results, uploaded=False): def parse_artists(results, uploaded=False):
artists = [] artists = []
for result in results: for result in results:
data = result['musicResponsiveListItemRenderer'] data = result[MRLIR]
artist = {} artist = {}
artist['browseId'] = nav(data, NAVIGATION_BROWSE_ID) artist['browseId'] = nav(data, NAVIGATION_BROWSE_ID)
artist['artist'] = get_item_text(data, 0) artist['artist'] = get_item_text(data, 0)
@ -43,7 +43,7 @@ def parse_library_albums(response, request_func, limit):
def parse_albums(results): def parse_albums(results):
albums = [] albums = []
for result in results: for result in results:
data = result['musicTwoRowItemRenderer'] data = result[MTRIR]
album = {} album = {}
album['browseId'] = nav(data, TITLE + NAVIGATION_BROWSE_ID) album['browseId'] = nav(data, TITLE + NAVIGATION_BROWSE_ID)
album['title'] = nav(data, TITLE_TEXT) album['title'] = nav(data, TITLE_TEXT)

View file

@ -8,9 +8,9 @@ def parse_playlist_items(results, menu_entries: List[List] = None):
count = 1 count = 1
for result in results: for result in results:
count += 1 count += 1
if 'musicResponsiveListItemRenderer' not in result: if MRLIR not in result:
continue continue
data = result['musicResponsiveListItemRenderer'] data = result[MRLIR]
try: try:
videoId = setVideoId = None videoId = setVideoId = None

View file

@ -5,7 +5,7 @@ from .songs import *
def parse_uploaded_items(results): def parse_uploaded_items(results):
songs = [] songs = []
for result in results: for result in results:
data = result['musicResponsiveListItemRenderer'] data = result[MRLIR]
if 'menu' not in data: if 'menu' not in data:
continue continue
entityId = nav(data, MENU_ITEMS)[-1]['menuNavigationItemRenderer']['navigationEndpoint'][ entityId = nav(data, MENU_ITEMS)[-1]['menuNavigationItemRenderer']['navigationEndpoint'][

View file

@ -9,12 +9,13 @@ from ytmusicapi.parsers import browsing
from ytmusicapi.setup import setup from ytmusicapi.setup import setup
from ytmusicapi.mixins.browsing import BrowsingMixin from ytmusicapi.mixins.browsing import BrowsingMixin
from ytmusicapi.mixins.watch import WatchMixin from ytmusicapi.mixins.watch import WatchMixin
from ytmusicapi.mixins.explore import ExploreMixin
from ytmusicapi.mixins.library import LibraryMixin from ytmusicapi.mixins.library import LibraryMixin
from ytmusicapi.mixins.playlists import PlaylistsMixin from ytmusicapi.mixins.playlists import PlaylistsMixin
from ytmusicapi.mixins.uploads import UploadsMixin 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. Allows automated interactions with YouTube Music by emulating the YouTube web client's requests.
Permits both authenticated and non-authenticated requests. Permits both authenticated and non-authenticated requests.
@ -77,8 +78,8 @@ class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMi
except Exception as e: except Exception as e:
print( print(
"Failed loading provided credentials. Make sure to provide a string or a file path. " "Failed loading provided credentials. Make sure to provide a string or a file path. "
"Reason: " + str(e)) "Reason: " + str(e))
else: # no authentication else: # no authentication
self.headers = initialize_headers() self.headers = initialize_headers()