add: integrate alt_oauth into YTMusic && add: token dict support for auth parameter
This commit is contained in:
parent
91949b5403
commit
6c94c80086
3 changed files with 62 additions and 21 deletions
|
|
@ -10,6 +10,7 @@ from requests import Response
|
|||
|
||||
from ytmusicapi.setup import main, setup # noqa: E402
|
||||
from ytmusicapi.ytmusic import YTMusic # noqa: E402
|
||||
from ytmusicapi.constants import OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET
|
||||
|
||||
|
||||
def get_resource(file: str) -> str:
|
||||
|
|
@ -27,6 +28,8 @@ sample_playlist = "PL6bPxvf5dW5clc3y9wAoslzqUrmkZ5c-u" # very large playlist
|
|||
headers_oauth = get_resource(config["auth"]["headers_oauth"])
|
||||
headers_browser = get_resource(config["auth"]["headers_file"])
|
||||
|
||||
alt_oauth_args = {'oauth_client_id': OAUTH_CLIENT_ID, 'oauth_client_secret': OAUTH_CLIENT_SECRET}
|
||||
|
||||
|
||||
class TestYTMusic(unittest.TestCase):
|
||||
|
||||
|
|
@ -37,6 +40,7 @@ class TestYTMusic(unittest.TestCase):
|
|||
assert isinstance(yt, YTMusic)
|
||||
cls.yt = YTMusic()
|
||||
cls.yt_oauth = YTMusic(headers_oauth)
|
||||
cls.yt_alt_oauth = YTMusic(headers_browser, alt_oauth=alt_oauth_args)
|
||||
cls.yt_auth = YTMusic(headers_browser, location="GB")
|
||||
cls.yt_brand = YTMusic(config["auth"]["headers"], config["auth"]["brand_account"])
|
||||
cls.yt_empty = YTMusic(config["auth"]["headers_empty"],
|
||||
|
|
@ -67,7 +71,14 @@ class TestYTMusic(unittest.TestCase):
|
|||
json_mock.side_effect = None
|
||||
with open(headers_oauth, mode="r", encoding="utf8") as headers:
|
||||
string_headers = headers.read()
|
||||
self.yt_oauth = YTMusic(string_headers)
|
||||
|
||||
self.yt_oauth = YTMusic(string_headers)
|
||||
with self.subTest():
|
||||
# ensure client works/ignores alt if browser credentials passed as auth
|
||||
self.assertFalse(self.yt_alt_oauth.is_alt_oauth)
|
||||
# oauth token dict entry and alt
|
||||
self.yt_alt_oauth = YTMusic(json.loads(string_headers), alt_oauth=alt_oauth_args)
|
||||
self.assertTrue(self.yt_alt_oauth.is_alt_oauth)
|
||||
|
||||
###############
|
||||
# BROWSING
|
||||
|
|
@ -148,10 +159,10 @@ class TestYTMusic(unittest.TestCase):
|
|||
def test_search_library(self):
|
||||
results = self.yt_oauth.search(config['queries']['library_any'], scope="library")
|
||||
self.assertGreater(len(results), 5)
|
||||
results = self.yt_auth.search(config['queries']['library_songs'],
|
||||
filter="songs",
|
||||
scope="library",
|
||||
limit=40)
|
||||
results = self.yt_alt_oauth.search(config['queries']['library_songs'],
|
||||
filter="songs",
|
||||
scope="library",
|
||||
limit=40)
|
||||
self.assertGreater(len(results), 10)
|
||||
results = self.yt_auth.search(config['queries']['library_albums'],
|
||||
filter="albums",
|
||||
|
|
@ -243,7 +254,7 @@ class TestYTMusic(unittest.TestCase):
|
|||
|
||||
def test_get_song_related_content(self):
|
||||
song = self.yt_oauth.get_watch_playlist(sample_video)
|
||||
song = self.yt_oauth.get_song_related(song["related"])
|
||||
song = self.yt_alt_oauth.get_song_related(song["related"])
|
||||
self.assertGreaterEqual(len(song), 5)
|
||||
|
||||
def test_get_lyrics(self):
|
||||
|
|
|
|||
|
|
@ -20,16 +20,26 @@ def load_headers_file(auth: str) -> Dict:
|
|||
return input_json
|
||||
|
||||
|
||||
def prepare_headers(
|
||||
session: requests.Session,
|
||||
proxies: Optional[Dict] = None,
|
||||
input_dict: Optional[CaseInsensitiveDict] = None,
|
||||
) -> Dict:
|
||||
def prepare_headers(auth_session: requests.Session | YTMusicOAuth,
|
||||
proxies: Optional[Dict] = None,
|
||||
input_dict: Optional[CaseInsensitiveDict] = None) -> Dict:
|
||||
"""
|
||||
|
||||
:param auth_session: Either the session to be used when creating a YTMusicOAuth
|
||||
instance or the YTMusicOAuth instance itself.
|
||||
:param proxies: Optional. Proxy configuration parameters passed to session.
|
||||
Ignored if YTMusicOAuth instance passed to function.
|
||||
:param input_dict: Optional. Either completed browser auth headers or oauth token.
|
||||
"""
|
||||
if input_dict:
|
||||
|
||||
if is_oauth(input_dict):
|
||||
oauth = YTMusicOAuth(session, proxies)
|
||||
headers = oauth.load_headers(dict(input_dict), input_dict['filepath'])
|
||||
if isinstance(auth_session, YTMusicOAuth):
|
||||
oauth = auth_session
|
||||
else:
|
||||
oauth = YTMusicOAuth(auth_session, proxies)
|
||||
|
||||
headers = oauth.load_headers(dict(input_dict), input_dict.get('filepath'))
|
||||
|
||||
elif is_browser(input_dict):
|
||||
headers = input_dict
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import gettext
|
|||
import os
|
||||
from functools import partial
|
||||
from contextlib import suppress
|
||||
from typing import Dict
|
||||
from typing import Dict, Optional
|
||||
|
||||
from requests.structures import CaseInsensitiveDict
|
||||
from ytmusicapi.auth.headers import load_headers_file, prepare_headers
|
||||
|
|
@ -28,16 +28,17 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
|
|||
"""
|
||||
|
||||
def __init__(self,
|
||||
auth: str = None,
|
||||
auth: Optional[str | dict] = None,
|
||||
user: str = None,
|
||||
requests_session=True,
|
||||
proxies: dict = None,
|
||||
language: str = 'en',
|
||||
location: str = ''):
|
||||
location: str = '',
|
||||
alt_oauth: Optional[dict] = None):
|
||||
"""
|
||||
Create a new instance to interact with YouTube Music.
|
||||
|
||||
:param auth: Optional. Provide a string or path to file.
|
||||
:param auth: Optional. Provide a string, path to file, or oauth token dict.
|
||||
Authentication credentials are needed to manage your library.
|
||||
See :py:func:`setup` for how to fill in the correct credentials.
|
||||
Default: A default header is used without authentication.
|
||||
|
|
@ -68,10 +69,14 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
|
|||
:param location: Optional. Can be used to change the location of the user.
|
||||
No location will be set by default. This means it is determined by the server.
|
||||
Available languages can be checked in the FAQ.
|
||||
:param alt_oauth: Optional. Used to specify a different oauth client id and secret to be
|
||||
used for authentication flow. Should contain both oauth_client_id
|
||||
and oauth_client_secret keys when provided.
|
||||
"""
|
||||
self.auth = auth
|
||||
self.input_dict = None
|
||||
self.is_oauth_auth = False
|
||||
self.alt_oauth = None
|
||||
|
||||
if isinstance(requests_session, requests.Session):
|
||||
self._session = requests_session
|
||||
|
|
@ -87,12 +92,23 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
|
|||
# value from https://github.com/yt-dlp/yt-dlp/blob/master/yt_dlp/extractor/youtube.py#L502
|
||||
self.cookies = {'SOCS': 'CAI'}
|
||||
if self.auth is not None:
|
||||
input_json = load_headers_file(self.auth)
|
||||
self.input_dict = CaseInsensitiveDict(input_json)
|
||||
self.input_dict['filepath'] = self.auth
|
||||
if isinstance(self.auth, str):
|
||||
input_json = load_headers_file(self.auth)
|
||||
self.input_dict = CaseInsensitiveDict(input_json)
|
||||
self.input_dict['filepath'] = self.auth
|
||||
|
||||
elif isinstance(self.auth, dict):
|
||||
self.input_dict = self.auth
|
||||
|
||||
self.is_oauth_auth = is_oauth(self.input_dict)
|
||||
|
||||
self.headers = prepare_headers(self._session, proxies, self.input_dict)
|
||||
# use custom oauth client parameters if provided
|
||||
if alt_oauth and isinstance(alt_oauth, dict):
|
||||
self.alt_oauth = YTMusicOAuth(self._session, proxies, **alt_oauth)
|
||||
# custom oauth passed in place of session, kwarg used as proxies are skipped
|
||||
self.headers = prepare_headers(self.alt_oauth, input_dict=self.input_dict)
|
||||
else:
|
||||
self.headers = prepare_headers(self._session, proxies, self.input_dict)
|
||||
|
||||
if 'x-goog-visitor-id' not in self.headers:
|
||||
self.headers.update(get_visitor_id(self._send_get_request))
|
||||
|
|
@ -132,6 +148,10 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
|
|||
except KeyError:
|
||||
raise Exception("Your cookie is missing the required value __Secure-3PAPISID")
|
||||
|
||||
@property
|
||||
def is_alt_oauth(self):
|
||||
return self.alt_oauth is not None and self.is_oauth_auth
|
||||
|
||||
def _send_request(self, endpoint: str, body: Dict, additionalParams: str = "") -> Dict:
|
||||
|
||||
if self.is_oauth_auth:
|
||||
|
|
|
|||
Loading…
Reference in a new issue