add: integrate alt_oauth into YTMusic && add: token dict support for auth parameter

This commit is contained in:
jcbirdwell 2023-12-16 16:26:24 -06:00
commit 6c94c80086
3 changed files with 62 additions and 21 deletions

View file

@ -10,6 +10,7 @@ from requests import Response
from ytmusicapi.setup import main, setup # noqa: E402 from ytmusicapi.setup import main, setup # noqa: E402
from ytmusicapi.ytmusic import YTMusic # 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: 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_oauth = get_resource(config["auth"]["headers_oauth"])
headers_browser = get_resource(config["auth"]["headers_file"]) 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): class TestYTMusic(unittest.TestCase):
@ -37,6 +40,7 @@ class TestYTMusic(unittest.TestCase):
assert isinstance(yt, YTMusic) assert isinstance(yt, YTMusic)
cls.yt = YTMusic() cls.yt = YTMusic()
cls.yt_oauth = YTMusic(headers_oauth) 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_auth = YTMusic(headers_browser, location="GB")
cls.yt_brand = YTMusic(config["auth"]["headers"], config["auth"]["brand_account"]) cls.yt_brand = YTMusic(config["auth"]["headers"], config["auth"]["brand_account"])
cls.yt_empty = YTMusic(config["auth"]["headers_empty"], cls.yt_empty = YTMusic(config["auth"]["headers_empty"],
@ -67,7 +71,14 @@ class TestYTMusic(unittest.TestCase):
json_mock.side_effect = None json_mock.side_effect = None
with open(headers_oauth, mode="r", encoding="utf8") as headers: with open(headers_oauth, mode="r", encoding="utf8") as headers:
string_headers = headers.read() 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 # BROWSING
@ -148,10 +159,10 @@ class TestYTMusic(unittest.TestCase):
def test_search_library(self): def test_search_library(self):
results = self.yt_oauth.search(config['queries']['library_any'], scope="library") results = self.yt_oauth.search(config['queries']['library_any'], scope="library")
self.assertGreater(len(results), 5) self.assertGreater(len(results), 5)
results = self.yt_auth.search(config['queries']['library_songs'], results = self.yt_alt_oauth.search(config['queries']['library_songs'],
filter="songs", filter="songs",
scope="library", scope="library",
limit=40) limit=40)
self.assertGreater(len(results), 10) self.assertGreater(len(results), 10)
results = self.yt_auth.search(config['queries']['library_albums'], results = self.yt_auth.search(config['queries']['library_albums'],
filter="albums", filter="albums",
@ -243,7 +254,7 @@ class TestYTMusic(unittest.TestCase):
def test_get_song_related_content(self): def test_get_song_related_content(self):
song = self.yt_oauth.get_watch_playlist(sample_video) 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) self.assertGreaterEqual(len(song), 5)
def test_get_lyrics(self): def test_get_lyrics(self):

View file

@ -20,16 +20,26 @@ def load_headers_file(auth: str) -> Dict:
return input_json return input_json
def prepare_headers( def prepare_headers(auth_session: requests.Session | YTMusicOAuth,
session: requests.Session, proxies: Optional[Dict] = None,
proxies: Optional[Dict] = None, input_dict: Optional[CaseInsensitiveDict] = None) -> Dict:
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 input_dict:
if is_oauth(input_dict): if is_oauth(input_dict):
oauth = YTMusicOAuth(session, proxies) if isinstance(auth_session, YTMusicOAuth):
headers = oauth.load_headers(dict(input_dict), input_dict['filepath']) 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): elif is_browser(input_dict):
headers = input_dict headers = input_dict

View file

@ -3,7 +3,7 @@ import gettext
import os import os
from functools import partial from functools import partial
from contextlib import suppress from contextlib import suppress
from typing import Dict from typing import Dict, Optional
from requests.structures import CaseInsensitiveDict from requests.structures import CaseInsensitiveDict
from ytmusicapi.auth.headers import load_headers_file, prepare_headers from ytmusicapi.auth.headers import load_headers_file, prepare_headers
@ -28,16 +28,17 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
""" """
def __init__(self, def __init__(self,
auth: str = None, auth: Optional[str | dict] = None,
user: str = None, user: str = None,
requests_session=True, requests_session=True,
proxies: dict = None, proxies: dict = None,
language: str = 'en', language: str = 'en',
location: str = ''): location: str = '',
alt_oauth: Optional[dict] = None):
""" """
Create a new instance to interact with YouTube Music. 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. Authentication credentials are needed to manage your library.
See :py:func:`setup` for how to fill in the correct credentials. See :py:func:`setup` for how to fill in the correct credentials.
Default: A default header is used without authentication. 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. :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. No location will be set by default. This means it is determined by the server.
Available languages can be checked in the FAQ. 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.auth = auth
self.input_dict = None self.input_dict = None
self.is_oauth_auth = False self.is_oauth_auth = False
self.alt_oauth = None
if isinstance(requests_session, requests.Session): if isinstance(requests_session, requests.Session):
self._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 # value from https://github.com/yt-dlp/yt-dlp/blob/master/yt_dlp/extractor/youtube.py#L502
self.cookies = {'SOCS': 'CAI'} self.cookies = {'SOCS': 'CAI'}
if self.auth is not None: if self.auth is not None:
input_json = load_headers_file(self.auth) if isinstance(self.auth, str):
self.input_dict = CaseInsensitiveDict(input_json) input_json = load_headers_file(self.auth)
self.input_dict['filepath'] = 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.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: if 'x-goog-visitor-id' not in self.headers:
self.headers.update(get_visitor_id(self._send_get_request)) self.headers.update(get_visitor_id(self._send_get_request))
@ -132,6 +148,10 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
except KeyError: except KeyError:
raise Exception("Your cookie is missing the required value __Secure-3PAPISID") 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: def _send_request(self, endpoint: str, body: Dict, additionalParams: str = "") -> Dict:
if self.is_oauth_auth: if self.is_oauth_auth: