// script.js - Versione con conferma email let currentUser = null; function checkSession() { const userJson = localStorage.getItem('currentUser'); if (userJson) { currentUser = JSON.parse(userJson); // Verifica se l'utente è verificato if (!currentUser.verified) { alert('Il tuo account non è ancora stato verificato. Controlla la tua email.'); localStorage.removeItem('currentUser'); window.location.href = 'login.html'; return; } const userInfo = document.getElementById('userInfo'); if (userInfo) { userInfo.innerHTML = 'Ciao ' + (currentUser.fullName || currentUser.email) + ''; } if (document.getElementById('videoList')) { loadMyVideos(); } } else { const currentPage = window.location.pathname; if (!currentPage.includes('login.html') && !currentPage.includes('register.html') && !currentPage.includes('verify.php')) { window.location.href = 'login.html'; } } } // CAPTCHA dinamico function generateCaptcha() { const num1 = Math.floor(Math.random() * 10) + 1; const num2 = Math.floor(Math.random() * 10) + 1; const ops = ['+', '-']; const op = ops[Math.floor(Math.random() * ops.length)]; let answer; let question; if (op === '+') { answer = num1 + num2; question = num1 + ' + ' + num2; } else { const a = Math.max(num1, num2); const b = Math.min(num1, num2); answer = a - b; question = a + ' - ' + b; } const label = document.getElementById('captchaQuestion'); if (label) { label.textContent = 'Quanto fa ' + question + '? (verifica anti-spam)'; } const hidden = document.getElementById('captchaAnswer'); if (hidden) { hidden.value = answer; } } // Registrazione const registerForm = document.getElementById('registerForm'); if (registerForm) { generateCaptcha(); registerForm.addEventListener('submit', async (e) => { e.preventDefault(); const fullName = document.getElementById('fullName').value; const email = document.getElementById('email').value; const password = document.getElementById('password').value; const confirmPassword = document.getElementById('confirm_password').value; const waiverAccepted = document.getElementById('waiverAccepted').checked; const captcha = document.getElementById('captcha').value; const captchaAnswer = document.getElementById('captchaAnswer').value; // Validazioni if (password !== confirmPassword) { alert('Le password non coincidono'); return; } if (password.length < 8) { alert('La password deve essere di almeno 8 caratteri'); return; } if (!/[A-Z]/.test(password)) { alert('La password deve contenere almeno una lettera maiuscola'); return; } if (!/[a-z]/.test(password)) { alert('La password deve contenere almeno una lettera minuscola'); return; } if (!/[0-9]/.test(password)) { alert('La password deve contenere almeno un numero'); return; } if (!waiverAccepted) { alert('Devi accettare la dichiarazione di rinuncia'); return; } if (parseInt(captcha) !== parseInt(captchaAnswer)) { alert('Risposta errata alla domanda di sicurezza'); generateCaptcha(); return; } // Verifica se email esiste già let users = JSON.parse(localStorage.getItem('users') || '[]'); if (users.find(u => u.email === email)) { alert('Email già registrata'); return; } // Crea token di verifica const verificationToken = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); const newUser = { id: Date.now(), email: email, password: btoa(password), fullName: fullName, verified: false, verificationToken: verificationToken, waiverSigned: true, waiverDate: new Date().toISOString(), createdAt: new Date().toISOString() }; users.push(newUser); localStorage.setItem('users', JSON.stringify(users)); // Salva waiver const waivers = JSON.parse(localStorage.getItem('waivers') || '[]'); waivers.push({ userId: newUser.id, email: email, fullName: fullName, signedAt: new Date().toISOString() }); localStorage.setItem('waivers', JSON.stringify(waivers)); // Invia email di verifica try { const response = await fetch('send_verification.php', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ email: email, name: fullName, token: verificationToken, userId: newUser.id, password: newUser.password }) }); const result = await response.json(); if (result.success) { alert('Registrazione completata! Ti abbiamo inviato una email di verifica. Clicca sul link per attivare il tuo account.'); window.location.href = 'login.html'; } else { alert('Registrazione completata ma non è stato possibile inviare l\'email di verifica. Contatta l\'amministratore.'); console.error('Errore invio email:', result.error); } } catch (error) { console.error('Errore:', error); alert('Registrazione completata! Contatta l\'amministratore per attivare il tuo account.'); window.location.href = 'login.html'; } }); } // Login const loginForm = document.getElementById('loginForm'); if (loginForm) { loginForm.addEventListener('submit', async (e) => { e.preventDefault(); const email = document.getElementById('email').value; const password = btoa(document.getElementById('password').value); let users = JSON.parse(localStorage.getItem('users') || '[]'); let user = users.find(u => u.email === email && u.password === password); if (!user) { try { const resp = await fetch('api_get_user.php', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({email: email, password: password}) }); const result = await resp.json(); if (result.found && result.user) { user = result.user; users.push(user); localStorage.setItem('users', JSON.stringify(users)); } } catch (e) { console.error('Errore fetch utente:', e); } } if (user) { if (!user.verified) { alert('Account non verificato. Controlla la tua email per il link di attivazione.'); return; } localStorage.setItem('currentUser', JSON.stringify(user)); alert('Login effettuato!'); window.location.href = 'index.html'; } else { alert('Credenziali non valide'); } }); } // Upload video const selectVideoBtn = document.getElementById('selectVideoBtn'); const videoInput = document.getElementById('videoInput'); const uploadBtn = document.getElementById('uploadBtn'); const fileName = document.getElementById('fileName'); if (selectVideoBtn) { selectVideoBtn.addEventListener('click', function() { videoInput.click(); }); } if (videoInput) { videoInput.addEventListener('change', function(e) { const file = e.target.files[0]; if (file && file.type.startsWith('video/')) { fileName.textContent = 'Video selezionato: ' + file.name + ' (' + (file.size / 1024 / 1024).toFixed(2) + ' MB)'; uploadBtn.disabled = false; } else { alert('Seleziona un file video valido'); uploadBtn.disabled = true; } }); } if (uploadBtn) { uploadBtn.addEventListener('click', async function() { const file = videoInput.files[0]; const userJson = localStorage.getItem('currentUser'); if (!userJson) { alert('Devi effettuare il login'); window.location.href = 'login.html'; return; } currentUser = JSON.parse(userJson); if (!currentUser.verified) { alert('Il tuo account non è verificato. Controlla la tua email.'); return; } if (!file) { alert('Seleziona un video'); return; } const formData = new FormData(); formData.append('video', file); const userTokenData = { id: currentUser.id, email: currentUser.email, fullName: currentUser.fullName || currentUser.email.split('@')[0] }; const token = btoa(JSON.stringify(userTokenData)); formData.append('token', token); const progressBar = document.getElementById('progressBar'); const progressFill = document.querySelector('.progress-fill'); if (progressBar) progressBar.style.display = 'block'; if (progressFill) progressFill.style.width = '0%'; try { const xhr = new XMLHttpRequest(); xhr.open('POST', 'upload.php', true); xhr.upload.onprogress = function(e) { if (e.lengthComputable && progressFill) { const percent = (e.loaded / e.total) * 100; progressFill.style.width = percent + '%'; progressFill.textContent = Math.round(percent) + '%'; } }; xhr.onload = function() { if (xhr.status === 200) { try { const response = JSON.parse(xhr.responseText); if (response.success) { alert('Video caricato con successo!'); videoInput.value = ''; fileName.textContent = ''; uploadBtn.disabled = true; loadMyVideos(); } else { alert('Errore: ' + (response.error || 'Sconosciuto')); } } catch(e) { alert('Risposta server non valida'); } } else { alert('Errore durante l\'upload (Status: ' + xhr.status + ')'); } if (progressBar) progressBar.style.display = 'none'; if (progressFill) progressFill.style.width = '0%'; }; xhr.onerror = function() { alert('Errore di connessione al server'); if (progressBar) progressBar.style.display = 'none'; }; xhr.send(formData); } catch (error) { alert('Errore: ' + error.message); if (progressBar) progressBar.style.display = 'none'; } }); } // Carica video dell'utente async function loadMyVideos() { const userJson = localStorage.getItem('currentUser'); if (!userJson) return; const currentUserData = JSON.parse(userJson); const container = document.getElementById('videoList'); if (!container) return; try { const response = await fetch('get_videos.php?userId=' + currentUserData.id); const videos = await response.json(); if (videos.length === 0) { container.innerHTML = '
Nessun video caricato
'; return; } let html = ''; for (let i = 0; i < videos.length; i++) { const video = videos[i]; let displayName = video.savedFileName || video.originalFileName || 'Video'; html += '';
html += '' + escapeHtml(displayName) + '
';
html += 'Data: ' + new Date(video.uploadDate).toLocaleString() + '
';
html += 'Dimensione: ' + (video.fileSize / 1024 / 1024).toFixed(2) + ' MB';
html += '
Errore nel caricamento dei video
'; } } function escapeHtml(text) { if (!text) return 'Video senza nome'; return text.replace(/[&<>]/g, function(m) { if (m === '&') return '&'; if (m === '<') return '<'; if (m === '>') return '>'; return m; }); } // Logout const logoutBtn = document.getElementById('logoutBtn'); if (logoutBtn) { logoutBtn.addEventListener('click', function() { localStorage.removeItem('currentUser'); window.location.href = 'login.html'; }); } checkSession();