File size: 22,836 Bytes
7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 7eab36a 9bfc2c5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | // βββ 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) => {
let msg;
try { msg = JSON.parse(e.data); } catch { return; }
handleMessage(msg);
});
ws.addEventListener('close', () => {
if (authenticated) {
setIndicator(false);
// Try to reconnect silently β session token is still in sessionStorage
reconnectTimer = 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 authenticate
const token = getToken();
if (token) {
// Try to resume existing session
setLoginLoading(true);
send({ type: 'auth_resume', token });
} else {
// Show login form
showLogin();
}
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 || [];
state.devices = msg.devices || [];
renderAll();
break;
}
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');
break;
}
case 'devices_updated': {
state.devices = msg.devices || [];
renderDeviceList();
updateDeviceCount();
if (selectedDeviceUUID) {
const d = state.devices.find(d => d.uuid === selectedDeviceUUID);
if (d) renderDeviceDetail(d);
}
break;
}
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); }
break;
}
default: break;
}
}
// βββ 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 open
if (!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 connection
ws.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 immediately
const 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();
renderNotifList();
updateNotifCount();
renderDeviceList();
updateDeviceCount();
if (selectedNotifId) {
const n = state.notifications.find(n => n.id === selectedNotifId);
if (!n) selectedNotifId = null;
else showSchedulePanel(n);
}
}
// βββ Notifications ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function renderNotifList() {
const list = document.getElementById('notif-list');
if (!state.notifications.length) {
list.innerHTML = '<div class="empty-state">No notifications yet.</div>';
return;
}
list.innerHTML = state.notifications.map(n => {
const sound = n.soundId ? state.sounds.find(s => s.id === n.soundId) : null;
const sel = n.id === selectedNotifId ? 'selected' : '';
return `
<div class="notif-item ${sel}" data-id="${n.id}">
<div class="notif-item-name">${esc(n.name)}</div>
<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 => {
el.addEventListener('click', () => {
selectedNotifId = el.dataset.id;
list.querySelectorAll('.notif-item').forEach(e => e.classList.remove('selected'));
el.classList.add('selected');
const notif = state.notifications.find(n => n.id === selectedNotifId);
if (notif) showSchedulePanel(notif);
});
});
}
function updateNotifCount() {
document.getElementById('notif-count').textContent = state.notifications.length;
}
function updateSoundSelect() {
const sel = document.getElementById('f-sound');
const current = sel.value;
sel.innerHTML = '<option value="">β No Sound β</option>' +
state.sounds.map(s => `<option value="${s.id}">${esc(s.name)}</option>`).join('');
if (current) sel.value = current;
}
// βββ Schedule Panel βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function showSchedulePanel(notif) {
document.getElementById('schedule-empty-state').style.display = 'none';
const 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 ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function renderDeviceList() {
const list = document.getElementById('device-list');
if (!state.devices.length) {
list.innerHTML = '<div class="empty-state">No devices yet.</div>';
return;
}
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>
<div class="device-item-info">
<div class="device-item-name">${esc(d.name)}</div>
<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 => {
el.addEventListener('click', () => {
selectedDeviceUUID = el.dataset.uuid;
list.querySelectorAll('.device-item').forEach(e => e.classList.remove('selected'));
el.classList.add('selected');
const d = state.devices.find(d => d.uuid === selectedDeviceUUID);
if (d) renderDeviceDetail(d);
});
});
}
function updateDeviceCount() {
document.getElementById('device-count').textContent = state.devices.length;
}
function renderDeviceDetail(device) {
document.getElementById('device-empty-state').style.display = 'none';
const 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 sounds
const 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 table
const 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 table
const schedEl = document.getElementById('detail-schedule');
const schedule = device.schedule || [];
if (!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 = '';
document.getElementById('f-hyperlink').value = '';
document.getElementById('f-sound').value = '';
});
document.getElementById('sound-upload-btn').addEventListener('click', () => {
document.getElementById('f-sound-file').click();
});
document.getElementById('f-sound-file').addEventListener('change', (e) => {
const 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];
const soundName = document.getElementById('f-sound-name').value.trim() || file.name;
pendingSoundFile = { soundName, data: base64 };
};
reader.readAsDataURL(file);
});
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 });
}
toast('βΆ Sent to all devices', 'success');
});
// βββ Now Toggle βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
document.getElementById('now-toggle').addEventListener('change', (e) => {
if (e.target.checked) {
setDateTimeToNow();
nowIntervalId = setInterval(setDateTimeToNow, 1000);
document.getElementById('datetime-pickers').style.opacity = '0.5';
document.getElementById('datetime-pickers').style.pointerEvents = 'none';
} else {
clearInterval(nowIntervalId);
document.getElementById('datetime-pickers').style.opacity = '';
document.getElementById('datetime-pickers').style.pointerEvents = '';
}
});
// βββ 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');
});
// βββ Tabs βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
const tab = btn.dataset.tab;
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
btn.classList.add('active');
document.getElementById(`tab-${tab}`).classList.add('active');
});
});
// βββ Device Name βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
document.getElementById('device-name-save').addEventListener('click', () => {
if (!selectedDeviceUUID) return;
const name = document.getElementById('device-name-input').value.trim();
if (!name) { toast('Enter a name', 'error'); return; }
send({ type: 'update_device_name', uuid: selectedDeviceUUID, name });
toast('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);
toastTimer = setTimeout(() => { el.className = el.className.replace('show', '').trim(); }, 3000);
}
// βββ 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(); |