repositories / Unfugwart
Unfugwart
Discord caretaker for Abteilung Unfug
owned by admin
ui.js
Rawconst phaseText = { unknown: 'Status unbekannt', offline: 'Offline', starting: 'Startet', updating: 'Prüft oder aktualisiert', 'loading-world': 'Lädt die Welt', saving: 'Speichert', ready: 'Bereit', stopping: 'Stoppt', running: 'Läuft' };
const phaseDetail = {
unknown: 'Serverstatus konnte nicht abgerufen werden.',
offline: 'Erster Mensch im Sprachkanal startet den Server.',
starting: 'Der Server startet. Spielbereitschaft noch nicht bestätigt.',
updating: 'Die Spielinstallation wird geprüft oder aktualisiert.',
'loading-world': 'Die Spielwelt wird geladen.',
saving: 'Die Welt wird gespeichert.',
ready: 'Das Spiel meldet: bereit zum Spielen.',
stopping: 'Der Stopp wurde angefordert. Warte auf das Ende des Prozesses.',
running: 'Spielbereitschaft noch nicht bestätigt.',
};
export const phaseLabel = telemetry => phaseText[effectivePhase(telemetry)] ?? phaseText.unknown;
export function voiceSummary(mapping, lifecycle, telemetry, now = Date.now()) {
const phase = lifecycle.stopping ? 'stopping' : effectivePhase(telemetry);
const icon = phase === 'offline' ? '💤' : phase === 'ready' ? '🟢' : phase === 'stopping' ? '🛑' : '🧹';
const countdown = phase !== 'offline' && lifecycle.deadlineAt > now ? ` · Feierabend in ${Math.ceil((lifecycle.deadlineAt - now) / 60_000)} min` : '';
const hold = lifecycle.holdUntil > now ? ' · Nachtschicht' : '';
return `${icon} ${mapping.displayName}: ${phaseText[phase] ?? phaseText.unknown}${countdown}${hold}`.slice(0, 500);
}
const fallbackEmojis = { sleeping: '💤', starting: '🧰', ready: '🎉', saving: '💾', stopping: '🛑', adventurer: '🧭' };
export function emojiPalette(fetched = [], overrides = {}) {
const aliases = { sleeping: ['sleeping', 'sleep', 'offline'], starting: ['starting', 'start', 'loading'], ready: ['ready'], saving: ['saving', 'save'], stopping: ['stopping', 'stop'], adventurer: ['adventurer'] };
return Object.fromEntries(Object.entries(aliases).map(([slot, names]) => {
const wanted = overrides[slot] ? [overrides[slot]] : names;
for (const name of wanted) {
const matches = fetched.filter(item => item && /^\d{2,22}$/.test(item.id ?? '') && /^[A-Za-z0-9_]{2,32}$/.test(item.name ?? '') && item.name === name);
if (!matches.length) continue;
if (new Set(matches.map(item => item.id)).size !== 1) return [slot, fallbackEmojis[slot]];
return [slot, { id: matches[0].id, name: matches[0].name, animated: Boolean(matches[0].animated) }];
}
return [slot, fallbackEmojis[slot]];
}));
}
const emojiText = value => typeof value === 'string' ? value : `${value.animated ? '<a' : '<'}:${value.name}:${value.id}>`;
const buttonEmoji = value => typeof value === 'string' ? { name: value } : { id: value.id, name: value.name, animated: value.animated };
export function effectivePhase(telemetry = {}) {
if (telemetry.status === 'offline') return 'offline';
if (telemetry.status === 'unknown') return 'unknown';
if (telemetry.phase === 'not-ready') return 'starting';
if (telemetry.phase === 'process-running') return 'running';
if (telemetry.status === 'starting' && (!telemetry.phase || telemetry.phase === 'unknown')) return 'starting';
if (telemetry.status === 'running' && (!telemetry.phase || telemetry.phase === 'unknown')) return 'running';
return telemetry.phase ?? 'unknown';
}
const stamp = value => value ? `<t:${Math.floor(value / 1000)}:R>` : 'unbekannt';
const bar = percent => `${'█'.repeat(Math.round(percent / 10))}${'░'.repeat(10 - Math.round(percent / 10))} ${Math.round(percent)} %`;
export function panelUrl(panelUrl, serverId) {
return `${panelUrl}/servers/view/${encodeURIComponent(serverId)}`;
}
export function controlsBlocked(lifecycle, telemetry, now = Date.now()) {
const phase = effectivePhase(telemetry);
const processOnly = telemetry.game === 'generic' && phase === 'running';
return Boolean(lifecycle.stopping || (lifecycle.startupUntil > now && !processOnly) || ['starting', 'updating', 'loading-world', 'stopping'].includes(phase));
}
export function renderStatus(mapping, lifecycle, telemetry, now = Date.now(), emojis = emojiPalette()) {
const phase = lifecycle.stopping ? 'stopping' : effectivePhase(telemetry);
const blocked = controlsBlocked(lifecycle, telemetry, now);
const slot = { offline: 'sleeping', ready: 'ready', saving: 'saving', stopping: 'stopping' }[phase] ?? 'starting';
const icon = phase === 'unknown' ? '❔' : emojiText(emojis[slot]);
const detail = telemetry.game === 'generic' && phase === 'running' ? 'Nur Prozessstatus. Spielbereitschaft wird nicht geprüft.' : phaseDetail[phase] ?? phaseDetail.unknown;
let automation;
if (lifecycle.known === false) {
automation = '**Automatik pausiert**\nSprachkanalstatus fehlt. Kein automatischer Stopp.';
} else if (lifecycle.holdUntil > now) {
automation = `**☕ Stopp pausiert bis ${stamp(lifecycle.holdUntil)}**\nWachhalten ist aktiviert.`;
} else if (phase === 'offline') {
automation = `**Kein Stopp geplant**\n${lifecycle.humans > 0 ? `${lifecycle.humans} im Sprachkanal.` : 'Sprachkanal leer.'}`;
} else if (phase === 'stopping') {
automation = '**Stopp läuft**\nNicht hart beenden; der Server soll sauber schließen.';
} else if (lifecycle.deadlineAt > now) {
automation = `**⏳ Stoppt ${stamp(lifecycle.deadlineAt)}**\nNiemand im Sprachkanal. Beitreten verhindert den Stopp.`;
} else if (lifecycle.known && lifecycle.humans > 0) {
automation = `**Kein automatischer Stopp**\n${lifecycle.humans} im Sprachkanal.`;
} else {
automation = '**Kein Stopp geplant**';
}
const fields = [];
const progressPhase = effectivePhase(telemetry);
if (telemetry.progress != null && ['updating', 'saving'].includes(progressPhase)) fields.push({ name: progressPhase === 'saving' ? 'Welt speichern' : 'Installation prüfen / aktualisieren', value: bar(telemetry.progress), inline: false });
if (mapping.connectAddress) fields.push({ name: 'Im Spiel direkt verbinden', value: `\`${mapping.connectAddress}\``, inline: false });
if (telemetry.players != null) fields.push({ name: 'Spieler · letzte Meldung', value: `${telemetry.players} · ${stamp(telemetry.lastPlayerObservationAt)} · nicht live`, inline: false });
if (lifecycle.error) fields.push({ name: 'Panel-Anfrage fehlgeschlagen', value: 'Erneut versuchen oder Panel prüfen.', inline: false });
if (lifecycle.voiceWarning) fields.push({ name: 'Sprachstatus nicht verfügbar', value: 'Kanalrechte prüfen; Serversteuerung funktioniert unabhängig davon.', inline: false });
return {
embeds: [{ title: `${emojiText(emojis.adventurer)} ${mapping.displayName}`, url: panelUrl(mapping.panelUrl, mapping.serverId), description: `**${icon} ${phaseText[phase] ?? phaseText.unknown}**\n${detail}\n\n${automation}`, color: phase === 'ready' ? 0x2ecc71 : phase === 'offline' ? 0x95a5a6 : 0xe67e22, fields, footer: { text: 'Unfugwart · Abteilung Unfug' } }],
components: [{ type: 1, components: [
{ type: 2, style: 3, custom_id: `uw:${mapping.serverId}:start`, label: 'Start', emoji: buttonEmoji(emojis.starting), disabled: Boolean(blocked || phase !== 'offline') },
{ type: 2, style: 1, custom_id: `uw:${mapping.serverId}:hold`, label: '1 h wach halten', emoji: buttonEmoji(emojis.ready), disabled: Boolean(blocked) },
{ type: 2, style: 2, custom_id: `uw:${mapping.serverId}:status`, label: 'Status', emoji: buttonEmoji(emojis.adventurer), disabled: false },
{ type: 2, style: 4, custom_id: `uw:${mapping.serverId}:stop`, label: 'Stop', emoji: buttonEmoji(emojis.stopping), disabled: Boolean(blocked || phase === 'offline') },
{ type: 2, style: 5, url: panelUrl(mapping.panelUrl, mapping.serverId), label: 'Panel' },
] }],
};
}
export function renderCommand(mapping, heading, description, fields = [], components = [], emojis = emojiPalette()) {
return {
embeds: [{ title: mapping ? `${emojiText(emojis.adventurer)} ${mapping.displayName}` : 'Unfugwart', description: `**${heading}**\n${description}`, color: 0x95a5a6, fields, footer: { text: 'Unfugwart · Abteilung Unfug' } }],
components,
allowedMentions: { parse: [] },
};
}
export function authorize({ interaction, mapping }) {
if (!interaction.guildId || interaction.guildId !== mapping.guildId || interaction.guild?.id !== mapping.guildId) return false;
const roles = [...(interaction.guild.roles.cache?.values?.() ?? [])].filter(role => role.name === mapping.controlRoleName && !role.managed);
if (roles.length !== 1) return false;
return Boolean(interaction.member?.roles?.cache?.has?.(roles[0].id));
}
export class Confirmations {
constructor({ now = Date.now, ttlMs = 60_000 } = {}) { this.now = now; this.ttlMs = ttlMs; this.pending = new Map(); }
create({ requesterId, serverId }) {
const token = `${requesterId}:${serverId}`;
this.pending.set(token, this.now() + this.ttlMs);
return token;
}
consume({ requesterId, serverId }) {
const token = `${requesterId}:${serverId}`;
const expiry = this.pending.get(token);
this.pending.delete(token);
return Boolean(expiry && expiry > this.now());
}
}
export function parseControlId(value) {
const match = /^uw:([^:]+):(start|hold|status|stop|confirm-stop)$/.exec(value ?? '');
return match ? { serverId: match[1], action: match[2] } : null;
}