/**
* Oscar Admin dashboard JS.
*
* Single-file client for index.php dashboard:
* - api(action, payload, method): POST/GET to action.php
* - toast/animateValue helpers
* - Detail renderers for sessions/users/generic JSON
* - Overview/users/sessions/rooms/directory renderers
* - BART catalog/browse/upload helpers
* - Buddy list (feedbag) helpers
* - Audit + API console + auto-refresh wiring
*
* The script is defensive: most handlers check for element presence so it can be
* safely loaded on pages that share admin_page() layout.
*/
(() => {
const CSRF = window.ADMIN_CSRF || '';
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => Array.from(r.querySelectorAll(s));
function esc(str) {
return String(str ?? '')
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function toast(msg, type = 'info', ms = 3200) {
const box = $('#toast-container');
if (!box) return;
const el = document.createElement('div');
el.className = `toast ${type}`;
el.textContent = msg;
box.appendChild(el);
setTimeout(() => {
el.classList.add('out');
el.addEventListener('animationend', () => el.remove(), { once: true });
}, ms);
}
function animateValue(el, to) {
if (!el) return;
const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const target = Number(to);
if (!Number.isFinite(target) || reduce) { el.textContent = String(to); return; }
const from = Number(el.textContent.replace(/[^0-9.-]/g, '')) || 0;
const start = performance.now();
const dur = 500;
const step = (now) => {
const p = Math.min(1, (now - start) / dur);
const ease = 1 - Math.pow(1 - p, 3);
el.textContent = String(Math.round(from + (target - from) * ease));
if (p < 1) requestAnimationFrame(step);
};
requestAnimationFrame(step);
}
function fmtVal(v) {
if (v === null || v === undefined || v === '') return '—';
if (typeof v === 'boolean') return v ? 'true' : 'false';
if (typeof v === 'number') return `${esc(v)}`;
if (typeof v === 'string') return esc(v);
if (Array.isArray(v)) {
if (!v.length) return 'empty';
if (v.every(x => ['string','number','boolean'].includes(typeof x) || x === null)) {
return v.map(x => `${esc(String(x))}`).join(' ');
}
return `
${v.map(x => `
${renderDetailHtml(x)}
`).join('')}
`;
}
if (typeof v === 'object') return renderDetailHtml(v);
return esc(String(v));
}
function renderDetailHtml(data) {
if (data === null || data === undefined) return '—';
if (['string','number','boolean'].includes(typeof data)) return fmtVal(data);
if (Array.isArray(data)) return fmtVal(data);
if (typeof data === 'object') {
const entries = Object.entries(data);
if (!entries.length) return 'empty';
return `
${entries.map(([k,v]) => `
${esc(k.replace(/_/g,' '))}
${fmtVal(v)}
`).join('')}
`;
}
return esc(String(data));
}
function setDetail(id, data) {
const el = typeof id === 'string' ? document.getElementById(id) : id;
if (!el) return;
if (typeof data === 'string') { el.textContent = data; return; }
el.innerHTML = renderDetailHtml(data);
}
function boolPill(v, trueLabel='Yes', falseLabel='No') {
return v ? `${esc(trueLabel)}` : `${esc(falseLabel)}`;
}
function renderSessionDetailHtml(data) {
const s = (data && Array.isArray(data.sessions) && data.sessions[0]) ? data.sessions[0] : data;
if (!s || typeof s !== 'object') return renderDetailHtml(data);
const instances = Array.isArray(s.instances) ? s.instances : [];
const away = !!(s.is_away || s.away_message);
return `
';
const r = await api('directory.keywords.list', { category_id: Number(categoryId) }, 'GET');
const list = r.ok && Array.isArray(r.data) ? r.data : [];
if (!r.ok) { tbody.innerHTML = `
${esc(r.error || 'Failed to load')}
`; return; }
if (!list.length) { tbody.innerHTML = '
No keywords.
'; return; }
tbody.innerHTML = list.map(k => `
${esc(k.id)}
${esc(k.name)}
`).join('');
$$('[data-del-kw]', tbody).forEach(b => b.addEventListener('click', async () => {
if (!confirm(`Delete keyword ${b.dataset.delKw}?`)) return;
const dr = await api('directory.keywords.delete', { id: Number(b.dataset.delKw) });
if (dr.ok) { toast('Keyword deleted', 'success'); loadKeywords(categoryId); } else toast(dr.error || 'Delete failed', 'error');
}));
}
$('#load-keywords-btn')?.addEventListener('click', () => {
const id = $('#keyword-category-id')?.value;
if (id) loadKeywords(id);
});
// User detail controls
$('#close-user-detail')?.addEventListener('click', () => $('#user-detail-card').style.display = 'none');
$('#close-session-detail')?.addEventListener('click', () => $('#session-detail-card').style.display = 'none');
$('#user-detail-save')?.addEventListener('click', async () => {
const sn = $('#user-detail-name').textContent;
if (!sn) return;
const r = await api('users.patch', { screen_name: sn, suspended_status: $('#user-detail-status').value, is_bot: $('#user-detail-bot').checked });
if (r.ok) { toast('User updated', 'success'); viewUser(sn); loadOverview(); } else toast(r.error || 'Update failed', 'error');
});
$('#user-detail-icon')?.addEventListener('click', async () => {
const sn = $('#user-detail-name').textContent;
if (!sn) return;
const r = await api('users.icon.get', { screen_name: sn }, 'GET');
const wrap = $('#user-detail-icon-wrap');
if (r.ok && r.data?.base64) {
wrap.innerHTML = ``;
} else {
wrap.innerHTML = `
${esc(r.error || 'No icon')}
`;
}
});
$('#user-detail-sessions')?.addEventListener('click', async () => {
const sn = $('#user-detail-name').textContent;
if (!sn) return;
const r = await api('sessions.get', { screen_name: sn }, 'GET');
const el = $('#user-detail-sessions-json');
el.style.display = 'block';
if (r.ok) el.innerHTML = renderSessionDetailHtml(r.data);
else setDetail(el, r.error || 'Failed');
});
// Bulk actions
$('#users-select-all')?.addEventListener('change', (e) => {
$$('.user-select').forEach(c => c.checked = e.target.checked);
});
$('#bulk-apply-status')?.addEventListener('click', async () => {
const users = selectedUsers();
if (!users.length) return toast('Select users first', 'error');
const status = $('#bulk-suspend-status').value;
if (!confirm(`Apply status "${status || 'active'}" to ${users.length} user(s)?`)) return;
for (const sn of users) await api('users.patch', { screen_name: sn, suspended_status: status });
toast('Bulk status update complete', 'success'); loadOverview();
});
$('#bulk-delete-users')?.addEventListener('click', async () => {
const users = selectedUsers();
if (!users.length) return toast('Select users first', 'error');
if (!confirm(`Delete ${users.length} user(s)? This cannot be undone.`)) return;
for (const sn of users) await api('users.delete', { screen_name: sn });
toast('Bulk delete complete', 'success'); loadOverview();
});
// BART
const BART_TYPES = [
{id:0,name:'Buddy icon (small)',desc:'Small buddy icon shown in buddy lists. GIF/JPEG/BMP/PNG, <= 32x32, <= 2KB.',group:'Icons',icon:'🖼️'},
{id:1,name:'Buddy icon',desc:'Standard buddy icon. GIF/JPEG/BMP/PNG, <= 64x64, <= 7KB.',group:'Icons',icon:'🖼️'},
{id:12,name:'Buddy icon (big)',desc:'Large buddy icon. GIF/JPEG/BMP/PNG, <= 1024x1024, <= 64KB.',group:'Icons',icon:'🖼️'},
{id:2,name:'Status string',desc:'Status text in StringTLV format (DATA flag always set).',group:'Status',icon:'💬'},
{id:13,name:'Status string time',desc:'Time when the status string was set.',group:'Status',icon:'🕒'},
{id:3,name:'Arrive sound',desc:'Sound played when a buddy comes online. WAV/MP3/MID, <= 10KB.',group:'Sounds',icon:'🔔'},
{id:96,name:'Depart sound',desc:'Sound played when a buddy goes offline. WAV/MP3/MID, <= 10KB.',group:'Sounds',icon:'🔕'},
{id:131,name:'IM sound',desc:'Sound played for instant messages. WAV/MP3, <= 10KB.',group:'Sounds',icon:'🎵'},
{id:4,name:'Rich text',desc:'Rich text formatting codes (DATA flag always set).',group:'Text & UI',icon:'✍️'},
{id:129,name:'IM chrome',desc:'IM window wallpaper/background. GIF/JPG/BMP.',group:'Text & UI',icon:'🎨'},
{id:136,name:'IM chrome XML',desc:'IM chrome XML definition.',group:'Text & UI',icon:'📄'},
{id:137,name:'IM chrome immersive',desc:'Immersive Expressions for IM chrome.',group:'Text & UI',icon:'✨'},
{id:5,name:'SuperBuddy icon',desc:'SuperBuddy icon XML.',group:'Other',icon:'⭐'},
{id:6,name:'Radio station',desc:'Radio station opaque struct (DATA flag always set).',group:'Other',icon:'📻'},
{id:15,name:'Current AV track',desc:'Current audio/video track XML.',group:'Other',icon:'🎬'},
{id:1024,name:'Emoticon set',desc:'Set of default emoticons.',group:'Other',icon:'😊'},
{id:1026,name:'Encryption cert chain',desc:'Certificate chain for encryption certs.',group:'Security',icon:'🔒'},
{id:1027,name:'Signing cert chain',desc:'Certificate chain for signing certs.',group:'Security',icon:'✒️'},
{id:1028,name:'Gateway cert',desc:'Certificate for enterprise gateway.',group:'Security',icon:'🛡️'},
];
const bartTypeById = new Map(BART_TYPES.map(t => [Number(t.id), t]));
let bartAssetsCache = [];
let bartLoadSeq = 0;
function bartTypeLabel(id) {
const t = bartTypeById.get(Number(id));
return t ? `${t.name} (${t.id})` : `Type ${id}`;
}
function renderBartTypeInfo(targetId, typeId) {
const el = document.getElementById(targetId);
if (!el) return;
const t = bartTypeById.get(Number(typeId));
if (!t) { el.innerHTML = `Unknown/custom type ID ${esc(typeId)}. You can still use it if the server supports it.`; return; }
el.innerHTML = `
${t.icon || '📦'}
${esc(t.name)}type #${esc(t.id)}${esc(t.group)}
${esc(t.desc)}
`;
}
function renderBartUploadPurpose(typeId) {
const el = document.getElementById('bart-upload-purpose');
if (!el) return;
const t = bartTypeById.get(Number(typeId));
if (!t) {
el.innerHTML = `
Uploading for
Custom type #${esc(typeId)}
Unknown type - make sure the server expects this type ID.
`;
return;
}
el.innerHTML = `
You're uploading
${t.icon || '📦'}${esc(t.name)} type #${esc(t.id)}
${esc(t.desc)}
`;
}
function selectBartType(id) {
id = Number(id);
const listType = $('#bart-list-type');
const upType = $('#bart-upload-type');
if (listType) listType.value = id;
if (upType) upType.value = id;
renderBartTypeInfo('bart-selected-type-info', id);
renderBartTypeInfo('bart-upload-type-info', id);
renderBartUploadPurpose(id);
$$('.bart-type-card').forEach(c => c.classList.toggle('selected', Number(c.dataset.typeId) === id));
}
function renderBartCatalog() {
const wrap = $('#bart-type-catalog');
if (!wrap) return;
const q = ($('#bart-type-filter')?.value || '').toLowerCase().trim();
const types = BART_TYPES.filter(t => !q || `${t.id} ${t.name} ${t.desc} ${t.group}`.toLowerCase().includes(q));
const groups = [];
for (const t of types) {
let g = groups.find(x => x.name === t.group);
if (!g) { g = {name: t.group, items: []}; groups.push(g); }
g.items.push(t);
}
const sel = Number($('#bart-list-type')?.value);
wrap.innerHTML = groups.map(g => `
${esc(g.name)}
${g.items.map(t => `
`).join('')}
`).join('') || '
No matching types.
';
$$('.bart-type-card', wrap).forEach(btn => btn.addEventListener('click', () => selectBartType(btn.dataset.typeId)));
}
function renderBartAssets() {
const tbody = $('#bart-list-tbody');
if (!tbody) return;
const q = ($('#bart-asset-filter')?.value || '').toLowerCase().trim();
const list = bartAssetsCache.filter(a => {
if (!q) return true;
const t = bartTypeById.get(Number(a.type));
return String(a.hash || '').toLowerCase().includes(q) || String(a.type).includes(q) || (t && t.name.toLowerCase().includes(q));
});
const count = $('#bart-asset-count');
if (count) count.textContent = bartAssetsCache.length ? `${list.length} of ${bartAssetsCache.length} assets` : '';
if (!list.length) { tbody.innerHTML = `
${bartAssetsCache.length ? 'No assets match your search.' : 'No assets found.'}