docs: docs, ~~docs~~, and docs with a splash of type hinting

This commit is contained in:
jcbirdwell 2023-12-28 18:16:22 -06:00
commit 940b827fb4
5 changed files with 187 additions and 73 deletions

View file

@ -1,8 +1,8 @@
from typing import Optional, Any, Union, Dict
from typing import Optional, Any, Dict
import time
import json
from .models import BaseTokenDict, DefaultScope, Bearer, FullTokenDict
from .models import BaseTokenDict, DefaultScope, Bearer, RefreshableTokenDict
class Credentials:
@ -13,7 +13,7 @@ class Credentials:
def get_code(self) -> Dict:
raise NotImplementedError()
def token_from_code(self, device_code: str) -> FullTokenDict:
def token_from_code(self, device_code: str) -> RefreshableTokenDict:
raise NotImplementedError()
def refresh_token(self, refresh_token: str) -> BaseTokenDict:
@ -21,16 +21,22 @@ class Credentials:
class Token:
""" Base class representation of the YouTubeMusicAPI OAuth token """
""" Base class representation of the YouTubeMusicAPI OAuth token. """
access_token: str
refresh_token: str
expires_in: str
expires_at: str
expires_in: int
expires_at: int
is_expiring: bool
scope: Union[str, DefaultScope]
token_type: Union[str, Bearer]
scope: DefaultScope
token_type: Bearer
def as_dict(self):
def __repr__(self) -> str:
""" Readable version. """
return f'{self.__class__.__name__}: {self.as_dict()}'
def as_dict(self) -> RefreshableTokenDict:
""" Returns dictionary containing underlying token values. """
return {
'access_token': self.access_token,
'refresh_token': self.refresh_token,
@ -40,14 +46,17 @@ class Token:
'token_type': self.token_type
}
def as_json(self):
def as_json(self) -> str:
# TODO: [PYDANTIC]: add a custom serializer
return json.dumps(self.as_dict())
def as_auth(self):
def as_auth(self) -> str:
""" Returns Authorization header ready str of token_type and access_token. """
return f'{self.token_type} {self.access_token}'
class OAuthToken(Token):
""" Wrapper for an OAuth token implementing expiration methods. """
def __init__(self,
access_token: str,
@ -56,40 +65,59 @@ class OAuthToken(Token):
token_type: str,
expires_at: Optional[int] = None,
expires_in: Optional[int] = None,
**etc: Optional[Any]):
**_: Optional[Any]):
"""
:param access_token: active oauth key
:param refresh_token: access_token's matching oauth refresh string
:param scope: most likely 'https://www.googleapis.com/auth/youtube'
: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
self._access_token = access_token
self._refresh_token = refresh_token
self._scope = scope
# set/calculate token expiration using current epoch
self._expires_at: int = expires_at if expires_at else int(time.time() + expires_in)
self._token_type = token_type
def update(self, fresh_access: BaseTokenDict):
"""
Update access_token and expiration attributes with a BaseTokenDict inplace.
expires_at attribute set using current epoch, avoid expiration desync
by passing only recently requested tokens dicts or updating values to compensate.
"""
self._access_token = fresh_access['access_token']
self._expires_at = int(time.time() + fresh_access['expires_in'])
@property
def access_token(self):
def access_token(self) -> str:
return self._access_token
@property
def refresh_token(self):
def refresh_token(self) -> str:
return self._refresh_token
@property
def token_type(self):
def token_type(self) -> Bearer:
return self._token_type
@property
def scope(self):
def scope(self) -> DefaultScope:
return self._scope
@property
def expires_at(self):
def expires_at(self) -> int:
return self._expires_at
@property
def expires_in(self):
return self.expires_at - time.time()
def expires_in(self) -> int:
return int(self.expires_at - time.time())
@property
def is_expiring(self) -> bool:

View file

@ -2,9 +2,8 @@ import webbrowser
from typing import Dict, Optional
import requests
from requests.structures import CaseInsensitiveDict
from .models import FullTokenDict, BaseTokenDict, CodeDict
from .models import RefreshableTokenDict, BaseTokenDict, AuthCodeDict
from .base import OAuthToken, Credentials
from .refreshing import RefreshingToken
from .exceptions import BadOAuthClient, UnauthorizedOAuthClient
@ -14,23 +13,44 @@ from ytmusicapi.constants import (OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_CO
class OAuthCredentials(Credentials):
"""
Class for handling OAuth credential retrieval and refreshing.
"""
def __init__(self,
client_id: Optional[str] = OAUTH_CLIENT_ID,
client_secret: Optional[str] = OAUTH_CLIENT_SECRET,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
session: Optional[requests.Session] = None,
proxies: Optional[Dict] = None):
self.client_id = client_id
self.client_secret = client_secret
self._session = session if session else requests.Session()
"""
:param client_id: Optional. Set the GoogleAPI client_id used for auth flows.
Requires client_secret also be provided if set.
:param client_secret: Optional. Corresponding secret for provided client_id.
:param session: Optional. Connection pooling with an active session.
:param proxies: Optional. Modify the session with proxy parameters.
"""
# id, secret should be None, None or str, str
if not isinstance(client_id, type(client_secret)):
raise KeyError(
'OAuthCredential init failure. Provide both client_id and client_secret or neither.'
)
# bind instance to OAuth client for auth flows
self.client_id = client_id if client_id else OAUTH_CLIENT_ID
self.client_secret = client_secret if client_secret else OAUTH_CLIENT_SECRET
self._session = session if session else requests.Session() # for auth requests
if proxies:
self._session.proxies.update(proxies)
def get_code(self) -> CodeDict:
def get_code(self) -> AuthCodeDict:
""" Method for obtaining a new user auth code. First step of token creation. """
code_response = self._send_request(OAUTH_CODE_URL, data={"scope": OAUTH_SCOPE})
return code_response.json()
def _send_request(self, url, data):
""" Method for sending post requests with required client_id and User-Agent modifications """
data.update({"client_id": self.client_id})
response = self._session.post(url, data, headers={"User-Agent": OAUTH_USER_AGENT})
if response.status_code == 401:
@ -50,7 +70,8 @@ class OAuthCredentials(Credentials):
)
return response
def token_from_code(self, device_code: str) -> FullTokenDict:
def token_from_code(self, device_code: str) -> RefreshableTokenDict:
""" Method for verifying user auth code and conversion into a FullTokenDict. """
response = self._send_request(
OAUTH_TOKEN_URL,
data={
@ -64,19 +85,32 @@ class OAuthCredentials(Credentials):
def prompt_for_token(self,
open_browser: bool = False,
to_file: Optional[str] = None) -> RefreshingToken:
"""
Method for CLI token creation via user inputs.
:param open_browser: Optional. Open browser to OAuth consent url automatically. (Default = False).
:param to_file: Optional. Path to store/sync json version of resulting token. (Default = None).
"""
code = self.get_code()
url = f"{code['verification_url']}?user_code={code['user_code']}"
if open_browser:
webbrowser.open(url)
input(f"Go to {url}, finish the login flow and press Enter when done, Ctrl-C to abort")
raw_token = self.token_from_code(code["device_code"])
base_token = OAuthToken(**raw_token)
ref_token = RefreshingToken(base_token, credentials=self)
ref_token = RefreshingToken(OAuthToken(**raw_token), credentials=self)
if to_file:
ref_token.local_cache = to_file
return ref_token
def refresh_token(self, refresh_token: str) -> BaseTokenDict:
"""
Method for requesting a new access token for a given refresh_token.
Token must have been created by the same OAuth client.
:param refresh_token: Corresponding refresh_token for a matching access_token.
Obtained via
"""
response = self._send_request(
OAUTH_TOKEN_URL,
data={

View file

@ -2,28 +2,32 @@
from typing import Union, Literal, TypedDict
DefaultScope = Literal['https://www.googleapis.com/auth/youtube']
Bearer = Literal['Bearer']
# for static typechecking
DefaultScope = Union[str, Literal['https://www.googleapis.com/auth/youtube']]
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
expires_in: int
scope: Union[str, DefaultScope]
token_type: Union[str, 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 FullTokenDict(BaseTokenDict):
class RefreshableTokenDict(BaseTokenDict):
""" Entire token. Including refresh. Obtained through token setup. """
expires_at: int
refresh_token: str
expires_at: int # UNIX epoch timestamp in seconds
refresh_token: str # str used to obtain new access token upon expiration
class CodeDict(TypedDict):
class AuthCodeDict(TypedDict):
""" Keys for the json object obtained via code response during auth flow. """
device_code: str
user_code: str
expires_in: int
interval: int
verification_url: str
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

View file

@ -1,15 +1,31 @@
from typing import Optional, Any
import time
from typing import Optional
import os
import json
from .base import OAuthToken, Token, Credentials
from .models import RefreshableTokenDict, Bearer, DefaultScope
class RefreshingToken(Token):
"""
Compositional implementation of Token that automatically refreshes
an underlying OAuthToken when required (credential expiration <= 1 min)
upon access_token attribute access.
"""
@classmethod
def from_file(cls, file_path: str, credentials: Credentials, sync=True):
"""
Initialize a refreshing token and underlying OAuthToken directly from a file.
:param file_path: path to json containing token values
:param credentials: credentials used with token in file.
:param sync: Optional. Whether to pass the filepath into instance enabling file
contents to be updated upon refresh. (Default=True).
:return: RefreshingToken instance
:rtype: RefreshingToken
"""
if os.path.isfile(file_path):
with open(file_path) as json_file:
file_pack = json.load(json_file)
@ -20,22 +36,32 @@ class RefreshingToken(Token):
token: OAuthToken,
credentials: Credentials,
local_cache: Optional[str] = None):
self.token = token
self.credentials = credentials
"""
:param token: Underlying Token being maintained.
:param credentials: OAuth client being used for refreshing.
:param local_cache: Optional. Path to json file where token values are stored.
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
# protected/property attribute enables auto writing token
# values to new file location via setter
self._local_cache = local_cache
@property
def local_cache(self):
def local_cache(self) -> str | None:
return self._local_cache
# as a property so swapping it will automatically dump the token to the new location
@local_cache.setter
def local_cache(self, path: str):
""" Update attribute and dump token to new path. """
self._local_cache = path
self.store_token()
@property
def access_token(self):
def access_token(self) -> str:
if self.token.is_expiring:
fresh = self.credentials.refresh_token(self.token.refresh_token)
self.token.update(fresh)
@ -43,34 +69,48 @@ class RefreshingToken(Token):
return self.token.access_token
def store_token(self):
if self.local_cache:
with open(self.local_cache, encoding="utf8", mode='w') as file:
def store_token(self, path: Optional[str] = None) -> None:
"""
Write token values to json file at specified path, defaulting to self.local_cache.
Operation does not update instance local_cache attribute.
Automatically called when local_cache is set post init.
"""
file_path = path if path else self.local_cache
if file_path:
with open(file_path, encoding="utf8", mode='w') as file:
json.dump(self.token.as_dict(), file, indent=True)
@property
def refresh_token(self):
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):
def expires_at(self) -> None:
# Refreshing token never expires
return None
@property
def expires_in(self):
def expires_in(self) -> None:
# Refreshing token never expires
return None
@property
def scope(self):
def scope(self) -> DefaultScope:
# pass underlying value
return self.token.scope
@property
def token_type(self):
def token_type(self) -> Bearer:
# pass underlying value
return self.token.token_type
def as_dict(self):
def as_dict(self) -> RefreshableTokenDict:
# override base class method with call to underlying token's method
return self.token.as_dict()

View file

@ -31,10 +31,10 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
"""
def __init__(self,
auth: Optional[str | dict] = None,
auth: Optional[str | Dict] = None,
user: str = None,
requests_session=True,
proxies: dict = None,
proxies: Dict = None,
language: str = 'en',
location: str = '',
oauth_credentials: Optional[OAuthCredentials] = None):
@ -75,16 +75,24 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
:param oauth_credentials: Optional. Used to specify a different oauth client to be
used for authentication flow.
"""
self._base_headers = None
self._headers = None
self.auth = auth
self._input_dict = {}
self.is_alt_oauth = False
self.is_oauth_auth = False
self.is_browser_auth = False
self.is_custom_oauth = False
self._token = None
self.proxies = proxies
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
# (?) 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._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
if isinstance(requests_session, requests.Session):
self._session = requests_session