fix: dataclass implementation of credentials

This commit is contained in:
jcbirdwell 2023-12-18 17:58:21 -06:00
commit 10241c7ee4
4 changed files with 58 additions and 56 deletions

View file

@ -9,7 +9,7 @@ from unittest import mock
from requests import Response 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, OAuthCredentials # noqa: E402
from ytmusicapi.constants import OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET from ytmusicapi.constants import OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET
@ -28,7 +28,7 @@ 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} alt_oauth_creds = OAuthCredentials(**{'client_id': OAUTH_CLIENT_ID, 'client_secret': OAUTH_CLIENT_SECRET})
class TestYTMusic(unittest.TestCase): class TestYTMusic(unittest.TestCase):
@ -40,7 +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_alt_oauth = YTMusic(headers_browser, oauth_credentials=alt_oauth_creds)
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"],
@ -71,13 +71,13 @@ 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():
def test_alt_oauth(self):
# ensure client works/ignores alt if browser credentials passed as auth # ensure client works/ignores alt if browser credentials passed as auth
self.assertFalse(self.yt_alt_oauth.is_alt_oauth) self.assertFalse(self.yt_alt_oauth.is_alt_oauth)
# oauth token dict entry and alt # oauth token dict entry and alt
self.yt_alt_oauth = YTMusic(json.loads(string_headers), alt_oauth=alt_oauth_args) self.yt_alt_oauth = YTMusic(json.loads(config['auth']['oauth_token']), oauth_credentials=alt_oauth_creds)
self.assertTrue(self.yt_alt_oauth.is_alt_oauth) self.assertTrue(self.yt_alt_oauth.is_alt_oauth)
############### ###############
@ -501,6 +501,7 @@ class TestYTMusic(unittest.TestCase):
self.assertEqual(response, "STATUS_SUCCEEDED", "Playlist edit failed") self.assertEqual(response, "STATUS_SUCCEEDED", "Playlist edit failed")
# end to end test adding playlist, adding item, deleting item, deleting playlist # end to end test adding playlist, adding item, deleting item, deleting playlist
@unittest.skip('You are creating too many playlists')
def test_end2end(self): def test_end2end(self):
playlist_id = self.yt_brand.create_playlist( playlist_id = self.yt_brand.create_playlist(
"test", "test",

View file

@ -6,7 +6,7 @@ import requests
from requests.structures import CaseInsensitiveDict from requests.structures import CaseInsensitiveDict
from ytmusicapi.auth.browser import is_browser from ytmusicapi.auth.browser import is_browser
from ytmusicapi.auth.oauth import YTMusicOAuth, is_oauth, is_custom_oauth from ytmusicapi.auth.oauth import OAuthCredentials, YTMusicOAuth, is_oauth, is_custom_oauth
from ytmusicapi.helpers import initialize_headers from ytmusicapi.helpers import initialize_headers
@ -14,31 +14,32 @@ def load_headers_file(auth: str) -> Dict:
if os.path.isfile(auth): if os.path.isfile(auth):
with open(auth) as json_file: with open(auth) as json_file:
input_json = json.load(json_file) input_json = json.load(json_file)
input_json['filepath'] = auth
else: else:
input_json = json.loads(auth) input_json = json.loads(auth)
return input_json return input_json
def prepare_headers(auth_session: requests.Session | YTMusicOAuth, def prepare_headers(session: requests.Session,
proxies: Optional[Dict] = None, proxies: Optional[Dict] = None,
input_dict: Optional[CaseInsensitiveDict] = None) -> Dict: input_dict: Optional[CaseInsensitiveDict] = None,
oauth_credentials: Optional[OAuthCredentials] = None
) -> Dict:
""" """
:param auth_session: Either the session to be used when creating a YTMusicOAuth :param session: Either the session to be used when creating a YTMusicOAuth
instance or the YTMusicOAuth instance itself. instance or the YTMusicOAuth instance itself.
:param proxies: Optional. Proxy configuration parameters passed to session. :param proxies: Optional. Proxy configuration parameters passed to session.
Ignored if YTMusicOAuth instance passed to function. Ignored if YTMusicOAuth instance passed to function.
:param input_dict: Optional. Either completed browser auth headers or oauth token. :param input_dict: Optional. Either completed browser auth headers or oauth token.
:param oauth_credentials: Optional. An instance of OAuthCredentials to use for authentication flow.
(Default = None)
""" """
if input_dict: if input_dict:
if is_oauth(input_dict): if is_oauth(input_dict):
if isinstance(auth_session, YTMusicOAuth): oauth = YTMusicOAuth(session, proxies, oauth_credentials=oauth_credentials)
oauth = auth_session
else:
oauth = YTMusicOAuth(auth_session, proxies)
headers = oauth.load_headers(dict(input_dict), input_dict.get('filepath')) headers = oauth.load_headers(dict(input_dict), input_dict.get('filepath'))
elif is_browser(input_dict): elif is_browser(input_dict):

View file

@ -2,6 +2,9 @@ import json
import time import time
import webbrowser import webbrowser
from typing import Dict, Optional from typing import Dict, Optional
from dataclasses import dataclass
from os import environ as env
import requests import requests
from requests.structures import CaseInsensitiveDict from requests.structures import CaseInsensitiveDict
@ -27,6 +30,12 @@ def is_custom_oauth(headers: CaseInsensitiveDict) -> bool:
return "authorization" in headers and headers["authorization"].startswith("Bearer ") return "authorization" in headers and headers["authorization"].startswith("Bearer ")
@dataclass
class OAuthCredentials:
client_id: Optional[str] = env.get('YTMA_OAUTH_ID', OAUTH_CLIENT_ID)
client_secret: Optional[str] = env.get('YTMA_OAUTH_SECRET', OAUTH_CLIENT_SECRET)
class YTMusicOAuth: class YTMusicOAuth:
"""OAuth implementation for YouTube Music based on YouTube TV""" """OAuth implementation for YouTube Music based on YouTube TV"""
@ -34,31 +43,23 @@ class YTMusicOAuth:
session: requests.Session, session: requests.Session,
proxies: Dict = None, proxies: Dict = None,
*, *,
oauth_client_id: Optional[str] = None, oauth_credentials: Optional[OAuthCredentials] = None):
oauth_client_secret: Optional[str] = None):
""" """
:param session: Session instance used for authorization requests. :param session: Session instance used for authorization requests.
:param proxies: Optional. Proxy configuration to be used by the session. :param proxies: Optional. Proxy configuration to be used by the session.
:param oauth_client_id: Optional. Keyword Only. Can be supplied to change the oauth client for token :param oauth_credentials: Optional. Instance of OAuthCredentials containing
retrieval and refreshing. Requires oauth_client_secret also be provided. a client id and secret used for authentication flow. Providing will override
:param oauth_client_secret: Optional. Keyword Only. Used in conjunction with oauth_client_id to switch those found in constants or provided as environmental variables.
underlying oauth client.
""" """
if not isinstance(oauth_client_id, type(oauth_client_secret)): self.credentials = oauth_credentials if oauth_credentials else OAuthCredentials()
raise KeyError(
'Alternate oauth credential usage requires an id AND a secret. Pass both or neither.'
)
self.oauth_id = oauth_client_id if oauth_client_id else OAUTH_CLIENT_ID
self.oauth_secret = oauth_client_secret if oauth_client_secret else OAUTH_CLIENT_SECRET
self._session = session self._session = session
if proxies: if proxies:
self._session.proxies.update(proxies) self._session.proxies.update(proxies)
def _send_request(self, url, data) -> requests.Response: def _send_request(self, url, data) -> requests.Response:
data.update({"client_id": self.oauth_id}) data.update({"client_id": self.credentials.client_id})
headers = {"User-Agent": OAUTH_USER_AGENT} headers = {"User-Agent": OAUTH_USER_AGENT}
return self._session.post(url, data, headers=headers) return self._session.post(url, data, headers=headers)
@ -77,7 +78,7 @@ class YTMusicOAuth:
response = self._send_request( response = self._send_request(
OAUTH_TOKEN_URL, OAUTH_TOKEN_URL,
data={ data={
"client_secret": self.oauth_secret, "client_secret": self.credentials.client_secret,
"grant_type": "http://oauth.net/grant_type/device/1.0", "grant_type": "http://oauth.net/grant_type/device/1.0",
"code": device_code, "code": device_code,
}, },
@ -88,7 +89,7 @@ class YTMusicOAuth:
response = self._send_request( response = self._send_request(
OAUTH_TOKEN_URL, OAUTH_TOKEN_URL,
data={ data={
"client_secret": self.oauth_secret, "client_secret": self.credentials.client_secret,
"grant_type": "refresh_token", "grant_type": "refresh_token",
"refresh_token": refresh_token, "refresh_token": refresh_token,
}, },

View file

@ -16,7 +16,7 @@ from ytmusicapi.mixins.explore import ExploreMixin
from ytmusicapi.mixins.library import LibraryMixin from ytmusicapi.mixins.library import LibraryMixin
from ytmusicapi.mixins.playlists import PlaylistsMixin from ytmusicapi.mixins.playlists import PlaylistsMixin
from ytmusicapi.mixins.uploads import UploadsMixin from ytmusicapi.mixins.uploads import UploadsMixin
from ytmusicapi.auth.oauth import YTMusicOAuth, is_oauth from ytmusicapi.auth.oauth import OAuthCredentials, YTMusicOAuth, is_oauth
class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin, class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin,
@ -34,7 +34,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
proxies: dict = None, proxies: dict = None,
language: str = 'en', language: str = 'en',
location: str = '', location: str = '',
alt_oauth: Optional[dict] = None): oauth_credentials: Optional[OAuthCredentials] = None):
""" """
Create a new instance to interact with YouTube Music. Create a new instance to interact with YouTube Music.
@ -69,14 +69,16 @@ 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 :param oauth_credentials: Optional. Used to specify a different oauth client id and secret to be
used for authentication flow. Should contain both oauth_client_id used for authentication flow.
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 oauth_credentials is not None:
self.oauth_credentials = oauth_credentials
else:
self.oauth_credentials = OAuthCredentials()
if isinstance(requests_session, requests.Session): if isinstance(requests_session, requests.Session):
self._session = requests_session self._session = requests_session
@ -95,20 +97,17 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
if isinstance(self.auth, str): if isinstance(self.auth, str):
input_json = load_headers_file(self.auth) input_json = load_headers_file(self.auth)
self.input_dict = CaseInsensitiveDict(input_json) self.input_dict = CaseInsensitiveDict(input_json)
self.input_dict['filepath'] = self.auth
elif isinstance(self.auth, dict): else:
self.input_dict = self.auth self.input_dict = self.auth
self.is_oauth_auth = is_oauth(self.input_dict) self.is_oauth_auth = is_oauth(self.input_dict)
self.is_alt_oauth = self.is_oauth_auth and oauth_credentials is not None
# use custom oauth client parameters if provided self.headers = prepare_headers(self._session,
if alt_oauth and isinstance(alt_oauth, dict): proxies,
self.alt_oauth = YTMusicOAuth(self._session, proxies, **alt_oauth) self.input_dict,
# custom oauth passed in place of session, kwarg used as proxies are skipped oauth_credentials=self.oauth_credentials)
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))
@ -148,14 +147,14 @@ 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:
self.headers = prepare_headers(self._session, self.proxies, self.input_dict) self.headers = prepare_headers(self._session,
self.proxies,
self.input_dict,
oauth_credentials=self.oauth_credentials)
body.update(self.context) body.update(self.context)
params = YTM_PARAMS params = YTM_PARAMS
if self.is_browser_auth: if self.is_browser_auth: