fix review findings
This commit is contained in:
parent
d05c011e42
commit
3abbbf8209
5 changed files with 45 additions and 69 deletions
|
|
@ -7,7 +7,6 @@ def load_headers_file(auth: str) -> Dict:
|
|||
if os.path.isfile(auth):
|
||||
with open(auth) as json_file:
|
||||
input_json = json.load(json_file)
|
||||
input_json['filepath'] = auth
|
||||
else:
|
||||
input_json = json.loads(auth)
|
||||
return input_json
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
from typing import Optional, Any, Dict
|
||||
from typing import Optional, Dict
|
||||
import time
|
||||
import json
|
||||
|
||||
from requests.structures import CaseInsensitiveDict
|
||||
|
||||
from .models import BaseTokenDict, DefaultScope, Bearer, RefreshableTokenDict
|
||||
|
||||
|
||||
|
|
@ -63,8 +65,7 @@ class OAuthToken(Token):
|
|||
scope: str,
|
||||
token_type: str,
|
||||
expires_at: Optional[int] = None,
|
||||
expires_in: Optional[int] = None,
|
||||
**_: Optional[Any]):
|
||||
expires_in: Optional[int] = None):
|
||||
"""
|
||||
|
||||
:param access_token: active oauth key
|
||||
|
|
@ -73,7 +74,6 @@ class OAuthToken(Token):
|
|||
:param token_type: commonly 'Bearer'
|
||||
:param expires_at: Optional. Unix epoch (seconds) of access token expiration.
|
||||
:param expires_in: Optional. Seconds till expiration, assumes/calculates epoch of init.
|
||||
:param _: void excess kwargs
|
||||
|
||||
"""
|
||||
# match baseclass attribute/property format
|
||||
|
|
@ -85,6 +85,17 @@ class OAuthToken(Token):
|
|||
self._expires_at: int = expires_at if expires_at else int(time.time() + expires_in)
|
||||
self._token_type = token_type
|
||||
|
||||
@staticmethod
|
||||
def is_oauth(headers: CaseInsensitiveDict) -> bool:
|
||||
oauth_structure = {
|
||||
"access_token",
|
||||
"expires_at",
|
||||
"expires_in",
|
||||
"token_type",
|
||||
"refresh_token",
|
||||
}
|
||||
return all(key in headers for key in oauth_structure)
|
||||
|
||||
def update(self, fresh_access: BaseTokenDict):
|
||||
"""
|
||||
Update access_token and expiration attributes with a BaseTokenDict inplace.
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
# stand-in classes for clarity until pydantic implementation
|
||||
"""models for oauth authentication"""
|
||||
|
||||
from typing import Union, Literal, TypedDict
|
||||
|
||||
# for static typechecking
|
||||
DefaultScope = Union[str, Literal['https://www.googleapis.com/auth/youtube']]
|
||||
Bearer = Union[str, Literal['Bearer']]
|
||||
|
||||
|
|
@ -10,24 +9,24 @@ Bearer = Union[str, Literal['Bearer']]
|
|||
class BaseTokenDict(TypedDict):
|
||||
""" Limited token. Does not provide a refresh token. Commonly obtained via a token refresh. """
|
||||
|
||||
access_token: str # str to be used in Authorization header
|
||||
expires_in: int # seconds until expiration from request timestamp
|
||||
scope: DefaultScope # should be 'https://www.googleapis.com/auth/youtube'
|
||||
token_type: Bearer # should be 'Bearer'
|
||||
access_token: str #: str to be used in Authorization header
|
||||
expires_in: int #: seconds until expiration from request timestamp
|
||||
scope: DefaultScope #: should be 'https://www.googleapis.com/auth/youtube'
|
||||
token_type: Bearer #: should be 'Bearer'
|
||||
|
||||
|
||||
class RefreshableTokenDict(BaseTokenDict):
|
||||
""" Entire token. Including refresh. Obtained through token setup. """
|
||||
|
||||
expires_at: int # UNIX epoch timestamp in seconds
|
||||
refresh_token: str # str used to obtain new access token upon expiration
|
||||
expires_at: int #: UNIX epoch timestamp in seconds
|
||||
refresh_token: str #: str used to obtain new access token upon expiration
|
||||
|
||||
|
||||
class AuthCodeDict(TypedDict):
|
||||
""" Keys for the json object obtained via code response during auth flow. """
|
||||
|
||||
device_code: str # code obtained via user confirmation and oauth consent
|
||||
user_code: str # alphanumeric code user is prompted to enter as confirmation. formatted as XXX-XXX-XXX.
|
||||
expires_in: int # seconds from original request timestamp
|
||||
interval: int # (?) "5" (?)
|
||||
verification_url: str # base url for OAuth consent screen for user signin/confirmation
|
||||
device_code: str #: code obtained via user confirmation and oauth consent
|
||||
user_code: str #: alphanumeric code user is prompted to enter as confirmation. formatted as XXX-XXX-XXX.
|
||||
expires_in: int #: seconds from original request timestamp
|
||||
interval: int #: (?) "5" (?)
|
||||
verification_url: str #: base url for OAuth consent screen for user signin/confirmation
|
||||
|
|
|
|||
|
|
@ -43,11 +43,11 @@ class RefreshingToken(Token):
|
|||
When provided, file contents is updated upon token refresh.
|
||||
"""
|
||||
|
||||
self.token: OAuthToken = token # internal token being used / refreshed / maintained
|
||||
self.credentials = credentials # credentials used for access_token refreshing
|
||||
self.token: OAuthToken = token #: internal token being used / refreshed / maintained
|
||||
self.credentials = credentials #: credentials used for access_token refreshing
|
||||
|
||||
# protected/property attribute enables auto writing token
|
||||
# values to new file location via setter
|
||||
#: protected/property attribute enables auto writing token
|
||||
# values to new file location via setter
|
||||
self._local_cache = local_cache
|
||||
|
||||
@property
|
||||
|
|
@ -81,31 +81,6 @@ class RefreshingToken(Token):
|
|||
with open(file_path, encoding="utf8", mode='w') as file:
|
||||
json.dump(self.token.as_dict(), file, indent=True)
|
||||
|
||||
@property
|
||||
def refresh_token(self) -> str:
|
||||
# pass underlying value
|
||||
return self.token.refresh_token
|
||||
|
||||
@property
|
||||
def is_expiring(self) -> bool:
|
||||
# Refreshing token never expires
|
||||
return False
|
||||
|
||||
@property
|
||||
def expires_at(self) -> None:
|
||||
# Refreshing token never expires
|
||||
return None
|
||||
|
||||
@property
|
||||
def expires_in(self) -> None:
|
||||
# Refreshing token never expires
|
||||
return None
|
||||
|
||||
@property
|
||||
def scope(self) -> DefaultScope:
|
||||
# pass underlying value
|
||||
return self.token.scope
|
||||
|
||||
@property
|
||||
def token_type(self) -> Bearer:
|
||||
# pass underlying value
|
||||
|
|
|
|||
|
|
@ -76,23 +76,23 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
|
|||
used for authentication flow.
|
||||
"""
|
||||
|
||||
self._base_headers = None # for authless initializing requests during OAuth flow
|
||||
self._headers = None # cache formed headers including auth
|
||||
self._base_headers = None #: for authless initializing requests during OAuth flow
|
||||
self._headers = None #: cache formed headers including auth
|
||||
|
||||
self.auth = auth # raw auth
|
||||
self._input_dict = {} # parsed auth arg value in dictionary format
|
||||
self.auth = auth #: raw auth
|
||||
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.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.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.oauth_credentials: OAuthCredentials # Client used for OAuth refreshing
|
||||
self._token: Token #: OAuth credential handler
|
||||
self.oauth_credentials: OAuthCredentials #: Client used for OAuth refreshing
|
||||
|
||||
self._session: requests.Session # request session for connection pooling
|
||||
self.proxies: Dict = proxies # params for session modification
|
||||
self._session: requests.Session #: request session for connection pooling
|
||||
self.proxies: Dict = proxies #: params for session modification
|
||||
|
||||
if isinstance(requests_session, requests.Session):
|
||||
self._session = requests_session
|
||||
|
|
@ -103,10 +103,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
|
|||
else: # Use the Requests API module as a "session".
|
||||
self._session = requests.api
|
||||
|
||||
if oauth_credentials is not None:
|
||||
self.oauth_credentials = oauth_credentials
|
||||
else:
|
||||
self.oauth_credentials = OAuthCredentials()
|
||||
self.oauth_credentials = oauth_credentials if oauth_credentials is not None else OAuthCredentials()
|
||||
|
||||
# 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
|
||||
|
|
@ -119,18 +116,13 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
|
|||
else:
|
||||
self._input_dict = self.auth
|
||||
|
||||
# check if OAuth by passing values as kwargs to OAuthToken init using
|
||||
# KeyError from incompatible input_dict as False
|
||||
try:
|
||||
if OAuthToken.is_oauth(self._input_dict):
|
||||
base_token = OAuthToken(**self._input_dict)
|
||||
self._token = RefreshingToken(base_token, self.oauth_credentials,
|
||||
self._input_dict.get('filepath'))
|
||||
self.is_oauth_auth = True
|
||||
self.is_alt_oauth = oauth_credentials is not None
|
||||
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
# prepare context
|
||||
self.context = initialize_context()
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue