minor touch-up: rebuild the entire oauth system

This commit is contained in:
jcbirdwell 2023-12-18 23:37:17 -06:00
commit 9cb8c63d99
5 changed files with 281 additions and 166 deletions

View file

@ -28,7 +28,10 @@ sample_playlist = "PL6bPxvf5dW5clc3y9wAoslzqUrmkZ5c-u" # very large playlist
headers_oauth = get_resource(config["auth"]["headers_oauth"])
headers_browser = get_resource(config["auth"]["headers_file"])
alt_oauth_creds = OAuthCredentials(**{'client_id': OAUTH_CLIENT_ID, 'client_secret': OAUTH_CLIENT_SECRET})
alt_oauth_creds = OAuthCredentials(**{
'client_id': OAUTH_CLIENT_ID,
'client_secret': OAUTH_CLIENT_SECRET
})
class TestYTMusic(unittest.TestCase):
@ -77,7 +80,8 @@ class TestYTMusic(unittest.TestCase):
# ensure client works/ignores alt if browser credentials passed as auth
self.assertFalse(self.yt_alt_oauth.is_alt_oauth)
# oauth token dict entry and alt
self.yt_alt_oauth = YTMusic(json.loads(config['auth']['oauth_token']), oauth_credentials=alt_oauth_creds)
self.yt_alt_oauth = YTMusic(json.loads(config['auth']['oauth_token']),
oauth_credentials=alt_oauth_creds)
self.assertTrue(self.yt_alt_oauth.is_alt_oauth)
###############
@ -501,7 +505,6 @@ class TestYTMusic(unittest.TestCase):
self.assertEqual(response, "STATUS_SUCCEEDED", "Playlist edit failed")
# end to end test adding playlist, adding item, deleting item, deleting playlist
@unittest.skip('You are creating too many playlists')
def test_end2end(self):
playlist_id = self.yt_brand.create_playlist(
"test",

View file

@ -1,13 +1,6 @@
import json
import os
from typing import Dict, Optional
import requests
from requests.structures import CaseInsensitiveDict
from ytmusicapi.auth.browser import is_browser
from ytmusicapi.auth.oauth import OAuthCredentials, YTMusicOAuth, is_oauth, is_custom_oauth
from ytmusicapi.helpers import initialize_headers
from typing import Dict
def load_headers_file(auth: str) -> Dict:
@ -17,43 +10,4 @@ def load_headers_file(auth: str) -> Dict:
input_json['filepath'] = auth
else:
input_json = json.loads(auth)
return input_json
def prepare_headers(session: requests.Session,
proxies: Optional[Dict] = None,
input_dict: Optional[CaseInsensitiveDict] = None,
oauth_credentials: Optional[OAuthCredentials] = None
) -> Dict:
"""
:param session: Either the session to be used when creating a YTMusicOAuth
instance or the YTMusicOAuth instance itself.
:param proxies: Optional. Proxy configuration parameters passed to session.
Ignored if YTMusicOAuth instance passed to function.
:param input_dict: Optional. Either completed browser auth headers or oauth token.
:param oauth_credentials: Optional. An instance of OAuthCredentials to use for authentication flow.
(Default = None)
"""
if input_dict:
if is_oauth(input_dict):
oauth = YTMusicOAuth(session, proxies, oauth_credentials=oauth_credentials)
headers = oauth.load_headers(dict(input_dict), input_dict.get('filepath'))
elif is_browser(input_dict):
headers = input_dict
elif is_custom_oauth(input_dict):
headers = input_dict
else:
raise Exception(
"Could not detect credential type. "
"Please ensure your oauth or browser credentials are set up correctly.")
else: # no authentication
headers = initialize_headers()
return headers

View file

@ -1,17 +1,15 @@
import json
import time
import webbrowser
from typing import Dict, Optional
from dataclasses import dataclass
from typing import Dict, Optional, Any
from os import environ as env
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)
from ytmusicapi.helpers import initialize_headers
def is_oauth(headers: CaseInsensitiveDict) -> bool:
@ -25,101 +23,196 @@ def is_oauth(headers: CaseInsensitiveDict) -> bool:
return all(key in headers for key in oauth_structure)
def is_custom_oauth(headers: CaseInsensitiveDict) -> bool:
"""Checks whether the headers contain a Bearer token, indicating a custom OAuth implementation."""
return "authorization" in headers and headers["authorization"].startswith("Bearer ")
class OAuthToken:
@classmethod
def from_response(cls, response):
return cls(**response.json())
def __init__(self, access_token: str, refresh_token: str, scope: str, expires_at: int,
token_type: str, **etc: Optional[Any]):
self._access_token = access_token
self._refresh_token = refresh_token
self._scope = scope
self._expires_at: int = expires_at
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}'
@dataclass
class OAuthCredentials:
client_id: Optional[str] = env.get('YTMA_OAUTH_ID', OAUTH_CLIENT_ID)
client_secret: Optional[str] = env.get('YTMA_OAUTH_SECRET', OAUTH_CLIENT_SECRET)
@classmethod
def from_env(cls,
session: Optional[requests.Session] = None,
proxies: Optional[Dict] = None,
*,
client_id_key='YTMA_OAUTH_CLIENT_ID',
client_secret_key='YTMA_OAUTH_CLIENT_SECRET'):
missing_keys = [x for x in [client_id_key, client_secret_key] if x not in env]
if missing_keys:
raise KeyError('Failed to build credentials from environment. Missing required keys: ',
missing_keys)
class YTMusicOAuth:
"""OAuth implementation for YouTube Music based on YouTube TV"""
return cls(client_id=env[client_id_key],
client_secret=env[client_secret_key],
session=session,
proxies=proxies)
def __init__(self,
session: requests.Session,
proxies: Dict = None,
*,
oauth_credentials: Optional[OAuthCredentials] = None):
"""
:param session: Session instance used for authorization requests.
:param proxies: Optional. Proxy configuration to be used by the session.
:param oauth_credentials: Optional. Instance of OAuthCredentials containing
a client id and secret used for authentication flow. Providing will override
those found in constants or provided as environmental variables.
"""
self.credentials = oauth_credentials if oauth_credentials else OAuthCredentials()
self._session = session
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 _send_request(self, url, data) -> requests.Response:
data.update({"client_id": self.credentials.client_id})
headers = {"User-Agent": OAUTH_USER_AGENT}
return self._session.post(url, data, headers=headers)
def get_code(self) -> Dict:
code_response = self._send_request(OAUTH_CODE_URL, data={"scope": OAUTH_SCOPE})
response_json = code_response.json()
return response_json
return code_response.json()
@staticmethod
def _parse_token(response) -> Dict:
token = response.json()
token["expires_at"] = int(time.time()) + int(token["expires_in"])
return token
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 get_token_from_code(self, device_code: str) -> Dict:
def token_from_code(self, device_code: str) -> OAuthToken:
response = self._send_request(
OAUTH_TOKEN_URL,
data={
"client_secret": self.credentials.client_secret,
"client_secret": self.client_secret,
"grant_type": "http://oauth.net/grant_type/device/1.0",
"code": device_code,
},
)
return self._parse_token(response)
return OAuthToken.from_response(response)
def refresh_token(self, refresh_token: str) -> Dict:
response = self._send_request(
OAUTH_TOKEN_URL,
data={
"client_secret": self.credentials.client_secret,
"grant_type": "refresh_token",
"refresh_token": refresh_token,
},
)
return self._parse_token(response)
@staticmethod
def dump_token(token: Dict, filepath: Optional[str]):
if not filepath or len(filepath) > 255:
return
with open(filepath, encoding="utf8", mode="w") as file:
json.dump(token, file, indent=True)
def setup(self, filepath: Optional[str] = None, open_browser: bool = False) -> Dict:
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")
token = self.get_token_from_code(code["device_code"])
self.dump_token(token, filepath)
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
return 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)
def load_headers(self, token: Dict, filepath: Optional[str] = None):
headers = initialize_headers()
if time.time() > token["expires_at"] - 3600:
token.update(self.refresh_token(token["refresh_token"]))
self.dump_token(token, filepath)
headers["Authorization"] = f"{token['token_type']} {token['access_token']}"
headers["Content-Type"] = "application/json"
headers["X-Goog-Request-Time"] = str(int(time.time()))
return headers
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

View file

@ -6,7 +6,7 @@ from typing import Dict
import requests
from ytmusicapi.auth.browser import setup_browser
from ytmusicapi.auth.oauth import YTMusicOAuth
from ytmusicapi.auth.oauth import OAuthCredentials
def setup(filepath: str = None, headers_raw: str = None) -> Dict:
@ -25,7 +25,10 @@ def setup(filepath: str = None, headers_raw: str = None) -> Dict:
def setup_oauth(filepath: str = None,
session: requests.Session = None,
proxies: dict = None,
open_browser: bool = False) -> Dict:
open_browser: bool = False,
env_credentials: bool = False,
client_id: str = None,
client_secret: str = None) -> Dict:
"""
Starts oauth flow from the terminal
and returns a string that can be passed to YTMusic()
@ -34,12 +37,33 @@ def setup_oauth(filepath: str = None,
:param proxies: Proxies to use for authentication
:param filepath: Optional filepath to store headers to.
:param open_browser: If True, open the default browser with the setup link
:param env_credentials: Optional. Specifies if client_id and client_secret should be
pulled from the environment. Modifies client_id and client_secret parameters to
instead specify the keys to search environment for. Default keys are
YTMA_OAUTH_CLIENT_ID for client_id and YTMA_OAUTH_CLIENT_SECRET for secret.
:param client_id: Optional. Used to specify the client_id oauth should use for authentication
flow. If used with env_credentials, instead specifies the environmental key of client_id.
If not used with env_credentials, client_secret MUST also be passed or both will be ignored.
:param client_secret: Optional. Same as client_id but for the oauth client secret.
:return: configuration headers string
"""
if not session:
session = requests.Session()
return YTMusicOAuth(session, proxies).setup(filepath, open_browser)
if env_credentials:
oauth_credentials = OAuthCredentials.from_env(session,
proxies,
client_id_key=client_id,
client_secret_key=client_secret)
elif client_id and client_secret:
oauth_credentials = OAuthCredentials(client_id, client_secret, session, proxies)
else:
oauth_credentials = OAuthCredentials(session=session, proxies=proxies)
return oauth_credentials.prompt_for_token(open_browser, filepath)
def parse_args(args):
@ -49,6 +73,7 @@ def parse_args(args):
choices=["oauth", "browser"],
help="choose a setup type.")
parser.add_argument("--file", type=Path, help="optional path to output file.")
return parser.parse_args(args)

View file

@ -4,9 +4,10 @@ import os
from functools import partial
from contextlib import suppress
from typing import Dict, Optional
import time
from requests.structures import CaseInsensitiveDict
from ytmusicapi.auth.headers import load_headers_file, prepare_headers
from ytmusicapi.auth.headers import load_headers_file
from ytmusicapi.parsers.i18n import Parser
from ytmusicapi.helpers import *
from ytmusicapi.mixins.browsing import BrowsingMixin
@ -16,7 +17,7 @@ from ytmusicapi.mixins.explore import ExploreMixin
from ytmusicapi.mixins.library import LibraryMixin
from ytmusicapi.mixins.playlists import PlaylistsMixin
from ytmusicapi.mixins.uploads import UploadsMixin
from ytmusicapi.auth.oauth import OAuthCredentials, YTMusicOAuth, is_oauth
from ytmusicapi.auth.oauth import OAuthCredentials, is_oauth, RefreshingToken, OAuthToken
class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin,
@ -69,16 +70,19 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
:param location: Optional. Can be used to change the location of the user.
No location will be set by default. This means it is determined by the server.
Available languages can be checked in the FAQ.
:param oauth_credentials: Optional. Used to specify a different oauth client id and secret to be
: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 = None
self._input_dict = {}
self.is_alt_oauth = False
self.is_oauth_auth = False
if oauth_credentials is not None:
self.oauth_credentials = oauth_credentials
else:
self.oauth_credentials = OAuthCredentials()
self.is_browser_auth = False
self.is_custom_oauth = False
self._token = None
self.proxies = proxies
if isinstance(requests_session, requests.Session):
self._session = requests_session
@ -89,28 +93,28 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
else: # Use the Requests API module as a "session".
self._session = requests.api
self.proxies = proxies
if oauth_credentials is not None:
self.oauth_credentials = oauth_credentials
else:
self.oauth_credentials = 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
self.cookies = {'SOCS': 'CAI'}
if self.auth is not None:
if isinstance(self.auth, str):
input_json = load_headers_file(self.auth)
self.input_dict = CaseInsensitiveDict(input_json)
self._input_dict = CaseInsensitiveDict(input_json)
else:
self.input_dict = self.auth
self._input_dict = self.auth
self.is_oauth_auth = is_oauth(self.input_dict)
self.is_alt_oauth = self.is_oauth_auth and oauth_credentials is not None
self.headers = prepare_headers(self._session,
proxies,
self.input_dict,
oauth_credentials=self.oauth_credentials)
if 'x-goog-visitor-id' not in self.headers:
self.headers.update(get_visitor_id(self._send_get_request))
if is_oauth(self._input_dict):
self.is_oauth_auth = True
self.is_alt_oauth = oauth_credentials is not None
self._token = RefreshingToken(OAuthToken(**self._input_dict),
self.oauth_credentials,
self._input_dict.get('filepath'))
# prepare context
self.context = initialize_context()
@ -138,31 +142,65 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
if user:
self.context['context']['user']['onBehalfOfUser'] = user
auth_header = self.headers.get("authorization")
self.is_browser_auth = auth_header and "SAPISIDHASH" in auth_header
auth_headers = self._input_dict.get("authorization")
if auth_headers:
if "SAPISIDHASH" in auth_headers:
self.is_browser_auth = True
elif auth_headers.startswith('Bearer'):
self.is_custom_oauth = True
# sapsid, origin, and params all set once during init
self.params = YTM_PARAMS
if self.is_browser_auth:
self.params += YTM_PARAMS_KEY
try:
cookie = self.headers.get('cookie')
cookie = self.base_headers.get('cookie')
self.sapisid = sapisid_from_cookie(cookie)
self.origin = self.base_headers.get('origin', self.base_headers.get('x-origin'))
except KeyError:
raise Exception("Your cookie is missing the required value __Secure-3PAPISID")
def _send_request(self, endpoint: str, body: Dict, additionalParams: str = "") -> Dict:
@property
def base_headers(self):
if not self._base_headers:
if self.is_browser_auth or self.is_custom_oauth:
self._base_headers = self._input_dict
else:
self._base_headers = {
"user-agent": USER_AGENT,
"accept": "*/*",
"accept-encoding": "gzip, deflate",
"content-type": "application/json",
"content-encoding": "gzip",
"origin": YTM_DOMAIN
}
if self.is_oauth_auth:
self.headers = prepare_headers(self._session,
self.proxies,
self.input_dict,
oauth_credentials=self.oauth_credentials)
return self._base_headers
body.update(self.context)
params = YTM_PARAMS
@property
def headers(self):
# set on first use
if not self._headers:
self._headers = self.base_headers
# keys updated each use, custom oauth implementations left untouched
if self.is_browser_auth:
origin = self.headers.get('origin', self.headers.get('x-origin'))
self.headers["authorization"] = get_authorization(self.sapisid + ' ' + origin)
params += YTM_PARAMS_KEY
self._headers["authorization"] = get_authorization(self.sapisid + ' ' + self.origin)
response = self._session.post(YTM_BASE_API + endpoint + params + additionalParams,
elif self.is_oauth_auth:
self._headers['authorization'] = self._token.as_auth()
self._headers['X-Goog-Request-Time'] = str(int(time.time()))
return self._headers
def _send_request(self, endpoint: str, body: Dict, additionalParams: str = "") -> Dict:
body.update(self.context)
# only required for post requests (?)
if 'X-Goog-Visitor-Id' not in self.headers:
self._headers.update(get_visitor_id(self._send_get_request))
response = self._session.post(YTM_BASE_API + endpoint + self.params + additionalParams,
json=body,
headers=self.headers,
proxies=self.proxies,
@ -176,11 +214,13 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
return response_text
def _send_get_request(self, url: str, params: Dict = None):
response = self._session.get(url,
params=params,
headers=self.headers,
proxies=self.proxies,
cookies=self.cookies)
response = self._session.get(
url,
params=params,
# handle first-use x-goog-visitor-id fetching
headers=self.headers if self._headers else self.base_headers,
proxies=self.proxies,
cookies=self.cookies)
return response
def _check_auth(self):