Luigit
repositories / Unfugwart

Unfugwart

Discord caretaker for Abteilung Unfug

owned by admin

discord-ui.js

Raw
import { readFile, writeFile, rename } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { ActivityType, Events, MessageFlags, Routes } from 'discord.js';
import { Confirmations, authorize, controlsBlocked, effectivePhase, emojiPalette, voiceSummary, panelUrl, parseControlId, renderStatus, renderCommand } from './ui.js';

const command = mappings => ({
  name: 'server', description: 'Server betreuen', options: [
    { type: 3, name: 'aktion', description: 'Aktion', required: true, choices: [{ name: 'Lagebericht', value: 'status' }, { name: 'Start', value: 'start' }, { name: '1 h wach halten', value: 'stay' }, { name: 'Stop', value: 'stop' }, { name: 'Setup prüfen', value: 'setup' }, { name: 'Orakel befragen', value: 'orakel' }] },
    { type: 3, name: 'ziel', description: 'Server', required: true, choices: mappings.map(mapping => ({ name: mapping.displayName.slice(0, 100), value: mapping.serverId })) },
  ],
});

const stateFile = path => path instanceof URL ? fileURLToPath(path) : path;
const isMissing = error => error?.code === 10008;
const isPermissionError = error => error?.code === 50001 || error?.code === 50013 || error?.status === 403;
const safeName = value => String(value ?? 'Server').slice(0, 100);

async function loadMessages(path) {
  try {
    const value = JSON.parse(await readFile(stateFile(path), 'utf8'));
    return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
  } catch { return {}; }
}

async function saveMessages(path, messages) {
  const safe = Object.fromEntries(Object.entries(messages).filter(([, id]) => typeof id === 'string' && /^\d+$/.test(id)));
  const file = stateFile(path);
  await writeFile(`${file}.tmp`, JSON.stringify(safe), { mode: 0o600 });
  await rename(`${file}.tmp`, file);
}

export class DiscordUi {
  constructor({ client, config, entries, statePath = new URL('./.unfugwart-state.json', import.meta.url), now = Date.now, log = console }) {
    this.client = client;
    this.config = config;
    this.entries = entries;
    this.statePath = statePath;
    this.now = now;
    this.log = log;
    this.messages = {};
    this.confirmations = new Confirmations({ now });
    this.timers = new Map();
    this.queues = new Map();
    this.saveQueue = Promise.resolve();
    this.last = new Map();
    this.lastVoice = new Map();
    this.voiceWarnings = new Map();
    this.lastPresence = null;
    this.closed = false;
    this.emojis = emojiPalette();
    this.appEmojiCount = 0;
    this.appEmojis = [];
    this.voiceRetryAt = new Map();
  }

  mapping(serverId) { return [...this.entries.values()].find(entry => entry.mapping.serverId === serverId); }
  emojisFor(entry) {
    const name = entry?.mapping.gameEmojiName;
    if (!name) return this.emojis;
    const icon = emojiPalette(this.appEmojis, { adventurer: name }).adventurer;
    return typeof icon === 'string' ? this.emojis : { ...this.emojis, adventurer: icon };
  }
  statusPayload(entry) {
    return renderStatus({ ...entry.mapping, panelUrl: this.config.panelUrl }, { ...entry.control.state(), voiceWarning: this.voiceWarnings.has(entry.mapping.voiceChannelId) }, entry.poller.state(), this.now(), this.emojisFor(entry));
  }
  response(entry, heading, description, fields = [], components = []) {
    return renderCommand(entry?.mapping, heading, description, fields, components, this.emojisFor(entry));
  }
  warn(area, entry) { this.log.warn?.(`${area} ${safeName(entry.mapping.displayName)}: nicht verfügbar`); }

  async refreshEmojis() {
    try {
      const fetched = await this.client.application.emojis.fetch();
      this.appEmojiCount = fetched.size;
      this.appEmojis = [...fetched.values()];
      this.emojis = emojiPalette(this.appEmojis, this.config.emojiNames);
    } catch { this.appEmojiCount = 0; this.appEmojis = []; this.emojis = emojiPalette([], this.config.emojiNames); }
    return this.emojis;
  }

  async start() {
    this.messages = await loadMessages(this.statePath);
    await this.refreshEmojis();
    for (const entry of this.entries.values()) {
      const controlState = entry.control.onState;
      const telemetryState = entry.poller.onState;
      entry.control.onState = (...args) => { controlState?.(...args); this.updatePresence(); this.schedule(entry); };
      entry.poller.onState = (...args) => { telemetryState?.(...args); this.updatePresence(); this.schedule(entry); };
      this.schedule(entry, true);
    }
    this.updatePresence();
    this.client.on(Events.InteractionCreate, interaction => void this.handleInteraction(interaction));
    await this.registerCommands();
  }

  async handleInteraction(interaction) {
    try { await this.interaction(interaction); } catch { await this.safeReply(interaction, this.response(null, 'Aktion fehlgeschlagen', 'Erneut versuchen. Falls es wieder passiert, Bot-Konsole prüfen.')); }
  }

  close() {
    this.closed = true;
    for (const timer of this.timers.values()) clearTimeout(timer);
    this.timers.clear();
  }

  schedule(entry, immediate = false) {
    if (this.closed || !entry.mapping.statusChannelId) return;
    const id = entry.mapping.serverId;
    if (this.timers.has(id)) {
      if (!immediate) return;
      clearTimeout(this.timers.get(id));
      this.timers.delete(id);
    }
    this.timers.set(id, setTimeout(() => {
      this.timers.delete(id);
      this.queue(entry);
    }, immediate ? 0 : 5_000));
  }

  queue(entry) {
    const id = entry.mapping.serverId;
    const previous = this.queues.get(id) ?? Promise.resolve();
    const next = previous.catch(() => {}).then(() => this.update(entry));
    this.queues.set(id, next);
    void next.catch(() => this.warn('Discord-Status', entry));
  }

  updatePresence() {
    const entries = [...this.entries.values()];
    const ready = entries.filter(entry => effectivePhase(entry.poller.state()) === 'ready').length;
    const name = `🧹 Abteilung Unfug · ${ready}/${entries.length} bereit`;
    if (name === this.lastPresence || !this.client.user) return;
    this.lastPresence = name;
    try { this.client.user.setPresence({ activities: [{ name, type: ActivityType.Watching }] }); } catch { /* Discord presence is optional. */ }
  }

  async fetchMessage(channel, id) {
    try { return await channel.messages.fetch(id, { force: true }); } catch (error) {
      if (isMissing(error)) return null;
      throw error;
    }
  }

  validMessage(message, serverId) {
    const embed = message?.embeds?.[0];
    return message?.author?.id === this.client.user?.id && (embed?.footer?.text === `unfugwart:${serverId}` || (embed?.url === panelUrl(this.config.panelUrl, serverId) && embed?.footer?.text === 'Unfugwart · Abteilung Unfug'));
  }

  async recoverMessage(channel, serverId) {
    let recovered;
    try { recovered = await channel.messages.fetch({ limit: 25, cache: false }); } catch (error) {
      throw error;
    }
    return recovered.find(item => this.validMessage(item, serverId)) ?? null;
  }

  persist() {
    const save = this.saveQueue.catch(() => {}).then(() => saveMessages(this.statePath, this.messages));
    this.saveQueue = save;
    return save;
  }

  async update(entry) {
    try {
      const telemetry = entry.poller.state();
      const payload = this.statusPayload(entry);
      const comparable = JSON.stringify(payload);
      const guild = this.client.guilds.cache.get(entry.mapping.guildId);
      const channel = guild?.channels.cache.get(entry.mapping.statusChannelId);
      if (!channel?.isTextBased?.()) return;
      const serverId = entry.mapping.serverId;
      let message = this.messages[serverId] ? await this.fetchMessage(channel, this.messages[serverId]) : null;
      const persistedMessage = this.validMessage(message, serverId);
      if (!persistedMessage) message = await this.recoverMessage(channel, serverId);
      if (!message) message = await channel.send(payload);
      else if (!persistedMessage || this.last.get(serverId) !== comparable) {
        try { message = await message.edit(payload); } catch (error) {
          if (!isMissing(error)) throw error;
          message = await channel.send(payload);
        }
      }
      this.messages[serverId] = message.id;
      try {
        await this.persist();
        this.last.set(serverId, comparable);
      } catch {
        this.warn('Discord-Status', entry);
      }
      await this.voiceStatus(entry, telemetry);
    } finally {
      this.schedule(entry);
    }
  }

  async voiceStatus(entry, telemetry = entry.poller.state()) {
    const voiceId = entry.mapping.voiceChannelId;
    const voice = this.client.guilds.cache.get(entry.mapping.guildId)?.channels.cache.get(voiceId);
    const text = voiceSummary(entry.mapping, entry.control.state(), telemetry, this.now());
    if (!voice?.isVoiceBased?.() || this.lastVoice.get(voiceId) === text || this.voiceRetryAt.get(voiceId) > this.now()) return;
    try {
      const route = Routes.channelVoiceStatus?.(voiceId) ?? `/channels/${voiceId}/voice-status`;
      await this.client.rest.put(route, { body: { status: text } });
      this.voiceRetryAt.delete(voiceId);
      const hadWarning = this.voiceWarnings.delete(voiceId);
      this.lastVoice.set(voiceId, text);
      if (hadWarning) this.schedule(entry, true);
    } catch (error) {
      this.voiceRetryAt.set(voiceId, this.now() + 60_000);
      if (isPermissionError(error) && !this.voiceWarnings.has(voiceId)) {
        this.voiceWarnings.set(voiceId, true);
        this.schedule(entry, true);
      }
      this.log.warn?.(`Discord-Sprachstatus ${safeName(entry.mapping.displayName)}: ${isPermissionError(error) ? 'fehlende Berechtigung' : 'nicht verfügbar'}`);
    }
  }

  async setupReport(entry) {
    await this.refreshEmojis();
    const mapping = entry.mapping;
    const guild = this.client.guilds.cache.get(mapping.guildId);
    const text = guild?.channels.cache.get(mapping.statusChannelId);
    const voice = guild?.channels.cache.get(mapping.voiceChannelId);
    const bot = guild?.members?.me;
    const labels = { ViewChannel: 'Kanal ansehen', SendMessages: 'Nachrichten senden', EmbedLinks: 'Links einbetten', ReadMessageHistory: 'Nachrichtenverlauf lesen', SetVoiceChannelStatus: 'Sprachstatus setzen', ManageChannels: 'Kanäle verwalten' };
    const check = (channel, valid, names) => {
      if (!valid) return { ok: false, detail: '⚠️ Kanal fehlt oder hat den falschen Typ.' };
      if (!bot) return { ok: false, detail: '⚠️ Bot-Rechte konnten nicht geprüft werden.' };
      const missing = names.filter(name => !bot.permissionsIn(channel).has(name));
      return { ok: !missing.length, detail: missing.length ? `⚠️ Fehlt: ${missing.map(name => labels[name]).join(', ')}` : '✅ Alle nötigen Rechte vorhanden.' };
    };
    const textCheck = check(text, text?.isTextBased?.(), ['ViewChannel', 'SendMessages', 'EmbedLinks', 'ReadMessageHistory']);
    const voiceCheck = check(voice, voice?.isVoiceBased?.(), ['ViewChannel', 'SetVoiceChannelStatus', 'ManageChannels']);
    const roles = [...(guild?.roles.cache.values() ?? [])].filter(role => role.name === mapping.controlRoleName && !role.managed);
    const resolved = Object.values(this.emojis).filter(emoji => typeof emoji !== 'string');
    const missingEmoji = Object.keys(this.emojis).filter(slot => typeof this.emojis[slot] === 'string');
    const emojiNote = missingEmoji.length ? `${resolved.length}/6 eigene Symbole geladen. Standard-Emojis ersetzen: ${missingEmoji.join(', ')}.` : '✅ Alle 6 eigenen Symbole geladen.';
    const telemetry = entry.poller.state();
    const consoleNote = telemetry.status === 'unknown' ? '⚠️ Keine aktuellen Daten. PufferPanel-Zugriff prüfen.' : telemetry.game === 'generic' ? 'Generisches Profil: nur Prozessstatus. Spielbereitschaft nicht bestätigt.' : telemetry.status === 'offline' ? 'Server offline; neue Konsolendaten erst beim Start.' : '✅ Laufdaten empfangen.';
    const ready = textCheck.ok && voiceCheck.ok && roles.length === 1;
    for (const target of this.entries.values()) this.schedule(target, true);
    return this.response(entry, ready ? '✅ Discord bereit' : '⚠️ Einrichtung prüfen', ready ? 'Kanäle und Steuerrolle passen.' : 'Die markierten Punkte korrigieren.', [
      { name: 'Statusnachricht', value: textCheck.detail },
      { name: 'Sprachkanal', value: voiceCheck.detail },
      { name: 'Wer steuern darf', value: roles.length === 1 ? `✅ Mitglieder der Rolle **${safeName(mapping.controlRoleName)}**.` : roles.length ? `⚠️ Mehrere Rollen heißen **${safeName(mapping.controlRoleName)}**. Genau eine behalten.` : `⚠️ Menschenrolle **${safeName(mapping.controlRoleName)}** fehlt.` },
      { name: 'Symbole', value: emojiNote },
      { name: 'PufferPanel', value: consoleNote },
    ]);
  }

  async registerCommands() {
    for (const [guildId, mappings] of Map.groupBy([...this.entries.values()].map(entry => entry.mapping), mapping => mapping.guildId)) {
      const commands = await this.client.application.commands.fetch({ guildId });
      const own = commands.find?.(item => item.name === 'server') ?? [...commands.values()].find(item => item.name === 'server');
      const body = command(mappings);
      if (own) await this.client.application.commands.edit(own.id, body, guildId);
      else await this.client.application.commands.create(body, guildId);
    }
  }

  async interaction(interaction) {
    const slash = interaction.isChatInputCommand?.() && interaction.commandName === 'server';
    const button = interaction.isButton?.() ? parseControlId(interaction.customId) : null;
    if (!slash && !button) return;
    const serverId = slash ? interaction.options.getString('ziel', true) : button.serverId;
    const requestedAction = slash ? interaction.options.getString('aktion', true) : button.action;
    const action = requestedAction === 'stay' ? 'hold' : requestedAction;
    const entry = this.mapping(serverId);
    if (!entry || interaction.guildId !== entry.mapping.guildId) return this.safeReply(interaction, this.response(null, 'Nicht verfügbar', 'Dieser Server gehört nicht zu diesem Discord-Server.'));
    if (action === 'orakel') return this.safeReply(interaction, this.response(entry, '🧙 Goblin-Orakel', '*Möge dein Ping kurz und dein Loot reich sein.*\nDer Hausmeister empfiehlt: erst speichern, dann Unfug.'));
    if (action === 'setup') {
      try { await interaction.deferReply({ flags: MessageFlags.Ephemeral }); } catch { return; }
      return this.safeEdit(interaction, await this.setupReport(entry));
    }
    if (action === 'status') {
      try { await interaction.deferReply({ flags: MessageFlags.Ephemeral }); } catch { return; }
      await entry.poller.poll();
      this.schedule(entry, true);
      return this.safeEdit(interaction, this.statusPayload(entry));
    }
    if (!authorize({ interaction, mapping: entry.mapping })) return this.safeReply(interaction, this.response(entry, 'Steuerrolle fehlt', `Zum Steuern brauchst du die Menschenrolle **${safeName(entry.mapping.controlRoleName)}**. Status bleibt frei zugänglich.`));
    const lifecycle = entry.control.state();
    const telemetry = entry.poller.state();
    if (!['start', 'hold', 'stop', 'confirm-stop'].includes(action) || controlsBlocked(lifecycle, telemetry, this.now())) return this.safeReply(interaction, this.response(entry, 'Bitte kurz warten', 'Start oder Stopp läuft bereits. **Status** zeigt den Fortschritt.'));
    if (action === 'start' && effectivePhase(telemetry) !== 'offline') return this.safeReply(interaction, this.response(entry, 'Kein weiterer Start', effectivePhase(telemetry) === 'unknown' ? 'Serverstatus unklar. Zuerst **Status** aktualisieren.' : 'Der Server läuft bereits. **1 h wach halten** verhindert den automatischen Stopp.'));
    if (action === 'stop' && effectivePhase(telemetry) === 'offline') return this.safeReply(interaction, this.response(entry, 'Bereits offline', 'Nichts zu stoppen. Der Server ist aus.'));
    if (action === 'stop') {
      this.confirmations.create({ requesterId: interaction.user.id, serverId });
      const voice = lifecycle.known ? `${lifecycle.humans} im Sprachkanal` : 'Nicht bekannt';
      const players = telemetry.players == null ? 'Nicht bekannt' : `${telemetry.players} · ${telemetry.lastPlayerObservationAt ? `<t:${Math.floor(telemetry.lastPlayerObservationAt / 1000)}:R>` : 'Zeit nicht bekannt'} · nicht live`;
      return this.safeReply(interaction, this.response(entry, '🛑 Server wirklich stoppen?', 'Laufende Spieler können getrennt werden, auch wenn niemand im Sprachkanal ist. Der Stopp wird sauber angefordert.', [
        { name: 'Sprachkanal', value: voice },
        { name: 'Spieler · letzte Meldung', value: players },
      ], [{ type: 1, components: [{ type: 2, style: 4, custom_id: `uw:${serverId}:confirm-stop`, label: 'Ja, stoppen' }] }]));
    }
    if (action === 'confirm-stop' && !this.confirmations.consume({ requesterId: interaction.user.id, serverId })) return this.safeReply(interaction, this.response(entry, 'Bestätigung abgelaufen', 'Erneut **Stop** wählen. Nur die Person, die den Stopp angefordert hat, kann ihn bestätigen.'));
    try { await interaction.deferReply({ flags: MessageFlags.Ephemeral }); } catch { return; }
    const result = action === 'start' ? await entry.control.manualStart() : action === 'hold' ? await entry.control.keepAwake() : await entry.control.confirmedStop();
    this.schedule(entry, true);
    if (result?.status !== 'success') return this.safeEdit(interaction, this.response(entry, result?.status === 'cancelled' ? 'Aktion abgebrochen' : 'Aktion fehlgeschlagen', result?.status === 'cancelled' ? 'Der Zustand hat sich inzwischen geändert. Aktuellen Status prüfen.' : 'PufferPanel-Anfrage fehlgeschlagen. Erneut versuchen oder Panel prüfen.'));
    const resultText = action === 'confirm-stop' ? ['🛑 Stopp angefordert', 'Der Server fährt herunter. **Status** bestätigt, sobald er offline ist.'] : action === 'hold' ? ['☕ Eine Stunde Pause vom Autostopp', 'Wachhalten aktiviert. Danach gilt wieder die Sprachkanal-Automatik.'] : ['▶ Start angefordert', 'Der Server startet. **Status** zeigt, wann das Spiel bereit ist.'];
    return this.safeEdit(interaction, this.response(entry, ...resultText));
  }

  async safeEdit(interaction, content) {
    try { await interaction.editReply(content); } catch { /* Interaction token failures are intentionally contained. */ }
  }

  async safeReply(interaction, value, ephemeral = true) {
    try {
      const payload = typeof value === 'string' ? { content: value } : value;
      if (interaction.deferred && !interaction.replied) await interaction.editReply(payload);
      else if (interaction.replied) await interaction.followUp({ ...payload, flags: ephemeral ? MessageFlags.Ephemeral : 0, allowedMentions: { parse: [] } });
      else await interaction.reply({ ...payload, flags: ephemeral ? MessageFlags.Ephemeral : 0, allowedMentions: { parse: [] } });
      return true;
    } catch { return false; }
  }
}