add get_charts (#213)
This commit is contained in:
parent
576d3bfb46
commit
42f08d1766
10 changed files with 240 additions and 102 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
142
ytmusicapi/mixins/explore.py
Normal file
142
ytmusicapi/mixins/explore.py
Normal 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
|
||||
|
|
@ -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'
|
||||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
65
ytmusicapi/parsers/explore.py
Normal file
65
ytmusicapi/parsers/explore.py
Normal 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'])]
|
||||
}
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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'][
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
Loading…
Reference in a new issue