validate playlist ids in playlist methods

additionally small code quality improvements
This commit is contained in:
sigma67 2021-05-14 19:45:41 +02:00
commit 5ae470e260
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
6 changed files with 29 additions and 26 deletions

View file

@ -10,6 +10,7 @@ config.read('./test.cfg', 'utf-8')
sample_album = "MPREb_4pL8gzRtw1p" # Eminem - Revival
sample_video = "ZrOKjDZOtkA" # Oasis - Wonderwall (Remastered)
sample_playlist = "PL6bPxvf5dW5clc3y9wAoslzqUrmkZ5c-u" # very large playlist
class TestYTMusic(unittest.TestCase):
@ -151,9 +152,9 @@ class TestYTMusic(unittest.TestCase):
self.assertEqual(len(playlist['tracks']), 12)
def test_get_watch_playlist_shuffle_playlist(self):
playlist = self.yt_auth.get_watch_playlist_shuffle(
videoId="u6XiiXJD0jg", playlistId="PL528pVfw3ao2VzfY6zE1TOZm1cBSdk7Q0", limit=99)
self.assertGreaterEqual(len(playlist['tracks']), 80)
playlist = self.yt_brand.get_watch_playlist_shuffle(
playlistId=config['playlists']['own'])
self.assertEqual(len(playlist['tracks']), 4)
###############
# LIBRARY
@ -251,7 +252,7 @@ class TestYTMusic(unittest.TestCase):
###############
def test_get_foreign_playlist(self):
playlist = self.yt.get_playlist("PL6bPxvf5dW5clc3y9wAoslzqUrmkZ5c-u", 300)
playlist = self.yt.get_playlist(sample_playlist, 300)
self.assertGreater(len(playlist['tracks']), 200)
def test_get_owned_playlist(self):

View file

@ -112,7 +112,10 @@ class BrowsingMixin:
body = {'query': query}
endpoint = 'search'
search_results = []
filters = ['albums', 'artists', 'playlists', 'community_playlists', 'featured_playlists', 'songs', 'videos', 'uploads']
filters = [
'albums', 'artists', 'playlists', 'community_playlists', 'featured_playlists', 'songs',
'videos', 'uploads'
]
if filter and filter not in filters:
raise Exception(
"Invalid filter provided. Please use one of the following filters or leave out the parameter: "
@ -146,12 +149,7 @@ class BrowsingMixin:
else:
param1 = 'EgWKAQI'
filter_params = {
'songs': 'I',
'videos': 'Q',
'albums': 'Y',
'artists': 'g'
}
filter_params = {'songs': 'I', 'videos': 'Q', 'albums': 'Y', 'artists': 'g'}
param2 = filter_params[filter]
if not ignore_spelling:
param3 = 'AWoMEA4QChADEAQQCRAF'
@ -307,7 +305,7 @@ class BrowsingMixin:
'musicDescriptionShelfRenderer',
is_key=True)
if descriptionShelf:
artist['description'] = descriptionShelf['description']['runs'][0]['text']
artist['description'] = nav(descriptionShelf, DESCRIPTION)
artist['views'] = None if 'subheader' not in descriptionShelf else descriptionShelf[
'subheader']['runs'][0]['text']
subscription_button = header['subscriptionButton']['subscribeButtonRenderer']
@ -753,10 +751,9 @@ class BrowsingMixin:
raise Exception("Invalid browseId provided. This song might not have lyrics.")
response = self._send_request('browse', {'browseId': browseId})
if 'sectionListRenderer' in response['contents'].keys():
lyrics['lyrics'] = response['contents']['sectionListRenderer']['contents'][0][
'musicDescriptionShelfRenderer']['description']['runs'][0]['text']
lyrics['source'] = response['contents']['sectionListRenderer']['contents'][0][
'musicDescriptionShelfRenderer']['footer']['runs'][0]['text']
lyrics['lyrics'] = nav(response, ['contents'] + SECTION_LIST_ITEM
+ ['musicDescriptionShelfRenderer'] + DESCRIPTION, True)
lyrics['source'] = nav(response, ['contents'] + SECTION_LIST_ITEM
+ ['musicDescriptionShelfRenderer', 'footer'] + RUN_TEXT, True)
return lyrics

View file

@ -79,8 +79,7 @@ class PlaylistsMixin:
playlist['title'] = nav(header, TITLE_TEXT)
playlist['thumbnails'] = nav(header, THUMBNAIL_CROPPED)
if "description" in header:
playlist["description"] = header["description"]["runs"][0]["text"]
playlist["description"] = nav(header, DESCRIPTION, True)
run_count = len(header['subtitle']['runs'])
if run_count > 1:
playlist['author'] = {
@ -187,7 +186,7 @@ class PlaylistsMixin:
:return: Status String or full response
"""
self._check_auth()
body = {'playlistId': playlistId}
body = {'playlistId': validate_playlist_id(playlistId)}
actions = []
if title:
actions.append({'action': 'ACTION_SET_PLAYLIST_NAME', 'playlistName': title})
@ -227,7 +226,7 @@ class PlaylistsMixin:
:return: Status String or full response
"""
self._check_auth()
body = {'playlistId': playlistId}
body = {'playlistId': validate_playlist_id(playlistId)}
endpoint = 'playlist/delete'
response = self._send_request(endpoint, body)
return response['status'] if 'status' in response else response
@ -247,7 +246,7 @@ class PlaylistsMixin:
:return: Status String and a dict containing the new setVideoId for each videoId or full response
"""
self._check_auth()
body = {'playlistId': playlistId, 'actions': []}
body = {'playlistId': validate_playlist_id(playlistId), 'actions': []}
if not videoIds and not source_playlist:
raise Exception(
"You must provide either videoIds or a source_playlist to add to the playlist")
@ -296,7 +295,7 @@ class PlaylistsMixin:
raise Exception(
"Cannot remove songs, because setVideoId is missing. Do you own this playlist?")
body = {'playlistId': playlistId, 'actions': []}
body = {'playlistId': validate_playlist_id(playlistId), 'actions': []}
for video in videos:
body['actions'].append({
'setVideoId': video['setVideoId'],

View file

@ -59,7 +59,7 @@ class WatchMixin:
}
is_playlist = False
if playlistId:
body['playlistId'] = playlistId if not playlistId.startswith("VL") else playlistId[2:]
body['playlistId'] = validate_playlist_id(playlistId)
is_playlist = body['playlistId'].startswith('PL')
if params:
body['params'] = params

View file

@ -1,4 +1,5 @@
# commonly used navigation paths
RUN_TEXT = ['runs', 0, 'text']
TAB_CONTENT = ['tabs', 0, 'tabRenderer', 'content']
SINGLE_COLUMN_TAB = ['contents', 'singleColumnBrowseResultsRenderer'] + TAB_CONTENT
SECTION_LIST = ['sectionListRenderer', 'contents']
@ -20,12 +21,13 @@ NAVIGATION_VIDEO_ID = ['navigationEndpoint', 'watchEndpoint', 'videoId']
NAVIGATION_PLAYLIST_ID = ['navigationEndpoint', 'watchEndpoint', 'playlistId']
NAVIGATION_WATCH_PLAYLIST_ID = ['navigationEndpoint', 'watchPlaylistEndpoint', 'playlistId']
HEADER_DETAIL = ['header', 'musicDetailHeaderRenderer']
DESCRIPTION = ['description'] + RUN_TEXT
CAROUSEL_TITLE = ['header', 'musicCarouselShelfBasicHeaderRenderer', 'title', 'runs', 0]
FRAMEWORK_MUTATIONS = ['frameworkUpdates', 'entityBatchUpdate', 'mutations']
TITLE = ['title', 'runs', 0]
TITLE_TEXT = ['title', 'runs', 0, 'text']
TITLE_TEXT = ['title'] + RUN_TEXT
TEXT_RUN = ['text', 'runs', 0]
SUBTITLE = ['subtitle', 'runs', 0, 'text']
SUBTITLE = ['subtitle'] + RUN_TEXT
SUBTITLE2 = ['subtitle', 'runs', 2, 'text']
SUBTITLE3 = ['subtitle', 'runs', 4, 'text']
THUMBNAIL = ['thumbnail', 'thumbnails']

View file

@ -138,6 +138,10 @@ def validate_response(response, per_page, limit, current_count):
return len(response['parsed']) >= expected_items_count
def validate_playlist_id(playlistId):
return playlistId if not playlistId.startswith("VL") else playlistId[2:]
def nav(root, items, none_if_absent=False):
"""Access a nested object in root by item sequence."""
try: