Merge remote-tracking branch 'Quizifiy/main'

This commit is contained in:
2025-09-20 22:19:34 +02:00
11 changed files with 1463 additions and 117 deletions

View File

@@ -7,11 +7,13 @@ Quizify is a music quiz that uses your Spotify playlists. Guess the artist, titl
- Login with Spotify
- Select your own playlists
- Multiple game modes: Guess artist, title, or year
- **Singleplayer and Local Multiplayer** (up to 4 players, each with their own score)
- Adjustable play duration and random start position for each song
- Spotify Web Playback (play songs directly in the browser)
- No song repeats until all have been played
- Smart search and answer evaluation (ignores bracket additions, apostrophes, etc.)
- Multilingual: All texts are loaded from language files, language is set via `.env`
- Invite/Referral link system for easy sharing
- Dockerfile included ready for deployment with [Coolify](https://coolify.io/) or any Docker-compatible platform
## Requirements
@@ -73,6 +75,8 @@ See `.env.example` for the required variables.
- The Spotify Redirect URI must exactly match `SPOTIPY_REDIRECT_URI` in the Spotify Developer Console.
- All texts are loaded from language files in the `locales` folder. Set the language via the `LANG` variable in your `.env` (e.g., `LANG=en-EN` or `LANG=de-DE`).
- You can set the play duration and start position for each song in the quiz interface.
- **Local Multiplayer:** After selecting "Local Multiplayer", you can enter up to 4 player names. Each player takes turns and has their own score.
- **Referral/Invite Link:** Generate a time-limited invite link to let friends join your quiz session (each with their own Spotify account).
## License

97
app.py
View File

@@ -10,6 +10,9 @@ import random
from difflib import SequenceMatcher
import re
import json
import unicodedata
import secrets
from datetime import datetime, timedelta
app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY")
@@ -34,15 +37,13 @@ def get_translations():
def get_spotify_client():
token_info = session.get("token_info", None)
if not token_info:
# Kein Token, redirect handled elsewhere
return None
# Prüfen, ob Token abgelaufen ist
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,
cache_path=".cache"
cache_path=None # <--- wichtig!
)
if sp_oauth.is_token_expired(token_info):
token_info = sp_oauth.refresh_access_token(token_info['refresh_token'])
@@ -53,13 +54,20 @@ def similarity(a, b):
return SequenceMatcher(None, a.lower(), b.lower()).ratio()
def clean_title(title):
# Unicode-Normalisierung (z.B. é -> e)
title = unicodedata.normalize('NFKD', title)
title = "".join([c for c in title if not unicodedata.combining(c)])
# Entfernt alles in () oder []
title = re.sub(r"(\s*[\(\[][^)\]]*[\)\]])", "", title)
# Vereinheitliche Apostrophen und Anführungszeichen
title = title.replace("", "'").replace("", "'").replace("`", "'")
title = title.replace('"', '').replace("", '').replace("", '').replace("", '')
title = title.replace("'", "") # Optional: alle Apostrophen entfernen
return title.strip()
title = title.replace("'", "")
# Entferne alle nicht-alphanumerischen Zeichen (außer Leerzeichen)
title = re.sub(r"[^a-zA-Z0-9äöüÄÖÜß ]", "", title)
# Mehrfache Leerzeichen zu einem
title = re.sub(r"\s+", " ", title)
return title.strip().lower()
def get_all_playlist_tracks(sp, playlist_id):
tracks = []
@@ -109,17 +117,28 @@ def callback():
user = sp.current_user()
session["user"] = user
return redirect("/playlists")
# Setze ein 30-Tage-Cookie mit Userdaten (ohne Token!)
resp = redirect("/playlists")
user_cookie = json.dumps({
"id": user.get("id"),
"display_name": user.get("display_name"),
"email": user.get("email"),
"images": user.get("images"),
})
resp.set_cookie("quizify_user", user_cookie, max_age=60*60*24*30, httponly=True, samesite="Lax")
return resp
@app.route("/playlists")
def playlists():
sp = get_spotify_client()
playlists = sp.current_user_playlists()["items"]
return render_template("playlists.html", playlists=playlists, translations=get_translations())
user = get_user_from_cookie()
return render_template("playlists.html", playlists=playlists, translations=get_translations(), user=user)
@app.route("/quiz/<playlist_id>")
def quiz(playlist_id):
game_mode = request.args.get('mode', 'artist')
is_multiplayer = request.args.get('local_multiplayer') == '1'
sp = get_spotify_client()
tracks = get_all_playlist_tracks(sp, playlist_id)
@@ -161,8 +180,10 @@ def quiz(playlist_id):
}
all_tracks.append(track_info)
user = get_user_from_cookie()
template = "quiz_multiplayer.html" if is_multiplayer else "quiz_single.html"
return render_template(
"quiz.html",
template,
track=track,
access_token=access_token,
playlist_id=playlist_id,
@@ -172,7 +193,8 @@ def quiz(playlist_id):
total_questions=len(tracks),
score=score,
answered=answered,
translations=get_translations()
translations=get_translations(),
user=user
)
@app.route("/search_track", methods=["POST"])
@@ -215,7 +237,8 @@ def check_answer():
game_mode = data.get('game_mode', 'artist')
playlist_id = data.get('playlist_id')
if game_mode == 'title':
# Immer clean_title für title und artist
if game_mode in ['title', 'artist']:
guess = clean_title(guess)
correct_answer = clean_title(correct_answer)
@@ -279,12 +302,9 @@ def toggle_playback():
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('home'))
@app.route('/')
def index():
user = session.get('user') # Benutzerinfos aus der Session holen, falls vorhanden
return render_template('index.html', user=user, translations=get_translations())
resp = redirect(url_for('home'))
resp.set_cookie("quizify_user", "", expires=0)
return resp
@app.route("/reset_quiz/<playlist_id>")
def reset_quiz(playlist_id):
@@ -295,5 +315,50 @@ def reset_quiz(playlist_id):
return redirect(url_for('quiz', playlist_id=playlist_id, mode=next_mode))
return redirect(url_for('playlists'))
@app.route("/gamemodes/<playlist_id>")
def gamemodes(playlist_id):
return render_template("gamemodes.html", playlist_id=playlist_id, translations=get_translations())
invites = {} # {token: expiry_datetime}
@app.route("/invite")
def invite():
duration = int(request.args.get("duration", 60)) # Minuten
token = secrets.token_urlsafe(16)
expires = datetime.utcnow() + timedelta(minutes=duration)
invites[token] = expires
invite_link = url_for('guest_join', token=token, _external=True)
# Gib nur den Link als Klartext zurück!
return invite_link
@app.route("/invite/<token>")
def guest_join(token):
expires = invites.get(token)
if not expires or expires < datetime.utcnow():
return "Invite link expired or invalid.", 403
# Setze ein Cookie, damit der Gast als eingeladener User erkannt wird (optional)
resp = redirect(url_for('login'))
resp.set_cookie("guest_token", token, max_age=60*60) # 1 Stunde gültig
return resp
def get_user_from_cookie():
user_cookie = request.cookies.get("quizify_user")
if user_cookie:
try:
return json.loads(user_cookie)
except Exception:
return None
return None
@app.route("/playerselect/<playlist_id>")
def playerselect(playlist_id):
game_mode = request.args.get('mode', 'artist')
return render_template(
"playerselect.html",
playlist_id=playlist_id,
game_mode=game_mode,
translations=get_translations()
)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)

View File

@@ -37,5 +37,23 @@
"album": "Album",
"year": "Jahr",
"open_on_spotify": "Auf Spotify öffnen",
"logout": "Abmelden"
"logout": "Abmelden",
"custom": "Anpassbar",
"quiz_mode": "Quiz-Modus",
"quiz_mode_desc": "Errate Künstler, Titel oder Jahr. Klassisches Musik-Quiz.",
"invite_guest": "Gast einladen",
"invite_duration": "Link gültig für (Minuten):",
"generate_link": "Link generieren",
"invite_link": "Einladungslink:",
"copy_link": "Link kopieren",
"copied": "Kopiert!",
"referral_link": "Einladungslink",
"referral_duration": "Link gültig für (Minuten):",
"generate_referral": "Einladungslink generieren",
"referral_link_label": "Dein Einladungslink:",
"copy_referral_link": "Link kopieren",
"singleplayer": "Singleplayer",
"singleplayer_desc": "Spiele alleine und teste dein Wissen.",
"local_multiplayer": "Lokaler Multiplayer",
"online_multiplayer": "Online Multiplayer"
}

View File

@@ -37,5 +37,23 @@
"album": "Album",
"year": "Year",
"open_on_spotify": "Open on Spotify",
"logout": "Logout"
"logout": "Logout",
"custom": "custom",
"quiz_mode": "Quiz Mode",
"quiz_mode_desc": "Guess artist, title or year. Classic music quiz.",
"invite_guest": "Invite Guest",
"invite_duration": "Link valid for (minutes):",
"generate_link": "Generate Link",
"invite_link": "Invite Link:",
"copy_link": "Copy Link",
"referral_link": "Referral Link",
"referral_duration": "Link valid for (minutes):",
"generate_referral": "Generate Referral Link",
"referral_link_label": "Your referral link:",
"copy_referral_link": "Copy Referral Link",
"copied": "Copied!",
"singleplayer": "Singleplayer",
"singleplayer_desc": "Play alone and test your knowledge.",
"local_multiplayer": "Local Multiplayer",
"online_multiplayer": "Online Multiplayer"
}

77
templates/gamemodes.html Normal file
View File

@@ -0,0 +1,77 @@
<!DOCTYPE html>
<html>
<head>
<title>{{ translations['quiz_title'] }} Game Modes</title>
<style>
body {
background: linear-gradient(135deg, #191414 0%, #1DB954 100%);
color: #fff;
font-family: Arial, sans-serif;
min-height: 100vh;
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.gamemode-container {
background: rgba(25, 20, 20, 0.92);
padding: 40px 50px;
border-radius: 22px;
box-shadow: 0 8px 32px 0 rgba(0,0,0,0.37);
min-width: 350px;
text-align: center;
}
.gamemode-btn {
display: block;
width: 100%;
padding: 18px 0;
margin: 18px 0;
font-size: 1.2em;
font-weight: bold;
border-radius: 30px;
border: none;
background: #1DB954;
color: #fff;
cursor: pointer;
transition: background 0.2s, transform 0.2s;
text-align: center;
letter-spacing: 1px;
}
.gamemode-btn:hover {
background: #1ed760;
transform: scale(1.04);
}
.gamemode-btn.disabled, .gamemode-btn[disabled] {
background: #535353;
color: #bbb;
cursor: not-allowed;
opacity: 0.7;
pointer-events: none;
border: 1px solid #888;
}
.gamemode-desc {
font-size: 0.95em;
color: #bdbdbd;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="gamemode-container">
<h2>{{ translations['quiz_title'] }} Game Modes</h2>
<form method="get" action="{{ url_for('playerselect', playlist_id=playlist_id) }}">
<input type="hidden" name="mode" value="title">
<button class="gamemode-btn" type="submit">{{ translations['quiz_mode'] if translations['quiz_mode'] else 'Quiz Mode' }}</button>
<div class="gamemode-desc">{{ translations['quiz_mode_desc'] if translations['quiz_mode_desc'] else 'Classic music quiz.' }}</div>
</form>
<button class="gamemode-btn disabled" disabled>Battle Mode</button>
<div class="gamemode-desc">Coming soon!</div>
<button class="gamemode-btn disabled" disabled>Party Mode</button>
<div class="gamemode-desc">Coming soon!</div>
<div style="margin-top:30px;">
<a href="{{ url_for('playlists') }}" style="color:#1DB954;">&larr; {{ translations['choose_playlist'] }}</a>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,81 @@
<!DOCTYPE html>
<html>
<head>
<title>{{ translations['quiz_title'] }} Player Selection</title>
<style>
body {
background: linear-gradient(135deg, #191414 0%, #1DB954 100%);
color: #fff;
font-family: Arial, sans-serif;
min-height: 100vh;
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.playerselect-container {
background: rgba(25, 20, 20, 0.92);
padding: 40px 50px;
border-radius: 22px;
box-shadow: 0 8px 32px 0 rgba(0,0,0,0.37);
min-width: 350px;
text-align: center;
}
.player-btn {
display: block;
width: 100%;
padding: 18px 0;
margin: 18px 0;
font-size: 1.2em;
font-weight: bold;
border-radius: 30px;
border: none;
background: #1DB954;
color: #fff;
cursor: pointer;
transition: background 0.2s, transform 0.2s;
text-align: center;
letter-spacing: 1px;
}
.player-btn:hover {
background: #1ed760;
transform: scale(1.04);
}
.player-btn.disabled, .player-btn[disabled] {
background: #535353;
color: #bbb;
cursor: not-allowed;
opacity: 0.7;
pointer-events: none;
border: 1px solid #888;
}
.player-desc {
font-size: 0.95em;
color: #bdbdbd;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="playerselect-container">
<h2>{{ translations['quiz_title'] }} Player Selection</h2>
<form method="get" action="{{ url_for('quiz', playlist_id=playlist_id) }}">
<input type="hidden" name="mode" value="{{ game_mode }}">
<button class="player-btn" type="submit">{{ translations['singleplayer'] }}</button>
<div class="player-desc">{{ translations['singleplayer_desc'] if translations['singleplayer_desc'] else 'Play alone and test your knowledge.' }}</div>
</form>
<form method="get" action="{{ url_for('quiz', playlist_id=playlist_id) }}">
<input type="hidden" name="mode" value="{{ game_mode }}">
<input type="hidden" name="local_multiplayer" value="1">
<button class="player-btn" type="submit">{{ translations['local_multiplayer'] }}</button>
<div class="player-desc">Spiele mit bis zu 4 Personen an einem Gerät.</div>
</form>
<button class="player-btn disabled" disabled>{{ translations['online_multiplayer'] if translations['online_multiplayer'] else 'Online Multiplayer' }}</button>
<div class="player-desc">Coming soon!</div>
<div style="margin-top:30px;">
<a href="{{ url_for('gamemodes', playlist_id=playlist_id) }}" style="color:#1DB954;">&larr; {{ translations['quiz_mode'] }}</a>
</div>
</div>
</body>
</html>

View File

@@ -51,19 +51,171 @@
background-color: #1ed760;
transform: scale(1.04);
}
/* Invite Button and Popup Styles */
.btn {
background-color: #1DB954;
color: #fff;
border: none;
border-radius: 30px;
padding: 10px 20px;
font-size: 1em;
font-weight: bold;
cursor: pointer;
transition: background 0.2s, transform 0.2s;
}
.btn:hover {
background-color: #1ed760;
transform: scale(1.04);
}
#invitePopup {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.5);
align-items: center;
justify-content: center;
z-index: 1000;
}
#invitePopup > div {
background: #191414;
color: #fff;
padding: 30px 40px;
border-radius: 18px;
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
min-width: 320px;
text-align: center;
position: relative;
}
#invitePopup span {
position: absolute;
top: 10px;
right: 18px;
cursor: pointer;
font-size: 1.5em;
}
#invitePopup label {
display: block;
margin: 15px 0 5px;
}
#invitePopup input {
width: 60px;
margin: 10px auto;
padding: 5px;
border: none;
border-radius: 5px;
text-align: center;
}
#invitePopup #inviteLinkResult {
margin-top: 18px;
word-break: break-all;
}
.top-bar {
width: 100%;
padding: 10px 0;
background: rgba(25, 20, 20, 0.85);
position: fixed;
top: 0;
left: 0;
display: flex;
justify-content: space-between;
align-items: center;
z-index: 100;
}
.top-bar-section {
display: flex;
align-items: center;
}
.top-bar-section.left {
margin-left: 30px;
}
.top-bar-section.center {
flex-grow: 1;
justify-content: center;
}
.top-bar-section.right {
margin-right: 30px;
}
</style>
</head>
<body>
<a href="{{ url_for('logout') }}" class="logout-btn" style="position:absolute;top:20px;right:30px;">
{{ translations['logout'] if translations['logout'] else 'Logout' }}
</a>
<div class="playlist-container">
<div class="top-bar">
<div class="top-bar-section left">
<button class="btn" onclick="openInvitePopup()">
{{ translations['referral_link'] if translations['referral_link'] else 'Referral Link' }}
</button>
</div>
<div class="top-bar-section center">
{% if user %}
<img src="{{ user.images[0].url if user.images and user.images[0] }}" style="width:32px;border-radius:50%;vertical-align:middle;margin-right:8px;">
<span>{{ user.display_name }}</span>
{% endif %}
</div>
<div class="top-bar-section right">
<a href="{{ url_for('logout') }}" class="btn btn-danger">
{{ translations['logout'] if translations['logout'] else 'Logout' }}
</a>
</div>
</div>
<div class="playlist-container" style="margin-top:80px;">
<h2>{{ translations['choose_playlist'] }}</h2>
<ul>
{% for pl in playlists %}
<li><a class="playlist-link" href="/quiz/{{ pl.id }}">{{ pl.name }}</a></li>
<li><a class="playlist-link" href="/gamemodes/{{ pl.id }}">{{ pl.name }}</a></li>
{% endfor %}
</ul>
</div>
<!-- Invite Popup -->
<div id="invitePopup">
<div>
<span onclick="closeInvitePopup()">&times;</span>
<h3>{{ translations['referral_link'] if translations['referral_link'] else 'Referral Link' }}</h3>
<label for="inviteDuration">{{ translations['referral_duration'] if translations['referral_duration'] else 'Link valid for (minutes):' }}</label>
<input type="number" id="inviteDuration" min="1" max="1440" value="60">
<br>
<button class="btn" onclick="generateInviteLink()">{{ translations['generate_referral'] if translations['generate_referral'] else 'Generate Referral Link' }}</button>
<div id="inviteLinkResult" style="margin-top:18px;">
<input id="inviteLinkInput" type="text" readonly style="width:90%;padding:8px;border-radius:8px;border:1px solid #444;display:none;background:#222;color:#fff;">
<button id="copyInviteBtn" class="btn" style="margin-top:8px;display:none;" onclick="copyInviteLink()">{{ translations['copy_referral_link'] if translations['copy_referral_link'] else 'Copy Referral Link' }}</button>
</div>
</div>
</div>
<script>
function openInvitePopup() {
document.getElementById('invitePopup').style.display = 'flex';
document.getElementById('inviteLinkResult').style.display = '';
document.getElementById('inviteLinkInput').style.display = 'none';
document.getElementById('copyInviteBtn').style.display = 'none';
document.getElementById('inviteLinkInput').value = '';
}
function closeInvitePopup() {
document.getElementById('invitePopup').style.display = 'none';
}
function generateInviteLink() {
const duration = document.getElementById('inviteDuration').value || 60;
fetch(`/invite?duration=${duration}`)
.then(response => response.text())
.then(link => {
document.getElementById('inviteLinkInput').value = link;
document.getElementById('inviteLinkInput').style.display = '';
document.getElementById('copyInviteBtn').style.display = '';
});
}
function copyInviteLink() {
const input = document.getElementById('inviteLinkInput');
input.select();
input.setSelectionRange(0, 99999);
document.execCommand('copy');
document.getElementById('copyInviteBtn').innerText = "{{ translations['copied'] if translations['copied'] else 'Copied!' }}";
setTimeout(() => {
document.getElementById('copyInviteBtn').innerText = "{{ translations['copy_referral_link'] if translations['copy_referral_link'] else 'Copy Referral Link' }}";
}, 1200);
}
</script>
</body>
</html>

View File

@@ -6,10 +6,15 @@
<script src="https://sdk.scdn.co/spotify-player.js"></script>
<style>
body {
background: linear-gradient(135deg, #191414 0%, #1DB954 100%);
color: #fff;
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
min-height: 100vh;
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.controls {
margin: 20px 0;
@@ -122,19 +127,12 @@
player.addListener('account_error', ({ message }) => { console.error(message); });
player.addListener('playback_error', ({ message }) => { console.error(message); });
// Playback status updates
player.addListener('player_state_changed', state => {
console.log(state);
updatePlayButton(state);
});
// Ready
player.addListener('ready', ({ device_id }) => {
console.log('Ready with Device ID', device_id);
document.getElementById('device_id').value = device_id;
// Hole Optionen
const playDuration = parseInt(getOption('playDuration', '0'), 10);
const playDuration = getPlayDuration();
const startPosition = getOption('startPosition', 'start');
let position_ms = 0;
if (startPosition === 'random') {
@@ -159,7 +157,7 @@
// Stoppe nach playDuration Sekunden (wenn nicht unendlich)
if (playDuration > 0) {
setTimeout(() => {
window.quizifyTimeout = setTimeout(() => {
player.pause();
}, playDuration * 1000);
}
@@ -178,25 +176,16 @@
window.spotifyPlayer = player;
};
function updatePlayButton(state) {
let playButton = document.getElementById('playPauseBtn');
if (state && !state.paused) {
playButton.innerHTML = i18n.pause;
} else {
playButton.innerHTML = '▶️ Play';
}
}
function setCorrectAnswer() {
if (currentGameMode === 'artist') {
correctAnswer = "{{ track.artists[0].name }}";
document.getElementById('question-text').innerText = i18n.question_artist;
document.getElementById('answerInput').placeholder = i18n.input_artist;
} else if (currentGameMode === 'title') {
} else if (currentGameMode === 'title' ) {
correctAnswer = "{{ track.name }}";
document.getElementById('question-text').innerText = i18n.question_title;
document.getElementById('answerInput').placeholder = i18n.input_title;
} else if (currentGameMode === 'year') {
} else if (currentGameMode === 'year' ) {
correctAnswer = "{{ track.album.release_date[:4] }}";
document.getElementById('question-text').innerText = i18n.question_year;
document.getElementById('answerInput').placeholder = i18n.input_year;
@@ -311,6 +300,10 @@
}
function switchGameMode(mode) {
// Beim Moduswechsel Multiplayer-Daten löschen
localStorage.removeItem('quizify_multiplayer_names');
localStorage.removeItem('quizify_multiplayer_scores');
localStorage.removeItem('quizify_multiplayer_current');
window.location.href = `/reset_quiz/{{ playlist_id }}?next_mode=${mode}`;
}
@@ -321,82 +314,260 @@ function getOption(key, defaultValue) {
return localStorage.getItem(key) || defaultValue;
}
window.onload = function() {
document.getElementById('playDuration').value = getOption('playDuration', '0');
const playDuration = getOption('playDuration', '0');
const sel = document.getElementById('playDuration');
const custom = document.getElementById('customDuration');
const label = document.getElementById('customDurationLabel');
if (['10','15','30','0'].includes(playDuration)) {
sel.value = playDuration;
custom.style.display = 'none';
label.style.display = 'none';
} else {
sel.value = 'custom';
custom.value = playDuration;
custom.style.display = '';
label.style.display = '';
}
document.getElementById('startPosition').value = getOption('startPosition', 'start');
updateMultiplayerUI();
// Prüfe, ob MultiplayerPopup existiert und sichtbar ist
const mpPopup = document.getElementById('multiplayerPopup');
if (!mpPopup || mpPopup.style.display === 'none') {
quizifyReady();
}
};
function onPlayDurationChange() {
const sel = document.getElementById('playDuration');
const custom = document.getElementById('customDuration');
const label = document.getElementById('customDurationLabel');
if (sel.value === 'custom') {
custom.style.display = '';
label.style.display = '';
setOption('playDuration', custom.value || '10');
} else {
custom.style.display = 'none';
label.style.display = 'none';
setOption('playDuration', sel.value);
}
}
function getPlayDuration() {
const sel = document.getElementById('playDuration');
if (sel.value === 'custom') {
return parseInt(document.getElementById('customDuration').value) || 10;
}
return parseInt(sel.value);
}
// "Nochmal X Sekunden"-Button Funktion
function replayDuration() {
const playDuration = getPlayDuration();
if (window.spotifyPlayer) {
window.spotifyPlayer.resume();
if (window.quizifyTimeout) clearTimeout(window.quizifyTimeout);
window.quizifyTimeout = setTimeout(() => {
window.spotifyPlayer.pause();
}, playDuration * 1000);
}
}
function updateMultiplayerUI() {
const names = JSON.parse(localStorage.getItem('quizify_multiplayer_names') || "[]");
const scores = JSON.parse(localStorage.getItem('quizify_multiplayer_scores') || "[]");
const current = parseInt(localStorage.getItem('quizify_multiplayer_current') || "0");
if(names.length > 1) {
document.getElementById('multiplayerBar').style.display = '';
let html = '';
names.forEach((n,i) => {
html += `<span style="margin:0 10px;${i===current?'font-weight:bold;text-decoration:underline;':''}">${n}: ${scores[i]}</span>`;
});
html += `<br><span style="font-size:0.95em;color:#bdbdbd;">Am Zug: <b>${names[current]}</b></span>`;
document.getElementById('multiplayerPlayers').innerHTML = html;
document.getElementById('answerInput').placeholder = "Antwort für " + names[current];
}
}
// Multiplayer: Nach jeder Antwort Punkte & Spieler wechseln
const origCheckAnswer = checkAnswer;
checkAnswer = function() {
const names = JSON.parse(localStorage.getItem('quizify_multiplayer_names') || "[]");
const scores = JSON.parse(localStorage.getItem('quizify_multiplayer_scores') || "[]");
const current = parseInt(localStorage.getItem('quizify_multiplayer_current') || "0");
const guess = document.getElementById('answerInput').value;
if (!guess) return;
fetch('/check_answer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
guess: guess,
correct_answer: correctAnswer,
game_mode: currentGameMode,
playlist_id: "{{ playlist_id }}"
})
})
.then(response => response.json())
.then(data => {
const resultContainer = document.getElementById('resultContainer');
resultContainer.style.display = 'block';
if (data.correct) {
resultContainer.className = 'result-container correct';
resultContainer.innerHTML = `<h3>${i18n.correct}</h3>`;
scores[current] = (scores[current] || 0) + 1;
localStorage.setItem('quizify_multiplayer_scores', JSON.stringify(scores));
} else {
resultContainer.className = 'result-container incorrect';
resultContainer.innerHTML = `<h3>${i18n.wrong}</h3>
<p>${i18n.right_answer} <strong>${data.correct_answer}</strong></p>`;
}
// Song-Infos ergänzen (wie gehabt)
// ...
// Nächster Spieler
let next = (current + 1) % names.length;
localStorage.setItem('quizify_multiplayer_current', next);
updateMultiplayerUI();
document.getElementById('nextQuestionBtn').style.display = 'inline-block';
})
.catch(error => {
console.error('Error checking answer:', error);
});
}
// Beim Laden Multiplayer-UI anzeigen, falls aktiv
window.onload = function() {
// ...dein bisheriger onload code...
updateMultiplayerUI();
// Starte Quiz nur, wenn KEIN Multiplayer-Popup offen ist
if (!document.getElementById('multiplayerPopup') || document.getElementById('multiplayerPopup').style.display === 'none') {
quizifyReady();
}
}
function quizifyReady() {
// Hier alles, was nach dem Schließen des Popups passieren soll
if (window.onSpotifyWebPlaybackSDKReady) {
window.onSpotifyWebPlaybackSDKReady();
}
setCorrectAnswer();
}
// Entferne Multiplayer-Daten, wenn NICHT im lokalen Multiplayer
if (!window.location.search.includes('local_multiplayer=1')) {
localStorage.removeItem('quizify_multiplayer_names');
localStorage.removeItem('quizify_multiplayer_scores');
localStorage.removeItem('quizify_multiplayer_current');
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div style="text-align:center; margin-bottom: 10px;">
<span id="progressInfo">{{ translations['songs_in_playlist'] }} {{ total_questions }}</span>
<span id="scoreInfo" style="margin-left:20px;">
{{ translations['score'] }}: {{ score }} / {{ answered if answered > 0 else 1 }}
({{ ((score / (answered if answered > 0 else 1)) * 100) | round(0) if answered > 0 else 0 }}{{ translations['percent'] }})
</span>
<body style="background: linear-gradient(135deg, #191414 0%, #1DB954 100%); min-height:100vh; margin:0; display:flex; align-items:center; justify-content:center;">
<div class="quiz-container" style="
background: rgba(25, 20, 20, 0.92);
padding: 40px 30px 30px 30px;
border-radius: 22px;
box-shadow: 0 8px 32px 0 rgba(0,0,0,0.37);
max-width: 500px;
width: 100%;
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
">
<div style="text-align:center; margin-bottom: 10px;">
<span id="progressInfo">{{ translations['songs_in_playlist'] }} {{ total_questions }}</span>
<span id="scoreInfo" style="margin-left:20px;">
{{ translations['score'] }}: {{ score }} / {{ answered if answered > 0 else 1 }}
({{ ((score / (answered if answered > 0 else 1)) * 100) | round(0) if answered > 0 else 0 }}{{ translations['percent'] }})
</span>
</div>
<div style="text-align:center; margin-bottom: 20px;">
<a href="/reset_quiz/{{ playlist_id }}" class="btn btn-danger" style="margin-top:10px;">{{ translations['end_quiz'] }}</a>
</div>
<h2 id="question-text" style="color:#fff;">{{ translations['question_artist'] }}</h2>
<input type="hidden" id="device_id" value="">
<div class="game-modes" style="margin-bottom:20px;">
<button class="btn {{ 'btn-success' if game_mode == 'artist' else 'btn-secondary' }}" onclick="switchGameMode('artist')">{{ translations['guess_artist'] }}</button>
<button class="btn {{ 'btn-success' if game_mode == 'title' else 'btn-secondary' }}" onclick="switchGameMode('title')">{{ translations['guess_title'] }}</button>
<button class="btn {{ 'btn-success' if game_mode == 'year' else 'btn-secondary' }}" onclick="switchGameMode('year')">{{ translations['guess_year'] }}</button>
</div>
<div class="game-options" style="margin-bottom:20px;">
<label>{{ translations['play_duration'] }}:
<select id="playDuration" onchange="onPlayDurationChange()">
<option value="10">10s</option>
<option value="15">15s</option>
<option value="30">30s</option>
<option value="0" selected>{{ translations['unlimited'] }}</option>
<option value="custom">{{ translations['custom'] }}</option>
</select>
<input type="number" id="customDuration" min="1" max="600" style="width:60px;display:none;" placeholder="Sek." onchange="setOption('playDuration', this.value)">
<span id="customDurationLabel" style="display:none;">s</span>
</label>
<label style="margin-left:20px;">{{ translations['start_position'] }}:
<select id="startPosition" onchange="setOption('startPosition', this.value)">
<option value="start" selected>{{ translations['start'] }}</option>
<option value="random">{{ translations['random'] }}</option>
</select>
</label>
</div>
<div class="controls" style="text-align: center; margin-bottom:20px;">
<button id="replayBtn" class="btn" onclick="replayDuration()">{{ translations['play_duration'] }} +</button>
</div>
<div style="text-align: center; margin-top: 10px;">
<input type="text" id="answerInput" placeholder="{{ translations['input_artist'] }}" oninput="searchTracks()" style="background:#222; color:#fff;">
<button class="btn" onclick="checkAnswer()">{{ translations['answer_button'] }}</button>
<div id="searchResults" class="search-results"></div>
<div id="resultContainer" class="result-container" style="background:#222; color:#fff; border:1px solid #444;"></div>
<a id="nextQuestionBtn" href="/quiz/{{ playlist_id }}?mode={{ game_mode }}" class="btn" style="display: none;">{{ translations['next_question'] }}</a>
</div>
<div class="hint-container" style="color:#bdbdbd;">
{% if game_mode == 'artist' %}
<p>{{ translations['tip_artist'] }}</p>
{% elif game_mode == 'title' %}
<p>{{ translations['tip_title'] }}</p>
{% elif game_mode == 'year' %}
<p>{{ translations['tip_year'] }}</p>
{% endif %}
</div>
<div id="multiplayerBar" style="display:none;margin-bottom:15px;text-align:center;">
<span id="multiplayerPlayers"></span>
</div>
</div>
{% if request.args.get('local_multiplayer') %}
<div id="multiplayerPopup" style="position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;z-index:2000;">
<div style="background:#191414;padding:30px 40px;border-radius:18px;box-shadow:0 8px 32px 0 rgba(0,0,0,0.37);min-width:320px;text-align:center;">
<h3>Lokaler Multiplayer</h3>
<p>Gib bis zu 4 Spielernamen ein:</p>
<form id="multiplayerForm" onsubmit="startMultiplayer(event)">
<input type="text" id="player1" placeholder="Spieler 1" required style="margin:5px;width:80%"><br>
<input type="text" id="player2" placeholder="Spieler 2" style="margin:5px;width:80%"><br>
<input type="text" id="player3" placeholder="Spieler 3" style="margin:5px;width:80%"><br>
<input type="text" id="player4" placeholder="Spieler 4" style="margin:5px;width:80%"><br>
<button class="btn" type="submit" style="margin-top:10px;">Starten</button>
</form>
</div>
</div>
<div style="text-align:center; margin-bottom: 20px;">
<a href="/reset_quiz/{{ playlist_id }}" class="btn btn-danger" style="margin-top:10px;">{{ translations['end_quiz'] }}</a>
</div>
<h2 id="question-text">{{ translations['question_artist'] }}</h2>
<!-- Verstecktes Feld für device_id -->
<input type="hidden" id="device_id" value="">
<!-- Spielmodi -->
<div class="game-modes">
<button class="btn {{ 'btn-success' if game_mode == 'artist' else 'btn-secondary' }}" onclick="switchGameMode('artist')">{{ translations['guess_artist'] }}</button>
<button class="btn {{ 'btn-success' if game_mode == 'title' else 'btn-secondary' }}" onclick="switchGameMode('title')">{{ translations['guess_title'] }}</button>
<button class="btn {{ 'btn-success' if game_mode == 'year' else 'btn-secondary' }}" onclick="switchGameMode('year')">{{ translations['guess_year'] }}</button>
</div>
<!-- Optionen für das Spiel -->
<div class="game-options">
<label>{{ translations['play_duration'] }}:
<select id="playDuration" onchange="setOption('playDuration', this.value)">
<option value="10">10s</option>
<option value="15">15s</option>
<option value="30">30s</option>
<option value="0" selected>{{ translations['unlimited'] }}</option>
</select>
</label>
<label style="margin-left:20px;">{{ translations['start_position'] }}:
<select id="startPosition" onchange="setOption('startPosition', this.value)">
<option value="start" selected>{{ translations['start'] }}</option>
<option value="random">{{ translations['random'] }}</option>
</select>
</label>
</div>
<!-- Player Controls -->
<div class="controls" style="text-align: center;">
<button id="playPauseBtn" class="btn" onclick="togglePlay()">{{ translations['pause'] }}</button>
</div>
<!-- Antwort-Eingabe -->
<div style="text-align: center; margin-top: 30px;">
<input type="text" id="answerInput" placeholder="{{ translations['input_artist'] }}" oninput="searchTracks()">
<button class="btn" onclick="checkAnswer()">{{ translations['answer_button'] }}</button>
<!-- Suchergebnisse -->
<div id="searchResults" class="search-results"></div>
<!-- Ergebnis-Anzeige -->
<div id="resultContainer" class="result-container"></div>
<!-- Nächste Frage Button, wird nach Antwort angezeigt -->
<a id="nextQuestionBtn" href="/quiz/{{ playlist_id }}?mode={{ game_mode }}" class="btn" style="display: none;">{{ translations['next_question'] }}</a>
</div>
<!-- Hilfe-Text je nach Modus -->
<div class="hint-container">
{% if game_mode == 'artist' %}
<p>{{ translations['tip_artist'] }}</p>
{% elif game_mode == 'title' %}
<p>{{ translations['tip_title'] }}</p>
{% elif game_mode == 'year' %}
<p>{{ translations['tip_year'] }}</p>
{% endif %}
</div>
<script>
function startMultiplayer(e) {
e.preventDefault();
const names = [];
for(let i=1;i<=4;i++) {
const val = document.getElementById('player'+i).value.trim();
if(val) names.push(val);
}
if(names.length < 2) {
alert("Bitte mindestens 2 Namen eingeben!");
return;
}
localStorage.setItem('quizify_multiplayer_names', JSON.stringify(names));
localStorage.setItem('quizify_multiplayer_scores', JSON.stringify(Array(names.length).fill(0)));
localStorage.setItem('quizify_multiplayer_current', 0);
document.getElementById('multiplayerPopup').style.display = 'none';
updateMultiplayerUI();
quizifyReady(); // <-- Musik und Quiz jetzt starten!
}
</script>
{% endif %}
</body>
</html>

67
templates/quiz_base.html Normal file
View File

@@ -0,0 +1,67 @@
<!DOCTYPE html>
<html>
<head>
<title>{{ translations['quiz_title'] }}</title>
<script src="https://sdk.scdn.co/spotify-player.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
background: linear-gradient(135deg, #191414 0%, #1DB954 100%);
color: #fff;
font-family: Arial, sans-serif;
min-height: 100vh;
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.quiz-container {
background: rgba(25, 20, 20, 0.92);
padding: 40px 30px 30px 30px;
border-radius: 22px;
box-shadow: 0 8px 32px 0 rgba(0,0,0,0.37);
max-width: 500px;
width: 100%;
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
}
.btn {
padding: 10px 15px;
margin: 5px;
background-color: #1DB954;
color: white;
border: none;
border-radius: 20px;
cursor: pointer;
}
.btn:hover { background-color: #1ed760; }
.btn-secondary { background-color: #535353; }
.btn-secondary:hover { background-color: #7b7b7b; }
.btn-success { background-color: #4CAF50; }
.btn-danger { background-color: #f44336; }
.game-modes { margin: 20px 0; display: flex; justify-content: center; }
.result-container { margin: 20px 0; padding: 15px; border-radius: 5px; text-align: center; display: none; }
.correct { background-color: #e8f5e9; border: 1px solid #4CAF50; }
.incorrect { background-color: #ffebee; border: 1px solid #f44336; }
input[type="text"], input[type="number"] {
padding: 10px; width: 300px; border: 1px solid #ddd; border-radius: 20px; font-size: 16px;
}
.hint-container { margin: 15px 0; font-style: italic; color: #666; }
.game-options { text-align: center; margin-bottom: 20px; }
.game-options label { margin-right: 20px; }
.search-results { margin-top: 15px; max-height: 200px; overflow-y: auto; border: 1px solid #ddd; border-radius: 5px; display: none; }
.search-item { padding: 8px 10px; border-bottom: 1px solid #eee; cursor: pointer; }
.search-item:hover { background-color: #f5f5f5; }
</style>
{% block extra_head %}{% endblock %}
</head>
<body>
<div class="quiz-container">
{% block quiz_content %}{% endblock %}
</div>
{% block extra_body %}{% endblock %}
</body>
</html>

View File

@@ -0,0 +1,441 @@
<!DOCTYPE html>
<html>
<head>
<title>{{ translations['quiz_title'] }}</title>
<script src="https://sdk.scdn.co/spotify-player.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
background: linear-gradient(135deg, #191414 0%, #1DB954 100%);
color: #fff;
font-family: Arial, sans-serif;
min-height: 100vh;
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.quiz-container {
background: rgba(25, 20, 20, 0.92);
padding: 40px 30px 30px 30px;
border-radius: 22px;
box-shadow: 0 8px 32px 0 rgba(0,0,0,0.37);
max-width: 500px;
width: 100%;
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
}
.btn {
padding: 10px 15px;
margin: 5px;
background-color: #1DB954;
color: white;
border: none;
border-radius: 20px;
cursor: pointer;
}
.btn:hover { background-color: #1ed760; }
.btn-secondary { background-color: #535353; }
.btn-secondary:hover { background-color: #7b7b7b; }
.btn-danger { background-color: #f44336; }
.game-modes { margin: 20px 0; display: flex; justify-content: center; }
.result-container { margin: 20px 0; padding: 15px; border-radius: 5px; text-align: center; display: none; }
.correct { background-color: #e8f5e9; border: 1px solid #4CAF50; }
.incorrect { background-color: #ffebee; border: 1px solid #f44336; }
input[type="text"], input[type="number"] {
padding: 10px; width: 300px; border: 1px solid #ddd; border-radius: 20px; font-size: 16px;
}
.search-results {
margin-top: 15px;
max-height: 200px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 5px;
display: none;
}
.search-item { padding: 8px 10px; border-bottom: 1px solid #eee; cursor: pointer; }
.search-item:hover { background-color: #f5f5f5; }
.hint-container { margin: 15px 0; font-style: italic; color: #bdbdbd; }
#multiplayerBar { margin-bottom:15px;text-align:center; }
</style>
</head>
<body>
<div class="quiz-container">
<!-- Multiplayer-Bar immer sichtbar -->
<div id="multiplayerBar" style="margin-bottom:15px;text-align:center;">
<span id="multiplayerPlayers"></span>
</div>
<div style="text-align:center; margin-bottom: 20px;">
<a href="/reset_quiz/{{ playlist_id }}?local_multiplayer=1" class="btn btn-danger" style="margin-top:10px;">{{ translations['end_quiz'] }}</a>
</div>
<h2 id="question-text" style="color:#fff;">{{ translations['question_artist'] }}</h2>
<input type="hidden" id="device_id" value="">
<div class="game-modes" style="margin-bottom:20px;">
<button class="btn {{ 'btn-success' if game_mode == 'artist' else 'btn-secondary' }}"
onclick="switchGameMode('artist')">{{ translations['guess_artist'] }}</button>
<button class="btn {{ 'btn-success' if game_mode == 'title' else 'btn-secondary' }}"
onclick="switchGameMode('title')">{{ translations['guess_title'] }}</button>
<button class="btn {{ 'btn-success' if game_mode == 'year' else 'btn-secondary' }}"
onclick="switchGameMode('year')">{{ translations['guess_year'] }}</button>
</div>
<div class="game-options" style="margin-bottom:20px;">
<label>{{ translations['play_duration'] }}:
<select id="playDuration" onchange="onPlayDurationChange()">
<option value="10">10s</option>
<option value="15">15s</option>
<option value="30">30s</option>
<option value="0" selected>{{ translations['unlimited'] }}</option>
<option value="custom">{{ translations['custom'] }}</option>
</select>
<input type="number" id="customDuration" min="1" max="600" style="width:60px;display:none;" placeholder="Sek." onchange="setOption('playDuration', this.value)">
<span id="customDurationLabel" style="display:none;">s</span>
</label>
<label style="margin-left:20px;">{{ translations['start_position'] }}:
<select id="startPosition" onchange="setOption('startPosition', this.value)">
<option value="start" selected>{{ translations['start'] }}</option>
<option value="random">{{ translations['random'] }}</option>
</select>
</label>
</div>
<div class="controls" style="text-align: center; margin-bottom:20px;">
<button id="replayBtn" class="btn" onclick="replayDuration()">{{ translations['play_duration'] }} +</button>
</div>
<div style="text-align: center; margin-top: 10px;">
<input type="text" id="answerInput" placeholder="{{ translations['input_artist'] }}" oninput="searchTracks()" style="background:#222; color:#fff;">
<button class="btn" onclick="checkAnswer()">{{ translations['answer_button'] }}</button>
<div id="searchResults" class="search-results"></div>
<div id="resultContainer" class="result-container" style="background:#222; color:#fff; border:1px solid #444;"></div>
<a id="nextQuestionBtn" href="/quiz/{{ playlist_id }}?mode={{ game_mode }}&local_multiplayer=1" class="btn" style="display: none;">{{ translations['next_question'] }}</a>
</div>
<div class="hint-container">
{% if game_mode == 'artist' %}
<p>{{ translations['tip_artist'] }}</p>
{% elif game_mode == 'title' %}
<p>{{ translations['tip_title'] }}</p>
{% elif game_mode == 'year' %}
<p>{{ translations['tip_year'] }}</p>
{% endif %}
</div>
</div>
<!-- Multiplayer Popup -->
<div id="multiplayerPopup" style="position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;z-index:2000;">
<div style="background:#191414;padding:30px 40px;border-radius:18px;box-shadow:0 8px 32px 0 rgba(0,0,0,0.37);min-width:320px;text-align:center;">
<h3>Lokaler Multiplayer</h3>
<p>Gib bis zu 4 Spielernamen ein:</p>
<form id="multiplayerForm" onsubmit="startMultiplayer(event)">
<input type="text" id="player1" placeholder="Spieler 1" required style="margin:5px;width:80%"><br>
<input type="text" id="player2" placeholder="Spieler 2" style="margin:5px;width:80%"><br>
<input type="text" id="player3" placeholder="Spieler 3" style="margin:5px;width:80%"><br>
<input type="text" id="player4" placeholder="Spieler 4" style="margin:5px;width:80%"><br>
<button class="btn" type="submit" style="margin-top:10px;">Starten</button>
</form>
</div>
</div>
<script>
// --- Multiplayer Popup ---
function startMultiplayer(e) {
e.preventDefault();
const names = [];
for(let i=1;i<=4;i++) {
const val = document.getElementById('player'+i).value.trim();
if(val) names.push(val);
}
if(names.length < 2) {
alert("Bitte mindestens 2 Namen eingeben!");
return;
}
localStorage.setItem('quizify_multiplayer_names', JSON.stringify(names));
localStorage.setItem('quizify_multiplayer_scores', JSON.stringify(Array(names.length).fill(0)));
localStorage.setItem('quizify_multiplayer_current', 0);
document.getElementById('multiplayerPopup').style.display = 'none';
updateMultiplayerUI();
quizifyReady();
}
// --- Spotify Web Playback SDK ---
let allTracks = {{ all_tracks|tojson }};
let currentGameMode = "{{ game_mode }}";
let correctAnswer = "";
const i18n = {{ translations|tojson }};
window.onSpotifyWebPlaybackSDKReady = () => {
const token = '{{ access_token }}';
const player = new Spotify.Player({
name: 'Musik Quiz Player',
getOAuthToken: cb => { cb(token); },
volume: 0.5
});
player.addListener('ready', ({ device_id }) => {
document.getElementById('device_id').value = device_id;
});
player.connect();
window.spotifyPlayer = player;
};
function quizifyReady() {
// Musik abspielen, wenn Popup geschlossen
function playTrackWhenReady() {
const device_id = document.getElementById('device_id').value;
if (!device_id) {
// Player ist noch nicht bereit, nochmal versuchen
setTimeout(playTrackWhenReady, 200);
return;
}
const playDuration = getPlayDuration();
const startPosition = getOption('startPosition', 'start');
let position_ms = 0;
if (startPosition === 'random') {
const duration = {{ track.duration_ms if track.duration_ms else 180000 }};
position_ms = Math.floor(Math.random() * (duration - 30000));
}
fetch(`/play_track?device_id=${device_id}&track_uri={{ track.uri }}&position_ms=${position_ms}`, { method: 'POST' });
if (playDuration > 0) {
window.quizifyTimeout = setTimeout(() => { window.spotifyPlayer.pause(); }, playDuration * 1000);
}
setCorrectAnswer();
}
// Player initialisieren, falls nicht vorhanden
if (!window.spotifyPlayer) {
window.onSpotifyWebPlaybackSDKReady = () => {
const token = '{{ access_token }}';
const player = new Spotify.Player({
name: 'Musik Quiz Player',
getOAuthToken: cb => { cb(token); },
volume: 0.5
});
player.addListener('ready', ({ device_id }) => {
document.getElementById('device_id').value = device_id;
playTrackWhenReady();
});
player.connect();
window.spotifyPlayer = player;
};
if (window.onSpotifyWebPlaybackSDKReady) window.onSpotifyWebPlaybackSDKReady();
} else {
playTrackWhenReady();
}
}
function setCorrectAnswer() {
if (currentGameMode === 'artist') {
correctAnswer = "{{ track.artists[0].name }}";
document.getElementById('question-text').innerText = i18n.question_artist;
document.getElementById('answerInput').placeholder = i18n.input_artist;
} else if (currentGameMode === 'title' ) {
correctAnswer = "{{ track.name }}";
document.getElementById('question-text').innerText = i18n.question_title;
document.getElementById('answerInput').placeholder = i18n.input_title;
} else if (currentGameMode === 'year' ) {
correctAnswer = "{{ track.album.release_date[:4] }}";
document.getElementById('question-text').innerText = i18n.question_year;
document.getElementById('answerInput').placeholder = i18n.input_year;
document.getElementById('answerInput').type = "number";
}
}
function searchTracks() {
const query = document.getElementById('answerInput').value;
if (query.length < 2) {
document.getElementById('searchResults').style.display = 'none';
return;
}
fetch('/search_track', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: query, all_tracks: allTracks })
})
.then(response => response.json())
.then(data => {
const resultsContainer = document.getElementById('searchResults');
resultsContainer.innerHTML = '';
if (data.results.length === 0) {
resultsContainer.style.display = 'none';
return;
}
data.results.forEach(result => {
const item = document.createElement('div');
item.className = 'search-item';
item.innerHTML = `<strong>${result.name}</strong> - ${result.artist}`;
item.onclick = function() {
document.getElementById('answerInput').value =
currentGameMode === 'artist' ? result.artist : result.name;
resultsContainer.style.display = 'none';
};
resultsContainer.appendChild(item);
});
resultsContainer.style.display = 'block';
});
}
function updateMultiplayerUI() {
const names = JSON.parse(localStorage.getItem('quizify_multiplayer_names') || "[]");
const scores = JSON.parse(localStorage.getItem('quizify_multiplayer_scores') || "[]");
const current = parseInt(localStorage.getItem('quizify_multiplayer_current') || "0");
let html = '';
if(names.length > 1) {
names.forEach((n,i) => {
html += `<span style="margin:0 10px;${i===current?'font-weight:bold;text-decoration:underline;':''}">${n}: ${scores[i] || 0}</span>`;
});
html += `<br><span style="font-size:0.95em;color:#bdbdbd;">Am Zug: <b>${names[current]}</b></span>`;
}
document.getElementById('multiplayerPlayers').innerHTML = html;
if(names.length > 1) {
document.getElementById('answerInput').placeholder = "Antwort für " + names[current];
}
}
function checkAnswer() {
const names = JSON.parse(localStorage.getItem('quizify_multiplayer_names') || "[]");
const scores = JSON.parse(localStorage.getItem('quizify_multiplayer_scores') || "[]");
const current = parseInt(localStorage.getItem('quizify_multiplayer_current') || "0");
const guess = document.getElementById('answerInput').value;
if (!guess) return;
fetch('/check_answer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
guess: guess,
correct_answer: correctAnswer,
game_mode: currentGameMode,
playlist_id: "{{ playlist_id }}"
})
})
.then(response => response.json())
.then(data => {
const resultContainer = document.getElementById('resultContainer');
resultContainer.style.display = 'block';
if (data.correct) {
resultContainer.className = 'result-container correct';
resultContainer.innerHTML = `<h3>${i18n.correct}</h3>`;
// Punkte werden jetzt NICHT hier gezählt!
resultContainer.dataset.wasCorrect = "1";
} else {
resultContainer.className = 'result-container incorrect';
resultContainer.innerHTML = `<h3>${i18n.wrong}</h3>
<p>${i18n.right_answer} <strong>${data.correct_answer}</strong></p>`;
resultContainer.dataset.wasCorrect = "0";
}
resultContainer.innerHTML += `
<div style="margin-top:10px;">
<img src="{{ track.album.images[0].url }}" alt="Cover" style="width:80px;border-radius:8px;"><br>
<strong>${i18n.song}:</strong> {{ track.name }}<br>
<strong>${i18n.artist}:</strong> {{ track.artists[0].name }}<br>
<strong>${i18n.album}:</strong> {{ track.album.name }}<br>
<strong>${i18n.year}:</strong> {{ track.album.release_date[:4] }}<br>
<a href="{{ track.external_urls.spotify }}" target="_blank" style="color:#1DB954;">${i18n.open_on_spotify}</a>
</div>
`;
document.getElementById('nextQuestionBtn').style.display = 'inline-block';
});
}
document.getElementById('nextQuestionBtn').addEventListener('click', function(e) {
// Punkte und Spielerwechsel erst jetzt!
const names = JSON.parse(localStorage.getItem('quizify_multiplayer_names') || "[]");
const scores = JSON.parse(localStorage.getItem('quizify_multiplayer_scores') || "[]");
let current = parseInt(localStorage.getItem('quizify_multiplayer_current') || "0");
const resultContainer = document.getElementById('resultContainer');
if (resultContainer.dataset.wasCorrect === "1") {
scores[current] = (scores[current] || 0) + 1;
localStorage.setItem('quizify_multiplayer_scores', JSON.stringify(scores));
}
// Nächster Spieler
let next = (current + 1) % names.length;
localStorage.setItem('quizify_multiplayer_current', next);
updateMultiplayerUI();
// Button funktioniert wie gehabt (Seitenwechsel)
// Kein preventDefault!
});
function switchGameMode(mode) {
// Multiplayer-Daten NICHT löschen, damit Namen erhalten bleiben!
window.location.href = `/quiz/{{ playlist_id }}?mode=${mode}&local_multiplayer=1`;
}
function setOption(key, value) { localStorage.setItem(key, value); }
function getOption(key, defaultValue) { return localStorage.getItem(key) || defaultValue; }
// Multiplayer-Daten beim Laden immer löschen, damit Popup erscheint
// localStorage.removeItem('quizify_multiplayer_names');
// localStorage.removeItem('quizify_multiplayer_scores');
// localStorage.removeItem('quizify_multiplayer_current');
window.onload = function() {
// Prüfe, ob wir aus dem Playerselect kommen (local_multiplayer=1 in der URL)
const urlParams = new URLSearchParams(window.location.search);
const isMultiplayer = urlParams.get('local_multiplayer') === '1';
if (isMultiplayer && !localStorage.getItem('quizify_multiplayer_names')) {
// Nur beim ersten Start im Multiplayer: Popup anzeigen
document.getElementById('multiplayerPopup').style.display = 'flex';
} else {
// Sonst: Popup ausblenden, UI und Quiz starten
document.getElementById('multiplayerPopup').style.display = 'none';
updateMultiplayerUI();
quizifyReady();
}
// PlayDuration-UI
const playDuration = getOption('playDuration', '0');
const sel = document.getElementById('playDuration');
const custom = document.getElementById('customDuration');
const label = document.getElementById('customDurationLabel');
if (['10','15','30','0'].includes(playDuration)) {
sel.value = playDuration;
custom.style.display = 'none';
label.style.display = 'none';
} else {
sel.value = 'custom';
custom.value = playDuration;
custom.style.display = '';
label.style.display = '';
}
document.getElementById('startPosition').value = getOption('startPosition', 'start');
};
function onPlayDurationChange() {
const sel = document.getElementById('playDuration');
const custom = document.getElementById('customDuration');
const label = document.getElementById('customDurationLabel');
if (sel.value === 'custom') {
custom.style.display = '';
label.style.display = '';
setOption('playDuration', custom.value || '10');
} else {
custom.style.display = 'none';
label.style.display = 'none';
setOption('playDuration', sel.value);
}
}
function getPlayDuration() {
const sel = document.getElementById('playDuration');
if (sel.value === 'custom') {
return parseInt(document.getElementById('customDuration').value) || 10;
}
return parseInt(sel.value);
}
function replayDuration() {
const playDuration = getPlayDuration();
if (window.spotifyPlayer) {
window.spotifyPlayer.resume();
if (window.quizifyTimeout) clearTimeout(window.quizifyTimeout);
window.quizifyTimeout = setTimeout(() => {
window.spotifyPlayer.pause();
}, playDuration * 1000);
}
}
</script>
</body>
</html>

252
templates/quiz_single.html Normal file
View File

@@ -0,0 +1,252 @@
{% extends "quiz_base.html" %}
{% block quiz_content %}
<div style="text-align:center; margin-bottom: 10px;">
<span id="progressInfo">{{ translations['songs_in_playlist'] }} {{ total_questions }}</span>
<span id="scoreInfo" style="margin-left:20px;">
{{ translations['score'] }}: {{ score }} / {{ answered if answered > 0 else 1 }}
({{ ((score / (answered if answered > 0 else 1)) * 100) | round(0) if answered > 0 else 0 }}{{ translations['percent'] }})
</span>
</div>
<div style="text-align:center; margin-bottom: 20px;">
<a href="/reset_quiz/{{ playlist_id }}" class="btn btn-danger" style="margin-top:10px;">{{ translations['end_quiz'] }}</a>
</div>
<h2 id="question-text" style="color:#fff;">{{ translations['question_artist'] }}</h2>
<input type="hidden" id="device_id" value="">
<div class="game-modes" style="margin-bottom:20px;">
<button class="btn {{ 'btn-success' if game_mode == 'artist' else 'btn-secondary' }}" onclick="switchGameMode('artist')">{{ translations['guess_artist'] }}</button>
<button class="btn {{ 'btn-success' if game_mode == 'title' else 'btn-secondary' }}" onclick="switchGameMode('title')">{{ translations['guess_title'] }}</button>
<button class="btn {{ 'btn-success' if game_mode == 'year' else 'btn-secondary' }}" onclick="switchGameMode('year')">{{ translations['guess_year'] }}</button>
</div>
<div class="game-options" style="margin-bottom:20px;">
<label>{{ translations['play_duration'] }}:
<select id="playDuration" onchange="onPlayDurationChange()">
<option value="10">10s</option>
<option value="15">15s</option>
<option value="30">30s</option>
<option value="0" selected>{{ translations['unlimited'] }}</option>
<option value="custom">{{ translations['custom'] }}</option>
</select>
<input type="number" id="customDuration" min="1" max="600" style="width:60px;display:none;" placeholder="Sek." onchange="setOption('playDuration', this.value)">
<span id="customDurationLabel" style="display:none;">s</span>
</label>
<label style="margin-left:20px;">{{ translations['start_position'] }}:
<select id="startPosition" onchange="setOption('startPosition', this.value)">
<option value="start" selected>{{ translations['start'] }}</option>
<option value="random">{{ translations['random'] }}</option>
</select>
</label>
</div>
<div class="controls" style="text-align: center; margin-bottom:20px;">
<button id="replayBtn" class="btn" onclick="replayDuration()">{{ translations['play_duration'] }} +</button>
</div>
<div style="text-align: center; margin-top: 10px;">
<input type="text" id="answerInput" placeholder="{{ translations['input_artist'] }}" oninput="searchTracks()" style="background:#222; color:#fff;">
<button class="btn" onclick="checkAnswer()">{{ translations['answer_button'] }}</button>
<div id="searchResults" class="search-results"></div>
<div id="resultContainer" class="result-container" style="background:#222; color:#fff; border:1px solid #444;"></div>
<a id="nextQuestionBtn" href="/quiz/{{ playlist_id }}?mode={{ game_mode }}" class="btn" style="display: none;">{{ translations['next_question'] }}</a>
</div>
<div class="hint-container" style="color:#bdbdbd;">
{% if game_mode == 'artist' %}
<p>{{ translations['tip_artist'] }}</p>
{% elif game_mode == 'title' %}
<p>{{ translations['tip_title'] }}</p>
{% elif game_mode == 'year' %}
<p>{{ translations['tip_year'] }}</p>
{% endif %}
</div>
{% endblock %}
{% block extra_body %}
<script>
let allTracks = {{ all_tracks|tojson }};
let currentGameMode = "{{ game_mode }}";
let correctAnswer = "";
const i18n = {{ translations|tojson }};
// Spotify Web Playback SDK
window.onSpotifyWebPlaybackSDKReady = () => {
const token = '{{ access_token }}';
const player = new Spotify.Player({
name: 'Musik Quiz Player',
getOAuthToken: cb => { cb(token); },
volume: 0.5
});
player.addListener('ready', ({ device_id }) => {
document.getElementById('device_id').value = device_id;
const playDuration = getPlayDuration();
const startPosition = getOption('startPosition', 'start');
let position_ms = 0;
if (startPosition === 'random') {
const duration = {{ track.duration_ms if track.duration_ms else 180000 }};
position_ms = Math.floor(Math.random() * (duration - 30000));
}
fetch(`/play_track?device_id=${device_id}&track_uri={{ track.uri }}&position_ms=${position_ms}`, { method: 'POST' });
if (playDuration > 0) {
window.quizifyTimeout = setTimeout(() => { player.pause(); }, playDuration * 1000);
}
setCorrectAnswer();
});
player.connect();
window.spotifyPlayer = player;
};
function setCorrectAnswer() {
if (currentGameMode === 'artist') {
correctAnswer = "{{ track.artists[0].name }}";
document.getElementById('question-text').innerText = i18n.question_artist;
document.getElementById('answerInput').placeholder = i18n.input_artist;
} else if (currentGameMode === 'title' ) {
correctAnswer = "{{ track.name }}";
document.getElementById('question-text').innerText = i18n.question_title;
document.getElementById('answerInput').placeholder = i18n.input_title;
} else if (currentGameMode === 'year' ) {
correctAnswer = "{{ track.album.release_date[:4] }}";
document.getElementById('question-text').innerText = i18n.question_year;
document.getElementById('answerInput').placeholder = i18n.input_year;
document.getElementById('answerInput').type = "number";
}
}
function searchTracks() {
const query = document.getElementById('answerInput').value;
if (query.length < 2) {
document.getElementById('searchResults').style.display = 'none';
return;
}
fetch('/search_track', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: query, all_tracks: allTracks })
})
.then(response => response.json())
.then(data => {
const resultsContainer = document.getElementById('searchResults');
resultsContainer.innerHTML = '';
if (data.results.length === 0) {
resultsContainer.style.display = 'none';
return;
}
data.results.forEach(result => {
const item = document.createElement('div');
item.className = 'search-item';
item.innerHTML = `<strong>${result.name}</strong> - ${result.artist}`;
item.onclick = function() {
document.getElementById('answerInput').value =
currentGameMode === 'artist' ? result.artist : result.name;
resultsContainer.style.display = 'none';
};
resultsContainer.appendChild(item);
});
resultsContainer.style.display = 'block';
});
}
function checkAnswer() {
const guess = document.getElementById('answerInput').value;
if (!guess) return;
fetch('/check_answer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
guess: guess,
correct_answer: correctAnswer,
game_mode: currentGameMode,
playlist_id: "{{ playlist_id }}"
})
})
.then(response => response.json())
.then(data => {
const resultContainer = document.getElementById('resultContainer');
resultContainer.style.display = 'block';
if (data.correct) {
resultContainer.className = 'result-container correct';
resultContainer.innerHTML = `<h3>${i18n.correct}</h3>`;
} else {
resultContainer.className = 'result-container incorrect';
resultContainer.innerHTML = `<h3>${i18n.wrong}</h3>
<p>${i18n.right_answer} <strong>${data.correct_answer}</strong></p>`;
}
// Song-Infos ergänzen
resultContainer.innerHTML += `
<div style="margin-top:10px;">
<img src="{{ track.album.images[0].url }}" alt="Cover" style="width:80px;border-radius:8px;"><br>
<strong>${i18n.song}:</strong> {{ track.name }}<br>
<strong>${i18n.artist}:</strong> {{ track.artists[0].name }}<br>
<strong>${i18n.album}:</strong> {{ track.album.name }}<br>
<strong>${i18n.year}:</strong> {{ track.album.release_date[:4] }}<br>
<a href="{{ track.external_urls.spotify }}" target="_blank" style="color:#1DB954;">${i18n.open_on_spotify}</a>
</div>
`;
document.getElementById('nextQuestionBtn').style.display = 'inline-block';
});
}
function switchGameMode(mode) {
window.location.href = `/reset_quiz/{{ playlist_id }}?next_mode=${mode}`;
}
function setOption(key, value) { localStorage.setItem(key, value); }
function getOption(key, defaultValue) { return localStorage.getItem(key) || defaultValue; }
window.onload = function() {
const playDuration = getOption('playDuration', '0');
const sel = document.getElementById('playDuration');
const custom = document.getElementById('customDuration');
const label = document.getElementById('customDurationLabel');
if (['10','15','30','0'].includes(playDuration)) {
sel.value = playDuration;
custom.style.display = 'none';
label.style.display = 'none';
} else {
sel.value = 'custom';
custom.value = playDuration;
custom.style.display = '';
label.style.display = '';
}
document.getElementById('startPosition').value = getOption('startPosition', 'start');
if (window.onSpotifyWebPlaybackSDKReady) window.onSpotifyWebPlaybackSDKReady();
};
function onPlayDurationChange() {
const sel = document.getElementById('playDuration');
const custom = document.getElementById('customDuration');
const label = document.getElementById('customDurationLabel');
if (sel.value === 'custom') {
custom.style.display = '';
label.style.display = '';
setOption('playDuration', custom.value || '10');
} else {
custom.style.display = 'none';
label.style.display = 'none';
setOption('playDuration', sel.value);
}
}
function getPlayDuration() {
const sel = document.getElementById('playDuration');
if (sel.value === 'custom') {
return parseInt(document.getElementById('customDuration').value) || 10;
}
return parseInt(sel.value);
}
function replayDuration() {
const playDuration = getPlayDuration();
if (window.spotifyPlayer) {
window.spotifyPlayer.resume();
if (window.quizifyTimeout) clearTimeout(window.quizifyTimeout);
window.quizifyTimeout = setTimeout(() => {
window.spotifyPlayer.pause();
}, playDuration * 1000);
}
}
</script>
<!-- Multiplayer-Daten im Singleplayer immer löschen -->
<script>
localStorage.removeItem('quizify_multiplayer_names');
localStorage.removeItem('quizify_multiplayer_scores');
localStorage.removeItem('quizify_multiplayer_current');
</script>
{% endblock %}