feat(web): serve the dashboard and its interface

The front-end is plain JavaScript served as is: no build step to run before
the bot starts, and no second toolchain to keep alive. A simple/advanced
switch hides the technical panels without ever standing in for a permission.

`npm run setup` starts the wizard alone, because the bot refuses to boot
without a token and the `.env` has to be writable from somewhere. When the
webhook and the dashboard share a port, a single HTTP server is started.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-23 20:09:14 +02:00
1 parent bf92badb05
commit 06a9be0cba
23 files changed
+5850 -2

No files matched your search

+428
View File
@@ -0,0 +1,428 @@
import { api } from '../core/api.js';
import { formatDate, formatRelative, h, mount } from '../core/dom.js';
import {
badge,
button,
card,
field,
grid,
input,
modal,
notice,
renderAsync,
select,
spinner,
stat,
table,
textarea,
toast,
toggle,
} from '../core/ui.js';
/** Discord server console: members, roles, moderation, announcements, routing. */
const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
const ACCESS_LABELS = { 0: 'Membre', 1: 'Staff', 2: 'Dev', 3: 'Owner' };
const ACCESS_TONE = { 0: 'neutral', 1: 'info', 2: 'success', 3: 'danger' };
const DURATIONS = [
{ value: String(5 * 60_000), label: '5 minutes' },
{ value: String(60 * 60_000), label: '1 heure' },
{ value: String(24 * 60 * 60_000), label: '1 jour' },
{ value: String(7 * 24 * 60 * 60_000), label: '7 jours' },
];
const MODERATION_ACTIONS = [
{ value: 'warn', label: 'Avertissement' },
{ value: 'mute', label: 'Exclusion temporaire' },
{ value: 'kick', label: 'Expulsion' },
{ value: 'ban', label: 'Bannissement' },
];
async function moderate(member, reload) {
const action = select(MODERATION_ACTIONS, { value: 'warn' });
const reason = input({ placeholder: 'Motif communiqué au membre' });
const duration = select(DURATIONS, { value: DURATIONS[1].value });
const durationField = field('Durée', duration);
durationField.style.display = 'none';
action.addEventListener('change', () => {
durationField.style.display = action.value === 'mute' ? '' : 'none';
});
const confirmed = await modal(
`Modérer ${member.displayName}`,
() => ({
node: h(
'div',
{ class: 'stack' },
notice(
'Le barème de rôles s’applique : tu ne peux pas agir sur quelqu’un au moins aussi haut placé.',
'info',
),
field('Action', action),
field('Motif', reason),
durationField,
),
submit: () => true,
}),
{ confirmLabel: 'Appliquer', tone: 'danger' },
);
if (!confirmed) return;
const result = await api.post('/api/discord/moderation', {
action: action.value,
userId: member.id,
reason: reason.value,
durationMs: action.value === 'mute' ? Number(duration.value) : undefined,
});
toast(`${result.label} appliqué.`);
reload();
}
async function manageRoles(member, roles, reload) {
const picker = select(
roles.filter((role) => !role.managed).map((role) => ({ value: role.id, label: role.name })),
{},
);
const current = h(
'div',
{ class: 'row' },
member.roles.map((roleId) => {
const role = roles.find((item) => item.id === roleId);
return badge(role?.name ?? roleId, 'info');
}),
);
let mode = 'add';
const confirmed = await modal(
`Rôles de ${member.displayName}`,
() => ({
node: h(
'div',
{ class: 'stack' },
h('h3', { text: 'Rôles actuels' }),
member.roles.length > 0 ? current : h('p', { class: 'muted', text: 'Aucun rôle.' }),
field(
'Action',
select(
[
{ value: 'add', label: 'Ajouter' },
{ value: 'remove', label: 'Retirer' },
],
{ value: 'add', onChange: (event) => (mode = event.target.value) },
),
),
field('Rôle', picker),
),
submit: () => true,
}),
{ confirmLabel: 'Appliquer' },
);
if (!confirmed) return;
await api.post(`/api/discord/members/${member.id}/roles`, { roleId: picker.value, action: mode });
toast('Rôles mis à jour.');
reload();
}
async function announce(channels) {
const channel = select(
channels
.filter((item) => item.kind === 'text' || item.kind === 'announcement')
.map((item) => ({ value: item.id, label: `#${item.name}` })),
{},
);
const title = input({ placeholder: 'Titre (facultatif)' });
const content = textarea({ placeholder: 'Ton message…' });
let asEmbed = true;
const confirmed = await modal(
'Publier une annonce',
() => ({
node: h(
'div',
{ class: 'stack' },
field('Salon', channel),
field('Titre', title),
field('Message', content),
toggle(true, (checked) => (asEmbed = checked), 'Publier sous forme d’embed'),
),
submit: () => content.value.trim() !== '' || title.value.trim() !== '',
}),
{ confirmLabel: 'Publier', tone: 'primary' },
);
if (!confirmed) return;
const result = await api.post('/api/discord/announce', {
channelId: channel.value,
title: title.value,
content: content.value,
asEmbed,
});
toast(`Annonce publiée (${result.messageId}).`);
}
function membersCard(guild, level) {
const host = h('div', { class: 'stack' });
const search = input({ type: 'search', placeholder: 'Nom, pseudo ou identifiant…' });
const load = () =>
renderAsync(
host,
() => api.get('/api/discord/members', { q: search.value.trim(), limit: 100 }),
(data) =>
table(
[
{
label: 'Membre',
render: (member) =>
h(
'div',
{ class: 'row' },
h('img', {
src: member.avatar,
alt: '',
width: 26,
height: 26,
style: { borderRadius: '50%' },
}),
h(
'div',
{},
h('strong', { text: member.displayName }),
h('div', { class: 'muted', text: `@${member.username}` }),
),
),
},
{
label: 'Niveau',
render: (member) => badge(ACCESS_LABELS[member.accessLevel], ACCESS_TONE[member.accessLevel]),
},
{
label: 'Arrivé',
className: 'nowrap advanced-only',
render: (member) => formatRelative(member.joinedAt),
},
{
label: 'État',
render: (member) =>
member.timeoutUntil && new Date(member.timeoutUntil) > new Date()
? badge('Exclu', 'warning')
: member.bot
? badge('Bot', 'neutral')
: '—',
},
{
label: '',
render: (member) =>
h(
'div',
{ class: 'row' },
level >= LEVELS.STAFF && button('Modérer', () => moderate(member, load), { tone: 'ghost' }),
level >= LEVELS.DEV &&
button('Rôles', () => manageRoles(member, guild.roles, load), { tone: 'ghost' }),
),
},
],
data.members,
{ empty: 'Aucun membre ne correspond.' },
),
);
let timer = null;
search.addEventListener('input', () => {
clearTimeout(timer);
timer = setTimeout(load, 300);
});
load();
return card('Membres', { subtitle: `${guild.memberCount} membre(s)`, actions: search }, host);
}
function notificationsCard(guild, level) {
const host = h('div', { class: 'stack' });
const load = () =>
renderAsync(
host,
() => api.get('/api/discord/notifications'),
(data) => {
const overrides = Object.fromEntries(data.overrides.map((row) => [row.type, row.channel_id]));
const channels = guild.channels.filter(
(item) => item.kind === 'text' || item.kind === 'announcement',
);
return table(
[
{ label: 'Type', key: 'type' },
{
label: 'Salon par défaut (.env)',
className: 'advanced-only',
render: (row) => {
const channel = guild.channels.find((item) => item.id === row.fallback);
return channel ? `#${channel.name}` : '—';
},
},
{
label: 'Salon utilisé',
render: (row) => {
if (level < LEVELS.STAFF) return row.current ? `#${row.current}` : '—';
const picker = select(
[
{ value: '', label: 'Valeur par défaut du .env' },
...channels.map((item) => ({ value: item.id, label: `#${item.name}` })),
],
{
value: overrides[row.type] ?? '',
onChange: async (event) => {
await api.put(`/api/discord/notifications/${row.type}`, {
channelId: event.target.value,
});
toast('Routage mis à jour.');
},
},
);
return picker;
},
},
],
Object.keys(data.defaults).map((type) => ({
type,
fallback: data.defaults[type],
current: overrides[type] ?? data.defaults[type],
})),
);
},
);
load();
return card(
'Notifications',
{ subtitle: 'Où le bot publie les événements Gitea et ses propres messages.' },
host,
);
}
export async function render(host, { state }) {
const level = state.me.accessLevel;
mount(host, spinner());
let guild;
try {
guild = await api.get('/api/discord/guild');
} catch (error) {
mount(host, notice(error.message, 'error'));
return;
}
const byKind = (kind) => guild.channels.filter((channel) => channel.kind === kind).length;
mount(
host,
h(
'div',
{ class: 'stack' },
h(
'div',
{ class: 'page-head' },
h(
'div',
{ class: 'row' },
guild.icon &&
h('img', { src: guild.icon, alt: '', width: 48, height: 48, style: { borderRadius: '12px' } }),
h(
'div',
{},
h('h1', { text: guild.name }),
h('p', { class: 'muted', text: `Créé le ${formatDate(guild.createdAt)}` }),
),
),
level >= LEVELS.STAFF &&
button('Publier une annonce', () => announce(guild.channels), { tone: 'primary' }),
),
card(
'Serveur',
{},
grid(
stat('Membres', guild.memberCount, { tone: 'primary' }),
stat('Salons texte', byKind('text')),
stat('Salons vocaux', byKind('voice')),
stat('Rôles', guild.roles.length),
stat('Boosts', guild.boostCount ?? 0),
stat('Niveau de boost', guild.boostTier),
),
),
membersCard(guild, level),
card(
'Rôles',
{ advanced: true, subtitle: 'Ordre hiérarchique, du plus élevé au plus bas.' },
table(
[
{
label: 'Rôle',
render: (role) =>
h(
'div',
{ class: 'row' },
h('span', {
style: {
width: '12px',
height: '12px',
borderRadius: '50%',
background: role.color === '#000000' ? 'var(--border)' : role.color,
display: 'inline-block',
},
}),
h('span', { text: role.name }),
),
},
{ label: 'Membres', className: 'num', key: 'memberCount' },
{ label: 'Position', className: 'num', key: 'position' },
{
label: 'Rôle FWS',
render: (role) => {
const mapping = Object.entries(guild.mapping.roles).find(([, id]) => id === role.id);
return mapping ? badge(mapping[0], 'success') : '—';
},
},
],
guild.roles,
),
),
notificationsCard(guild, level),
card(
'Commandes',
{ advanced: true, subtitle: 'Commandes slash chargées et niveau requis.' },
await renderCommands(),
),
),
);
}
async function renderCommands() {
const host = h('div', {});
renderAsync(
host,
() => api.get('/api/discord/commands'),
(data) =>
table(
[
{ label: 'Commande', render: (command) => `/${command.name}` },
{ label: 'Description', key: 'description' },
{ label: 'Niveau', render: (command) => badge(command.accessLabel, ACCESS_TONE[command.access]) },
{
label: 'Sous-commandes',
render: (command) => (command.options ?? []).map((option) => option.name).join(', ') || '—',
},
],
data.commands,
),
);
return host;
}