Files
quizify/templates/quiz.html
2025-10-31 19:56:05 +01:00

392 lines
16 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>{{ translations['quiz_title'] }}</title>
<!-- Spotify Web Playback SDK -->
<script src="https://sdk.scdn.co/spotify-player.js"></script>
<style>
/* Dark, modern theme for the quiz page */
:root{
--bg:#0f1113;
--card:#121416;
--muted:#9aa3a8;
--accent:#1DB954;
--accent-strong:#17c24a;
--danger:#f44336;
--success:#4CAF50;
--glass: rgba(255,255,255,0.03);
--radius:14px;
}
html,body{height:100%;}
body {
margin:0;
padding:24px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial;
background: linear-gradient(180deg, #070708 0%, #0b0c0e 100%);
color:#e6eef1;
display:flex;
align-items:flex-start;
justify-content:center;
}
.quiz-viewport{
width:100%;
max-width:980px;
background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0.01));
border-radius:18px;
padding:28px;
box-shadow: 0 6px 30px rgba(2,6,23,0.6);
backdrop-filter: blur(6px);
}
/* header area */
.quiz-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px}
.quiz-header .left{display:flex;align-items:center;gap:12px}
.back-link{background:transparent;border:1px solid rgba(255,255,255,0.06);color:var(--muted);padding:8px 12px;border-radius:10px;text-decoration:none}
.back-link:hover{border-color:rgba(255,255,255,0.12);color:#fff}
/* progress and score */
.meta{display:flex;gap:16px;align-items:center;color:var(--muted);font-size:0.95rem}
/* question */
h2#question-text{font-size:1.7rem;margin:6px 0 14px;color:#fff}
.game-modes{display:flex;gap:10px;justify-content:center;margin-bottom:18px;flex-wrap:wrap}
.btn{padding:10px 16px;border-radius:12px;border:none;cursor:pointer;font-weight:600}
.btn:not(.btn-danger){background:var(--glass);color:#dff3e6;border:1px solid rgba(255,255,255,0.04)}
.btn:hover{transform:translateY(-1px)}
.btn-success{background:linear-gradient(180deg,var(--accent),var(--accent-strong));color:#08120a}
.btn-secondary{background:transparent;color:var(--muted);border:1px solid rgba(255,255,255,0.04)}
.btn-danger{background:transparent;color:var(--danger);border:1px solid rgba(244,67,54,0.12)}
.game-options{display:flex;gap:12px;justify-content:center;margin-bottom:18px;flex-wrap:wrap}
select{background:transparent;color:var(--muted);border:1px solid rgba(255,255,255,0.04);padding:8px 10px;border-radius:10px}
.controls{text-align:center;margin:18px 0}
input[type="text"], input[type="number"]{
width:min(72%,520px);
padding:12px 14px;border-radius:12px;border:1px solid rgba(255,255,255,0.04);background:rgba(255,255,255,0.02);color:#e6eef1;font-size:1rem;outline:none
}
.search-results{margin-top:8px;max-height:260px;overflow:auto;border-radius:10px;background:var(--card);border:1px solid rgba(255,255,255,0.03);display:none}
.search-item{padding:10px 12px;border-bottom:1px solid rgba(255,255,255,0.02);cursor:pointer;color:#dbe7e9}
.search-item:hover{background:rgba(255,255,255,0.02)}
.result-container{margin:18px auto;padding:16px;border-radius:12px;text-align:center;display:none;max-width:720px}
.result-container.correct{background:linear-gradient(180deg, rgba(6,58,6,0.6), rgba(6,58,6,0.45));border:1px solid rgba(76,175,80,0.18)}
.result-container.incorrect{background:linear-gradient(180deg, rgba(58,6,6,0.6), rgba(58,6,6,0.45));border:1px solid rgba(244,67,54,0.12)}
.result-container img{width:84px;border-radius:8px;margin-top:10px}
.result-container a{color:var(--accent);text-decoration:none;font-weight:600}
.hint-container{color:var(--muted);text-align:center;margin-top:16px}
/* responsive */
@media (max-width:700px){
.quiz-viewport{padding:16px}
input[type="text"]{width:92%}
.game-modes{gap:8px}
}
</style>
<script>
// Speichern aller Tracks für die Suche
let allTracks = {{ all_tracks|tojson }};
let currentGameMode = "{{ game_mode }}";
let correctAnswer = "";
// translations für JS verfügbar machen
const i18n = {{ translations|tojson }};
// Wird aufgerufen, wenn Spotify Web Playback SDK geladen ist
window.onSpotifyWebPlaybackSDKReady = () => {
const token = '{{ access_token }}';
const player = new Spotify.Player({
name: 'Musik Quiz Player',
getOAuthToken: cb => { cb(token); },
volume: 0.5
});
// Error handling
player.addListener('initialization_error', ({ message }) => { console.error(message); });
player.addListener('authentication_error', ({ message }) => { console.error(message); });
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 startPosition = getOption('startPosition', 'start');
let position_ms = 0;
if (startPosition === 'random') {
// Schätze Songlänge (du kannst {{ track.duration_ms }} als Variable mitgeben!)
const duration = {{ track.duration_ms if track.duration_ms else 180000 }};
position_ms = Math.floor(Math.random() * (duration - 30000)); // max 30s vor Ende
}
// Starte Wiedergabe an gewünschter Stelle
fetch(`/play_track?device_id=${device_id}&track_uri={{ track.uri }}&position_ms=${position_ms}`, { method: 'POST' })
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
console.error('Error starting playback:', error);
});
// Stoppe nach playDuration Sekunden (wenn nicht unendlich)
if (playDuration > 0) {
setTimeout(() => {
player.pause();
}, playDuration * 1000);
}
setCorrectAnswer();
});
// Not Ready
player.addListener('not_ready', ({ device_id }) => {
console.log('Device ID has gone offline', device_id);
});
// Connect to the player!
player.connect();
// Globale Referenz zum Player für andere Funktionen
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') {
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 togglePlay() {
const deviceId = document.getElementById('device_id').value;
fetch('/toggle_playback', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ device_id: deviceId })
})
.then(response => response.json())
.catch(error => {
console.error('Error toggling playback:', error);
});
}
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';
})
.catch(error => {
console.error('Error searching tracks:', error);
});
}
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>
`;
// Zeige den "Nächste Frage" Button
document.getElementById('nextQuestionBtn').style.display = 'inline-block';
})
.catch(error => {
console.error('Error checking answer:', error);
});
}
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() {
document.getElementById('playDuration').value = getOption('playDuration', '0');
document.getElementById('startPosition').value = getOption('startPosition', 'start');
};
</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>
</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>
</body>
</html>