Files
quizify/templates/quiz.html
SimolZimol d38254bc3c modified: .env.example
modified:   Dockerfile
	modified:   app.py
	new file:   locales/de-DE.json
	modified:   templates/login.html
	modified:   templates/playlists.html
	modified:   templates/quiz.html
2025-05-19 17:39:11 +02:00

400 lines
13 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>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.controls {
margin: 20px 0;
}
.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;
}
.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;
}
.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;
}
h2 {
color: #333;
text-align: center;
}
.hint-container {
margin: 15px 0;
font-style: italic;
color: #666;
}
.game-options {
text-align: center;
margin-bottom: 20px;
}
.game-options label {
margin-right: 20px;
}
</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 = '⏸️ 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>Richtig! 🎉</h3>`;
} else {
resultContainer.className = 'result-container incorrect';
resultContainer.innerHTML = `<h3>Falsch 😢</h3>
<p>Die richtige Antwort ist: <strong>${data.correct_answer}</strong></p>`;
}
// Song-Infos ergänzen (du müsstest sie ggf. aus dem Backend mitgeben)
resultContainer.innerHTML += `
<div style="margin-top:10px;">
<img src="{{ track.album.images[0].url }}" alt="Cover" style="width:80px;border-radius:8px;"><br>
<strong>Song:</strong> {{ track.name }}<br>
<strong>Künstler:</strong> {{ track.artists[0].name }}<br>
<strong>Album:</strong> {{ track.album.name }}<br>
<strong>Jahr:</strong> {{ track.album.release_date[:4] }}<br>
<a href="{{ track.external_urls.spotify }}" target="_blank" style="color:#1DB954;">Auf Spotify öffnen</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">Songs in Playlist: {{ total_questions }}</span>
<span id="scoreInfo" style="margin-left:20px;">
Richtige: {{ score }} / {{ answered if answered > 0 else 1 }}
({{ ((score / (answered if answered > 0 else 1)) * 100) | round(0) if answered > 0 else 0 }}%)
</span>
</div>
<div style="text-align:center; margin-bottom: 20px;">
<a href="/reset_quiz/{{ playlist_id }}" class="btn btn-danger" style="margin-top:10px;">Quiz beenden</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>Abspielzeit:
<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>Unendlich</option>
</select>
</label>
<label style="margin-left:20px;">Startposition:
<select id="startPosition" onchange="setOption('startPosition', this.value)">
<option value="start" selected>Anfang</option>
<option value="random">Zufällig</option>
</select>
</label>
</div>
<!-- Player Controls -->
<div class="controls" style="text-align: center;">
<button id="playPauseBtn" class="btn" onclick="togglePlay()">⏸️ 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>