From 1a78e615da7febe0a12b6d0c0bbb542c222f8c51 Mon Sep 17 00:00:00 2001 From: sigma67 Date: Wed, 5 Apr 2023 21:25:23 +0200 Subject: [PATCH] streamline oauth code and fix refresh_token bug --- ytmusicapi/auth/headers.py | 26 ++++++++++---------------- ytmusicapi/auth/oauth.py | 4 ++-- 2 files changed, 12 insertions(+), 18 deletions(-) diff --git a/ytmusicapi/auth/headers.py b/ytmusicapi/auth/headers.py index 39feff3..5a4a2fa 100644 --- a/ytmusicapi/auth/headers.py +++ b/ytmusicapi/auth/headers.py @@ -14,23 +14,17 @@ def prepare_headers(session: requests.Session, auth: Optional[str] = None) -> Dict: headers = {} if auth: - try: - if os.path.isfile(auth): - with open(auth) as json_file: - input_json = json.load(json_file) - else: - input_json = json.loads(auth) + if os.path.isfile(auth): + with open(auth) as json_file: + input_json = json.load(json_file) + else: + input_json = json.loads(auth) - if "oauth.json" in auth: - oauth = YTMusicOAuth(session, proxies) - headers = oauth.load_headers(input_json, auth) - else: - headers = CaseInsensitiveDict(input_json) - - except Exception as e: - print( - "Failed loading provided credentials. Make sure to provide a string or a file path. " - "Reason: " + str(e)) + if "oauth.json" in auth: + oauth = YTMusicOAuth(session, proxies) + headers = oauth.load_headers(input_json, auth) + else: + headers = CaseInsensitiveDict(input_json) else: # no authentication headers = initialize_headers() diff --git a/ytmusicapi/auth/oauth.py b/ytmusicapi/auth/oauth.py index b25c09f..c866a13 100644 --- a/ytmusicapi/auth/oauth.py +++ b/ytmusicapi/auth/oauth.py @@ -50,7 +50,7 @@ class YTMusicOAuth: def dump_token(token, filepath): token["expires_at"] = int(time.time()) + int(token["expires_in"]) with open(filepath, encoding="utf8", mode="w") as file: - json.dump(token, file) + json.dump(token, file, indent=True) def setup(self, filepath: Optional[str] = None) -> Dict: code = self.get_code() @@ -63,7 +63,7 @@ class YTMusicOAuth: def load_headers(self, token: Dict, filepath: Optional[str] = None): headers = initialize_headers() if time.time() > token["expires_at"] - 3600: - token = self.refresh_token(token["refresh_token"]) + 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"