remove get_playlist_suggestions - add suggestions and related to get_playlist

get_playlist_suggestions was not working anymore due to changes on YouTube's end
calls to the playlist page on YouTube Music now also return co-dependent continuations for suggestions and related items
to support both, these continuations are now part of get_playlist, but made optional through function parameters
default values are set backwards-compatible, i.e. no extra requests are performed without setting the new parameters
This commit is contained in:
sigma67 2022-09-30 19:30:41 +02:00
commit c2d5e46805
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
4 changed files with 94 additions and 45 deletions

View file

@ -315,21 +315,19 @@ class TestYTMusic(unittest.TestCase):
###############
def test_get_foreign_playlist(self):
playlist = self.yt.get_playlist(sample_playlist, limit=300)
playlist = self.yt.get_playlist(sample_playlist, limit=300, suggestions_limit=7)
self.assertGreater(len(playlist['tracks']), 200)
self.assertNotIn('suggestions', playlist)
playlist = self.yt.get_playlist("RDCLAK5uy_kpxnNxJpPZjLKbL9WgvrPuErWkUxMP6x4", limit=None)
playlist = self.yt.get_playlist("RDCLAK5uy_kpxnNxJpPZjLKbL9WgvrPuErWkUxMP6x4", limit=None, related=True)
self.assertGreater(len(playlist['tracks']), 100)
self.assertEqual(len(playlist['related']), 10)
def test_get_owned_playlist(self):
playlist = self.yt_brand.get_playlist(config['playlists']['own'])
playlist = self.yt_brand.get_playlist(config['playlists']['own'], related=True, suggestions_limit=21)
self.assertLess(len(playlist['tracks']), 100)
if not playlist['suggestions_token']:
self.skipTest("Suggestions not available")
suggestions = self.yt_brand.get_playlist_suggestions(playlist['suggestions_token'])
self.assertGreater(len(suggestions['tracks']), 5)
refresh = self.yt_brand.get_playlist_suggestions(suggestions['refresh_token'])
self.assertGreater(len(refresh['tracks']), 5)
self.assertEqual(len(playlist['suggestions']), 21)
self.assertEqual(len(playlist['related']), 10)
def test_edit_playlist(self):
playlist = self.yt_brand.get_playlist(config['playlists']['own'])
@ -362,7 +360,7 @@ class TestYTMusic(unittest.TestCase):
self.assertEqual(response["status"], 'STATUS_SUCCEEDED', "Adding playlist item failed")
self.assertGreater(len(response["playlistEditResults"]), 0, "Adding playlist item failed")
time.sleep(2)
playlist = self.yt_auth.get_playlist(playlistId)
playlist = self.yt_auth.get_playlist(playlistId, related=True)
self.assertEqual(len(playlist['tracks']), 46, "Getting playlist items failed")
response = self.yt_auth.remove_playlist_items(playlistId, playlist['tracks'])
self.assertEqual(response, 'STATUS_SUCCEEDED', "Playlist item removal failed")

View file

@ -1,10 +1,17 @@
from ytmusicapi.navigation import nav
def get_continuations(results, continuation_type, limit, request_func, parse_func, ctoken_path=""):
def get_continuations(results,
continuation_type,
limit,
request_func,
parse_func,
ctoken_path="",
reloadable=False):
items = []
while 'continuations' in results and (limit is None or len(items) < limit):
additionalParams = get_continuation_params(results, ctoken_path)
additionalParams = get_reloadable_continuation_params(results) if reloadable \
else get_continuation_params(results, ctoken_path)
response = request_func(additionalParams)
if 'continuationContents' in response:
results = response['continuationContents'][continuation_type]
@ -46,12 +53,17 @@ def get_parsed_continuation_items(response, parse_func, continuation_type):
return {'results': results, 'parsed': get_continuation_contents(results, parse_func)}
def get_continuation_params(results, ctoken_path):
def get_continuation_params(results, ctoken_path=''):
ctoken = nav(results,
['continuations', 0, 'next' + ctoken_path + 'ContinuationData', 'continuation'])
return get_continuation_string(ctoken)
def get_reloadable_continuation_params(results):
ctoken = nav(results, ['continuations', 0, 'reloadContinuationData', 'continuation'])
return get_continuation_string(ctoken)
def get_continuation_string(ctoken):
return "&ctoken=" + ctoken + "&continuation=" + ctoken

View file

@ -2,19 +2,24 @@ import unicodedata
from typing import Dict, Union, Tuple
from ._utils import *
from ytmusicapi.continuations import get_continuations, get_continuation_string
from ytmusicapi.continuations import *
from ytmusicapi.navigation import *
from ytmusicapi.helpers import to_int, sum_total_duration
from ytmusicapi.parsers.playlists import *
from ytmusicapi.parsers.browsing import parse_content_list, parse_playlist
class PlaylistsMixin:
def get_playlist(self, playlistId: str, limit: int = 100) -> Dict:
def get_playlist(self, playlistId: str, limit: int = 100, related: bool = False, suggestions_limit: int = 0) -> Dict:
"""
Returns a list of playlist items
:param playlistId: Playlist id
:param limit: How many songs to return. `None` retrieves them all. Default: 100
:param related: Whether to fetch 10 related playlists or not. Default: False
:param suggestions_limit: How many suggestions to return. The result is a list of
suggested playlist items (videos) contained in a "suggestions" key.
7 items are retrieved in each internal request. Default: 0
:return: Dictionary with information about the playlist.
The key ``tracks`` contains a List of playlistItem dictionaries
@ -31,6 +36,35 @@ class PlaylistsMixin:
"duration": "6+ hours",
"duration_seconds": 52651,
"trackCount": 237,
"suggestions": [
{
"videoId": "HLCsfOykA94",
"title": "Mambo (GATTÜSO Remix)",
"artists": [{
"name": "Nikki Vianna",
"id": "UCMW5eSIO1moVlIBLQzq4PnQ"
}],
"album": {
"name": "Mambo (GATTÜSO Remix)",
"id": "MPREb_jLeQJsd7U9w"
},
"likeStatus": "LIKE",
"thumbnails": [...],
"isAvailable": true,
"isExplicit": false,
"duration": "3:32",
"duration_seconds": 212,
"setVideoId": "to_be_updated_by_client"
}
],
"related": [
{
"title": "Presenting MYRNE",
"playlistId": "RDCLAK5uy_mbdO3_xdD4NtU1rWI0OmvRSRZ8NH4uJCM",
"thumbnails": [...],
"description": "Playlist • YouTube Music"
}
],
"tracks": [
{
"videoId": "bjGppZKiuFE",
@ -99,21 +133,44 @@ class PlaylistsMixin:
playlist['duration'] = header['secondSubtitle']['runs'][2]['text']
playlist['trackCount'] = song_count
playlist['suggestions_token'] = nav(
response, SINGLE_COLUMN_TAB + ['sectionListRenderer', 'contents', 1] + MUSIC_SHELF
+ RELOAD_CONTINUATION, True)
playlist['tracks'] = []
request_func = lambda additionalParams: self._send_request(endpoint, body, additionalParams)
# suggestions and related are missing e.g. on liked songs
section_list = nav(response, SINGLE_COLUMN_TAB + ['sectionListRenderer'])
if 'continuations' in section_list:
additionalParams = get_continuation_params(section_list)
if own_playlist and (suggestions_limit > 0 or related):
parse_func = lambda results: parse_playlist_items(results)
suggested = request_func(additionalParams)
continuation = nav(suggested, SECTION_LIST_CONTINUATION)
additionalParams = get_continuation_params(continuation)
suggestions_shelf = nav(continuation, CONTENT + MUSIC_SHELF)
playlist['suggestions'] = get_continuation_contents(suggestions_shelf, parse_func)
parse_func = lambda results: parse_playlist_items(results)
playlist['suggestions'].extend(get_continuations(suggestions_shelf,
'musicShelfContinuation',
suggestions_limit - len(playlist['suggestions']),
request_func,
parse_func,
reloadable=True))
if related:
response = request_func(additionalParams)
continuation = nav(response, SECTION_LIST_CONTINUATION)
parse_func = lambda results: parse_content_list(results, parse_playlist)
playlist['related'] = get_continuation_contents(nav(continuation, CONTENT + CAROUSEL),
parse_func)
if song_count > 0:
playlist['tracks'].extend(parse_playlist_items(results['contents']))
playlist['tracks'] = parse_playlist_items(results['contents'])
if limit is None:
limit = song_count
songs_to_get = min(limit, song_count)
parse_func = lambda contents: parse_playlist_items(contents)
if 'continuations' in results:
request_func = lambda additionalParams: self._send_request(
endpoint, body, additionalParams)
parse_func = lambda contents: parse_playlist_items(contents)
playlist['tracks'].extend(
get_continuations(results, 'musicPlaylistShelfContinuation',
songs_to_get - len(playlist['tracks']), request_func,
@ -122,25 +179,6 @@ class PlaylistsMixin:
playlist['duration_seconds'] = sum_total_duration(playlist)
return playlist
def get_playlist_suggestions(self, suggestions_token: str) -> Dict:
"""
Gets suggested tracks to add to a playlist. Suggestions are offered for playlists with less than 100 tracks
:param suggestions_token: Token returned by :py:func:`get_playlist` or this function
:return: Dictionary containing suggested `tracks` and a `refresh_token` to get another set of suggestions.
For data format of tracks, check :py:func:`get_playlist`
"""
if not suggestions_token:
raise Exception('Suggestions token is None. '
'Please ensure the playlist is small enough to receive suggestions.')
endpoint = 'browse'
additionalParams = get_continuation_string(suggestions_token)
response = self._send_request(endpoint, {}, additionalParams)
results = nav(response, ['continuationContents', 'musicShelfContinuation'])
refresh_token = nav(results, RELOAD_CONTINUATION)
suggestions = parse_playlist_items(results['contents'])
return {'tracks': suggestions, 'refresh_token': refresh_token}
def create_playlist(self,
title: str,
description: str,

View file

@ -1,10 +1,11 @@
# commonly used navigation paths
CONTENT = ['contents', 0]
RUN_TEXT = ['runs', 0, 'text']
TAB_CONTENT = ['tabs', 0, 'tabRenderer', 'content']
SINGLE_COLUMN_TAB = ['contents', 'singleColumnBrowseResultsRenderer'] + TAB_CONTENT
SECTION_LIST = ['sectionListRenderer', 'contents']
SECTION_LIST_ITEM = ['sectionListRenderer', 'contents', 0]
ITEM_SECTION = ['itemSectionRenderer', 'contents', 0]
SECTION_LIST_ITEM = ['sectionListRenderer'] + CONTENT
ITEM_SECTION = ['itemSectionRenderer'] + CONTENT
MUSIC_SHELF = ['musicShelfRenderer']
GRID = ['gridRenderer']
GRID_ITEMS = GRID + ['items']
@ -52,13 +53,13 @@ FEEDBACK_TOKEN = ['feedbackEndpoint', 'feedbackToken']
BADGE_LABEL = [
'badges', 0, 'musicInlineBadgeRenderer', 'accessibilityData', 'accessibilityData', 'label'
]
RELOAD_CONTINUATION = ['continuations', 0, 'reloadContinuationData', 'continuation']
CATEGORY_TITLE = ['musicNavigationButtonRenderer', 'buttonText'] + RUN_TEXT
CATEGORY_PARAMS = ['musicNavigationButtonRenderer', 'clickCommand', 'browseEndpoint', 'params']
MRLIR = 'musicResponsiveListItemRenderer'
MTRIR = 'musicTwoRowItemRenderer'
TASTE_PROFILE_ITEMS = ["contents", "tastebuilderRenderer", "contents"]
TASTE_PROFILE_ARTIST = ["title", "runs"]
SECTION_LIST_CONTINUATION = ['continuationContents', 'sectionListContinuation']
def nav(root, items, none_if_absent=False):