diff --git a/tests/auth/test_oauth.py b/tests/auth/test_oauth.py index adaa4e2..aae772f 100644 --- a/tests/auth/test_oauth.py +++ b/tests/auth/test_oauth.py @@ -10,7 +10,6 @@ from requests import Response from ytmusicapi.auth.oauth import OAuthToken from ytmusicapi.auth.types import AuthType -from ytmusicapi.constants import OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET from ytmusicapi.setup import main from ytmusicapi.ytmusic import OAuthCredentials, YTMusic @@ -27,8 +26,8 @@ def fixture_blank_code() -> dict[str, Any]: @pytest.fixture(name="alt_oauth_credentials") -def fixture_alt_oauth_credentials() -> OAuthCredentials: - return OAuthCredentials(OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET) +def fixture_alt_oauth_credentials(config) -> OAuthCredentials: + return OAuthCredentials(config["auth"]["client_id"], config["auth"]["client_secret"]) @pytest.fixture(name="yt_alt_oauth") @@ -47,7 +46,19 @@ class TestOAuth: oauth_filepath = oauth_file.name with ( mock.patch("builtins.input", return_value="y"), - mock.patch("sys.argv", ["ytmusicapi", "oauth", "--file", oauth_filepath]), + mock.patch( + "sys.argv", + [ + "ytmusicapi", + "oauth", + "--file", + oauth_filepath, + "--client-id", + "test_id", + "--client-secret", + "test_secret", + ], + ), mock.patch("webbrowser.open"), ): main() @@ -63,7 +74,6 @@ class TestOAuth: oauth_file.close() Path(oauth_file.name).unlink() - @pytest.mark.skip(reason="this test needs to be fixed with the oauth update") def test_oauth_tokens(self, oauth_filepath: str, yt_oauth: YTMusic): # ensure instance initialized token assert yt_oauth._token is not None diff --git a/tests/conftest.py b/tests/conftest.py index c0f484d..11e3927 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,6 +4,7 @@ from pathlib import Path import pytest from ytmusicapi import YTMusic +from ytmusicapi.auth.oauth import OAuthCredentials def get_resource(file: str) -> str: @@ -56,8 +57,11 @@ def fixture_yt_auth(browser_filepath) -> YTMusic: @pytest.fixture(name="yt_oauth") -def fixture_yt_oauth(oauth_filepath) -> YTMusic: - return YTMusic(oauth_filepath) +def fixture_yt_oauth(oauth_filepath, config) -> YTMusic: + credentials = OAuthCredentials( + client_id=config["auth"]["client_id"], client_secret=config["auth"]["client_secret"] + ) + return YTMusic(oauth_filepath, oauth_credentials=credentials) @pytest.fixture(name="yt_brand") diff --git a/tests/test.example.cfg b/tests/test.example.cfg index 2bb79d1..769f325 100644 --- a/tests/test.example.cfg +++ b/tests/test.example.cfg @@ -8,6 +8,8 @@ headers_empty = headers_account_with_empty_library_as_json_as_string browser_file = ./browser.json oauth_file = ./oauth.json headers_raw = raw_headers_pasted_from_browser +client_id = yt-data-api-client-id-tv +client_secret = yt-data-api-client-secret-tv [queries] uploads_songs = query_gives_gt_20_songs diff --git a/ytmusicapi/__init__.py b/ytmusicapi/__init__.py index 4f3ce51..4ed851d 100644 --- a/ytmusicapi/__init__.py +++ b/ytmusicapi/__init__.py @@ -12,4 +12,4 @@ except PackageNotFoundError: __copyright__ = "Copyright 2023 sigma67" __license__ = "MIT" __title__ = "ytmusicapi" -__all__ = ["YTMusic", "setup_oauth", "setup"] +__all__ = ["YTMusic", "setup", "setup_oauth"] diff --git a/ytmusicapi/auth/oauth/credentials.py b/ytmusicapi/auth/oauth/credentials.py index 17368c4..3ae2112 100644 --- a/ytmusicapi/auth/oauth/credentials.py +++ b/ytmusicapi/auth/oauth/credentials.py @@ -6,8 +6,6 @@ from typing import Optional import requests from ytmusicapi.constants import ( - OAUTH_CLIENT_ID, - OAUTH_CLIENT_SECRET, OAUTH_CODE_URL, OAUTH_SCOPE, OAUTH_TOKEN_URL, @@ -47,8 +45,8 @@ class OAuthCredentials(Credentials): def __init__( self, - client_id: Optional[str] = None, - client_secret: Optional[str] = None, + client_id: str, + client_secret: str, session: Optional[requests.Session] = None, proxies: Optional[dict] = None, ): @@ -66,8 +64,8 @@ class OAuthCredentials(Credentials): ) # 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.client_id = client_id + self.client_secret = client_secret self._session = session if session else requests.Session() # for auth requests if proxies: diff --git a/ytmusicapi/constants.py b/ytmusicapi/constants.py index 3092680..d002b54 100644 --- a/ytmusicapi/constants.py +++ b/ytmusicapi/constants.py @@ -18,8 +18,6 @@ SUPPORTED_LOCATIONS = { "TN", "TR", "TW", "TZ", "UA", "UG", "US", "UY", "VE", "VN", "YE", "ZA", "ZW" } # fmt: on -OAUTH_CLIENT_ID = "861556708454-d6dlm3lh05idd8npek18k6be8ba3oc68.apps.googleusercontent.com" -OAUTH_CLIENT_SECRET = "SboVhoG9s0rNafixCSGGKXAT" OAUTH_SCOPE = "https://www.googleapis.com/auth/youtube" OAUTH_CODE_URL = "https://www.youtube.com/o/oauth2/device/code" OAUTH_TOKEN_URL = "https://oauth2.googleapis.com/token" diff --git a/ytmusicapi/setup.py b/ytmusicapi/setup.py index a76c5df..b9bf6e0 100644 --- a/ytmusicapi/setup.py +++ b/ytmusicapi/setup.py @@ -23,52 +23,67 @@ def setup(filepath: Optional[str] = None, headers_raw: Optional[str] = None) -> def setup_oauth( + client_id: str, + client_secret: str, filepath: Optional[str] = None, session: Optional[requests.Session] = None, proxies: Optional[dict] = None, open_browser: bool = False, - client_id: Optional[str] = None, - client_secret: Optional[str] = None, ) -> RefreshingToken: """ Starts oauth flow from the terminal and returns a string that can be passed to YTMusic() + :param client_id: Optional. Used to specify the client_id oauth should use for authentication + flow. If provided, 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. :param session: Session to use for authentication :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 client_id: Optional. Used to specify the client_id oauth should use for authentication - flow. If provided, 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() - if client_id and client_secret: - oauth_credentials = OAuthCredentials(client_id, client_secret, session, proxies) - - else: - oauth_credentials = OAuthCredentials(session=session, proxies=proxies) + oauth_credentials = OAuthCredentials(client_id, client_secret, session, proxies) return RefreshingToken.prompt_for_token(oauth_credentials, open_browser, filepath) def parse_args(args): parser = argparse.ArgumentParser(description="Setup ytmusicapi.") - parser.add_argument("setup_type", type=str, choices=["oauth", "browser"], help="choose a setup type.") - parser.add_argument("--file", type=Path, help="optional path to output file.") + # parser.add_argument("setup_type", type=str, choices=["oauth", "browser"], help="choose a setup type.") + subparsers = parser.add_subparsers(help="choose a setup type.", dest="setup_type") + oauth_parser = subparsers.add_parser( + "oauth", + help="create an oauth token using your Google Youtube API credentials; type 'ytmusicapi oauth -h' for details.", + ) + oauth_parser.add_argument("--file", type=Path, help="optional path to output file") + oauth_parser.add_argument("--client-id", type=str, help="use your Google Youtube API client ID.") + oauth_parser.add_argument("--client-secret", type=str, help="use your Google Youtube API client secret.") + browser_parser = subparsers.add_parser( + "browser", + help="use cookies from request headers (deprecated); type 'ytmusicapi browser -h' for details.", + ) + browser_parser.add_argument("--file", type=Path, help="optional path to output file.") return parser.parse_args(args) def main(): args = parse_args(sys.argv[1:]) + if args.setup_type == "oauth" and (args.client_id is None or args.client_secret is None): + print( + "You have to supply both your Google Youtube API client ID and client secret to create a valid oauth token." + ) + return filename = args.file.as_posix() if args.file else f"{args.setup_type}.json" print(f"Creating {filename} with your authentication credentials...") if args.setup_type == "oauth": - return setup_oauth(filename, open_browser=True) + return setup_oauth( + client_id=args.client_id, client_secret=args.client_secret, filepath=filename, open_browser=True + ) else: return setup(filename) diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index 2cccae9..9847da6 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -100,7 +100,7 @@ class YTMusicBase: self.auth_type: AuthType = AuthType.UNAUTHORIZED self._token: Token #: OAuth credential handler - self.oauth_credentials: OAuthCredentials #: Client used for OAuth refreshing + self.oauth_credentials: Optional[OAuthCredentials] #: Client used for OAuth refreshing self._session: requests.Session #: request session for connection pooling self.proxies: Optional[dict[str, str]] = proxies #: params for session modification @@ -118,9 +118,7 @@ class YTMusicBase: # 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: - self.oauth_credentials = ( - oauth_credentials if oauth_credentials is not None else OAuthCredentials() - ) + self.oauth_credentials = oauth_credentials auth_path: Optional[Path] = None if isinstance(self.auth, str): auth_str: str = self.auth @@ -134,7 +132,7 @@ class YTMusicBase: else: self._input_dict = CaseInsensitiveDict(self.auth) - if OAuthToken.is_oauth(self._input_dict): + if self.oauth_credentials is not None and OAuthToken.is_oauth(self._input_dict): self._token = RefreshingToken( credentials=self.oauth_credentials, _local_cache=auth_path, **self._input_dict )