Feature: Add upload_song, get_uploaded_songs, delete_uploaded_song
This commit is contained in:
parent
cc47ad7473
commit
5d237ddd3c
5 changed files with 137 additions and 5 deletions
|
|
@ -5,8 +5,6 @@ A work-in-progress API that emulates web requests from the YouTube Music web cli
|
||||||
|
|
||||||
Currently you need to extract your authentication data from your web browser and provide it through a file for it to work.
|
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.
|
|
||||||
|
|
||||||
Simple usage example:
|
Simple usage example:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
@ -26,7 +24,7 @@ Requirements
|
||||||
Setup and Usage
|
Setup and Usage
|
||||||
===============
|
===============
|
||||||
|
|
||||||
See the `Documentation <https://ytmusicapi.readthedocs.io/en/latest/reference.html>`_ for detailed instructions
|
See the `Documentation <https://ytmusicapi.readthedocs.io/en/latest/usage.html>`_ for detailed instructions
|
||||||
|
|
||||||
Contributing
|
Contributing
|
||||||
==============
|
==============
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ Features
|
||||||
--------
|
--------
|
||||||
- Library management: list, create, delete, and modify playlists and playlist items
|
- Library management: list, create, delete, and modify playlists and playlist items
|
||||||
- Search: Search for songs on YouTube Music
|
- Search: Search for songs on YouTube Music
|
||||||
|
- Uploads: Upload songs, list uploaded songs and delete uploaded songs
|
||||||
|
|
||||||
Usage Example
|
Usage Example
|
||||||
-------------
|
-------------
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,26 @@ def parse_playlist_items(results, owned=False):
|
||||||
|
|
||||||
return songs
|
return songs
|
||||||
|
|
||||||
|
def parse_uploaded_items(results):
|
||||||
|
songs = []
|
||||||
|
for result in results:
|
||||||
|
data = result['musicResponsiveListItemRenderer']
|
||||||
|
entityId = data['menu']['menuRenderer']['items'][-1]['menuNavigationItemRenderer']['navigationEndpoint'][
|
||||||
|
'confirmDialogEndpoint']['content']['confirmDialogRenderer']['confirmButton']['buttonRenderer']['command'][
|
||||||
|
'musicDeletePrivatelyOwnedEntityCommand']['entityId']
|
||||||
|
|
||||||
|
videoId = data['menu']['menuRenderer']['items'][0]['menuServiceItemRenderer']['serviceEndpoint'][
|
||||||
|
'queueAddEndpoint']['queueTarget']['videoId']
|
||||||
|
|
||||||
|
title = get_item_text(data, 0)
|
||||||
|
artist = get_item_text(data, 1)
|
||||||
|
album = get_item_text(data, 2)
|
||||||
|
|
||||||
|
song = {'entityId': entityId, 'videoId': videoId, 'artist': artist, 'title': title, 'album': album}
|
||||||
|
songs.append(song)
|
||||||
|
|
||||||
|
return songs
|
||||||
|
|
||||||
|
|
||||||
def parse_search_result(data, resultType = None):
|
def parse_search_result(data, resultType = None):
|
||||||
search_result = {}
|
search_result = {}
|
||||||
|
|
@ -88,9 +108,13 @@ def parse_search_result(data, resultType = None):
|
||||||
|
|
||||||
|
|
||||||
def get_item_text(item, index):
|
def get_item_text(item, index):
|
||||||
|
if not 'runs' in item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer']['text']:
|
||||||
|
return ''
|
||||||
|
|
||||||
return item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer']['text']['runs'][0]['text']
|
return item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer']['text']['runs'][0]['text']
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
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:
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,19 @@ class TestYTMusic(unittest.TestCase):
|
||||||
results = youtube_auth.search("Oasis Wonderwall")
|
results = youtube_auth.search("Oasis Wonderwall")
|
||||||
self.assertGreater(len(results), 0)
|
self.assertGreater(len(results), 0)
|
||||||
|
|
||||||
|
def test_get_uploaded_songs(self):
|
||||||
|
results = youtube_auth.get_uploaded_songs(50)
|
||||||
|
self.assertEqual(len(results), 50)
|
||||||
|
|
||||||
|
def test_upload_song(self):
|
||||||
|
response = youtube_auth.upload_song('../12 - Turning Point.mp3')
|
||||||
|
self.assertEqual(response, 'OK')
|
||||||
|
|
||||||
|
def test_delete_uploaded_song(self):
|
||||||
|
results = youtube_auth.get_uploaded_songs()
|
||||||
|
response = youtube_auth.delete_uploaded_song(results[0])
|
||||||
|
self.assertEqual(response, 'STATUS_SUCCEEDED')
|
||||||
|
|
||||||
# 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):
|
||||||
playlist = youtube_auth.create_playlist("test", "test description")
|
playlist = youtube_auth.create_playlist("test", "test description")
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,10 @@
|
||||||
import requests
|
import requests
|
||||||
import json
|
import json
|
||||||
import pkg_resources
|
import pkg_resources
|
||||||
|
import ntpath
|
||||||
|
import os
|
||||||
from ytmusicapi.helpers import \
|
from ytmusicapi.helpers import \
|
||||||
parse_playlist_items, parse_search_result, html_to_txt
|
parse_playlist_items, parse_uploaded_items, parse_search_result, html_to_txt
|
||||||
|
|
||||||
params = '?alt=json&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30'
|
params = '?alt=json&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30'
|
||||||
base_url = 'https://music.youtube.com/youtubei/v1/'
|
base_url = 'https://music.youtube.com/youtubei/v1/'
|
||||||
|
|
@ -353,7 +355,8 @@ class YTMusic:
|
||||||
Remove songs from an existing playlist
|
Remove songs from an existing playlist
|
||||||
|
|
||||||
:param playlistId: Playlist id
|
:param playlistId: Playlist id
|
||||||
:param videos: List of Dictionaries containing video information. Must contain videoId and setVideoId
|
:param videos: List of PlaylistItems, see :py:func:`get_playlist_items`.
|
||||||
|
Must contain videoId and setVideoId
|
||||||
:return: Status String or full response
|
:return: Status String or full response
|
||||||
"""
|
"""
|
||||||
self.__check_auth()
|
self.__check_auth()
|
||||||
|
|
@ -372,3 +375,96 @@ class YTMusic:
|
||||||
endpoint = 'browse/edit_playlist'
|
endpoint = 'browse/edit_playlist'
|
||||||
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 get_uploaded_songs(self, limit=25):
|
||||||
|
"""
|
||||||
|
Returns a list of uploaded songs
|
||||||
|
|
||||||
|
:param limit: How many songs to return. Default: 25
|
||||||
|
:return: List of uploaded songs.
|
||||||
|
|
||||||
|
Each item is in the following format::
|
||||||
|
|
||||||
|
{
|
||||||
|
"entityId": "t_po_CICr2crg7OWpchDpjPjrBA",
|
||||||
|
"videoId": "Uise6RPKoek",
|
||||||
|
"artist": "Coldplay",
|
||||||
|
"title": "A Sky Full Of Stars",
|
||||||
|
"album": "Ghost Stories"
|
||||||
|
}
|
||||||
|
|
||||||
|
"""
|
||||||
|
self.__check_auth()
|
||||||
|
endpoint = 'browse'
|
||||||
|
body = {"browseId": "FEmusic_library_privately_owned_tracks"}
|
||||||
|
response = self.__send_request(endpoint, body)
|
||||||
|
results = response['contents']['singleColumnBrowseResultsRenderer']['tabs'][0]['tabRenderer']['content']['sectionListRenderer']['contents'][1]['itemSectionRenderer']['contents'][0]['musicShelfRenderer']
|
||||||
|
songs = []
|
||||||
|
|
||||||
|
songs.extend(parse_uploaded_items(results['contents'][1:]))
|
||||||
|
|
||||||
|
request_count = 1
|
||||||
|
while request_count * 25 < limit:
|
||||||
|
ctoken = results['continuations'][0]['nextContinuationData']['continuation']
|
||||||
|
additionalParams = "&ctoken=" + ctoken + "&continuation=" + ctoken
|
||||||
|
response = self.__send_request(endpoint, body, additionalParams)
|
||||||
|
results = response['continuationContents']['musicShelfContinuation']
|
||||||
|
songs.extend(parse_uploaded_items(results['contents']))
|
||||||
|
request_count += 1
|
||||||
|
|
||||||
|
return songs
|
||||||
|
|
||||||
|
def upload_song(self, filepath):
|
||||||
|
"""
|
||||||
|
Uploads a song to YouTube Music
|
||||||
|
|
||||||
|
:param filepath: Path to the music file
|
||||||
|
:return: Status String or full response
|
||||||
|
"""
|
||||||
|
self.__check_auth()
|
||||||
|
if not os.path.isfile(filepath):
|
||||||
|
return
|
||||||
|
|
||||||
|
headers = self.headers
|
||||||
|
upload_url = "https://upload.youtube.com/upload/usermusic/http?authuser=0"
|
||||||
|
file = open(filepath, 'rb')
|
||||||
|
req = requests.Request('POST', upload_url,
|
||||||
|
files={'file': file},
|
||||||
|
headers=headers)
|
||||||
|
prepped = req.prepare()
|
||||||
|
filesize = str(int(prepped.headers['content-length']) -500)
|
||||||
|
|
||||||
|
body = "filename=" + ntpath.basename(filepath)
|
||||||
|
headers['content-type'] = 'application/x-www-form-urlencoded;charset=utf-8'
|
||||||
|
headers['X-Goog-Upload-Command'] = 'start'
|
||||||
|
headers['X-Goog-Upload-Header-Content-Length'] = filesize
|
||||||
|
headers['X-Goog-Upload-Protocol'] = 'resumable'
|
||||||
|
response = requests.post(upload_url, data=body, headers=headers)
|
||||||
|
headers['X-Goog-Upload-Command'] = 'upload, finalize'
|
||||||
|
headers['X-Goog-Upload-Offset'] = '0'
|
||||||
|
upload_url = response.headers['X-Goog-Upload-URL']
|
||||||
|
file.seek(0)
|
||||||
|
response = requests.post(upload_url, files={'file': file}, headers=headers)
|
||||||
|
file.close()
|
||||||
|
if response.status_code == 200:
|
||||||
|
return 'STATUS_SUCCEEDED'
|
||||||
|
else:
|
||||||
|
return response.content
|
||||||
|
|
||||||
|
def delete_uploaded_song(self, uploaded_song):
|
||||||
|
"""
|
||||||
|
Deletes a previously uploaded song
|
||||||
|
|
||||||
|
:param uploaded_song: The uploaded song to delete,
|
||||||
|
e.g. retrieved from :py:func:`get_uploaded_songs`
|
||||||
|
:return: Status String or error
|
||||||
|
"""
|
||||||
|
self.__check_auth()
|
||||||
|
endpoint = 'music/delete_privately_owned_entity'
|
||||||
|
body = {"entityId": uploaded_song['entityId']}
|
||||||
|
response = self.__send_request(endpoint, body)
|
||||||
|
|
||||||
|
if 'error' not in response:
|
||||||
|
return 'STATUS_SUCCEEDED'
|
||||||
|
else:
|
||||||
|
return response['error']
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue