Feature: add get_song (#42)

This commit is contained in:
sigma67 2020-07-14 10:08:00 +02:00
commit d74e532dcd
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
4 changed files with 110 additions and 1 deletions

View file

@ -24,6 +24,7 @@ Browsing
.. automethod:: YTMusic.get_artist .. automethod:: YTMusic.get_artist
.. automethod:: YTMusic.get_artist_albums .. automethod:: YTMusic.get_artist_albums
.. automethod:: YTMusic.get_album .. automethod:: YTMusic.get_album
.. automethod:: YTMusic.get_song
Library Library
------- -------

View file

@ -60,6 +60,10 @@ class TestYTMusic(unittest.TestCase):
self.assertEqual(len(results), 9) self.assertEqual(len(results), 9)
self.assertEqual(len(results['tracks']), 7) self.assertEqual(len(results['tracks']), 7)
def test_get_song(self):
song = youtube.get_song("ZrOKjDZOtkA")
self.assertGreaterEqual(len(song), 17)
############### ###############
# LIBRARY # LIBRARY
############### ###############

View file

@ -1,4 +1,8 @@
import requests
import json
import codecs
from typing import List, Dict from typing import List, Dict
from urllib.parse import parse_qs
from ytmusicapi.helpers import * from ytmusicapi.helpers import *
from ytmusicapi.parsers import * from ytmusicapi.parsers import *
@ -371,3 +375,103 @@ class BrowsingMixin:
album['tracks'].append(track) album['tracks'].append(track)
return album return album
def get_song(self, video_id: str) -> Dict:
"""
Returns metadata about a song or video.
:param videoId: Video id
:return: Dictionary with song metadata.
Example::
{
"videoId": "ZrOKjDZOtkA",
"title": "Wonderwall (Remastered)",
"lengthSeconds": "259",
"keywords": [
"Oasis",
"(What's",
"..."
],
"channelId": "UCmMUZbaYdNH0bEd1PAlAqsA",
"isOwnerViewing": false,
"shortDescription": "Provided to YouTube by Ignition...",
"isCrawlable": true,
"thumbnail": {
"thumbnails": [
{
"url": "https://i.ytimg.com/vi/ZrOKjDZOtkA/maxresdefault.jpg",
"width": 1920,
"height": 1080
}
]
},
"averageRating": 4.5673099,
"allowRatings": true,
"viewCount": "18136380",
"author": "Oasis - Topic",
"isPrivate": false,
"isUnpluggedCorpus": false,
"isLiveContent": false,
"provider": "Ignition",
"artists": [
"Oasis"
],
"copyright": "℗ 2014 Big Brother Recordings ...",
"production": [
"Composer: Noel Gallagher",
"Lyricist: Noel Gallagher",
"Producer: Owen Morris & Noel Gallagher"
],
"release": "2014-09-29",
"streamingData": {
"expiresInSeconds": "21540",
"formats": [
{
"itag": 18,
"mimeType": "video/mp4; codecs=\"avc1.42001E, mp4a.40.2\"",
"bitrate": 306477,
"width": 360,
"height": 360,
"lastModified": "1574970034520502",
"contentLength": "9913027",
"quality": "medium",
"fps": 25,
"qualityLabel": "360p",
"projectionType": "RECTANGULAR",
"averageBitrate": 306419,
"audioQuality": "AUDIO_QUALITY_LOW",
"approxDurationMs": "258809",
"audioSampleRate": "44100",
"audioChannels": 2,
"signatureCipher": "..."
}
],
"adaptiveFormats": []
}
}
"""
endpoint = "https://www.youtube.com/get_video_info"
params = {"video_id": video_id, "hl": self.language, "el": "detailpage"}
response = requests.get(endpoint, params, headers=self.headers, proxies=self.proxies)
text = parse_qs(response.text)
if 'player_response' not in text:
return text
player_response = json.loads(text['player_response'][0])
song_meta = player_response['videoDetails']
if song_meta['shortDescription'].endswith("Auto-generated by YouTube."):
try:
description = song_meta['shortDescription'].split('\n\n')
for i, detail in enumerate(description):
description[i] = codecs.escape_decode(detail)[0].decode('utf-8')
song_meta['provider'] = description[0].replace('Provided to YouTube by ', '')
song_meta['artists'] = [artist for artist in description[1].split(' · ')[1:]]
song_meta['copyright'] = description[3]
song_meta['production'] = [pub for pub in description[5].split('\n')]
song_meta['release'] = description[4].replace('Released on: ', '')
except KeyError as e:
pass
song_meta['streamingData'] = player_response['streamingData']
return song_meta

View file

@ -75,7 +75,7 @@ class YTMusic(BrowsingMixin, LibraryMixin, PlaylistsMixin, UploadsMixin):
if language not in supported_languages: if language not in supported_languages:
raise Exception("Language not supported. Supported languages are " raise Exception("Language not supported. Supported languages are "
', '.join(supported_languages)) ', '.join(supported_languages))
self.language = language
try: try:
locale.setlocale(locale.LC_ALL, language) locale.setlocale(locale.LC_ALL, language)
except locale.Error: except locale.Error: