From d74e532dcdfd5f122e25aff8488ca2d02355cbc1 Mon Sep 17 00:00:00 2001 From: sigma67 Date: Tue, 14 Jul 2020 10:08:00 +0200 Subject: [PATCH] Feature: add get_song (#42) --- docs/source/reference.rst | 1 + tests/test.py | 4 ++ ytmusicapi/mixins/browsing.py | 104 ++++++++++++++++++++++++++++++++++ ytmusicapi/ytmusic.py | 2 +- 4 files changed, 110 insertions(+), 1 deletion(-) diff --git a/docs/source/reference.rst b/docs/source/reference.rst index 6157ea7..005fa8b 100644 --- a/docs/source/reference.rst +++ b/docs/source/reference.rst @@ -24,6 +24,7 @@ Browsing .. automethod:: YTMusic.get_artist .. automethod:: YTMusic.get_artist_albums .. automethod:: YTMusic.get_album +.. automethod:: YTMusic.get_song Library ------- diff --git a/tests/test.py b/tests/test.py index c284451..9df0060 100644 --- a/tests/test.py +++ b/tests/test.py @@ -60,6 +60,10 @@ class TestYTMusic(unittest.TestCase): self.assertEqual(len(results), 9) self.assertEqual(len(results['tracks']), 7) + def test_get_song(self): + song = youtube.get_song("ZrOKjDZOtkA") + self.assertGreaterEqual(len(song), 17) + ############### # LIBRARY ############### diff --git a/ytmusicapi/mixins/browsing.py b/ytmusicapi/mixins/browsing.py index ebd8d5c..00c634a 100644 --- a/ytmusicapi/mixins/browsing.py +++ b/ytmusicapi/mixins/browsing.py @@ -1,4 +1,8 @@ +import requests +import json +import codecs from typing import List, Dict +from urllib.parse import parse_qs from ytmusicapi.helpers import * from ytmusicapi.parsers import * @@ -371,3 +375,103 @@ class BrowsingMixin: album['tracks'].append(track) 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 diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index 0c2918f..7dd3b04 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -75,7 +75,7 @@ class YTMusic(BrowsingMixin, LibraryMixin, PlaylistsMixin, UploadsMixin): if language not in supported_languages: raise Exception("Language not supported. Supported languages are " ', '.join(supported_languages)) - + self.language = language try: locale.setlocale(locale.LC_ALL, language) except locale.Error: