commit 9032ea8d354bbf655070f4d585e72ef67e918ab1 Author: sigma67 Date: Tue Feb 18 22:36:45 2020 +0100 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bb73e43 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea +headers_auth.json \ No newline at end of file diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..e6d02db --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +include README.md +include ytmusicapi/*.json \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..ba4bddd --- /dev/null +++ b/README.md @@ -0,0 +1,39 @@ +# ytmusicapi: Unofficial API for YouTube Music +A work-in-progress API that emulates web requests from the YouTube Music web client. + +Currently you need to extract your authentication data from your web browser and provide it through a file for it to work. + +Note: I have not tested this with any account other than my own. Please let me know if it works for you. + +## Requirements + +- Python 3 - https://www.python.org + +## Setup + +`pip install git+https://github.com/sigma67/ytmusicapi` + +###Authenticated requests +To run authenticated requests you need to copy your request headers from a POST request in your YTMusic Web Client. +To do so, follow these steps: +- Copy `headers_auth.json.example` to `headers_auth.json` +- Open YTMusic in Firefox +- Go to the developer tools (Ctrl-Shift-I) and right click a POST request. +- Copy the request headers (right click > copy > copy request headers) +- Paste the three missing items to `headers_auth.json` + +## Usage +Unauthenticated requests for retrieving playlist content or searching: +``` +from ytmusicapi import YTMusic +ytmusic = YTMusic() +``` + +Authenticated request to interact with your playlist (requires setting up your credentials in `headers_auth.json`): +``` +from ytmusicapi import YTMusic +ytmusic = YTMusic('headers_auth.json') +``` + +## Contributing +Pull requests are welcome. There are still lots of features unimplemented, for example retrieving content from the library and other parts of YTMusic. \ No newline at end of file diff --git a/headers_auth.json.example b/headers_auth.json.example new file mode 100644 index 0000000..d548167 --- /dev/null +++ b/headers_auth.json.example @@ -0,0 +1,11 @@ +{ + "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", + "x-origin": "https://music.youtube.com", + "Authorization": "PASTE_AUTHORIZATION", + "X-Youtube-Identity-Token": "PASTE_IDENTITY", + "Cookie" : "PASTE_COOKIE" +} \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..35bf9c6 --- /dev/null +++ b/setup.py @@ -0,0 +1,14 @@ +from setuptools import setup, find_packages + +setup(name='ytmusicapi', + version='0.1', + description='Unofficial YTMusic API', + long_description=(open('README.md').read()), + url='https://github.com/sigma67/ytmusicapi', + author='sigma67', + author_email='', + license='MIT', + packages=find_packages(), + include_package_data=True, + zip_safe=False +) diff --git a/ytmusicapi/__init__.py b/ytmusicapi/__init__.py new file mode 100644 index 0000000..e7a438c --- /dev/null +++ b/ytmusicapi/__init__.py @@ -0,0 +1,6 @@ +from ytmusicapi._version import __version__ +from ytmusicapi.ytmusic import YTMusic + +__copyright__ = 'Copyright 2020 sigma67' +__license__ = 'MIT' +__title__ = 'ytmusicapi' \ No newline at end of file diff --git a/ytmusicapi/_version.py b/ytmusicapi/_version.py new file mode 100644 index 0000000..a68927d --- /dev/null +++ b/ytmusicapi/_version.py @@ -0,0 +1 @@ +__version__ = "0.1.0" \ No newline at end of file diff --git a/ytmusicapi/context.json b/ytmusicapi/context.json new file mode 100644 index 0000000..ff02c9f --- /dev/null +++ b/ytmusicapi/context.json @@ -0,0 +1,47 @@ +{ + "context": { + "activePlayers": [ + { + "playerContextParams": "Q0FFU0FnZ0I=" + } + ], + "capabilities": {}, + "client": { + "clientName": "WEB_REMIX", + "clientVersion": "0.1", + "experimentIds": [], + "experimentsToken": "", + "gl": "DE", + "hl": "en", + "locationInfo": { + "locationPermissionAuthorizationStatus": "LOCATION_PERMISSION_AUTHORIZATION_STATUS_UNSUPPORTED" + }, + "musicAppInfo": { + "musicActivityMasterSwitch": "MUSIC_ACTIVITY_MASTER_SWITCH_INDETERMINATE", + "musicLocationMasterSwitch": "MUSIC_LOCATION_MASTER_SWITCH_INDETERMINATE", + "pwaInstallabilityStatus": "PWA_INSTALLABILITY_STATUS_UNKNOWN" + }, + "utcOffsetMinutes": 60 + }, + "request": { + "internalExperimentFlags": [ + { + "key": "force_music_enable_outertube_tastebuilder_browse", + "value": "true" + }, + { + "key": "force_music_enable_outertube_playlist_detail_browse", + "value": "true" + }, + { + "key": "force_music_enable_outertube_search_suggestions", + "value": "true" + } + ], + "sessionIndex": {} + }, + "user": { + "enableSafetyMode": false + } + } +} \ No newline at end of file diff --git a/ytmusicapi/headers.json b/ytmusicapi/headers.json new file mode 100644 index 0000000..a49c6ec --- /dev/null +++ b/ytmusicapi/headers.json @@ -0,0 +1,8 @@ +{ + "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", + "x-origin": "https://music.youtube.com" +} \ No newline at end of file diff --git a/ytmusicapi/helpers.py b/ytmusicapi/helpers.py new file mode 100644 index 0000000..76d9368 --- /dev/null +++ b/ytmusicapi/helpers.py @@ -0,0 +1,33 @@ +## Static helper methods + +def parse_songs(results): + songs = [] + count = 1 + for result in results: + count += 1 + if not 'musicResponsiveListItemRenderer' in result: + continue + data = result['musicResponsiveListItemRenderer'] + try: + # if item is not playable, there is not videoId + if 'playNavigationEndpoint' in data['overlay']['musicItemThumbnailOverlayRenderer']['content']['musicPlayButtonRenderer']: + videoId = data['overlay']['musicItemThumbnailOverlayRenderer']['content']['musicPlayButtonRenderer']['playNavigationEndpoint']['watchEndpoint']['videoId'] + + # if playlist is not owned, removal is not possible + if 'menuServiceItemRenderer' in data['menu']['menuRenderer']['items'][4]: + removeAction = \ + data['menu']['menuRenderer']['items'][4]['menuServiceItemRenderer']['serviceEndpoint']['playlistEditEndpoint']['actions'][0] + else: + removeAction = None + + else: + videoId = None + + artist = data['flexColumns'][1]['musicResponsiveListItemFlexColumnRenderer']['text']['runs'][0]['text'] + title = data['flexColumns'][0]['musicResponsiveListItemFlexColumnRenderer']['text']['runs'][0]['text'] + song = {'videoId': videoId, 'artist': artist, 'title': title, 'removeAction': removeAction} + songs.append(song) + except Exception as e: + print("Item " + str(count) + ": " + str(e)) + + return songs \ No newline at end of file diff --git a/ytmusicapi/test.py b/ytmusicapi/test.py new file mode 100644 index 0000000..1684ebe --- /dev/null +++ b/ytmusicapi/test.py @@ -0,0 +1,41 @@ +from ytmusicapi.ytmusic import YTMusic + +# YTMusic.get_playlist_items("PLQwVIlKxHM6qgidcRDp0-KFY1JmdGS206") +youtube = YTMusic() +youtube_auth = YTMusic('../headers_auth.json') + +def get_foreign_playlist(): + songs = youtube.get_playlist_items("PLw-VjHDlEOgs658kAHR_LAaILBXb-s6Q5") + assert (len(songs) == 200) + + +def get_owned_playlist(): + songs = youtube_auth.get_playlist_items('PLQwVIlKxHM6oCeKLTsUx_w9CmWjHKdg68') + assert (len(songs) == 64) + +#end to end test adding playlist, adding item, deleting item, deleting playlist +def end2end(): + playlist = youtube_auth.add_playlist("test", "test description", False) + print(playlist) + response = youtube_auth.add_playlist_item(playlist, 'y0Hhvtmv0gk') + assert(response['status'] == 'STATUS_SUCCEEDED') + items = youtube_auth.get_playlist_items(playlist) + assert(len(items) == 1) + response = youtube_auth.remove_playlist_item(playlist, items[0]) + assert(response['status'] == 'STATUS_SUCCEEDED') + response = youtube_auth.delete_playlist(playlist) + assert(response['command']['handlePlaylistDeletionCommand']['playlistId'] == playlist) + +# youtube.add_playlist_item('PLQwVIlKxHM6p6LRH_53M7tvRXaz0eVzpa', 'y0Hhvtmv0gk') +# songs = youtube.get_playlist_items("PLw-VjHDlEOgs658kAHR_LAaILBXb-s6Q5") +# for song in songs: +# youtube.add_playlist_item('PLQwVIlKxHM6p6LRH_53M7tvRXaz0eVzpa', song['videoId']) +# songs = youtube.get_playlist_items("PLQwVIlKxHM6p6LRH_53M7tvRXaz0eVzpa") +# for song in songs: +# youtube.remove_playlist_item("PLQwVIlKxHM6p6LRH_53M7tvRXaz0eVzpa", song['removeAction']) +# id = youtube.add_playlist("test3", "test description", True) +# youtube.remove_playlist_item('PLQwVIlKxHM6rPU4UadJV7UZf9miJcK-hm', 'cilnCQMJudo') +# YTMusic.search('lione revive') + +if __name__ == '__main__': + end2end() diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py new file mode 100644 index 0000000..d68725b --- /dev/null +++ b/ytmusicapi/ytmusic.py @@ -0,0 +1,106 @@ +import requests +import json +import pkg_resources +from ytmusicapi.helpers import parse_songs + +params = '?alt=json&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30' +base_url = 'https://music.youtube.com/youtubei/v1/' + +class YTMusic: + def __init__(self, auth=""): + self.auth = auth + file = auth if auth else pkg_resources.resource_filename('ytmusicapi', 'headers.json') + with open(file) as json_file: + self.headers = json.load(json_file) + + with open(pkg_resources.resource_filename('ytmusicapi','context.json')) as json_file: + self.body = json.load(json_file) + + def __send_request(self, endpoint, additionalParams=""): + response = requests.post(base_url + endpoint + params + additionalParams, json=self.body, headers=self.headers) + return json.loads(response.text) + + def search(self, query): + self.body['query'] = query + self.body['params'] = 'Eg-KAQwIARAAGAAgACgAMABqChAEEAMQCRAFEAo%3D' + endpoint = 'search' + + response = self.__send_request(endpoint) + results = response['contents']['sectionListRenderer']['contents'][0]['musicShelfRenderer']['contents'] + songs = [] + for result in results: + try: + data = result['musicResponsiveListItemRenderer'] + # videoId + videoId = data['overlay']['musicItemThumbnailOverlayRenderer']['content']['musicPlayButtonRenderer']['playNavigationEndpoint']['watchEndpoint']['videoId'] + artist = data['flexColumns'][1]['musicResponsiveListItemFlexColumnRenderer']['text']['runs'][0]['text'] + title = data['flexColumns'][0]['musicResponsiveListItemFlexColumnRenderer']['text']['runs'][0]['text'] + song = {'videoId': videoId, 'artist': artist, 'title': title} + songs.append(song) + except Exception as e: + print(str(e)) + + print(str(len(songs)) + " search results") + + return songs + + def get_playlist_items(self, playlistId, limit=1000): + self.body['browseEndpointContextSupportedConfigs'] = {"browseEndpointContextMusicConfig": {"pageType": "MUSIC_PAGE_TYPE_PLAYLIST"}} + self.body['browseId'] = "VL" + playlistId + endpoint = 'browse' + response = self.__send_request(endpoint) + results = response['contents']['singleColumnBrowseResultsRenderer']['tabs'][0]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['musicPlaylistShelfRenderer'] + songs = [] + if 'musicDetailHeaderRenderer' in response['header']: #playlist not owned + header = response['header']['musicDetailHeaderRenderer'] + else: + header = response['header']['musicEditablePlaylistDetailHeaderRenderer']['header']['musicDetailHeaderRenderer'] + song_count = int(header['secondSubtitle']['runs'][0]['text'].split(' ')[0]) + songs_to_get = min(limit, song_count) + songs.extend(parse_songs(results['contents'])) + request_count = 1 + + while len(songs) < songs_to_get: + print("requested from " + str(request_count * 100)) + ctoken = results['continuations'][0]['nextContinuationData']['continuation'] + additionalParams = "&ctoken=" + ctoken + "&continuation=" + ctoken + + response = self.__send_request(endpoint, additionalParams) + results = response['continuationContents']['musicPlaylistShelfContinuation']['contents'] + songs.extend(parse_songs(results)) + request_count += 1 + + print(len(songs)) + return songs + + def add_playlist(self, title, description, public=False): + self.body['title'] = title + self.body['description'] = description + self.body['privacyStatus'] = 'PUBLIC' if public else 'PRIVATE' + endpoint = 'playlist/create' + response = self.__send_request(endpoint) + return response['playlistId'] + + def delete_playlist(self, playlistId): + self.body['playlistId'] = playlistId + endpoint = 'playlist/delete' + response = self.__send_request(endpoint) + print(response) + + def add_playlist_item(self, playlistId, videoId): + self.body['playlistId'] = playlistId + self.body['actions'] = {'action': 'ACTION_ADD_VIDEO', 'addedVideoId': videoId} + endpoint = 'browse/edit_playlist' + response = self.__send_request(endpoint) + print(response) + + def remove_playlist_item(self, playlistId, song): + if not song['removeAction']: + print("Cannot remove this song, since you don't own this playlist.") + return + + self.body['playlistId'] = playlistId + self.body['actions'] = song['removeAction'] + endpoint = 'browse/edit_playlist' + response = self.__send_request(endpoint) + print(response) \ No newline at end of file