Files
FWS-DiscordBot/src/web/public/views/discord.js
T
BlackAngelTV 99e1fd2723 fix(moderation): tell a mute apart from a kick in the logs
A timeout was filed as "Exclusion temporaire" right next to "Expulsion",
so a sanction could not be read back from the log channel, the direct
message or `/mod logs`. Each action now carries its own emoji and wording
behind a single label, used by every surface.
2026-09-25 20:29:19 +02:00

465 lines
14 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.
import { api } from '../core/api.js';
import { formatDate, formatRelative, h, mount } from '../core/dom.js';
import {
badge,
button,
card,
confirmAction,
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' },
];
// Mirrors MODERATION_ACTIONS in `src/config/constants.js`, emoji included: the
// panel must not be the one place where a mute reads like a kick.
const MODERATION_ACTIONS = [
{ value: 'warn', label: '⚠️ Avertissement' },
{ value: 'mute', label: '🔇 Mise en sourdine' },
{ 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, initialSearch = '') {
const host = h('div', { class: 'stack' });
// Pre-filled when the command palette sent us here for one member, so the
// link lands on that person rather than on the top of the roster.
const search = input({
type: 'search',
placeholder: 'Nom, pseudo ou identifiant…',
value: initialSearch,
});
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,
);
}
/** `#/discord?member=nom` — where the command palette points a member result. */
const memberQuery = () => new URLSearchParams(window.location.hash.split('?')[1] ?? '').get('member') ?? '';
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, memberQuery()),
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 slash',
{
subtitle: 'Commandes chargées par le bot et niveau requis pour chacune.',
actions:
level >= LEVELS.OWNER &&
button(
'Publier sur Discord',
async () => {
if (
!(await confirmAction(
'Publier les commandes',
'Les commandes chargées remplacent celles enregistrées sur le serveur. L’effet est immédiat.',
))
) {
return;
}
const result = await api.post('/api/discord/commands/deploy', {});
toast(`${result.count} commande(s) publiée(s) sur le serveur.`);
},
{ tone: 'primary' },
),
},
h('p', {
class: 'muted',
text: 'À relancer après chaque ajout ou modification de commande — l’équivalent de `npm run deploy:commands`.',
}),
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;
}