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 time
import json import json
from .models import BaseTokenDict, DefaultScope, Bearer, FullTokenDict from .models import BaseTokenDict, DefaultScope, Bearer, RefreshableTokenDict
class Credentials: class Credentials:
@ -13,7 +13,7 @@ class Credentials:
def get_code(self) -> Dict: def get_code(self) -> Dict:
raise NotImplementedError() raise NotImplementedError()
def token_from_code(self, device_code: str) -> FullTokenDict: def token_from_code(self, device_code: str) -> RefreshableTokenDict:
raise NotImplementedError() raise NotImplementedError()
def refresh_token(self, refresh_token: str) -> BaseTokenDict: def refresh_token(self, refresh_token: str) -> BaseTokenDict:
@ -21,16 +21,22 @@ class Credentials:
class Token: class Token:
""" Base class representation of the YouTubeMusicAPI OAuth token """ """ Base class representation of the YouTubeMusicAPI OAuth token. """
access_token: str access_token: str
refresh_token: str refresh_token: str
expires_in: str expires_in: int
expires_at: str expires_at: int
is_expiring: bool
scope: Union[str, DefaultScope] scope: DefaultScope
token_type: Union[str, Bearer] 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 { return {
'access_token': self.access_token, 'access_token': self.access_token,
'refresh_token': self.refresh_token, 'refresh_token': self.refresh_token,
@ -40,14 +46,17 @@ class Token:
'token_type': self.token_type '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()) 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}' return f'{self.token_type} {self.access_token}'
class OAuthToken(Token): class OAuthToken(Token):
""" Wrapper for an OAuth token implementing expiration methods. """
def __init__(self, def __init__(self,
access_token: str, access_token: str,
@ -56,40 +65,59 @@ class OAuthToken(Token):
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,
**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._access_token = access_token
self._refresh_token = refresh_token self._refresh_token = refresh_token
self._scope = scope 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._expires_at: int = expires_at if expires_at else int(time.time() + expires_in)
self._token_type = token_type self._token_type = token_type
def update(self, fresh_access: BaseTokenDict): 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._access_token = fresh_access['access_token']
self._expires_at = int(time.time() + fresh_access['expires_in']) self._expires_at = int(time.time() + fresh_access['expires_in'])
@property @property
def access_token(self): def access_token(self) -> str:
return self._access_token return self._access_token
@property @property
def refresh_token(self): def refresh_token(self) -> str:
return self._refresh_token return self._refresh_token
@property @property
def token_type(self): def token_type(self) -> Bearer:
return self._token_type return self._token_type
@property @property
def scope(self): def scope(self) -> DefaultScope:
return self._scope return self._scope
@property @property
def expires_at(self): def expires_at(self) -> int:
return self._expires_at return self._expires_at
@property @property
def expires_in(self): def expires_in(self) -> int:
return self.expires_at - time.time() return int(self.expires_at - time.time())
@property @property
def is_expiring(self) -> bool: def is_expiring(self) -> bool:

View file

@ -2,9 +2,8 @@ import webbrowser
from typing import Dict, Optional from typing import Dict, Optional
import requests 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 .base import OAuthToken, Credentials
from .refreshing import RefreshingToken from .refreshing import RefreshingToken
from .exceptions import BadOAuthClient, UnauthorizedOAuthClient 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 OAuthCredentials(Credentials):
"""
Class for handling OAuth credential retrieval and refreshing.
"""
def __init__(self, def __init__(self,
client_id: Optional[str] = OAUTH_CLIENT_ID, client_id: Optional[str] = None,
client_secret: Optional[str] = OAUTH_CLIENT_SECRET, client_secret: Optional[str] = None,
session: Optional[requests.Session] = None, session: Optional[requests.Session] = None,
proxies: Optional[Dict] = None): proxies: Optional[Dict] = None):
self.client_id = client_id """
self.client_secret = client_secret :param client_id: Optional. Set the GoogleAPI client_id used for auth flows.
self._session = session if session else requests.Session() 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: if proxies:
self._session.proxies.update(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}) code_response = self._send_request(OAUTH_CODE_URL, data={"scope": OAUTH_SCOPE})
return code_response.json() return code_response.json()
def _send_request(self, url, data): 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}) data.update({"client_id": self.client_id})
response = self._session.post(url, data, headers={"User-Agent": OAUTH_USER_AGENT}) response = self._session.post(url, data, headers={"User-Agent": OAUTH_USER_AGENT})
if response.status_code == 401: if response.status_code == 401:
@ -50,7 +70,8 @@ class OAuthCredentials(Credentials):
) )
return response 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( response = self._send_request(
OAUTH_TOKEN_URL, OAUTH_TOKEN_URL,
data={ data={
@ -64,19 +85,32 @@ class OAuthCredentials(Credentials):
def prompt_for_token(self, def prompt_for_token(self,
open_browser: bool = False, open_browser: bool = False,
to_file: Optional[str] = None) -> RefreshingToken: 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() code = self.get_code()
url = f"{code['verification_url']}?user_code={code['user_code']}" url = f"{code['verification_url']}?user_code={code['user_code']}"
if open_browser: if open_browser:
webbrowser.open(url) webbrowser.open(url)
input(f"Go to {url}, finish the login flow and press Enter when done, Ctrl-C to abort") 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"]) raw_token = self.token_from_code(code["device_code"])
base_token = OAuthToken(**raw_token) ref_token = RefreshingToken(OAuthToken(**raw_token), credentials=self)
ref_token = RefreshingToken(base_token, credentials=self)
if to_file: if to_file:
ref_token.local_cache = to_file ref_token.local_cache = to_file
return ref_token return ref_token
def refresh_token(self, refresh_token: str) -> BaseTokenDict: 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( response = self._send_request(
OAUTH_TOKEN_URL, OAUTH_TOKEN_URL,
data={ data={

View file

@ -2,28 +2,32 @@
from typing import Union, Literal, TypedDict from typing import Union, Literal, TypedDict
DefaultScope = Literal['https://www.googleapis.com/auth/youtube'] # for static typechecking
Bearer = Literal['Bearer'] DefaultScope = Union[str, Literal['https://www.googleapis.com/auth/youtube']]
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
expires_in: int access_token: str # str to be used in Authorization header
scope: Union[str, DefaultScope] expires_in: int # seconds until expiration from request timestamp
token_type: Union[str, Bearer] 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. """ """ 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. """ """ Keys for the json object obtained via code response during auth flow. """
device_code: str
user_code: str device_code: str # code obtained via user confirmation and oauth consent
expires_in: int user_code: str # alphanumeric code user is prompted to enter as confirmation. formatted as XXX-XXX-XXX.
interval: int expires_in: int # seconds from original request timestamp
verification_url: str 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 from typing import Optional
import time
import os import os
import json import json
from .base import OAuthToken, Token, Credentials from .base import OAuthToken, Token, Credentials
from .models import RefreshableTokenDict, Bearer, DefaultScope
class RefreshingToken(Token): 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 @classmethod
def from_file(cls, file_path: str, credentials: Credentials, sync=True): 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): if os.path.isfile(file_path):
with open(file_path) as json_file: with open(file_path) as json_file:
file_pack = json.load(json_file) file_pack = json.load(json_file)
@ -20,22 +36,32 @@ class RefreshingToken(Token):
token: OAuthToken, token: OAuthToken,
credentials: Credentials, credentials: Credentials,
local_cache: Optional[str] = None): 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 self._local_cache = local_cache
@property @property
def local_cache(self): def local_cache(self) -> str | None:
return self._local_cache return self._local_cache
# as a property so swapping it will automatically dump the token to the new location
@local_cache.setter @local_cache.setter
def local_cache(self, path: str): def local_cache(self, path: str):
""" Update attribute and dump token to new path. """
self._local_cache = path self._local_cache = path
self.store_token() self.store_token()
@property @property
def access_token(self): def access_token(self) -> str:
if self.token.is_expiring: if self.token.is_expiring:
fresh = self.credentials.refresh_token(self.token.refresh_token) fresh = self.credentials.refresh_token(self.token.refresh_token)
self.token.update(fresh) self.token.update(fresh)
@ -43,34 +69,48 @@ class RefreshingToken(Token):
return self.token.access_token return self.token.access_token
def store_token(self): def store_token(self, path: Optional[str] = None) -> None:
if self.local_cache: """
with open(self.local_cache, encoding="utf8", mode='w') as file: 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) json.dump(self.token.as_dict(), file, indent=True)
@property @property
def refresh_token(self): def refresh_token(self) -> str:
# pass underlying value
return self.token.refresh_token return self.token.refresh_token
@property @property
def is_expiring(self) -> bool: def is_expiring(self) -> bool:
# Refreshing token never expires
return False return False
@property @property
def expires_at(self): def expires_at(self) -> None:
# Refreshing token never expires
return None return None
@property @property
def expires_in(self): def expires_in(self) -> None:
# Refreshing token never expires
return None return None
@property @property
def scope(self): def scope(self) -> DefaultScope:
# pass underlying value
return self.token.scope return self.token.scope
@property @property
def token_type(self): def token_type(self) -> Bearer:
# pass underlying value
return self.token.token_type 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() return self.token.as_dict()

View file

@ -31,10 +31,10 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
""" """
def __init__(self, def __init__(self,
auth: Optional[str | dict] = None, auth: Optional[str | Dict] = None,
user: str = None, user: str = None,
requests_session=True, requests_session=True,
proxies: dict = None, proxies: Dict = None,
language: str = 'en', language: str = 'en',
location: str = '', location: str = '',
oauth_credentials: Optional[OAuthCredentials] = None): 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 :param oauth_credentials: Optional. Used to specify a different oauth client to be
used for authentication flow. used for authentication flow.
""" """
self._base_headers = None
self._headers = None self._base_headers = None # for authless initializing requests during OAuth flow
self.auth = auth self._headers = None # cache formed headers including auth
self._input_dict = {}
self.is_alt_oauth = False self.auth = auth # raw auth
self.is_oauth_auth = False self._input_dict = {} # parsed auth arg value in dictionary format
self.is_browser_auth = False
self.is_custom_oauth = False # (?) may be better implemented as an auth_type attribute with a literal/enum value (?)
self._token = None self.is_alt_oauth = False # YTM instance is using a non-default OAuth client (id & secret)
self.proxies = proxies 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): if isinstance(requests_session, requests.Session):
self._session = requests_session self._session = requests_session