From da9042d51855db87ae93da0ec5b25268430363f8 Mon Sep 17 00:00:00 2001 From: IlyaShurupov Date: Sun, 7 Jul 2024 15:28:50 +0300 Subject: [PATCH] tmp --- spotifyAuth.py | 154 ++++++++++++++++++++++++++++++++++++++++--------- token | 1 + 2 files changed, 127 insertions(+), 28 deletions(-) create mode 100644 token diff --git a/spotifyAuth.py b/spotifyAuth.py index b87f5da..e1ee12c 100644 --- a/spotifyAuth.py +++ b/spotifyAuth.py @@ -1,47 +1,145 @@ import requests import base64 -# Method 2: Using regular expressions - import re +import webbrowser +from http.server import BaseHTTPRequestHandler, HTTPServer +import urllib.parse +import threading +import time + +CODE = '' +TOKEN = '' + +# Define the HTTP request handler class +class RequestHandler(BaseHTTPRequestHandler): + + # Handle GET requests + def do_GET(self): + global CODE + + # Parse the URL and query parameters + parsed_url = urllib.parse.urlparse(self.path) + query_params = urllib.parse.parse_qs(parsed_url.query) + + # Extract the authorization code from query parameters + if 'code' in query_params: + authorization_code = query_params['code'][0] + print(f"Authorization Code: {authorization_code}") + + # You can now proceed with exchanging this authorization code for an access token + # Example: Call a function to exchange code for access token + #with open('code', 'w') as file: + # file.write(authorization_code) + + # code = authorization_code + # print("Shutting down the callback server") + + # Send response back to the browser + self.send_response(200) + self.send_header('Content-type', 'text/html') + self.end_headers() + self.wfile.write(b'Authorization code received. You can close this window.') + + print("\n\nCode recieved!!!\n") + CODE = authorization_code + # self.server.shutdown() + + else: + # Handle cases where code is not found + self.send_response(400) + self.send_header('Content-type', 'text/html') + self.end_headers() + self.wfile.write(b'Authorization code not found.') + + +# Set up and start the HTTP server +def startLoginCallbackServer(): + server_address = ('localhost', 8888) # Use any free port you prefer + httpd = HTTPServer(server_address, RequestHandler) + print('Starting HTTP server on port 8080...') + httpd.serve_forever() -# Your Spotify app credentials client_id = '***REDACTED***' client_secret = '***REDACTED***' -# Encode client_id and client_secret in Base64 -client_creds = f"{client_id}:{client_secret}" -client_creds_b64 = base64.b64encode(client_creds.encode()) -# Spotify token endpoint -token_url = 'https://accounts.spotify.com/api/token' +def openLoginPage(): + authorize_url = 'https://accounts.spotify.com/authorize' -# Parameters for requesting access token -token_data = { - "grant_type": "client_credentials", - "client_secret": client_secret, - "client_id": client_id, - "scope": "user-read-private, playlist-read-private, playlist-read-collaborative", -} + params = { + 'client_id': client_id, + 'response_type': 'code', + 'redirect_uri': 'http://localhost:8888', + 'scope': 'user-read-private user-read-email', # Add scopes based on your needs + } -# HTTP headers including encoded client_id and client_secret -token_headers = { + auth_url = f"{authorize_url}?client_id={params['client_id']}&response_type={params['response_type']}&redirect_uri={params['redirect_uri']}&scope={params['scope']}" + webbrowser.open(auth_url) + + +def authenticateWepAPIAfterLogin(code): + global TOKEN + + client_creds = f"{client_id}:{client_secret}" + client_creds_b64 = base64.b64encode(client_creds.encode()) + + token_url = 'https://accounts.spotify.com/api/token' + + token_data = { + "grant_type": "authorization_code", + "client_secret": client_secret, + "client_id": client_id, + "code": code, + 'redirect_uri': 'http://localhost:8888', + "scope": "user-read-private, playlist-read-private, playlist-read-collaborative", + } + + token_headers = { # "Authorization": f"Basic {client_creds_b64.decode()}" - "Content-Type" : "application/x-www-form-urlencoded" -} + "Content-Type" : "application/x-www-form-urlencoded" + } -# Requesting access token -token_response = requests.post(token_url, data=token_data, headers=token_headers) + print("\nAuthenticating WEB API\n") + + token_response = requests.post(token_url, data=token_data) + + if token_response.status_code not in range(200, 299): + print(f"Failed to retrieve access token: {token_response.status_code}") + print(token_response.json()) + + token = token_response.json()['access_token'] + token_type = token_response.json()['token_type'] + token_time = token_response.json()['expires_in'] -# Handling response -if token_response.status_code not in range(200, 299): - print(f"Failed to retrieve access token: {token_response.status_code}") print(token_response.json()) -token = token_response.json()['access_token'] -token_type = token_response.json()['token_type'] -token_time = token_response.json()['expires_in'] + TOKEN = token + + print(f"\nGot the token! - {TOKEN} \n") + + + +def main(): + thread1 = threading.Thread(target=startLoginCallbackServer) + thread1.start() + + time.sleep(3) + + openLoginPage() + + time.sleep(3) + + print("Got the code ", CODE) + + authenticateWepAPIAfterLogin(CODE) + + with open('token', 'w') as file: + file.write(TOKEN) + + thread1.stop() + if __name__ == "__main__": - print(token_response.json()) + main() diff --git a/token b/token new file mode 100644 index 0000000..355f6ff --- /dev/null +++ b/token @@ -0,0 +1 @@ +BQCZr9A0eTYv5paloVLjSQGRQtkYatgH0tVWewIn-lMXh5dRUGK7xWqwHjgmLD9Kf3DDsAo2t5bmQ7g_W6EyFSMz2Tu4ZuMXPk3p0wrwvfnWyNi6W3uKELvDaMSS1hHDKe651RTUpApom6FUnoGnQ-SRYDZzoH9FwR0nOeMJgMqzpLtR0bXx3rkS3z_AeSmXIGjxBK7u7uWk3Iqabp2CGA \ No newline at end of file