diff --git a/tests/README.rst b/tests/README.rst index de78fd1..ff54d83 100644 --- a/tests/README.rst +++ b/tests/README.rst @@ -1,15 +1,29 @@ Package tests ============================================ Tests use the ``unittest`` framework. Each function has a corresponding unittest. -Sometimes there is a single unittest for multiple functions to ensure there are no permanent changes in the user's YouTube account (i.e. subscribe and unsubscribe). +Sometimes there is a single unittest for multiple functions to ensure there are no permanent changes in the user's +YouTube account (i.e. subscribe and unsubscribe). + +Note that there must be a ``browser.json`` and ``oauth.json`` in the `tests` folder to run all authenticated tests. +These two files can be easily obtained as the default outputs of running the following commands respectively: + +.. code-block:: bash + + ytmusicapi browser + ytmusicapi oauth + -Note that there must be a ``headers_auth.json`` in the `tests` folder to run authenticated tests. -For testing the song upload, there also needs to be a file with the name specified in the code in the project root. Copy ``tests/test.cfg.example`` to ``tests/test.cfg`` to run the tests. The entry descriptions should be self-explanatory. For the headers_raw, you need to indent the overflowing lines with a tab character. For the upload test you need a suitable music file in the test directory. Adjust the file to contain appropriate information for your YouTube account and local setup. +Brand accounts can be created by first signing into the google account you wish to have as the parent/controlling +account then navigating `here. `_ +Once the brand account/channel has been created, you can obtain the account ID needed for your test.cfg by +navigating to your `google account page `_ and selecting the brand account via the +profile drop down in the top right, the brand ID should then be present in the URL. + Coverage badge -------------- Make sure you installed the dev requirements as explained in `CONTRIBUTING.rst `_. Run diff --git a/tests/test.cfg.example b/tests/test.cfg.example index 25cf53e..c593ea8 100644 --- a/tests/test.cfg.example +++ b/tests/test.cfg.example @@ -3,14 +3,25 @@ brand_account = 101234229123420379537 brand_account_empty = 1123456629123420379537 headers = headers_auth_json_as_string headers_empty = headers_account_with_empty_library_as_json_as_string -headers_file = ./headers_auth.json -headers_oauth = ./oauth.json -oauth_code = {"device_code":"","user_code":"","expires_in":1800,"interval":5,"verification_url":"https://www.google.com/device"} -oauth_token = {"access_token":"","expires_in":1000,"refresh_token":"","scope":"https://www.googleapis.com/auth/youtube","token_type":"Bearer"} +browser_file = ./browser.json +oauth_file = ./oauth.json headers_raw = raw_headers_pasted_from_browser +[queries] +uploads_songs = query_gives_gt_20_songs +library_any = query_gives_gt_5_results +library_songs = query_gives_gt_10_songs +library_albums = query_gives_gte_5_albums +library_artists = query_gives_gte_1_artist +library_playlists = query_gives_gte_1_playlist + [playlists] own = owned_playlist_id +own_length = number_of_tracks_in_playlist + +[albums] +album_browse_id = sample_id_of_regionally_available_album +album_track_length = available_album_length [uploads] file = song_in_tests_directory.mp3 diff --git a/tests/test.py b/tests/test.py index cb6161b..d43e100 100644 --- a/tests/test.py +++ b/tests/test.py @@ -8,8 +8,10 @@ from unittest import mock from requests import Response +from ytmusicapi.auth.types import AuthType from ytmusicapi.setup import main, setup # noqa: E402 -from ytmusicapi.ytmusic import YTMusic # noqa: E402 +from ytmusicapi.ytmusic import YTMusic, OAuthCredentials # noqa: E402 +from ytmusicapi.constants import OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET def get_resource(file: str) -> str: @@ -23,9 +25,18 @@ config.read(get_resource("test.cfg"), "utf-8") sample_album = "MPREb_4pL8gzRtw1p" # Eminem - Revival sample_video = "hpSrLjc5SMs" # Oasis - Wonderwall sample_playlist = "PL6bPxvf5dW5clc3y9wAoslzqUrmkZ5c-u" # very large playlist +blank_code = { + "device_code": "", + "user_code": "", + "expires_in": 1800, + "interval": 5, + "verification_url": "https://www.google.com/device" +} -headers_oauth = get_resource(config["auth"]["headers_oauth"]) -headers_browser = get_resource(config["auth"]["headers_file"]) +oauth_filepath = get_resource(config["auth"]["oauth_file"]) +browser_filepath = get_resource(config["auth"]["browser_file"]) + +alt_oauth_creds = OAuthCredentials(OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET) class TestYTMusic(unittest.TestCase): @@ -36,15 +47,16 @@ class TestYTMusic(unittest.TestCase): with YTMusic(requests_session=False) as yt: assert isinstance(yt, YTMusic) cls.yt = YTMusic() - cls.yt_oauth = YTMusic(headers_oauth) - cls.yt_auth = YTMusic(headers_browser, location="GB") + cls.yt_oauth = YTMusic(oauth_filepath) + cls.yt_alt_oauth = YTMusic(browser_filepath, oauth_credentials=alt_oauth_creds) + cls.yt_auth = YTMusic(browser_filepath, location="GB") cls.yt_brand = YTMusic(config["auth"]["headers"], config["auth"]["brand_account"]) cls.yt_empty = YTMusic(config["auth"]["headers_empty"], config["auth"]["brand_account_empty"]) - @mock.patch("sys.argv", ["ytmusicapi", "browser", "--file", headers_browser]) + @mock.patch("sys.argv", ["ytmusicapi", "browser", "--file", browser_filepath]) def test_setup_browser(self): - headers = setup(headers_browser, config["auth"]["headers_raw"]) + headers = setup(browser_filepath, config["auth"]["headers_raw"]) self.assertGreaterEqual(len(headers), 2) headers_raw = config["auth"]["headers_raw"].split("\n") with mock.patch("builtins.input", side_effect=(headers_raw + [EOFError()])): @@ -53,21 +65,65 @@ class TestYTMusic(unittest.TestCase): @mock.patch("requests.Response.json") @mock.patch("requests.Session.post") - @mock.patch("sys.argv", ["ytmusicapi", "oauth", "--file", headers_oauth]) + @mock.patch("sys.argv", ["ytmusicapi", "oauth", "--file", oauth_filepath]) def test_setup_oauth(self, session_mock, json_mock): session_mock.return_value = Response() - json_mock.side_effect = [ - json.loads(config["auth"]["oauth_code"]), - json.loads(config["auth"]["oauth_token"]), - ] + fresh_token = self.yt_oauth._token.as_dict() + json_mock.side_effect = [blank_code, fresh_token] with mock.patch("builtins.input", return_value="y"): main() - self.assertTrue(Path(headers_oauth).exists()) + self.assertTrue(Path(oauth_filepath).exists()) json_mock.side_effect = None - with open(headers_oauth, mode="r", encoding="utf8") as headers: - string_headers = headers.read() - self.yt_oauth = YTMusic(string_headers) + with open(oauth_filepath, mode="r", encoding="utf8") as oauth_file: + string_oauth_token = oauth_file.read() + self.yt_oauth = YTMusic(string_oauth_token) + + ############### + # OAUTH + ############### + # 000 so test is run first and fresh token is available to others + def test_oauth_tokens(self): + # ensure instance initialized token + self.assertIsNotNone(self.yt_oauth._token) + + # set reference file + with open(oauth_filepath, 'r') as f: + first_json = json.load(f) + + # pull reference values from underlying token + first_token = self.yt_oauth._token.token.access_token + first_expire = self.yt_oauth._token.token.expires_at + # make token expire + self.yt_oauth._token.token._expires_at = time.time() + # check + self.assertTrue(self.yt_oauth._token.token.is_expiring) + # pull new values, assuming token will be refreshed on access + second_token = self.yt_oauth._token.access_token + second_expire = self.yt_oauth._token.token.expires_at + second_token_inner = self.yt_oauth._token.token.access_token + # check it was refreshed + self.assertNotEqual(first_token, second_token) + # check expiration timestamps to confirm + self.assertNotEqual(second_expire, first_expire) + self.assertGreater(second_expire, time.time() + 60) + # check token is propagating properly + self.assertEqual(second_token, second_token_inner) + + with open(oauth_filepath, 'r') as f2: + second_json = json.load(f2) + + # ensure token is updating local file + self.assertNotEqual(first_json, second_json) + + def test_oauth_custom_client(self): + # ensure client works/ignores alt if browser credentials passed as auth + self.assertNotEqual(self.yt_alt_oauth.auth_type, AuthType.OAUTH_CUSTOM_CLIENT) + with open(oauth_filepath, 'r') as f: + token_dict = json.load(f) + # oauth token dict entry and alt + self.yt_alt_oauth = YTMusic(token_dict, oauth_credentials=alt_oauth_creds) + self.assertEqual(self.yt_alt_oauth.auth_type, AuthType.OAUTH_CUSTOM_CLIENT) ############### # BROWSING @@ -135,24 +191,37 @@ class TestYTMusic(unittest.TestCase): self.assertRaises( Exception, self.yt.search, - "audiomachine", + config['queries']['uploads_songs'], filter="songs", scope="uploads", limit=40, ) - results = self.yt_auth.search("audiomachine", scope="uploads", limit=40) + results = self.yt_auth.search(config['queries']['uploads_songs'], + scope="uploads", + limit=40) self.assertGreater(len(results), 20) def test_search_library(self): - results = self.yt_oauth.search("garrix", scope="library") + results = self.yt_oauth.search(config['queries']['library_any'], scope="library") self.assertGreater(len(results), 5) - results = self.yt_auth.search("bergersen", filter="songs", scope="library", limit=40) + results = self.yt_alt_oauth.search(config['queries']['library_songs'], + filter="songs", + scope="library", + limit=40) self.assertGreater(len(results), 10) - results = self.yt_auth.search("garrix", filter="albums", scope="library", limit=40) + results = self.yt_auth.search(config['queries']['library_albums'], + filter="albums", + scope="library", + limit=40) self.assertGreaterEqual(len(results), 4) - results = self.yt_auth.search("garrix", filter="artists", scope="library", limit=40) + results = self.yt_auth.search(config['queries']['library_artists'], + filter="artists", + scope="library", + limit=40) self.assertGreaterEqual(len(results), 1) - results = self.yt_auth.search("garrix", filter="playlists", scope="library") + results = self.yt_auth.search(config['queries']['library_playlists'], + filter="playlists", + scope="library") self.assertGreaterEqual(len(results), 1) self.assertRaises(Exception, self.yt_auth.search, @@ -207,15 +276,20 @@ class TestYTMusic(unittest.TestCase): self.assertGreater(len(results), 100) def test_get_album_browse_id(self): + warnings.filterwarnings(action="ignore", category=DeprecationWarning) browse_id = self.yt.get_album_browse_id("OLAK5uy_nMr9h2VlS-2PULNz3M3XVXQj_P3C2bqaY") self.assertEqual(browse_id, sample_album) + with self.subTest(): + escaped_browse_id = self.yt.get_album_browse_id( + "OLAK5uy_nbMYyrfeg5ZgknoOsOGBL268hGxtcbnDM") + self.assertEqual(escaped_browse_id, 'MPREb_scJdtUCpPE2') def test_get_album(self): results = self.yt_auth.get_album(sample_album) self.assertGreaterEqual(len(results), 9) self.assertTrue(results["tracks"][0]["isExplicit"]) self.assertIn("feedbackTokens", results["tracks"][0]) - self.assertEqual(len(results["other_versions"]), 2) + self.assertGreaterEqual(len(results["other_versions"]), 1) # appears to be regional results = self.yt.get_album("MPREb_BQZvl3BFGay") self.assertEqual(len(results["tracks"]), 7) self.assertEqual(len(results["tracks"][0]["artists"]), 1) @@ -230,7 +304,7 @@ class TestYTMusic(unittest.TestCase): def test_get_song_related_content(self): song = self.yt_oauth.get_watch_playlist(sample_video) - song = self.yt_oauth.get_song_related(song["related"]) + song = self.yt_alt_oauth.get_song_related(song["related"]) self.assertGreaterEqual(len(song), 5) def test_get_lyrics(self): @@ -244,8 +318,8 @@ class TestYTMusic(unittest.TestCase): self.assertRaises(Exception, self.yt.get_lyrics, playlist["lyrics"]) def test_get_signatureTimestamp(self): - signatureTimestamp = self.yt.get_signatureTimestamp() - self.assertIsNotNone(signatureTimestamp) + signature_timestamp = self.yt.get_signatureTimestamp() + self.assertIsNotNone(signature_timestamp) def test_set_tasteprofile(self): self.assertRaises(Exception, self.yt.set_tasteprofile, "not an artist") @@ -284,7 +358,8 @@ class TestYTMusic(unittest.TestCase): def test_get_charts(self): charts = self.yt_oauth.get_charts() - self.assertEqual(len(charts), 4) + # songs section appears to be removed currently (US) + self.assertGreaterEqual(len(charts), 3) charts = self.yt.get_charts(country="US") self.assertEqual(len(charts), 5) charts = self.yt.get_charts(country="BE") @@ -305,12 +380,12 @@ class TestYTMusic(unittest.TestCase): self.assertGreater(len(playlist["tracks"]), 45) playlist = self.yt_oauth.get_watch_playlist("UoAf_y9Ok4k") # private track self.assertGreaterEqual(len(playlist["tracks"]), 25) - playlist = self.yt.get_watch_playlist( - playlistId="OLAK5uy_kt7zOXlNCGsYFEdNc5Pvnr4JFfMkspmc8", shuffle=True) - self.assertEqual(len(playlist["tracks"]), 12) + playlist = self.yt.get_watch_playlist(playlistId=config['albums']['album_browse_id'], + shuffle=True) + self.assertEqual(len(playlist["tracks"]), config.getint('albums', 'album_track_length')) playlist = self.yt_brand.get_watch_playlist(playlistId=config["playlists"]["own"], shuffle=True) - self.assertEqual(len(playlist["tracks"]), 4) + self.assertEqual(len(playlist["tracks"]), config.getint('playlists', 'own_length')) ################ # LIBRARY @@ -475,17 +550,18 @@ class TestYTMusic(unittest.TestCase): ) self.assertEqual(response, "STATUS_SUCCEEDED", "Playlist edit failed") - # end to end test adding playlist, adding item, deleting item, deleting playlist + # end-to-end test adding playlist, adding item, deleting item, deleting playlist + # @unittest.skip('You are creating too many playlists. Please wait a bit...') def test_end2end(self): - playlistId = self.yt_brand.create_playlist( + playlist_id = self.yt_brand.create_playlist( "test", "test description", source_playlist="OLAK5uy_lGQfnMNGvYCRdDq9ZLzJV2BJL2aHQsz9Y", ) - self.assertEqual(len(playlistId), 34, "Playlist creation failed") - self.yt_brand.edit_playlist(playlistId, addToTop=True) + self.assertEqual(len(playlist_id), 34, "Playlist creation failed") + self.yt_brand.edit_playlist(playlist_id, addToTop=True) response = self.yt_brand.add_playlist_items( - playlistId, + playlist_id, [sample_video, sample_video], source_playlist="OLAK5uy_nvjTE32aFYdFN7HCyMv3cGqD3wqBb4Jow", duplicates=True, @@ -493,12 +569,12 @@ class TestYTMusic(unittest.TestCase): self.assertEqual(response["status"], "STATUS_SUCCEEDED", "Adding playlist item failed") self.assertGreater(len(response["playlistEditResults"]), 0, "Adding playlist item failed") time.sleep(2) - self.yt_brand.edit_playlist(playlistId, addToTop=False) - playlist = self.yt_brand.get_playlist(playlistId, related=True) + self.yt_brand.edit_playlist(playlist_id, addToTop=False) + playlist = self.yt_brand.get_playlist(playlist_id, related=True) self.assertEqual(len(playlist["tracks"]), 46, "Getting playlist items failed") - response = self.yt_brand.remove_playlist_items(playlistId, playlist["tracks"]) + response = self.yt_brand.remove_playlist_items(playlist_id, playlist["tracks"]) self.assertEqual(response, "STATUS_SUCCEEDED", "Playlist item removal failed") - self.yt_brand.delete_playlist(playlistId) + self.yt_brand.delete_playlist(playlist_id) ############### # UPLOADS diff --git a/ytmusicapi/auth/headers.py b/ytmusicapi/auth/headers.py deleted file mode 100644 index 0827950..0000000 --- a/ytmusicapi/auth/headers.py +++ /dev/null @@ -1,48 +0,0 @@ -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 YTMusicOAuth, is_oauth, is_custom_oauth -from ytmusicapi.helpers import initialize_headers - - -def load_headers_file(auth: str) -> Dict: - if os.path.isfile(auth): - with open(auth) as json_file: - input_json = json.load(json_file) - else: - input_json = json.loads(auth) - - return input_json - - -def prepare_headers( - session: requests.Session, - proxies: Optional[Dict] = None, - input_dict: Optional[CaseInsensitiveDict] = None, -) -> Dict: - if input_dict: - - if is_oauth(input_dict): - oauth = YTMusicOAuth(session, proxies) - headers = oauth.load_headers(dict(input_dict), input_dict['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 diff --git a/ytmusicapi/auth/oauth.py b/ytmusicapi/auth/oauth.py deleted file mode 100644 index 6a06e48..0000000 --- a/ytmusicapi/auth/oauth.py +++ /dev/null @@ -1,102 +0,0 @@ -import json -import time -import webbrowser -from typing import Dict, Optional - -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: - oauth_structure = { - "access_token", - "expires_at", - "expires_in", - "token_type", - "refresh_token", - } - 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 YTMusicOAuth: - """OAuth implementation for YouTube Music based on YouTube TV""" - - def __init__(self, session: requests.Session, proxies: Dict = None): - self._session = session - if proxies: - self._session.proxies.update(proxies) - - def _send_request(self, url, data) -> requests.Response: - data.update({"client_id": OAUTH_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 - - @staticmethod - def _parse_token(response) -> Dict: - token = response.json() - token["expires_at"] = int(time.time()) + int(token["expires_in"]) - return token - - def get_token_from_code(self, device_code: str) -> Dict: - response = self._send_request( - OAUTH_TOKEN_URL, - data={ - "client_secret": OAUTH_CLIENT_SECRET, - "grant_type": "http://oauth.net/grant_type/device/1.0", - "code": device_code, - }, - ) - return self._parse_token(response) - - def refresh_token(self, refresh_token: str) -> Dict: - response = self._send_request( - OAUTH_TOKEN_URL, - data={ - "client_secret": OAUTH_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: - 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) - - return token - - 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 diff --git a/ytmusicapi/auth/oauth/__init__.py b/ytmusicapi/auth/oauth/__init__.py new file mode 100644 index 0000000..d0b86c6 --- /dev/null +++ b/ytmusicapi/auth/oauth/__init__.py @@ -0,0 +1,5 @@ +from .credentials import OAuthCredentials +from .refreshing import RefreshingToken +from .base import OAuthToken + +__all__ = ['OAuthCredentials', 'RefreshingToken', 'OAuthToken'] diff --git a/ytmusicapi/auth/oauth/base.py b/ytmusicapi/auth/oauth/base.py new file mode 100644 index 0000000..980be2a --- /dev/null +++ b/ytmusicapi/auth/oauth/base.py @@ -0,0 +1,134 @@ +from typing import Optional, Dict +import time +import json + +from requests.structures import CaseInsensitiveDict + +from .models import BaseTokenDict, DefaultScope, Bearer, RefreshableTokenDict + + +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) -> RefreshableTokenDict: + 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: int + expires_at: int + is_expiring: bool + + scope: DefaultScope + token_type: Bearer + + 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, + 'scope': self.scope, + 'expires_at': self.expires_at, + 'expires_in': self.expires_in, + 'token_type': self.token_type + } + + def as_json(self) -> str: + return json.dumps(self.as_dict()) + + 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, + refresh_token: str, + scope: str, + token_type: str, + expires_at: Optional[int] = None, + expires_in: Optional[int] = None): + """ + + :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. + + """ + # 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 + + @staticmethod + 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) + + 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) -> str: + return self._access_token + + @property + def refresh_token(self) -> str: + return self._refresh_token + + @property + def token_type(self) -> Bearer: + return self._token_type + + @property + def scope(self) -> DefaultScope: + return self._scope + + @property + def expires_at(self) -> int: + return self._expires_at + + @property + def expires_in(self) -> int: + return int(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..2afef4c --- /dev/null +++ b/ytmusicapi/auth/oauth/credentials.py @@ -0,0 +1,123 @@ +import webbrowser +from typing import Dict, Optional + +import requests + +from .models import RefreshableTokenDict, BaseTokenDict, AuthCodeDict +from .base import OAuthToken, Credentials +from .refreshing import RefreshingToken +from .exceptions import BadOAuthClient, UnauthorizedOAuthClient + +from ytmusicapi.constants import (OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_CODE_URL, + OAUTH_SCOPE, OAUTH_TOKEN_URL, OAUTH_USER_AGENT) + + +class OAuthCredentials(Credentials): + """ + Class for handling OAuth credential retrieval and refreshing. + """ + + def __init__(self, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + session: Optional[requests.Session] = None, + proxies: Optional[Dict] = None): + """ + :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) -> 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: + data = response.json() + issue = data.get('error') + if issue == 'unauthorized_client': + raise UnauthorizedOAuthClient( + 'Token refresh error. Most likely client/token mismatch.') + + elif issue == 'invalid_client': + raise BadOAuthClient( + 'OAuth client failure. Most likely client_id and client_secret mismatch or ' + 'YouTubeData API is not enabled.') + else: + raise Exception( + f'OAuth request error. status_code: {response.status_code}, url: {url}, content: {data}' + ) + return response + + 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={ + "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: + """ + 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"]) + 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={ + "client_secret": self.client_secret, + "grant_type": "refresh_token", + "refresh_token": refresh_token, + }, + ) + + return response.json() diff --git a/ytmusicapi/auth/oauth/exceptions.py b/ytmusicapi/auth/oauth/exceptions.py new file mode 100644 index 0000000..04069ae --- /dev/null +++ b/ytmusicapi/auth/oauth/exceptions.py @@ -0,0 +1,12 @@ +class BadOAuthClient(Exception): + """ + OAuth client request failure. + Ensure provided client_id and secret are correct and YouTubeData API is enabled. + """ + + +class UnauthorizedOAuthClient(Exception): + """ + OAuth client lacks permissions for specified token. + Token can only be refreshed by OAuth credentials used for its creation. + """ diff --git a/ytmusicapi/auth/oauth/models.py b/ytmusicapi/auth/oauth/models.py new file mode 100644 index 0000000..d301602 --- /dev/null +++ b/ytmusicapi/auth/oauth/models.py @@ -0,0 +1,32 @@ +"""models for oauth authentication""" + +from typing import Union, Literal, TypedDict + +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 #: 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 RefreshableTokenDict(BaseTokenDict): + """ Entire token. Including refresh. Obtained through token setup. """ + + expires_at: int #: UNIX epoch timestamp in seconds + refresh_token: str #: str used to obtain new access token upon expiration + + +class AuthCodeDict(TypedDict): + """ Keys for the json object obtained via code response during auth flow. """ + + 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 diff --git a/ytmusicapi/auth/oauth/refreshing.py b/ytmusicapi/auth/oauth/refreshing.py new file mode 100644 index 0000000..0d77252 --- /dev/null +++ b/ytmusicapi/auth/oauth/refreshing.py @@ -0,0 +1,91 @@ +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) + + return cls(OAuthToken(**file_pack), credentials, file_path if sync else None) + + def __init__(self, + token: OAuthToken, + credentials: Credentials, + local_cache: Optional[str] = None): + """ + :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) -> str | None: + return self._local_cache + + @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) -> str: + 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, 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 token_type(self) -> Bearer: + # pass underlying value + return self.token.token_type + + def as_dict(self) -> RefreshableTokenDict: + # override base class method with call to underlying token's method + return self.token.as_dict() diff --git a/ytmusicapi/auth/types.py b/ytmusicapi/auth/types.py new file mode 100644 index 0000000..106c051 --- /dev/null +++ b/ytmusicapi/auth/types.py @@ -0,0 +1,25 @@ +"""enum representing types of authentication supported by this library""" + +from enum import Enum, auto +from typing import List + + +class AuthType(int, Enum): + """enum representing types of authentication supported by this library""" + + UNAUTHORIZED = auto() + + BROWSER = auto() + + #: client auth via OAuth token refreshing + OAUTH_DEFAULT = auto() + + #: YTM instance is using a non-default OAuth client (id & secret) + OAUTH_CUSTOM_CLIENT = auto() + + #: allows fully formed OAuth headers to ignore browser auth refresh flow + OAUTH_CUSTOM_FULL = auto() + + @classmethod + def oauth_types(cls) -> List["AuthType"]: + return [cls.OAUTH_DEFAULT, cls.OAUTH_CUSTOM_CLIENT, cls.OAUTH_CUSTOM_FULL] diff --git a/ytmusicapi/mixins/browsing.py b/ytmusicapi/mixins/browsing.py index f64b330..c3cbdf3 100644 --- a/ytmusicapi/mixins/browsing.py +++ b/ytmusicapi/mixins/browsing.py @@ -337,7 +337,7 @@ class BrowsingMixin: return user_playlists - def get_album_browse_id(self, audioPlaylistId: str) -> str: + def get_album_browse_id(self, audioPlaylistId: str) -> str | None: """ Get an album's browseId based on its audioPlaylistId @@ -346,6 +346,7 @@ class BrowsingMixin: """ params = {"list": audioPlaylistId} response = self._send_get_request(YTM_DOMAIN + "/playlist", params) + matches = re.search(r"\"MPRE.+?\"", response.text.encode("utf8").decode("unicode_escape")) browse_id = None if matches: diff --git a/ytmusicapi/mixins/explore.py b/ytmusicapi/mixins/explore.py index 8690af7..5429835 100644 --- a/ytmusicapi/mixins/explore.py +++ b/ytmusicapi/mixins/explore.py @@ -95,8 +95,8 @@ class ExploreMixin: Global charts have no Trending section, US charts have an extra Genres section with some Genre charts. :param country: ISO 3166-1 Alpha-2 country code. Default: ZZ = Global - :return: Dictionary containing chart songs (only if authenticated), chart videos, chart artists and - trending videos. + :return: Dictionary containing chart songs (only if authenticated with premium account), + chart videos, chart artists and trending videos. Example:: @@ -192,8 +192,8 @@ class ExploreMixin: body = {'browseId': 'FEmusic_charts'} if country: body['formData'] = {'selectedValues': [country]} - endpoint = 'browse' - response = self._send_request(endpoint, body) + + response = self._send_request('browse', body) results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST) charts = {'countries': {}} menu = nav( @@ -209,9 +209,13 @@ class ExploreMixin: ])) charts_categories = ['videos', 'artists'] - has_songs = bool(self.auth) has_genres = country == 'US' has_trending = country != 'ZZ' + + # use result length to determine if songs category is present + # could also be done via an is_premium attribute on YTMusic instance + has_songs = (len(results) - 1) > (len(charts_categories) + has_genres + has_trending) + if has_songs: charts_categories.insert(0, 'songs') if has_genres: diff --git a/ytmusicapi/mixins/uploads.py b/ytmusicapi/mixins/uploads.py index 91655bf..feab698 100644 --- a/ytmusicapi/mixins/uploads.py +++ b/ytmusicapi/mixins/uploads.py @@ -11,6 +11,7 @@ from ytmusicapi.parsers.library import parse_library_albums, parse_library_artis pop_songs_random_mix from ytmusicapi.parsers.albums import parse_album_header from ytmusicapi.parsers.uploads import parse_uploaded_items +from ..auth.types import AuthType class UploadsMixin: @@ -197,7 +198,7 @@ class UploadsMixin: :return: Status String or full response """ self._check_auth() - if not self.is_browser_auth: + if not self.auth_type == AuthType.BROWSER: raise Exception("Please provide authentication before using this function") if not os.path.isfile(filepath): raise Exception("The provided file does not exist.") diff --git a/ytmusicapi/setup.py b/ytmusicapi/setup.py index 7a0edb5..f826ec4 100644 --- a/ytmusicapi/setup.py +++ b/ytmusicapi/setup.py @@ -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,9 @@ 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, + 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 +36,22 @@ 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 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() - return YTMusicOAuth(session, proxies).setup(filepath, open_browser) + if 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 +61,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) diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index 29bc187..75bf940 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -3,10 +3,10 @@ import gettext import os from functools import partial from contextlib import suppress -from typing import Dict +from typing import Dict, Optional +import time from requests.structures import CaseInsensitiveDict -from ytmusicapi.auth.headers import load_headers_file, prepare_headers from ytmusicapi.parsers.i18n import Parser from ytmusicapi.helpers import * from ytmusicapi.mixins.browsing import BrowsingMixin @@ -16,7 +16,10 @@ 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 YTMusicOAuth, is_oauth + +from .auth.oauth import OAuthCredentials, RefreshingToken, OAuthToken +from .auth.oauth.base import Token +from .auth.types import AuthType class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin, @@ -28,16 +31,17 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin """ def __init__(self, - auth: str = None, + auth: Optional[str | Dict] = None, user: str = None, requests_session=True, - proxies: dict = None, + proxies: Dict = None, language: str = 'en', - location: str = ''): + location: str = '', + oauth_credentials: Optional[OAuthCredentials] = None): """ Create a new instance to interact with YouTube Music. - :param auth: Optional. Provide a string or path to file. + :param auth: Optional. Provide a string, path to file, or oauth token dict. Authentication credentials are needed to manage your library. See :py:func:`setup` for how to fill in the correct credentials. Default: A default header is used without authentication. @@ -68,10 +72,23 @@ 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 to be + used for authentication flow. """ - self.auth = auth - self.input_dict = None - self.is_oauth_auth = False + + 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 + + self.auth_type: AuthType = AuthType.UNAUTHORIZED + + 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 @@ -82,20 +99,28 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin else: # Use the Requests API module as a "session". self._session = requests.api - self.proxies = proxies # 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: - input_json = load_headers_file(self.auth) - self.input_dict = CaseInsensitiveDict(input_json) - self.input_dict['filepath'] = self.auth - self.is_oauth_auth = is_oauth(self.input_dict) + self.oauth_credentials = oauth_credentials if oauth_credentials is not None else OAuthCredentials() + auth_filepath = None + if isinstance(self.auth, str): + if os.path.isfile(auth): + with open(auth) as json_file: + auth_filepath = auth + input_json = json.load(json_file) + else: + input_json = json.loads(auth) + self._input_dict = CaseInsensitiveDict(input_json) - self.headers = prepare_headers(self._session, proxies, self.input_dict) + else: + self._input_dict = self.auth - if 'x-goog-visitor-id' not in self.headers: - self.headers.update(get_visitor_id(self._send_get_request)) + if OAuthToken.is_oauth(self._input_dict): + base_token = OAuthToken(**self._input_dict) + self._token = RefreshingToken(base_token, self.oauth_credentials, auth_filepath) + self.auth_type = AuthType.OAUTH_CUSTOM_CLIENT if oauth_credentials else AuthType.OAUTH_DEFAULT # prepare context self.context = initialize_context() @@ -123,27 +148,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 - if self.is_browser_auth: + auth_headers = self._input_dict.get("authorization") + if auth_headers: + if "SAPISIDHASH" in auth_headers: + self.auth_type = AuthType.BROWSER + elif auth_headers.startswith('Bearer'): + self.auth_type = AuthType.OAUTH_CUSTOM_FULL + + # sapsid, origin, and params all set once during init + self.params = YTM_PARAMS + if self.auth_type == AuthType.BROWSER: + 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") + @property + def base_headers(self): + if not self._base_headers: + if self.auth_type == AuthType.BROWSER or self.auth_type == AuthType.OAUTH_CUSTOM_FULL: + 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 + } + + return self._base_headers + + @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.auth_type == AuthType.BROWSER: + self._headers["authorization"] = get_authorization(self.sapisid + ' ' + self.origin) + + elif self.auth_type in AuthType.oauth_types(): + 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: - - if self.is_oauth_auth: - self.headers = prepare_headers(self._session, self.proxies, self.input_dict) body.update(self.context) - params = YTM_PARAMS - 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 - response = self._session.post(YTM_BASE_API + endpoint + params + additionalParams, + # 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, @@ -157,11 +220,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):