get x-goog-visitor-id dynamically to avoid errors caused by its expiry

removed headers.json
all headers provided by user are now used in the headers file created by setup.py instead of only required headers
This commit is contained in:
sigma67 2021-04-27 22:55:00 +02:00
commit 048f17989a
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
7 changed files with 169 additions and 149 deletions

View file

@ -1,4 +1,5 @@
import unittest import unittest
import unittest.mock
import configparser import configparser
import sys import sys
sys.path.insert(0, '..') sys.path.insert(0, '..')
@ -7,20 +8,25 @@ from ytmusicapi.ytmusic import YTMusic # noqa: E402
config = configparser.RawConfigParser() config = configparser.RawConfigParser()
config.read('./test.cfg', 'utf-8') config.read('./test.cfg', 'utf-8')
youtube = YTMusic(requests_session=False)
youtube_auth = YTMusic(config['auth']['headers_file'])
youtube_brand = YTMusic(config['auth']['headers'], config['auth']['brand_account'])
sample_album = "MPREb_4pL8gzRtw1p" # Eminem - Revival sample_album = "MPREb_4pL8gzRtw1p" # Eminem - Revival
sample_video = "ZrOKjDZOtkA" # Oasis - Wonderwall (Remastered) sample_video = "ZrOKjDZOtkA" # Oasis - Wonderwall (Remastered)
class TestYTMusic(unittest.TestCase): class TestYTMusic(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.yt = YTMusic(requests_session=False)
cls.yt_auth = YTMusic(config['auth']['headers_file'])
cls.yt_brand = YTMusic(config['auth']['headers'], config['auth']['brand_account'])
def test_init(self): def test_init(self):
self.assertRaises(Exception, YTMusic, "{}") self.assertRaises(Exception, YTMusic, "{}")
def test_setup(self): def test_setup(self):
YTMusic.setup(config['auth']['headers_file'], config['auth']['headers_raw']) headers = YTMusic.setup(config['auth']['headers_file'], config['auth']['headers_raw'])
self.assertGreaterEqual(len(headers), 2)
with unittest.mock.patch('builtins.input', return_value=config['auth']['headers_raw']):
self.assertGreaterEqual(len(headers), 2)
############### ###############
# BROWSING # BROWSING
@ -28,31 +34,31 @@ class TestYTMusic(unittest.TestCase):
def test_search(self): def test_search(self):
query = "Oasis Wonderwall" query = "Oasis Wonderwall"
self.assertRaises(Exception, youtube_auth.search, query, "song") self.assertRaises(Exception, self.yt_auth.search, query, "song")
results = youtube.search(query) results = self.yt.search(query)
self.assertGreater(len(results), 10) self.assertGreater(len(results), 10)
results = youtube_auth.search(query, 'songs') results = self.yt_auth.search(query, 'songs')
self.assertGreater(len(results), 10) self.assertGreater(len(results), 10)
results = youtube_auth.search(query, 'videos') results = self.yt_auth.search(query, 'videos')
self.assertGreater(len(results), 10) self.assertGreater(len(results), 10)
results = youtube_auth.search(query, 'albums', limit=40) results = self.yt_auth.search(query, 'albums', limit=40)
self.assertGreater(len(results), 20) self.assertGreater(len(results), 20)
results = youtube_auth.search(query, 'artists') results = self.yt_auth.search(query, 'artists')
self.assertGreater(len(results), 0) self.assertGreater(len(results), 0)
results = youtube_auth.search(query, 'playlists') results = self.yt_auth.search(query, 'playlists')
self.assertGreater(len(results), 5) self.assertGreater(len(results), 5)
def test_search_ignore_spelling(self): def test_search_ignore_spelling(self):
query = "Martin Stig Andersen - Deteriation" query = "Martin Stig Andersen - Deteriation"
results = youtube_auth.search(query, ignore_spelling=True) results = self.yt_auth.search(query, ignore_spelling=True)
self.assertGreater(len(results), 0) self.assertGreater(len(results), 0)
def test_search_uploads(self): def test_search_uploads(self):
results = youtube_auth.search('audiomachine', 'uploads', limit=40) results = self.yt_auth.search('audiomachine', 'uploads', limit=40)
self.assertGreater(len(results), 20) self.assertGreater(len(results), 20)
def test_get_artist(self): def test_get_artist(self):
results = youtube.get_artist("MPLAUCmMUZbaYdNH0bEd1PAlAqsA") results = self.yt.get_artist("MPLAUCmMUZbaYdNH0bEd1PAlAqsA")
self.assertEqual(len(results), 14) self.assertEqual(len(results), 14)
# test correctness of related artists # test correctness of related artists
@ -63,86 +69,86 @@ class TestYTMusic(unittest.TestCase):
if set(x.keys()) == {"browseId", "subscribers", "title", "thumbnails"} if set(x.keys()) == {"browseId", "subscribers", "title", "thumbnails"}
]), len(related)) ]), len(related))
results = youtube.get_artist("UCLZ7tlKC06ResyDmEStSrOw") # no album year results = self.yt.get_artist("UCLZ7tlKC06ResyDmEStSrOw") # no album year
self.assertGreaterEqual(len(results), 11) self.assertGreaterEqual(len(results), 11)
results = youtube.get_artist( results = self.yt.get_artist(
"UCDAPd3S5CBIEKXn-tvy57Lg") # no thumbnail, albums, subscribe count "UCDAPd3S5CBIEKXn-tvy57Lg") # no thumbnail, albums, subscribe count
self.assertGreaterEqual(len(results), 11) self.assertGreaterEqual(len(results), 11)
def test_get_artist_for_non_youtube_music_channel(self): def test_get_artist_for_non_youtube_music_channel(self):
# all YouTube channel IDs can be looked up in YouTube Music, but the page they return will not necessarily return any music content # all YouTube channel IDs can be looked up in YouTube Music, but the page they return will not necessarily return any music content
non_music_channel_id = "UCUcpVoi5KkJmnE3bvEhHR0Q" # e.g. https://music.youtube.com/channel/UCUcpVoi5KkJmnE3bvEhHR0Q non_music_channel_id = "UCUcpVoi5KkJmnE3bvEhHR0Q" # e.g. https://music.youtube.com/channel/UCUcpVoi5KkJmnE3bvEhHR0Q
self.assertRaises(ValueError, youtube.get_artist, non_music_channel_id) self.assertRaises(ValueError, self.yt.get_artist, non_music_channel_id)
def test_get_artist_albums(self): def test_get_artist_albums(self):
artist = youtube.get_artist("UCAeLFBCQS7FvI8PvBrWvSBg") artist = self.yt.get_artist("UCAeLFBCQS7FvI8PvBrWvSBg")
results = youtube.get_artist_albums(artist['albums']['browseId'], results = self.yt.get_artist_albums(artist['albums']['browseId'],
artist['albums']['params']) artist['albums']['params'])
self.assertGreater(len(results), 0) self.assertGreater(len(results), 0)
def test_get_artist_singles(self): def test_get_artist_singles(self):
artist = youtube_auth.get_artist("UCAeLFBCQS7FvI8PvBrWvSBg") artist = self.yt_auth.get_artist("UCAeLFBCQS7FvI8PvBrWvSBg")
results = youtube_auth.get_artist_albums(artist['singles']['browseId'], results = self.yt_auth.get_artist_albums(artist['singles']['browseId'],
artist['singles']['params']) artist['singles']['params'])
self.assertGreater(len(results), 0) self.assertGreater(len(results), 0)
def test_get_user(self): def test_get_user(self):
results = youtube.get_user("UC44hbeRoCZVVMVg5z0FfIww") results = self.yt.get_user("UC44hbeRoCZVVMVg5z0FfIww")
self.assertEqual(len(results), 3) self.assertEqual(len(results), 3)
def test_get_user_playlists(self): def test_get_user_playlists(self):
results = youtube.get_user("UCPVhZsC2od1xjGhgEc2NEPQ") results = self.yt.get_user("UCPVhZsC2od1xjGhgEc2NEPQ")
results = youtube.get_user_playlists("UCPVhZsC2od1xjGhgEc2NEPQ", results = self.yt.get_user_playlists("UCPVhZsC2od1xjGhgEc2NEPQ",
results['playlists']['params']) results['playlists']['params'])
self.assertGreater(len(results), 100) self.assertGreater(len(results), 100)
def test_get_album_browse_id(self): def test_get_album_browse_id(self):
browse_id = youtube.get_album_browse_id("OLAK5uy_nMr9h2VlS-2PULNz3M3XVXQj_P3C2bqaY") browse_id = self.yt.get_album_browse_id("OLAK5uy_nMr9h2VlS-2PULNz3M3XVXQj_P3C2bqaY")
self.assertEqual(browse_id, sample_album) self.assertEqual(browse_id, sample_album)
def test_get_album(self): def test_get_album(self):
results = youtube_auth.get_album(sample_album) results = self.yt_auth.get_album(sample_album)
self.assertGreaterEqual(len(results), 9) self.assertGreaterEqual(len(results), 9)
self.assertTrue(results['tracks'][0]['isExplicit']) self.assertTrue(results['tracks'][0]['isExplicit'])
self.assertIn('feedbackTokens', results['tracks'][0]) self.assertIn('feedbackTokens', results['tracks'][0])
results = youtube.get_album("MPREb_BQZvl3BFGay") results = self.yt.get_album("MPREb_BQZvl3BFGay")
self.assertEqual(len(results['tracks']), 7) self.assertEqual(len(results['tracks']), 7)
def test_get_song(self): def test_get_song(self):
song = youtube.get_song(sample_video) song = self.yt.get_song(sample_video)
self.assertGreaterEqual(len(song), 16) self.assertGreaterEqual(len(song), 16)
def test_get_streaming_data(self): def test_get_streaming_data(self):
streaming_data = youtube_auth.get_streaming_data(sample_video) streaming_data = self.yt_auth.get_streaming_data(sample_video)
self.assertGreaterEqual(len(streaming_data), 3) self.assertGreaterEqual(len(streaming_data), 3)
def test_get_lyrics(self): def test_get_lyrics(self):
playlist = youtube.get_watch_playlist(sample_video) playlist = self.yt.get_watch_playlist(sample_video)
lyrics_song = youtube.get_lyrics(playlist["lyrics"]) lyrics_song = self.yt.get_lyrics(playlist["lyrics"])
self.assertIsNotNone(lyrics_song["lyrics"]) self.assertIsNotNone(lyrics_song["lyrics"])
self.assertIsNotNone(lyrics_song["source"]) self.assertIsNotNone(lyrics_song["source"])
playlist = youtube.get_watch_playlist("9TnpB8WgW4s") playlist = self.yt.get_watch_playlist("9TnpB8WgW4s")
self.assertIsNone(playlist["lyrics"]) self.assertIsNone(playlist["lyrics"])
self.assertRaises(Exception, youtube.get_lyrics, playlist["lyrics"]) self.assertRaises(Exception, self.yt.get_lyrics, playlist["lyrics"])
############### ###############
# WATCH # WATCH
############### ###############
def test_get_watch_playlist(self): def test_get_watch_playlist(self):
playlist = youtube_auth.get_watch_playlist("9mWr4c_ig54", limit=50) playlist = self.yt_auth.get_watch_playlist("9mWr4c_ig54", limit=50)
self.assertGreater(len(playlist['tracks']), 45) self.assertGreater(len(playlist['tracks']), 45)
playlist = youtube_auth.get_watch_playlist("UoAf_y9Ok4k") # private track playlist = self.yt_auth.get_watch_playlist("UoAf_y9Ok4k") # private track
self.assertGreaterEqual(len(playlist['tracks']), 25) self.assertGreaterEqual(len(playlist['tracks']), 25)
def test_get_watch_playlist_shuffle(self): def test_get_watch_playlist_shuffle(self):
playlist = youtube.get_watch_playlist_shuffle( playlist = self.yt.get_watch_playlist_shuffle(
playlistId="OLAK5uy_lKgoGvlrWhX0EIPavQUXxyPed8Cj38AWc") playlistId="OLAK5uy_lKgoGvlrWhX0EIPavQUXxyPed8Cj38AWc")
self.assertEqual(len(playlist['tracks']), 12) self.assertEqual(len(playlist['tracks']), 12)
def test_get_watch_playlist_shuffle_playlist(self): def test_get_watch_playlist_shuffle_playlist(self):
playlist = youtube_auth.get_watch_playlist_shuffle( playlist = self.yt_auth.get_watch_playlist_shuffle(
videoId="u6XiiXJD0jg", playlistId="PL528pVfw3ao2VzfY6zE1TOZm1cBSdk7Q0", limit=99) videoId="u6XiiXJD0jg", playlistId="PL528pVfw3ao2VzfY6zE1TOZm1cBSdk7Q0", limit=99)
self.assertGreaterEqual(len(playlist['tracks']), 80) self.assertGreaterEqual(len(playlist['tracks']), 80)
@ -151,114 +157,114 @@ class TestYTMusic(unittest.TestCase):
############### ###############
def test_get_library_playlists(self): def test_get_library_playlists(self):
playlists = youtube_brand.get_library_playlists(50) playlists = self.yt_brand.get_library_playlists(50)
self.assertGreater(len(playlists), 25) self.assertGreater(len(playlists), 25)
def test_get_library_songs(self): def test_get_library_songs(self):
songs = youtube_brand.get_library_songs(100) songs = self.yt_brand.get_library_songs(100)
self.assertGreaterEqual(len(songs), 100) self.assertGreaterEqual(len(songs), 100)
songs = youtube_auth.get_library_songs(200, validate_responses=True) songs = self.yt_auth.get_library_songs(200, validate_responses=True)
self.assertGreaterEqual(len(songs), 200) self.assertGreaterEqual(len(songs), 200)
songs = youtube_auth.get_library_songs(order='a_to_z') songs = self.yt_auth.get_library_songs(order='a_to_z')
self.assertGreaterEqual(len(songs), 25) self.assertGreaterEqual(len(songs), 25)
songs = youtube_auth.get_library_songs(order='z_to_a') songs = self.yt_auth.get_library_songs(order='z_to_a')
self.assertGreaterEqual(len(songs), 25) self.assertGreaterEqual(len(songs), 25)
songs = youtube_auth.get_library_songs(order='recently_added') songs = self.yt_auth.get_library_songs(order='recently_added')
self.assertGreaterEqual(len(songs), 25) self.assertGreaterEqual(len(songs), 25)
def test_get_library_albums(self): def test_get_library_albums(self):
albums = youtube_auth.get_library_albums(100) albums = self.yt_auth.get_library_albums(100)
self.assertGreater(len(albums), 50) self.assertGreater(len(albums), 50)
albums = youtube_brand.get_library_albums(100, order='a_to_z') albums = self.yt_brand.get_library_albums(100, order='a_to_z')
self.assertGreater(len(albums), 50) self.assertGreater(len(albums), 50)
albums = youtube_brand.get_library_albums(100, order='z_to_a') albums = self.yt_brand.get_library_albums(100, order='z_to_a')
self.assertGreater(len(albums), 50) self.assertGreater(len(albums), 50)
albums = youtube_brand.get_library_albums(100, order='recently_added') albums = self.yt_brand.get_library_albums(100, order='recently_added')
self.assertGreater(len(albums), 50) self.assertGreater(len(albums), 50)
def test_get_library_artists(self): def test_get_library_artists(self):
artists = youtube_brand.get_library_artists(50) artists = self.yt_brand.get_library_artists(50)
self.assertGreater(len(artists), 40) self.assertGreater(len(artists), 40)
artists = youtube_brand.get_library_artists(order='a_to_z', limit=50) artists = self.yt_brand.get_library_artists(order='a_to_z', limit=50)
self.assertGreater(len(artists), 40) self.assertGreater(len(artists), 40)
artists = youtube_brand.get_library_artists(order='z_to_a') artists = self.yt_brand.get_library_artists(order='z_to_a')
self.assertGreater(len(artists), 20) self.assertGreater(len(artists), 20)
artists = youtube_brand.get_library_artists(order='recently_added') artists = self.yt_brand.get_library_artists(order='recently_added')
self.assertGreater(len(artists), 20) self.assertGreater(len(artists), 20)
def test_get_library_subscriptions(self): def test_get_library_subscriptions(self):
artists = youtube_brand.get_library_subscriptions(50) artists = self.yt_brand.get_library_subscriptions(50)
self.assertGreater(len(artists), 40) self.assertGreater(len(artists), 40)
artists = youtube_brand.get_library_subscriptions(order='a_to_z') artists = self.yt_brand.get_library_subscriptions(order='a_to_z')
self.assertGreater(len(artists), 20) self.assertGreater(len(artists), 20)
artists = youtube_brand.get_library_subscriptions(order='z_to_a') artists = self.yt_brand.get_library_subscriptions(order='z_to_a')
self.assertGreater(len(artists), 20) self.assertGreater(len(artists), 20)
artists = youtube_brand.get_library_subscriptions(order='recently_added') artists = self.yt_brand.get_library_subscriptions(order='recently_added')
self.assertGreater(len(artists), 20) self.assertGreater(len(artists), 20)
def test_get_liked_songs(self): def test_get_liked_songs(self):
songs = youtube_brand.get_liked_songs(200) songs = self.yt_brand.get_liked_songs(200)
self.assertGreater(len(songs['tracks']), 100) self.assertGreater(len(songs['tracks']), 100)
def test_get_history(self): def test_get_history(self):
songs = youtube_auth.get_history() songs = self.yt_auth.get_history()
self.assertGreater(len(songs), 0) self.assertGreater(len(songs), 0)
@unittest.skip @unittest.skip
def test_remove_history_items(self): def test_remove_history_items(self):
songs = youtube_auth.get_history() songs = self.yt_auth.get_history()
response = youtube_auth.remove_history_items( response = self.yt_auth.remove_history_items(
[songs[0]['feedbackToken'], songs[1]['feedbackToken']]) [songs[0]['feedbackToken'], songs[1]['feedbackToken']])
self.assertIn('feedbackResponses', response) self.assertIn('feedbackResponses', response)
def test_rate_song(self): def test_rate_song(self):
response = youtube_auth.rate_song(sample_video, 'LIKE') response = self.yt_auth.rate_song(sample_video, 'LIKE')
self.assertIn('actions', response) self.assertIn('actions', response)
response = youtube_auth.rate_song(sample_video, 'INDIFFERENT') response = self.yt_auth.rate_song(sample_video, 'INDIFFERENT')
self.assertIn('actions', response) self.assertIn('actions', response)
def test_edit_song_library_status(self): def test_edit_song_library_status(self):
album = youtube_brand.get_album(sample_album) album = self.yt_brand.get_album(sample_album)
response = youtube_brand.edit_song_library_status( response = self.yt_brand.edit_song_library_status(
album['tracks'][2]['feedbackTokens']['add']) album['tracks'][2]['feedbackTokens']['add'])
self.assertTrue(response['feedbackResponses'][0]['isProcessed']) self.assertTrue(response['feedbackResponses'][0]['isProcessed'])
response = youtube_brand.edit_song_library_status( response = self.yt_brand.edit_song_library_status(
album['tracks'][2]['feedbackTokens']['remove']) album['tracks'][2]['feedbackTokens']['remove'])
self.assertTrue(response['feedbackResponses'][0]['isProcessed']) self.assertTrue(response['feedbackResponses'][0]['isProcessed'])
def test_rate_playlist(self): def test_rate_playlist(self):
response = youtube_auth.rate_playlist('OLAK5uy_l3g4WcHZsEx_QuEDZzWEiyFzZl6pL0xZ4', 'LIKE') response = self.yt_auth.rate_playlist('OLAK5uy_l3g4WcHZsEx_QuEDZzWEiyFzZl6pL0xZ4', 'LIKE')
self.assertIn('actions', response) self.assertIn('actions', response)
response = youtube_auth.rate_playlist('OLAK5uy_l3g4WcHZsEx_QuEDZzWEiyFzZl6pL0xZ4', response = self.yt_auth.rate_playlist('OLAK5uy_l3g4WcHZsEx_QuEDZzWEiyFzZl6pL0xZ4',
'INDIFFERENT') 'INDIFFERENT')
self.assertIn('actions', response) self.assertIn('actions', response)
def test_subscribe_artists(self): def test_subscribe_artists(self):
youtube_auth.subscribe_artists(['UCUDVBtnOQi4c7E8jebpjc9Q', 'UCiMhD4jzUqG-IgPzUmmytRQ']) self.yt_auth.subscribe_artists(['UCUDVBtnOQi4c7E8jebpjc9Q', 'UCiMhD4jzUqG-IgPzUmmytRQ'])
youtube_auth.unsubscribe_artists(['UCUDVBtnOQi4c7E8jebpjc9Q', 'UCiMhD4jzUqG-IgPzUmmytRQ']) self.yt_auth.unsubscribe_artists(['UCUDVBtnOQi4c7E8jebpjc9Q', 'UCiMhD4jzUqG-IgPzUmmytRQ'])
############### ###############
# PLAYLISTS # PLAYLISTS
############### ###############
def test_get_foreign_playlist(self): def test_get_foreign_playlist(self):
playlist = youtube.get_playlist("PL6bPxvf5dW5clc3y9wAoslzqUrmkZ5c-u", 300) playlist = self.yt.get_playlist("PL6bPxvf5dW5clc3y9wAoslzqUrmkZ5c-u", 300)
self.assertGreater(len(playlist['tracks']), 200) self.assertGreater(len(playlist['tracks']), 200)
def test_get_owned_playlist(self): def test_get_owned_playlist(self):
playlist = youtube_auth.get_playlist(config['playlists']['own'], 300) playlist = self.yt_auth.get_playlist(config['playlists']['own'], 300)
self.assertGreater(len(playlist['tracks']), 200) self.assertGreater(len(playlist['tracks']), 200)
def test_edit_playlist(self): def test_edit_playlist(self):
playlist = youtube_auth.get_playlist(config['playlists']['own']) playlist = self.yt_auth.get_playlist(config['playlists']['own'])
response = youtube_auth.edit_playlist(playlist['id'], response = self.yt_auth.edit_playlist(playlist['id'],
title='', title='',
description='', description='',
privacyStatus='PRIVATE', privacyStatus='PRIVATE',
moveItem=(playlist['tracks'][1]['setVideoId'], moveItem=(playlist['tracks'][1]['setVideoId'],
playlist['tracks'][0]['setVideoId'])) playlist['tracks'][0]['setVideoId']))
self.assertEqual(response, 'STATUS_SUCCEEDED', "Playlist edit failed") self.assertEqual(response, 'STATUS_SUCCEEDED', "Playlist edit failed")
youtube_auth.edit_playlist(playlist['id'], self.yt_auth.edit_playlist(playlist['id'],
title=playlist['title'], title=playlist['title'],
description=playlist['description'], description=playlist['description'],
privacyStatus=playlist['privacy'], privacyStatus=playlist['privacy'],
@ -268,22 +274,22 @@ class TestYTMusic(unittest.TestCase):
# end to end test adding playlist, adding item, deleting item, deleting playlist # end to end test adding playlist, adding item, deleting item, deleting playlist
def test_end2end(self): def test_end2end(self):
playlistId = youtube_auth.create_playlist( playlistId = self.yt_auth.create_playlist(
"test", "test",
"test description", "test description",
source_playlist="OLAK5uy_lGQfnMNGvYCRdDq9ZLzJV2BJL2aHQsz9Y") source_playlist="OLAK5uy_lGQfnMNGvYCRdDq9ZLzJV2BJL2aHQsz9Y")
self.assertEqual(len(playlistId), 34, "Playlist creation failed") self.assertEqual(len(playlistId), 34, "Playlist creation failed")
response = youtube_auth.add_playlist_items( response = self.yt_auth.add_playlist_items(
playlistId, ['y0Hhvtmv0gk', sample_video], playlistId, ['y0Hhvtmv0gk', sample_video],
source_playlist='OLAK5uy_nvjTE32aFYdFN7HCyMv3cGqD3wqBb4Jow', source_playlist='OLAK5uy_nvjTE32aFYdFN7HCyMv3cGqD3wqBb4Jow',
duplicates=True) duplicates=True)
self.assertEqual(response["status"], 'STATUS_SUCCEEDED', "Adding playlist item failed") self.assertEqual(response["status"], 'STATUS_SUCCEEDED', "Adding playlist item failed")
self.assertGreater(len(response["playlistEditResults"]), 0, "Adding playlist item failed") self.assertGreater(len(response["playlistEditResults"]), 0, "Adding playlist item failed")
playlist = youtube_auth.get_playlist(playlistId) playlist = self.yt_auth.get_playlist(playlistId)
self.assertEqual(len(playlist['tracks']), 46, "Getting playlist items failed") self.assertEqual(len(playlist['tracks']), 46, "Getting playlist items failed")
response = youtube_auth.remove_playlist_items(playlistId, playlist['tracks']) response = self.yt_auth.remove_playlist_items(playlistId, playlist['tracks'])
self.assertEqual(response, 'STATUS_SUCCEEDED', "Playlist item removal failed") self.assertEqual(response, 'STATUS_SUCCEEDED', "Playlist item removal failed")
response = youtube_auth.delete_playlist(playlistId) response = self.yt_auth.delete_playlist(playlistId)
self.assertEqual(response['command']['handlePlaylistDeletionCommand']['playlistId'], self.assertEqual(response['command']['handlePlaylistDeletionCommand']['playlistId'],
playlistId, "Playlist removal failed") playlistId, "Playlist removal failed")
@ -292,55 +298,55 @@ class TestYTMusic(unittest.TestCase):
############### ###############
def test_get_library_upload_songs(self): def test_get_library_upload_songs(self):
results = youtube_auth.get_library_upload_songs(50) results = self.yt_auth.get_library_upload_songs(50)
self.assertGreater(len(results), 25) self.assertGreater(len(results), 25)
@unittest.skip("Must not have any uploaded songs to pass") @unittest.skip("Must not have any uploaded songs to pass")
def test_get_library_upload_songs_empty(self): def test_get_library_upload_songs_empty(self):
results = youtube_auth.get_library_upload_songs(100) results = self.yt_auth.get_library_upload_songs(100)
self.assertEquals(len(results), 0) self.assertEquals(len(results), 0)
def test_get_library_upload_albums(self): def test_get_library_upload_albums(self):
results = youtube_auth.get_library_upload_albums(50) results = self.yt_auth.get_library_upload_albums(50)
self.assertGreater(len(results), 40) self.assertGreater(len(results), 40)
@unittest.skip("Must not have any uploaded albums to pass") @unittest.skip("Must not have any uploaded albums to pass")
def test_get_library_upload_albums_empty(self): def test_get_library_upload_albums_empty(self):
results = youtube_auth.get_library_upload_albums(100) results = self.yt_auth.get_library_upload_albums(100)
self.assertEquals(len(results), 0) self.assertEquals(len(results), 0)
def test_get_library_upload_artists(self): def test_get_library_upload_artists(self):
results = youtube_auth.get_library_upload_artists(50) results = self.yt_auth.get_library_upload_artists(50)
self.assertGreater(len(results), 25) self.assertGreater(len(results), 25)
results = youtube_auth.get_library_upload_artists(50, order='a_to_z') results = self.yt_auth.get_library_upload_artists(50, order='a_to_z')
self.assertGreater(len(results), 25) self.assertGreater(len(results), 25)
results = youtube_auth.get_library_upload_artists(50, order='z_to_a') results = self.yt_auth.get_library_upload_artists(50, order='z_to_a')
self.assertGreater(len(results), 25) self.assertGreater(len(results), 25)
results = youtube_auth.get_library_upload_artists(50, order='recently_added') results = self.yt_auth.get_library_upload_artists(50, order='recently_added')
self.assertGreater(len(results), 25) self.assertGreater(len(results), 25)
@unittest.skip("Must not have any uploaded artsts to pass") @unittest.skip("Must not have any uploaded artsts to pass")
def test_get_library_upload_artists_empty(self): def test_get_library_upload_artists_empty(self):
results = youtube_auth.get_library_upload_artists(100) results = self.yt_auth.get_library_upload_artists(100)
self.assertEquals(len(results), 0) self.assertEquals(len(results), 0)
def test_upload_song(self): def test_upload_song(self):
self.assertRaises(Exception, youtube_auth.upload_song, 'song.wav') self.assertRaises(Exception, self.yt_auth.upload_song, 'song.wav')
response = youtube_auth.upload_song(config['uploads']['file']) response = self.yt_auth.upload_song(config['uploads']['file'])
self.assertEqual(response.status_code, 409) self.assertEqual(response.status_code, 409)
@unittest.skip("Do not delete uploads") @unittest.skip("Do not delete uploads")
def test_delete_upload_entity(self): def test_delete_upload_entity(self):
results = youtube_auth.get_library_upload_songs() results = self.yt_auth.get_library_upload_songs()
response = youtube_auth.delete_upload_entity(results[0]['entityId']) response = self.yt_auth.delete_upload_entity(results[0]['entityId'])
self.assertEqual(response, 'STATUS_SUCCEEDED') self.assertEqual(response, 'STATUS_SUCCEEDED')
def test_get_library_upload_album(self): def test_get_library_upload_album(self):
album = youtube_auth.get_library_upload_album(config['uploads']['private_album_id']) album = self.yt_auth.get_library_upload_album(config['uploads']['private_album_id'])
self.assertGreater(len(album['tracks']), 0) self.assertGreater(len(album['tracks']), 0)
def test_get_library_upload_artist(self): def test_get_library_upload_artist(self):
tracks = youtube_auth.get_library_upload_artist(config['uploads']['private_artist_id'], tracks = self.yt_auth.get_library_upload_artist(config['uploads']['private_artist_id'],
100) 100)
self.assertGreater(len(tracks), 0) self.assertGreater(len(tracks), 0)

4
ytmusicapi/constants.py Normal file
View file

@ -0,0 +1,4 @@
YTM_DOMAIN = 'https://music.youtube.com/'
YTM_BASE_API = YTM_DOMAIN + 'youtubei/v1/'
YTM_PARAMS = '?alt=json&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'

View file

@ -1,9 +0,0 @@
{
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0",
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.5",
"Content-Type": "application/json",
"X-Goog-AuthUser": "0",
"origin": "https://music.youtube.com",
"X-Goog-Visitor-Id": "CgtWaTB2WWRDeEFUYyjhv-X8BQ%3D%3D"
}

View file

@ -1,9 +1,11 @@
import re import re
import json
from http.cookies import SimpleCookie from http.cookies import SimpleCookie
from hashlib import sha1 from hashlib import sha1
import time import time
from functools import wraps from functools import wraps
import locale import locale
from ytmusicapi.constants import *
def prepare_browse_endpoint(type, browseId): def prepare_browse_endpoint(type, browseId):
@ -44,6 +46,26 @@ def prepare_order_params(order):
return order_params[orders.index(order)] return order_params[orders.index(order)]
def initialize_headers():
return {
"User-Agent": USER_AGENT,
"Accept": "*/*",
"Content-Type": "application/json",
"origin": YTM_DOMAIN,
"X-Goog-AuthUser": "0"
}
def get_visitor_id(request_func):
response = request_func(YTM_DOMAIN)
matches = re.findall(r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', response)
visitor_id = ""
if len(matches) > 0:
ytcfg = json.loads(matches[0])
visitor_id = ytcfg.get('VISITOR_DATA')
return {'X-Goog-Visitor-Id': visitor_id}
def html_to_txt(html_text): def html_to_txt(html_text):
tags = re.findall("<[^>]+>", html_text) tags = re.findall("<[^>]+>", html_text)
for tag in tags: for tag in tags:

View file

@ -1,8 +1,5 @@
import requests
import json
import codecs import codecs
from urllib.parse import parse_qs from urllib.parse import parse_qs
from typing import List, Dict
from ytmusicapi.helpers import * from ytmusicapi.helpers import *
from ytmusicapi.parsers.browsing import * from ytmusicapi.parsers.browsing import *
from ytmusicapi.parsers.albums import * from ytmusicapi.parsers.albums import *
@ -140,9 +137,6 @@ class BrowsingMixin:
param2 = 'BAAGAAgASgA' param2 = 'BAAGAAgASgA'
elif filter == 'playlists': elif filter == 'playlists':
param2 = 'BAAGAAgACgB' param2 = 'BAAGAAgACgB'
elif filter == 'uploads':
self.__check_auth()
param2 = 'RABGAEgASgB'
else: else:
param2 = 'RAAGAAgACgA' param2 = 'RAAGAAgACgA'
params = param1 + param2 + param3 params = param1 + param2 + param3
@ -415,10 +409,9 @@ class BrowsingMixin:
:param audioPlaylistId: id of the audio playlist (starting with `OLAK5uy_`) :param audioPlaylistId: id of the audio playlist (starting with `OLAK5uy_`)
:return: browseId (starting with `MPREb_`) :return: browseId (starting with `MPREb_`)
""" """
endpoint = "https://music.youtube.com/playlist"
params = {"list": audioPlaylistId} params = {"list": audioPlaylistId}
response = requests.get(endpoint, params, headers=self.headers, proxies=self.proxies) response = self._send_get_request(YTM_DOMAIN + "playlist", params)
matches = re.findall(r"\"MPRE.+?\"", response.text) matches = re.findall(r"\"MPRE.+?\"", response)
browse_id = None browse_id = None
if len(matches) > 0: if len(matches) > 0:
browse_id = matches[0].encode('utf8').decode('unicode-escape').strip('"') browse_id = matches[0].encode('utf8').decode('unicode-escape').strip('"')
@ -588,8 +581,8 @@ class BrowsingMixin:
""" """
endpoint = "https://www.youtube.com/get_video_info" endpoint = "https://www.youtube.com/get_video_info"
params = {"video_id": videoId, "hl": self.language, "el": "detailpage"} params = {"video_id": videoId, "hl": self.language, "el": "detailpage"}
response = requests.get(endpoint, params, headers=self.headers, proxies=self.proxies) response = self._send_get_request(endpoint, params)
text = parse_qs(response.text) text = parse_qs(response)
if 'player_response' not in text: if 'player_response' not in text:
return text return text
player_response = json.loads(text['player_response'][0]) player_response = json.loads(text['player_response'][0])
@ -709,8 +702,8 @@ class BrowsingMixin:
"c": "WEB_REMIX", "c": "WEB_REMIX",
"cver": "0.1" "cver": "0.1"
} }
response = requests.get(endpoint, params, headers=self.headers, proxies=self.proxies) response = self._send_get_request(endpoint, params)
text = parse_qs(response.text) text = parse_qs(response)
if 'player_response' not in text: if 'player_response' not in text:
return text return text

View file

@ -1,7 +1,6 @@
import pkg_resources
import json
import os import os
import platform import platform
from ytmusicapi.helpers import *
path = os.path.dirname(os.path.realpath(__file__)) + os.sep path = os.path.dirname(os.path.realpath(__file__)) + os.sep
@ -20,32 +19,27 @@ def setup(filepath=None, headers_raw=None):
else: else:
contents = headers_raw.split('\n') contents = headers_raw.split('\n')
required_headers = ["Cookie", "X-Goog-AuthUser"]
required_headers_lower = {v.lower(): v for v in required_headers }
try: try:
headers = {} user_headers = {}
for content in contents: for content in contents:
header = content.split(': ') header = content.split(': ')
key = header[0].lower() user_headers[header[0]] = ': '.join(header[1:])
if key in required_headers_lower:
headers[required_headers_lower[key]] = ': '.join(header[1:])
except Exception as e: except Exception as e:
raise Exception("Error parsing your input, please try again. Full error: " + str(e)) raise Exception("Error parsing your input, please try again. Full error: " + str(e))
if len(headers) != len(required_headers): missing_headers = {"cookie", "x-goog-authuser"} - set(k.lower() for k in user_headers.keys())
missing = set(required_headers) - set(headers) if missing_headers:
raise Exception( raise Exception(
"The following entries are missing in your headers: " + ", ".join(missing) "The following entries are missing in your headers: " + ", ".join(missing_headers)
+ ". Please try a different request (such as /browse) and make sure you are logged in." + ". Please try a different request (such as /browse) and make sure you are logged in."
) )
with open(pkg_resources.resource_filename('ytmusicapi', 'headers.json')) as json_file: headers = initialize_headers()
default_headers = json.load(json_file) headers.update(user_headers)
default_headers.update(headers)
if filepath is not None: if filepath is not None:
with open(filepath, 'w') as file: with open(filepath, 'w') as file:
json.dump(default_headers, file, ensure_ascii=True, indent=4, sort_keys=True) json.dump(headers, file, ensure_ascii=True, indent=4, sort_keys=True)
return json.dumps(default_headers) return json.dumps(headers)

View file

@ -1,5 +1,4 @@
import requests import requests
import json
import gettext import gettext
import pkg_resources import pkg_resources
import os import os
@ -14,9 +13,6 @@ from ytmusicapi.mixins.library import LibraryMixin
from ytmusicapi.mixins.playlists import PlaylistsMixin from ytmusicapi.mixins.playlists import PlaylistsMixin
from ytmusicapi.mixins.uploads import UploadsMixin from ytmusicapi.mixins.uploads import UploadsMixin
params = '?alt=json&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30'
base_url = 'https://music.youtube.com/youtubei/v1/'
class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMixin): class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMixin):
""" """
@ -68,19 +64,29 @@ class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMi
self.proxies = proxies self.proxies = proxies
try: # prepare headers
if auth is None or os.path.isfile(auth): self.headers = {}
file = auth if auth else pkg_resources.resource_filename( if auth:
'ytmusicapi', 'headers.json') try:
with open(file) as json_file: if os.path.isfile(auth):
self.headers = json.load(json_file) file = auth
else: with open(file) as json_file:
self.headers = json.loads(auth) self.headers = json.load(json_file)
except Exception as e: else:
print( self.headers = json.loads(auth)
"Failed loading provided credentials. Make sure to provide a string or a file path. "
"Reason: " + str(e))
except Exception as e:
print(
"Failed loading provided credentials. Make sure to provide a string or a file path. "
"Reason: " + str(e))
else: # no authentication
self.headers = initialize_headers()
if 'X-Goog-Visitor-Id' not in self.headers:
self.headers.update(get_visitor_id(self._send_get_request))
# prepare context
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)
@ -117,7 +123,7 @@ class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMi
if self.auth: if self.auth:
origin = self.headers.get('origin', self.headers.get('x-origin')) origin = self.headers.get('origin', self.headers.get('x-origin'))
self.headers["Authorization"] = get_authorization(self.sapisid + ' ' + origin) self.headers["Authorization"] = get_authorization(self.sapisid + ' ' + origin)
response = self._session.post(base_url + endpoint + params + additionalParams, response = self._session.post(YTM_BASE_API + endpoint + YTM_PARAMS + additionalParams,
json=body, json=body,
headers=self.headers, headers=self.headers,
proxies=self.proxies) proxies=self.proxies)
@ -129,6 +135,10 @@ class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMi
raise Exception(message + error) raise Exception(message + error)
return response_text return response_text
def _send_get_request(self, url: str, params: Dict = None):
response = requests.get(url, params, headers=self.headers, proxies=self.proxies)
return response.text
def _check_auth(self): def _check_auth(self):
if not self.auth: if not self.auth:
raise Exception("Please provide authentication before using this function") raise Exception("Please provide authentication before using this function")