Dezio/web/dashboard/static/app.js
astar76 709f9b707a Dezio: an all-in-one Discord bot in Rust
Music with a live player, Last.fm, video downloads, games, AI chat, moderation, logging,
a web dashboard and a Game Boy Activity.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 11:47:43 -05:00

471 lines
25 KiB
JavaScript

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.

// Dezio dashboard. Plain JS, no frameworks. Everything is built with textContent (never innerHTML),
// because server, channel and role names come from users.
"use strict";
const state = { me: null, page: "me" };
// ---------------------------------------------------------------------------- helpers
function h(tag, attrs, ...children) {
const el = document.createElement(tag);
for (const [key, value] of Object.entries(attrs || {})) {
if (value === undefined || value === null || value === false) continue;
if (key === "class") el.className = value;
else if (key.startsWith("on")) el.addEventListener(key.slice(2), value);
else if (key === "value") el.value = value;
else if (key === "checked") el.checked = Boolean(value);
else el.setAttribute(key, value === true ? "" : value);
}
for (const child of children.flat()) {
if (child === null || child === undefined || child === false) continue;
el.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return el;
}
const $ = (id) => document.getElementById(id);
function toast(text) {
const el = $("toast");
el.textContent = text;
el.classList.remove("hidden");
clearTimeout(toast.timer);
toast.timer = setTimeout(() => el.classList.add("hidden"), 3500);
}
async function api(method, path, body) {
const options = { method, credentials: "same-origin", headers: {} };
if (body !== undefined) {
options.headers["Content-Type"] = "application/json";
options.headers["X-CSRF-Token"] = state.me ? state.me.csrf : "";
options.body = JSON.stringify(body);
}
const response = await fetch(path, options);
let data = {};
try { data = await response.json(); } catch (e) { /* empty answer */ }
if (!response.ok) throw new Error(data.error || `Something went wrong (${response.status})`);
return data;
}
// A text box with place suggestions underneath while you type (only you see them).
function placeSuggestions(input) {
const list = h("div", { class: "suggest hidden" });
let timer, asked = "";
const close = () => list.classList.add("hidden");
input.addEventListener("input", () => {
clearTimeout(timer);
const text = input.value.trim();
if (text.length < 2) return close();
timer = setTimeout(async () => {
asked = text;
let found = [];
try { found = await api("GET", "/api/places?q=" + encodeURIComponent(text)); } catch (e) { /* none this time */ }
if (asked !== input.value.trim()) return; // they kept typing
list.replaceChildren(...found.map((label) => h("button", { type: "button", class: "suggest-item",
onmousedown: (event) => { event.preventDefault(); input.value = label; close(); } }, label)));
list.classList.toggle("hidden", !found.length);
}, 250);
});
input.addEventListener("blur", () => setTimeout(close, 150));
input.addEventListener("keydown", (event) => { if (event.key === "Escape") close(); });
return h("div", { class: "suggest-wrap" }, input, list);
}
// A section with its own Save button. `collect()` returns the JSON to send.
function section(title, hint, body, collect, path) {
const status = h("span", { class: "status" });
const button = h("button", { class: "btn primary", type: "button" }, "Save");
button.addEventListener("click", async () => {
button.disabled = true;
status.className = "status";
status.textContent = "Saving…";
try {
const result = await api("PATCH", path, collect());
status.className = "status ok";
status.textContent = (result.notes && result.notes[0]) || "Saved ✓";
} catch (e) {
status.className = "status err";
status.textContent = e.message;
} finally {
button.disabled = false;
}
});
return h("section", { class: "section" }, h("h2", {}, title), hint ? h("p", { class: "hint" }, hint) : null,
body, h("div", { class: "actions" }, button, status));
}
function field(label, input, note) {
return h("label", { class: "field" }, h("span", {}, label), input, note ? h("small", {}, note) : null);
}
function toggle(label, checked, note) {
const input = h("input", { type: "checkbox", checked });
const el = h("label", { class: "toggle" }, input, h("div", {}, label, note ? h("small", {}, note) : null));
el.input = input;
return el;
}
function channelSelect(channels, value, emptyLabel) {
const select = h("select", {}, h("option", { value: "" }, emptyLabel || "— none —"));
let group = null, groupName = null;
for (const c of channels) {
if (c.category !== groupName) {
groupName = c.category;
group = groupName ? h("optgroup", { label: groupName }) : select;
if (groupName) select.append(group);
}
group.append(h("option", { value: c.id }, `#${c.name}${c.can_send ? "" : " (Dezio can't post here)"}`));
}
select.value = value || "";
return select;
}
function radios(name, options, value) {
const wrap = h("div", { class: "choices" });
for (const [val, label] of options) {
wrap.append(h("label", {}, h("input", { type: "radio", name, value: val, checked: val === value }), label));
}
wrap.value = () => (wrap.querySelector("input:checked") || {}).value;
return wrap;
}
// ---------------------------------------------------------------------------- quote styles
// One editor for a person's own quote look (Your settings) and for a server's default (server page).
// The preview is drawn by the bot itself, so it is exactly what /quote will make.
function quoteSection(title, hint, q, path) {
const st = JSON.parse(JSON.stringify(q.style));
const inputs = {};
const status = h("span", { class: "status" });
const preview = h("img", { class: "quote-preview", alt: "Preview of the quote card" });
let timer, token = 0;
const refresh = () => {
clearTimeout(timer);
timer = setTimeout(async () => {
const mine = ++token;
status.className = "status";
status.textContent = "Drawing…";
try {
const response = await fetch("/api/quote/preview", { method: "POST", credentials: "same-origin",
headers: { "Content-Type": "application/json", "X-CSRF-Token": state.me.csrf }, body: JSON.stringify({ style: st }) });
if (!response.ok) throw new Error((await response.json()).error || "Couldn't draw that");
const blob = await response.blob();
if (mine === token) { preview.src = URL.createObjectURL(blob); status.textContent = ""; }
} catch (e) { status.className = "status err"; status.textContent = e.message; }
}, 500);
};
const bind = (el, key, read) => { el.addEventListener("input", () => { st[key] = read(el); refresh(); }); inputs[key] = el; return el; };
const select = (key, options) => { const el = h("select", {}, options.map(([v, l]) => h("option", { value: v }, l))); el.value = st[key]; return bind(el, key, (e) => e.value); };
const colour = (key) => { const el = h("input", { type: "color", value: st[key] || "#000000" }); return bind(el, key, (e) => e.value); };
const check = (key, label) => { const t = toggle(label, st[key]); t.input.addEventListener("input", () => { st[key] = t.input.checked; refresh(); }); inputs[key] = t.input; return t; };
const presetBox = h("select", {}, q.presets.map((p) => h("option", { value: p.key }, p.label)));
presetBox.value = st.preset;
presetBox.addEventListener("change", () => {
const base = q.presets.find((p) => p.key === presetBox.value).style;
const keep = { font: st.font, size: st.size, bold: st.bold };
Object.assign(st, base, keep);
for (const [key, el] of Object.entries(inputs)) {
if (el.type === "checkbox") el.checked = Boolean(st[key]);
else if (el.type === "color") el.value = st[key] || "#000000";
else el.value = st[key] ?? "";
}
gradient.input.checked = Boolean(st.bg2);
refresh();
});
const gradient = toggle("Gradient background", Boolean(st.bg2));
const end = h("input", { type: "color", value: st.bg2 || "#eb459e" });
gradient.input.addEventListener("input", () => { st.bg2 = gradient.input.checked ? end.value : null; refresh(); });
end.addEventListener("input", () => { if (gradient.input.checked) { st.bg2 = end.value; refresh(); } });
const fonts = h("datalist", { id: "fonts-" + path.replace(/\W/g, "") }, q.fonts.map((f) => h("option", { value: f })));
const font = h("input", { type: "text", value: st.font, maxlength: 40, list: fonts.id });
bind(font, "font", (e) => e.value.trim() || "Noto Sans");
const size = h("input", { type: "number", min: 0, max: 160, value: st.size });
bind(size, "size", (e) => Math.max(0, Math.min(160, Number(e.value) || 0)));
const mark = h("input", { type: "text", value: st.watermark, maxlength: 40, placeholder: "empty = none" });
bind(mark, "watermark", (e) => e.value);
const body = h("div", {},
h("div", { class: "row" }, field("Start from", presetBox), field("Layout", select("layout", [["wide", "Wide (1200×630)"], ["portrait", "Portrait (630×790)"]])),
field("Picture", select("image", [["fade", "Fading into the background"], ["circle", "Round avatar"], ["none", "No picture"]]))),
h("div", { class: "row" }, check("grayscale", "Black & white picture"), check("flip", "Flip sides"), check("marks", "Big quote marks")),
h("div", { class: "row" }, check("name", "Show “- Name”"), check("handle", "Show @handle"), check("line", "Divider line"), check("bold", "Bold text"), check("quote_chars", "“ ” around the text")),
h("div", { class: "row" }, field("Icon", select("icon", [["none", "None"], ["avatar", "Their avatar"], ["server", "Server icon"]])), field("Font (any Google Font)", font), field("Text size (0 = fit)", size), field("Watermark", mark)),
h("div", { class: "row" }, field("Background", colour("bg")), field("Text", colour("text")), field("Name", colour("author")), field("Handle & watermark", colour("muted")),
h("div", { class: "field" }, gradient, end)),
fonts, preview);
const save = h("button", { class: "btn primary", type: "button" }, "Save");
const reset = h("button", { class: "btn", type: "button" }, q.saved ? "Remove my saved style" : "Back to the default look");
const send = async (value, done) => {
try { await api("PATCH", path, { quote: value }); status.className = "status ok"; status.textContent = done; }
catch (e) { status.className = "status err"; status.textContent = e.message; }
};
save.addEventListener("click", () => send(st, "Saved ✓"));
reset.addEventListener("click", async () => { await send(null, "Removed ✓ — reload to see the default"); });
refresh();
return h("section", { class: "section" }, h("h2", {}, title), hint ? h("p", { class: "hint" }, hint) : null, body, h("div", { class: "actions" }, save, reset, status));
}
// ---------------------------------------------------------------------------- role menus
// The same menus the /cosmetics editor in Discord changes: presets can be edited, custom menus added.
function roleMenusSection(g, path) {
const wrap = h("div", {});
const status = h("span", { class: "status" });
const act = async (payload) => {
status.className = "status";
status.textContent = "Working…";
try {
const result = await api("POST", `${path}/rolemenus`, payload);
status.className = "status ok";
status.textContent = (result.notes && result.notes[0]) || "Done ✓";
draw(result.rolemenus.menus);
} catch (e) { status.className = "status err"; status.textContent = e.message; }
};
const draw = (menus) => {
const cards = menus.map((m) => {
const name = h("input", { type: "text", value: m.name, maxlength: 60 });
const emoji = h("input", { type: "text", value: m.emoji, maxlength: 8 });
const kind = radios("one-" + m.key, [["many", "Members can pick several"], ["one", "Pick one"]], m.one ? "one" : "many");
const boxes = h("div", { class: "roles" }, m.available.map((r) => h("label", {}, h("input", { type: "checkbox", value: r, checked: m.roles.includes(r) }), r)));
const more = h("textarea", { maxlength: 1500, placeholder: "Add roles: names separated by commas or new lines" });
const channel = channelSelect(g.channels, "", "— channel to post in —");
const roles = () => [...boxes.querySelectorAll("input:checked")].map((b) => b.value).concat(more.value.split(/[,\n]/).map((x) => x.trim()).filter(Boolean));
const button = (label, cls, fn) => h("button", { class: "btn " + cls, type: "button", onclick: fn }, label);
return h("div", { class: "subcard" }, h("h3", {}, `${m.emoji} ${m.name}`, m.preset ? h("small", {}, " preset") : null),
h("div", { class: "row" }, field("Name", name), field("Emoji", emoji)), kind, boxes, more,
h("div", { class: "actions" },
button("Save", "primary", () => act({ action: "save", key: m.key, name: name.value, emoji: emoji.value, one: kind.value() === "one", roles: roles() })),
m.preset ? button("Reset to preset", "", () => act({ action: "reset", key: m.key })) : button("Delete", "danger", () => { if (confirm(`Delete ${m.name}? Its roles and posted message are removed too.`)) act({ action: "delete", key: m.key }); })),
h("div", { class: "actions" }, channel, button("Publish", "", () => act({ action: "publish", key: m.key, channel: channel.value }))));
});
const name = h("input", { type: "text", maxlength: 60, placeholder: "Games, Colours, Ping roles…" });
const emoji = h("input", { type: "text", maxlength: 8, placeholder: "🎮" });
const roles = h("textarea", { maxlength: 1500, placeholder: "Role names separated by commas or new lines" });
const create = h("div", { class: "subcard" }, h("h3", {}, "➕ New menu"), h("div", { class: "row" }, field("Name", name), field("Emoji", emoji)), roles,
h("div", { class: "actions" }, h("button", { class: "btn primary", type: "button", onclick: () => act({ action: "create", name: name.value, emoji: emoji.value,
roles: roles.value.split(/[,\n]/).map((x) => x.trim()).filter(Boolean) }) }, "Create")));
wrap.replaceChildren(...cards, create);
};
draw(g.rolemenus.menus);
return h("section", { class: "section" }, h("h2", {}, "🎭 Role menus"),
h("p", { class: "hint" }, "Dropdowns members use to give themselves roles. Edit a preset or make your own, then Publish it to a channel (Dezio creates any missing roles)."),
wrap, h("div", { class: "actions" }, status));
}
// ---------------------------------------------------------------------------- pages
async function showMe() {
const main = $("main");
main.replaceChildren(h("p", { class: "muted" }, "Loading…"));
const s = await api("GET", "/api/user");
const parts = [h("h1", {}, "Your settings"), h("p", { class: "sub" }, "These follow you to every server that has Dezio.")];
if (s.lastfm_available) {
const name = h("input", { type: "text", value: s.lastfm || "", placeholder: "Last.fm username", maxlength: 30 });
parts.push(section("🎧 Last.fm", s.lastfm ? `Linked to ${s.lastfm}.` : "Link your account for /fm, charts and “Who knows?”.",
field("Username", name, "Leave empty and save to unlink."), () => ({ lastfm: name.value.trim() }), "/api/user"));
}
if (s.afk_available) {
const list = h("div", {});
const render = (items) => list.replaceChildren(...(items.length ? items.map((a) =>
h("div", { class: "afk-item" }, h("span", {}, h("b", {}, a.where), ` — ${a.reason}`),
h("span", { class: "muted" }, a.since ? new Date(a.since * 1000).toLocaleString() : ""))) :
[h("p", { class: "muted" }, "You're not AFK anywhere.")]));
render(s.afk);
const reason = h("input", { type: "text", placeholder: "Why you're away", maxlength: 200 });
const set = h("button", { class: "btn", type: "button" }, "Go AFK everywhere");
const clear = h("button", { class: "btn danger", type: "button" }, "Clear AFK");
const doAfk = async (value) => {
try {
const result = await api("PATCH", "/api/user", { afk: value });
render(result.settings.afk);
toast(value ? "You're AFK everywhere." : "AFK cleared.");
} catch (e) { toast(e.message); }
};
set.addEventListener("click", () => doAfk({ reason: reason.value }));
clear.addEventListener("click", () => doAfk(null));
parts.push(h("section", { class: "section" }, h("h2", {}, "💤 AFK"),
h("p", { class: "hint" }, "People who ping you are told you're away. Talking again in Discord also clears it."),
list, field("Reason", reason), h("div", { class: "actions" }, set, clear)));
}
const quality = radios("quality", [["fast", "⚡ Fast (smaller files)"], ["best", "💎 Best quality"]], s.download_quality);
parts.push(section("⬇️ Downloads", "The default for /download and D!download.", quality,
() => ({ download_quality: quality.value() }), "/api/user"));
const home = h("input", { type: "text", value: s.weather_home || "", placeholder: "e.g. Denver Colorado, Paris or a ZIP code",
maxlength: 100, autocomplete: "off" });
const places = placeSuggestions(home);
const unit = radios("unit", [["c", "°C"], ["f", "°F"]], s.temp_unit);
parts.push(section("🌤️ Weather", "Used when you run /weather without a place.",
h("div", { class: "row" }, field("Home", places), field("Units", unit)),
() => ({ weather_home: home.value, temp_unit: unit.value() }), "/api/user"));
const snipe = toggle("Don't let others snipe my messages", s.snipe_optout, "Your deleted and edited messages won't show in snipe.");
const dms = toggle("Block DMs sent through Dezio", s.dm_block, "Nobody can use /dm_echo to message you.");
parts.push(section("🔒 Privacy", null, h("div", {}, snipe, dms),
() => ({ snipe_optout: snipe.input.checked, dm_block: dms.input.checked }), "/api/user"));
parts.push(quoteSection("💬 Quote style", "How the pictures made with “Create Quote” look when you make them. Your own style wins over the server's.", s.quote, "/api/user"));
main.replaceChildren(...parts);
}
async function showGuild(id) {
const main = $("main");
main.replaceChildren(h("p", { class: "muted" }, "Loading…"));
let g;
try { g = await api("GET", `/api/guilds/${id}`); } catch (e) {
main.replaceChildren(h("p", { class: "error" }, e.message));
return;
}
const path = `/api/guilds/${id}`;
const parts = [h("h1", {}, g.name), h("p", { class: "sub" }, "Server settings — you can change these because you have Manage Server.")];
// general
const prefix = h("input", { type: "text", value: g.prefix, maxlength: 10 });
const volume = h("input", { type: "range", min: 0, max: 100, value: g.music_volume });
const volumeLabel = h("span", {}, `Default music volume: ${g.music_volume}%`);
volume.addEventListener("input", () => { volumeLabel.textContent = `Default music volume: ${volume.value}%`; });
const snipe = toggle("Snipe is on in this server", g.snipe, "Lets members see the last deleted and edited messages.");
parts.push(section("⚙️ General", null, h("div", {},
h("div", { class: "row" }, field("Prefix", prefix, "Slash commands always work too."),
h("label", { class: "field" }, volumeLabel, volume)), snipe),
() => ({ prefix: prefix.value, music_volume: Number(volume.value), snipe: snipe.input.checked }), path));
// logging
if (g.logging) {
const selects = {};
const rows = g.logging.types.map((t) => {
selects[t.key] = channelSelect(g.channels, g.logging.channels[t.key], "— off —");
return h("tr", {}, h("td", {}, `${t.emoji} ${t.label}`), h("td", {}, selects[t.key]));
});
parts.push(section("📝 Logging", "Pick a channel for each kind of event, or leave it off.",
h("table", { class: "logtable" }, h("tbody", {}, rows)),
() => ({ logging: Object.fromEntries(Object.entries(selects).map(([k, s]) => [k, s.value || null])) }), path));
}
// welcome
if (g.welcome) {
const w = g.welcome;
const message = (kind, title) => {
const e = w[`${kind}_embed`];
const on = toggle(`Send ${kind} messages`, w[`${kind}_enabled`]);
const chan = channelSelect(g.channels, w[`${kind}_channel`]);
const inputs = {
title: h("input", { type: "text", value: e.title, maxlength: 256 }),
description: h("textarea", { maxlength: 2000 }, e.description),
image: h("input", { type: "text", value: e.image, placeholder: "https://… (optional)", maxlength: 500 }),
thumbnail: h("input", { type: "text", value: e.thumbnail, placeholder: "{avatar} or https://…", maxlength: 500 }),
footer: h("input", { type: "text", value: e.footer, maxlength: 300 }),
};
const card = h("div", { class: "subcard" }, h("h3", {}, title), on, field("Channel", chan),
field("Title", inputs.title), field("Message", inputs.description), field("Image", inputs.image),
field("Thumbnail", inputs.thumbnail), field("Footer", inputs.footer));
card.collect = () => ({
[`${kind}_enabled`]: on.input.checked, [`${kind}_channel`]: chan.value || null,
[`${kind}_embed`]: Object.fromEntries(Object.entries(inputs).map(([k, el]) => [k, el.value])),
});
return card;
};
const welcome = message("welcome", "👋 Welcome");
const goodbye = message("goodbye", "🚪 Goodbye");
const roleBoxes = h("div", { class: "roles" });
for (const r of g.roles) {
const box = h("input", { type: "checkbox", value: r.id, checked: w.autoroles.includes(r.id), disabled: !r.assignable });
const dot = h("span", { class: "dot" });
if (r.colour) dot.style.background = r.colour;
roleBoxes.append(h("label", { title: r.assignable ? "" : "Above Dezio's role — Dezio can't give it" }, box, dot, r.name));
}
const sticky = toggle("Sticky roles", w.sticky_roles, "People who leave and come back get their old roles back.");
parts.push(section("👋 Welcome & goodbye",
"Placeholders: {mention} {name} {display_name} {server} {count} {id} {avatar}",
h("div", {}, h("div", { class: "cols" }, welcome, goodbye),
field("Autoroles — given to everyone who joins", roleBoxes), sticky),
() => ({ welcome: { ...welcome.collect(), ...goodbye.collect(), sticky_roles: sticky.input.checked,
autoroles: [...roleBoxes.querySelectorAll("input:checked")].map((b) => b.value) } }), path));
}
// AI
if (g.ai) {
const persona = h("textarea", { maxlength: 4000, placeholder: g.ai.default_persona }, g.ai.persona);
persona.rows = 8;
const lock = channelSelect(g.channels, g.ai.lock, "— any channel —");
parts.push(section("🤖 AI chat", "How Dezio talks when someone mentions it. Leave the personality empty for the default.",
h("div", {}, field("Personality", persona), field("Only answer in", lock)),
() => ({ ai: { persona: persona.value, lock: lock.value || null } }), path));
}
if (g.quote) {
parts.push(quoteSection("💬 Quote style (server default)", "Used for “Create Quote” by people who haven't saved a style of their own.", g.quote, path));
}
if (g.rolemenus) {
parts.push(roleMenusSection(g, path));
}
main.replaceChildren(...parts);
}
// ---------------------------------------------------------------------------- navigation
function renderSide() {
const side = $("side");
const me = state.me;
const meButton = h("button", { type: "button", class: state.page === "me" ? "active" : "", onclick: () => go("me") },
h("span", { class: "icon" }, h("img", { src: me.user.avatar, alt: "" })), h("span", { class: "label" }, "Your settings"));
const servers = me.guilds.map((g) => {
const icon = g.icon ? h("img", { src: g.icon, alt: "" }) : g.name.split(/\s+/).map((w) => w[0]).join("").slice(0, 3);
return h("button", {
type: "button", class: state.page === g.id ? "active" : "", disabled: !g.manage,
title: g.manage ? g.name : `${g.name} — you need Manage Server`, onclick: () => go(g.id),
}, h("span", { class: "icon" }, icon), h("span", { class: "label" }, g.name));
});
side.replaceChildren(h("h4", {}, "You"), meButton, h("h4", {}, "Servers"),
...(servers.length ? servers : [h("p", { class: "muted" }, "No servers shared with Dezio.")]));
}
async function go(page) {
state.page = page;
history.replaceState(null, "", page === "me" ? "/dashboard" : `/dashboard#${page}`);
renderSide();
try {
if (page === "me") await showMe(); else await showGuild(page);
} catch (e) {
$("main").replaceChildren(h("p", { class: "error" }, e.message));
}
}
const ERRORS = {
setup: "Sign-in isn't set up yet — the bot owner needs to add the OAuth client secret.",
state: "That sign-in link expired. Please try again.",
discord: "Discord didn't accept the sign-in. Please try again.",
};
async function start() {
const error = new URLSearchParams(location.search).get("error");
let me;
try { me = await api("GET", "/api/me"); } catch (e) { me = { signed_in: false, sign_in: true }; }
if (!me.signed_in) {
$("gate").classList.remove("hidden");
if (!me.sign_in) {
$("gate-text").textContent = ERRORS.setup;
$("gate-login").classList.add("hidden");
}
if (error && ERRORS[error]) {
$("gate-error").textContent = ERRORS[error];
$("gate-error").classList.remove("hidden");
}
return;
}
state.me = me;
$("who-avatar").src = me.user.avatar;
$("who-name").textContent = me.user.name;
$("who").classList.remove("hidden");
$("app").classList.remove("hidden");
$("logout").addEventListener("click", async () => {
try { await api("POST", "/logout", {}); } catch (e) { /* signed out anyway */ }
location.href = "/dashboard";
});
const wanted = location.hash.slice(1);
await go(me.guilds.some((g) => g.id === wanted && g.manage) ? wanted : "me");
}
start();