463 lines
24 KiB
JavaScript
463 lines
24 KiB
JavaScript
/* ==========================================================================
|
|
KittyRec Admin — Shared JS Library
|
|
Provides: api(), toast(), modal helpers, drawer, command palette, shortcuts.
|
|
Exposes everything on window.KR to avoid clobbering page-local helpers.
|
|
========================================================================== */
|
|
(function () {
|
|
'use strict';
|
|
|
|
const KR = window.KR = window.KR || {};
|
|
|
|
/* ── Toast ─────────────────────────────────────────────────────────── */
|
|
function ensureToastContainer() {
|
|
let c = document.getElementById('toast-container');
|
|
if (!c) {
|
|
c = document.createElement('div');
|
|
c.id = 'toast-container';
|
|
document.body.appendChild(c);
|
|
}
|
|
return c;
|
|
}
|
|
KR.toast = function (msg, type) {
|
|
type = type || 'success';
|
|
const c = ensureToastContainer();
|
|
const t = document.createElement('div');
|
|
t.className = 'toast ' + type;
|
|
t.textContent = msg;
|
|
c.appendChild(t);
|
|
setTimeout(() => { t.classList.add('fade'); setTimeout(() => t.remove(), 260); }, 3500);
|
|
return t;
|
|
};
|
|
if (!window.toast) window.toast = KR.toast;
|
|
|
|
/* ── API wrappers ──────────────────────────────────────────────────── */
|
|
KR.apiPost = async function (url, data) {
|
|
const r = await fetch(url, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(data || {}),
|
|
});
|
|
try { return await r.json(); } catch { return { ok: false, error: 'bad_response' }; }
|
|
};
|
|
KR.apiGet = async function (url) {
|
|
const r = await fetch(url);
|
|
try { return await r.json(); } catch { return null; }
|
|
};
|
|
if (!window.api) window.api = KR.apiPost;
|
|
|
|
/* ── Generic Modal ─────────────────────────────────────────────────── */
|
|
KR.openModal = function (id) {
|
|
const el = document.getElementById(id);
|
|
if (!el) return;
|
|
el.classList.add('open');
|
|
const input = el.querySelector('input:not([type=hidden]), textarea');
|
|
if (input) setTimeout(() => input.focus(), 50);
|
|
};
|
|
KR.closeModal = function (id) {
|
|
const el = document.getElementById(id);
|
|
if (el) el.classList.remove('open');
|
|
};
|
|
// Click-outside to close .kr-modal-backdrop
|
|
document.addEventListener('click', (e) => {
|
|
if (e.target.classList && e.target.classList.contains('kr-modal-backdrop')) {
|
|
e.target.classList.remove('open');
|
|
}
|
|
});
|
|
|
|
/* ── Utilities ─────────────────────────────────────────────────────── */
|
|
KR.debounce = function (fn, ms) {
|
|
let t;
|
|
return function () {
|
|
clearTimeout(t);
|
|
const args = arguments, ctx = this;
|
|
t = setTimeout(() => fn.apply(ctx, args), ms);
|
|
};
|
|
};
|
|
KR.escapeHtml = function (s) {
|
|
if (s == null) return '';
|
|
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
};
|
|
KR.formatRelTime = function (ts) {
|
|
if (!ts) return '';
|
|
const d = typeof ts === 'string' ? new Date(ts) : new Date(ts);
|
|
const diff = (Date.now() - d.getTime()) / 1000;
|
|
if (diff < 60) return Math.floor(diff) + 's ago';
|
|
if (diff < 3600) return Math.floor(diff/60) + 'm ago';
|
|
if (diff < 86400) return Math.floor(diff/3600) + 'h ago';
|
|
if (diff < 604800) return Math.floor(diff/86400) + 'd ago';
|
|
return d.toISOString().slice(0, 10);
|
|
};
|
|
|
|
/* ── Player Drawer ─────────────────────────────────────────────────── */
|
|
function ensureDrawer() {
|
|
let d = document.getElementById('kr-player-drawer');
|
|
if (d) return d;
|
|
d = document.createElement('aside');
|
|
d.id = 'kr-player-drawer';
|
|
d.innerHTML = `
|
|
<div class="kr-drawer-head">
|
|
<div class="kr-drawer-avatar" id="kr-drawer-avatar">?</div>
|
|
<div>
|
|
<div class="kr-drawer-name" id="kr-drawer-name">Loading…</div>
|
|
<div class="kr-drawer-sub" id="kr-drawer-sub"></div>
|
|
</div>
|
|
<button class="kr-drawer-close" onclick="KR.closeDrawer()" title="Close (Esc)">×</button>
|
|
</div>
|
|
<div class="kr-drawer-body" id="kr-drawer-body">
|
|
<p style="color:var(--text3);font-size:.85rem;text-align:center;padding:2rem 0">Loading…</p>
|
|
</div>`;
|
|
document.body.appendChild(d);
|
|
return d;
|
|
}
|
|
KR.openDrawer = async function (pid) {
|
|
const d = ensureDrawer();
|
|
d.classList.add('open');
|
|
d.dataset.pid = pid;
|
|
document.getElementById('kr-drawer-name').textContent = 'Loading…';
|
|
document.getElementById('kr-drawer-sub').textContent = '#' + pid;
|
|
document.getElementById('kr-drawer-body').innerHTML = '<p style="color:var(--text3);font-size:.85rem;text-align:center;padding:2rem 0">Loading…</p>';
|
|
(function() {
|
|
var av = document.getElementById('kr-drawer-avatar');
|
|
av.textContent = '?';
|
|
var img = new Image();
|
|
img.style.cssText = 'width:100%;height:100%;object-fit:cover;border-radius:50%';
|
|
img.onload = function() { av.textContent = ''; av.appendChild(img); };
|
|
img.src = '/alt/' + pid;
|
|
})();
|
|
|
|
try {
|
|
const p = await KR.apiGet('/admin/api/player_status/' + pid);
|
|
if (!p || p.error) {
|
|
document.getElementById('kr-drawer-body').innerHTML = '<p style="color:var(--red);font-size:.85rem;padding:1rem">Error: ' + (p && p.error || 'not found') + '</p>';
|
|
return;
|
|
}
|
|
document.getElementById('kr-drawer-name').textContent = p.username || '#' + pid;
|
|
(function() { var av = document.getElementById('kr-drawer-avatar'); if (av.textContent === '?') av.textContent = (p.username || String(pid)).charAt(0).toUpperCase(); })();
|
|
document.getElementById('kr-drawer-sub').textContent = p.display_name ? p.display_name + ' · #' + pid : '#' + pid;
|
|
|
|
const badges = [];
|
|
if (p.online) badges.push('<span class="badge badge-green"><span class="dot"></span> Online</span>');
|
|
else badges.push('<span class="badge badge-gray">Offline</span>');
|
|
if (p.banned) badges.push('<span class="badge badge-red">Banned</span>');
|
|
if (p.developer) badges.push('<span class="badge badge-yellow">Dev</span>');
|
|
|
|
const ptSecs = p.playtime_seconds || 0;
|
|
const ptH = Math.floor(ptSecs / 3600);
|
|
const ptM = Math.floor((ptSecs % 3600) / 60);
|
|
const ptStr = ptH > 0 ? ptH + 'h ' + ptM + 'm' : (ptM > 0 ? ptM + 'm' : '< 1m');
|
|
document.getElementById('kr-drawer-body').innerHTML = `
|
|
<div style="margin-bottom:1rem;display:flex;flex-wrap:wrap;gap:.35rem">${badges.join(' ')}</div>
|
|
${p.ban_reason ? '<div style="background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.25);padding:.5rem .7rem;border-radius:6px;font-size:.78rem;color:var(--red);margin-bottom:.85rem"><strong>Ban:</strong> ' + KR.escapeHtml(p.ban_reason) + '</div>' : ''}
|
|
<div class="kr-drawer-stats">
|
|
<div class="kr-stat"><div class="k">Level</div><div class="v">${p.level ?? '—'}</div></div>
|
|
<div class="kr-stat"><div class="k">ID</div><div class="v">#${p.id}</div></div>
|
|
<div class="kr-stat"><div class="k">Playtime</div><div class="v">${ptStr}</div></div>
|
|
<div class="kr-stat"><div class="k">Sessions</div><div class="v">${p.session_count || 0}</div></div>
|
|
</div>
|
|
<div class="kr-drawer-actions">
|
|
<a class="kr-btn kr-btn-ghost kr-btn-sm" href="/admin/players/${p.id}" style="justify-content:center">Full Profile</a>
|
|
<button class="kr-btn kr-btn-ghost kr-btn-sm" onclick="KR.drawerGift(${p.id}, ${JSON.stringify(p.username||'').replace(/"/g,'"')})">Gift</button>
|
|
<button class="kr-btn kr-btn-ghost kr-btn-sm" onclick="KR.drawerBan(${p.id}, ${JSON.stringify(p.username||'').replace(/"/g,'"')})">Ban</button>
|
|
${p.banned ? '<button class="kr-btn kr-btn-green kr-btn-sm" onclick="KR.drawerUnban(' + p.id + ')">Unban</button>' : ''}
|
|
<button class="kr-btn kr-btn-ghost kr-btn-sm" onclick="KR.drawerDisconnect(${p.id})">Disconnect</button>
|
|
<button class="kr-btn kr-btn-ghost kr-btn-sm" onclick="KR.drawerToggleDev(${p.id})">${p.developer ? 'Revoke Dev' : 'Grant Dev'}</button>
|
|
</div>`;
|
|
} catch (e) {
|
|
document.getElementById('kr-drawer-body').innerHTML = '<p style="color:var(--red);font-size:.85rem;padding:1rem">Fetch error</p>';
|
|
}
|
|
};
|
|
KR.closeDrawer = function () {
|
|
const d = document.getElementById('kr-player-drawer');
|
|
if (d) d.classList.remove('open');
|
|
};
|
|
KR.drawerDisconnect = async function (pid) {
|
|
const r = await KR.apiPost('/admin/api/disconnect/' + pid);
|
|
KR.toast(r.ok ? 'Disconnected' : (r.error || 'Error'), r.ok ? 'success' : 'error');
|
|
if (r.ok) KR.openDrawer(pid);
|
|
};
|
|
KR.drawerUnban = async function (pid) {
|
|
if (!confirm('Unban this player?')) return;
|
|
const r = await KR.apiPost('/admin/api/unban/' + pid);
|
|
KR.toast(r.ok ? 'Unbanned' : (r.error || 'Error'), r.ok ? 'success' : 'error');
|
|
if (r.ok) KR.openDrawer(pid);
|
|
};
|
|
KR.drawerToggleDev = async function (pid) {
|
|
const r = await KR.apiPost('/admin/api/toggle_dev/' + pid);
|
|
if (r.developer !== undefined) {
|
|
KR.toast(r.developer ? 'Dev granted' : 'Dev revoked');
|
|
KR.openDrawer(pid);
|
|
} else KR.toast(r.error || 'Error', 'error');
|
|
};
|
|
KR.drawerBan = function (pid, username) {
|
|
if (window.openBanModal) { window.openBanModal(pid, username); return; }
|
|
const reason = prompt('Ban reason:');
|
|
if (reason === null) return;
|
|
const hours = parseInt(prompt('Duration hours (0 = permanent):', '24')) || 0;
|
|
KR.apiPost('/admin/api/ban/' + pid, { reason: reason || 'Admin ban', duration_hours: hours, drop_ws: true })
|
|
.then(r => { KR.toast(r.ok ? 'Banned' : (r.error || 'Error'), r.ok ? 'success' : 'error'); if (r.ok) KR.openDrawer(pid); });
|
|
};
|
|
KR.drawerGift = function (pid, username) {
|
|
if (window.openGiftModal) { window.openGiftModal(pid, username); return; }
|
|
const xp = parseInt(prompt('XP amount:', '1000'));
|
|
if (!xp || isNaN(xp)) return;
|
|
KR.apiPost('/admin/api/gift_player/' + pid, { xp, rarity: 10, message: 'From the KittyRec team!' })
|
|
.then(r => { KR.toast(r.error ? r.error : 'Gift sent', r.error ? 'error' : 'success'); });
|
|
};
|
|
|
|
/* ── Command Palette ───────────────────────────────────────────────── */
|
|
const commands = [];
|
|
KR.registerCommand = function (section, label, run, hint) {
|
|
commands.push({ section: section || 'Actions', label, run, hint: hint || '' });
|
|
};
|
|
|
|
function ensurePalette() {
|
|
let p = document.getElementById('kr-cmd-palette');
|
|
if (p) return p;
|
|
p = document.createElement('div');
|
|
p.id = 'kr-cmd-palette';
|
|
p.innerHTML = `
|
|
<div class="kr-cmd-box">
|
|
<input id="kr-cmd-input" type="text" placeholder="Search commands or players…" autocomplete="off">
|
|
<div class="kr-cmd-results" id="kr-cmd-results"></div>
|
|
</div>`;
|
|
document.body.appendChild(p);
|
|
|
|
const input = p.querySelector('#kr-cmd-input');
|
|
const results = p.querySelector('#kr-cmd-results');
|
|
let active = 0;
|
|
let current = [];
|
|
|
|
const renderResults = KR.debounce(async () => {
|
|
const q = input.value.trim().toLowerCase();
|
|
current = [];
|
|
let html = '';
|
|
|
|
// Commands section
|
|
const matching = commands.filter(c => !q || c.label.toLowerCase().includes(q) || c.section.toLowerCase().includes(q));
|
|
if (matching.length) {
|
|
const bySec = {};
|
|
matching.forEach(c => { (bySec[c.section] = bySec[c.section] || []).push(c); });
|
|
Object.keys(bySec).forEach(sec => {
|
|
html += '<div class="kr-cmd-section">' + KR.escapeHtml(sec) + '</div>';
|
|
bySec[sec].forEach(c => {
|
|
const idx = current.length;
|
|
current.push({ kind: 'cmd', run: c.run });
|
|
html += '<div class="kr-cmd-item" data-idx="' + idx + '">' + KR.escapeHtml(c.label) + (c.hint ? '<span class="kr-cmd-hint">' + KR.escapeHtml(c.hint) + '</span>' : '') + '</div>';
|
|
});
|
|
});
|
|
}
|
|
|
|
// Player search section
|
|
if (q && q.length >= 2) {
|
|
try {
|
|
const players = await KR.apiGet('/admin/api/search_players?q=' + encodeURIComponent(q));
|
|
if (Array.isArray(players) && players.length) {
|
|
html += '<div class="kr-cmd-section">Players</div>';
|
|
players.slice(0, 8).forEach(p => {
|
|
const idx = current.length;
|
|
current.push({ kind: 'player', pid: p.id });
|
|
const onl = p.online ? '<span class="badge badge-green" style="margin-left:.5rem">Online</span>' : '';
|
|
html += '<div class="kr-cmd-item" data-idx="' + idx + '">' + KR.escapeHtml(p.username) + ' <span style="color:var(--text3);font-size:.75rem;margin-left:.35rem">Lv ' + (p.level || 0) + '</span>' + onl + '<span class="kr-cmd-hint">#' + p.id + '</span></div>';
|
|
});
|
|
}
|
|
} catch {}
|
|
}
|
|
|
|
if (!html) html = '<div class="kr-cmd-empty">No results</div>';
|
|
results.innerHTML = html;
|
|
active = 0;
|
|
highlight();
|
|
}, 150);
|
|
|
|
function highlight() {
|
|
results.querySelectorAll('.kr-cmd-item').forEach((el, i) => el.classList.toggle('active', i === active));
|
|
const cur = results.querySelector('.kr-cmd-item.active');
|
|
if (cur) cur.scrollIntoView({ block: 'nearest' });
|
|
}
|
|
function runIdx(i) {
|
|
const item = current[i];
|
|
if (!item) return;
|
|
KR.closePalette();
|
|
if (item.kind === 'cmd') item.run();
|
|
if (item.kind === 'player') KR.openDrawer(item.pid);
|
|
}
|
|
|
|
input.addEventListener('input', renderResults);
|
|
input.addEventListener('keydown', (e) => {
|
|
const items = results.querySelectorAll('.kr-cmd-item');
|
|
if (e.key === 'ArrowDown') { e.preventDefault(); active = Math.min(active + 1, items.length - 1); highlight(); }
|
|
else if (e.key === 'ArrowUp') { e.preventDefault(); active = Math.max(active - 1, 0); highlight(); }
|
|
else if (e.key === 'Enter') { e.preventDefault(); runIdx(active); }
|
|
else if (e.key === 'Escape') { KR.closePalette(); }
|
|
});
|
|
results.addEventListener('click', (e) => {
|
|
const el = e.target.closest('.kr-cmd-item');
|
|
if (el) runIdx(parseInt(el.dataset.idx));
|
|
});
|
|
p.addEventListener('click', (e) => { if (e.target === p) KR.closePalette(); });
|
|
|
|
// Trigger first render so commands show immediately
|
|
renderResults();
|
|
return p;
|
|
}
|
|
KR.openPalette = function () {
|
|
const p = ensurePalette();
|
|
p.classList.add('open');
|
|
const input = p.querySelector('#kr-cmd-input');
|
|
input.value = '';
|
|
input.dispatchEvent(new Event('input'));
|
|
setTimeout(() => input.focus(), 30);
|
|
};
|
|
KR.closePalette = function () {
|
|
const p = document.getElementById('kr-cmd-palette');
|
|
if (p) p.classList.remove('open');
|
|
};
|
|
|
|
/* ── Keyboard Shortcuts ────────────────────────────────────────────── */
|
|
const shortcuts = [];
|
|
KR.registerShortcut = function (combo, fn, label) {
|
|
shortcuts.push({ combo: combo.toLowerCase(), fn, label: label || combo });
|
|
};
|
|
|
|
let gSequence = null, gTimer = null;
|
|
document.addEventListener('keydown', (e) => {
|
|
const tag = (e.target && e.target.tagName) || '';
|
|
const inField = tag === 'INPUT' || tag === 'TEXTAREA' || e.target.isContentEditable;
|
|
|
|
// Cmd+K / Ctrl+K
|
|
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
|
|
e.preventDefault();
|
|
KR.openPalette();
|
|
return;
|
|
}
|
|
|
|
if (e.key === 'Escape') {
|
|
KR.closePalette();
|
|
KR.closeDrawer();
|
|
document.querySelectorAll('.kr-modal-backdrop.open, .modal-backdrop.open').forEach(m => m.classList.remove('open'));
|
|
return;
|
|
}
|
|
|
|
if (inField) return;
|
|
|
|
// '?' help
|
|
if (e.key === '?') { e.preventDefault(); KR.toggleShortcutHelp(); return; }
|
|
|
|
// '/' focus a search input if one exists
|
|
if (e.key === '/') {
|
|
const search = document.querySelector('input[type=search], input#search, input[placeholder*="earch"]');
|
|
if (search) { e.preventDefault(); search.focus(); return; }
|
|
}
|
|
|
|
// Two-key 'g X' navigation
|
|
if (e.key === 'g') { gSequence = 'g'; clearTimeout(gTimer); gTimer = setTimeout(() => gSequence = null, 900); return; }
|
|
if (gSequence === 'g') {
|
|
const go = { d: '/admin/', p: '/admin/players', b: '/admin/bans', s: '/admin/sessions', g: '/admin/gifts' };
|
|
const target = go[e.key.toLowerCase()];
|
|
if (target) { e.preventDefault(); window.location.href = target; }
|
|
gSequence = null; clearTimeout(gTimer);
|
|
return;
|
|
}
|
|
|
|
// Single-key shortcuts
|
|
for (const s of shortcuts) {
|
|
if (s.combo === e.key.toLowerCase()) { e.preventDefault(); s.fn(); return; }
|
|
}
|
|
});
|
|
|
|
KR.toggleShortcutHelp = function () {
|
|
let h = document.getElementById('kr-shortcut-help');
|
|
if (!h) {
|
|
h = document.createElement('div');
|
|
h.id = 'kr-shortcut-help';
|
|
h.innerHTML = `
|
|
<div class="kr-help-box">
|
|
<h3>Keyboard Shortcuts</h3>
|
|
<div class="kr-help-row"><span>Open command palette</span><span><kbd>⌘</kbd> <kbd>K</kbd></span></div>
|
|
<div class="kr-help-row"><span>Go to Dashboard</span><span><kbd>g</kbd> <kbd>d</kbd></span></div>
|
|
<div class="kr-help-row"><span>Go to Players</span><span><kbd>g</kbd> <kbd>p</kbd></span></div>
|
|
<div class="kr-help-row"><span>Go to Bans</span><span><kbd>g</kbd> <kbd>b</kbd></span></div>
|
|
<div class="kr-help-row"><span>Go to Sessions</span><span><kbd>g</kbd> <kbd>s</kbd></span></div>
|
|
<div class="kr-help-row"><span>Go to Gifts</span><span><kbd>g</kbd> <kbd>g</kbd></span></div>
|
|
<div class="kr-help-row"><span>Focus search</span><span><kbd>/</kbd></span></div>
|
|
<div class="kr-help-row"><span>Close / cancel</span><span><kbd>Esc</kbd></span></div>
|
|
<div class="kr-help-row"><span>This help</span><span><kbd>?</kbd></span></div>
|
|
<div style="margin-top:1rem;text-align:right"><button class="kr-btn kr-btn-ghost kr-btn-sm" onclick="KR.toggleShortcutHelp()">Close</button></div>
|
|
</div>`;
|
|
document.body.appendChild(h);
|
|
h.addEventListener('click', (e) => { if (e.target === h) h.classList.remove('open'); });
|
|
}
|
|
h.classList.toggle('open');
|
|
};
|
|
|
|
/* ── Default commands ──────────────────────────────────────────────── */
|
|
KR.registerCommand('Go', 'Dashboard', () => location.href = '/admin/', 'g d');
|
|
KR.registerCommand('Go', 'Players', () => location.href = '/admin/players', 'g p');
|
|
KR.registerCommand('Go', 'Bans', () => location.href = '/admin/bans', 'g b');
|
|
KR.registerCommand('Go', 'Sessions', () => location.href = '/admin/sessions', 'g s');
|
|
KR.registerCommand('Go', 'Gifts', () => location.href = '/admin/gifts', 'g g');
|
|
KR.registerCommand('Go', 'Weekly Challenges', () => location.href = '/admin/live/weekly');
|
|
KR.registerCommand('Go', 'Store', () => location.href = '/admin/live/store');
|
|
KR.registerCommand('Go', 'Rooms', () => location.href = '/admin/live/rooms');
|
|
KR.registerCommand('Go', 'Events', () => location.href = '/admin/live/events');
|
|
KR.registerCommand('Go', 'Console', () => location.href = '/admin/live/console');
|
|
KR.registerCommand('Go', 'Analytics', () => location.href = '/admin/analytics');
|
|
KR.registerCommand('Go', 'Avatar Items', () => location.href = '/admin/live/avatar_items');
|
|
KR.registerCommand('Go', 'Swatches', () => location.href = '/admin/live/swatches');
|
|
KR.registerCommand('Go', 'UGC Avatar', () => location.href = '/admin/live/ugc_items');
|
|
KR.registerCommand('Go', 'Game Assets', () => location.href = '/admin/live/textures');
|
|
KR.registerCommand('Go', 'Music', () => location.href = '/admin/live/music');
|
|
KR.registerCommand('Go', 'CDN', () => location.href = '/admin/live/cdn');
|
|
KR.registerCommand('Go', 'Downloads', () => location.href = '/admin/live/downloads');
|
|
KR.registerCommand('Go', 'Videos', () => location.href = '/admin/videos');
|
|
KR.registerCommand('Go', 'KittyRec Mod', () => location.href = '/admin/kittyrec/mod');
|
|
KR.registerCommand('Go', 'DLL Archive', () => location.href = '/admin/live/dll_archive');
|
|
KR.registerCommand('Go', 'Gifts DB', () => location.href = '/admin/admin_gifts/');
|
|
KR.registerCommand('Go', 'Ban Log DB', () => location.href = '/admin/admin_bans/');
|
|
KR.registerCommand('Go', 'Leaderboard', () => location.href = '/admin/leaderboard');
|
|
KR.registerCommand('Go', 'Chat Moderation', () => location.href = '/admin/chat');
|
|
KR.registerCommand('Go', 'Todos', () => location.href = '/admin/admin_todos/');
|
|
KR.registerCommand('Go', 'Issues', () => location.href = '/admin/admin_issues/');
|
|
KR.registerCommand('Action', 'Reroll Store', async () => { const r = await KR.apiPost('/admin/api/reroll_store'); KR.toast(r.ok ? 'Store rerolled' : (r.error || 'Error'), r.ok ? 'success' : 'error'); });
|
|
KR.registerCommand('Action', 'Git Sync', async () => { KR.toast('Syncing…', 'info'); const r = await KR.apiPost('/admin/api/git_sync'); KR.toast(r.ok ? 'Git synced' : (r.error || 'Error'), r.ok ? 'success' : 'error'); });
|
|
KR.registerCommand('Action', 'Toggle Maintenance',async () => {
|
|
const cur = await KR.apiGet('/admin/api/maintenance');
|
|
const next = !cur.maintenance;
|
|
const r = await KR.apiPost('/admin/api/maintenance', { enabled: next, exempt_ids: cur.exempt_ids || [] });
|
|
KR.toast(r.ok ? ('Maintenance ' + (next ? 'ON' : 'OFF')) : (r.error || 'Error'), r.ok ? 'success' : 'error');
|
|
});
|
|
KR.registerCommand('Action', 'Reboot Server', async () => { if (!confirm('Reboot server?')) return; const r = await KR.apiPost('/admin/api/reboot'); KR.toast(r.ok ? 'Reboot scheduled' : (r.error || 'Error'), r.ok ? 'success' : 'error'); });
|
|
KR.registerCommand('Help', 'Keyboard Shortcuts',() => KR.toggleShortcutHelp(), '?');
|
|
|
|
/* ── Admin WebSocket ───────────────────────────────────────────────── */
|
|
KR._adminWsHandlers = [];
|
|
KR.onAdminMsg = function (handler) { KR._adminWsHandlers.push(handler); };
|
|
|
|
KR.connectAdminWS = function () {
|
|
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
const url = proto + '//' + location.host + '/admin/ws';
|
|
let retryDelay = 1000;
|
|
let ws;
|
|
|
|
function dispatch(msg) {
|
|
KR._adminWsHandlers.forEach(function (h) { try { h(msg); } catch (e) {} });
|
|
if (msg.type === 'online_count') {
|
|
const el = document.getElementById('sb-online-count');
|
|
if (el) el.textContent = msg.count;
|
|
}
|
|
}
|
|
|
|
function connect() {
|
|
ws = new WebSocket(url);
|
|
ws.onopen = function () { retryDelay = 1000; };
|
|
ws.onmessage = function (e) {
|
|
try { dispatch(JSON.parse(e.data)); } catch (err) {}
|
|
};
|
|
ws.onclose = function () { setTimeout(connect, retryDelay); retryDelay = Math.min(retryDelay * 2, 30000); };
|
|
ws.onerror = function () { ws.close(); };
|
|
}
|
|
|
|
connect();
|
|
};
|
|
})();
|