Add additional endpoints: get_playlists, get_liked_songs, edit_playlist. Renamed add_playlist to create_playlist
This commit is contained in:
parent
2388f7ce76
commit
7ed4d4358a
4 changed files with 99 additions and 24 deletions
2
setup.py
2
setup.py
|
|
@ -1,7 +1,7 @@
|
|||
from setuptools import setup, find_packages
|
||||
|
||||
setup(name='ytmusicapi',
|
||||
version='0.2',
|
||||
version='0.3',
|
||||
description='Unofficial YTMusic API',
|
||||
long_description=(open('README.md').read()),
|
||||
url='https://github.com/sigma67/ytmusicapi',
|
||||
|
|
|
|||
|
|
@ -12,20 +12,15 @@ def parse_songs(results):
|
|||
# if item is not playable, there is not videoId
|
||||
if 'playNavigationEndpoint' in data['overlay']['musicItemThumbnailOverlayRenderer']['content']['musicPlayButtonRenderer']:
|
||||
videoId = data['overlay']['musicItemThumbnailOverlayRenderer']['content']['musicPlayButtonRenderer']['playNavigationEndpoint']['watchEndpoint']['videoId']
|
||||
|
||||
# if playlist is not owned, removal is not possible
|
||||
if 'menuServiceItemRenderer' in data['menu']['menuRenderer']['items'][4]:
|
||||
removeAction = \
|
||||
data['menu']['menuRenderer']['items'][4]['menuServiceItemRenderer']['serviceEndpoint']['playlistEditEndpoint']['actions'][0]
|
||||
else:
|
||||
removeAction = None
|
||||
|
||||
else:
|
||||
videoId = None
|
||||
|
||||
# if playlist is not owned, the playlist item can't be interacted with
|
||||
setVideoId = data['playlistItemData']['playlistSetVideoId'] if 'playlistItemData' in data else None
|
||||
|
||||
artist = data['flexColumns'][1]['musicResponsiveListItemFlexColumnRenderer']['text']['runs'][0]['text']
|
||||
title = data['flexColumns'][0]['musicResponsiveListItemFlexColumnRenderer']['text']['runs'][0]['text']
|
||||
song = {'videoId': videoId, 'artist': artist, 'title': title, 'removeAction': removeAction}
|
||||
song = {'videoId': videoId, 'artist': artist, 'title': title, 'setVideoId': setVideoId}
|
||||
songs.append(song)
|
||||
except Exception as e:
|
||||
print("Item " + str(count) + ": " + str(e))
|
||||
|
|
|
|||
|
|
@ -1,14 +1,15 @@
|
|||
from ytmusicapi.ytmusic import YTMusic
|
||||
|
||||
# YTMusic.get_playlist_items("PLQwVIlKxHM6qgidcRDp0-KFY1JmdGS206")
|
||||
youtube = YTMusic()
|
||||
youtube_auth = YTMusic('../headers_auth.json')
|
||||
|
||||
def get_playlists():
|
||||
songs = youtube.get_playlists()
|
||||
|
||||
def get_foreign_playlist():
|
||||
songs = youtube.get_playlist_items("PLw-VjHDlEOgs658kAHR_LAaILBXb-s6Q5")
|
||||
assert (len(songs) == 200)
|
||||
|
||||
|
||||
def get_owned_playlist():
|
||||
songs = youtube_auth.get_playlist_items('PLQwVIlKxHM6oCeKLTsUx_w9CmWjHKdg68')
|
||||
assert (len(songs) == 64)
|
||||
|
|
@ -19,14 +20,14 @@ def search():
|
|||
|
||||
#end to end test adding playlist, adding item, deleting item, deleting playlist
|
||||
def end2end():
|
||||
playlist = youtube_auth.add_playlist("test", "test description", False)
|
||||
playlist = youtube_auth.create_playlist("test", "test description")
|
||||
print(playlist)
|
||||
response = youtube_auth.add_playlist_item(playlist, 'y0Hhvtmv0gk')
|
||||
assert(response['status'] == 'STATUS_SUCCEEDED')
|
||||
assert(response == 'STATUS_SUCCEEDED')
|
||||
items = youtube_auth.get_playlist_items(playlist)
|
||||
assert(len(items) == 1)
|
||||
response = youtube_auth.remove_playlist_item(playlist, items[0])
|
||||
assert(response['status'] == 'STATUS_SUCCEEDED')
|
||||
assert(response == 'STATUS_SUCCEEDED')
|
||||
response = youtube_auth.delete_playlist(playlist)
|
||||
assert(response['command']['handlePlaylistDeletionCommand']['playlistId'] == playlist)
|
||||
|
||||
|
|
@ -43,4 +44,6 @@ def end2end():
|
|||
|
||||
if __name__ == '__main__':
|
||||
#end2end()
|
||||
search()
|
||||
#search()
|
||||
#get_owned_playlist()
|
||||
youtube_auth.get_liked_songs()
|
||||
|
|
|
|||
|
|
@ -20,6 +20,10 @@ class YTMusic:
|
|||
response = requests.post(base_url + endpoint + params + additionalParams, json=self.body, headers=self.headers)
|
||||
return json.loads(response.text)
|
||||
|
||||
def __check_auth(self):
|
||||
if self.auth == "":
|
||||
raise Exception("Please provide authentication before using this function")
|
||||
|
||||
def search(self, query):
|
||||
self.body['query'] = query
|
||||
self.body['params'] = 'Eg-KAQwIARAAGAAgACgAMABqChAEEAMQCRAFEAo%3D'
|
||||
|
|
@ -46,7 +50,43 @@ class YTMusic:
|
|||
|
||||
return songs
|
||||
|
||||
def get_playlists(self):
|
||||
"""
|
||||
Retrieves the content of the 'Library' page
|
||||
:return: List of owned playlists
|
||||
"""
|
||||
self.__check_auth()
|
||||
self.body['browseId'] = 'FEmusic_liked_playlists'
|
||||
endpoint = 'browse'
|
||||
response = self.__send_request(endpoint)
|
||||
results = response['contents']['singleColumnBrowseResultsRenderer']['tabs'][0]['tabRenderer']['content']['sectionListRenderer']['contents'][1]['itemSectionRenderer']['contents'][0]['gridRenderer']['items']
|
||||
playlists = []
|
||||
# skip first item ("New Playlist" button)
|
||||
for result in results[1:]:
|
||||
data = result['musicTwoRowItemRenderer']
|
||||
playlistId = data['title']['runs'][0]['navigationEndpoint']['browseEndpoint']['browseId'][2:]
|
||||
title = data['title']['runs'][0]['text']
|
||||
playlists.append({'playlistId': playlistId, 'title': title})
|
||||
|
||||
return playlists
|
||||
|
||||
def get_liked_songs(self, limit=1000):
|
||||
return self.get_playlist_items('LM', limit)
|
||||
|
||||
def get_history(self):
|
||||
self.__check_auth()
|
||||
self.body['browseId'] = 'FEmusic_history'
|
||||
endpoint = 'browse'
|
||||
response = self.__send_request(endpoint)
|
||||
raise NotImplementedError
|
||||
|
||||
def get_playlist_items(self, playlistId, limit=1000):
|
||||
"""
|
||||
Returns a list of playlist items
|
||||
:param playlistId: The playlist's id
|
||||
:param limit: How many songs to return. Default: 1000
|
||||
:return: List of playlistItem dictionaries, containing { videoId, artist, title, setVideoId }
|
||||
"""
|
||||
self.body['browseEndpointContextSupportedConfigs'] = {"browseEndpointContextMusicConfig": {"pageType": "MUSIC_PAGE_TYPE_PLAYLIST"}}
|
||||
self.body['browseId'] = "VL" + playlistId
|
||||
endpoint = 'browse'
|
||||
|
|
@ -62,33 +102,69 @@ class YTMusic:
|
|||
songs.extend(parse_songs(results['contents']))
|
||||
request_count = 1
|
||||
|
||||
while len(songs) < songs_to_get:
|
||||
print("requested from " + str(request_count * 100))
|
||||
while request_count * 100 < songs_to_get:
|
||||
ctoken = results['continuations'][0]['nextContinuationData']['continuation']
|
||||
print("requested from " + str(request_count * 100))
|
||||
additionalParams = "&ctoken=" + ctoken + "&continuation=" + ctoken
|
||||
|
||||
response = self.__send_request(endpoint, additionalParams)
|
||||
results = response['continuationContents']['musicPlaylistShelfContinuation']['contents']
|
||||
songs.extend(parse_songs(results))
|
||||
results = response['continuationContents']['musicPlaylistShelfContinuation']
|
||||
songs.extend(parse_songs(results['contents']))
|
||||
request_count += 1
|
||||
|
||||
return songs
|
||||
|
||||
def add_playlist(self, title, description, public=False):
|
||||
def create_playlist(self, title, description, privacy_status="PRIVATE"):
|
||||
"""
|
||||
Creates a new empty playlist and returns its id.
|
||||
:param title: Playlist title
|
||||
:param description: Playlist description
|
||||
:param privacy_status: Playlists can be 'PUBLIC', 'PRIVATE', or 'UNLISTED'. Default: 'PRIVATE'
|
||||
:return: ID of the YouTube playlist
|
||||
"""
|
||||
self.__check_auth()
|
||||
self.body['title'] = title
|
||||
self.body['description'] = description
|
||||
self.body['privacyStatus'] = 'PUBLIC' if public else 'PRIVATE'
|
||||
self.body['privacyStatus'] = privacy_status
|
||||
endpoint = 'playlist/create'
|
||||
response = self.__send_request(endpoint)
|
||||
return response['playlistId']
|
||||
|
||||
def edit_playlist(self, playlistId, title=None, description=None, privacyStatus=None):
|
||||
"""
|
||||
|
||||
:param playlistId: Playlist ID
|
||||
:param title: Optional. New title for the playlist
|
||||
:param description: Optional. New description for the playlist
|
||||
:param privacyStatus: Optional. New privacy status for the playlist
|
||||
:return: Request status
|
||||
"""
|
||||
self.__check_auth()
|
||||
self.body['playlistId'] = playlistId
|
||||
actions = []
|
||||
if title:
|
||||
actions.append({'action': 'ACTION_SET_PLAYLIST_NAME', 'playlistName': title})
|
||||
|
||||
if description:
|
||||
actions.append({'action': 'ACTION_SET_PLAYLIST_DESCRIPTION', 'playlistDescription': description})
|
||||
|
||||
if privacyStatus:
|
||||
actions.append({'action': 'ACTION_SET_PLAYLIST_PRIVACY', 'playlistPrivacy': privacyStatus})
|
||||
|
||||
self.body['actions'] = actions
|
||||
endpoint = 'browse/edit_playlist'
|
||||
response = self.__send_request(endpoint)
|
||||
return response['status'] if 'status' in response else response
|
||||
|
||||
def delete_playlist(self, playlistId):
|
||||
self.__check_auth()
|
||||
self.body['playlistId'] = playlistId
|
||||
endpoint = 'playlist/delete'
|
||||
response = self.__send_request(endpoint)
|
||||
return response['status'] if 'status' in response else response
|
||||
|
||||
def add_playlist_item(self, playlistId, videoId):
|
||||
self.__check_auth()
|
||||
self.body['playlistId'] = playlistId
|
||||
self.body['actions'] = {'action': 'ACTION_ADD_VIDEO', 'addedVideoId': videoId}
|
||||
endpoint = 'browse/edit_playlist'
|
||||
|
|
@ -96,12 +172,13 @@ class YTMusic:
|
|||
return response['status'] if 'status' in response else response
|
||||
|
||||
def remove_playlist_item(self, playlistId, song):
|
||||
if not song['removeAction']:
|
||||
self.__check_auth()
|
||||
if not song['setVideoId']:
|
||||
print("Cannot remove this song, since you don't own this playlist.")
|
||||
return
|
||||
|
||||
self.body['playlistId'] = playlistId
|
||||
self.body['actions'] = song['removeAction']
|
||||
self.body['actions'] = { 'setVideoId': song['setVideoId'], 'removedVideoId': song['videoId'], 'action': 'ACTION_REMOVE_VIDEO'}
|
||||
endpoint = 'browse/edit_playlist'
|
||||
response = self.__send_request(endpoint)
|
||||
return response['status'] if 'status' in response else response
|
||||
Loading…
Reference in a new issue