get x-goog-visitor-id dynamically to avoid errors caused by its expiry
removed headers.json all headers provided by user are now used in the headers file created by setup.py instead of only required headers
This commit is contained in:
parent
391eb3f4aa
commit
048f17989a
7 changed files with 169 additions and 149 deletions
4
ytmusicapi/constants.py
Normal file
4
ytmusicapi/constants.py
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
YTM_DOMAIN = 'https://music.youtube.com/'
|
||||
YTM_BASE_API = YTM_DOMAIN + 'youtubei/v1/'
|
||||
YTM_PARAMS = '?alt=json&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30'
|
||||
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
{
|
||||
"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",
|
||||
"origin": "https://music.youtube.com",
|
||||
"X-Goog-Visitor-Id": "CgtWaTB2WWRDeEFUYyjhv-X8BQ%3D%3D"
|
||||
}
|
||||
|
|
@ -1,9 +1,11 @@
|
|||
import re
|
||||
import json
|
||||
from http.cookies import SimpleCookie
|
||||
from hashlib import sha1
|
||||
import time
|
||||
from functools import wraps
|
||||
import locale
|
||||
from ytmusicapi.constants import *
|
||||
|
||||
|
||||
def prepare_browse_endpoint(type, browseId):
|
||||
|
|
@ -44,6 +46,26 @@ def prepare_order_params(order):
|
|||
return order_params[orders.index(order)]
|
||||
|
||||
|
||||
def initialize_headers():
|
||||
return {
|
||||
"User-Agent": USER_AGENT,
|
||||
"Accept": "*/*",
|
||||
"Content-Type": "application/json",
|
||||
"origin": YTM_DOMAIN,
|
||||
"X-Goog-AuthUser": "0"
|
||||
}
|
||||
|
||||
|
||||
def get_visitor_id(request_func):
|
||||
response = request_func(YTM_DOMAIN)
|
||||
matches = re.findall(r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', response)
|
||||
visitor_id = ""
|
||||
if len(matches) > 0:
|
||||
ytcfg = json.loads(matches[0])
|
||||
visitor_id = ytcfg.get('VISITOR_DATA')
|
||||
return {'X-Goog-Visitor-Id': visitor_id}
|
||||
|
||||
|
||||
def html_to_txt(html_text):
|
||||
tags = re.findall("<[^>]+>", html_text)
|
||||
for tag in tags:
|
||||
|
|
|
|||
|
|
@ -1,8 +1,5 @@
|
|||
import requests
|
||||
import json
|
||||
import codecs
|
||||
from urllib.parse import parse_qs
|
||||
from typing import List, Dict
|
||||
from ytmusicapi.helpers import *
|
||||
from ytmusicapi.parsers.browsing import *
|
||||
from ytmusicapi.parsers.albums import *
|
||||
|
|
@ -140,9 +137,6 @@ class BrowsingMixin:
|
|||
param2 = 'BAAGAAgASgA'
|
||||
elif filter == 'playlists':
|
||||
param2 = 'BAAGAAgACgB'
|
||||
elif filter == 'uploads':
|
||||
self.__check_auth()
|
||||
param2 = 'RABGAEgASgB'
|
||||
else:
|
||||
param2 = 'RAAGAAgACgA'
|
||||
params = param1 + param2 + param3
|
||||
|
|
@ -415,10 +409,9 @@ class BrowsingMixin:
|
|||
:param audioPlaylistId: id of the audio playlist (starting with `OLAK5uy_`)
|
||||
:return: browseId (starting with `MPREb_`)
|
||||
"""
|
||||
endpoint = "https://music.youtube.com/playlist"
|
||||
params = {"list": audioPlaylistId}
|
||||
response = requests.get(endpoint, params, headers=self.headers, proxies=self.proxies)
|
||||
matches = re.findall(r"\"MPRE.+?\"", response.text)
|
||||
response = self._send_get_request(YTM_DOMAIN + "playlist", params)
|
||||
matches = re.findall(r"\"MPRE.+?\"", response)
|
||||
browse_id = None
|
||||
if len(matches) > 0:
|
||||
browse_id = matches[0].encode('utf8').decode('unicode-escape').strip('"')
|
||||
|
|
@ -588,8 +581,8 @@ class BrowsingMixin:
|
|||
"""
|
||||
endpoint = "https://www.youtube.com/get_video_info"
|
||||
params = {"video_id": videoId, "hl": self.language, "el": "detailpage"}
|
||||
response = requests.get(endpoint, params, headers=self.headers, proxies=self.proxies)
|
||||
text = parse_qs(response.text)
|
||||
response = self._send_get_request(endpoint, params)
|
||||
text = parse_qs(response)
|
||||
if 'player_response' not in text:
|
||||
return text
|
||||
player_response = json.loads(text['player_response'][0])
|
||||
|
|
@ -709,8 +702,8 @@ class BrowsingMixin:
|
|||
"c": "WEB_REMIX",
|
||||
"cver": "0.1"
|
||||
}
|
||||
response = requests.get(endpoint, params, headers=self.headers, proxies=self.proxies)
|
||||
text = parse_qs(response.text)
|
||||
response = self._send_get_request(endpoint, params)
|
||||
text = parse_qs(response)
|
||||
if 'player_response' not in text:
|
||||
return text
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import pkg_resources
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
from ytmusicapi.helpers import *
|
||||
|
||||
path = os.path.dirname(os.path.realpath(__file__)) + os.sep
|
||||
|
||||
|
|
@ -20,32 +19,27 @@ def setup(filepath=None, headers_raw=None):
|
|||
else:
|
||||
contents = headers_raw.split('\n')
|
||||
|
||||
required_headers = ["Cookie", "X-Goog-AuthUser"]
|
||||
required_headers_lower = {v.lower(): v for v in required_headers }
|
||||
try:
|
||||
headers = {}
|
||||
user_headers = {}
|
||||
for content in contents:
|
||||
header = content.split(': ')
|
||||
key = header[0].lower()
|
||||
if key in required_headers_lower:
|
||||
headers[required_headers_lower[key]] = ': '.join(header[1:])
|
||||
user_headers[header[0]] = ': '.join(header[1:])
|
||||
|
||||
except Exception as e:
|
||||
raise Exception("Error parsing your input, please try again. Full error: " + str(e))
|
||||
|
||||
if len(headers) != len(required_headers):
|
||||
missing = set(required_headers) - set(headers)
|
||||
missing_headers = {"cookie", "x-goog-authuser"} - set(k.lower() for k in user_headers.keys())
|
||||
if missing_headers:
|
||||
raise Exception(
|
||||
"The following entries are missing in your headers: " + ", ".join(missing)
|
||||
"The following entries are missing in your headers: " + ", ".join(missing_headers)
|
||||
+ ". Please try a different request (such as /browse) and make sure you are logged in."
|
||||
)
|
||||
|
||||
with open(pkg_resources.resource_filename('ytmusicapi', 'headers.json')) as json_file:
|
||||
default_headers = json.load(json_file)
|
||||
headers = initialize_headers()
|
||||
headers.update(user_headers)
|
||||
|
||||
default_headers.update(headers)
|
||||
if filepath is not None:
|
||||
with open(filepath, 'w') as file:
|
||||
json.dump(default_headers, file, ensure_ascii=True, indent=4, sort_keys=True)
|
||||
json.dump(headers, file, ensure_ascii=True, indent=4, sort_keys=True)
|
||||
|
||||
return json.dumps(default_headers)
|
||||
return json.dumps(headers)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import requests
|
||||
import json
|
||||
import gettext
|
||||
import pkg_resources
|
||||
import os
|
||||
|
|
@ -14,9 +13,6 @@ from ytmusicapi.mixins.library import LibraryMixin
|
|||
from ytmusicapi.mixins.playlists import PlaylistsMixin
|
||||
from ytmusicapi.mixins.uploads import UploadsMixin
|
||||
|
||||
params = '?alt=json&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30'
|
||||
base_url = 'https://music.youtube.com/youtubei/v1/'
|
||||
|
||||
|
||||
class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMixin):
|
||||
"""
|
||||
|
|
@ -68,19 +64,29 @@ class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMi
|
|||
|
||||
self.proxies = proxies
|
||||
|
||||
try:
|
||||
if auth is None or os.path.isfile(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)
|
||||
else:
|
||||
self.headers = json.loads(auth)
|
||||
except Exception as e:
|
||||
print(
|
||||
"Failed loading provided credentials. Make sure to provide a string or a file path. "
|
||||
"Reason: " + str(e))
|
||||
# prepare headers
|
||||
self.headers = {}
|
||||
if auth:
|
||||
try:
|
||||
if os.path.isfile(auth):
|
||||
file = auth
|
||||
with open(file) as json_file:
|
||||
self.headers = json.load(json_file)
|
||||
else:
|
||||
self.headers = json.loads(auth)
|
||||
|
||||
except Exception as e:
|
||||
print(
|
||||
"Failed loading provided credentials. Make sure to provide a string or a file path. "
|
||||
"Reason: " + str(e))
|
||||
|
||||
else: # no authentication
|
||||
self.headers = initialize_headers()
|
||||
|
||||
if 'X-Goog-Visitor-Id' not in self.headers:
|
||||
self.headers.update(get_visitor_id(self._send_get_request))
|
||||
|
||||
# prepare context
|
||||
with open(pkg_resources.resource_filename('ytmusicapi', 'context.json')) as json_file:
|
||||
self.context = json.load(json_file)
|
||||
|
||||
|
|
@ -117,7 +123,7 @@ class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMi
|
|||
if self.auth:
|
||||
origin = self.headers.get('origin', self.headers.get('x-origin'))
|
||||
self.headers["Authorization"] = get_authorization(self.sapisid + ' ' + origin)
|
||||
response = self._session.post(base_url + endpoint + params + additionalParams,
|
||||
response = self._session.post(YTM_BASE_API + endpoint + YTM_PARAMS + additionalParams,
|
||||
json=body,
|
||||
headers=self.headers,
|
||||
proxies=self.proxies)
|
||||
|
|
@ -129,6 +135,10 @@ class YTMusic(BrowsingMixin, WatchMixin, LibraryMixin, PlaylistsMixin, UploadsMi
|
|||
raise Exception(message + error)
|
||||
return response_text
|
||||
|
||||
def _send_get_request(self, url: str, params: Dict = None):
|
||||
response = requests.get(url, params, headers=self.headers, proxies=self.proxies)
|
||||
return response.text
|
||||
|
||||
def _check_auth(self):
|
||||
if not self.auth:
|
||||
raise Exception("Please provide authentication before using this function")
|
||||
|
|
|
|||
Loading…
Reference in a new issue