refactor authtypes

This commit is contained in:
sigma67 2023-12-31 11:18:39 +01:00
commit c848e50b3b
No known key found for this signature in database
GPG key ID: 1C314227DF0103D0
5 changed files with 50 additions and 36 deletions

View file

@ -8,6 +8,7 @@ from unittest import mock
from requests import Response from requests import Response
from ytmusicapi.auth.types import AuthType
from ytmusicapi.setup import main, setup # noqa: E402 from ytmusicapi.setup import main, setup # noqa: E402
from ytmusicapi.ytmusic import YTMusic, OAuthCredentials # 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
@ -82,7 +83,7 @@ class TestYTMusic(unittest.TestCase):
# OAUTH # OAUTH
############### ###############
# 000 so test is run first and fresh token is available to others # 000 so test is run first and fresh token is available to others
def test_000_oauth_tokens(self): def test_oauth_tokens(self):
# ensure instance initialized token # ensure instance initialized token
self.assertIsNotNone(self.yt_oauth._token) self.assertIsNotNone(self.yt_oauth._token)
@ -115,14 +116,14 @@ class TestYTMusic(unittest.TestCase):
# ensure token is updating local file # ensure token is updating local file
self.assertNotEqual(first_json, second_json) self.assertNotEqual(first_json, second_json)
def test_alt_oauth(self): def test_oauth_custom_client(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.assertNotEqual(self.yt_alt_oauth.auth_type, AuthType.OAUTH_CUSTOM_CLIENT)
with open(oauth_filepath, 'r') as f: with open(oauth_filepath, 'r') as f:
token_dict = json.load(f) token_dict = json.load(f)
# oauth token dict entry and alt # oauth token dict entry and alt
self.yt_alt_oauth = YTMusic(token_dict, oauth_credentials=alt_oauth_creds) self.yt_alt_oauth = YTMusic(token_dict, oauth_credentials=alt_oauth_creds)
self.assertTrue(self.yt_alt_oauth.is_alt_oauth) self.assertEqual(self.yt_alt_oauth.auth_type, AuthType.OAUTH_CUSTOM_CLIENT)
############### ###############
# BROWSING # BROWSING

View file

@ -1,12 +0,0 @@
import json
import os
from typing import Dict
def load_headers_file(auth: str) -> Dict:
if os.path.isfile(auth):
with open(auth) as json_file:
input_json = json.load(json_file)
else:
input_json = json.loads(auth)
return input_json

25
ytmusicapi/auth/types.py Normal file
View file

@ -0,0 +1,25 @@
"""enum representing types of authentication supported by this library"""
from enum import Enum, auto
from typing import List
class AuthType(int, Enum):
"""enum representing types of authentication supported by this library"""
UNAUTHORIZED = auto()
BROWSER = auto()
#: client auth via OAuth token refreshing
OAUTH_DEFAULT = auto()
#: YTM instance is using a non-default OAuth client (id & secret)
OAUTH_CUSTOM_CLIENT = auto()
#: allows fully formed OAuth headers to ignore browser auth refresh flow
OAUTH_CUSTOM_FULL = auto()
@classmethod
def oauth_types(cls) -> List["AuthType"]:
return [cls.OAUTH_DEFAULT, cls.OAUTH_CUSTOM_CLIENT, cls.OAUTH_CUSTOM_FULL]

View file

@ -10,6 +10,7 @@ from ytmusicapi.continuations import get_continuations
from ytmusicapi.parsers.library import parse_library_albums, parse_library_artists, get_library_contents from ytmusicapi.parsers.library import parse_library_albums, parse_library_artists, get_library_contents
from ytmusicapi.parsers.albums import parse_album_header from ytmusicapi.parsers.albums import parse_album_header
from ytmusicapi.parsers.uploads import parse_uploaded_items from ytmusicapi.parsers.uploads import parse_uploaded_items
from ..auth.types import AuthType
class UploadsMixin: class UploadsMixin:
@ -194,7 +195,7 @@ class UploadsMixin:
:return: Status String or full response :return: Status String or full response
""" """
self._check_auth() self._check_auth()
if not self.is_browser_auth: if not self.auth_type == AuthType.BROWSER:
raise Exception("Please provide authentication before using this function") raise Exception("Please provide authentication before using this function")
if not os.path.isfile(filepath): if not os.path.isfile(filepath):
raise Exception("The provided file does not exist.") raise Exception("The provided file does not exist.")

View file

@ -17,9 +17,9 @@ 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 .auth.headers import load_headers_file
from .auth.oauth import OAuthCredentials, RefreshingToken, OAuthToken from .auth.oauth import OAuthCredentials, RefreshingToken, OAuthToken
from .auth.oauth.base import Token from .auth.oauth.base import Token
from .auth.types import AuthType
class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin, class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin,
@ -82,11 +82,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
self.auth = auth #: raw auth self.auth = auth #: raw auth
self._input_dict = {} #: parsed auth arg value in dictionary format self._input_dict = {} #: parsed auth arg value in dictionary format
# (?) may be better implemented as an auth_type attribute with a literal/enum value (?) self.auth_type: AuthType = AuthType.UNAUTHORIZED
self.is_alt_oauth = False #: YTM instance is using a non-default OAuth client (id & secret)
self.is_oauth_auth = False #: client auth via OAuth token refreshing
self.is_browser_auth = False #: authorization via extracted browser headers, enables uploading capabilities
self.is_custom_oauth = False #: allows fully formed OAuth headers to ignore browser auth refresh flow
self._token: Token #: OAuth credential handler self._token: Token #: OAuth credential handler
self.oauth_credentials: OAuthCredentials #: Client used for OAuth refreshing self.oauth_credentials: OAuthCredentials #: Client used for OAuth refreshing
@ -103,14 +99,19 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
else: # Use the Requests API module as a "session". else: # Use the Requests API module as a "session".
self._session = requests.api self._session = requests.api
self.oauth_credentials = oauth_credentials if oauth_credentials is not None else OAuthCredentials()
# see google cookie docs: https://policies.google.com/technologies/cookies # see google cookie docs: https://policies.google.com/technologies/cookies
# 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:
self.oauth_credentials = oauth_credentials if oauth_credentials is not None else OAuthCredentials()
auth_filepath = None
if isinstance(self.auth, str): if isinstance(self.auth, str):
input_json = load_headers_file(self.auth) if os.path.isfile(auth):
with open(auth) as json_file:
auth_filepath = auth
input_json = json.load(json_file)
else:
input_json = json.loads(auth)
self._input_dict = CaseInsensitiveDict(input_json) self._input_dict = CaseInsensitiveDict(input_json)
else: else:
@ -118,10 +119,8 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
if OAuthToken.is_oauth(self._input_dict): if OAuthToken.is_oauth(self._input_dict):
base_token = OAuthToken(**self._input_dict) base_token = OAuthToken(**self._input_dict)
self._token = RefreshingToken(base_token, self.oauth_credentials, self._token = RefreshingToken(base_token, self.oauth_credentials, auth_filepath)
self._input_dict.get('filepath')) self.auth_type = AuthType.OAUTH_CUSTOM_CLIENT if oauth_credentials else AuthType.OAUTH_DEFAULT
self.is_oauth_auth = True
self.is_alt_oauth = oauth_credentials is not None
# prepare context # prepare context
self.context = initialize_context() self.context = initialize_context()
@ -152,13 +151,13 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
auth_headers = self._input_dict.get("authorization") auth_headers = self._input_dict.get("authorization")
if auth_headers: if auth_headers:
if "SAPISIDHASH" in auth_headers: if "SAPISIDHASH" in auth_headers:
self.is_browser_auth = True self.auth_type = AuthType.BROWSER
elif auth_headers.startswith('Bearer'): elif auth_headers.startswith('Bearer'):
self.is_custom_oauth = True self.auth_type = AuthType.OAUTH_CUSTOM_FULL
# sapsid, origin, and params all set once during init # sapsid, origin, and params all set once during init
self.params = YTM_PARAMS self.params = YTM_PARAMS
if self.is_browser_auth: if self.auth_type == AuthType.BROWSER:
self.params += YTM_PARAMS_KEY self.params += YTM_PARAMS_KEY
try: try:
cookie = self.base_headers.get('cookie') cookie = self.base_headers.get('cookie')
@ -170,7 +169,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
@property @property
def base_headers(self): def base_headers(self):
if not self._base_headers: if not self._base_headers:
if self.is_browser_auth or self.is_custom_oauth: if self.auth_type == AuthType.BROWSER or self.auth_type == AuthType.OAUTH_CUSTOM_FULL:
self._base_headers = self._input_dict self._base_headers = self._input_dict
else: else:
self._base_headers = { self._base_headers = {
@ -191,10 +190,10 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
self._headers = self.base_headers self._headers = self.base_headers
# keys updated each use, custom oauth implementations left untouched # keys updated each use, custom oauth implementations left untouched
if self.is_browser_auth: if self.auth_type == AuthType.BROWSER:
self._headers["authorization"] = get_authorization(self.sapisid + ' ' + self.origin) self._headers["authorization"] = get_authorization(self.sapisid + ' ' + self.origin)
elif self.is_oauth_auth: elif self.auth_type in AuthType.oauth_types():
self._headers['authorization'] = self._token.as_auth() self._headers['authorization'] = self._token.as_auth()
self._headers['X-Goog-Request-Time'] = str(int(time.time())) self._headers['X-Goog-Request-Time'] = str(int(time.time()))