From 0fc5417ab967400451bcc8365f3912971f1111df Mon Sep 17 00:00:00 2001 From: sigma67 Date: Wed, 17 May 2023 21:01:07 +0200 Subject: [PATCH] open browser on ytmusic oauth call (closes #384) --- ytmusicapi/auth/oauth.py | 5 ++++- ytmusicapi/setup.py | 12 ++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/ytmusicapi/auth/oauth.py b/ytmusicapi/auth/oauth.py index 6750ffe..5f687fa 100644 --- a/ytmusicapi/auth/oauth.py +++ b/ytmusicapi/auth/oauth.py @@ -1,5 +1,6 @@ import json import time +import webbrowser from typing import Dict, Optional import requests @@ -74,9 +75,11 @@ class YTMusicOAuth: with open(filepath, encoding="utf8", mode="w") as file: json.dump(token, file, indent=True) - def setup(self, filepath: Optional[str] = None) -> Dict: + def setup(self, filepath: Optional[str] = None, open_browser: bool = False) -> Dict: code = self.get_code() url = f"{code['verification_url']}?user_code={code['user_code']}" + if open_browser: + webbrowser.open(url) input(f"Go to {url}, finish the login flow and press Enter when done, Ctrl-C to abort") token = self.get_token_from_code(code["device_code"]) self.dump_token(token, filepath) diff --git a/ytmusicapi/setup.py b/ytmusicapi/setup.py index cad60ad..7a0edb5 100644 --- a/ytmusicapi/setup.py +++ b/ytmusicapi/setup.py @@ -24,7 +24,8 @@ def setup(filepath: str = None, headers_raw: str = None) -> Dict: def setup_oauth(filepath: str = None, session: requests.Session = None, - proxies: dict = None) -> Dict: + proxies: dict = None, + open_browser: bool = False) -> Dict: """ Starts oauth flow from the terminal and returns a string that can be passed to YTMusic() @@ -32,12 +33,13 @@ def setup_oauth(filepath: str = None, :param session: Session to use for authentication :param proxies: Proxies to use for authentication :param filepath: Optional filepath to store headers to. + :param open_browser: If True, open the default browser with the setup link :return: configuration headers string """ if not session: session = requests.Session() - return YTMusicOAuth(session, proxies).setup(filepath) + return YTMusicOAuth(session, proxies).setup(filepath, open_browser) def parse_args(args): @@ -54,5 +56,7 @@ def main(): args = parse_args(sys.argv[1:]) filename = args.file.as_posix() if args.file else f"{args.setup_type}.json" print(f"Creating {filename} with your authentication credentials...") - func = setup_oauth if args.setup_type == "oauth" else setup - return func(filename) + if args.setup_type == "oauth": + return setup_oauth(filename, open_browser=True) + else: + return setup(filename)