Finalize 0.7.0 release (see release info for all changes)

This commit is contained in:
sigma67 2020-05-03 12:04:50 +02:00
commit 56f754367a
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
10 changed files with 517 additions and 193 deletions

1
.gitignore vendored
View file

@ -2,3 +2,4 @@
headers_auth.json headers_auth.json
docs/build docs/build
**.bat **.bat
**.cfg

View file

@ -12,10 +12,19 @@ such as retrieving your library content or creating large playlists.
Features Features
-------- --------
- Browsing: get artist information and releases (songs, videos, albums, singles), get albums - **Browsing**: get artist information and releases (songs, videos, albums, singles), get albums
- Library management: list, create, delete, and modify playlists and playlist items - **Library management**:
- Search: Search for songs on YouTube Music
- Uploads: Upload songs, list uploaded songs and delete uploaded songs * get the playlists, songs, artists, albums and subscriptions in your library
* rate songs, albums and playlists
* subscribe/unsubscribe artists
- **Playlists**: create, delete, and modify playlists and playlist items
- **Search**: Search for songs on YouTube Music
- **Uploads**:
* Upload songs and remove them again
* List uploaded songs, artists and albums
Usage Example Usage Example
------------- -------------

View file

@ -27,6 +27,10 @@ Browsing
Library Library
------- -------
.. automethod:: YTMusic.get_library_playlists
.. automethod:: YTMusic.get_library_songs
.. automethod:: YTMusic.get_library_artists
.. automethod:: YTMusic.get_library_albums
.. automethod:: YTMusic.get_liked_songs .. automethod:: YTMusic.get_liked_songs
.. automethod:: YTMusic.get_history .. automethod:: YTMusic.get_history
.. automethod:: YTMusic.rate_song .. automethod:: YTMusic.rate_song
@ -36,8 +40,7 @@ Library
Playlists Playlists
--------- ---------
.. automethod:: YTMusic.get_playlists .. automethod:: YTMusic.get_playlist
.. automethod:: YTMusic.get_playlist_items
.. automethod:: YTMusic.create_playlist .. automethod:: YTMusic.create_playlist
.. automethod:: YTMusic.edit_playlist .. automethod:: YTMusic.edit_playlist
.. automethod:: YTMusic.delete_playlist .. automethod:: YTMusic.delete_playlist
@ -46,6 +49,8 @@ Playlists
Uploads Uploads
------- -------
.. automethod:: YTMusic.get_uploaded_songs .. automethod:: YTMusic.get_library_upload_songs
.. automethod:: YTMusic.get_library_upload_artists
.. automethod:: YTMusic.get_library_upload_albums
.. automethod:: YTMusic.upload_song .. automethod:: YTMusic.upload_song
.. automethod:: YTMusic.delete_uploaded_song .. automethod:: YTMusic.delete_uploaded_song

View file

@ -34,3 +34,19 @@ With the :code:`ytmusic` instance you can now perform authenticated requests:
playlistId = ytmusic.create_playlist("test", "test description") playlistId = ytmusic.create_playlist("test", "test description")
search_results = ytmusic.search("Oasis Wonderwall") search_results = ytmusic.search("Oasis Wonderwall")
ytmusic.add_playlist_items(playlistId, [search_results[0]['videoId']]) ytmusic.add_playlist_items(playlistId, [search_results[0]['videoId']])
Brand accounts
##############
To send requests as a brand account, there is no need to change authentication credentials.
Simply provide the ID of the brand account when instantiating YTMusic.
You can get the ID from https://myaccount.google.com/ after selecting your brand account
(https://myaccount.google.com/b/21_digit_number).
Example:
.. code-block:: python
from ytmusicapi import YTMusic
ytmusic = YTMusic('headers_auth.json', 101234161234936123473)

View file

@ -5,7 +5,9 @@ Sometimes there is a single unittest for multiple functions to ensure there are
Note that there must be a `headers_auth.json` in the project root to run authenticated tests. Note that there must be a `headers_auth.json` in the project root to run authenticated tests.
For testing the song upload, there also needs to be a file with the name specified in the code in the project root. For testing the song upload, there also needs to be a file with the name specified in the code in the project root.
For `test_get_owned_playlist` you need to modify the test to
Copy `tests/test.cfg.example` to `test.cfg` in the project root to run tests with coverage.
Adjust the file to contain appropriate information for your YouTube account and local setup.
Coverage badge Coverage badge
-------------- --------------
@ -15,6 +17,6 @@ Install `coverage` and `coverage-badge` with pip. Run
to generate a coverage report in the project root. With to generate a coverage report in the project root. With
`coverage-badge -o coverage.svg` `coverage-badge -o tests/coverage.svg -f`
you generate the badge. Move both files to the `tests` directory. you generate the badge.

View file

@ -9,13 +9,13 @@
</mask> </mask>
<g mask="url(#a)"> <g mask="url(#a)">
<path fill="#555" d="M0 0h63v20H0z"/> <path fill="#555" d="M0 0h63v20H0z"/>
<path fill="#a4a61d" d="M63 0h36v20H63z"/> <path fill="#4c1" d="M63 0h36v20H63z"/>
<path fill="url(#b)" d="M0 0h99v20H0z"/> <path fill="url(#b)" d="M0 0h99v20H0z"/>
</g> </g>
<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"> <g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
<text x="31.5" y="15" fill="#010101" fill-opacity=".3">coverage</text> <text x="31.5" y="15" fill="#010101" fill-opacity=".3">coverage</text>
<text x="31.5" y="14">coverage</text> <text x="31.5" y="14">coverage</text>
<text x="80" y="15" fill="#010101" fill-opacity=".3">85%</text> <text x="80" y="15" fill="#010101" fill-opacity=".3">95%</text>
<text x="80" y="14">85%</text> <text x="80" y="14">95%</text>
</g> </g>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 904 B

After

Width:  |  Height:  |  Size: 901 B

Before After
Before After

10
tests/test.cfg.example Normal file
View file

@ -0,0 +1,10 @@
[auth]
brand_account = 101234229123420379537
headers = headers_auth_json_as_string
headers_file = ./headers_auth.json
[playlists]
own = owned_playlist_id
[uploads]
file = song_in_project_root.mp3

View file

@ -1,14 +1,18 @@
import unittest import unittest
import os import configparser
from ytmusicapi.ytmusic import YTMusic from ytmusicapi.ytmusic import YTMusic
config = configparser.RawConfigParser()
config.read('./test.cfg')
youtube = YTMusic() youtube = YTMusic()
youtube_auth = YTMusic('headers_auth.json') youtube_auth = YTMusic(config['auth']['headers_file'])
youtube_brand = YTMusic(config['auth']['headers'], config['auth']['brand_account'])
class TestYTMusic(unittest.TestCase): class TestYTMusic(unittest.TestCase):
def test_setup(self): def test_setup(self):
YTMusic.setup() YTMusic.setup(config['auth']['headers_file'])
############### ###############
# BROWSING # BROWSING
@ -17,6 +21,12 @@ class TestYTMusic(unittest.TestCase):
def test_search(self): def test_search(self):
results = youtube_auth.search("Oasis Wonderwall") results = youtube_auth.search("Oasis Wonderwall")
self.assertGreater(len(results), 0) self.assertGreater(len(results), 0)
results = youtube_auth.search("Oasis Wonderwall", 'videos')
self.assertGreater(len(results), 0)
results = youtube_auth.search("Oasis Wonderwall", 'albums')
self.assertGreater(len(results), 0)
results = youtube_auth.search("Oasis Wonderwall", 'artists')
self.assertGreater(len(results), 0)
def test_get_artist(self): def test_get_artist(self):
results = youtube.get_artist("UCmMUZbaYdNH0bEd1PAlAqsA") results = youtube.get_artist("UCmMUZbaYdNH0bEd1PAlAqsA")
@ -34,32 +44,36 @@ class TestYTMusic(unittest.TestCase):
def test_get_album(self): def test_get_album(self):
results = youtube.get_album("MPREb_BQZvl3BFGay") results = youtube.get_album("MPREb_BQZvl3BFGay")
self.assertEqual(len(results), 4) self.assertEqual(len(results), 8)
self.assertEqual(len(results['tracks']), 7) self.assertEqual(len(results['tracks']), 7)
############### ###############
# LIBRARY # LIBRARY
############### ###############
def test_get_playlists(self): def test_get_library_playlists(self):
playlists = youtube_auth.get_playlists() playlists = youtube_brand.get_library_playlists(50)
self.assertGreater(len(playlists), 0) self.assertGreater(len(playlists), 0)
def test_get_library_songs(self): def test_get_library_songs(self):
songs = youtube_auth.get_library_songs(); songs = youtube_brand.get_library_songs(200)
self.assertGreater(len(songs), 0) self.assertGreater(len(songs), 0)
def test_get_library_albums(self): def test_get_library_albums(self):
albums = youtube_auth.get_library_albums(); albums = youtube_brand.get_library_albums(50)
self.assertGreater(len(albums), 0) self.assertGreater(len(albums), 0)
def test_get_library_artists(self): def test_get_library_artists(self):
artists = youtube_auth.get_library_artists(); artists = youtube_brand.get_library_artists(50)
self.assertGreater(len(artists), 0)
def test_get_library_subscriptions(self):
artists = youtube_brand.get_library_subscriptions(50)
self.assertGreater(len(artists), 0) self.assertGreater(len(artists), 0)
def test_get_liked_songs(self): def test_get_liked_songs(self):
songs = youtube_auth.get_liked_songs(100) songs = youtube_brand.get_liked_songs(200)
self.assertGreater(len(songs), 0) self.assertGreater(len(songs['tracks']), 100)
def test_get_history(self): def test_get_history(self):
songs = youtube_auth.get_history() songs = youtube_auth.get_history()
@ -86,43 +100,60 @@ class TestYTMusic(unittest.TestCase):
############### ###############
def test_get_foreign_playlist(self): def test_get_foreign_playlist(self):
songs = youtube.get_playlist_items("PLw-VjHDlEOgs658kAHR_LAaILBXb-s6Q5") playlist = youtube.get_playlist("PLQwVIlKxHM6qv-o99iX9R85og7IzF9YS_", 200)
self.assertEqual(len(songs), 200) self.assertEqual(len(playlist['tracks']), 200)
def test_get_owned_playlist(self): def test_get_owned_playlist(self):
songs = youtube_auth.get_playlist_items('PL528pVfw3ao2VzfY6zE1TOZm1cBSdk7Q0') playlist = youtube_auth.get_playlist(config['playlists']['own'], 300)
self.assertEqual(len(songs), 287) self.assertEqual(len(playlist['tracks']), 284)
def test_edit_playlist(self):
playlist = youtube_auth.get_playlist(config['playlists']['own'])
response = youtube_auth.edit_playlist(playlist['id'], title='', description='', privacyStatus='PRIVATE')
self.assertEqual(response, 'STATUS_SUCCEEDED', "Playlist edit failed")
youtube_auth.edit_playlist(
playlist['id'], title=playlist['title'],
description=playlist['description'], privacyStatus=playlist['privacy'])
self.assertEqual(response, 'STATUS_SUCCEEDED', "Playlist edit failed")
# end to end test adding playlist, adding item, deleting item, deleting playlist
def test_end2end(self):
playlistId = youtube_auth.create_playlist("test", "test description")
self.assertEqual(len(playlistId), 34, "Playlist creation failed")
response = youtube_auth.add_playlist_items(playlistId, ['y0Hhvtmv0gk'])
self.assertEqual(response, 'STATUS_SUCCEEDED', "Adding playlist item failed")
playlist = youtube_auth.get_playlist(playlistId)
self.assertEqual(len(playlist['tracks']), 1, "Getting playlist items failed")
response = youtube_auth.remove_playlist_items(playlistId, playlist['tracks'])
self.assertEqual(response, 'STATUS_SUCCEEDED', "Playlist item removal failed")
response = youtube_auth.delete_playlist(playlistId)
self.assertEqual(response['command']['handlePlaylistDeletionCommand']['playlistId'], playlistId, "Playlist removal failed")
############### ###############
# UPLOADS # UPLOADS
############### ###############
def test_get_uploaded_songs(self): def test_get_library_upload_songs(self):
results = youtube_auth.get_uploaded_songs(126) results = youtube_auth.get_library_upload_songs(126)
self.assertGreater(len(results), 100) self.assertGreater(len(results), 100)
def test_get_library_upload_albums(self):
results = youtube_auth.get_library_upload_albums(50)
self.assertGreater(len(results), 25)
def test_get_library_upload_artists(self):
results = youtube_auth.get_library_upload_artists(50)
self.assertGreater(len(results), 25)
def test_upload_song(self): def test_upload_song(self):
response = youtube_auth.upload_song('12 - Turning Point 자.mp3') response = youtube_auth.upload_song(config['uploads']['file'])
self.assertEqual(response.status_code, 409) self.assertEqual(response.status_code, 409)
def test_delete_uploaded_song(self): def test_delete_uploaded_song(self):
results = youtube_auth.get_uploaded_songs() results = youtube_auth.get_library_upload_songs()
response = youtube_auth.delete_uploaded_song(results[0]) response = youtube_auth.delete_uploaded_song(results[0])
self.assertEqual(response, 'STATUS_SUCCEEDED') self.assertEqual(response, 'STATUS_SUCCEEDED')
# end to end test adding playlist, adding item, deleting item, deleting playlist
def test_end2end(self):
playlist = youtube_auth.create_playlist("test", "test description")
self.assertEqual(len(playlist), 34, "Playlist creation failed")
response = youtube_auth.add_playlist_items(playlist, ['y0Hhvtmv0gk'])
self.assertEqual(response, 'STATUS_SUCCEEDED', "Adding playlist item failed")
items = youtube_auth.get_playlist_items(playlist)
self.assertEqual(len(items), 1, "Getting playlist items failed")
response = youtube_auth.remove_playlist_items(playlist, items)
self.assertEqual(response, 'STATUS_SUCCEEDED', "Playlist item removal failed")
response = youtube_auth.delete_playlist(playlist)
self.assertEqual(response['command']['handlePlaylistDeletionCommand']['playlistId'], playlist, "Playlist removal failed")
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View file

@ -6,13 +6,82 @@ CONTINUATION = ['continuations', 0, 'nextContinuationData', 'continuation']
MENU_ITEMS = ['menu', 'menuRenderer', 'items'] MENU_ITEMS = ['menu', 'menuRenderer', 'items']
MENU_SERVICE = ['menuServiceItemRenderer', 'serviceEndpoint'] MENU_SERVICE = ['menuServiceItemRenderer', 'serviceEndpoint']
PLAY_BUTTON = ['overlay', 'musicItemThumbnailOverlayRenderer', 'content', 'musicPlayButtonRenderer'] PLAY_BUTTON = ['overlay', 'musicItemThumbnailOverlayRenderer', 'content', 'musicPlayButtonRenderer']
NAVIGATION_BROWSE_ID = ['navigationEndpoint', 'browseEndpoint', 'browseId']
NAVIGATION_VIDEO_ID = ['navigationEndpoint', 'watchEndpoint', 'videoId']
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, 'text'] TITLE = ['title', 'runs', 0]
TITLE_TEXT = ['title', 'runs', 0, 'text']
SUBTITLE = ['subtitle', 'runs', 0, 'text'] SUBTITLE = ['subtitle', 'runs', 0, 'text']
SUBTITLE2 = ['subtitle', 'runs', 2, 'text'] SUBTITLE2 = ['subtitle', 'runs', 2, 'text']
SUBTITLE3 = ['subtitle', 'runs', 4, 'text'] SUBTITLE3 = ['subtitle', 'runs', 4, 'text']
def parse_playlists(results):
playlists = []
for result in results:
data = result['musicTwoRowItemRenderer']
playlist = {}
playlist['playlistId'] = nav(data, TITLE + NAVIGATION_BROWSE_ID)[2:]
playlist['title'] = nav(data, TITLE_TEXT)
if len(data['subtitle']['runs']) == 3:
playlist['count'] = nav(data, SUBTITLE2).split(' ')[0]
playlists.append(playlist)
return playlists
def parse_artists(results, uploaded=False):
artists = []
for result in results:
data = result['musicResponsiveListItemRenderer']
artist = {}
artist['browseId'] = nav(data, NAVIGATION_BROWSE_ID)
artist['artist'] = get_item_text(data, 0)
if uploaded:
artist['songs'] = get_item_text(data, 1).split(' ')[0]
else:
subtitle = get_item_text(data, 1)
if subtitle:
artist['subscribers'] = subtitle.split(' ')[0]
artists.append(artist)
return artists
def parse_albums(results):
albums = []
for result in results:
data = result['musicTwoRowItemRenderer']
album = {}
album['browseId'] = nav(data, TITLE + NAVIGATION_BROWSE_ID)
album['title'] = nav(data, TITLE_TEXT)
album['type'] = nav(data, SUBTITLE)
album['artists'] = []
run_count = len(data['subtitle']['runs'])
has_artists = False
if run_count == 3:
if nav(data, SUBTITLE2).isdigit():
album['year'] = nav(data, SUBTITLE2)
else:
has_artists = True
elif run_count > 3:
album['year'] = nav(data, SUBTITLE3)
has_artists = True
if has_artists:
for i in range(1, int(run_count / 2)):
album['artists'].append({
'name': data['subtitle']['runs'][i * 2]['text'],
'id': nav(data['subtitle']['runs'][i * 2], NAVIGATION_BROWSE_ID)
})
albums.append(album)
return albums
def parse_playlist_items(results, owned=False): def parse_playlist_items(results, owned=False):
songs = [] songs = []
count = 1 count = 1
@ -36,10 +105,11 @@ def parse_playlist_items(results, owned=False):
if 'playNavigationEndpoint' in nav(data, PLAY_BUTTON): if 'playNavigationEndpoint' in nav(data, PLAY_BUTTON):
videoId = nav(data, PLAY_BUTTON)['playNavigationEndpoint']['watchEndpoint']['videoId'] videoId = nav(data, PLAY_BUTTON)['playNavigationEndpoint']['watchEndpoint']['videoId']
runs = [None] * 3 title = get_item_text(data, 0)
for i in range(len(runs)):
if 'text' in data['flexColumns'][i]['musicResponsiveListItemFlexColumnRenderer']: artists = parse_song_artists(data, 1)
runs[i] = get_item_text(data, i)
album = parse_song_album(data, 2)
duration = None duration = None
if 'fixedColumns' in data: if 'fixedColumns' in data:
@ -48,7 +118,7 @@ def parse_playlist_items(results, owned=False):
else: else:
duration = data['fixedColumns'][0]['musicResponsiveListItemFixedColumnRenderer']['text']['runs'][0]['text'] duration = data['fixedColumns'][0]['musicResponsiveListItemFixedColumnRenderer']['text']['runs'][0]['text']
song = {'videoId': videoId, 'title': runs[0], 'artist': runs[1], 'album': runs[2]} song = {'videoId': videoId, 'title': title, 'artists': artists, 'album': album}
if duration: if duration:
song['duration'] = duration song['duration'] = duration
if owned: if owned:
@ -96,10 +166,9 @@ def parse_search_result(data, resultType = None):
if resultType in ['song', 'video']: if resultType in ['song', 'video']:
search_result['videoId'] = nav(data, PLAY_BUTTON)['playNavigationEndpoint']['watchEndpoint']['videoId'] search_result['videoId'] = nav(data, PLAY_BUTTON)['playNavigationEndpoint']['watchEndpoint']['videoId']
search_result['title'] = get_item_text(data, 0) search_result['title'] = get_item_text(data, 0)
search_result['artist'] = get_item_text(data, 1 + default)
if resultType in ['artist', 'album', 'playlist']: if resultType in ['artist', 'album', 'playlist']:
search_result['browseId'] = data['navigationEndpoint']['browseEndpoint']['browseId'] search_result['browseId'] = nav(data, NAVIGATION_BROWSE_ID)
if resultType in ['artist']: if resultType in ['artist']:
search_result['artist'] = get_item_text(data, 0) search_result['artist'] = get_item_text(data, 0)
@ -116,12 +185,14 @@ def parse_search_result(data, resultType = None):
search_result['itemCount'] = get_item_text(data, 2 + default).split(' ')[0] search_result['itemCount'] = get_item_text(data, 2 + default).split(' ')[0]
elif resultType in ['song']: elif resultType in ['song']:
search_result['artists'] = parse_song_artists(data, 1 + default)
hasAlbum = len(data['flexColumns']) == 4 + default hasAlbum = len(data['flexColumns']) == 4 + default
if hasAlbum: if hasAlbum:
search_result['album'] = get_item_text(data, 2 + default) search_result['album'] = parse_song_album(data, 2 + default)
search_result['duration'] = get_item_text(data, 2 + hasAlbum + default) search_result['duration'] = get_item_text(data, 2 + hasAlbum + default)
elif resultType in ['video']: elif resultType in ['video']:
search_result['artist'] = get_item_text(data, 1 + default)
search_result['views'] = get_item_text(data, 2 + default).split(' ')[0] search_result['views'] = get_item_text(data, 2 + default).split(' ')[0]
search_result['duration'] = get_item_text(data, 3 + default) search_result['duration'] = get_item_text(data, 3 + default)
@ -130,11 +201,44 @@ def parse_search_result(data, resultType = None):
return search_result return search_result
def parse_song_artists(data, index):
flex_item = get_flex_column_item(data, index)
artists = []
for j in range(int(len(flex_item['text']['runs']) / 2) + 1):
artists.append({
'name': get_item_text(data, index, j * 2),
'id': get_browse_id(flex_item, j * 2)
})
return artists
def parse_song_album(data, index):
flex_item = get_flex_column_item(data, index)
return None if not flex_item else {
'name': get_item_text(data, index),
'id': get_browse_id(flex_item, 0)
}
def get_item_text(item, index, run_index=0): def get_item_text(item, index, run_index=0):
if 'runs' not in item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer']['text']: column = get_flex_column_item(item, index)
return column if not column else column['text']['runs'][run_index]['text']
def get_flex_column_item(item, index):
if 'text' not in item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer'] or \
'runs' not in item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer']['text']:
return None return None
return item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer']['text']['runs'][run_index]['text'] return item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer']
def get_browse_id(item, index):
if 'navigationEndpoint' not in item['text']['runs'][index]:
return None
else:
return nav(item['text']['runs'][index], NAVIGATION_BROWSE_ID)
def get_continuations(results, continuation_type, per_page, limit, request_func, parse_func): def get_continuations(results, continuation_type, per_page, limit, request_func, parse_func):
@ -145,7 +249,8 @@ def get_continuations(results, continuation_type, per_page, limit, request_func,
additionalParams = "&ctoken=" + ctoken + "&continuation=" + ctoken additionalParams = "&ctoken=" + ctoken + "&continuation=" + ctoken
response = request_func(additionalParams) response = request_func(additionalParams)
results = response['continuationContents'][continuation_type] results = response['continuationContents'][continuation_type]
items.extend(parse_func(results['contents'])) continuation_contents = 'contents' if 'Shelf' in continuation_type else 'items'
items.extend(parse_func(results[continuation_contents]))
request_count += 1 request_count += 1
return items return items
@ -157,8 +262,20 @@ def nav(root, items):
return root return root
def find_object_by_key(object_list, key): def find_object_by_key(object_list, key, nested=None):
for item in object_list: for item in object_list:
if nested:
item = item[nested]
if key in item: if key in item:
return item return item
return None return None
def find_objects_by_key(object_list, key, nested=None):
objects = []
for item in object_list:
if nested:
item = item[nested]
if key in item:
objects.append(item)
return objects

View file

@ -3,6 +3,7 @@ import json
import pkg_resources import pkg_resources
import ntpath import ntpath
import os import os
from typing import List, Dict, Union
from ytmusicapi.helpers import * from ytmusicapi.helpers import *
from ytmusicapi.parsers import * from ytmusicapi.parsers import *
from ytmusicapi.setup import setup from ytmusicapi.setup import setup
@ -17,7 +18,7 @@ class YTMusic:
Permits both authenticated and non-authenticated requests. Permits both authenticated and non-authenticated requests.
Authentication header data must be provided on initialization. Authentication header data must be provided on initialization.
""" """
def __init__(self, auth=None): def __init__(self, auth: str = None, user: str = None):
""" """
Create a new instance to interact with YouTube Music. Create a new instance to interact with YouTube Music.
@ -26,6 +27,11 @@ class YTMusic:
Should be an adjusted version of `headers_auth.json.example` in the project root. Should be an adjusted version of `headers_auth.json.example` in the project root.
See :py:func:`setup` for how to fill in the correct credentials. See :py:func:`setup` for how to fill in the correct credentials.
Default: A default header is used without authentication. Default: A default header is used without authentication.
:param user: Optional. Specify a user ID string to use in requests.
This is needed if you want to send requests on behalf of a brand account.
Otherwise the default account is used. You can retrieve the user ID
by going to https://myaccount.google.com and selecting your brand account.
The user ID will be in the URL: https://myaccount.google.com/b/user_id/
""" """
self.auth = auth self.auth = auth
@ -43,6 +49,8 @@ class YTMusic:
with open(pkg_resources.resource_filename('ytmusicapi', 'context.json')) as json_file: with open(pkg_resources.resource_filename('ytmusicapi', 'context.json')) as json_file:
self.context = json.load(json_file) self.context = json.load(json_file)
if user:
self.context['context']['user']['onBehalfOfUser'] = user
# verify authentication credentials work # verify authentication credentials work
if auth: if auth:
@ -51,7 +59,7 @@ class YTMusic:
if 'error' in response: if 'error' in response:
raise Exception("The provided credentials are invalid. Reason given by the server: " + response['error']['status']) raise Exception("The provided credentials are invalid. Reason given by the server: " + response['error']['status'])
def __send_request(self, endpoint, body, additionalParams=""): def __send_request(self, endpoint: str, body: Dict, additionalParams: str = ""):
body.update(self.context) body.update(self.context)
if self.auth: if self.auth:
self.headers["Authorization"] = get_authorization(self.sapisid + ' ' + self.headers['x-origin']) self.headers["Authorization"] = get_authorization(self.sapisid + ' ' + self.headers['x-origin'])
@ -63,7 +71,7 @@ class YTMusic:
raise Exception("Please provide authentication before using this function") raise Exception("Please provide authentication before using this function")
@classmethod @classmethod
def setup(cls, filepath=None): def setup(cls, filepath: str = None):
""" """
Requests browser headers from the user via command line Requests browser headers from the user via command line
and returns a string that can be passed to YTMusic() and returns a string that can be passed to YTMusic()
@ -77,11 +85,10 @@ class YTMusic:
# BROWSING # BROWSING
############### ###############
def search(self, query, filter=None): def search(self, query: str, filter: str = None) -> List[Dict]:
""" """
Search YouTube music Search YouTube music
Returns up to 20 results within the provided category. Returns up to 20 results within the provided category.
By default only songs (audio-only) are returned
:param query: Query string, i.e. 'Oasis Wonderwall' :param query: Query string, i.e. 'Oasis Wonderwall'
:param filter: Filter for item types. Allowed values: :param filter: Filter for item types. Allowed values:
@ -95,18 +102,22 @@ class YTMusic:
Example list:: Example list::
[ [
{ {
'videoId': 'ZrOKjDZOtkA', "videoId": "ZrOKjDZOtkA",
'artist': 'Oasis', "title": "Wonderwall (Remastered)",
'title': 'Wonderwall (Remastered)', "artists": [
'resultType': 'song' {
"name": "Oasis",
"id": "UCmMUZbaYdNH0bEd1PAlAqsA"
}
],
"album": {
"name": "(What's The Story) Morning Glory? (Remastered)",
"id": "MPREb_9nqEki4ZDpp"
}, },
{ "duration": "4:19",
'videoId': 'Gvfgut8nAgw', "resultType": "song"
'artist': 'Oasis', }
'title': 'Wonderwall',
'resultType': 'song'
}
] ]
@ -168,12 +179,12 @@ class YTMusic:
return search_results return search_results
def get_artist(self, channelId): def get_artist(self, channelId: str) -> Dict:
""" """
Get information about an artist and their top releases (songs, Get information about an artist and their top releases (songs,
albums, singles and videos). The top lists contain pointers albums, singles and videos). The top lists contain pointers
for getting the full list of releases. For songs/videos, pass for getting the full list of releases. For songs/videos, pass
the browseId to :py:func:`get_playlist_items`. For albums/singles, the browseId to :py:func:`get_playlist`. For albums/singles,
pass browseId and params to :py:func:`get_artist_albums`. pass browseId and params to :py:func:`get_artist_albums`.
:param channelId: channel id of the artist :param channelId: channel id of the artist
@ -238,12 +249,12 @@ class YTMusic:
results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST) results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST)
artist = {} artist = {}
artist['name'] = nav(response['header']['musicImmersiveHeaderRenderer'], TITLE) artist['name'] = nav(response['header']['musicImmersiveHeaderRenderer'], TITLE_TEXT)
artist['description'] = results[-1]['musicDescriptionShelfRenderer']['description']['runs'][0]['text'] artist['description'] = results[-1]['musicDescriptionShelfRenderer']['description']['runs'][0]['text']
artist['views'] = results[-1]['musicDescriptionShelfRenderer']['subheader']['runs'][0]['text'].split(' ')[0] artist['views'] = results[-1]['musicDescriptionShelfRenderer']['subheader']['runs'][0]['text'].split(' ')[0]
artist['songs'] = {} artist['songs'] = {}
if 'musicShelfRenderer' in results[0]: # API sometimes does not return songs if 'musicShelfRenderer' in results[0]: # API sometimes does not return songs
artist['songs']['browseId'] = results[0]['musicShelfRenderer']['title']['runs'][0]['navigationEndpoint']['browseEndpoint']['browseId'] artist['songs']['browseId'] = nav(results[0]['musicShelfRenderer'], TITLE + NAVIGATION_BROWSE_ID)
artist['songs']['results'] = parse_playlist_items(results[0]['musicShelfRenderer']['contents']) artist['songs']['results'] = parse_playlist_items(results[0]['musicShelfRenderer']['contents'])
categories = ['albums', 'singles', 'videos'] categories = ['albums', 'singles', 'videos']
@ -253,27 +264,28 @@ class YTMusic:
if len(data) > 0: if len(data) > 0:
artist[category] = {"results": []} artist[category] = {"results": []}
if 'navigationEndpoint' in nav(data[0], CAROUSEL_TITLE): if 'navigationEndpoint' in nav(data[0], CAROUSEL_TITLE):
artist[category]['browseId'] = nav(data[0], CAROUSEL_TITLE)['navigationEndpoint']['browseEndpoint']['browseId'] artist[category]['browseId'] = nav(data[0], CAROUSEL_TITLE + NAVIGATION_BROWSE_ID)
if category in ['albums', 'singles']: if category in ['albums', 'singles']:
artist[category]['params'] = nav(data[0], CAROUSEL_TITLE)['navigationEndpoint']['browseEndpoint']['params'] artist[category]['params'] = nav(data[0], CAROUSEL_TITLE)['navigationEndpoint']['browseEndpoint']['params']
for item in data[0]['contents']: for item in data[0]['contents']:
result = {'title': nav(item['musicTwoRowItemRenderer'], TITLE)} item = item['musicTwoRowItemRenderer']
result = {'title': nav(item, TITLE_TEXT)}
if category == 'albums': if category == 'albums':
result['year'] = nav(item['musicTwoRowItemRenderer'], SUBTITLE2) result['year'] = nav(item, SUBTITLE2)
result['browseId'] = item['musicTwoRowItemRenderer']['title']['runs'][0]['navigationEndpoint']['browseEndpoint']['browseId'] result['browseId'] = nav(item, TITLE + NAVIGATION_BROWSE_ID)
elif category == 'singles': elif category == 'singles':
result['year'] = nav(item['musicTwoRowItemRenderer'], SUBTITLE) result['year'] = nav(item, SUBTITLE)
result['browseId'] = item['musicTwoRowItemRenderer']['title']['runs'][0]['navigationEndpoint']['browseEndpoint']['browseId'] result['browseId'] = nav(item, TITLE + NAVIGATION_BROWSE_ID)
elif category == 'videos': elif category == 'videos':
result['views'] = nav(item['musicTwoRowItemRenderer'], SUBTITLE2).split(' ')[0] result['views'] = nav(item, SUBTITLE2).split(' ')[0]
result['videoId'] = item['musicTwoRowItemRenderer']['title']['runs'][0]['navigationEndpoint']['watchEndpoint']['videoId'] result['videoId'] = nav(item, TITLE + NAVIGATION_VIDEO_ID)
result['playlistId'] = item['musicTwoRowItemRenderer']['title']['runs'][0]['navigationEndpoint']['watchEndpoint']['playlistId'] result['playlistId'] = nav(item, TITLE + NAVIGATION_VIDEO_ID)
artist[category]['results'].append(result) artist[category]['results'].append(result)
return artist return artist
def get_artist_albums(self, channelId, params): def get_artist_albums(self, channelId: str, params: str) -> List[Dict]:
""" """
Get the full list of an artist's albums or singles Get the full list of an artist's albums or singles
@ -295,14 +307,14 @@ class YTMusic:
body = {"browseId": channelId, "params": params} body = {"browseId": channelId, "params": params}
endpoint = 'browse' endpoint = 'browse'
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
artist = nav(response['header']['musicHeaderRenderer'], TITLE) artist = nav(response['header']['musicHeaderRenderer'], TITLE_TEXT)
results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST) results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST)
albums = [] albums = []
musicShelf = results[0]['musicShelfRenderer'] musicShelf = results[0]['musicShelfRenderer']
release_type = nav(musicShelf, TITLE).lower() release_type = nav(musicShelf, TITLE_TEXT).lower()
for result in musicShelf['contents']: for result in musicShelf['contents']:
data = result['musicResponsiveListItemRenderer'] data = result['musicResponsiveListItemRenderer']
browseId = data['navigationEndpoint']['browseEndpoint']['browseId'] browseId = nav(data, NAVIGATION_BROWSE_ID)
title = get_item_text(data, 0) title = get_item_text(data, 0)
album_type = get_item_text(data, 1) if release_type == "albums" else "Single" album_type = get_item_text(data, 1) if release_type == "albums" else "Single"
year = get_item_text(data, 1, 2) if release_type == "albums" else get_item_text(data, 1) year = get_item_text(data, 1, 2) if release_type == "albums" else get_item_text(data, 1)
@ -310,7 +322,7 @@ class YTMusic:
return albums return albums
def get_album(self, browseId): def get_album(self, browseId: str) -> Dict:
""" """
Get information and tracks of an album Get information and tracks of an album
@ -332,12 +344,24 @@ class YTMusic:
body = prepare_browse_endpoint("ALBUM", browseId) body = prepare_browse_endpoint("ALBUM", browseId)
endpoint = 'browse' endpoint = 'browse'
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
data = nav(response, FRAMEWORK_MUTATIONS)
album = {} album = {}
album['title'] = nav(response, FRAMEWORK_MUTATIONS)[0]['payload']['musicAlbumRelease']['title'] album_data = find_object_by_key(data, 'musicAlbumRelease', 'payload')['musicAlbumRelease']
album['description'] = nav(response, FRAMEWORK_MUTATIONS)[1]['payload']['musicAlbumReleaseDetail']['description'] album['title'] = album_data['title']
album['artist'] = nav(response, FRAMEWORK_MUTATIONS)[3]['payload']['musicArtist']['name'] album['trackCount'] = album_data['trackCount']
album['durationMs'] = album_data['durationMs']
album['playlistId'] = album_data['audioPlaylistId']
album['releaseDate'] = album_data['releaseDate']
album['description'] = find_object_by_key(data, 'musicAlbumReleaseDetail', 'payload')['musicAlbumReleaseDetail']['description']
album['artist'] = []
artists_data = find_objects_by_key(data, 'musicArtist', 'payload')
for artist in artists_data:
album['artist'].append({
'name': artist['musicArtist']['name'],
'id': artist['musicArtist']['externalChannelId']
})
album['tracks'] = [] album['tracks'] = []
for item in nav(response, FRAMEWORK_MUTATIONS)[4:]: for item in data[4:]:
if 'musicTrack' in item['payload']: if 'musicTrack' in item['payload']:
track = {} track = {}
track['index'] = item['payload']['musicTrack']['albumTrackIndex'] track['index'] = item['payload']['musicTrack']['albumTrackIndex']
@ -354,10 +378,11 @@ class YTMusic:
# LIBRARY # LIBRARY
############### ###############
def get_playlists(self): def get_library_playlists(self, limit: int = 25) -> List[Dict]:
""" """
Retrieves the content of the 'Library' page Retrieves the playlists in the user's library.
:param limit: Number of playlists to retrieve
:return: List of owned playlists. :return: List of owned playlists.
Each item is in the following format:: Each item is in the following format::
@ -375,22 +400,24 @@ class YTMusic:
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
results = find_object_by_key(nav(response, SINGLE_COLUMN_TAB + SECTION_LIST), 'itemSectionRenderer') results = find_object_by_key(nav(response, SINGLE_COLUMN_TAB + SECTION_LIST), 'itemSectionRenderer')
results = nav(results, ITEM_SECTION)['gridRenderer']['items'] results = nav(results, ITEM_SECTION)['gridRenderer']
playlists = [] playlists = parse_playlists(results['items'][1:])
# skip first item ("New Playlist" button)
for result in results[1:]:
data = result['musicTwoRowItemRenderer']
playlist = {}
playlist['playlistId'] = data['title']['runs'][0]['navigationEndpoint']['browseEndpoint']['browseId'][2:]
playlist['title'] = nav(data, TITLE)
if len(data['subtitle']['runs']) == 3:
playlist['count'] = nav(data, SUBTITLE2).split(' ')[0]
playlists.append(playlist) if 'continuations' in results:
request_func = lambda additionalParams: self.__send_request(endpoint, body, additionalParams)
parse_func = lambda contents: parse_playlists(contents)
playlists.extend(get_continuations(results, 'gridContinuation', 25, limit, request_func, parse_func))
return playlists return playlists
def get_library_songs(self, limit=100): def get_library_songs(self, limit: int = 25) -> List[Dict]:
"""
Gets the songs in the user's library (liked videos are not included).
To get liked songs and videos, use :py:func:`get_liked_songs`
:param limit: Number of songs to retrieve
:return: List of songs. . Same format as :py:func:`get_playlist`
"""
self.__check_auth() self.__check_auth()
body = {'browseId': 'FEmusic_liked_videos'} body = {'browseId': 'FEmusic_liked_videos'}
endpoint = 'browse' endpoint = 'browse'
@ -402,68 +429,104 @@ class YTMusic:
if 'continuations' in results: if 'continuations' in results:
request_func = lambda additionalParams: self.__send_request(endpoint, body, additionalParams) request_func = lambda additionalParams: self.__send_request(endpoint, body, additionalParams)
parse_func = lambda contents: parse_playlist_items(contents) parse_func = lambda contents: parse_playlist_items(contents)
songs.extend(get_continuations(results, 'musicShelfContinuation', 100, limit, request_func, parse_func)) songs.extend(get_continuations(results, 'musicShelfContinuation', 25, limit, request_func, parse_func))
return songs return songs
def get_library_albums(self, upload=False): def get_library_albums(self, limit: int = 25) -> List[Dict]:
"""
Gets the albums in the user's library.
:param limit: Number of albums to return
:return: List of albums
"""
self.__check_auth() self.__check_auth()
if not upload: body = {'browseId': 'FEmusic_liked_albums'}
body = {'browseId': 'FEmusic_liked_albums'}
endpoint = 'browse' endpoint = 'browse'
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
results = find_object_by_key(nav(response, SINGLE_COLUMN_TAB + SECTION_LIST), 'itemSectionRenderer') results = find_object_by_key(nav(response, SINGLE_COLUMN_TAB + SECTION_LIST), 'itemSectionRenderer')
results = nav(results, ITEM_SECTION)['gridRenderer']['items'] results = nav(results, ITEM_SECTION)
albums = [] if 'gridRenderer' not in results:
# skip first item ("New Playlist" button) return []
for result in results: else:
data = result['musicTwoRowItemRenderer'] results = results['gridRenderer']
album = {} albums = parse_albums(results['items'])
album['browseId'] = data['title']['runs'][0]['navigationEndpoint']['browseEndpoint']['browseId']
album['title'] = nav(data, TITLE)
album['type'] = nav(data, SUBTITLE)
album['artist'] = nav(data, SUBTITLE2)
album['year'] = nav(data, SUBTITLE3)
albums.append(album)
#todo continuations if 'continuations' in results:
request_func = lambda additionalParams: self.__send_request(endpoint, body, additionalParams)
parse_func = lambda contents: parse_albums(contents)
albums.extend(get_continuations(results, 'gridContinuation', 25, limit, request_func, parse_func))
return albums return albums
def get_library_artists(self): def get_library_artists(self, limit: int = 25) -> List[Dict]:
"""
Gets the artists of the songs in the user's library.
:param limit: Number of artists to return
:return: List of artists.
Each item is in the following format::
{
"browseId": "UCxEqaQWosMHaTih-tgzDqug",
"artist": "WildVibes",
"subscribers": "2.91K"
}
"""
self.__check_auth()
body = {'browseId': 'FEmusic_library_corpus_track_artists'}
endpoint = 'browse'
response = self.__send_request(endpoint, body)
results = find_object_by_key(nav(response, SINGLE_COLUMN_TAB + SECTION_LIST), 'itemSectionRenderer')
results = nav(results, ITEM_SECTION)['musicShelfRenderer']
artists = parse_artists(results['contents'])
if 'continuations' in results:
request_func = lambda additionalParams: self.__send_request(endpoint, body, additionalParams)
parse_func = lambda contents: parse_artists(contents)
artists.extend(get_continuations(results, 'musicShelfContinuation', 25, limit, request_func, parse_func))
return artists
def get_library_subscriptions(self, limit: int = 25) -> List[Dict]:
"""
Gets the artists the user has subscribed to.
:param limit: Number of artists to return
:return: List of artists. Same format as :py:func:`get_library_artists`
"""
self.__check_auth() self.__check_auth()
body = {'browseId': 'FEmusic_library_corpus_artists'} body = {'browseId': 'FEmusic_library_corpus_artists'}
endpoint = 'browse' endpoint = 'browse'
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
results = find_object_by_key(nav(response, SINGLE_COLUMN_TAB + SECTION_LIST), 'itemSectionRenderer') results = find_object_by_key(nav(response, SINGLE_COLUMN_TAB + SECTION_LIST), 'itemSectionRenderer')
results = nav(results, ITEM_SECTION)['musicShelfRenderer'] results = nav(results, ITEM_SECTION)['musicShelfRenderer']
artists = [] artists = parse_artists(results['contents'])
for result in results['contents']:
data = result['musicResponsiveListItemRenderer']
browseId = data['navigationEndpoint']['browseEndpoint']['browseId']
artist = get_item_text(data, 0)
subscribers = get_item_text(data, 1).split(' ')[0]
artists.append({"browseId": browseId, "artist": artist, "subscribers": subscribers})
#todo continuations if 'continuations' in results:
request_func = lambda additionalParams: self.__send_request(endpoint, body, additionalParams)
parse_func = lambda contents: parse_artists(contents)
artists.extend(get_continuations(results, 'musicShelfContinuation', 25, limit, request_func, parse_func))
return artists return artists
def get_liked_songs(self, limit=1000): def get_liked_songs(self, limit: int = 100) -> Dict:
""" """
Gets playlist items for the 'Liked Songs' playlist Gets playlist items for the 'Liked Songs' playlist
:param limit: How many items to return. Default: 1000 :param limit: How many items to return. Default: 100
:return: List of playlistItem dictionaries. See :py:func:`get_playlist_items` :return: List of playlistItem dictionaries. See :py:func:`get_playlist`
""" """
return self.get_playlist_items('LM', limit) return self.get_playlist('LM', limit)
def get_history(self): def get_history(self) -> List[Dict]:
""" """
Gets your play history in reverse chronological order Gets your play history in reverse chronological order
:return: List of playlistItems, see :py:func:`get_playlist_items` :return: List of playlistItems, see :py:func:`get_playlist`
The additional property 'played' indicates when the playlistItem was played The additional property 'played' indicates when the playlistItem was played
""" """
self.__check_auth() self.__check_auth()
@ -476,12 +539,12 @@ class YTMusic:
data = content['musicShelfRenderer']['contents'] data = content['musicShelfRenderer']['contents']
songlist = parse_playlist_items(data) songlist = parse_playlist_items(data)
for song in songlist: for song in songlist:
song['played'] = nav(content['musicShelfRenderer'], TITLE) song['played'] = nav(content['musicShelfRenderer'], TITLE_TEXT)
songs.extend(songlist) songs.extend(songlist)
return songs return songs
def rate_song(self, videoId, rating='INDIFFERENT'): def rate_song(self, videoId: str, rating: str = 'INDIFFERENT') -> Dict:
""" """
Rates a song ("thumbs up"/"thumbs down" interactions on YouTube Music) Rates a song ("thumbs up"/"thumbs down" interactions on YouTube Music)
@ -500,12 +563,12 @@ class YTMusic:
return self.__send_request(endpoint, body) return self.__send_request(endpoint, body)
def rate_playlist(self, playlistId, rating='INDIFFERENT'): def rate_playlist(self, playlistId: str, rating: str = 'INDIFFERENT') -> Dict:
""" """
Rates a playlist/album ("Add to library"/"Remove from library" interactions on YouTube Music) Rates a playlist/album ("Add to library"/"Remove from library" interactions on YouTube Music)
You can also dislike a playlist/album, which has an effect on your recommendations You can also dislike a playlist/album, which has an effect on your recommendations
:param videoId: Video id :param playlistId: Playlist id
:param rating: One of 'LIKE', 'DISLIKE', 'INDIFFERENT' :param rating: One of 'LIKE', 'DISLIKE', 'INDIFFERENT'
| 'INDIFFERENT' removes the playlist/album from the library | 'INDIFFERENT' removes the playlist/album from the library
@ -515,14 +578,11 @@ class YTMusic:
self.__check_auth() self.__check_auth()
body = {'target': {'playlistId': playlistId}} body = {'target': {'playlistId': playlistId}}
endpoint = prepare_like_endpoint(rating) endpoint = prepare_like_endpoint(rating)
if endpoint is None: return endpoint if not endpoint else self.__send_request(endpoint, body)
return
return self.__send_request(endpoint, body) def subscribe_artists(self, channelIds: List[str]) -> Dict:
def subscribe_artists(self, channelIds: list) -> dict:
""" """
Subscribe to artists. Adds the artists to your libary Subscribe to artists. Adds the artists to your library
:param channelIds: Artist channel ids :param channelIds: Artist channel ids
:return: Full response :return: Full response
@ -532,9 +592,9 @@ class YTMusic:
endpoint = 'subscription/subscribe' endpoint = 'subscription/subscribe'
return self.__send_request(endpoint, body) return self.__send_request(endpoint, body)
def unsubscribe_artists(self, channelIds: list) -> dict: def unsubscribe_artists(self, channelIds: List[str]) -> Dict:
""" """
Unsubscribe from artists. Removes the artists from your libary Unsubscribe from artists. Removes the artists from your library
:param channelIds: Artist channel ids :param channelIds: Artist channel ids
:return: Full response :return: Full response
@ -548,22 +608,46 @@ class YTMusic:
# PLAYLISTS # PLAYLISTS
############### ###############
def get_playlist_items(self, playlistId, limit=1000): def get_playlist(self, playlistId: str, limit: int = 100) -> Dict:
""" """
Returns a list of playlist items Returns a list of playlist items
:param playlistId: Playlist id :param playlistId: Playlist id
:param limit: How many songs to return. Default: 1000 :param limit: How many songs to return. Default: 100
:return: List of playlistItem dictionaries :return: List of playlistItem dictionaries
Each item is in the following format:: Each item is in the following format::
{ {
'videoId': 'PLQwVIlKxHM6rz0fDJVv_0UlXGEWf-bFys', "id": "PLQwVIlKxHM6qv-o99iX9R85og7IzF9YS_",
'artist': 'Artist', "privacy": "PUBLIC",
'title': 'Song Title', "title": "New EDM This Week 03/13/2020",
'album': None, "description": "Weekly r/EDM new release roundup. Created with github.com/sigma67/spotifyplaylist_to_gmusic",
'setVideoId': '56B44F6D10557CC6' "author": "sigmatics",
"year": "2020",
"duration": "6+ hours",
"trackCount": 237,
"tracks": [
{
"videoId": "bjGppZKiuFE",
"title": "Lost",
"artists": [
{
"name": "Guest Who",
"id": "UCkgCRdnnqWnUeIH7EIc3dBg"
},
{
"name": "Kate Wild",
"id": "UCwR2l3JfJbvB6aq0RnnJfWg"
}
],
"album": {
"name": "Lost",
"id": "MPREb_PxmzvDuqOnC"
},
"duration": "2:58"
}
]
} }
The setVideoId is the unique id of this playlist item and The setVideoId is the unique id of this playlist item and
@ -575,32 +659,46 @@ class YTMusic:
endpoint = 'browse' endpoint = 'browse'
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST)[0]['musicPlaylistShelfRenderer'] results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST)[0]['musicPlaylistShelfRenderer']
songs = [] playlist = {'id': results['playlistId']}
if 'musicDetailHeaderRenderer' in response['header']: #playlist not owned own_playlist = 'musicEditablePlaylistDetailHeaderRenderer' in response['header']
if not own_playlist:
header = response['header']['musicDetailHeaderRenderer'] header = response['header']['musicDetailHeaderRenderer']
playlist['privacy'] = 'PUBLIC'
else: else:
header = response['header']['musicEditablePlaylistDetailHeaderRenderer']['header']['musicDetailHeaderRenderer'] header = response['header']['musicEditablePlaylistDetailHeaderRenderer']
playlist['privacy'] = header['editHeader']['musicPlaylistEditHeaderRenderer']['privacy']
header = header['header']['musicDetailHeaderRenderer']
playlist['title'] = nav(header, TITLE_TEXT)
playlist['description'] = header['description']['runs'][0]['text']
run_count = len(header['subtitle']['runs'])
if run_count > 1:
playlist['author'] = nav(header, SUBTITLE2)
if run_count > 3:
playlist['year'] = nav(header, SUBTITLE3)
if len(header['secondSubtitle']['runs']) > 1: if len(header['secondSubtitle']['runs']) > 1:
song_count = int(header['secondSubtitle']['runs'][0]['text'].split(' ')[0]) song_count = int(header['secondSubtitle']['runs'][0]['text'].split(' ')[0])
playlist['duration'] = header['secondSubtitle']['runs'][2]['text']
else: else:
playlist['duration'] = header['secondSubtitle']['runs'][0]['text']
song_count = limit song_count = limit
if song_count == 0: playlist['trackCount'] = song_count
return songs playlist['tracks'] = []
own_playlist = 'musicEditablePlaylistDetailHeaderRenderer' in response['header'] if song_count > 0:
songs.extend(parse_playlist_items(results['contents'], own_playlist)) playlist['tracks'].extend(parse_playlist_items(results['contents'], own_playlist))
songs_to_get = min(limit, song_count) songs_to_get = min(limit, song_count)
if 'continuations' in results: if 'continuations' in results:
request_func = lambda additionalParams: self.__send_request(endpoint, body, additionalParams) request_func = lambda additionalParams: self.__send_request(endpoint, body, additionalParams)
parse_func = lambda contents: parse_playlist_items(contents, own_playlist) parse_func = lambda contents: parse_playlist_items(contents, own_playlist)
songs.extend(get_continuations(results, 'musicPlaylistShelfContinuation', 100, songs_to_get, request_func, parse_func)) playlist['tracks'].extend(get_continuations(results, 'musicPlaylistShelfContinuation', 100, songs_to_get, request_func, parse_func))
return songs return playlist
def create_playlist(self, title, description, privacy_status="PRIVATE"): def create_playlist(self, title: str, description: str, privacy_status: str = "PRIVATE") -> str:
""" """
Creates a new empty playlist and returns its id. Creates a new empty playlist and returns its id.
@ -619,7 +717,7 @@ class YTMusic:
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
return response['playlistId'] return response['playlistId']
def edit_playlist(self, playlistId, title=None, description=None, privacyStatus=None): def edit_playlist(self, playlistId: str, title: str = None, description: str = None, privacyStatus: str = None) -> Union[str, Dict]:
""" """
Edit title, description or privacyStatus of a playlist. Edit title, description or privacyStatus of a playlist.
@ -646,7 +744,7 @@ class YTMusic:
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
return response['status'] if 'status' in response else response return response['status'] if 'status' in response else response
def delete_playlist(self, playlistId): def delete_playlist(self, playlistId: str) -> Union[str, Dict]:
""" """
Delete a playlist. Delete a playlist.
@ -659,7 +757,7 @@ class YTMusic:
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
return response['status'] if 'status' in response else response return response['status'] if 'status' in response else response
def add_playlist_items(self, playlistId, videoIds): def add_playlist_items(self, playlistId: str, videoIds: List[str]) -> Union[str, Dict]:
""" """
Add songs to an existing playlist Add songs to an existing playlist
@ -679,19 +777,18 @@ class YTMusic:
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
return response['status'] if 'status' in response else response return response['status'] if 'status' in response else response
def remove_playlist_items(self, playlistId, videos): def remove_playlist_items(self, playlistId: str, videos: List[Dict]) -> Union[str, Dict]:
""" """
Remove songs from an existing playlist Remove songs from an existing playlist
:param playlistId: Playlist id :param playlistId: Playlist id
:param videos: List of PlaylistItems, see :py:func:`get_playlist_items`. :param videos: List of PlaylistItems, see :py:func:`get_playlist`.
Must contain videoId and setVideoId Must contain videoId and setVideoId
:return: Status String or full response :return: Status String or full response
""" """
self.__check_auth() self.__check_auth()
if not videos[0]['setVideoId']: if not videos[0]['setVideoId']:
print("Cannot remove songs, because setVideoId is missing. Do you own this playlist?") raise Exception("Cannot remove songs, because setVideoId is missing. Do you own this playlist?")
return
body = {'playlistId': playlistId, 'actions': []} body = {'playlistId': playlistId, 'actions': []}
for video in videos: for video in videos:
@ -709,7 +806,7 @@ class YTMusic:
# UPLOADS # UPLOADS
############### ###############
def get_uploaded_songs(self, limit=25): def get_library_upload_songs(self, limit: int = 25) -> List[Dict]:
""" """
Returns a list of uploaded songs Returns a list of uploaded songs
@ -743,19 +840,55 @@ class YTMusic:
return songs return songs
def get_uploaded_albums(self): def get_library_upload_albums(self, limit: int = 25) -> List[Dict]:
"""
Gets the albums of uploaded songs in the user's library.
:param limit: Number of albums to return
:returns List of albums as returned by :py:func:`get_library_albums`
"""
self.__check_auth() self.__check_auth()
body = {'browseId': 'FEmusic_library_privately_owned_albums'} body = {'browseId': 'FEmusic_library_privately_owned_releases'}
endpoint = 'browse' endpoint = 'browse'
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
results = find_object_by_key(nav(response, SINGLE_COLUMN_TAB + SECTION_LIST), 'itemSectionRenderer')
results = nav(results, ITEM_SECTION)
if 'gridRenderer' not in results:
return []
else:
results = results['gridRenderer']
albums = parse_albums(results['items'])
def get_library_upload_artists(self): if 'continuations' in results:
request_func = lambda additionalParams: self.__send_request(endpoint, body, additionalParams)
parse_func = lambda contents: parse_albums(contents)
albums.extend(get_continuations(results, 'gridContinuation', 25, limit, request_func, parse_func))
return albums
def get_library_upload_artists(self, limit: int = 25) -> List[Dict]:
"""
Gets the artists of uploaded songs in the user's library.
:param limit:
:returns List of artists as returned by :py:func:`get_library_artists`
"""
self.__check_auth() self.__check_auth()
body = {'browseId': 'FEmusic_library_privately_owned_artists'} body = {'browseId': 'FEmusic_library_privately_owned_artists'}
endpoint = 'browse' endpoint = 'browse'
response = self.__send_request(endpoint, body) response = self.__send_request(endpoint, body)
results = find_object_by_key(nav(response, SINGLE_COLUMN_TAB + SECTION_LIST), 'itemSectionRenderer')
results = nav(results, ITEM_SECTION)['musicShelfRenderer']
artists = parse_artists(results['contents'], True)
def upload_song(self, filepath): if 'continuations' in results:
request_func = lambda additionalParams: self.__send_request(endpoint, body, additionalParams)
parse_func = lambda contents: parse_artists(contents, True)
artists.extend(get_continuations(results, 'musicShelfContinuation', 25, limit, request_func, parse_func))
return artists
def upload_song(self, filepath: str) -> Union[str, requests.Response]:
""" """
Uploads a song to YouTube Music Uploads a song to YouTube Music
@ -764,7 +897,7 @@ class YTMusic:
""" """
self.__check_auth() self.__check_auth()
if not os.path.isfile(filepath): if not os.path.isfile(filepath):
return raise Exception("The provided file does not exist.")
supported_filetypes = ["mp3", "m4a", "wma", "flac", "ogg"] supported_filetypes = ["mp3", "m4a", "wma", "flac", "ogg"]
if os.path.splitext(filepath)[1][1:] not in supported_filetypes: if os.path.splitext(filepath)[1][1:] not in supported_filetypes:
@ -791,12 +924,12 @@ class YTMusic:
else: else:
return response return response
def delete_uploaded_song(self, uploaded_song): def delete_uploaded_song(self, uploaded_song: Dict) -> Union[str, Dict]:
""" """
Deletes a previously uploaded song Deletes a previously uploaded song
:param uploaded_song: The uploaded song to delete, :param uploaded_song: The uploaded song to delete,
e.g. retrieved from :py:func:`get_uploaded_songs` e.g. retrieved from :py:func:`get_library_upload_songs`
:return: Status String or error :return: Status String or error
""" """
self.__check_auth() self.__check_auth()