tmp
This commit is contained in:
parent
c690162983
commit
7df0c0a0ff
49 changed files with 1439861 additions and 169 deletions
179
spotifyAuth.py
179
spotifyAuth.py
|
|
@ -1,88 +1,31 @@
|
|||
import requests
|
||||
import base64
|
||||
import re
|
||||
|
||||
import requests
|
||||
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'<html><body>Authorization code received. You can close this window.</body></html>')
|
||||
|
||||
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'<html><body>Authorization code not found.</body></html>')
|
||||
|
||||
|
||||
# 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()
|
||||
|
||||
import os.path
|
||||
|
||||
client_id = '***REDACTED***'
|
||||
client_secret = '***REDACTED***'
|
||||
client_secret = None
|
||||
token = None
|
||||
|
||||
|
||||
def openLoginPage():
|
||||
authorize_url = 'https://accounts.spotify.com/authorize'
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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 resolve_client_secret():
|
||||
global client_secret
|
||||
if os.path.exists('secret'):
|
||||
with open('secret', 'r') as file:
|
||||
client_secret = file.readline().strip()
|
||||
else:
|
||||
client_secret = input("Enter the application secret: ")
|
||||
with open('secret', 'w') as file:
|
||||
file.write(client_secret)
|
||||
|
||||
|
||||
def authenticateWepAPIAfterLogin(code):
|
||||
global TOKEN
|
||||
|
||||
client_creds = f"{client_id}:{client_secret}"
|
||||
client_creds_b64 = base64.b64encode(client_creds.encode())
|
||||
def retrieve_web_api_token(authorization_code):
|
||||
global token
|
||||
|
||||
token_url = 'https://accounts.spotify.com/api/token'
|
||||
|
||||
|
|
@ -90,56 +33,90 @@ def authenticateWepAPIAfterLogin(code):
|
|||
"grant_type": "authorization_code",
|
||||
"client_secret": client_secret,
|
||||
"client_id": client_id,
|
||||
"code": code,
|
||||
"code": authorization_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"
|
||||
}
|
||||
|
||||
print("\nAuthenticating WEB API\n")
|
||||
|
||||
token_response = requests.post(token_url, data=token_data)
|
||||
auth_string = f'{client_id}:{client_secret}'
|
||||
b64_auth_string = base64.b64encode(auth_string.encode()).decode()
|
||||
|
||||
# Define the headers
|
||||
headers = {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Authorization': f'Basic {b64_auth_string}'
|
||||
}
|
||||
|
||||
token_response = requests.post(token_url, data=token_data, headers=headers)
|
||||
|
||||
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())
|
||||
raise ValueError
|
||||
|
||||
token = token_response.json()['access_token']
|
||||
token_type = token_response.json()['token_type']
|
||||
token_time = token_response.json()['expires_in']
|
||||
|
||||
print(token_response.json())
|
||||
|
||||
TOKEN = token
|
||||
|
||||
print(f"\nGot the token! - {TOKEN} \n")
|
||||
|
||||
|
||||
class RequestHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
|
||||
def main():
|
||||
thread1 = threading.Thread(target=startLoginCallbackServer)
|
||||
thread1.start()
|
||||
parsed_url = urllib.parse.urlparse(self.path)
|
||||
query_params = urllib.parse.parse_qs(parsed_url.query)
|
||||
|
||||
if 'code' in query_params:
|
||||
authorization_code = query_params['code'][0]
|
||||
|
||||
time.sleep(3)
|
||||
self.send_response(200)
|
||||
self.send_header('Content-type', 'text/html')
|
||||
self.end_headers()
|
||||
self.wfile.write(b'<html><body>Authorization code received. You can close this window.</body></html>')
|
||||
|
||||
openLoginPage()
|
||||
retrieve_web_api_token(authorization_code)
|
||||
|
||||
time.sleep(3)
|
||||
threading.Thread(target=self.server.shutdown).start()
|
||||
|
||||
print("Got the code ", CODE)
|
||||
else:
|
||||
self.send_response(400)
|
||||
self.send_header('Content-type', 'text/html')
|
||||
self.end_headers()
|
||||
self.wfile.write(b'<html><body>Authorization code not found.</body></html>')
|
||||
|
||||
authenticateWepAPIAfterLogin(CODE)
|
||||
|
||||
with open('token', 'w') as file:
|
||||
file.write(TOKEN)
|
||||
def run_redirect_server():
|
||||
httpd = HTTPServer(('localhost', 8888), RequestHandler)
|
||||
print('Starting HTTP redirection server')
|
||||
httpd.serve_forever()
|
||||
|
||||
thread1.stop()
|
||||
|
||||
def open_authenticate_page():
|
||||
authorize_url = 'https://accounts.spotify.com/authorize'
|
||||
|
||||
params = {
|
||||
'client_id': client_id,
|
||||
'response_type': 'code',
|
||||
'redirect_uri': 'http://localhost:8888',
|
||||
"scope": "user-top-read playlist-read-collaborative user-read-email user-library-read user-read-private playlist-read-private",
|
||||
}
|
||||
|
||||
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 authenticate():
|
||||
resolve_client_secret()
|
||||
|
||||
redirect_server = threading.Thread(target=run_redirect_server)
|
||||
redirect_server.start()
|
||||
|
||||
time.sleep(1)
|
||||
open_authenticate_page()
|
||||
|
||||
redirect_server.join()
|
||||
|
||||
return token
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
authenticate()
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue