fix review findings

This commit is contained in:
sigma67 2023-12-31 10:43:26 +01:00
commit 3abbbf8209
No known key found for this signature in database
GPG key ID: 1C314227DF0103D0
5 changed files with 45 additions and 69 deletions

View file

@ -7,7 +7,6 @@ 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

View file

@ -1,7 +1,9 @@
from typing import Optional, Any, Dict from typing import Optional, Dict
import time import time
import json import json
from requests.structures import CaseInsensitiveDict
from .models import BaseTokenDict, DefaultScope, Bearer, RefreshableTokenDict from .models import BaseTokenDict, DefaultScope, Bearer, RefreshableTokenDict
@ -63,8 +65,7 @@ class OAuthToken(Token):
scope: str, scope: str,
token_type: str, token_type: str,
expires_at: Optional[int] = None, expires_at: Optional[int] = None,
expires_in: Optional[int] = None, expires_in: Optional[int] = None):
**_: Optional[Any]):
""" """
:param access_token: active oauth key :param access_token: active oauth key
@ -73,7 +74,6 @@ class OAuthToken(Token):
:param token_type: commonly 'Bearer' :param token_type: commonly 'Bearer'
:param expires_at: Optional. Unix epoch (seconds) of access token expiration. :param expires_at: Optional. Unix epoch (seconds) of access token expiration.
:param expires_in: Optional. Seconds till expiration, assumes/calculates epoch of init. :param expires_in: Optional. Seconds till expiration, assumes/calculates epoch of init.
:param _: void excess kwargs
""" """
# match baseclass attribute/property format # 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._expires_at: int = expires_at if expires_at else int(time.time() + expires_in)
self._token_type = token_type 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): def update(self, fresh_access: BaseTokenDict):
""" """
Update access_token and expiration attributes with a BaseTokenDict inplace. Update access_token and expiration attributes with a BaseTokenDict inplace.

View file

@ -1,8 +1,7 @@
# stand-in classes for clarity until pydantic implementation """models for oauth authentication"""
from typing import Union, Literal, TypedDict from typing import Union, Literal, TypedDict
# for static typechecking
DefaultScope = Union[str, Literal['https://www.googleapis.com/auth/youtube']] DefaultScope = Union[str, Literal['https://www.googleapis.com/auth/youtube']]
Bearer = Union[str, Literal['Bearer']] Bearer = Union[str, Literal['Bearer']]
@ -10,24 +9,24 @@ Bearer = Union[str, Literal['Bearer']]
class BaseTokenDict(TypedDict): class BaseTokenDict(TypedDict):
""" Limited token. Does not provide a refresh token. Commonly obtained via a token refresh. """ """ Limited token. Does not provide a refresh token. Commonly obtained via a token refresh. """
access_token: str # str to be used in Authorization header access_token: str #: str to be used in Authorization header
expires_in: int # seconds until expiration from request timestamp expires_in: int #: seconds until expiration from request timestamp
scope: DefaultScope # should be 'https://www.googleapis.com/auth/youtube' scope: DefaultScope #: should be 'https://www.googleapis.com/auth/youtube'
token_type: Bearer # should be 'Bearer' token_type: Bearer #: should be 'Bearer'
class RefreshableTokenDict(BaseTokenDict): class RefreshableTokenDict(BaseTokenDict):
""" Entire token. Including refresh. Obtained through token setup. """ """ Entire token. Including refresh. Obtained through token setup. """
expires_at: int # UNIX epoch timestamp in seconds expires_at: int #: UNIX epoch timestamp in seconds
refresh_token: str # str used to obtain new access token upon expiration refresh_token: str #: str used to obtain new access token upon expiration
class AuthCodeDict(TypedDict): class AuthCodeDict(TypedDict):
""" Keys for the json object obtained via code response during auth flow. """ """ Keys for the json object obtained via code response during auth flow. """
device_code: str # code obtained via user confirmation and oauth consent 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. 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 expires_in: int #: seconds from original request timestamp
interval: int # (?) "5" (?) interval: int #: (?) "5" (?)
verification_url: str # base url for OAuth consent screen for user signin/confirmation verification_url: str #: base url for OAuth consent screen for user signin/confirmation

View file

@ -43,11 +43,11 @@ class RefreshingToken(Token):
When provided, file contents is updated upon token refresh. When provided, file contents is updated upon token refresh.
""" """
self.token: OAuthToken = token # internal token being used / refreshed / maintained self.token: OAuthToken = token #: internal token being used / refreshed / maintained
self.credentials = credentials # credentials used for access_token refreshing self.credentials = credentials #: credentials used for access_token refreshing
# protected/property attribute enables auto writing token #: protected/property attribute enables auto writing token
# values to new file location via setter # values to new file location via setter
self._local_cache = local_cache self._local_cache = local_cache
@property @property
@ -81,31 +81,6 @@ class RefreshingToken(Token):
with open(file_path, encoding="utf8", mode='w') as file: with open(file_path, encoding="utf8", mode='w') as file:
json.dump(self.token.as_dict(), file, indent=True) 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 @property
def token_type(self) -> Bearer: def token_type(self) -> Bearer:
# pass underlying value # pass underlying value

View file

@ -76,23 +76,23 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
used for authentication flow. used for authentication flow.
""" """
self._base_headers = None # for authless initializing requests during OAuth flow self._base_headers = None #: for authless initializing requests during OAuth flow
self._headers = None # cache formed headers including auth self._headers = None #: cache formed headers including auth
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 (?) # (?) 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_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_oauth_auth = False #: client auth via OAuth token refreshing
self.is_browser_auth = False # authorization via extracted browser headers, enables uploading capabilities 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_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
self._session: requests.Session # request session for connection pooling self._session: requests.Session #: request session for connection pooling
self.proxies: Dict = proxies # params for session modification self.proxies: Dict = proxies #: params for session modification
if isinstance(requests_session, requests.Session): if isinstance(requests_session, requests.Session):
self._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". else: # Use the Requests API module as a "session".
self._session = requests.api self._session = requests.api
if oauth_credentials is not None: self.oauth_credentials = oauth_credentials if oauth_credentials is not None else OAuthCredentials()
self.oauth_credentials = oauth_credentials
else:
self.oauth_credentials = 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
@ -119,18 +116,13 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
else: else:
self._input_dict = self.auth self._input_dict = self.auth
# check if OAuth by passing values as kwargs to OAuthToken init using if OAuthToken.is_oauth(self._input_dict):
# KeyError from incompatible input_dict as False
try:
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,
self._input_dict.get('filepath')) self._input_dict.get('filepath'))
self.is_oauth_auth = True self.is_oauth_auth = True
self.is_alt_oauth = oauth_credentials is not None self.is_alt_oauth = oauth_credentials is not None
except TypeError:
pass
# prepare context # prepare context
self.context = initialize_context() self.context = initialize_context()