Files
client/app/renderer/js/admin.js
T

1264 lines
78 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Account-free server administration, drawn in the detail pane like the installed TS6 6.0.0.5163 client.
// Layout sources (main.js): ts-info-edit-channel @4266500 (topic card, description card, "Channel Settings"
// + Show Advanced, General / Audio Codec / Audio Quality cards, advanced Moderation / Type / User Limits
// cards, Cancel + Save Options footer), channel info grid @4129883, server info @4549328 (host banner,
// welcome card, File Transfer Info, Manage list, info grid, version footer, Server Settings), client info
// @4396396, ban list @4498573 and the sticky navigation bars of the server sub-views; codec bandwidth
// @2367914. Commands are unchanged (ts6spec-controls §1.5): every mutation carries the admin_context
// generation, server-wide and destructive changes still need an explicit typed-target confirmation, and
// only changed values are sent. Short forms that the official client shows as popups stay <dialog>s.
import { h } from './dom.js';
import { callOn } from './core.js';
import { viewedConnection, connectionById, isAlive, isConnected, selectedChannel, ownClient, on, emit } from './state.js';
import { t, getLanguage, onLanguageChange } from './i18n.js';
import { errorText, stripBBCode } from './text.js';
import { openServerSnapshots } from './server-snapshots.js';
import { joinChannel } from './tree.js';
import { openFileBrowser } from './files.js';
import { menuPosition } from './menu-position.js';
import { confirmAction } from './confirmations.js';
import { badgeShowcase } from './badges.js';
import { openServerIcons } from './server-icons.js';
const L = (key, args) => t(`admin.${key}`, args);
let modal = null; // short popup forms (<dialog>)
let pane = null; // the detail-pane view inside #channel-info-view
let initialized = false;
let fieldId = 0;
let channelPopup = null;
const codecs = ['speex_narrowband', 'speex_wideband', 'speex_ultrawideband', 'celt_mono', 'opus_voice', 'opus_music'];
// Official codecHelper tables (bits/s per quality 0–10); other codecs have no bandwidth estimate.
const OPUS_BITRATE = {
opus_voice: [4096, 8192, 12288, 16384, 20480, 24576, 28672, 32768, 36864, 40960, 45056],
opus_music: [7200, 14400, 21600, 28800, 36000, 43200, 50400, 57600, 64800, 72000, 79200],
};
const GROUP_ICONS = new Set([100, 200, 300, 500, 600]);
// Exact serveredit allowlist. Only changed values are sent.
const serverFields = [
['general', 'name', 'text', 64], ['general', 'welcomemessage', 'textarea', 8192],
['general', 'maxclients', 'number', 65535], ['general', 'reserved_slots', 'number', 65535],
['general', 'nickname', 'text', 1024], ['general', 'name_phonetic', 'text', 1024],
['host', 'hostmessage', 'textarea', 8192], ['host', 'hostmessage_mode', 'number', 3],
['host', 'hostbanner_url', 'text', 1024], ['host', 'hostbanner_gfx_url', 'text', 1024],
['host', 'hostbanner_gfx_interval', 'number', 4294967295], ['host', 'hostbanner_mode', 'number', 2],
['host', 'hostbutton_tooltip', 'text', 1024], ['host', 'hostbutton_url', 'text', 1024],
['host', 'hostbutton_gfx_url', 'text', 1024], ['host', 'icon_id', 'number', 4294967295],
['transfer', 'max_download_total_bandwidth', 'number'], ['transfer', 'max_upload_total_bandwidth', 'number'],
['transfer', 'download_quota', 'number'], ['transfer', 'upload_quota', 'number'],
['security', 'antiflood_points_tick_reduce', 'number', 4294967295],
['security', 'antiflood_points_needed_command_block', 'number', 4294967295],
['security', 'antiflood_points_needed_ip_block', 'number', 4294967295],
['security', 'codec_encryption_mode', 'number', 2], ['security', 'needed_identity_security_level', 'number', 255],
['security', 'default_server_group', 'number'], ['security', 'default_channel_group', 'number'],
['security', 'default_channel_admin_group', 'number'], ['security', 'complain_autoban_count', 'number', 4294967295],
['security', 'complain_autoban_time', 'number', 4294967295], ['security', 'complain_remove_time', 'number', 4294967295],
['misc', 'min_clients_in_channel_before_forced_silence', 'number', 4294967295],
['misc', 'priority_speaker_dimm_modificator', 'number'],
['misc', 'channel_temp_delete_delay_default', 'number', 4294967295], ['misc', 'weblist_enabled', 'checkbox'],
...['client', 'query', 'channel', 'permissions', 'server', 'filetransfer'].map((name) => ['logging', `log_${name}`, 'checkbox']),
];
// Server Settings cards: General + User Limits always, the rest behind Show Advanced (official server edit).
const serverCards = [
['general', ['name', 'name_phonetic', 'nickname']], ['limits', ['maxclients', 'reserved_slots']],
['host', null], ['transfer', null], ['security', null], ['misc', null], ['logging', null],
];
const PANE_ROUTES = new Set(['server', 'server.info', 'server.edit', 'channel.info', 'channel.info.inline', 'channel.manage',
'channel.edit', 'channel.create', 'channel.createChild', 'client.info', 'permissions', 'bans', 'keys', 'passwords', 'clients', 'log']);
// ---------- shared session plumbing ----------
const live = (s) => isAlive(s.conn) && isConnected(s.conn) && s.conn.session === s.session && viewedConnection() === s.conn;
const alive = (s) => (s === modal || s === pane) && live(s);
const host = () => document.getElementById('channel-info-view');
const lang = () => getLanguage();
function glyph(name, cls = '') {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('class', `icon${cls ? ` ${cls}` : ''}`);
svg.setAttribute('aria-hidden', 'true');
const use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
use.setAttribute('href', `#i-${name}`);
svg.append(use);
return svg;
}
function closeModal() {
const s = modal;
if (!s) return;
modal = null;
s.root.close();
s.root.remove();
if (s.anchor?.isConnected) s.anchor.focus({ preventScroll: true });
}
function dropPane(text) {
if (!pane) return;
pane = null;
emit('admin-view', { kind: null });
const el = host();
if (text && el && !el.hidden) el.replaceChildren(h('p', { class: 'adm-gone', role: 'status', text }));
}
function permission(s, name) {
const value = s.context?.permissions?.[name];
return value == null || value !== 0;
}
// A family of rights is denied only when the server reported every one of them as 0.
function anyAllowed(s, prefix) {
const values = Object.entries(s.context?.permissions ?? {}).filter(([name]) => name.startsWith(prefix)).map(([, v]) => v);
return values.length === 0 || values.some((v) => v !== 0);
}
function deny(el, s, right) {
if (right && !permission(s, right)) { el.disabled = true; el.title = L('denied', { permission: right }); }
return el;
}
function setStatus(s, text, alert = false) {
s.status.textContent = text;
s.status.setAttribute('role', alert ? 'alert' : 'status');
}
function guarded(s, fn) {
return () => {
if (!alive(s) || s.busy) return;
try { fn(); } catch (error) { setStatus(s, errorText(error), true); }
};
}
async function request(s, command, args = {}, mutation = false) {
if (!alive(s)) throw new Error(L('changed'));
if (mutation) args = { ...args, generation: s.context.generation };
const result = await callOn(s.conn.id, command, args);
if (!alive(s)) throw new Error(L('changed'));
return result;
}
async function run(s, work) {
if (!alive(s) || s.busy) return;
const operation = s.operation = (s.operation ?? 0) + 1;
s.busy = true;
s.root.setAttribute('aria-busy', 'true');
const enabled = [...s.root.querySelectorAll('button,input,select,textarea')].filter((el) => !el.disabled);
for (const el of enabled) el.disabled = true;
setStatus(s, L('working'));
try { await work(); }
catch (e) { if (alive(s) && operation === s.operation) setStatus(s, errorText(e), true); }
finally {
for (const el of enabled) el.disabled = false;
if (operation === s.operation) {
s.busy = false;
s.root.removeAttribute('aria-busy');
if (alive(s) && s.status.textContent === L('working')) s.status.textContent = '';
}
}
}
function control(type, id, value, props) {
return h(type === 'textarea' ? 'textarea' : 'input', { id, type: type === 'textarea' ? null : type,
value: type === 'checkbox' ? undefined : String(value ?? ''), checked: type === 'checkbox' ? Boolean(value) : undefined,
autocomplete: type === 'password' ? 'new-password' : 'off', ...props });
}
// Label + control. Modal forms use the shared client-field layout; pane forms use the official ts-option-row.
function field(parent, key, type = 'text', value = '', props = {}, cls = 'client-field') {
const id = `admin-field-${++fieldId}`;
const input = control(type, id, value, props);
parent.append(h('label', { class: cls, for: id }, h('span', { class: cls === 'client-field' ? null : 'adm-row-label', text: L(key) }), input));
return input;
}
function select(parent, key, values, value, cls = 'client-field') {
const id = `admin-field-${++fieldId}`;
const input = h('select', { id }, values.map(([v, text]) => h('option', { value: String(v), text })));
input.value = String(value);
parent.append(h('label', { class: cls, for: id }, h('span', { class: cls === 'client-field' ? null : 'adm-row-label', text: L(key) }), input));
return input;
}
const row = (parent, key, type, value, props) => field(parent, key, type, value, props, 'adm-row');
const rowSelect = (parent, key, values, value) => select(parent, key, values, value, 'adm-row');
const info = (text, hidden = false) => h('p', { class: 'adm-info', text, hidden });
function channel(s, id) {
const c = s.conn.snap.channels.find((c) => c.id === id);
if (!c) throw new Error(L('channelGone'));
return c;
}
function channels(s, exclude = null) {
const blocked = new Set(exclude == null ? [] : [exclude]);
let changed;
do { changed = false; for (const c of s.conn.snap.channels) if (blocked.has(c.parent_id) && !blocked.has(c.id)) { blocked.add(c.id); changed = true; } } while (changed);
return [[0, L('serverRoot')], ...s.conn.snap.channels.filter((c) => !blocked.has(c.id)).map((c) => [c.id, c.name])];
}
const siblings = (s, parent, except) => [[0, L('first')], ...s.conn.snap.channels.filter((ch) => ch.parent_id === parent && ch.id !== except).map((ch) => [ch.id, ch.name])];
function fillOptions(input, values) { input.replaceChildren(...values.map(([v, text]) => h('option', { value: String(v), text }))); }
// ---------- formatting ----------
function date(unix) {
const n = Number(unix);
return Number.isFinite(n) && n > 0 ? new Date(n * 1000).toLocaleDateString(lang(), { year: 'numeric', month: 'short', day: 'numeric' }) : L('unknownValue');
}
function duration(seconds) {
const n = Number(seconds);
if (!Number.isFinite(n) || n < 0) return L('unknownValue');
if (n < 45) return L('fewSeconds');
const [unit, size] = n < 3600 ? ['minute', 60] : n < 86400 ? ['hour', 3600] : ['day', 86400];
return new Intl.NumberFormat(lang(), { style: 'unit', unit, unitDisplay: 'long' }).format(Math.max(1, Math.round(n / size)));
}
function bytes(value) {
let n = Number(value);
if (!Number.isFinite(n) || n < 0) return L('unknownValue');
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
let i = 0;
while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; }
return `${new Intl.NumberFormat(lang(), { maximumFractionDigits: i ? 2 : 0 }).format(n)} ${units[i]}`;
}
// Official getCodecBandwidthUsage: payload bitrate rounded up to whole 50 pps frames, plus 18 kbit/s overhead.
function bandwidth(codec, quality) {
const table = OPUS_BITRATE[codec];
if (!table) return null;
const q = Math.min(10, Math.max(0, Math.round(Number(quality) || 0)));
const bits = 50 * Math.ceil(table[q] / 50 / 8) * 8;
const kib = (bits + 18000) / 8 / 1024;
return `${(kib >= 1 ? kib : 0).toFixed(2)} KiB`;
}
const qualityStep = (q) => Math.min(5, Math.max(1, Math.ceil((Number(q) || 0) / 2)));
const strip = (text) => stripBBCode(text ?? '').trim();
const codecName = (codec) => (codecs.includes(codec) ? L(`codec.${codec}`) : String(codec ?? L('unknownValue')));
const version = (text) => String(text ?? '').replace(/\s*\[Build:.*$/i, '').trim();
function region(code) {
if (!code) return L('unknownValue');
try { return new Intl.DisplayNames([lang()], { type: 'region' }).of(code) ?? code; } catch { return code; }
}
// ---------- modal popups ----------
function page(s, key) {
s.page++;
s.title.textContent = L(key);
s.body.replaceChildren();
setStatus(s, '');
s.footer.replaceChildren(h('button', { type: 'button', class: 'btn', text: L('close'), onclick: closeModal }));
return s.page;
}
function action(s, parent, key, fn, right, danger = false) {
const b = h('button', { type: 'button', class: danger ? 'btn btn-danger' : 'btn', text: L(key), onclick: guarded(s, fn) });
parent.append(deny(b, s, right));
return b;
}
function form(s, key, save, { danger = false, confirm = null } = {}) {
const f = h('form', { class: 'adm-dialog-form' });
s.body.append(f);
const submit = h('button', { type: 'submit', class: danger ? 'btn btn-primary btn-danger' : 'btn btn-primary', text: L(key) });
let confirmed;
const finish = () => {
if (confirm !== null) { f.append(h('p', { class: 'client-detail', text: L('confirmTarget', { target: confirm }) })); confirmed = field(f, 'confirm', 'checkbox', false, { required: true }); }
f.append(submit);
};
f.addEventListener('submit', (e) => {
e.preventDefault();
if (s.busy || !f.reportValidity() || (confirmed && !confirmed.checked)) return;
void run(s, async () => { await save(); });
});
return { f, finish };
}
function success(s) {
s.body.replaceChildren(h('p', { text: L('success') }));
setStatus(s, L('success'));
s.after?.();
}
function channelMove(s, id) {
const c = channel(s, id); page(s, 'channel.move');
let parent, order;
const { f, finish } = form(s, 'channel.move', async () => { await request(s, 'channel_move', { channel_id: id, parent_id: Number(parent.value), order: Number(order.value) }, true); success(s); });
f.append(h('p', { class: 'client-detail', text: c.name }));
parent = select(f, 'parent', channels(s, id), c.parent_id);
order = select(f, 'insertAfter', [], 0);
const update = () => fillOptions(order, siblings(s, Number(parent.value), id));
parent.addEventListener('change', update); update(); finish();
}
function channelDelete(s, id) {
const c = channel(s, id); page(s, 'channel.delete');
let force;
const { f, finish } = form(s, 'channel.delete', async () => { await request(s, 'channel_delete', { channel_id: id, force: force.checked, confirm: c.name }, true); success(s); }, { danger: true, confirm: c.name });
force = field(f, 'forceDelete', 'checkbox');
force.disabled = !permission(s, 'b_channel_delete_flag_force');
finish();
if (!permission(s, `b_channel_delete_${c.channel_type}`)) {
f.querySelector('button').disabled = true;
setStatus(s, L('denied', { permission: `b_channel_delete_${c.channel_type}` }));
}
}
function away(s) {
page(s, 'away'); const me = ownClient(s.conn);
let state, message;
const { f, finish } = form(s, 'save', async () => { await request(s, 'set_away', { away: state.checked, ...(state.checked ? { message: message.value } : {}) }); success(s); refresh(); });
state = field(f, 'away', 'checkbox', me?.away);
message = field(f, 'awayMessage', 'text', me?.away_message ?? '', { maxLength: 80 });
message.disabled = !state.checked; state.addEventListener('change', () => { message.disabled = !state.checked; }); finish();
}
function talkRequest(s, requested = true) {
page(s, requested ? 'talk.request' : 'talk.withdraw'); let message;
const { f, finish } = form(s, requested ? 'talk.request' : 'talk.withdraw', async () => { await request(s, 'talk_request', { request: requested, ...(requested ? { message: message.value } : {}) }); success(s); });
if (requested) message = field(f, 'message', 'text', '', { maxLength: 50 }); finish();
}
function talkQueue(s) {
page(s, 'talk.queue');
const actions = h('div', { class: 'adm-dialog-actions' }); s.body.append(actions);
action(s, actions, 'talk.request', () => talkRequest(s), 'b_client_request_talker');
action(s, actions, 'talk.withdraw', () => talkRequest(s, false));
action(s, actions, 'refresh', () => talkQueue(s));
const clients = [...s.conn.snap.clients].filter((c) => c.talk_request || c.is_talker).sort((a, b) => (a.talk_request?.time_unix ?? Infinity) - (b.talk_request?.time_unix ?? Infinity));
if (!clients.length) s.body.append(h('p', { class: 'client-detail', text: L('talk.empty') }));
for (const c of clients) {
const entry = h('div', { class: 'adm-dialog-row' }, h('strong', { text: c.nickname }), h('span', { text: c.talk_request?.message ?? '' }));
action(s, entry, c.is_talker ? 'talk.revoke' : 'talk.grant', () => run(s, async () => { await request(s, 'talk_power', { client_id: c.id, uid: c.uid, grant: !c.is_talker }, true); success(s); }), 'b_client_set_flag_talker', c.is_talker);
action(s, entry, 'info', () => { void openAdminAction('client.info', { connectionId: s.conn.id, clientId: c.id }); });
s.body.append(entry);
}
const targets = new Map(s.conn.snap.clients.filter((c) => c.uid).map((c) => [c.id, { id: c.id, uid: c.uid, nickname: c.nickname }]));
const target = select(s.body, 'client', [...targets.values()].map((c) => [c.id, c.nickname]), s.conn.snap.own_client_id);
const grants = h('div', { class: 'adm-dialog-actions' }); s.body.append(grants);
for (const grant of [true, false]) action(s, grants, grant ? 'talk.grant' : 'talk.revoke', () => run(s, async () => {
const c = targets.get(Number(target.value));
if (!c?.uid) throw new Error(L('changed'));
await request(s, 'talk_power', { client_id: c.id, uid: c.uid, grant }, true); success(s);
}), 'b_client_set_flag_talker', !grant);
}
function confirmDelete(s, command, args, title, target) {
page(s, title);
const { finish } = form(s, 'delete', async () => { await request(s, command, args, true); success(s); }, { danger: true, confirm: String(target) }); finish();
}
function banCreate(s) {
page(s, 'bans.create'); let ip, name, uid, duration_, reason;
const { f, finish } = form(s, 'bans.create', async () => {
if (![ip, name, uid].some((input) => input.value.trim())) throw new Error(L('banTargetRequired'));
await request(s, 'ban_add', { ip: ip.value, name: name.value, uid: uid.value, duration_s: Number(duration_.value), reason: reason.value }, true); success(s);
});
ip = field(f, 'ip', 'text', '', { maxLength: 255 }); name = field(f, 'namePattern', 'text', '', { maxLength: 255 }); uid = field(f, 'uid', 'text', '', { maxLength: 255 });
duration_ = field(f, 'duration', 'number', 3600, { min: 0, max: 4294967295, step: 1, required: true }); reason = field(f, 'reason', 'text', '', { maxLength: 512 });
const maximum = s.context.permissions?.i_client_ban_max_bantime;
if (maximum != null && maximum >= 0) {
duration_.max = String(maximum);
if (maximum > 0) { duration_.min = '1'; duration_.value = String(Math.min(3600, maximum)); }
}
f.append(h('p', { class: 'client-detail', text: L('banDuration') })); finish();
}
function keyCreate(s) {
page(s, 'keys.create'); let kind, group, target, description;
const { f, finish } = form(s, 'keys.create', async () => {
if (!group.value) throw new Error(L('groupRequired'));
const result = await request(s, 'privilege_key_add', { kind: kind.value, group_id: Number(group.value), ...(kind.value === 'channel_group' ? { channel_id: Number(target.value) } : {}), description: description.value }, true);
success(s); field(s.body, 'token', 'text', result.token, { readOnly: true });
});
kind = select(f, 'keyType', [['server_group', L('serverGroup')], ['channel_group', L('channelGroup')]], 'server_group');
group = select(f, 'group', [], ''); target = select(f, 'channel', channels(s).filter(([id]) => id !== 0), s.channelId);
const update = () => { const values = kind.value === 'server_group' ? s.conn.snap.server_groups : s.conn.snap.channel_groups; fillOptions(group, (values ?? []).filter(regularGroup).map((g) => [g.id, g.name])); target.disabled = kind.value === 'server_group'; };
kind.addEventListener('change', update); update(); description = field(f, 'description', 'text', '', { maxLength: 255 }); finish();
}
function keyUse(s) {
page(s, 'keys.use'); let token;
const { f, finish } = form(s, 'keys.use', async () => { await request(s, 'privilege_key_use', { token: token.value.replace(/^token=/, '').trim() }, true); success(s); });
token = field(f, 'token', 'text', '', { maxLength: 255, required: true }); finish();
}
function passwordCreate(s) {
page(s, 'passwords.create'); let password, description, duration_, target, channelPassword;
const { f, finish } = form(s, 'passwords.create', async () => {
await request(s, 'temp_password_add', { password: password.value, description: description.value, duration_s: Number(duration_.value), channel_id: Number(target.value), channel_password: channelPassword.value }, true); success(s);
});
password = field(f, 'password', 'password', '', { required: true, maxLength: 255 }); description = field(f, 'description', 'text', '', { maxLength: 255 });
duration_ = field(f, 'duration', 'number', 3600, { min: 1, max: 4294967295, step: 1, required: true });
target = select(f, 'channel', channels(s), 0); channelPassword = field(f, 'channelPassword', 'password', '', { maxLength: 255 });
const update = () => { const ch = s.conn.snap.channels.find((c) => c.id === Number(target.value)); channelPassword.required = Boolean(ch?.has_password); channelPassword.disabled = !ch?.has_password; if (channelPassword.disabled) channelPassword.value = ''; };
target.addEventListener('change', update); update(); finish();
}
async function openModal(conn, name, options = {}) {
closeModal();
const title = h('h2', { id: 'admin-heading', text: L('server') });
const body = h('div', { class: 'client-dialog-body' });
const status = h('p', { class: 'client-dialog-status', role: 'status', text: L('loading') });
const footer = h('div', { class: 'client-dialog-footer' }, h('button', { type: 'button', class: 'btn', text: L('close'), onclick: closeModal }));
const dialog = h('dialog', { class: 'client-dialog adm-dialog', 'aria-labelledby': title.id }, title,
h('p', { class: 'client-detail client-target', text: `${conn.snap.server?.name ?? conn.conn.address} — ${conn.conn.address}` }), body, status, footer);
const s = { mode: 'modal', conn, session: conn.session, channelId: options.channelId ?? selectedChannel(conn)?.id, clientId: options.clientId,
anchor: document.activeElement, title, body, status, footer, root: dialog, page: 0, busy: false, context: options.context ?? null, after: options.after ?? null };
modal = s;
dialog.addEventListener('cancel', (e) => { e.preventDefault(); if (!s.busy) closeModal(); });
document.body.append(dialog); dialog.showModal();
await run(s, async () => {
if (!s.context) {
s.context = await request(s, 'admin_context');
if (!Number.isSafeInteger(s.context.generation) || s.context.generation < 1) throw new Error(L('changed'));
}
s.busy = false;
switch (name) {
case 'channel.subscribe':
case 'channel.unsubscribe':
s.busy = true;
await request(s, 'channel_subscribe', { channel_id: s.channelId, subscribe: name === 'channel.subscribe' }); success(s); break;
case 'channel.move': channelMove(s, s.channelId); break;
case 'channel.delete': channelDelete(s, s.channelId); break;
case 'away': away(s); break;
case 'talk.request': talkRequest(s); break;
case 'talk.queue': talkQueue(s); break;
case 'bans.create': banCreate(s); break;
case 'keys.create': keyCreate(s); break;
case 'keys.use': keyUse(s); break;
case 'passwords.create': passwordCreate(s); break;
case 'confirm': confirmDelete(s, options.command, options.args, options.titleKey, options.target); break;
default: closeModal();
}
});
}
// Popups opened from a pane reuse its admin_context and refresh the pane page after an acknowledged change.
function popup(s, name, options = {}) {
const pageAtOpen = s.page;
void openModal(s.conn, name, { channelId: s.channelId, context: s.context, ...options,
after: () => { if (pane === s && alive(s) && s.page === pageAtOpen && !s.busy) s.reopen?.(); } });
}
// ---------- detail pane ----------
function paneView(s, route) {
s.page++;
s.rerender = null;
s.reopen = null;
s.watchChannel = null;
s.view = { kind: route.kind, connectionId: s.conn.id, id: route.id ?? null, title: route.title,
backAction: route.back ?? null, editAction: route.edit ?? null, modes: route.modes ?? null };
emit('admin-view', s.view);
s.status = h('p', { class: 'adm-status', role: 'status' });
s.body = h('div', { class: 'adm-readable' });
s.scroll = h('div', { class: 'adm-scroll' }, s.body);
s.root.replaceChildren(s.scroll);
return s.page;
}
function retitle(s, title) {
if (s.view.title === title) return;
s.view = { ...s.view, title };
emit('admin-view', s.view);
}
const serverRoute = (s, extra = {}) => ({ kind: 'server', title: s.conn.snap.server?.name || s.conn.conn.address, modes: ['info', 'events'], ...extra });
// Sticky navigation bar of the server sub-views (ts-sticky-bar > tsv-navigation-bar): icon + title, actions.
function subpage(s, key, iconName, controls = []) {
const pageNo = paneView(s, serverRoute(s, { back: 'server.info' }));
const bar = h('div', { class: 'adm-navbar' }, h('div', { class: 'adm-navbar-title' }, glyph(iconName), h('h3', { text: L(key) })),
h('div', { class: 'adm-grow' }), ...controls);
s.scroll.replaceChildren(h('div', { class: 'adm-sticky' }, bar), s.body);
return pageNo;
}
function card(cls, ...children) { return h('section', { class: `adm-card ${cls}` }, ...children); }
function gridItem(iconName, lines, full = false) {
return h('div', { class: `adm-grid-item${full ? ' adm-full' : ''}` }, glyph(iconName, 'adm-grid-icon'),
h('div', { class: 'adm-grid-stack' }, ...lines.map(([label, value], i) => h('p', { class: i ? 'adm-grid-sub' : 'adm-grid-title' },
h('span', { class: 'adm-unfocused', text: `${label}: ` }), value instanceof Node ? value : h('span', { class: i && lines.dim ? 'adm-unfocused' : null, text: String(value) })))));
}
function iconButton(iconName, key, fn, cls = '') {
return h('button', { type: 'button', class: `adm-icon-btn${cls ? ` ${cls}` : ''}`, title: L(key), onclick: fn },
glyph(iconName), h('span', { class: 'adm-visually-hidden', text: L(key) }));
}
function advancedToggle(s, targets) {
const label = h('span');
const chevron = h('span', { class: 'adm-advanced-chevron' }, glyph('item-expand'));
const b = h('button', { type: 'button', class: 'adm-advanced', 'aria-expanded': String(Boolean(s.advanced)) }, chevron, label);
const apply = () => {
label.textContent = L(s.advanced ? 'hideAdvanced' : 'showAdvanced');
b.setAttribute('aria-expanded', String(Boolean(s.advanced)));
for (const el of targets) el.hidden = !s.advanced;
};
b.addEventListener('click', () => { s.advanced = !s.advanced; apply(); });
apply();
return { button: b, apply };
}
function sectionTitle(key, toggle) {
return h('div', { class: 'adm-section-title adm-full' }, h('h3', { text: L(key) }), toggle);
}
function actionsCard(s, onCancel, extra = []) {
return card('adm-full adm-actions', ...extra, s.status, h('div', { class: 'adm-actions-buttons' },
h('button', { type: 'button', class: 'btn', text: L('cancel'), onclick: guarded(s, onCancel) }),
h('button', { type: 'submit', class: 'btn btn-primary', text: L('saveOptions') })));
}
function paneForm(s, save) {
const f = h('form', { class: 'adm-widgets adm-form' });
let next = null;
f.addEventListener('submit', (e) => {
e.preventDefault();
if (s.busy || !f.reportValidity()) return;
next = null;
void run(s, async () => { next = await save(); }).then(() => { if (typeof next === 'function' && pane === s && alive(s)) next(); });
});
return f;
}
// Channel icon as the tree draws it (official ChannelGreen / ChannelYellow).
const channelGlyph = (ch) => (ch.has_password ? 'channel-yellow' : 'channel');
function canEditChannel(s) { return anyAllowed(s, 'b_channel_modify_'); }
function channelInfo(s, id, notice = '') {
const c = channel(s, id);
s.channelId = id;
const pageNo = paneView(s, { kind: 'channel', id, title: c.name, edit: canEditChannel(s) ? 'channel.edit' : null });
s.watchChannel = id;
let description = null;
const draw = () => {
const ch = s.conn.snap.channels.find((x) => x.id === id);
if (!ch) { dropPane(L('channelGone')); return; }
retitle(s, ch.name);
const topic = strip(ch.topic);
const users = s.conn.snap.clients.filter((cl) => cl.channel_id === id).length;
const limit = typeof ch.max_clients_limit === 'number' ? ch.max_clients_limit : L('unlimited');
const step = ch.codec_quality == null ? 0 : qualityStep(ch.codec_quality);
const stars = h('span', { class: 'adm-stars', 'aria-label': `${step}/5`, text: '★'.repeat(step) + '☆'.repeat(5 - step) });
const codec = h('span', {}, h('span', { text: codecName(ch.codec) }),
ch.is_unencrypted === false ? h('span', { class: 'adm-codec-lock', title: L('encrypt') }, ' · ', glyph('lock')) : null);
const flags = [ch.is_default && L('flagDefault'), ch.has_password && L('password')].filter(Boolean);
s.body.replaceChildren(s.status, h('div', { class: 'adm-widgets' },
card('adm-full adm-topic-card', h('div', { class: 'adm-topic' }, glyph(channelGlyph(ch), 'adm-topic-icon'),
h('p', { class: `adm-topic-text${topic ? '' : ' is-empty'}`, text: topic || L('noTopic') }))),
card('adm-full adm-description', description ? h('p', { class: 'adm-description-text', text: strip(description) }) : null),
gridItem('user', [[L('users'), `${users} / ${limit}`], [L('subchannels'), s.conn.snap.channels.filter((x) => x.parent_id === id).length]]),
gridItem('microphone', [[L('qualityLabel'), stars], [L('codecLabel'), codec]]),
gridItem('info', [[L('type'), L(ch.channel_type ?? 'temporary')], [L('flags'), flags.length ? flags.join(', ') : L('none')]], true)));
};
s.rerender = draw;
s.reopen = () => channelInfo(s, id);
draw();
void run(s, async () => {
const result = await request(s, 'channel_description', { channel_id: id });
if (pageNo !== s.page) return;
description = result.description ?? '';
draw();
}).then(() => { if (notice && pageNo === s.page && alive(s)) setStatus(s, notice); });
}
// Official ts-info-edit-channel, also used for creation (no channel yet, parent chosen in General).
function channelEdit(s, id, parent = 0) {
const c = id == null ? null : channel(s, id);
const pageNo = paneView(s, c ? { kind: 'channel', id, title: c.name } : { kind: 'channel', id: parent || null, title: L(parent ? 'channel.createChild' : 'channel.create') });
s.channelId = c ? id : parent || s.channelId;
if (c) s.watchChannel = id;
s.reopen = () => channelEdit(s, id, parent);
const dirty = new Map();
const advanced = [];
const adv = (el) => { advanced.push(el); el.hidden = !s.advanced; return el; };
const may = (right) => !c || permission(s, right);
const lock = (input, right) => { if (c && !permission(s, right)) { input.disabled = true; input.title = L('denied', { permission: right }); } return input; };
const text = (input, wire, type = 'text') => input.addEventListener('input', () => dirty.set(wire, () => (type === 'number' ? Number(input.value) : input.value)));
let parentInput, name;
const f = paneForm(s, async () => {
const values = Object.fromEntries([...dirty].map(([key, get]) => [key, get()]));
if (!c) values.channel_name = name.value;
if (!Object.keys(values).length) { setStatus(s, L('noChanges')); return null; }
const result = await request(s, c ? 'channel_edit' : 'channel_create', c ? { channel_id: id, properties: values } : { parent_id: Number(parentInput.value), properties: values }, true);
if (pageNo !== s.page) return null;
const created = Number(result?.channel_id);
if (c) return () => channelInfo(s, id, L('success'));
if (s.conn.snap.channels.some((ch) => ch.id === created)) return () => channelInfo(s, created, L('success'));
return () => createdPage(s, parent);
});
// Topic card: channel icon, editable topic pill.
const topicId = `admin-field-${++fieldId}`;
const topic = lock(control('text', topicId, c?.topic ?? '', { maxLength: 255, placeholder: L('noTopic') }), 'b_channel_modify_topic');
text(topic, 'channel_topic');
const topicCard = card('adm-full adm-topic-card', h('div', { class: 'adm-topic' }, glyph(c ? channelGlyph(c) : 'channel', 'adm-topic-icon'),
glyph('edit', 'adm-pencil'),
h('label', { class: 'adm-topic-field', for: topicId }, h('span', { class: 'adm-visually-hidden', text: L('topic') }), topic, glyph('edit', 'adm-pencil'))));
// Description card: editable text with the official top-right pencil.
const descriptionId = `admin-field-${++fieldId}`;
const description = lock(control('textarea', descriptionId, '', { maxLength: 8192, rows: 1 }), 'b_channel_modify_description');
text(description, 'channel_description');
const descriptionCard = card('adm-full adm-description adm-description-edit',
h('label', { class: 'adm-description-field', for: descriptionId }, h('span', { class: 'adm-visually-hidden', text: L('description') }), description),
glyph('edit', 'adm-pencil adm-pencil-corner'));
if (c) {
void request(s, 'channel_description', { channel_id: id }).then((r) => {
if (alive(s) && pageNo === s.page && !dirty.has('channel_description') && r.description != null) description.value = r.description;
}).catch((e) => { if (alive(s) && pageNo === s.page) setStatus(s, errorText(e), true); });
}
// General: (create: parent + position), name, password, phonetic name.
const general = card('adm-full', h('h4', { text: L('section.general') }));
let order;
if (!c) {
parentInput = rowSelect(general, 'parent', channels(s), parent);
order = rowSelect(general, 'insertAfter', siblings(s, parent), 0);
order.disabled = !permission(s, 'b_channel_create_with_sortorder');
parentInput.addEventListener('change', () => {
fillOptions(order, siblings(s, Number(parentInput.value)));
if (dirty.has('channel_order')) dirty.set('channel_order', () => Number(order.value));
});
order.addEventListener('change', () => dirty.set('channel_order', () => Number(order.value)));
}
name = lock(row(general, 'name', 'text', c?.name ?? '', { maxLength: 40, required: true, placeholder: L('namePlaceholder') }), 'b_channel_modify_name');
text(name, 'channel_name');
const forced = s.context.permissions?.b_channel_create_modify_with_force_password > 0;
const password = row(general, 'password', 'password', '', { maxLength: 1024, required: !c && forced,
placeholder: L(!c && forced ? 'passwordRequiredPlaceholder' : 'passwordPlaceholder') });
if (!may('b_channel_modify_password') || (!c && !permission(s, 'b_channel_create_with_password'))) {
password.disabled = true; password.title = L('denied', { permission: c ? 'b_channel_modify_password' : 'b_channel_create_with_password' });
}
password.addEventListener('input', () => { if (password.value || (!c && forced)) dirty.set('channel_password', () => password.value); else dirty.delete('channel_password'); });
if (!c && forced) dirty.set('channel_password', () => password.value);
general.append(info(L('passwordInfo')));
if (c?.has_password && !forced) {
const removeRow = adv(h('div', { class: 'adm-row-group' }));
const remove = row(removeRow, 'removePassword', 'checkbox', false);
remove.disabled = password.disabled;
remove.addEventListener('change', () => {
password.disabled = remove.checked;
if (remove.checked) { password.value = ''; dirty.set('channel_password', () => ''); } else dirty.delete('channel_password');
});
general.append(removeRow);
}
const phoneticRow = adv(h('div', { class: 'adm-row-group' }));
const phonetic = row(phoneticRow, 'phonetic', 'text', c?.phonetic_name ?? '', { maxLength: 255, placeholder: L('phoneticPlaceholder') });
text(phonetic, 'channel_name_phonetic');
phoneticRow.append(info(L('phoneticInfo')));
general.append(phoneticRow);
// Audio Codec | Audio Quality, side by side.
const codec = h('select', { id: `admin-field-${++fieldId}`, class: 'adm-codec', 'aria-label': L('codec') },
codecs.map((v, i) => h('option', { value: String(i), text: L(`codec.${v}`) })));
codec.value = String(Math.max(0, codecs.indexOf(c?.codec ?? 'opus_voice')));
lock(codec, 'b_channel_modify_codec');
const codecInfo = info('');
const codecCard = card('adm-codec-card', h('h4', { text: L('codec') }), h('div', { class: 'adm-option' }, codec), codecInfo);
const encryptRow = adv(h('div', { class: 'adm-row-group' }));
const encrypt = lock(row(encryptRow, 'encrypt', 'checkbox', c ? c.is_unencrypted !== true : true), 'b_channel_modify_make_codec_encrypted');
encrypt.addEventListener('change', () => dirty.set('channel_codec_is_unencrypted', () => !encrypt.checked));
codecCard.append(encryptRow);
const q0 = c?.codec_quality ?? 6;
const quality = lock(control('number', `admin-field-${++fieldId}`, q0, { min: 0, max: 10, step: 1 }), 'b_channel_modify_codec_quality');
const slider = h('input', { type: 'range', min: '1', max: '5', step: '1', value: String(qualityStep(q0)), 'aria-label': L('qualityTitle') });
slider.disabled = quality.disabled;
const maximum = s.context.permissions?.i_channel_create_modify_with_codec_maxquality;
if (maximum != null && maximum >= 0) { quality.max = String(Math.min(10, maximum)); slider.max = String(Math.max(1, Math.floor(Math.min(10, maximum) / 2))); }
// CSP forbids style attributes; the segment index goes through CSSOM.
const segments = [0, 1, 2, 3, 4].map((i) => { const seg = h('span', { class: 'adm-quality-segment' }); seg.style.setProperty('--i', String(i)); return seg; });
const meter = h('div', { class: 'adm-quality' }, h('div', { class: 'adm-quality-track', 'aria-hidden': 'true' }, ...segments), slider, glyph('slider-knob', 'adm-quality-knob'));
const bandwidthText = h('p', { class: 'adm-info adm-bandwidth' });
const sync = () => {
const step = Number(slider.value);
meter.style.setProperty('--step', String(step));
segments.forEach((seg, i) => seg.setAttribute('data-on', String(i < step)));
slider.setAttribute('aria-valuetext', L(`qualityLevel.${step}`));
const name_ = codecs[Number(codec.value)];
const usage = bandwidth(name_, quality.value);
bandwidthText.textContent = usage ? L('bandwidth', { bandwidth: usage }) : '';
codecInfo.textContent = L(name_ === 'opus_voice' || name_ === 'opus_music' ? `codecInfo.${name_}` : 'codecInfo.legacy');
};
const setQuality = () => dirty.set('channel_codec_quality', () => Number(quality.value));
slider.addEventListener('input', () => { quality.value = String(Number(slider.value) * 2 > Number(quality.max) ? Number(quality.max) : Number(slider.value) * 2); setQuality(); sync(); });
quality.addEventListener('input', () => { slider.value = String(qualityStep(quality.value)); setQuality(); sync(); });
codec.addEventListener('change', () => { dirty.set('channel_codec', () => Number(codec.value)); sync(); });
if (!c) dirty.set('channel_codec', () => Number(codec.value));
const qualityCard = card('adm-quality-card', h('h4', { text: L('qualityTitle') }), meter, bandwidthText);
const qualityAdvanced = adv(h('div', { class: 'adm-row-group' }));
qualityAdvanced.append(h('label', { class: 'adm-row', for: quality.id }, h('span', { class: 'adm-row-label', text: L('quality') }), quality));
if (c) {
const latency = lock(row(qualityAdvanced, 'latency', 'number', c.codec_latency_factor ?? '', { min: 1, max: 10, step: 1 }), 'b_channel_modify_codec');
text(latency, 'channel_codec_latency_factor', 'number');
}
qualityCard.append(qualityAdvanced);
sync();
// Advanced: Moderation (edit only, as before), Type, User Limits.
const cards = [];
if (c) {
const moderation = adv(card('adm-full', h('h4', { text: L('moderation') })));
const talk = lock(row(moderation, 'neededTalk', 'number', c.needed_talk_power ?? '', { min: -2147483648, max: 2147483647, step: 1 }), 'b_channel_modify_needed_talk_power');
text(talk, 'channel_needed_talk_power', 'number');
moderation.append(info(L('neededTalkInfo')));
cards.push(moderation);
}
// Creation picks the lifetime up front, so the Type card is always visible there.
const typeCard = card('adm-full', h('h4', { text: L('type') }));
if (c) adv(typeCard);
const kind = rowSelect(typeCard, 'channelType', ['temporary', 'semi_permanent', 'permanent'].map((v) => [v, L(v)]), c?.channel_type ?? 'temporary');
for (const option of kind.options) option.disabled = !permission(s, `b_channel_${c ? 'modify_make' : 'create'}_${option.value}`);
if (!c && kind.selectedOptions[0]?.disabled) kind.value = [...kind.options].find((option) => !option.disabled)?.value ?? '';
kind.required = true;
const typeInfo = info('');
typeCard.append(typeInfo);
const flagType = () => { dirty.set('channel_flag_permanent', () => kind.value === 'permanent'); dirty.set('channel_flag_semi_permanent', () => kind.value === 'semi_permanent'); };
const syncType = () => { typeInfo.textContent = L(`typeInfo.${kind.value || 'temporary'}`); };
if (!c) flagType();
kind.addEventListener('change', () => { flagType(); syncType(); });
syncType();
const isDefault = lock(row(typeCard, 'defaultChannel', 'checkbox', c?.is_default), 'b_channel_modify_make_default');
isDefault.addEventListener('change', () => dirty.set('channel_flag_default', () => isDefault.checked));
typeCard.append(info(L('defaultChannelInfo')));
const delay = lock(row(typeCard, 'deleteDelay', 'number', c?.delete_delay_s ?? '', { min: 0, max: 4294967295, step: 1 }), 'b_channel_modify_temp_delete_delay');
text(delay, 'channel_delete_delay', 'number');
typeCard.append(info(L('deleteDelayInfo')));
if (c) {
order = rowSelect(typeCard, 'insertAfter', siblings(s, c.parent_id, id), c.order ?? 0);
order.disabled = !permission(s, 'b_channel_modify_sortorder');
order.addEventListener('change', () => dirty.set('channel_order', () => Number(order.value)));
}
cards.push(typeCard);
const limits = adv(card('adm-full', h('h4', { text: L('userLimits') })));
const limitRows = (suffix, value, unlimitedKey, numberKey, infoKey, inheritKey = null) => {
const unlimited = lock(row(limits, unlimitedKey, 'checkbox', value === 'unlimited' || (value == null && !inheritKey)), `b_channel_modify_${suffix}`);
const inherited = inheritKey ? lock(row(limits, inheritKey, 'checkbox', value === 'inherited' || value == null), `b_channel_modify_${suffix}`) : null;
const amount = lock(row(limits, numberKey, 'number', typeof value === 'number' ? value : '', { min: 0, max: 2147483647, step: 1 }), `b_channel_modify_${suffix}`);
limits.append(info(L(infoKey)));
const free = () => unlimited.checked || Boolean(inherited?.checked);
const apply = () => { amount.disabled = (c && !permission(s, `b_channel_modify_${suffix}`)) || free(); amount.required = !free(); };
const mark = () => {
dirty.set(`channel_${suffix}`, () => (free() ? -1 : Number(amount.value)));
dirty.set(`channel_flag_${suffix}_unlimited`, () => unlimited.checked);
if (inherited) dirty.set(`channel_flag_${suffix}_inherited`, () => inherited.checked);
apply();
};
unlimited.addEventListener('change', () => { if (unlimited.checked && inherited) inherited.checked = false; mark(); });
inherited?.addEventListener('change', () => { if (inherited.checked) unlimited.checked = false; mark(); });
amount.addEventListener('input', mark);
apply();
};
limitRows('maxclients', c ? c.max_clients_limit : 'unlimited', 'maxUnlimited', 'maxclients', 'maxInfo');
limitRows('maxfamilyclients', c ? c.max_family_clients_limit : 'inherited', 'familyUnlimited', 'maxfamilyclients', 'familyInfo', 'familyInherited');
cards.push(limits);
const toggle = advancedToggle(s, advanced);
f.append(topicCard, descriptionCard, sectionTitle('channel.edit', toggle.button), general, codecCard, qualityCard, ...cards,
actionsCard(s, () => (c ? channelInfo(s, id) : channelLanding(s, parent))));
s.body.replaceChildren(f);
}
// After an acknowledged create the new channel may not be in the snapshot yet; say so plainly.
function createdPage(s, parent) {
paneView(s, { kind: 'channel', id: parent || null, title: L(parent ? 'channel.createChild' : 'channel.create') });
s.body.replaceChildren(h('div', { class: 'adm-widgets' }, card('adm-full adm-note', h('p', { role: 'status', text: L('success') }))));
}
function channelLanding(s, parent) {
const target = s.conn.snap.channels.find((ch) => ch.id === (parent || selectedChannel(s.conn)?.id));
if (target) channelInfo(s, target.id); else serverInfo(s);
}
function serverInfo(s, notice = '') {
const pageNo = paneView(s, serverRoute(s, { edit: anyAllowed(s, 'b_virtualserver_modify_') ? 'server.edit' : null }));
s.reopen = () => serverInfo(s);
let values = null;
const draw = () => {
const server = s.conn.snap.server ?? {};
const v = values ?? {};
retitle(s, server.name || s.conn.conn.address);
const welcome = strip(server.welcome_message ?? v.virtualserver_welcomemessage);
const online = s.conn.snap.clients.filter((cl) => cl.client_type !== 'query').length;
const max = v.virtualserver_maxclients;
s.body.replaceChildren(s.status, h('div', { class: 'adm-widgets' },
card('adm-full adm-banner'),
card(`adm-full adm-welcome${welcome ? '' : ' is-empty'}`, h('p', { text: welcome || L('noWelcome') })),
transferCard(s, v, draw),
manageCard(s),
gridItem('user', [[L('users'), max == null ? String(online) : `${online} / ${max}`], [L('channels'), s.conn.snap.channels.length]]),
gridItem('info', [[L('uptime'), v.virtualserver_uptime == null ? L('unknownValue') : duration(v.virtualserver_uptime)], [L('created'), date(v.virtualserver_created)]])),
h('p', { class: 'adm-footnote', text: [version(server.version ?? v.virtualserver_version), server.platform ?? v.virtualserver_platform].filter(Boolean).join(' • ') }));
};
s.rerender = draw;
draw();
void run(s, async () => {
const result = await request(s, 'server_info');
if (pageNo !== s.page) return;
values = Object.assign({}, ...(result.rows ?? []));
draw();
}).then(() => { if (notice && pageNo === s.page && alive(s)) setStatus(s, notice); });
}
// File Transfer Info (ftQuota widget): monthly quota and lifetime totals from servergetvariables.
function transferCard(s, v, draw) {
const open = Boolean(s.ftOpen);
const toggle = h('button', { type: 'button', class: 'adm-ft-toggle', 'aria-expanded': String(open), title: L('ftInfo'),
onclick: () => { s.ftOpen = !s.ftOpen; draw(); s.ftToggle?.focus({ preventScroll: true }); } }, glyph('navigation-back'),
h('span', { class: 'adm-visually-hidden', text: L('ftInfo') }));
s.ftToggle = toggle;
const quota = (used, limit) => {
const max = Number(limit);
const unlimited = limit == null || !Number.isFinite(max) || max < 0 || max >= 2 ** 53;
return L('ftOf', { used: bytes(used), quota: unlimited ? L('unlimited') : bytes(max * 1024 * 1024) });
};
return card('adm-ft', h('div', { class: 'adm-card-head' }, h('h4', { text: L('ftInfo') }), toggle),
open ? h('div', { class: 'adm-ft-body' },
h('p', { class: 'adm-card-subtitle', text: L('ftMonthly') }),
h('p', {}, h('span', { class: 'adm-unfocused', text: `${L('ftDownload')}: ` }), quota(v.virtualserver_month_bytes_downloaded, v.virtualserver_download_quota)),
h('p', {}, h('span', { class: 'adm-unfocused', text: `${L('ftUpload')}: ` }), quota(v.virtualserver_month_bytes_uploaded, v.virtualserver_upload_quota)),
h('p', { class: 'adm-card-subtitle', text: L('ftTotal') }),
h('p', {}, h('span', { class: 'adm-unfocused', text: `${L('ftDownload')}: ` }), bytes(v.virtualserver_total_bytes_downloaded)),
h('p', {}, h('span', { class: 'adm-unfocused', text: `${L('ftUpload')}: ` }), bytes(v.virtualserver_total_bytes_uploaded))) : null);
}
function serverIconsPage(s) {
const tools = h('div', { class: 'adm-navbar-tools' });
const pageNo = subpage(s, 'icons', 'server-icons', [tools]);
s.reopen = () => serverIconsPage(s);
s.serverIcons?.close();
s.serverIcons = openServerIcons(s.conn.id, {
host: s.body, toolbar: tools,
onBack: () => { if (pane === s && s.page === pageNo) openPane(s.conn, 'server.info'); },
});
}
function manageCard(s) {
const entry = ([key, iconName, fn, right]) => deny(h('button', { type: 'button', class: 'adm-link', onclick: guarded(s, fn) }, glyph(iconName), h('span', { text: L(key) })), s, right);
const official = [
['permissions', 'mode-server-permissions', () => permissionsPage(s)],
['bans', 'mode-server-bans', () => listPage(s, 'bans'), 'b_client_ban_list'],
['keys', 'privilege-key', () => listPage(s, 'keys'), 'b_virtualserver_token_list'],
['passwords', 'lock-opened', () => listPage(s, 'passwords')],
['icons', 'server-icons', () => serverIconsPage(s)],
['clients', 'groups', () => database(s), 'b_virtualserver_client_dblist'],
['snapshots', 'settings-addons', () => openServerSnapshots(s.conn.id)],
];
// TeamsPeach actions with no Manage entry in the official client, kept below a divider.
const subscribe = (flag) => run(s, async () => { await request(s, 'channel_subscribe_all', { subscribe: flag }); setStatus(s, L('success')); });
const extensions = [
['serverChat', 'mode-chat', () => emit('show-server-chat')],
['localRecording', 'mode-recording', () => emit('set-view', 'recording')],
['log', 'mode-events', () => serverLog(s), 'b_virtualserver_log_view'],
['subscribeAll', 'visible', () => { void subscribe(true); }],
['unsubscribeAll', 'hidden', () => { void subscribe(false); }],
];
return card('adm-manage', h('p', { class: 'adm-card-subtitle', text: L('manage') }), ...official.map(entry),
h('div', { class: 'adm-divider', role: 'separator' }), ...extensions.map(entry));
}
function serverEdit(s) {
const pageNo = paneView(s, serverRoute(s));
s.reopen = () => serverEdit(s);
s.body.replaceChildren(s.status);
void run(s, async () => {
const result = await request(s, 'server_info');
if (pageNo !== s.page) return;
const existing = Object.assign({}, ...(result.rows ?? []));
const dirty = new Map();
const advanced = [];
const inputs = {};
const f = paneForm(s, async () => {
if (!confirmed.checked) return null;
const values = Object.fromEntries([...dirty].map(([key, get]) => [key, get()]));
if (!Object.keys(values).length) { setStatus(s, L('noChanges')); return null; }
await request(s, 'server_edit', { confirm: s.context.server_uid, properties: values }, true);
return pageNo === s.page ? () => serverInfo(s, L('success')) : null;
});
const make = (parent, key) => {
const [, , type, max] = serverFields.find(([, k]) => k === key);
const wire = `virtualserver_${key}`;
const input = field(parent, `serverField.${key}`, type, type === 'checkbox' ? existing[wire] === '1' : existing[wire] ?? '',
type === 'number' ? { min: key === 'priority_speaker_dimm_modificator' ? undefined : 0, max: max ?? Number.MAX_SAFE_INTEGER, step: key === 'priority_speaker_dimm_modificator' ? 'any' : 1 } : { maxLength: max },
key === 'welcomemessage' ? 'adm-description-field' : 'adm-row');
input.addEventListener('input', () => dirty.set(wire, () => (type === 'checkbox' ? input.checked : type === 'number' ? Number(input.value) : input.value)));
input.addEventListener('change', () => { if (type === 'checkbox') dirty.set(wire, () => input.checked); });
if (key === 'name' && !permission(s, 'b_virtualserver_modify_name')) input.disabled = true;
inputs[key] = input;
return input;
};
const welcome = card('adm-full adm-description adm-description-edit');
make(welcome, 'welcomemessage');
inputs.welcomemessage.parentNode.children[0].className = 'adm-visually-hidden';
welcome.append(glyph('edit', 'adm-pencil adm-pencil-corner'));
const cards = [];
for (const [section, keys] of serverCards) {
const el = card('adm-full', h('h4', { text: L(`section.${section}`) }));
const list = keys ?? serverFields.filter(([category]) => category === section).map(([, key]) => key);
for (const key of list) {
if (key === 'nickname') {
const wrap = h('div', { class: 'adm-row-group' });
make(wrap, key);
advanced.push(wrap);
el.append(wrap);
continue;
}
make(el, key);
if (key === 'name_phonetic') el.append(info(L('phoneticInfo')));
}
if (section === 'general') {
const password = row(el, 'password', 'password', '', { maxLength: 1024, placeholder: L('serverPasswordPlaceholder') });
password.addEventListener('input', () => { if (password.value) dirty.set('virtualserver_password', () => password.value); else dirty.delete('virtualserver_password'); });
el.append(info(L('serverPasswordInfo')));
const removeRow = h('div', { class: 'adm-row-group' });
const remove = row(removeRow, 'removePassword', 'checkbox', false);
remove.addEventListener('change', () => {
password.disabled = remove.checked;
if (remove.checked) { password.value = ''; dirty.set('virtualserver_password', () => ''); } else dirty.delete('virtualserver_password');
});
advanced.push(removeRow); el.append(removeRow);
}
if (keys === null) advanced.push(el);
cards.push(el);
}
for (const el of advanced) el.hidden = !s.advanced;
const toggle = advancedToggle(s, advanced);
const target = `${s.conn.snap.server?.name ?? s.conn.conn.address} (${s.context.server_uid})`;
const confirmBox = h('div', { class: 'adm-confirm' }, h('p', { class: 'adm-info', text: L('confirmTarget', { target }) }));
const confirmed = row(confirmBox, 'confirm', 'checkbox', false, { required: true });
f.append(card('adm-full adm-banner'), welcome, sectionTitle('server.edit', toggle.button), ...cards,
actionsCard(s, () => serverInfo(s), [confirmBox]));
s.body.replaceChildren(f);
});
}
function clientInfo(s, id) {
const cl = s.conn.snap.clients.find((c) => c.id === id);
if (!cl?.uid) throw new Error(L('changed'));
const pageNo = paneView(s, { kind: 'client', id, title: cl.nickname, modes: ['info', 'chat'] });
s.clientId = id;
s.reopen = () => clientInfo(s, id);
let values = null;
const draw = () => {
const client = s.conn.snap.clients.find((c) => c.id === id);
if (!client) { dropPane(L('changed')); return; }
retitle(s, client.nickname);
const v = values ?? {};
const text = strip(client.description ?? v.client_description);
const serverGroups = (client.server_groups ?? []).map((gid) => s.conn.snap.server_groups?.find((g) => g.id === gid)).filter(Boolean);
const channelGroup = s.conn.snap.channel_groups?.find((g) => g.id === client.channel_group_id);
const groups = [...serverGroups.map((g) => groupEntry(g)), channelGroup ? groupEntry(channelGroup, L('channelGroupBadge')) : null].filter(Boolean);
const connected = v.connection_connected_time == null ? L('unknownValue') : duration(Number(v.connection_connected_time) / 1000);
const total = v.client_totalconnections == null ? L('unknownValue') : Number(v.client_totalconnections);
s.body.replaceChildren(s.status, h('div', { class: 'adm-widgets' },
card('adm-full adm-topic-card adm-deep', h('div', { class: 'adm-topic' }, glyph('avatar', 'adm-avatar'),
h('p', { class: `adm-topic-text${text ? '' : ' is-empty'}`, text: text || L('noDescription') }))),
card('adm-full adm-deep adm-groups', h('h4', { text: L('groups') }),
groups.length ? h('div', { class: 'adm-group-list' }, ...groups) : h('p', { class: 'adm-empty-text', text: L('groupsEmpty') })),
card('adm-full adm-deep adm-badges', h('h4', { text: t('client.info.badges.title') }), badgeShowcase(client.badges)),
gridItem('server-connect', Object.assign([[L('connected'), connected], [L('firstConnection'), date(v.client_created)]], { dim: true })),
gridItem('globe', Object.assign([[L('location'), region(client.country ?? v.client_country)], [L('totalConnections'), total]], { dim: true }))),
h('p', { class: 'adm-footnote' }, h('span', { text: `${L('uidShort')}: ${client.uid}` }), h('br'),
h('span', { text: [version(v.client_version), v.client_platform].filter(Boolean).join(' • ') })));
};
s.rerender = draw;
draw();
void run(s, async () => {
const result = await request(s, 'client_info', { client_id: id, uid: cl.uid });
if (pageNo !== s.page) return;
values = Object.assign({}, ...(result.rows ?? [result]));
draw();
});
}
// Snapshot group types are regular / template / query (core snapshot.rs group_type); only regular groups are assignable.
const regularGroup = (g) => g.type !== 'template' && g.type !== 'query';
function groupIcon(group) {
return glyph(GROUP_ICONS.has(Number(group.icon_id)) ? `group-${group.icon_id}` : 'empty', 'adm-group-icon');
}
function groupEntry(group, badge = null) {
return h('div', { class: 'adm-group' }, groupIcon(group), h('span', { text: group.name }), badge ? h('span', { class: 'adm-badge', text: badge }) : null);
}
function permissionsPage(s) {
const search = h('input', { type: 'search', class: 'adm-search-input', placeholder: L('search'), 'aria-label': L('search') });
subpage(s, 'permissions', 'mode-server-permissions', [h('label', { class: 'adm-search' }, glyph('search'), search)]);
s.reopen = () => permissionsPage(s);
const list = h('div', { class: 'adm-widgets adm-sub-widgets' });
const draw = () => {
const query = search.value.trim().toLowerCase();
const server = s.conn.snap.server ?? {};
const section = (key, groups, defaultId, badge) => {
const shown = (groups ?? []).filter((g) => regularGroup(g) && (!query || g.name.toLowerCase().includes(query)));
return card('adm-full adm-deep adm-group-card', h('h4', { text: L(key) }),
shown.length ? h('div', { class: 'adm-group-list' }, ...shown.map((g) => groupEntry(g, g.id === defaultId ? badge : null)))
: h('p', { class: 'adm-empty-text', text: L('noResults') }));
};
list.replaceChildren(
section('serverGroups', s.conn.snap.server_groups, server.default_server_group, L('serverGuests')),
section('channelGroups', s.conn.snap.channel_groups, server.default_channel_group, L('channelGuests')));
};
search.addEventListener('input', draw);
s.rerender = draw;
s.body.replaceChildren(s.status, list);
draw();
}
const lists = {
bans: { icon: 'mode-server-bans', command: 'ban_list', create: 'bans.create', right: 'b_client_ban_create', empty: 'bansEmpty' },
keys: { icon: 'privilege-key', command: 'privilege_key_list', create: 'keys.create', right: 'b_virtualserver_token_add', empty: 'keysEmpty' },
passwords: { icon: 'lock-opened', command: 'temp_password_list', create: 'passwords.create', empty: 'passwordsEmpty' },
};
function listEntry(iconName, title, lines) {
return h('div', { class: 'adm-list-item' }, glyph(iconName, 'adm-list-icon'),
h('div', { class: 'adm-list-text' }, h('p', { class: 'adm-list-title', text: title }), ...lines.filter(Boolean).map((line) => h('p', { class: 'adm-list-sub', text: line }))),
);
}
function emptyEntry(key) {
return h('div', { class: 'adm-list-item adm-list-empty' }, glyph('empty', 'adm-list-icon'), h('p', { class: 'adm-list-title', text: L(key) }));
}
function listPage(s, kind) {
const spec = lists[kind];
const clear = deny(h('button', { type: 'button', class: 'btn btn-primary btn-danger btn-bar', text: L('clearList'), hidden: true,
onclick: guarded(s, () => popup(s, 'confirm', { command: 'ban_delete_all', args: { confirm: 'all_bans' }, titleKey: 'bans.deleteAll', target: L('allBans') })) }), s, 'b_client_ban_delete');
const controls = [
kind === 'bans' ? clear : null,
kind === 'keys' ? deny(h('button', { type: 'button', class: 'btn btn-ghost btn-bar', text: L('keys.use'), onclick: guarded(s, () => popup(s, 'keys.use')) }), s, 'b_virtualserver_token_use') : null,
deny(h('button', { type: 'button', class: 'btn btn-primary btn-bar', text: L('create'), onclick: guarded(s, () => popup(s, spec.create)) }), s, spec.right),
iconButton('refresh', 'refresh', guarded(s, () => listPage(s, kind)), 'adm-tinted'),
].filter(Boolean);
const pageNo = subpage(s, kind, spec.icon, controls);
s.reopen = () => listPage(s, kind);
const data = h('div', { class: 'adm-list' });
s.body.replaceChildren(s.status, data);
void run(s, async () => {
const result = await request(s, spec.command);
if (pageNo !== s.page) return;
const rows = result.rows ?? [];
clear.hidden = !rows.length;
if (!rows.length) { data.append(emptyEntry(spec.empty)); return; }
for (const r of rows) {
let args, command, target, entry;
const remove = () => iconButton('item-close', 'delete', (event) => {
if (!alive(s) || s.busy) return;
const [key, subtitle] = { bans: ['delete_ban', 'server.banlist.delete.warning'], keys: ['delete_privilege_key', 'server.privilege_keys.delete.warning'], passwords: ['delete_temp_pw', 'server.temp_passwords.delete.confirm'] }[kind];
void confirmAction(event, key, t(subtitle), () => run(s, async () => { await request(s, command, args, true); s.reopen?.(); }),
{ onSaveError: (error) => setStatus(s, errorText(error), true) });
}, 'adm-destructive');
if (kind === 'bans') {
target = r.banid; command = 'ban_delete'; args = { ban_id: Number(target), confirm: String(target) };
const title = r.name || r.ip || r.uid || r.mytsid || String(target);
const lasting = Number(r.duration) > 0 ? L('banExpires', { date: date(Number(r.created) + Number(r.duration)) }) : L('permanent');
entry = listEntry('mode-server-bans', title, [[r.ip, r.uid].filter((x) => x && x !== title).join(' · '),
r.reason ? L('banReason', { text: r.reason }) : L('noReason'), [lasting, r.invokername ? L('bannedBy', { name: r.invokername }) : null].filter(Boolean).join(' · ')]);
} else if (kind === 'keys') {
target = r.token; command = 'privilege_key_delete'; args = { token: target, confirm: target };
const channelKey = String(r.token_type) === '1';
const group = (channelKey ? s.conn.snap.channel_groups : s.conn.snap.server_groups)?.find((g) => String(g.id) === String(r.token_id1));
const ch = channelKey ? s.conn.snap.channels.find((x) => String(x.id) === String(r.token_id2)) : null;
entry = listEntry('privilege-key', target, [[L(channelKey ? 'channelGroup' : 'serverGroup'), group?.name ?? r.token_id1, ch?.name].filter((x) => x != null && x !== '').join(' · '),
r.token_description, r.token_created ? L('createdOn', { date: date(r.token_created) }) : null]);
} else {
target = r.pw; command = 'temp_password_delete'; args = { password: target, confirm: target };
const ch = s.conn.snap.channels.find((x) => String(x.id) === String(r.tcid));
entry = listEntry('lock-opened', target, [r.desc, [r.end ? L('validUntil', { date: date(r.end) }) : null, ch?.name, r.nickname].filter(Boolean).join(' · ')]);
}
if (target != null) entry.append(deny(remove(), s, kind === 'keys' ? 'b_virtualserver_token_delete' : kind === 'bans' ? 'b_client_ban_delete' : null));
data.append(entry);
}
});
}
// Client List (official server client list): search by nickname or UID, page size in the footer.
function database(s, start = 0, search = null, size = s.pageSize ?? 25) {
s.pageSize = size;
const by = h('select', { class: 'adm-by', 'aria-label': L('searchBy') }, h('option', { value: 'name', text: L('nickname') }), h('option', { value: 'uid', text: L('uidShort') }));
by.value = search?.uid ? 'uid' : 'name';
const pattern = h('input', { type: 'search', class: 'adm-search-input', placeholder: L('search'), 'aria-label': L('searchPattern'), maxLength: 1024, value: search?.pattern ?? '' });
const find = h('form', { class: 'adm-bar-form' }, by, h('label', { class: 'adm-search' }, glyph('search'), pattern));
find.addEventListener('submit', (e) => {
e.preventDefault();
if (!alive(s) || s.busy) return;
const text = pattern.value.trim();
database(s, 0, text ? { pattern: text, uid: by.value === 'uid' } : null, size);
});
const pageNo = subpage(s, 'clients', 'groups', [find, iconButton('refresh', 'refresh', guarded(s, () => database(s, start, search, size)), 'adm-tinted')]);
s.reopen = () => database(s, start, search, size);
const data = h('div', { class: 'adm-list' });
s.body.replaceChildren(s.status, data);
const summary = h('p', { class: 'adm-footer-text', text: L('pagination', { start: 0, end: 0, total: 0 }) });
const previous = iconButton('navigation-back', 'previous', guarded(s, () => database(s, Math.max(0, start - size), null, size)), 'adm-tinted');
const next = iconButton('navigation-forward', 'next', guarded(s, () => database(s, start + size, null, size)), 'adm-tinted');
const perPage = h('select', { class: 'adm-page-size', 'aria-label': L('pageSize') }, [25, 50, 100].map((n) => h('option', { value: String(n), text: String(n) })));
perPage.value = String(size);
perPage.addEventListener('change', guarded(s, () => database(s, 0, search, Number(perPage.value))));
previous.disabled = true; next.disabled = true;
previous.hidden = Boolean(search); next.hidden = Boolean(search); perPage.hidden = Boolean(search);
s.root.append(h('footer', { class: 'adm-footer' }, summary, h('div', { class: 'adm-grow' }), previous, next, perPage));
void run(s, async () => {
const result = await request(s, search ? 'client_database_find' : 'client_database_list', search ?? { start, duration: size });
if (pageNo !== s.page) return;
const rows = result.rows ?? [];
if (!rows.length) data.append(emptyEntry('noResults'));
for (const r of rows) {
const id = Number(r.cldbid);
const entry = listEntry('user', r.client_nickname ?? String(r.cldbid), [r.client_unique_identifier,
r.client_lastconnected ? L('lastConnection', { date: date(r.client_lastconnected) }) : null]);
if (Number.isSafeInteger(id) && id > 0) {
entry.append(deny(iconButton('item-close', 'delete', guarded(s, () => popup(s, 'confirm', { command: 'client_database_delete',
args: { client_database_id: id, confirm: String(id) }, titleKey: 'clients.delete', target: `${r.client_nickname ?? ''} (${id})` })), 'adm-destructive'), s, 'b_client_delete_dbproperties'));
}
data.append(entry);
}
const total = Number(rows[0]?.count);
const end = rows.length ? start + rows.length : start;
summary.textContent = Number.isFinite(total) ? L('pagination', { start: rows.length ? start + 1 : 0, end, total })
: rows.length ? L('page', { start: start + 1, end }) : L('pagination', { start: 0, end: 0, total: 0 });
previous.disabled = start === 0;
next.disabled = rows.length < size;
});
}
function serverLog(s) {
const pageNo = subpage(s, 'log', 'mode-events');
s.reopen = () => serverLog(s);
const output = h('div', { class: 'adm-list adm-log' });
const f = h('form', { class: 'adm-widgets adm-sub-widgets' });
const controls = card('adm-full adm-deep');
const lines = row(controls, 'logLines', 'number', 100, { required: true, min: 1, max: 1000, step: 1 });
const position = row(controls, 'logPosition', 'number', 0, { required: true, min: 0, max: Number.MAX_SAFE_INTEGER, step: 1 });
const reverse = row(controls, 'logReverse', 'checkbox', true);
const instance = row(controls, 'logInstance', 'checkbox');
controls.append(h('div', { class: 'adm-actions-buttons adm-actions-end' }, h('button', { type: 'submit', class: 'btn btn-primary', text: L('load') })));
f.append(controls);
f.addEventListener('submit', (e) => {
e.preventDefault();
if (s.busy || !f.reportValidity()) return;
void run(s, async () => {
const result = await request(s, 'server_log', { lines: Number(lines.value), begin_pos: Number(position.value), reverse: reverse.checked, instance: instance.checked });
if (pageNo !== s.page) return;
const rows = result.rows ?? [];
output.replaceChildren(...(rows.length ? rows.map((r) => h('p', { class: 'adm-log-line', text: r.l ?? Object.entries(r).map(([k, v]) => `${k}=${v}`).join(' ') }))
: [emptyEntry('noResults')]));
});
});
s.body.replaceChildren(s.status, f, output);
}
async function openPane(conn, name, options = {}) {
const el = host();
if (!el) return;
closeModal();
const s = { mode: 'pane', conn, session: conn.session, root: h('div', { class: 'adm-view' }), page: 0, busy: false, context: null,
advanced: pane?.advanced ?? false, ftOpen: pane?.ftOpen ?? false,
channelId: options.channelId ?? selectedChannel(conn)?.id, clientId: options.clientId };
pane = s;
emit('set-view', 'channel-info');
if (pane !== s) return;
el.replaceChildren(s.root);
const ch = conn.snap.channels.find((c) => c.id === s.channelId);
const client = conn.snap.clients.find((c) => c.id === s.clientId);
paneView(s, name === 'client.info' && client ? { kind: 'client', id: client.id, title: client.nickname, modes: ['info', 'chat'] }
: name.startsWith('channel.') && ch ? { kind: 'channel', id: ch.id, title: ch.name } : serverRoute(s));
s.body.append(s.status);
await run(s, async () => {
s.context = await request(s, 'admin_context');
if (!Number.isSafeInteger(s.context.generation) || s.context.generation < 1) throw new Error(L('changed'));
});
if (!alive(s) || !s.context) return;
try {
switch (name) {
case 'server.edit': serverEdit(s); break;
case 'channel.info': case 'channel.info.inline': case 'channel.manage': channelInfo(s, s.channelId); break;
case 'channel.edit': channelEdit(s, s.channelId); break;
case 'channel.create': channelEdit(s, null, 0); break;
case 'channel.createChild': channelEdit(s, null, s.channelId); break;
case 'client.info': clientInfo(s, s.clientId); break;
case 'permissions': permissionsPage(s); break;
case 'bans': case 'keys': case 'passwords': listPage(s, name); break;
case 'clients': database(s); break;
case 'log': serverLog(s); break;
default: serverInfo(s);
}
} catch (error) { if (alive(s)) setStatus(s, errorText(error), true); }
}
// ---------- channel context menu ----------
function closeChannelPopup() {
const p = channelPopup;
if (!p) return;
channelPopup = null;
document.removeEventListener('pointerdown', p.outside, true);
window.removeEventListener('resize', closeChannelPopup);
p.node.remove();
if (p.anchor?.isConnected) p.anchor.focus({ preventScroll: true });
}
async function openChannelPopup(event, rowEl) {
closeChannelPopup();
const conn = viewedConnection();
const id = Number(rowEl.dataset.cid);
const ch = conn?.snap?.channels.find((c) => c.id === id);
if (!isConnected(conn) || !ch) return;
const anchor = rowEl.querySelector('.row-btn');
const keyboard = event.type === 'keydown';
const rect = keyboard ? anchor.getBoundingClientRect() : { left: event.clientX, right: event.clientX, top: event.clientY, bottom: event.clientY };
const node = h('div', { class: 'client-menu', role: 'menu', 'aria-label': ch.name, tabindex: -1 }, h('div', { class: 'client-menu-title', text: ch.name }));
const p = { conn, session: conn.session, node, anchor, outside: (e) => { if (!node.contains(e.target)) closeChannelPopup(); } };
channelPopup = p;
const valid = () => channelPopup === p && isAlive(conn) && isConnected(conn) && viewedConnection() === conn && conn.session === p.session;
const item = (key, fn, destructive = false) => {
const b = h('button', { type: 'button', class: `client-menu-item${destructive ? ' destructive' : ''}`, role: 'menuitem', text: L(key), onclick: () => {
if (!valid()) return;
closeChannelPopup(); fn();
} }); node.append(b); return b;
};
const open = (name) => openAdminAction(name, { connectionId: conn.id, channelId: id });
if (ch.id !== conn.snap.own_channel_id) item('join', () => joinChannel(id));
item('info', () => open('channel.info'));
item('files', () => openFileBrowser(conn, id));
const edit = item('channel.edit', () => open('channel.edit'));
const remove = item('channel.delete', () => open('channel.delete'), true);
node.append(h('div', { class: 'client-menu-section', text: L('channel.manage') }));
item('channel.createChild', () => open('channel.createChild'));
item('channel.move', () => open('channel.move'));
item(ch.subscribed ? 'unsubscribe' : 'subscribe', () => open(ch.subscribed ? 'channel.unsubscribe' : 'channel.subscribe'));
document.body.append(node);
const size = node.getBoundingClientRect();
const pos = menuPosition(rect, size, { width: innerWidth, height: innerHeight, top: 40 });
node.style.left = `${pos.x}px`; node.style.top = `${pos.y}px`;
node.addEventListener('keydown', (e) => {
const entries = [...node.querySelectorAll('[role="menuitem"]')].filter((b) => !b.disabled);
const index = entries.indexOf(document.activeElement);
if (e.key === 'Escape' || e.key === 'Tab') { if (e.key === 'Escape') e.preventDefault(); closeChannelPopup(); }
else if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) {
e.preventDefault(); entries[e.key === 'Home' ? 0 : e.key === 'End' ? entries.length - 1 : (index + (e.key === 'ArrowDown' ? 1 : entries.length - 1)) % entries.length]?.focus();
}
});
document.addEventListener('pointerdown', p.outside, true);
window.addEventListener('resize', closeChannelPopup);
node.querySelector('button')?.focus({ preventScroll: true });
try {
const context = await callOn(conn.id, 'admin_context', {});
if (!valid()) return;
const values = Object.entries(context.permissions ?? {}).filter(([name]) => name.startsWith('b_channel_modify_')).map(([, v]) => v);
edit.disabled = values.length > 0 && values.every((v) => v === 0);
remove.disabled = context.permissions?.[`b_channel_delete_${ch.channel_type}`] === 0;
if (edit.disabled) edit.title = L('denied', { permission: 'b_channel_modify_*' });
if (remove.disabled) remove.title = L('denied', { permission: `b_channel_delete_${ch.channel_type}` });
} catch (error) { if (valid()) node.append(h('p', { class: 'client-menu-note', role: 'status', text: errorText(error) })); }
}
// ---------- public API ----------
/** Called by the shell when the viewed server or selected channel changes while the info view is shown. */
export async function renderChannelInfo(options = {}) {
const el = host();
if (!el || el.hidden) return;
const conn = options.connectionId ? connectionById(options.connectionId) : viewedConnection();
const id = options.channelId ?? selectedChannel(conn)?.id;
if (!isConnected(conn) || viewedConnection() !== conn || !conn.snap.channels.some((c) => c.id === id)) {
dropPane(null);
el.replaceChildren(h('p', { class: 'adm-gone', role: 'status', text: L('channelGone') }));
return;
}
// Keep the shown channel (info or settings) when the selection did not move away from it.
if (options.channelId == null && pane && alive(pane) && pane.watchChannel === id) return;
await openPane(conn, 'channel.info', { channelId: id });
}
export async function openAdminAction(actionName = 'server', options = {}) {
const conn = options.connectionId ? connectionById(options.connectionId) : viewedConnection();
if (!isConnected(conn) || viewedConnection() !== conn) return;
closeChannelPopup();
if (PANE_ROUTES.has(actionName)) await openPane(conn, actionName, options);
else await openModal(conn, actionName, options);
}
function refresh() {
if (modal && !alive(modal)) closeModal();
if (channelPopup && (!isConnected(channelPopup.conn) || viewedConnection() !== channelPopup.conn || channelPopup.conn.session !== channelPopup.session)) closeChannelPopup();
if (pane && !alive(pane)) dropPane(L('changed'));
else if (pane?.watchChannel != null && !pane.conn.snap.channels.some((c) => c.id === pane.watchChannel)) dropPane(L('channelGone'));
else if (pane?.rerender && !pane.busy) pane.rerender();
const conn = viewedConnection();
const connected = isConnected(conn); const me = ownClient(conn);
for (const id of ['btn-away', 'btn-create-channel', 'btn-info', 'btn-server-admin', 'btn-talk-power']) {
const el = document.getElementById(id); if (!el) continue;
// The server card title (#btn-server-admin) carries the server name and state, so it is never hidden.
if (id !== 'btn-server-admin') el.hidden = !connected;
el.disabled = !connected;
if (id === 'btn-away') { el.setAttribute('aria-pressed', String(Boolean(me?.away))); el.title = L(me?.away ? 'available' : 'away'); }
if (id === 'btn-talk-power') {
el.title = L(me?.talk_request ? 'talk.pending' : 'talk.queue');
el.hidden = !connected || !conn.snap.clients.some((client) => client.channel_id === conn.snap.own_channel_id && client.talk_request);
}
}
}
export function initAdmin() {
if (initialized) return; initialized = true;
const buttons = { 'btn-away': 'away', 'btn-create-channel': 'channel.create', 'btn-info': 'channel.info.inline', 'btn-server-admin': 'server.info', 'btn-talk-power': 'talk.queue' };
document.addEventListener('click', (event) => {
const target = event.target.closest('button,[data-admin-action]'); if (!target) return;
const name = target.dataset.adminAction ?? buttons[target.id];
if (name) void openAdminAction(name, { channelId: target.dataset.channelId ? Number(target.dataset.channelId) : undefined, clientId: target.dataset.clientId ? Number(target.dataset.clientId) : undefined });
});
const channelMenu = (event) => {
if (event.type === 'keydown' && event.key !== 'ContextMenu' && !(event.key === 'F10' && event.shiftKey)) return;
const rowEl = event.target.closest('.channel-row[data-cid]'); if (!rowEl) return;
event.preventDefault(); void openChannelPopup(event, rowEl);
};
document.addEventListener('contextmenu', channelMenu); document.addEventListener('keydown', channelMenu);
for (const topic of ['view', 'snapshot', 'connection', 'connection-closed', 'core-status']) on(topic, refresh);
// Leaving the info view ends the pane so the shell header never keeps a stale admin title.
on('set-view', (name) => { if (name !== 'channel-info') dropPane(null); });
onLanguageChange(() => { closeModal(); closeChannelPopup(); refresh(); if (pane && alive(pane) && !pane.busy) pane.reopen?.(); });
refresh();
}