team-9/testing/script.js
2025-08-02 04:07:17 +02:00

377 lines
No EOL
13 KiB
JavaScript

const API_BASE_URL = 'https://fbbb261497e3.ngrok-free.app';
// Funzione per mostrare messaggi di status
function showStatus(message, isSuccess = true) {
const statusDiv = document.getElementById('status');
statusDiv.innerHTML = `<div class="status ${isSuccess ? 'success' : 'error'}">${message}</div>`;
}
// Funzione per mostrare i risultati
function showResult(data) {
const resultDiv = document.getElementById('result');
resultDiv.style.display = 'block';
resultDiv.textContent = JSON.stringify(data, null, 2);
}
// GET: Ottiene dati dal database
async function getData() {
try {
console.log('📥 Richiesta GET in corso...');
showStatus('📥 Richiesta GET in corso...', true);
const response = await fetch(`${API_BASE_URL}/api/data`);
const data = await response.json();
if (response.ok) {
showStatus('✅ Dati ottenuti con successo!', true);
showResult(data);
} else {
showStatus(`❌ Errore: ${data.detail || 'Errore sconosciuto'}`, false);
}
} catch (error) {
console.error('Errore GET:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// POST: Inserisce dati nel database
async function createData() {
try {
console.log('📤 Richiesta POST in corso...');
showStatus('📤 Richiesta POST in corso...', true);
const response = await fetch(`${API_BASE_URL}/api/data`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
const data = await response.json();
if (response.ok) {
showStatus('✅ Dato inserito con successo!', true);
showResult(data);
} else {
showStatus(`❌ Errore: ${data.detail || 'Errore sconosciuto'}`, false);
}
} catch (error) {
console.error('Errore POST:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// POST: Inserisce coordinate nel database
async function createCoordinates() {
try {
console.log('📍 Richiesta POST coordinate in corso...');
showStatus('📍 Richiesta POST coordinate in corso...', true);
coordinates = {
"coords": [123.12,456.78],
}
const response = await fetch(`${API_BASE_URL}/geo-access`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(coordinates)
});
const data = await response.json();
if (response.ok) {
showStatus('✅ Coordinate inserite con successo!', true);
showResult(data);
} else {
showStatus(`❌ Errore: ${data.detail || 'Errore sconosciuto'}`, false);
}
} catch (error) {
console.error('Errore POST coordinate:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// Check GPS Location
async function checkGPSLocation() {
try {
console.log('🌍 Richiesta coordinate GPS...');
showStatus('🌍 Richiesta coordinate GPS...', true);
// Ottieni coordinate GPS
const position = await getCurrentPosition();
const { latitude, longitude } = position.coords;
console.log(`📍 Coordinate GPS: ${latitude}, ${longitude}`);
showStatus(`📍 Coordinate GPS ottenute: ${latitude.toFixed(6)}, ${longitude.toFixed(6)}`, true);
// Chiama la route geo-access/real
const coordinates = {
"coords": [latitude, longitude]
};
const response = await fetch(`${API_BASE_URL}/geo-access/real`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(coordinates)
});
const data = await response.json();
if (response.ok) {
const result = data.success ? '✅ DENTRO' : '❌ FUORI';
showStatus(`${result} - Sei ${data.success ? 'dentro' : 'fuori'} dal raggio di 2000 metri!`, data.success);
showResult(data);
} else {
showStatus(`❌ Errore: ${data.detail || 'Errore sconosciuto'}`, false);
}
} catch (error) {
console.error('Errore GPS:', error);
showStatus(`❌ Errore GPS: ${error.message}`, false);
}
}
// Funzione per ottenere la posizione GPS
function getCurrentPosition() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error('Geolocalizzazione non supportata'));
return;
}
navigator.geolocation.getCurrentPosition(
(position) => resolve(position),
(error) => reject(new Error(`Errore GPS: ${error.message}`)),
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 60000
}
);
});
}
// Send Molinella coordinates
async function sendMolinellaCoordinates() {
try {
console.log('🏘️ Invio coordinate Molinella...');
showStatus('🏘️ Invio coordinate Molinella...', true);
// Coordinate hardcoded di Molinella
const coordinates = {
"coords": [44.61758, 11.66719]
};
console.log(`📍 Coordinate Molinella: ${coordinates.coords[0]}, ${coordinates.coords[1]}`);
showStatus(`📍 Coordinate Molinella: ${coordinates.coords[0]}, ${coordinates.coords[1]}`, true);
// Chiama la route geo-access/real
const response = await fetch(`${API_BASE_URL}/geo-access/real`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(coordinates)
});
const data = await response.json();
if (response.ok) {
const result = data.success ? '✅ DENTRO' : '❌ FUORI';
showStatus(`${result} - Molinella è ${data.success ? 'dentro' : 'fuori'} dal raggio di 50 metri!`, data.success);
showResult(data);
} else {
showStatus(`❌ Errore: ${data.detail || 'Errore sconosciuto'}`, false);
}
} catch (error) {
console.error('Errore Molinella:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// Queue CRUD Operations
// Add song to queue
async function addQueueItem() {
try {
console.log('🎵 Aggiunta canzone alla queue...');
showStatus('🎵 Aggiunta canzone alla queue...', true);
// Canzone hardcoded
const song = {
"titolo": "Bohemian Rhapsody",
"coverUrl": "https://i.scdn.co/image/abc123",
"color": "#3b5998",
"artista": "Queen",
"voti": 0
};
const response = await fetch(`${API_BASE_URL}/queue/add`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(song)
});
const data = await response.json();
if (response.ok) {
showStatus('✅ Canzone aggiunta alla queue!', true);
showResult(data);
} else {
showStatus(`❌ Errore: ${data.detail || 'Errore sconosciuto'}`, false);
}
} catch (error) {
console.error('Errore aggiunta canzone:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// Read queue
async function readQueue() {
try {
console.log('📋 Lettura queue...');
showStatus('📋 Lettura queue...', true);
const response = await fetch(`${API_BASE_URL}/queue/read`);
const data = await response.json();
if (response.ok) {
showStatus(`✅ Queue letta! ${data.count} canzoni trovate`, true);
showResult(data);
} else {
showStatus(`❌ Errore: ${data.detail || 'Errore sconosciuto'}`, false);
}
} catch (error) {
console.error('Errore lettura queue:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// Vote up (incrementa voti)
async function voteUp() {
try {
console.log('👍 Voto positivo...');
showStatus('👍 Voto positivo...', true);
// Per semplicità, vota il primo item della queue
const response = await fetch(`${API_BASE_URL}/queue/read`);
const queueData = await response.json();
if (response.ok && queueData.data.length > 0) {
const firstItemId = queueData.data[0].id;
const voteResponse = await fetch(`${API_BASE_URL}/queue/vote/${firstItemId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ "increment": true })
});
const voteData = await voteResponse.json();
if (voteResponse.ok) {
showStatus('✅ Voto positivo aggiunto!', true);
showResult(voteData);
} else {
showStatus(`❌ Errore: ${voteData.detail || 'Errore sconosciuto'}`, false);
}
} else {
showStatus('❌ Nessuna canzone nella queue da votare', false);
}
} catch (error) {
console.error('Errore voto positivo:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// Vote down (decrementa voti)
async function voteDown() {
try {
console.log('👎 Voto negativo...');
showStatus('👎 Voto negativo...', true);
// Per semplicità, vota il primo item della queue
const response = await fetch(`${API_BASE_URL}/queue/read`);
const queueData = await response.json();
if (response.ok && queueData.data.length > 0) {
const firstItemId = queueData.data[0].id;
const voteResponse = await fetch(`${API_BASE_URL}/queue/vote/${firstItemId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ "increment": false })
});
const voteData = await voteResponse.json();
if (voteResponse.ok) {
showStatus('✅ Voto negativo aggiunto!', true);
showResult(voteData);
} else {
showStatus(`❌ Errore: ${voteData.detail || 'Errore sconosciuto'}`, false);
}
} else {
showStatus('❌ Nessuna canzone nella queue da votare', false);
}
} catch (error) {
console.error('Errore voto negativo:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// Delete item from queue
async function deleteQueueItem() {
try {
console.log('🗑️ Eliminazione item dalla queue...');
showStatus('🗑️ Eliminazione item dalla queue...', true);
// Per semplicità, elimina il primo item della queue
const response = await fetch(`${API_BASE_URL}/queue/read`);
const queueData = await response.json();
if (response.ok && queueData.data.length > 0) {
const firstItemId = queueData.data[0].id;
const deleteResponse = await fetch(`${API_BASE_URL}/queue/delete/${firstItemId}`, {
method: 'DELETE'
});
const deleteData = await deleteResponse.json();
if (deleteResponse.ok) {
showStatus('✅ Item eliminato dalla queue!', true);
showResult(deleteData);
} else {
showStatus(`❌ Errore: ${deleteData.detail || 'Errore sconosciuto'}`, false);
}
} else {
showStatus('❌ Nessuna canzone nella queue da eliminare', false);
}
} catch (error) {
console.error('Errore eliminazione item:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// Test di connessione all'avvio
window.addEventListener('load', async () => {
try {
const response = await fetch(`${API_BASE_URL}/`);
if (response.ok) {
console.log('✅ Backend connesso!');
} else {
console.log('❌ Backend non raggiungibile');
}
} catch (error) {
console.log('❌ Backend non raggiungibile:', error.message);
}
});