new file: Dockerfile new file: app.py new file: requirements.txt new file: start.bat new file: templates/login.html new file: templates/playlists.html new file: templates/quiz.html
73 lines
2.1 KiB
Python
73 lines
2.1 KiB
Python
from flask import Flask, redirect, request, session, url_for, render_template
|
|
import os
|
|
from dotenv import load_dotenv
|
|
import spotipy
|
|
from spotipy.oauth2 import SpotifyOAuth
|
|
import random
|
|
|
|
load_dotenv()
|
|
|
|
app = Flask(__name__)
|
|
app.secret_key = os.getenv("SECRET_KEY")
|
|
|
|
SCOPE = "user-library-read playlist-read-private"
|
|
|
|
def get_spotify_client():
|
|
return spotipy.Spotify(auth_manager=SpotifyOAuth(
|
|
client_id=os.getenv("SPOTIPY_CLIENT_ID"),
|
|
client_secret=os.getenv("SPOTIPY_CLIENT_SECRET"),
|
|
redirect_uri=os.getenv("SPOTIPY_REDIRECT_URI"),
|
|
scope=SCOPE,
|
|
cache_path=".cache"
|
|
))
|
|
|
|
@app.route("/")
|
|
def home():
|
|
return render_template("login.html")
|
|
|
|
@app.route("/login")
|
|
def login():
|
|
sp_oauth = SpotifyOAuth(
|
|
client_id=os.getenv("SPOTIPY_CLIENT_ID"),
|
|
client_secret=os.getenv("SPOTIPY_CLIENT_SECRET"),
|
|
redirect_uri=os.getenv("SPOTIPY_REDIRECT_URI"),
|
|
scope=SCOPE
|
|
)
|
|
auth_url = sp_oauth.get_authorize_url()
|
|
return redirect(auth_url)
|
|
|
|
@app.route("/callback")
|
|
def callback():
|
|
sp_oauth = SpotifyOAuth(
|
|
client_id=os.getenv("SPOTIPY_CLIENT_ID"),
|
|
client_secret=os.getenv("SPOTIPY_CLIENT_SECRET"),
|
|
redirect_uri=os.getenv("SPOTIPY_REDIRECT_URI"),
|
|
scope=SCOPE
|
|
)
|
|
session.clear()
|
|
code = request.args.get('code')
|
|
token_info = sp_oauth.get_access_token(code)
|
|
session["token_info"] = token_info
|
|
return redirect("/playlists")
|
|
|
|
@app.route("/playlists")
|
|
def playlists():
|
|
sp = get_spotify_client()
|
|
playlists = sp.current_user_playlists()["items"]
|
|
return render_template("playlists.html", playlists=playlists)
|
|
|
|
@app.route("/quiz/<playlist_id>")
|
|
def quiz(playlist_id):
|
|
sp = get_spotify_client()
|
|
items = sp.playlist_items(playlist_id, additional_types=["track"])["items"]
|
|
|
|
tracks = [item["track"] for item in items if item["track"]["preview_url"]]
|
|
if not tracks:
|
|
return "Keine Tracks mit Vorschau verfügbar!"
|
|
|
|
track = random.choice(tracks)
|
|
return render_template("quiz.html", track=track)
|
|
|
|
if __name__ == "__main__":
|
|
app.run(debug=True)
|