Initial commit

This commit is contained in:
sigma67 2020-02-18 22:36:45 +01:00
commit 9032ea8d35
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
12 changed files with 310 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
.idea
headers_auth.json

2
MANIFEST.in Normal file
View file

@ -0,0 +1,2 @@
include README.md
include ytmusicapi/*.json

39
README.md Normal file
View file

@ -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.

11
headers_auth.json.example Normal file
View file

@ -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"
}

14
setup.py Normal file
View file

@ -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
)

6
ytmusicapi/__init__.py Normal file
View file

@ -0,0 +1,6 @@
from ytmusicapi._version import __version__
from ytmusicapi.ytmusic import YTMusic
__copyright__ = 'Copyright 2020 sigma67'
__license__ = 'MIT'
__title__ = 'ytmusicapi'

1
ytmusicapi/_version.py Normal file
View file

@ -0,0 +1 @@
__version__ = "0.1.0"

47
ytmusicapi/context.json Normal file
View file

@ -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
}
}
}

8
ytmusicapi/headers.json Normal file
View file

@ -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"
}

33
ytmusicapi/helpers.py Normal file
View file

@ -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

41
ytmusicapi/test.py Normal file
View file

@ -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()

106
ytmusicapi/ytmusic.py Normal file
View file

@ -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)