From e21492b7d380a8ed006abf70c04583c661900f12 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Thu, 14 Dec 2023 15:55:22 -0600 Subject: [PATCH 01/22] oauth: add support for alternate oauth client --- ytmusicapi/auth/oauth.py | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/ytmusicapi/auth/oauth.py b/ytmusicapi/auth/oauth.py index 6a06e48..35e93af 100644 --- a/ytmusicapi/auth/oauth.py +++ b/ytmusicapi/auth/oauth.py @@ -30,13 +30,35 @@ def is_custom_oauth(headers: CaseInsensitiveDict) -> bool: class YTMusicOAuth: """OAuth implementation for YouTube Music based on YouTube TV""" - def __init__(self, session: requests.Session, proxies: Dict = None): + def __init__(self, + session: requests.Session, + proxies: Dict = None, + *, + oauth_client_id: Optional[str] = None, + oauth_client_secret: Optional[str] = None): + """ + :param session: Session instance used for authorization requests. + :param proxies: Optional. Proxy configuration to be used by the session. + :param oauth_client_id: Optional. Keyword Only. Can be supplied to change the oauth client for token + retrieval and refreshing. Requires oauth_client_secret also be provided. + :param oauth_client_secret: Optional. Keyword Only. Used in conjunction with oauth_client_id to switch + underlying oauth client. + """ + + if not isinstance(oauth_client_id, type(oauth_client_secret)): + raise KeyError( + 'Alternate oauth credential usage requires an id AND a secret. Pass both or neither.' + ) + + self.oauth_id = oauth_client_id if oauth_client_id else OAUTH_CLIENT_ID + self.oauth_secret = oauth_client_secret if oauth_client_secret else OAUTH_CLIENT_SECRET + 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}) + data.update({"client_id": self.oauth_id}) headers = {"User-Agent": OAUTH_USER_AGENT} return self._session.post(url, data, headers=headers) @@ -55,7 +77,7 @@ class YTMusicOAuth: response = self._send_request( OAUTH_TOKEN_URL, data={ - "client_secret": OAUTH_CLIENT_SECRET, + "client_secret": self.oauth_secret, "grant_type": "http://oauth.net/grant_type/device/1.0", "code": device_code, }, @@ -66,7 +88,7 @@ class YTMusicOAuth: response = self._send_request( OAUTH_TOKEN_URL, data={ - "client_secret": OAUTH_CLIENT_SECRET, + "client_secret": self.oauth_secret, "grant_type": "refresh_token", "refresh_token": refresh_token, }, From b9be59de50c93739ce8e979162c5ac96abb00ea3 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Sat, 16 Dec 2023 15:55:06 -0600 Subject: [PATCH 02/22] get_album_browse_id: fix depreciated escape sequence error && add performance increase --- ytmusicapi/mixins/browsing.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ytmusicapi/mixins/browsing.py b/ytmusicapi/mixins/browsing.py index 61cf9ab..fe4dbf2 100644 --- a/ytmusicapi/mixins/browsing.py +++ b/ytmusicapi/mixins/browsing.py @@ -332,7 +332,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 @@ -341,11 +341,11 @@ 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: - browse_id = matches.group().strip('"') - return browse_id + + if (start := response.text.find('MPREb_')) == -1: + return None + + return response.text[start:(response.text.find('"', start) - 1)] def get_album(self, browseId: str) -> Dict: """ From b2c078df636fd82548af8359cb0491cd23ccdccf Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Sat, 16 Dec 2023 15:58:00 -0600 Subject: [PATCH 03/22] get_charts: fix index errors on authorized song chart missing --- tests/test.py | 3 ++- ytmusicapi/mixins/explore.py | 8 ++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/test.py b/tests/test.py index 9aff93d..f69f3d4 100644 --- a/tests/test.py +++ b/tests/test.py @@ -284,7 +284,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") diff --git a/ytmusicapi/mixins/explore.py b/ytmusicapi/mixins/explore.py index 8690af7..9b554ef 100644 --- a/ytmusicapi/mixins/explore.py +++ b/ytmusicapi/mixins/explore.py @@ -95,7 +95,7 @@ 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 + :return: Dictionary containing chart songs (only if authenticated and available), chart videos, chart artists and trending videos. Example:: @@ -209,9 +209,13 @@ class ExploreMixin: ])) charts_categories = ['videos', 'artists'] - has_songs = bool(self.auth) has_genres = country == 'US' has_trending = country != 'ZZ' + # songs section appears to no longer exist, extra length check avoids + # index errors and will still include songs if the feature is added back + has_songs = bool( + self.auth) and len(results) - 1 > (len(charts_categories) + has_genres + has_trending) + if has_songs: charts_categories.insert(0, 'songs') if has_genres: From b60af9cc25cc39f5f8759a63a323a658b5389d0c Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Sat, 16 Dec 2023 16:07:07 -0600 Subject: [PATCH 04/22] add: set_album_save as a convenience/alias/findable method for album rate_playlist --- tests/test.py | 7 +++++++ ytmusicapi/mixins/library.py | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/tests/test.py b/tests/test.py index f69f3d4..e4a9a2b 100644 --- a/tests/test.py +++ b/tests/test.py @@ -417,6 +417,13 @@ class TestYTMusic(unittest.TestCase): "INDIFFERENT") self.assertIn("actions", response) + def test_save_album(self): + response = self.yt_auth.set_album_save("OLAK5uy_kCxQGgn8Ayb-8VNSs3Ok7qdcKe5PJy6ZQ") + self.assertIn("actions", response) + response = self.yt_auth.set_album_save("OLAK5uy_kCxQGgn8Ayb-8VNSs3Ok7qdcKe5PJy6ZQ", + saved=False) + self.assertIn("actions", response) + def test_subscribe_artists(self): self.yt_auth.subscribe_artists(["UCUDVBtnOQi4c7E8jebpjc9Q", "UCiMhD4jzUqG-IgPzUmmytRQ"]) self.yt_auth.unsubscribe_artists(["UCUDVBtnOQi4c7E8jebpjc9Q", "UCiMhD4jzUqG-IgPzUmmytRQ"]) diff --git a/ytmusicapi/mixins/library.py b/ytmusicapi/mixins/library.py index 71b01bb..c265293 100644 --- a/ytmusicapi/mixins/library.py +++ b/ytmusicapi/mixins/library.py @@ -267,6 +267,25 @@ class LibraryMixin: return self._send_request(endpoint, body) + def set_album_save(self, audioPlaylistId: str, saved=True): + """ + Edit the save status of an album in the user's library. Findable convenience/alias + method for album portion of rate_playlist. + + :param audioPlaylistId: audioPlaylistId (starts with "OLAKuy_") for the target album + :param saved: Boolean. The resulting saved state of the album. (Default = True) + + :return: Full response + """ + + self._check_auth() + body = {'target': {'playlistId': audioPlaylistId}} + endpoint = prepare_like_endpoint('LIKE' if saved else 'INDIFFERENT') + if endpoint is None: + return + + return self._send_request(endpoint, body) + def edit_song_library_status(self, feedbackTokens: List[str] = None) -> Dict: """ Adds or removes a song from your library depending on the token provided. From 91949b54031bd4d9c95ccca4ff31906a940bf1a7 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Sat, 16 Dec 2023 16:18:38 -0600 Subject: [PATCH 05/22] fix: externalize library dependent or regional arguments to test.cfg --- tests/test.cfg.example | 13 ++++++++++ tests/test.py | 57 ++++++++++++++++++++++++++---------------- 2 files changed, 48 insertions(+), 22 deletions(-) diff --git a/tests/test.cfg.example b/tests/test.cfg.example index 25cf53e..e0a9c90 100644 --- a/tests/test.cfg.example +++ b/tests/test.cfg.example @@ -9,8 +9,21 @@ oauth_code = {"device_code":"","user_code":"","expires_in":1800,"interval":5,"ve oauth_token = {"access_token":"","expires_in":1000,"refresh_token":"","scope":"https://www.googleapis.com/auth/youtube","token_type":"Bearer"} 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 e4a9a2b..2cfccc0 100644 --- a/tests/test.py +++ b/tests/test.py @@ -135,24 +135,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_auth.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, @@ -215,7 +228,7 @@ class TestYTMusic(unittest.TestCase): 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) @@ -244,8 +257,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") @@ -306,12 +319,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_lKgoGvlrWhX0EIPavQUXxyPed8Cj38AWc", 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 @@ -485,15 +498,15 @@ class TestYTMusic(unittest.TestCase): # end to end test adding playlist, adding item, deleting item, deleting playlist 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, @@ -501,12 +514,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 From 6c94c80086a2eabd90177365dae309b8bb473af5 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Sat, 16 Dec 2023 16:26:24 -0600 Subject: [PATCH 06/22] add: integrate alt_oauth into YTMusic && add: token dict support for auth parameter --- tests/test.py | 23 +++++++++++++++++------ ytmusicapi/auth/headers.py | 24 +++++++++++++++++------- ytmusicapi/ytmusic.py | 36 ++++++++++++++++++++++++++++-------- 3 files changed, 62 insertions(+), 21 deletions(-) diff --git a/tests/test.py b/tests/test.py index 2cfccc0..b8395d2 100644 --- a/tests/test.py +++ b/tests/test.py @@ -10,6 +10,7 @@ from requests import Response from ytmusicapi.setup import main, setup # noqa: E402 from ytmusicapi.ytmusic import YTMusic # noqa: E402 +from ytmusicapi.constants import OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET def get_resource(file: str) -> str: @@ -27,6 +28,8 @@ 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_args = {'oauth_client_id': OAUTH_CLIENT_ID, 'oauth_client_secret': OAUTH_CLIENT_SECRET} + class TestYTMusic(unittest.TestCase): @@ -37,6 +40,7 @@ class TestYTMusic(unittest.TestCase): assert isinstance(yt, YTMusic) cls.yt = YTMusic() cls.yt_oauth = YTMusic(headers_oauth) + cls.yt_alt_oauth = YTMusic(headers_browser, alt_oauth=alt_oauth_args) cls.yt_auth = YTMusic(headers_browser, location="GB") cls.yt_brand = YTMusic(config["auth"]["headers"], config["auth"]["brand_account"]) cls.yt_empty = YTMusic(config["auth"]["headers_empty"], @@ -67,7 +71,14 @@ class TestYTMusic(unittest.TestCase): 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) + + self.yt_oauth = YTMusic(string_headers) + with self.subTest(): + # 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(string_headers), alt_oauth=alt_oauth_args) + self.assertTrue(self.yt_alt_oauth.is_alt_oauth) ############### # BROWSING @@ -148,10 +159,10 @@ class TestYTMusic(unittest.TestCase): def test_search_library(self): results = self.yt_oauth.search(config['queries']['library_any'], scope="library") self.assertGreater(len(results), 5) - results = self.yt_auth.search(config['queries']['library_songs'], - 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(config['queries']['library_albums'], filter="albums", @@ -243,7 +254,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): diff --git a/ytmusicapi/auth/headers.py b/ytmusicapi/auth/headers.py index 0827950..5901e8a 100644 --- a/ytmusicapi/auth/headers.py +++ b/ytmusicapi/auth/headers.py @@ -20,16 +20,26 @@ def load_headers_file(auth: str) -> Dict: return input_json -def prepare_headers( - session: requests.Session, - proxies: Optional[Dict] = None, - input_dict: Optional[CaseInsensitiveDict] = None, -) -> Dict: +def prepare_headers(auth_session: requests.Session | YTMusicOAuth, + proxies: Optional[Dict] = None, + input_dict: Optional[CaseInsensitiveDict] = None) -> Dict: + """ + + :param auth_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. + """ if input_dict: if is_oauth(input_dict): - oauth = YTMusicOAuth(session, proxies) - headers = oauth.load_headers(dict(input_dict), input_dict['filepath']) + if isinstance(auth_session, YTMusicOAuth): + oauth = auth_session + else: + oauth = YTMusicOAuth(auth_session, proxies) + + headers = oauth.load_headers(dict(input_dict), input_dict.get('filepath')) elif is_browser(input_dict): headers = input_dict diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index 29bc187..d246bfa 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -3,7 +3,7 @@ import gettext import os from functools import partial from contextlib import suppress -from typing import Dict +from typing import Dict, Optional from requests.structures import CaseInsensitiveDict from ytmusicapi.auth.headers import load_headers_file, prepare_headers @@ -28,16 +28,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, language: str = 'en', - location: str = ''): + location: str = '', + alt_oauth: Optional[dict] = 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 +69,14 @@ 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 alt_oauth: Optional. Used to specify a different oauth client id and secret to be + used for authentication flow. Should contain both oauth_client_id + and oauth_client_secret keys when provided. """ self.auth = auth self.input_dict = None self.is_oauth_auth = False + self.alt_oauth = None if isinstance(requests_session, requests.Session): self._session = requests_session @@ -87,12 +92,23 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin # 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 + if isinstance(self.auth, str): + input_json = load_headers_file(self.auth) + self.input_dict = CaseInsensitiveDict(input_json) + self.input_dict['filepath'] = self.auth + + elif isinstance(self.auth, dict): + self.input_dict = self.auth + self.is_oauth_auth = is_oauth(self.input_dict) - self.headers = prepare_headers(self._session, proxies, self.input_dict) + # use custom oauth client parameters if provided + if alt_oauth and isinstance(alt_oauth, dict): + self.alt_oauth = YTMusicOAuth(self._session, proxies, **alt_oauth) + # custom oauth passed in place of session, kwarg used as proxies are skipped + self.headers = prepare_headers(self.alt_oauth, input_dict=self.input_dict) + else: + self.headers = prepare_headers(self._session, proxies, self.input_dict) if 'x-goog-visitor-id' not in self.headers: self.headers.update(get_visitor_id(self._send_get_request)) @@ -132,6 +148,10 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin except KeyError: raise Exception("Your cookie is missing the required value __Secure-3PAPISID") + @property + def is_alt_oauth(self): + return self.alt_oauth is not None and self.is_oauth_auth + def _send_request(self, endpoint: str, body: Dict, additionalParams: str = "") -> Dict: if self.is_oauth_auth: From 742f5842fa554e60e6b718780eca4d3577d38127 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Mon, 18 Dec 2023 12:53:31 -0600 Subject: [PATCH 07/22] unadd: set_album_save. unneeded duplicate to rate_playlist --- tests/test.py | 7 ------- ytmusicapi/mixins/library.py | 19 ------------------- 2 files changed, 26 deletions(-) diff --git a/tests/test.py b/tests/test.py index b8395d2..0fea602 100644 --- a/tests/test.py +++ b/tests/test.py @@ -441,13 +441,6 @@ class TestYTMusic(unittest.TestCase): "INDIFFERENT") self.assertIn("actions", response) - def test_save_album(self): - response = self.yt_auth.set_album_save("OLAK5uy_kCxQGgn8Ayb-8VNSs3Ok7qdcKe5PJy6ZQ") - self.assertIn("actions", response) - response = self.yt_auth.set_album_save("OLAK5uy_kCxQGgn8Ayb-8VNSs3Ok7qdcKe5PJy6ZQ", - saved=False) - self.assertIn("actions", response) - def test_subscribe_artists(self): self.yt_auth.subscribe_artists(["UCUDVBtnOQi4c7E8jebpjc9Q", "UCiMhD4jzUqG-IgPzUmmytRQ"]) self.yt_auth.unsubscribe_artists(["UCUDVBtnOQi4c7E8jebpjc9Q", "UCiMhD4jzUqG-IgPzUmmytRQ"]) diff --git a/ytmusicapi/mixins/library.py b/ytmusicapi/mixins/library.py index c265293..71b01bb 100644 --- a/ytmusicapi/mixins/library.py +++ b/ytmusicapi/mixins/library.py @@ -267,25 +267,6 @@ class LibraryMixin: return self._send_request(endpoint, body) - def set_album_save(self, audioPlaylistId: str, saved=True): - """ - Edit the save status of an album in the user's library. Findable convenience/alias - method for album portion of rate_playlist. - - :param audioPlaylistId: audioPlaylistId (starts with "OLAKuy_") for the target album - :param saved: Boolean. The resulting saved state of the album. (Default = True) - - :return: Full response - """ - - self._check_auth() - body = {'target': {'playlistId': audioPlaylistId}} - endpoint = prepare_like_endpoint('LIKE' if saved else 'INDIFFERENT') - if endpoint is None: - return - - return self._send_request(endpoint, body) - def edit_song_library_status(self, feedbackTokens: List[str] = None) -> Dict: """ Adds or removes a song from your library depending on the token provided. From 10241c7ee44090af30937e2a7a45aaf83f9bc4a4 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Mon, 18 Dec 2023 17:58:21 -0600 Subject: [PATCH 08/22] fix: dataclass implementation of credentials --- tests/test.py | 21 ++++++++++---------- ytmusicapi/auth/headers.py | 21 ++++++++++---------- ytmusicapi/auth/oauth.py | 33 ++++++++++++++++---------------- ytmusicapi/ytmusic.py | 39 +++++++++++++++++++------------------- 4 files changed, 58 insertions(+), 56 deletions(-) diff --git a/tests/test.py b/tests/test.py index 0fea602..e9bfb3a 100644 --- a/tests/test.py +++ b/tests/test.py @@ -9,7 +9,7 @@ from unittest import mock from requests import Response 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 @@ -28,7 +28,7 @@ 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_args = {'oauth_client_id': OAUTH_CLIENT_ID, 'oauth_client_secret': OAUTH_CLIENT_SECRET} +alt_oauth_creds = OAuthCredentials(**{'client_id': OAUTH_CLIENT_ID, 'client_secret': OAUTH_CLIENT_SECRET}) class TestYTMusic(unittest.TestCase): @@ -40,7 +40,7 @@ class TestYTMusic(unittest.TestCase): assert isinstance(yt, YTMusic) cls.yt = YTMusic() cls.yt_oauth = YTMusic(headers_oauth) - cls.yt_alt_oauth = YTMusic(headers_browser, alt_oauth=alt_oauth_args) + cls.yt_alt_oauth = YTMusic(headers_browser, oauth_credentials=alt_oauth_creds) cls.yt_auth = YTMusic(headers_browser, location="GB") cls.yt_brand = YTMusic(config["auth"]["headers"], config["auth"]["brand_account"]) cls.yt_empty = YTMusic(config["auth"]["headers_empty"], @@ -71,14 +71,14 @@ class TestYTMusic(unittest.TestCase): 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) - self.yt_oauth = YTMusic(string_headers) - with self.subTest(): - # 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(string_headers), alt_oauth=alt_oauth_args) - self.assertTrue(self.yt_alt_oauth.is_alt_oauth) + def test_alt_oauth(self): + # 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.assertTrue(self.yt_alt_oauth.is_alt_oauth) ############### # BROWSING @@ -501,6 +501,7 @@ 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", diff --git a/ytmusicapi/auth/headers.py b/ytmusicapi/auth/headers.py index 5901e8a..289b40d 100644 --- a/ytmusicapi/auth/headers.py +++ b/ytmusicapi/auth/headers.py @@ -6,7 +6,7 @@ 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.auth.oauth import OAuthCredentials, YTMusicOAuth, is_oauth, is_custom_oauth from ytmusicapi.helpers import initialize_headers @@ -14,31 +14,32 @@ def load_headers_file(auth: str) -> Dict: if os.path.isfile(auth): with open(auth) as json_file: input_json = json.load(json_file) + input_json['filepath'] = auth else: input_json = json.loads(auth) return input_json -def prepare_headers(auth_session: requests.Session | YTMusicOAuth, +def prepare_headers(session: requests.Session, proxies: Optional[Dict] = None, - input_dict: Optional[CaseInsensitiveDict] = None) -> Dict: + input_dict: Optional[CaseInsensitiveDict] = None, + oauth_credentials: Optional[OAuthCredentials] = None + ) -> Dict: """ - :param auth_session: Either the session to be used when creating a YTMusicOAuth + :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): - if isinstance(auth_session, YTMusicOAuth): - oauth = auth_session - else: - oauth = YTMusicOAuth(auth_session, proxies) - + oauth = YTMusicOAuth(session, proxies, oauth_credentials=oauth_credentials) headers = oauth.load_headers(dict(input_dict), input_dict.get('filepath')) elif is_browser(input_dict): diff --git a/ytmusicapi/auth/oauth.py b/ytmusicapi/auth/oauth.py index 35e93af..2e436c8 100644 --- a/ytmusicapi/auth/oauth.py +++ b/ytmusicapi/auth/oauth.py @@ -2,6 +2,9 @@ import json import time import webbrowser from typing import Dict, Optional +from dataclasses import dataclass +from os import environ as env + import requests from requests.structures import CaseInsensitiveDict @@ -27,6 +30,12 @@ def is_custom_oauth(headers: CaseInsensitiveDict) -> bool: return "authorization" in headers and headers["authorization"].startswith("Bearer ") +@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) + + class YTMusicOAuth: """OAuth implementation for YouTube Music based on YouTube TV""" @@ -34,31 +43,23 @@ class YTMusicOAuth: session: requests.Session, proxies: Dict = None, *, - oauth_client_id: Optional[str] = None, - oauth_client_secret: Optional[str] = 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_client_id: Optional. Keyword Only. Can be supplied to change the oauth client for token - retrieval and refreshing. Requires oauth_client_secret also be provided. - :param oauth_client_secret: Optional. Keyword Only. Used in conjunction with oauth_client_id to switch - underlying oauth client. + :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. """ - if not isinstance(oauth_client_id, type(oauth_client_secret)): - raise KeyError( - 'Alternate oauth credential usage requires an id AND a secret. Pass both or neither.' - ) - - self.oauth_id = oauth_client_id if oauth_client_id else OAUTH_CLIENT_ID - self.oauth_secret = oauth_client_secret if oauth_client_secret else OAUTH_CLIENT_SECRET + self.credentials = oauth_credentials if oauth_credentials else OAuthCredentials() self._session = session if proxies: self._session.proxies.update(proxies) def _send_request(self, url, data) -> requests.Response: - data.update({"client_id": self.oauth_id}) + data.update({"client_id": self.credentials.client_id}) headers = {"User-Agent": OAUTH_USER_AGENT} return self._session.post(url, data, headers=headers) @@ -77,7 +78,7 @@ class YTMusicOAuth: response = self._send_request( OAUTH_TOKEN_URL, data={ - "client_secret": self.oauth_secret, + "client_secret": self.credentials.client_secret, "grant_type": "http://oauth.net/grant_type/device/1.0", "code": device_code, }, @@ -88,7 +89,7 @@ class YTMusicOAuth: response = self._send_request( OAUTH_TOKEN_URL, data={ - "client_secret": self.oauth_secret, + "client_secret": self.credentials.client_secret, "grant_type": "refresh_token", "refresh_token": refresh_token, }, diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index d246bfa..a3dbc05 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -16,7 +16,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 YTMusicOAuth, is_oauth +from ytmusicapi.auth.oauth import OAuthCredentials, YTMusicOAuth, is_oauth class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin, @@ -34,7 +34,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin proxies: dict = None, language: str = 'en', location: str = '', - alt_oauth: Optional[dict] = None): + oauth_credentials: Optional[OAuthCredentials] = None): """ Create a new instance to interact with YouTube Music. @@ -69,14 +69,16 @@ 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 alt_oauth: Optional. Used to specify a different oauth client id and secret to be - used for authentication flow. Should contain both oauth_client_id - and oauth_client_secret keys when provided. + :param oauth_credentials: Optional. Used to specify a different oauth client id and secret to be + used for authentication flow. """ self.auth = auth self.input_dict = None self.is_oauth_auth = False - self.alt_oauth = None + if oauth_credentials is not None: + self.oauth_credentials = oauth_credentials + else: + self.oauth_credentials = OAuthCredentials() if isinstance(requests_session, requests.Session): self._session = requests_session @@ -95,20 +97,17 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin if isinstance(self.auth, str): input_json = load_headers_file(self.auth) self.input_dict = CaseInsensitiveDict(input_json) - self.input_dict['filepath'] = self.auth - elif isinstance(self.auth, dict): + else: 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 - # use custom oauth client parameters if provided - if alt_oauth and isinstance(alt_oauth, dict): - self.alt_oauth = YTMusicOAuth(self._session, proxies, **alt_oauth) - # custom oauth passed in place of session, kwarg used as proxies are skipped - self.headers = prepare_headers(self.alt_oauth, input_dict=self.input_dict) - else: - self.headers = prepare_headers(self._session, proxies, self.input_dict) + 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)) @@ -148,14 +147,14 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin except KeyError: raise Exception("Your cookie is missing the required value __Secure-3PAPISID") - @property - def is_alt_oauth(self): - return self.alt_oauth is not None and self.is_oauth_auth - 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) + self.headers = prepare_headers(self._session, + self.proxies, + self.input_dict, + oauth_credentials=self.oauth_credentials) + body.update(self.context) params = YTM_PARAMS if self.is_browser_auth: From 9cb8c63d99e5ad45d71e076d55a658fe2c5f040b Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Mon, 18 Dec 2023 23:37:17 -0600 Subject: [PATCH 09/22] minor touch-up: rebuild the entire oauth system --- tests/test.py | 9 +- ytmusicapi/auth/headers.py | 48 +------- ytmusicapi/auth/oauth.py | 239 ++++++++++++++++++++++++++----------- ytmusicapi/setup.py | 31 ++++- ytmusicapi/ytmusic.py | 122 ++++++++++++------- 5 files changed, 282 insertions(+), 167 deletions(-) diff --git a/tests/test.py b/tests/test.py index e9bfb3a..7d7199c 100644 --- a/tests/test.py +++ b/tests/test.py @@ -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", diff --git a/ytmusicapi/auth/headers.py b/ytmusicapi/auth/headers.py index 289b40d..6831b8b 100644 --- a/ytmusicapi/auth/headers.py +++ b/ytmusicapi/auth/headers.py @@ -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 diff --git a/ytmusicapi/auth/oauth.py b/ytmusicapi/auth/oauth.py index 2e436c8..8ecaff0 100644 --- a/ytmusicapi/auth/oauth.py +++ b/ytmusicapi/auth/oauth.py @@ -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 diff --git a/ytmusicapi/setup.py b/ytmusicapi/setup.py index 7a0edb5..20f051f 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,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) diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index a3dbc05..cb54fb1 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -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): From 8dac2e528f042203cbf63ecc94a51236808d6c4e Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Tue, 19 Dec 2023 13:49:03 -0600 Subject: [PATCH 10/22] fix: new token init --- ytmusicapi/auth/oauth.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/ytmusicapi/auth/oauth.py b/ytmusicapi/auth/oauth.py index 8ecaff0..8e68e3f 100644 --- a/ytmusicapi/auth/oauth.py +++ b/ytmusicapi/auth/oauth.py @@ -27,14 +27,21 @@ class OAuthToken: @classmethod def from_response(cls, response): - return cls(**response.json()) + data = response.json() + return cls(**data) - def __init__(self, access_token: str, refresh_token: str, scope: str, expires_at: int, - token_type: str, **etc: Optional[Any]): + 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 + self._expires_at: int = expires_at if expires_at else int(time.time() + expires_in) self._token_type = token_type @property From 5f1945ae056c765a4576ce9d9754745d117e7803 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Tue, 19 Dec 2023 13:59:35 -0600 Subject: [PATCH 11/22] remove: env support --- ytmusicapi/auth/oauth.py | 18 ------------------ ytmusicapi/setup.py | 16 ++-------------- 2 files changed, 2 insertions(+), 32 deletions(-) diff --git a/ytmusicapi/auth/oauth.py b/ytmusicapi/auth/oauth.py index 8e68e3f..528a6f7 100644 --- a/ytmusicapi/auth/oauth.py +++ b/ytmusicapi/auth/oauth.py @@ -2,7 +2,6 @@ import json import time import webbrowser from typing import Dict, Optional, Any -from os import environ as env import os import requests @@ -88,23 +87,6 @@ class OAuthToken: class OAuthCredentials: - @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) - - return cls(client_id=env[client_id_key], - client_secret=env[client_secret_key], - session=session, - proxies=proxies) - def __init__(self, client_id: Optional[str] = OAUTH_CLIENT_ID, client_secret: Optional[str] = OAUTH_CLIENT_SECRET, diff --git a/ytmusicapi/setup.py b/ytmusicapi/setup.py index 20f051f..f826ec4 100644 --- a/ytmusicapi/setup.py +++ b/ytmusicapi/setup.py @@ -26,7 +26,6 @@ def setup_oauth(filepath: str = None, session: requests.Session = None, proxies: dict = None, open_browser: bool = False, - env_credentials: bool = False, client_id: str = None, client_secret: str = None) -> Dict: """ @@ -37,13 +36,8 @@ 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. + 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 @@ -51,13 +45,7 @@ def setup_oauth(filepath: str = None, if not session: session = requests.Session() - 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: + if client_id and client_secret: oauth_credentials = OAuthCredentials(client_id, client_secret, session, proxies) else: From 814ea9999be2b76827b5311463f76f0d96183f46 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Wed, 20 Dec 2023 15:15:25 -0600 Subject: [PATCH 12/22] get_album_browse_id: reverted and subtest added for edge case --- tests/test.py | 6 ++++++ ytmusicapi/mixins/browsing.py | 9 +++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/tests/test.py b/tests/test.py index 7d7199c..fab1746 100644 --- a/tests/test.py +++ b/tests/test.py @@ -237,6 +237,11 @@ class TestYTMusic(unittest.TestCase): def test_get_album_browse_id(self): 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") + # general length, I believe 17 is standard, but unsure if edge cases exist + self.assertLess(len(escaped_browse_id), 24) def test_get_album(self): results = self.yt_auth.get_album(sample_album) @@ -505,6 +510,7 @@ 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. Please wait a bit...') def test_end2end(self): playlist_id = self.yt_brand.create_playlist( "test", diff --git a/ytmusicapi/mixins/browsing.py b/ytmusicapi/mixins/browsing.py index fe4dbf2..4c644e1 100644 --- a/ytmusicapi/mixins/browsing.py +++ b/ytmusicapi/mixins/browsing.py @@ -342,10 +342,11 @@ class BrowsingMixin: params = {"list": audioPlaylistId} response = self._send_get_request(YTM_DOMAIN + "/playlist", params) - if (start := response.text.find('MPREb_')) == -1: - return None - - return response.text[start:(response.text.find('"', start) - 1)] + matches = re.search(r"\"MPRE.+?\"", response.text.encode("utf8").decode("unicode_escape")) + browse_id = None + if matches: + browse_id = matches.group().strip('"') + return browse_id def get_album(self, browseId: str) -> Dict: """ From 45df3afdfbdde756ea5cc23ada071f8221390179 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Wed, 20 Dec 2023 15:18:29 -0600 Subject: [PATCH 13/22] 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() From 7b60e65ea4f82c170544f7ef4584cc160a56e5fe Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Thu, 28 Dec 2023 17:58:39 -0600 Subject: [PATCH 14/22] test_get_album_browse_id: hindsight test edit and bulletproof fix for warning --- tests/test.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test.py b/tests/test.py index fab1746..85c9186 100644 --- a/tests/test.py +++ b/tests/test.py @@ -235,13 +235,13 @@ 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") - # general length, I believe 17 is standard, but unsure if edge cases exist - self.assertLess(len(escaped_browse_id), 24) + self.assertEqual(escaped_browse_id, 'MPREb_scJdtUCpPE2') def test_get_album(self): results = self.yt_auth.get_album(sample_album) From 38685c9b1718742843d06867a0d861a9589e231c Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Thu, 28 Dec 2023 18:00:12 -0600 Subject: [PATCH 15/22] explore.py: charts fix and docs edit --- ytmusicapi/mixins/explore.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/ytmusicapi/mixins/explore.py b/ytmusicapi/mixins/explore.py index 9b554ef..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 and available), 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( @@ -211,10 +211,10 @@ class ExploreMixin: has_genres = country == 'US' has_trending = country != 'ZZ' - # songs section appears to no longer exist, extra length check avoids - # index errors and will still include songs if the feature is added back - has_songs = bool( - self.auth) and len(results) - 1 > (len(charts_categories) + has_genres + has_trending) + + # 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') From fe85234ce3e8d5f914564c8f058fdca71909a8f3 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Thu, 28 Dec 2023 18:04:54 -0600 Subject: [PATCH 16/22] credentials.py: custom exceptions.py for pesky issues --- ytmusicapi/auth/oauth/credentials.py | 20 ++++++++++++++++++-- ytmusicapi/auth/oauth/exceptions.py | 12 ++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 ytmusicapi/auth/oauth/exceptions.py diff --git a/ytmusicapi/auth/oauth/credentials.py b/ytmusicapi/auth/oauth/credentials.py index 22535b0..514f628 100644 --- a/ytmusicapi/auth/oauth/credentials.py +++ b/ytmusicapi/auth/oauth/credentials.py @@ -7,6 +7,7 @@ from requests.structures import CaseInsensitiveDict from .models import FullTokenDict, BaseTokenDict, CodeDict 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) @@ -42,10 +43,25 @@ class OAuthCredentials(Credentials): 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}) + 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) -> FullTokenDict: - """ Returns a FullTokenDict, including refresh_token """ response = self._send_request( OAUTH_TOKEN_URL, data={ 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. + """ From a589eadcab8868e4089cb4c29ad65503f2857ccb Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Thu, 28 Dec 2023 18:13:11 -0600 Subject: [PATCH 17/22] ytmusic: oauth initialization changes to fix keyerrors, reduce code and improve speed --- ytmusicapi/auth/oauth/__init__.py | 4 ++-- ytmusicapi/auth/oauth/credentials.py | 11 ----------- ytmusicapi/ytmusic.py | 19 +++++++++++++------ 3 files changed, 15 insertions(+), 19 deletions(-) diff --git a/ytmusicapi/auth/oauth/__init__.py b/ytmusicapi/auth/oauth/__init__.py index f8813a2..d0b86c6 100644 --- a/ytmusicapi/auth/oauth/__init__.py +++ b/ytmusicapi/auth/oauth/__init__.py @@ -1,5 +1,5 @@ -from .credentials import OAuthCredentials, is_oauth +from .credentials import OAuthCredentials from .refreshing import RefreshingToken from .base import OAuthToken -__all__ = ['OAuthCredentials', 'is_oauth', 'RefreshingToken', 'OAuthToken'] +__all__ = ['OAuthCredentials', 'RefreshingToken', 'OAuthToken'] diff --git a/ytmusicapi/auth/oauth/credentials.py b/ytmusicapi/auth/oauth/credentials.py index 514f628..2d3e5b4 100644 --- a/ytmusicapi/auth/oauth/credentials.py +++ b/ytmusicapi/auth/oauth/credentials.py @@ -13,17 +13,6 @@ from ytmusicapi.constants import (OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_CO 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, diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index cb54fb1..ff7b26e 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -7,7 +7,6 @@ from typing import Dict, Optional import time from requests.structures import CaseInsensitiveDict -from ytmusicapi.auth.headers import load_headers_file from ytmusicapi.parsers.i18n import Parser from ytmusicapi.helpers import * from ytmusicapi.mixins.browsing import BrowsingMixin @@ -17,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 OAuthCredentials, is_oauth, RefreshingToken, OAuthToken + +from .auth.headers import load_headers_file +from .auth.oauth import OAuthCredentials, RefreshingToken, OAuthToken +from .auth.oauth.base import Token class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin, @@ -109,12 +111,17 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin else: self._input_dict = self.auth - if is_oauth(self._input_dict): + # check if OAuth by passing values as kwargs to OAuthToken init using + # KeyError from incompatible input_dict as False + try: + base_token = OAuthToken(**self._input_dict) + self._token = RefreshingToken(base_token, self.oauth_credentials, + self._input_dict.get('filepath')) 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')) + + except TypeError: + pass # prepare context self.context = initialize_context() From 940b827fb495d026c546ed46f431523a3224c0fc Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Thu, 28 Dec 2023 18:16:22 -0600 Subject: [PATCH 18/22] docs: docs, ~~docs~~, and docs with a splash of type hinting --- ytmusicapi/auth/oauth/base.py | 66 +++++++++++++++++-------- ytmusicapi/auth/oauth/credentials.py | 56 +++++++++++++++++----- ytmusicapi/auth/oauth/models.py | 34 +++++++------ ytmusicapi/auth/oauth/refreshing.py | 72 +++++++++++++++++++++------- ytmusicapi/ytmusic.py | 32 ++++++++----- 5 files changed, 187 insertions(+), 73 deletions(-) diff --git a/ytmusicapi/auth/oauth/base.py b/ytmusicapi/auth/oauth/base.py index 1882dcd..cd59ce1 100644 --- a/ytmusicapi/auth/oauth/base.py +++ b/ytmusicapi/auth/oauth/base.py @@ -1,8 +1,8 @@ -from typing import Optional, Any, Union, Dict +from typing import Optional, Any, Dict import time import json -from .models import BaseTokenDict, DefaultScope, Bearer, FullTokenDict +from .models import BaseTokenDict, DefaultScope, Bearer, RefreshableTokenDict class Credentials: @@ -13,7 +13,7 @@ class Credentials: def get_code(self) -> Dict: raise NotImplementedError() - def token_from_code(self, device_code: str) -> FullTokenDict: + def token_from_code(self, device_code: str) -> RefreshableTokenDict: raise NotImplementedError() def refresh_token(self, refresh_token: str) -> BaseTokenDict: @@ -21,16 +21,22 @@ class Credentials: class Token: - """ Base class representation of the YouTubeMusicAPI OAuth token """ + """ Base class representation of the YouTubeMusicAPI OAuth token. """ access_token: str refresh_token: str - expires_in: str - expires_at: str + expires_in: int + expires_at: int + is_expiring: bool - scope: Union[str, DefaultScope] - token_type: Union[str, Bearer] + scope: DefaultScope + token_type: Bearer - def as_dict(self): + def __repr__(self) -> str: + """ Readable version. """ + return f'{self.__class__.__name__}: {self.as_dict()}' + + def as_dict(self) -> RefreshableTokenDict: + """ Returns dictionary containing underlying token values. """ return { 'access_token': self.access_token, 'refresh_token': self.refresh_token, @@ -40,14 +46,17 @@ class Token: 'token_type': self.token_type } - def as_json(self): + def as_json(self) -> str: + # TODO: [PYDANTIC]: add a custom serializer return json.dumps(self.as_dict()) - def as_auth(self): + def as_auth(self) -> str: + """ Returns Authorization header ready str of token_type and access_token. """ return f'{self.token_type} {self.access_token}' class OAuthToken(Token): + """ Wrapper for an OAuth token implementing expiration methods. """ def __init__(self, access_token: str, @@ -56,40 +65,59 @@ class OAuthToken(Token): token_type: str, expires_at: Optional[int] = None, expires_in: Optional[int] = None, - **etc: Optional[Any]): + **_: Optional[Any]): + """ + + :param access_token: active oauth key + :param refresh_token: access_token's matching oauth refresh string + :param scope: most likely 'https://www.googleapis.com/auth/youtube' + :param token_type: commonly 'Bearer' + :param expires_at: Optional. Unix epoch (seconds) of access token expiration. + :param expires_in: Optional. Seconds till expiration, assumes/calculates epoch of init. + :param _: void excess kwargs + + """ + # match baseclass attribute/property format self._access_token = access_token self._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 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): + def access_token(self) -> str: return self._access_token @property - def refresh_token(self): + def refresh_token(self) -> str: return self._refresh_token @property - def token_type(self): + def token_type(self) -> Bearer: return self._token_type @property - def scope(self): + def scope(self) -> DefaultScope: return self._scope @property - def expires_at(self): + def expires_at(self) -> int: return self._expires_at @property - def expires_in(self): - return self.expires_at - time.time() + def expires_in(self) -> int: + return int(self.expires_at - time.time()) @property def is_expiring(self) -> bool: diff --git a/ytmusicapi/auth/oauth/credentials.py b/ytmusicapi/auth/oauth/credentials.py index 2d3e5b4..2afef4c 100644 --- a/ytmusicapi/auth/oauth/credentials.py +++ b/ytmusicapi/auth/oauth/credentials.py @@ -2,9 +2,8 @@ import webbrowser from typing import Dict, Optional import requests -from requests.structures import CaseInsensitiveDict -from .models import FullTokenDict, BaseTokenDict, CodeDict +from .models import RefreshableTokenDict, BaseTokenDict, AuthCodeDict from .base import OAuthToken, Credentials from .refreshing import RefreshingToken from .exceptions import BadOAuthClient, UnauthorizedOAuthClient @@ -14,23 +13,44 @@ from ytmusicapi.constants import (OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_CO class OAuthCredentials(Credentials): + """ + Class for handling OAuth credential retrieval and refreshing. + """ def __init__(self, - client_id: Optional[str] = OAUTH_CLIENT_ID, - client_secret: Optional[str] = OAUTH_CLIENT_SECRET, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, 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() + """ + :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) -> CodeDict: + def get_code(self) -> AuthCodeDict: + """ Method for obtaining a new user auth code. First step of token creation. """ code_response = self._send_request(OAUTH_CODE_URL, data={"scope": OAUTH_SCOPE}) 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: @@ -50,7 +70,8 @@ class OAuthCredentials(Credentials): ) return response - def token_from_code(self, device_code: str) -> FullTokenDict: + def token_from_code(self, device_code: str) -> RefreshableTokenDict: + """ Method for verifying user auth code and conversion into a FullTokenDict. """ response = self._send_request( OAUTH_TOKEN_URL, data={ @@ -64,19 +85,32 @@ class OAuthCredentials(Credentials): 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"]) - base_token = OAuthToken(**raw_token) - ref_token = RefreshingToken(base_token, credentials=self) + 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={ diff --git a/ytmusicapi/auth/oauth/models.py b/ytmusicapi/auth/oauth/models.py index d624566..7778bbf 100644 --- a/ytmusicapi/auth/oauth/models.py +++ b/ytmusicapi/auth/oauth/models.py @@ -2,28 +2,32 @@ from typing import Union, Literal, TypedDict -DefaultScope = Literal['https://www.googleapis.com/auth/youtube'] -Bearer = Literal['Bearer'] +# for static typechecking +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 - expires_in: int - scope: Union[str, DefaultScope] - token_type: Union[str, Bearer] + + 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 FullTokenDict(BaseTokenDict): +class RefreshableTokenDict(BaseTokenDict): """ Entire token. Including refresh. Obtained through token setup. """ - expires_at: int - refresh_token: str + + expires_at: int # UNIX epoch timestamp in seconds + refresh_token: str # str used to obtain new access token upon expiration -class CodeDict(TypedDict): +class AuthCodeDict(TypedDict): """ Keys for the json object obtained via code response during auth flow. """ - device_code: str - user_code: str - expires_in: int - interval: int - verification_url: str + + 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 index 0c02d99..82df8d1 100644 --- a/ytmusicapi/auth/oauth/refreshing.py +++ b/ytmusicapi/auth/oauth/refreshing.py @@ -1,15 +1,31 @@ -from typing import Optional, Any -import time +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) @@ -20,22 +36,32 @@ class RefreshingToken(Token): token: OAuthToken, credentials: Credentials, local_cache: Optional[str] = None): - self.token = token - self.credentials = credentials + """ + :param token: Underlying Token being maintained. + :param credentials: OAuth client being used for refreshing. + :param local_cache: Optional. Path to json file where token values are stored. + When provided, file contents is updated upon token refresh. + """ + + self.token: OAuthToken = token # internal token being used / refreshed / maintained + self.credentials = credentials # credentials used for access_token refreshing + + # protected/property attribute enables auto writing token + # values to new file location via setter self._local_cache = local_cache @property - def local_cache(self): + def local_cache(self) -> str | None: 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): + """ Update attribute and dump token to new path. """ self._local_cache = path self.store_token() @property - def access_token(self): + def access_token(self) -> str: if self.token.is_expiring: fresh = self.credentials.refresh_token(self.token.refresh_token) self.token.update(fresh) @@ -43,34 +69,48 @@ class RefreshingToken(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: + 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 refresh_token(self): + def refresh_token(self) -> str: + # pass underlying value return self.token.refresh_token @property def is_expiring(self) -> bool: + # Refreshing token never expires return False @property - def expires_at(self): + def expires_at(self) -> None: + # Refreshing token never expires return None @property - def expires_in(self): + def expires_in(self) -> None: + # Refreshing token never expires return None @property - def scope(self): + def scope(self) -> DefaultScope: + # pass underlying value return self.token.scope @property - def token_type(self): + def token_type(self) -> Bearer: + # pass underlying value return self.token.token_type - def as_dict(self): + def as_dict(self) -> RefreshableTokenDict: + # override base class method with call to underlying token's method return self.token.as_dict() diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index ff7b26e..6198054 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -31,10 +31,10 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin """ def __init__(self, - auth: Optional[str | dict] = None, + auth: Optional[str | Dict] = None, user: str = None, requests_session=True, - proxies: dict = None, + proxies: Dict = None, language: str = 'en', location: str = '', oauth_credentials: Optional[OAuthCredentials] = None): @@ -75,16 +75,24 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin :param oauth_credentials: Optional. Used to specify a different oauth client to be used for authentication flow. """ - self._base_headers = None - self._headers = None - self.auth = auth - self._input_dict = {} - self.is_alt_oauth = False - self.is_oauth_auth = False - self.is_browser_auth = False - self.is_custom_oauth = False - self._token = None - self.proxies = proxies + + 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 + + # (?) may be better implemented as an auth_type attribute with a literal/enum value (?) + self.is_alt_oauth = False # YTM instance is using a non-default OAuth client (id & secret) + self.is_oauth_auth = False # client auth via OAuth token refreshing + self.is_browser_auth = False # authorization via extracted browser headers, enables uploading capabilities + self.is_custom_oauth = False # allows fully formed OAuth headers to ignore browser auth refresh flow + + self._token: Token # OAuth credential handler + self.oauth_credentials: OAuthCredentials # Client used for OAuth refreshing + + self._session: requests.Session # request session for connection pooling + self.proxies: Dict = proxies # params for session modification if isinstance(requests_session, requests.Session): self._session = requests_session From a6ae5add7f052b59255dba1e50cadba8313897d3 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Thu, 28 Dec 2023 18:23:51 -0600 Subject: [PATCH 19/22] tests: further edits for clarity and oauth tests --- tests/README.rst | 20 ++++++++-- tests/test.cfg.example | 6 +-- tests/test.py | 86 +++++++++++++++++++++++++++++++----------- 3 files changed, 82 insertions(+), 30 deletions(-) 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 e0a9c90..c593ea8 100644 --- a/tests/test.cfg.example +++ b/tests/test.cfg.example @@ -3,10 +3,8 @@ 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] diff --git a/tests/test.py b/tests/test.py index 85c9186..99f6e79 100644 --- a/tests/test.py +++ b/tests/test.py @@ -24,14 +24,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(**{ - 'client_id': OAUTH_CLIENT_ID, - 'client_secret': OAUTH_CLIENT_SECRET -}) +alt_oauth_creds = OAuthCredentials(OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET) class TestYTMusic(unittest.TestCase): @@ -42,16 +46,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_alt_oauth = YTMusic(headers_browser, oauth_credentials=alt_oauth_creds) - 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()])): @@ -60,28 +64,64 @@ 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_000_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_alt_oauth(self): # ensure client works/ignores alt if browser credentials passed as auth self.assertFalse(self.yt_alt_oauth.is_alt_oauth) + with open(oauth_filepath, 'r') as f: + token_dict = json.load(f) # 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(token_dict, oauth_credentials=alt_oauth_creds) self.assertTrue(self.yt_alt_oauth.is_alt_oauth) ############### @@ -509,7 +549,7 @@ 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): playlist_id = self.yt_brand.create_playlist( From d05c011e420fb681a50af2e7025e85c5d66ae630 Mon Sep 17 00:00:00 2001 From: jcbirdwell Date: Thu, 28 Dec 2023 18:27:37 -0600 Subject: [PATCH 20/22] fix: not here not now --- ytmusicapi/auth/oauth/base.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ytmusicapi/auth/oauth/base.py b/ytmusicapi/auth/oauth/base.py index cd59ce1..751adcf 100644 --- a/ytmusicapi/auth/oauth/base.py +++ b/ytmusicapi/auth/oauth/base.py @@ -47,7 +47,6 @@ class Token: } def as_json(self) -> str: - # TODO: [PYDANTIC]: add a custom serializer return json.dumps(self.as_dict()) def as_auth(self) -> str: From 3abbbf820903ceaeedc9402986ac3d58840cacda Mon Sep 17 00:00:00 2001 From: sigma67 Date: Sun, 31 Dec 2023 10:43:26 +0100 Subject: [PATCH 21/22] fix review findings --- ytmusicapi/auth/headers.py | 1 - ytmusicapi/auth/oauth/base.py | 19 +++++++++++---- ytmusicapi/auth/oauth/models.py | 25 ++++++++++---------- ytmusicapi/auth/oauth/refreshing.py | 33 ++++---------------------- ytmusicapi/ytmusic.py | 36 +++++++++++------------------ 5 files changed, 45 insertions(+), 69 deletions(-) diff --git a/ytmusicapi/auth/headers.py b/ytmusicapi/auth/headers.py index 6831b8b..c3d8165 100644 --- a/ytmusicapi/auth/headers.py +++ b/ytmusicapi/auth/headers.py @@ -7,7 +7,6 @@ def load_headers_file(auth: str) -> Dict: if os.path.isfile(auth): with open(auth) as json_file: input_json = json.load(json_file) - input_json['filepath'] = auth else: input_json = json.loads(auth) return input_json diff --git a/ytmusicapi/auth/oauth/base.py b/ytmusicapi/auth/oauth/base.py index 751adcf..980be2a 100644 --- a/ytmusicapi/auth/oauth/base.py +++ b/ytmusicapi/auth/oauth/base.py @@ -1,7 +1,9 @@ -from typing import Optional, Any, Dict +from typing import Optional, Dict import time import json +from requests.structures import CaseInsensitiveDict + from .models import BaseTokenDict, DefaultScope, Bearer, RefreshableTokenDict @@ -63,8 +65,7 @@ class OAuthToken(Token): scope: str, token_type: str, expires_at: Optional[int] = None, - expires_in: Optional[int] = None, - **_: Optional[Any]): + expires_in: Optional[int] = None): """ :param access_token: active oauth key @@ -73,7 +74,6 @@ class OAuthToken(Token): :param token_type: commonly 'Bearer' :param expires_at: Optional. Unix epoch (seconds) of access token expiration. :param expires_in: Optional. Seconds till expiration, assumes/calculates epoch of init. - :param _: void excess kwargs """ # match baseclass attribute/property format @@ -85,6 +85,17 @@ class OAuthToken(Token): 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. diff --git a/ytmusicapi/auth/oauth/models.py b/ytmusicapi/auth/oauth/models.py index 7778bbf..d301602 100644 --- a/ytmusicapi/auth/oauth/models.py +++ b/ytmusicapi/auth/oauth/models.py @@ -1,8 +1,7 @@ -# stand-in classes for clarity until pydantic implementation +"""models for oauth authentication""" from typing import Union, Literal, TypedDict -# for static typechecking DefaultScope = Union[str, Literal['https://www.googleapis.com/auth/youtube']] Bearer = Union[str, Literal['Bearer']] @@ -10,24 +9,24 @@ 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' + 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 + 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 + 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 index 82df8d1..0d77252 100644 --- a/ytmusicapi/auth/oauth/refreshing.py +++ b/ytmusicapi/auth/oauth/refreshing.py @@ -43,11 +43,11 @@ class RefreshingToken(Token): 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 + 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 + #: protected/property attribute enables auto writing token + # values to new file location via setter self._local_cache = local_cache @property @@ -81,31 +81,6 @@ class RefreshingToken(Token): with open(file_path, encoding="utf8", mode='w') as file: json.dump(self.token.as_dict(), file, indent=True) - @property - def refresh_token(self) -> str: - # pass underlying value - return self.token.refresh_token - - @property - def is_expiring(self) -> bool: - # Refreshing token never expires - return False - - @property - def expires_at(self) -> None: - # Refreshing token never expires - return None - - @property - def expires_in(self) -> None: - # Refreshing token never expires - return None - - @property - def scope(self) -> DefaultScope: - # pass underlying value - return self.token.scope - @property def token_type(self) -> Bearer: # pass underlying value diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index 6198054..922cb2a 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -76,23 +76,23 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin used for authentication flow. """ - self._base_headers = None # for authless initializing requests during OAuth flow - self._headers = None # cache formed headers including auth + 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 = auth #: raw auth + self._input_dict = {} #: parsed auth arg value in dictionary format # (?) may be better implemented as an auth_type attribute with a literal/enum value (?) - self.is_alt_oauth = False # YTM instance is using a non-default OAuth client (id & secret) - self.is_oauth_auth = False # client auth via OAuth token refreshing - self.is_browser_auth = False # authorization via extracted browser headers, enables uploading capabilities - self.is_custom_oauth = False # allows fully formed OAuth headers to ignore browser auth refresh flow + self.is_alt_oauth = False #: YTM instance is using a non-default OAuth client (id & secret) + self.is_oauth_auth = False #: client auth via OAuth token refreshing + self.is_browser_auth = False #: authorization via extracted browser headers, enables uploading capabilities + self.is_custom_oauth = False #: allows fully formed OAuth headers to ignore browser auth refresh flow - self._token: Token # OAuth credential handler - self.oauth_credentials: OAuthCredentials # Client used for OAuth refreshing + self._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 + 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 @@ -103,10 +103,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin else: # Use the Requests API module as a "session". self._session = requests.api - if oauth_credentials is not None: - self.oauth_credentials = oauth_credentials - else: - self.oauth_credentials = OAuthCredentials() + self.oauth_credentials = oauth_credentials if oauth_credentials is not None else 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 @@ -119,18 +116,13 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin else: self._input_dict = self.auth - # check if OAuth by passing values as kwargs to OAuthToken init using - # KeyError from incompatible input_dict as False - try: + if OAuthToken.is_oauth(self._input_dict): base_token = OAuthToken(**self._input_dict) self._token = RefreshingToken(base_token, self.oauth_credentials, self._input_dict.get('filepath')) self.is_oauth_auth = True self.is_alt_oauth = oauth_credentials is not None - except TypeError: - pass - # prepare context self.context = initialize_context() From c848e50b3bdb8d585880cb83abb163924d5f3a07 Mon Sep 17 00:00:00 2001 From: sigma67 Date: Sun, 31 Dec 2023 11:18:39 +0100 Subject: [PATCH 22/22] refactor authtypes --- tests/test.py | 9 +++++---- ytmusicapi/auth/headers.py | 12 ------------ ytmusicapi/auth/types.py | 25 ++++++++++++++++++++++++ ytmusicapi/mixins/uploads.py | 3 ++- ytmusicapi/ytmusic.py | 37 ++++++++++++++++++------------------ 5 files changed, 50 insertions(+), 36 deletions(-) delete mode 100644 ytmusicapi/auth/headers.py create mode 100644 ytmusicapi/auth/types.py diff --git a/tests/test.py b/tests/test.py index 99f6e79..d43e100 100644 --- a/tests/test.py +++ b/tests/test.py @@ -8,6 +8,7 @@ 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, OAuthCredentials # noqa: E402 from ytmusicapi.constants import OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET @@ -82,7 +83,7 @@ class TestYTMusic(unittest.TestCase): # OAUTH ############### # 000 so test is run first and fresh token is available to others - def test_000_oauth_tokens(self): + def test_oauth_tokens(self): # ensure instance initialized token self.assertIsNotNone(self.yt_oauth._token) @@ -115,14 +116,14 @@ class TestYTMusic(unittest.TestCase): # ensure token is updating local file self.assertNotEqual(first_json, second_json) - def test_alt_oauth(self): + def test_oauth_custom_client(self): # ensure client works/ignores alt if browser credentials passed as auth - self.assertFalse(self.yt_alt_oauth.is_alt_oauth) + 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.assertTrue(self.yt_alt_oauth.is_alt_oauth) + self.assertEqual(self.yt_alt_oauth.auth_type, AuthType.OAUTH_CUSTOM_CLIENT) ############### # BROWSING diff --git a/ytmusicapi/auth/headers.py b/ytmusicapi/auth/headers.py deleted file mode 100644 index c3d8165..0000000 --- a/ytmusicapi/auth/headers.py +++ /dev/null @@ -1,12 +0,0 @@ -import json -import os -from typing import Dict - - -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 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/uploads.py b/ytmusicapi/mixins/uploads.py index e63bb19..6465a9b 100644 --- a/ytmusicapi/mixins/uploads.py +++ b/ytmusicapi/mixins/uploads.py @@ -10,6 +10,7 @@ from ytmusicapi.continuations import get_continuations from ytmusicapi.parsers.library import parse_library_albums, parse_library_artists, get_library_contents from ytmusicapi.parsers.albums import parse_album_header from ytmusicapi.parsers.uploads import parse_uploaded_items +from ..auth.types import AuthType class UploadsMixin: @@ -194,7 +195,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/ytmusic.py b/ytmusicapi/ytmusic.py index 922cb2a..75bf940 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -17,9 +17,9 @@ from ytmusicapi.mixins.library import LibraryMixin from ytmusicapi.mixins.playlists import PlaylistsMixin from ytmusicapi.mixins.uploads import UploadsMixin -from .auth.headers import load_headers_file 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, @@ -82,11 +82,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin self.auth = auth #: raw auth self._input_dict = {} #: parsed auth arg value in dictionary format - # (?) may be better implemented as an auth_type attribute with a literal/enum value (?) - self.is_alt_oauth = False #: YTM instance is using a non-default OAuth client (id & secret) - self.is_oauth_auth = False #: client auth via OAuth token refreshing - self.is_browser_auth = False #: authorization via extracted browser headers, enables uploading capabilities - self.is_custom_oauth = False #: allows fully formed OAuth headers to ignore browser auth refresh flow + self.auth_type: AuthType = AuthType.UNAUTHORIZED self._token: Token #: OAuth credential handler self.oauth_credentials: OAuthCredentials #: Client used for OAuth refreshing @@ -103,14 +99,19 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin else: # Use the Requests API module as a "session". self._session = requests.api - self.oauth_credentials = oauth_credentials if oauth_credentials is not None else 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: + self.oauth_credentials = oauth_credentials if oauth_credentials is not None else OAuthCredentials() + auth_filepath = None if isinstance(self.auth, str): - input_json = load_headers_file(self.auth) + 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) else: @@ -118,10 +119,8 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin if OAuthToken.is_oauth(self._input_dict): base_token = OAuthToken(**self._input_dict) - self._token = RefreshingToken(base_token, self.oauth_credentials, - self._input_dict.get('filepath')) - self.is_oauth_auth = True - self.is_alt_oauth = oauth_credentials is not None + 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() @@ -152,13 +151,13 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin auth_headers = self._input_dict.get("authorization") if auth_headers: if "SAPISIDHASH" in auth_headers: - self.is_browser_auth = True + self.auth_type = AuthType.BROWSER elif auth_headers.startswith('Bearer'): - self.is_custom_oauth = True + self.auth_type = AuthType.OAUTH_CUSTOM_FULL # sapsid, origin, and params all set once during init self.params = YTM_PARAMS - if self.is_browser_auth: + if self.auth_type == AuthType.BROWSER: self.params += YTM_PARAMS_KEY try: cookie = self.base_headers.get('cookie') @@ -170,7 +169,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin @property def base_headers(self): if not self._base_headers: - if self.is_browser_auth or self.is_custom_oauth: + if self.auth_type == AuthType.BROWSER or self.auth_type == AuthType.OAUTH_CUSTOM_FULL: self._base_headers = self._input_dict else: self._base_headers = { @@ -191,10 +190,10 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin self._headers = self.base_headers # keys updated each use, custom oauth implementations left untouched - if self.is_browser_auth: + if self.auth_type == AuthType.BROWSER: self._headers["authorization"] = get_authorization(self.sapisid + ' ' + self.origin) - elif self.is_oauth_auth: + 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()))