From 45df3afdfbdde756ea5cc23ada071f8221390179 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Wed, 20 Dec 2023 15:18:29 -0600 Subject: [PATCH] oauth: file separation, classes restructured, fix refresh error, model classes for clarity --- ytmusicapi/auth/oauth.py | 207 --------------------------- ytmusicapi/auth/oauth/__init__.py | 5 + ytmusicapi/auth/oauth/base.py | 96 +++++++++++++ ytmusicapi/auth/oauth/credentials.py | 84 +++++++++++ ytmusicapi/auth/oauth/models.py | 29 ++++ ytmusicapi/auth/oauth/refreshing.py | 76 ++++++++++ 6 files changed, 290 insertions(+), 207 deletions(-) delete mode 100644 ytmusicapi/auth/oauth.py create mode 100644 ytmusicapi/auth/oauth/__init__.py create mode 100644 ytmusicapi/auth/oauth/base.py create mode 100644 ytmusicapi/auth/oauth/credentials.py create mode 100644 ytmusicapi/auth/oauth/models.py create mode 100644 ytmusicapi/auth/oauth/refreshing.py diff --git a/ytmusicapi/auth/oauth.py b/ytmusicapi/auth/oauth.py deleted file mode 100644 index 528a6f7..0000000 --- a/ytmusicapi/auth/oauth.py +++ /dev/null @@ -1,207 +0,0 @@ -import json -import time -import webbrowser -from typing import Dict, Optional, Any -import os - -import requests -from requests.structures import CaseInsensitiveDict - -from ytmusicapi.constants import (OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_CODE_URL, - OAUTH_SCOPE, OAUTH_TOKEN_URL, OAUTH_USER_AGENT) - - -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) - - -class OAuthToken: - - @classmethod - def from_response(cls, response): - data = response.json() - return cls(**data) - - def __init__(self, - access_token: str, - refresh_token: str, - scope: str, - token_type: str, - expires_at: Optional[int] = None, - expires_in: Optional[int] = None, - **etc: Optional[Any]): - self._access_token = access_token - self._refresh_token = refresh_token - self._scope = scope - self._expires_at: int = expires_at if expires_at else int(time.time() + expires_in) - self._token_type = token_type - - @property - def access_token(self): - return self._access_token - - @property - def refresh_token(self): - return self._refresh_token - - @property - def token_type(self): - return self._token_type - - @property - def scope(self): - return self._scope - - @property - def expires_at(self): - return self._expires_at - - @property - def expires_in(self): - return self.expires_at - time.time() - - @property - def is_expiring(self) -> bool: - return self.expires_in < 60 - - def as_dict(self): - return { - 'access_token': self.access_token, - 'refresh_token': self.refresh_token, - 'scope': self.scope, - 'expires_at': self.expires_at, - 'expires_in': self.expires_in, - 'token_type': self.token_type - } - - def as_auth(self): - return f'{self.token_type} {self.access_token}' - - -class OAuthCredentials: - - def __init__(self, - client_id: Optional[str] = OAUTH_CLIENT_ID, - client_secret: Optional[str] = OAUTH_CLIENT_SECRET, - 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() - if proxies: - self._session.proxies.update(proxies) - - def get_code(self) -> Dict: - code_response = self._send_request(OAUTH_CODE_URL, data={"scope": OAUTH_SCOPE}) - return code_response.json() - - def _send_request(self, url, data): - data.update({"client_id": self.client_id}) - return self._session.post(url, data, headers={"User-Agent": OAUTH_USER_AGENT}) - - def token_from_code(self, device_code: str) -> OAuthToken: - response = self._send_request( - OAUTH_TOKEN_URL, - data={ - "client_secret": self.client_secret, - "grant_type": "http://oauth.net/grant_type/device/1.0", - "code": device_code, - }, - ) - return OAuthToken.from_response(response) - - def prompt_for_token(self, open_browser: bool = False, to_file: Optional[str] = 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"]) - ref_token = RefreshingToken(raw_token, credentials=self) - if to_file: - ref_token.local_cache = to_file - return ref_token - - def refresh_token(self, refresh_token: str) -> OAuthToken: - response = self._send_request( - OAUTH_TOKEN_URL, - data={ - "client_secret": self.client_secret, - "grant_type": "refresh_token", - "refresh_token": refresh_token, - }, - ) - return OAuthToken.from_response(response) - - -class RefreshingToken(OAuthToken): - - @classmethod - def from_file(cls, file_path: str, credentials: Optional[OAuthCredentials] = None, sync=True): - if os.path.isfile(file_path): - with open(file_path) as json_file: - file_pack = json.load(json_file) - - creds = credentials if credentials else OAuthCredentials() - - return cls(OAuthToken(**file_pack), creds, file_path if sync else None) - - def __init__(self, - token: OAuthToken, - credentials: OAuthCredentials, - local_cache: Optional[str] = None): - self.token = token - self.credentials = credentials - self._local_cache = local_cache - - @property - def local_cache(self): - 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): - with open(path, encoding="utf8", mode='w') as file: - json.dump(self.token.as_dict(), file, indent=True) - self._local_cache = path - - @property - def access_token(self): - if self.token.is_expiring: - self.token = self.credentials.refresh_token(self.token.refresh_token) - # update stored token file on refresh when provided - if self.local_cache: - with open(self.local_cache, encoding="utf8", mode='w') as file: - json.dump(self.token.as_dict(), file, indent=True) - return self.token.access_token - - @property - def refresh_token(self): - return self.token.refresh_token - - @property - def is_expiring(self) -> bool: - return False - - @property - def expires_at(self): - return None - - @property - def expires_in(self): - return None - - @property - def scope(self): - return self.token.scope - - @property - def token_type(self): - return self.token.token_type diff --git a/ytmusicapi/auth/oauth/__init__.py b/ytmusicapi/auth/oauth/__init__.py new file mode 100644 index 0000000..f8813a2 --- /dev/null +++ b/ytmusicapi/auth/oauth/__init__.py @@ -0,0 +1,5 @@ +from .credentials import OAuthCredentials, is_oauth +from .refreshing import RefreshingToken +from .base import OAuthToken + +__all__ = ['OAuthCredentials', 'is_oauth', 'RefreshingToken', 'OAuthToken'] diff --git a/ytmusicapi/auth/oauth/base.py b/ytmusicapi/auth/oauth/base.py new file mode 100644 index 0000000..1882dcd --- /dev/null +++ b/ytmusicapi/auth/oauth/base.py @@ -0,0 +1,96 @@ +from typing import Optional, Any, Union, Dict +import time +import json + +from .models import BaseTokenDict, DefaultScope, Bearer, FullTokenDict + + +class Credentials: + """ Base class representation of YouTubeMusicAPI OAuth Credentials """ + client_id: str + client_secret: str + + def get_code(self) -> Dict: + raise NotImplementedError() + + def token_from_code(self, device_code: str) -> FullTokenDict: + raise NotImplementedError() + + def refresh_token(self, refresh_token: str) -> BaseTokenDict: + raise NotImplementedError() + + +class Token: + """ Base class representation of the YouTubeMusicAPI OAuth token """ + access_token: str + refresh_token: str + expires_in: str + expires_at: str + + scope: Union[str, DefaultScope] + token_type: Union[str, Bearer] + + def as_dict(self): + return { + 'access_token': self.access_token, + 'refresh_token': self.refresh_token, + 'scope': self.scope, + 'expires_at': self.expires_at, + 'expires_in': self.expires_in, + 'token_type': self.token_type + } + + def as_json(self): + return json.dumps(self.as_dict()) + + def as_auth(self): + return f'{self.token_type} {self.access_token}' + + +class OAuthToken(Token): + + def __init__(self, + access_token: str, + refresh_token: str, + scope: str, + token_type: str, + expires_at: Optional[int] = None, + expires_in: Optional[int] = None, + **etc: Optional[Any]): + self._access_token = access_token + self._refresh_token = refresh_token + self._scope = scope + 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): + self._access_token = fresh_access['access_token'] + self._expires_at = int(time.time() + fresh_access['expires_in']) + + @property + def access_token(self): + return self._access_token + + @property + def refresh_token(self): + return self._refresh_token + + @property + def token_type(self): + return self._token_type + + @property + def scope(self): + return self._scope + + @property + def expires_at(self): + return self._expires_at + + @property + def expires_in(self): + return self.expires_at - time.time() + + @property + def is_expiring(self) -> bool: + return self.expires_in < 60 diff --git a/ytmusicapi/auth/oauth/credentials.py b/ytmusicapi/auth/oauth/credentials.py new file mode 100644 index 0000000..22535b0 --- /dev/null +++ b/ytmusicapi/auth/oauth/credentials.py @@ -0,0 +1,84 @@ +import webbrowser +from typing import Dict, Optional + +import requests +from requests.structures import CaseInsensitiveDict + +from .models import FullTokenDict, BaseTokenDict, CodeDict +from .base import OAuthToken, Credentials +from .refreshing import RefreshingToken + +from ytmusicapi.constants import (OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_CODE_URL, + OAUTH_SCOPE, OAUTH_TOKEN_URL, OAUTH_USER_AGENT) + + +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) + + +class OAuthCredentials(Credentials): + + def __init__(self, + client_id: Optional[str] = OAUTH_CLIENT_ID, + client_secret: Optional[str] = OAUTH_CLIENT_SECRET, + 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() + if proxies: + self._session.proxies.update(proxies) + + def get_code(self) -> CodeDict: + code_response = self._send_request(OAUTH_CODE_URL, data={"scope": OAUTH_SCOPE}) + return code_response.json() + + def _send_request(self, url, data): + data.update({"client_id": self.client_id}) + return self._session.post(url, data, headers={"User-Agent": OAUTH_USER_AGENT}) + + def token_from_code(self, device_code: str) -> FullTokenDict: + """ Returns a FullTokenDict, including refresh_token """ + response = self._send_request( + OAUTH_TOKEN_URL, + data={ + "client_secret": self.client_secret, + "grant_type": "http://oauth.net/grant_type/device/1.0", + "code": device_code, + }, + ) + return response.json() + + def prompt_for_token(self, + open_browser: bool = False, + to_file: Optional[str] = None) -> RefreshingToken: + 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) + if to_file: + ref_token.local_cache = to_file + return ref_token + + def refresh_token(self, refresh_token: str) -> BaseTokenDict: + response = self._send_request( + OAUTH_TOKEN_URL, + data={ + "client_secret": self.client_secret, + "grant_type": "refresh_token", + "refresh_token": refresh_token, + }, + ) + + return response.json() diff --git a/ytmusicapi/auth/oauth/models.py b/ytmusicapi/auth/oauth/models.py new file mode 100644 index 0000000..d624566 --- /dev/null +++ b/ytmusicapi/auth/oauth/models.py @@ -0,0 +1,29 @@ +# stand-in classes for clarity until pydantic implementation + +from typing import Union, Literal, TypedDict + +DefaultScope = Literal['https://www.googleapis.com/auth/youtube'] +Bearer = 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] + + +class FullTokenDict(BaseTokenDict): + """ Entire token. Including refresh. Obtained through token setup. """ + expires_at: int + refresh_token: str + + +class CodeDict(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 diff --git a/ytmusicapi/auth/oauth/refreshing.py b/ytmusicapi/auth/oauth/refreshing.py new file mode 100644 index 0000000..0c02d99 --- /dev/null +++ b/ytmusicapi/auth/oauth/refreshing.py @@ -0,0 +1,76 @@ +from typing import Optional, Any +import time +import os +import json + +from .base import OAuthToken, Token, Credentials + + +class RefreshingToken(Token): + + @classmethod + def from_file(cls, file_path: str, credentials: Credentials, sync=True): + if os.path.isfile(file_path): + with open(file_path) as json_file: + file_pack = json.load(json_file) + + return cls(OAuthToken(**file_pack), credentials, file_path if sync else None) + + def __init__(self, + token: OAuthToken, + credentials: Credentials, + local_cache: Optional[str] = None): + self.token = token + self.credentials = credentials + self._local_cache = local_cache + + @property + def local_cache(self): + 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): + self._local_cache = path + self.store_token() + + @property + def access_token(self): + if self.token.is_expiring: + fresh = self.credentials.refresh_token(self.token.refresh_token) + self.token.update(fresh) + self.store_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: + json.dump(self.token.as_dict(), file, indent=True) + + @property + def refresh_token(self): + return self.token.refresh_token + + @property + def is_expiring(self) -> bool: + return False + + @property + def expires_at(self): + return None + + @property + def expires_in(self): + return None + + @property + def scope(self): + return self.token.scope + + @property + def token_type(self): + return self.token.token_type + + def as_dict(self): + return self.token.as_dict()