84 lines
2.4 KiB
Python
84 lines
2.4 KiB
Python
__version__ = "pre-dev"
|
|
__all__ = ["quizify"]
|
|
__author__ = "SimolZimol"
|
|
|
|
from flask import Flask, redirect, request, session, url_for, render_template
|
|
import os
|
|
import spotipy
|
|
from spotipy.oauth2 import SpotifyOAuth
|
|
import random
|
|
|
|
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)
|
|
|
|
@app.route('/logout')
|
|
def logout():
|
|
session.pop('user', None)
|
|
return redirect(url_for('index'))
|
|
|
|
@app.route('/')
|
|
def index():
|
|
user = session.get('user') # Benutzerinfos aus der Session holen, falls vorhanden
|
|
return render_template('index.html', user=user)
|
|
|
|
if __name__ == "__main__":
|
|
app.run(host="0.0.0.0", port=5000, debug=True)
|