Update public/admin/script.js
Browse files1234567891011121314151617181920212223242526272829303 unmodified lines3435363738394041424344454647484950515253545556575859606162633 unmodified lines67686970717273747576777879808182834 unmodified lines888990919293942 unmodified lines9798991001011021034 unmodified lines10810911011111211324 unmodified lines13813914014114214314414525 unmodified lines1711721731741751761771781791801811821831841851861871881895 unmodified lines1951961971981992002012022032 unmodified lines20620720820921021121221316 unmodified lines2302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812821 unmodified line2842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623631 unmodified line3653663673683693703712 unmodified lines3743753763773783793804 unmodified lines38538638738838939039139239339439539639739839940014 unmodified lines4154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444459 unmodified lines4554564574584594604612 unmodified lines4644654664674684694704714724734744754764774782 unmodified lines481482483484485486487488489490491492493494495496497498499500501// βββ DISPATCH Admin Script ββββββββββββββββββββββββββββββββββββββββββββββββββββ// All state is received from and pushed to the server via WebSocket only.// No GET/POST for data; only file loading uses HTTP.// βββ State ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββlet state = {sounds: [], // [{ id, name, data }]notifications: [], // [{ id, name, heading, body, hyperlink, displayed, soundId }]devices: [], // [{ uuid, name, notifications, lastConnection, schedule, pendingChanges, online }]};let selectedNotifId = null;let selectedDeviceUUID = null;let nowIntervalId = null;let pendingSoundFile = null; // { name: str, data: base64 }let ws = null;let reconnectTimer = null;// βββ WebSocket ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction connect() {const proto = location.protocol === 'https:' ? 'wss' : 'wss';ws = new WebSocket(`${proto}://${location.host}/admin-ws`);ws.addEventListener('open', () => {setIndicator(true);clearTimeout(reconnectTimer);});ws.addEventListener('message', (e) => {3 unmodified lines});ws.addEventListener('close', () => {setIndicator(false);reconnectTimer = setTimeout(connect, 3000);});ws.addEventListener('error', () => ws.close());}function send(msg) {if (ws && ws.readyState === WebSocket.OPEN) {ws.send(JSON.stringify(msg));}}function setIndicator(online) {const dot = document.getElementById('ws-indicator');const label = document.getElementById('ws-label');dot.className = `indicator ${online ? 'online' : 'offline'}`;label.textContent = online ? 'LIVE' : 'OFFLINE';}// βββ Message Handling βββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction handleMessage(msg) {switch (msg.type) {case 'full_state': {state.sounds = msg.sounds || [];state.notifications = msg.notifications || [];3 unmodified lines}case 'sound_added': {if (!state.sounds.find(s => s.id === msg.sound.id)) {state.sounds.push(msg.sound);}updateSoundSelect();break;}case 'notification_added': {if (!state.notifications.find(n => n.id === msg.notification.id)) {state.notifications.push(msg.notification);}renderNotifList();updateNotifCount();toast('Notification created', 'success');4 unmodified linesstate.devices = msg.devices || [];renderDeviceList();updateDeviceCount();// Refresh device detail if openif (selectedDeviceUUID) {const d = state.devices.find(d => d.uuid === selectedDeviceUUID);if (d) renderDeviceDetail(d);2 unmodified lines}case 'sound_data': {// A sound's full data returned (for preview, etc.)const existing = state.sounds.find(s => s.id === msg.sound.id);if (existing) { existing.data = msg.sound.data; }else { state.sounds.push(msg.sound); }4 unmodified lines}}// βββ Render All βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction renderAll() {updateSoundSelect();24 unmodified lines<div class="notif-item-heading">${esc(n.heading)}</div><div class="notif-item-body">${esc(n.body)}</div>${sound ? `<span class="notif-item-sound">βͺ ${esc(sound.name)}</span>` : ''}</div>`;}).join('');list.querySelectorAll('.notif-item').forEach(el => {25 unmodified linesconst active = document.getElementById('schedule-active');active.style.display = 'flex';active.style.flexDirection = 'column';document.getElementById('selected-notif-name').textContent = notif.heading || notif.name;// Set datetime pickers to nowsetDateTimeToNow();}function setDateTimeToNow() {const now = new Date();const dateStr = now.toISOString().slice(0, 10);const timeStr = now.toTimeString().slice(0, 5);document.getElementById('sched-date').value = dateStr;document.getElementById('sched-time').value = timeStr;}// βββ Devices ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ5 unmodified lines}list.innerHTML = state.devices.map(d => {const sel = d.uuid === selectedDeviceUUID ? 'selected' : '';const lastConn = d.lastConnection? `Last seen ${timeSince(d.lastConnection)}`: 'Active now';return `<div class="device-item ${sel}" data-uuid="${d.uuid}"><span class="indicator ${d.online ? 'online' : 'offline'}"></span>2 unmodified lines<div class="device-item-uuid">${d.uuid.slice(0,18)}β¦</div><div class="device-item-last">${lastConn}</div></div></div>`;}).join('');list.querySelectorAll('.device-item').forEach(el => {16 unmodified linesconst detail = document.getElementById('device-detail');detail.style.display = 'block';// Headerdocument.getElementById('detail-device-name-display').textContent = device.name;document.getElementById('detail-device-uuid').textContent = device.uuid;document.getElementById('device-name-input').value = device.name;const statusEl = document.getElementById('device-status-indicator');statusEl.className = `indicator ${device.online ? 'online' : 'offline'}`;// Cached soundsconst soundsEl = document.getElementById('detail-sounds');const cached = device.cachedSounds || [];if (!cached.length) {soundsEl.innerHTML = '<span style="color:var(--text-dimmer);font-size:12px">None cached</span>';} else {soundsEl.innerHTML = cached.map(sid => {const sound = state.sounds.find(s => s.id === sid);return `<span class="tag"><span class="tag-dot"></span>${esc(sound ? sound.name : sid.slice(0,8))}</span>`;}).join('');}// Notifications tableconst notifsEl = document.getElementById('detail-notifications');const deviceNotifs = device.notifications || [];if (!deviceNotifs.length) {notifsEl.innerHTML = '<div class="empty-state" style="padding:20px 0">No notifications</div>';} else {notifsEl.innerHTML = `<table class="data-table"><thead><tr><th>NAME</th><th>HEADING</th><th>DISPLAYED</th></tr></thead><tbody>${deviceNotifs.map(n => `<tr><td>${esc(n.name)}</td><td>${esc(n.heading)}</td><td style="color:${n.displayed ? 'var(--green)' : 'var(--text-dimmer)'}">${n.displayed ? 'β YES' : 'β NO'}</td></tr>`).join('')}</tbody></table>`;}// Schedule tableconst schedEl = document.getElementById('detail-schedule');1 unmodified lineif (!schedule.length) {schedEl.innerHTML = '<div class="empty-state" style="padding:20px 0">No scheduled notifications</div>';} else {schedEl.innerHTML = `<table class="data-table"><thead><tr><th>NOTIFICATION</th><th>SCHEDULED FOR</th><th>ACTION</th></tr></thead><tbody>${schedule.map(entry => {const notif = state.notifications.find(n => n.id === entry.notificationId);const name = notif ? (notif.heading || notif.name) : entry.notificationId.slice(0,8);const when = new Date(entry.scheduledAt).toLocaleString();return `<tr><td>${esc(name)}</td><td>${when}</td><td><button class="action-btn" data-uuid="${device.uuid}" data-nid="${entry.notificationId}">REMOVE</button></td></tr>`;}).join('')}</tbody></table>`;schedEl.querySelectorAll('.action-btn').forEach(btn => {btn.addEventListener('click', () => {send({type: 'remove_schedule',uuid: btn.dataset.uuid,notificationId: btn.dataset.nid,});toast('Schedule entry removed');});});}}// βββ Form: Create Notification ββββββββββββββββββββββββββββββββββββββββββββββββdocument.getElementById('create-notif-btn').addEventListener('click', () => {const name = document.getElementById('f-name').value.trim();const heading = document.getElementById('f-heading').value.trim();const body = document.getElementById('f-body').value.trim();const hyperlink= document.getElementById('f-hyperlink').value.trim();const soundId = document.getElementById('f-sound').value;if (!name || !heading) {toast('Name and Heading are required', 'error');return;}// If there is a pending sound upload, upload it first, then create notifif (pendingSoundFile) {const { soundName, data } = pendingSoundFile;if (!soundName) { toast('Please enter a name for the sound', 'error'); return; }send({ type: 'create_sound', name: soundName, data });// We'll pick up the soundId from the next sound_added event...// To keep things simple, generate a local temp approach: just warn user to re-selectpendingSoundFile = null;document.getElementById('sound-file-name').textContent = 'No file chosen';document.getElementById('f-sound-name').value = '';toast('Sound uploaded! Select it in the Sound dropdown, then create the notification.', 'success');return;}send({type: 'create_notification',name, heading, body, hyperlink,soundId: soundId || null,});// Clear formdocument.getElementById('f-name').value = '';document.getElementById('f-heading').value = '';document.getElementById('f-body').value = '';1 unmodified linedocument.getElementById('f-sound').value = '';});// βββ Sound File Upload ββββββββββββββββββββββββββββββββββββββββββββββββββββββββdocument.getElementById('sound-upload-btn').addEventListener('click', () => {document.getElementById('f-sound-file').click();});2 unmodified linesconst file = e.target.files[0];if (!file) return;document.getElementById('sound-file-name').textContent = file.name;const reader = new FileReader();reader.onload = (evt) => {const base64 = evt.target.result.split(',')[1];4 unmodified lines});document.getElementById('f-sound-name').addEventListener('input', () => {if (pendingSoundFile) {pendingSoundFile.soundName = document.getElementById('f-sound-name').value.trim();}});// βββ Play Now Button ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdocument.getElementById('play-now-btn').addEventListener('click', () => {if (!selectedNotifId) return;// Play on ALL devices β or if a device is selected in devices tab, just that one// Here we play on all connected devicesfor (const device of state.devices) {send({ type: 'play_now', uuid: device.uuid, notificationId: selectedNotifId });}14 unmodified lines}});// βββ Schedule Button ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdocument.getElementById('schedule-btn').addEventListener('click', () => {if (!selectedNotifId) return;const dateVal = document.getElementById('sched-date').value;const timeVal = document.getElementById('sched-time').value;if (!dateVal || !timeVal) { toast('Select a date and time', 'error'); return; }const scheduledAt = new Date(`${dateVal}T${timeVal}`).getTime();if (isNaN(scheduledAt)) { toast('Invalid date/time', 'error'); return; }// Schedule on ALL devices, or just selected deviceconst targets = selectedDeviceUUID? state.devices.filter(d => d.uuid === selectedDeviceUUID): state.devices;if (!targets.length) { toast('No devices to schedule on', 'error'); return; }for (const device of targets) {send({type: 'schedule_notification',uuid: device.uuid,notificationId: selectedNotifId,scheduledAt,});}toast(`Scheduled on ${targets.length} device(s)`, 'success');});9 unmodified lines});});// βββ Device Name Save βββββββββββββββββββββββββββββββββββββββββββββββββββββββββdocument.getElementById('device-name-save').addEventListener('click', () => {if (!selectedDeviceUUID) return;const name = document.getElementById('device-name-input').value.trim();2 unmodified linestoast('Name updated', 'success');});// βββ Toast ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββlet toastTimer;function toast(msg, type = '') {let el = document.getElementById('toast');if (!el) {el = document.createElement('div');el.id = 'toast';document.body.appendChild(el);}el.textContent = msg;el.className = type ? `show ${type}` : 'show';clearTimeout(toastTimer);2 unmodified lines// βββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction esc(str) {return String(str || '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');}function timeSince(ts) {const diff = Date.now() - ts;if (diff < 60000) return `${Math.floor(diff/1000)}s ago`;if (diff < 3600000) return `${Math.floor(diff/60000)}m ago`;if (diff < 86400000) return `${Math.floor(diff/3600000)}h ago`;return `${Math.floor(diff/86400000)}d ago`;}// βββ Boot βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββsetDateTimeToNow();connect();1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465663 unmodified lines7071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251263 unmodified lines1301311321331341351361371381391401411421434 unmodified lines1481491501511521532 unmodified lines1561571581591601614 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321424 unmodified lines23924024124224324424525 unmodified lines2712722732742752762772782792802812822832845 unmodified lines2902912922932942952962 unmodified lines29930030130230330430516 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523531 unmodified line3553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014021 unmodified line4044054064074084092 unmodified lines4124134144154164174 unmodified lines42242342442542642742842943043143243314 unmodified lines4484494504514524534544554564574584594604614624634644654664679 unmodified lines4774784794804814824832 unmodified lines4864874884894904914924934944954964974984995005015025035042 unmodified lines507508509510511512513514515516517518519520521522// βββ DISPATCH Admin Script ββββββββββββββββββββββββββββββββββββββββββββββββββββconst SESSION_KEY = 'dispatch_session_token';// βββ State ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββlet state = {sounds: [],notifications: [],devices: [],};let selectedNotifId = null;let selectedDeviceUUID = null;let nowIntervalId = null;let pendingSoundFile = null;let ws = null;let reconnectTimer = null;let authenticated = false;// βββ UI Refs ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββconst loginScreen = document.getElementById('login-screen');const appEl = document.getElementById('app');const loginBtn = document.getElementById('login-btn');const loginPwInput = document.getElementById('login-password');const loginError = document.getElementById('login-error');const loginForm = document.getElementById('login-form');const loginConnecting = document.getElementById('login-connecting');// βββ Auth Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction getToken() { return sessionStorage.getItem(SESSION_KEY); }function setToken(t) { sessionStorage.setItem(SESSION_KEY, t); }function clearToken() { sessionStorage.removeItem(SESSION_KEY); }function showApp() {loginScreen.style.display = 'none';appEl.style.display = 'block';authenticated = true;}function showLogin(errorMsg) {appEl.style.display = 'none';loginScreen.style.display = 'flex';authenticated = false;loginForm.style.display = 'block';loginConnecting.style.display = 'none';loginPwInput.value = '';loginError.textContent = errorMsg || '';}function setLoginLoading(loading) {loginForm.style.display = loading ? 'none' : 'block';loginConnecting.style.display = loading ? 'flex' : 'none';}// βββ WebSocket ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction connect() {clearTimeout(reconnectTimer);const proto = location.protocol === 'https:' ? 'wss' : 'ws';ws = new WebSocket(`${proto}://${location.host}/admin-ws`);ws.addEventListener('open', () => {// Server will immediately send auth_required; we respond appropriately});ws.addEventListener('message', (e) => {3 unmodified lines});ws.addEventListener('close', () => {if (authenticated) {setIndicator(false);// Try to reconnect silently β session token is still in sessionStoragereconnectTimer = setTimeout(connect, 3000);}});ws.addEventListener('error', () => ws.close());}function send(msg) {if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(msg));}// βββ Message Handling βββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction handleMessage(msg) {switch (msg.type) {case 'auth_required': {// Server is asking us to authenticateconst token = getToken();if (token) {// Try to resume existing sessionsetLoginLoading(true);send({ type: 'auth_resume', token });} else {// Show login formshowLogin();}break;}case 'auth_ok': {setToken(msg.token);showApp();setIndicator(true);break;}case 'auth_error': {clearToken();showLogin(msg.reason || 'Authentication failed.');break;}case 'auth_timeout': {clearToken();showLogin('Connection timed out. Please try again.');break;}case 'full_state': {state.sounds = msg.sounds || [];state.notifications = msg.notifications || [];3 unmodified lines}case 'sound_added': {if (!state.sounds.find(s => s.id === msg.sound.id)) state.sounds.push(msg.sound);updateSoundSelect();break;}case 'notification_added': {if (!state.notifications.find(n => n.id === msg.notification.id))state.notifications.push(msg.notification);renderNotifList();updateNotifCount();toast('Notification created', 'success');4 unmodified linesstate.devices = msg.devices || [];renderDeviceList();updateDeviceCount();if (selectedDeviceUUID) {const d = state.devices.find(d => d.uuid === selectedDeviceUUID);if (d) renderDeviceDetail(d);2 unmodified lines}case 'sound_data': {const existing = state.sounds.find(s => s.id === msg.sound.id);if (existing) { existing.data = msg.sound.data; }else { state.sounds.push(msg.sound); }4 unmodified lines}}// βββ Login Form βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββloginBtn.addEventListener('click', doLogin);loginPwInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') doLogin(); });function doLogin() {const password = loginPwInput.value;if (!password) { loginError.textContent = 'Enter a password.'; return; }loginError.textContent = '';setLoginLoading(true);// If WS is not open yet, connect first then send on openif (!ws || ws.readyState !== WebSocket.OPEN) {connect();// wait for auth_required, then it will show login β but we want to auto-submit// Store the password to auto-submit after connectionws.addEventListener('open', () => {// auth_required will trigger from server, which will show login again// Instead, wait for auth_required then send login directly}, { once: true });// Override: on auth_required from a fresh connect after user clicked login,// send the login immediatelyconst originalHandler = ws.onmessage;ws.addEventListener('message', function onFirstMsg(e) {let msg;try { msg = JSON.parse(e.data); } catch { return; }if (msg.type === 'auth_required') {ws.removeEventListener('message', onFirstMsg);send({ type: 'auth_login', password });}});} else {send({ type: 'auth_login', password });}}// βββ Logout βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdocument.getElementById('logout-btn').addEventListener('click', () => {clearToken();authenticated = false;clearTimeout(reconnectTimer);if (ws) ws.close();showLogin();});// βββ Render All βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction renderAll() {updateSoundSelect();24 unmodified lines<div class="notif-item-heading">${esc(n.heading)}</div><div class="notif-item-body">${esc(n.body)}</div>${sound ? `<span class="notif-item-sound">βͺ ${esc(sound.name)}</span>` : ''}</div>`;}).join('');list.querySelectorAll('.notif-item').forEach(el => {25 unmodified linesconst active = document.getElementById('schedule-active');active.style.display = 'flex';active.style.flexDirection = 'column';document.getElementById('selected-notif-name').textContent = notif.heading || notif.name;setDateTimeToNow();}function setDateTimeToNow() {const now = new Date();document.getElementById('sched-date').value = now.toISOString().slice(0, 10);document.getElementById('sched-time').value = now.toTimeString().slice(0, 5);}// βββ Devices ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ5 unmodified lines}list.innerHTML = state.devices.map(d => {const sel = d.uuid === selectedDeviceUUID ? 'selected' : '';const lastConn = d.lastConnection ? `Last seen ${timeSince(d.lastConnection)}` : 'Active now';return `<div class="device-item ${sel}" data-uuid="${d.uuid}"><span class="indicator ${d.online ? 'online' : 'offline'}"></span>2 unmodified lines<div class="device-item-uuid">${d.uuid.slice(0,18)}β¦</div><div class="device-item-last">${lastConn}</div></div></div>`;}).join('');list.querySelectorAll('.device-item').forEach(el => {16 unmodified linesconst detail = document.getElementById('device-detail');detail.style.display = 'block';document.getElementById('detail-device-name-display').textContent = device.name;document.getElementById('detail-device-uuid').textContent = device.uuid;document.getElementById('device-name-input').value = device.name;document.getElementById('device-status-indicator').className = `indicator ${device.online ? 'online' : 'offline'}`;// Cached soundsconst soundsEl = document.getElementById('detail-sounds');const cached = device.cachedSounds || [];soundsEl.innerHTML = !cached.length? '<span style="color:var(--text-dimmer);font-size:12px">None cached</span>': cached.map(sid => {const sound = state.sounds.find(s => s.id === sid);return `<span class="tag"><span class="tag-dot"></span>${esc(sound ? sound.name : sid.slice(0,8))}</span>`;}).join('');// Notifications tableconst notifsEl = document.getElementById('detail-notifications');const deviceNotifs = device.notifications || [];notifsEl.innerHTML = !deviceNotifs.length? '<div class="empty-state" style="padding:20px 0">No notifications</div>': `<table class="data-table"><thead><tr><th>NAME</th><th>HEADING</th><th>DISPLAYED</th></tr></thead><tbody>${deviceNotifs.map(n => `<tr><td>${esc(n.name)}</td><td>${esc(n.heading)}</td><td style="color:${n.displayed ? 'var(--green)' : 'var(--text-dimmer)'}">${n.displayed ? 'β YES' : 'β NO'}</td></tr>`).join('')}</tbody></table>`;// Schedule tableconst schedEl = document.getElementById('detail-schedule');1 unmodified lineif (!schedule.length) {schedEl.innerHTML = '<div class="empty-state" style="padding:20px 0">No scheduled notifications</div>';} else {schedEl.innerHTML = `<table class="data-table"><thead><tr><th>NOTIFICATION</th><th>SCHEDULED FOR</th><th>ACTION</th></tr></thead><tbody>${schedule.map(entry => {const notif = state.notifications.find(n => n.id === entry.notificationId);const name = notif ? (notif.heading || notif.name) : entry.notificationId.slice(0,8);return `<tr><td>${esc(name)}</td><td>${new Date(entry.scheduledAt).toLocaleString()}</td><td><button class="action-btn" data-uuid="${device.uuid}" data-nid="${entry.notificationId}">REMOVE</button></td></tr>`;}).join('')}</tbody></table>`;schedEl.querySelectorAll('.action-btn').forEach(btn => {btn.addEventListener('click', () => {send({ type: 'remove_schedule', uuid: btn.dataset.uuid, notificationId: btn.dataset.nid });toast('Schedule entry removed');});});}}// βββ Create Notification ββββββββββββββββββββββββββββββββββββββββββββββββββββββdocument.getElementById('create-notif-btn').addEventListener('click', () => {const name = document.getElementById('f-name').value.trim();const heading = document.getElementById('f-heading').value.trim();const body = document.getElementById('f-body').value.trim();const hyperlink = document.getElementById('f-hyperlink').value.trim();const soundId = document.getElementById('f-sound').value;if (!name || !heading) { toast('Name and Heading are required', 'error'); return; }if (pendingSoundFile) {const { soundName, data } = pendingSoundFile;if (!soundName) { toast('Enter a name for the sound', 'error'); return; }send({ type: 'create_sound', name: soundName, data });pendingSoundFile = null;document.getElementById('sound-file-name').textContent = 'No file chosen';document.getElementById('f-sound-name').value = '';toast('Sound uploaded β select it in the dropdown, then create the notification.', 'success');return;}send({ type: 'create_notification', name, heading, body, hyperlink, soundId: soundId || null });document.getElementById('f-name').value = '';document.getElementById('f-heading').value = '';document.getElementById('f-body').value = '';1 unmodified linedocument.getElementById('f-sound').value = '';});document.getElementById('sound-upload-btn').addEventListener('click', () => {document.getElementById('f-sound-file').click();});2 unmodified linesconst file = e.target.files[0];if (!file) return;document.getElementById('sound-file-name').textContent = file.name;const reader = new FileReader();reader.onload = (evt) => {const base64 = evt.target.result.split(',')[1];4 unmodified lines});document.getElementById('f-sound-name').addEventListener('input', () => {if (pendingSoundFile) pendingSoundFile.soundName = document.getElementById('f-sound-name').value.trim();});// βββ Play Now βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdocument.getElementById('play-now-btn').addEventListener('click', () => {if (!selectedNotifId) return;for (const device of state.devices) {send({ type: 'play_now', uuid: device.uuid, notificationId: selectedNotifId });}14 unmodified lines}});// βββ Schedule βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdocument.getElementById('schedule-btn').addEventListener('click', () => {if (!selectedNotifId) return;const dateVal = document.getElementById('sched-date').value;const timeVal = document.getElementById('sched-time').value;if (!dateVal || !timeVal) { toast('Select a date and time', 'error'); return; }const scheduledAt = new Date(`${dateVal}T${timeVal}`).getTime();if (isNaN(scheduledAt)) { toast('Invalid date/time', 'error'); return; }const targets = selectedDeviceUUID? state.devices.filter(d => d.uuid === selectedDeviceUUID): state.devices;if (!targets.length) { toast('No devices to schedule on', 'error'); return; }for (const device of targets) {send({ type: 'schedule_notification', uuid: device.uuid, notificationId: selectedNotifId, scheduledAt });}toast(`Scheduled on ${targets.length} device(s)`, 'success');});9 unmodified lines});});// βββ Device Name βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdocument.getElementById('device-name-save').addEventListener('click', () => {if (!selectedDeviceUUID) return;const name = document.getElementById('device-name-input').value.trim();2 unmodified linestoast('Name updated', 'success');});// βββ WS Indicator βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction setIndicator(online) {const dot = document.getElementById('ws-indicator');const label = document.getElementById('ws-label');dot.className = `indicator ${online ? 'online' : 'offline'}`;label.textContent = online ? 'LIVE' : 'OFFLINE';}// βββ Toast ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββlet toastTimer;function toast(msg, type = '') {let el = document.getElementById('toast');if (!el) { el = document.createElement('div'); el.id = 'toast'; document.body.appendChild(el); }el.textContent = msg;el.className = type ? `show ${type}` : 'show';clearTimeout(toastTimer);2 unmodified lines// βββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction esc(str) {return String(str || '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');}function timeSince(ts) {const d = Date.now() - ts;if (d < 60000) return `${Math.floor(d/1000)}s ago`;if (d < 3600000) return `${Math.floor(d/60000)}m ago`;if (d < 86400000) return `${Math.floor(d/3600000)}h ago`;return `${Math.floor(d/86400000)}d ago`;}// βββ Boot βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββsetDateTimeToNow();connect();
public/admin/script.js+193-172