setInterval(getState, 4000); setInterval(updateProgress, 500); // Update progress every second // Get the
  • elements var liElements = document.querySelectorAll('ul li'); var lastChange = 0; var lastStateUpdateTime = Date.now(); var songStartTime = 0; var currentSongLength = 0; var isPlaying = false; var userIsInteracting = false; // Flag to track user interaction with the slider // Add click event listener to each
  • element liElements.forEach(function(li) { li.addEventListener('click', function() { //var liText = this.innerText; var id = this.dataset.id; playSongById(id); }); }); function simpleGetCall(endpoint) { var xhr = new XMLHttpRequest(); xhr.open("GET", "/" + endpoint, true); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { getState(); // Fetch the latest state right after the button action } }; xhr.send(); } function postValue(endpoint,value) { var xhr = new XMLHttpRequest(); xhr.open("POST", "/" + endpoint, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); xhr.send("value="+encodeURIComponent(value)); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { getState(); // Fetch the latest state right after the button action } }; } function getState() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { var state = JSON.parse(xhr.response); isPlaying = state['playing']; if (isPlaying) { songStartTime = Date.now() - state['time'] * 1000; currentSongLength = state['length'] * 1000; } lastStateUpdateTime = Date.now(); displayState(state); } } xhr.open("GET","/state", true); xhr.send(); } function updateProgress() { if (isPlaying && !userIsInteracting) { // Check if user is not interacting var elapsedTime = Date.now() - songStartTime; if (elapsedTime >= currentSongLength) { elapsedTime = currentSongLength; isPlaying = false; // Stop updating if the song has ended } var progressElement = document.getElementById('progressSlider'); progressElement.value = elapsedTime / 1000; // Convert to seconds document.getElementById("progressLabel").innerHTML = Math.floor(elapsedTime / 1000); } } function displayState(state) { var title = state['title'] || '—'; var titleEl = document.getElementById("state"); if (titleEl) titleEl.innerHTML = title; var bigTitleEl = document.getElementById("stateTitle"); if (bigTitleEl) bigTitleEl.innerText = title; var progressLabel = document.getElementById("progressLabel"); if (progressLabel) progressLabel.innerHTML = state['time']; var progressMax = document.getElementById("progressMax"); if (progressMax) progressMax.innerHTML = state['length'] || 0; var voltageEl = document.getElementById("voltage"); if (voltageEl) voltageEl.innerHTML = (state['voltage'] || '') + ' mV'; var heapEl = document.getElementById("heap"); if (heapEl) heapEl.innerHTML = (state['heap'] || '') + ' bytes free heap'; var uidEl = document.getElementById("uid"); if (uidEl) uidEl.innerHTML = 'Last NFC ID: ' + (state['uid'] || ''); /* ==== Autofill convenience fields ==== */ var fm = document.getElementById('fileManager'); if (state['filepath'] && fm && fm.style.display == 'none') { var moveFrom = document.getElementById('moveFrom'); var deleteFileName = document.getElementById('deleteFileName'); var song = document.getElementById('song'); if (moveFrom) moveFrom.value = state['filepath']; if (deleteFileName) deleteFileName.value = state['filepath']; if (song) song.value = state['filepath']; } if (state['uid']) { var rfidEl = document.getElementById('rfid'); if (rfidEl) rfidEl.value = state['uid']; } var btn = document.querySelector('.play-button'); if (btn) { if (state['playing']) { btn.classList.add('paused'); } else { btn.classList.remove('paused'); } } if (Date.now()-lastChange>1200) { var progress = document.getElementById('progressSlider'); if (progress) { progress.value = state['time']; progress.max = state['length']; } var volume = document.getElementById('volumeSlider'); if (volume) volume.value = state['volume']; } updateProgress(); } function playSongById(id) { var url = "/playbyid"; var params = "id="+id; var http = new XMLHttpRequest(); http.open("GET", url+"?"+params, true); http.onreadystatechange = function() { if(http.readyState == 4 && http.status == 200) { getState(); } } http.send(null); } function playNamedSong(song) { var xhr = new XMLHttpRequest(); xhr.open("POST", "/playnamed"); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); //application/x-www-form-urlencoded var body = song; xhr.send("title="+encodeURIComponent(body)); } function editMapping() { var rfid = document.getElementById('rfid').value; var song = document.getElementById('song').value; var modeEl = document.getElementById('mode'); var mode = modeEl ? modeEl.value : 's'; var xhr = new XMLHttpRequest(); xhr.open("POST", "/edit_mapping", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); xhr.send("rfid=" + encodeURIComponent(rfid) + "&song=" + encodeURIComponent(song) + "&mode=" + encodeURIComponent(mode)); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { alert("Mapping updated successfully!"); } else if (xhr.readyState === 4) { alert("Failed to update mapping: " + (xhr.responseText || xhr.status)); } }; } // Validate file before upload function validateFile(file) { var maxSize = 50 * 1024 * 1024; // 50MB limit var allowedTypes = ['audio/mpeg', 'audio/wav', 'audio/flac', 'audio/mp4', 'audio/ogg']; var allowedExtensions = ['.mp3', '.wav', '.flac', '.m4a', '.ogg']; if (file.size > maxSize) { return 'File too large. Maximum size is 50MB.'; } var fileName = file.name.toLowerCase(); var hasValidExtension = allowedExtensions.some(ext => fileName.endsWith(ext)); if (!hasValidExtension) { return 'Invalid file type. Only audio files (.mp3, .wav, .flac, .m4a, .ogg) are allowed.'; } return null; // No error } // Handle form submission with AJAX to show upload status document.getElementById('uploadForm').addEventListener('submit', function(event) { event.preventDefault(); // Prevent the default form submit var fileInput = document.getElementById('uploadFile'); var file = fileInput.files[0]; if (!file) { alert('Please select a file to upload.'); return; } var validationError = validateFile(file); if (validationError) { alert(validationError); return; } var form = event.target; var formData = new FormData(form); var uploadButton = document.getElementById('uploadButton'); var uploadStatus = document.getElementById('uploadStatus'); var uploadProgress = document.getElementById('uploadProgress'); var progressFill = document.getElementById('progressFill'); var progressText = document.getElementById('progressText'); // Disable upload button and show progress uploadButton.disabled = true; uploadButton.value = 'Uploading...'; uploadProgress.style.display = 'block'; uploadStatus.innerHTML = 'Preparing upload...'; var xhr = new XMLHttpRequest(); xhr.open('POST', '/upload', true); xhr.upload.onloadstart = function() { uploadStatus.innerHTML = 'Upload started...'; }; xhr.upload.onprogress = function(event) { if (event.lengthComputable) { var percentComplete = Math.round((event.loaded / event.total) * 100); progressFill.style.width = percentComplete + '%'; progressText.innerHTML = percentComplete + '%'; uploadStatus.innerHTML = 'Uploading: ' + percentComplete + '% (' + Math.round(event.loaded / 1024) + 'KB / ' + Math.round(event.total / 1024) + 'KB)'; } }; xhr.upload.onerror = function() { uploadStatus.innerHTML = 'Upload failed due to network error.'; resetUploadForm(); }; xhr.upload.onabort = function() { uploadStatus.innerHTML = 'Upload was cancelled.'; resetUploadForm(); }; xhr.onreadystatechange = function() { if (xhr.readyState === 4) { // Request is done if (xhr.status >= 200 && xhr.status < 300) { // Success status code range uploadStatus.innerHTML = 'Upload completed successfully!'; progressFill.style.width = '100%'; progressText.innerHTML = '100%'; setTimeout(function() { alert('File uploaded successfully!'); location.reload(); // Reload to get updated playlist }, 1000); } else { var errorMsg = xhr.responseText || 'Unknown error occurred'; uploadStatus.innerHTML = 'Upload failed: ' + errorMsg; alert('Upload failed: ' + errorMsg); resetUploadForm(); } } }; xhr.send(formData); // Send the form data using XMLHttpRequest }); function resetUploadForm() { var uploadButton = document.getElementById('uploadButton'); var uploadProgress = document.getElementById('uploadProgress'); var progressFill = document.getElementById('progressFill'); var progressText = document.getElementById('progressText'); uploadButton.disabled = false; uploadButton.value = 'Upload'; uploadProgress.style.display = 'none'; progressFill.style.width = '0%'; progressText.innerHTML = '0%'; // Clear file input document.getElementById('uploadFile').value = ''; } /* ================= File Manager Functions ================= */ function toggleFileManager() { var fm = document.getElementById('fileManager'); if (fm.style.display === 'none' || fm.style.display === '') { fm.style.display = 'block'; } else { fm.style.display = 'none'; } } function moveFile() { var from = document.getElementById('moveFrom').value.trim(); var to = document.getElementById('moveTo').value.trim(); if (!from || !to) { alert('Please provide both source and destination paths.'); return; } var xhr = new XMLHttpRequest(); xhr.open('GET', '/move_file?from=' + encodeURIComponent(from) + '&to=' + encodeURIComponent(to), true); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { alert('File moved successfully.'); location.reload(); } else { alert('Move failed: ' + (xhr.responseText || 'Unknown error')); } } }; xhr.send(); } function deleteFileOnServer() { var filename = document.getElementById('deleteFileName').value.trim(); if (!filename) { alert('Please provide filename to delete.'); return; } if (!confirm('Are you sure you want to delete ' + filename + '?')) { return; } var xhr = new XMLHttpRequest(); xhr.open('GET', '/delete_file?filename=' + encodeURIComponent(filename), true); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { alert('File deleted successfully.'); location.reload(); } else { alert('Delete failed: ' + (xhr.responseText || 'Unknown error')); } } }; xhr.send(); } /* Ensure the site stylesheet loads reliably — retry loader if necessary Improved detection: verify a computed style from CSS is applied (safer than just checking stylesheet href). Retries with exponential backoff and deduplicates link tags we add. */ (function ensureCssLoaded(){ var retries = 0; var maxRetries = 6; // Check a computed style that the stylesheet defines. // .status color in CSS is --muted: #6b7280 -> rgb(107, 114, 128) function isStyleApplied() { var el = document.querySelector('.status') || document.querySelector('.topbar'); if (!el) return false; try { var color = getComputedStyle(el).color; // Expect "rgb(107, 114, 128)" when CSS is applied if (!color) return false; // Loose check for the three numeric components to be present return color.indexOf('107') !== -1 && color.indexOf('114') !== -1 && color.indexOf('128') !== -1; } catch (e) { return false; } } function removeOldRetryLinks() { var links = Array.prototype.slice.call(document.querySelectorAll('link[data-retry-css]')); links.forEach(function(l){ l.parentNode.removeChild(l); }); } function tryLoad() { if (isStyleApplied()) { console.log('style.css appears applied'); return; } if (retries >= maxRetries) { console.warn('style.css failed to apply after ' + retries + ' attempts'); return; } retries++; // Remove previous retry-inserted links to avoid piling them up removeOldRetryLinks(); var link = document.createElement('link'); link.rel = 'stylesheet'; link.setAttribute('data-retry-css', '1'); // cache-busting query to force a fresh fetch when retrying link.href = 'style.css?cb=' + Date.now(); var timeout = 800 + retries * 300; // increasing timeout per attempt var done = false; function success() { if (done) return; done = true; // Give browser a short moment to apply rules setTimeout(function(){ if (isStyleApplied()) { console.log('style.css loaded and applied (attempt ' + retries + ')'); } else { console.warn('style.css loaded but styles not applied — retrying...'); setTimeout(tryLoad, timeout); } }, 200); } link.onload = success; link.onerror = function() { if (done) return; done = true; console.warn('style.css load error (attempt ' + retries + '), retrying...'); setTimeout(tryLoad, timeout); }; // Append link to head document.head.appendChild(link); // Safety check: if onload/onerror doesn't fire, verify computed style after timeout setTimeout(function(){ if (done) return; if (isStyleApplied()) { console.log('style.css appears applied (delayed check)'); } else { console.warn('style.css still not applied after timeout (attempt ' + retries + '), retrying...'); setTimeout(tryLoad, timeout); } }, timeout + 300); } // Start after a short delay to let the browser initiate initial requests setTimeout(tryLoad, 150); })();