From 5191942d5ab949ddceb53d730b012e8d9be1475a Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Tue, 15 Sep 2026 14:51:17 +0200 Subject: [PATCH] feat(voice): add temporary voice channel manager Joining the trigger channel must feel instant and never leave orphan channels behind, so the ownership is stored in SQLite, empty channels are deleted after a short grace period and a startup sweep cleans up whatever a restart left behind. --- .env.example | 6 + src/commands/voice/voice.js | 248 ++++++ src/config/env.js | 2 + src/core/client.js | 2 + .../migrations/003-voice-channels.sql | 14 + src/database/repositories/voice-repository.js | 64 ++ src/events/client-ready.js | 2 + src/events/interaction-create.js | 2 + src/events/voice-state-update.js | 33 + src/services/voice/voice-service.js | 715 ++++++++++++++++++ src/ui/buttons.js | 51 +- tests/voice.test.js | 139 ++++ 12 files changed, 1277 insertions(+), 1 deletion(-) create mode 100644 src/commands/voice/voice.js create mode 100644 src/database/migrations/003-voice-channels.sql create mode 100644 src/database/repositories/voice-repository.js create mode 100644 src/events/voice-state-update.js create mode 100644 src/services/voice/voice-service.js create mode 100644 tests/voice.test.js diff --git a/.env.example b/.env.example index 9b34cc0..97ea3f2 100644 --- a/.env.example +++ b/.env.example @@ -42,6 +42,12 @@ CHANNEL_NOTIF_ERRORS_ID= # Category under which private ticket channels are created (M6) CATEGORY_TICKETS_ID= +# --- Salons vocaux temporaires (M14) ---------------------------------------- +# Salon vocal « rejoindre pour créer » : y entrer crée un salon temporaire +CHANNEL_VOICE_TRIGGER_ID= +# Catégorie d'accueil des salons vocaux créés (facultatif) +CATEGORY_VOICE_ID= + # --- Gitea (M5-T01) ---------------------------------------------------------- GITEA_URL=https://gitea.nocode-var.tech # Token with least privilege (read:repository, write:issue). Never log it. diff --git a/src/commands/voice/voice.js b/src/commands/voice/voice.js new file mode 100644 index 0000000..91b7325 --- /dev/null +++ b/src/commands/voice/voice.js @@ -0,0 +1,248 @@ +import { ChannelType, MessageFlags, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { UserFacingError } from '../../core/errors.js'; +import { + activeChannelCount, + claimOwnership, + getVoiceSettings, + kickUser, + NAME_MAX, + permitUser, + postSetupPanel, + rejectUser, + removeChannel, + renameChannel, + saveVoiceSettings, + setChannelLimit, + showInfo, + toggleLock, + transferOwnership, +} from '../../services/voice/voice-service.js'; +import { baseEmbed, successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.USER; +export const subcommandAccess = { setup: ACCESS_LEVELS.STAFF, panel: ACCESS_LEVELS.STAFF }; + +const voiceChannelOption = (option) => option.addChannelTypes(ChannelType.GuildVoice); + +export const data = new SlashCommandBuilder() + .setName('voice') + .setDescription('Gestion des salons vocaux temporaires') + .addSubcommand((sub) => + sub + .setName('setup') + .setDescription('Configurer le salon déclencheur et les salons créés') + .addChannelOption((option) => + voiceChannelOption( + option + .setName('trigger') + .setDescription('Salon vocal à rejoindre pour créer un salon') + .setRequired(true), + ), + ) + .addChannelOption((option) => + option + .setName('category') + .setDescription('Catégorie d’accueil des salons créés') + .addChannelTypes(ChannelType.GuildCategory), + ) + .addStringOption((option) => + option + .setName('template') + .setDescription('Modèle du nom, avec {user} (ex. « 🔊 Salon de {user} »)') + .setMaxLength(NAME_MAX), + ) + .addIntegerOption((option) => + option + .setName('limit') + .setDescription('Places par défaut (0 = illimité)') + .setMinValue(0) + .setMaxValue(99), + ) + .addBooleanOption((option) => + option.setName('panel').setDescription('Publier le panneau d’explication dans le salon déclencheur'), + ), + ) + .addSubcommand((sub) => sub.setName('config').setDescription('Afficher la configuration actuelle')) + .addSubcommand((sub) => + sub.setName('panel').setDescription('Republier le panneau d’explication dans le salon déclencheur'), + ) + .addSubcommand((sub) => + sub + .setName('name') + .setDescription('Renommer ton salon') + .addStringOption((option) => + option.setName('name').setDescription('Nouveau nom').setRequired(true).setMaxLength(NAME_MAX), + ), + ) + .addSubcommand((sub) => + sub + .setName('limit') + .setDescription('Limiter le nombre de places (0 = illimité)') + .addIntegerOption((option) => + option + .setName('limit') + .setDescription('Nombre de places') + .setRequired(true) + .setMinValue(0) + .setMaxValue(99), + ), + ) + .addSubcommand((sub) => sub.setName('lock').setDescription('Verrouiller ton salon')) + .addSubcommand((sub) => sub.setName('unlock').setDescription('Déverrouiller ton salon')) + .addSubcommand((sub) => + sub + .setName('permit') + .setDescription('Autoriser un membre à rejoindre ton salon') + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), + ) + .addSubcommand((sub) => + sub + .setName('reject') + .setDescription('Interdire l’accès à un membre') + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), + ) + .addSubcommand((sub) => + sub + .setName('kick') + .setDescription('Exclure un membre du salon') + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), + ) + .addSubcommand((sub) => + sub + .setName('transfer') + .setDescription('Transférer la propriété du salon') + .addUserOption((option) => + option.setName('user').setDescription('Nouveau propriétaire').setRequired(true), + ), + ) + .addSubcommand((sub) => sub.setName('claim').setDescription('Récupérer un salon abandonné')) + .addSubcommand((sub) => + sub + .setName('delete') + .setDescription('Supprimer un salon temporaire') + .addChannelOption((option) => + voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')), + ), + ) + .addSubcommand((sub) => + sub + .setName('info') + .setDescription('Détails du salon temporaire') + .addChannelOption((option) => + voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')), + ), + ); + +function configEmbed(guildId) { + const settings = getVoiceSettings(guildId); + return baseEmbed(COLORS.primary) + .setTitle('Salons vocaux temporaires') + .addFields( + { + name: 'Salon déclencheur', + value: settings.triggerId ? `<#${settings.triggerId}>` : '❌ Non configuré', + inline: true, + }, + { + name: 'Catégorie', + value: settings.categoryId ? `<#${settings.categoryId}>` : 'Aucune', + inline: true, + }, + { name: 'Modèle du nom', value: `\`${settings.template}\``, inline: true }, + { + name: 'Limite par défaut', + value: settings.defaultLimit ? `${settings.defaultLimit} places` : 'Illimitée', + inline: true, + }, + { name: 'Salons actifs', value: String(activeChannelCount(guildId)), inline: true }, + ); +} + +async function runSetup(interaction) { + const trigger = interaction.options.getChannel('trigger', true); + if (trigger.type !== ChannelType.GuildVoice) { + throw new UserFacingError('Le salon déclencheur doit être un salon **vocal**.'); + } + + const category = interaction.options.getChannel('category'); + const template = interaction.options.getString('template'); + const limit = interaction.options.getInteger('limit'); + + if (category && category.type !== ChannelType.GuildCategory) { + throw new UserFacingError('La catégorie d’accueil doit être une **catégorie**.'); + } + if (trigger.id === category?.id) { + throw new UserFacingError('Le salon déclencheur ne peut pas être sa propre catégorie d’accueil.'); + } + + saveVoiceSettings( + interaction.guildId, + { + trigger: trigger.id, + ...(category && { category: category.id }), + ...(template && { template }), + ...(limit !== null && { limit }), + }, + interaction.user.id, + ); + + await interaction.reply({ + embeds: [successEmbed(`Salon déclencheur : <#${trigger.id}>`)], + flags: MessageFlags.Ephemeral, + }); + + const wantsPanel = interaction.options.getBoolean('panel') ?? true; + if (wantsPanel) await postSetupPanel(interaction).catch(() => {}); +} + +/** Every subcommand acts on the caller's temporary channel, checked by the service (M14-T06). */ +export async function execute(interaction) { + const subcommand = interaction.options.getSubcommand(); + const channel = interaction.options.getChannel('channel'); + + switch (subcommand) { + case 'setup': + await runSetup(interaction); + return; + case 'panel': + await postSetupPanel(interaction); + return; + case 'config': + await interaction.reply({ embeds: [configEmbed(interaction.guildId)], flags: MessageFlags.Ephemeral }); + return; + case 'name': + await renameChannel(interaction, interaction.options.getString('name', true)); + return; + case 'limit': + await setChannelLimit(interaction, interaction.options.getInteger('limit', true)); + return; + case 'lock': + case 'unlock': + await toggleLock(interaction, { locked: subcommand === 'lock' }); + return; + case 'permit': + await permitUser(interaction, interaction.options.getUser('user', true).id); + return; + case 'reject': + await rejectUser(interaction, interaction.options.getUser('user', true).id); + return; + case 'kick': + await kickUser(interaction, interaction.options.getUser('user', true).id); + return; + case 'transfer': + await transferOwnership(interaction, interaction.options.getUser('user', true).id); + return; + case 'claim': + await claimOwnership(interaction); + return; + case 'delete': + await removeChannel(interaction, { channelId: channel?.id ?? null }); + return; + case 'info': + await showInfo(interaction, { channelId: channel?.id ?? null }); + return; + default: + return; + } +} diff --git a/src/config/env.js b/src/config/env.js index f1ae751..9b9e5e3 100644 --- a/src/config/env.js +++ b/src/config/env.js @@ -43,6 +43,8 @@ export const env = Object.freeze({ notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'), notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'), ticketCategory: read('CATEGORY_TICKETS_ID'), + voiceTrigger: read('CHANNEL_VOICE_TRIGGER_ID'), + voiceCategory: read('CATEGORY_VOICE_ID'), }, gitea: { diff --git a/src/core/client.js b/src/core/client.js index d140b96..b9d577d 100644 --- a/src/core/client.js +++ b/src/core/client.js @@ -6,6 +6,7 @@ import { Client, Collection, GatewayIntentBits, Partials } from 'discord.js'; * - GuildMembers (privileged): welcome, departures, role assignment * - GuildModeration: ban/kick audit events * - GuildMessages: /clear and ticket channels + * - GuildVoiceStates: temporary voice channels (M14) * MessageContent is intentionally not requested. */ export function createClient() { @@ -15,6 +16,7 @@ export function createClient() { GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildModeration, GatewayIntentBits.GuildMessages, + GatewayIntentBits.GuildVoiceStates, ], partials: [Partials.GuildMember], }); diff --git a/src/database/migrations/003-voice-channels.sql b/src/database/migrations/003-voice-channels.sql new file mode 100644 index 0000000..1097dba --- /dev/null +++ b/src/database/migrations/003-voice-channels.sql @@ -0,0 +1,14 @@ +-- Temporary voice channels created by joining the trigger channel (M14) +CREATE TABLE IF NOT EXISTS voice_channels ( + channel_id TEXT PRIMARY KEY, + guild_id TEXT NOT NULL, + owner_id TEXT NOT NULL, + trigger_id TEXT, + name TEXT NOT NULL, + locked INTEGER NOT NULL DEFAULT 0, + user_limit INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE INDEX IF NOT EXISTS idx_voice_channels_guild ON voice_channels (guild_id); +CREATE INDEX IF NOT EXISTS idx_voice_channels_owner ON voice_channels (guild_id, owner_id); diff --git a/src/database/repositories/voice-repository.js b/src/database/repositories/voice-repository.js new file mode 100644 index 0000000..2619a01 --- /dev/null +++ b/src/database/repositories/voice-repository.js @@ -0,0 +1,64 @@ +import { getDatabase } from '../index.js'; + +export function addVoiceChannel({ channelId, guildId, ownerId, triggerId = null, name, userLimit = 0 }) { + getDatabase() + .prepare( + `INSERT INTO voice_channels (channel_id, guild_id, owner_id, trigger_id, name, user_limit) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (channel_id) DO UPDATE SET + owner_id = excluded.owner_id, + name = excluded.name`, + ) + .run(channelId, guildId, ownerId, triggerId, name, userLimit); +} + +export function getVoiceChannel(channelId) { + return getDatabase().prepare('SELECT * FROM voice_channels WHERE channel_id = ?').get(channelId) ?? null; +} + +export function listVoiceChannels(guildId) { + return getDatabase() + .prepare('SELECT * FROM voice_channels WHERE guild_id = ? ORDER BY created_at ASC') + .all(guildId); +} + +/** Channels still owned by a member, used to move them back instead of creating another (M14-T03). */ +export function listOwnedVoiceChannels(guildId, ownerId) { + return getDatabase() + .prepare('SELECT * FROM voice_channels WHERE guild_id = ? AND owner_id = ? ORDER BY created_at ASC') + .all(guildId, ownerId); +} + +export function setVoiceOwner(channelId, ownerId) { + return getDatabase() + .prepare('UPDATE voice_channels SET owner_id = ? WHERE channel_id = ?') + .run(ownerId, channelId).changes; +} + +export function setVoiceName(channelId, name) { + return getDatabase().prepare('UPDATE voice_channels SET name = ? WHERE channel_id = ?').run(name, channelId) + .changes; +} + +export function setVoiceLocked(channelId, locked) { + return getDatabase() + .prepare('UPDATE voice_channels SET locked = ? WHERE channel_id = ?') + .run(locked ? 1 : 0, channelId).changes; +} + +export function setVoiceLimit(channelId, userLimit) { + return getDatabase() + .prepare('UPDATE voice_channels SET user_limit = ? WHERE channel_id = ?') + .run(userLimit, channelId).changes; +} + +export function removeVoiceChannel(channelId) { + return getDatabase().prepare('DELETE FROM voice_channels WHERE channel_id = ?').run(channelId).changes; +} + +export function countVoiceChannels(guildId) { + const row = getDatabase() + .prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE guild_id = ?') + .get(guildId); + return row.count; +} diff --git a/src/events/client-ready.js b/src/events/client-ready.js index ba94f64..f148589 100644 --- a/src/events/client-ready.js +++ b/src/events/client-ready.js @@ -1,6 +1,7 @@ import { ActivityType, Events } from 'discord.js'; import { createLogger } from '../core/logger.js'; import { startPollScheduler } from '../services/polls/poll-service.js'; +import { sweepVoiceChannels } from '../services/voice/voice-service.js'; const log = createLogger('discord'); @@ -10,6 +11,7 @@ export const once = true; export async function execute(client) { client.user.setActivity('FWS Arch', { type: ActivityType.Watching }); startPollScheduler(client); + await sweepVoiceChannels(client); log.info(`Connected as ${client.user.tag}`, { guilds: client.guilds.cache.size, commands: client.commands.size, diff --git a/src/events/interaction-create.js b/src/events/interaction-create.js index 59187c1..ae0b5c8 100644 --- a/src/events/interaction-create.js +++ b/src/events/interaction-create.js @@ -5,6 +5,7 @@ import { hasAccess } from '../core/permissions.js'; import { handleGiteaModal } from '../services/gitea/gitea-modals.js'; import { handlePollComponent } from '../services/polls/poll-service.js'; import { handleTicketComponent } from '../services/tickets/ticket-service.js'; +import { handleVoiceComponent, handleVoiceModal } from '../services/voice/voice-service.js'; import { errorEmbed } from '../ui/embeds.js'; const log = createLogger('interactions'); @@ -15,6 +16,7 @@ export const name = Events.InteractionCreate; const routes = [ { prefix: 'ticket:', component: handleTicketComponent }, { prefix: 'poll:', component: handlePollComponent }, + { prefix: 'voice:', component: handleVoiceComponent, modal: handleVoiceModal }, { prefix: 'issue:', modal: handleGiteaModal }, { prefix: 'pr:', modal: handleGiteaModal }, ]; diff --git a/src/events/voice-state-update.js b/src/events/voice-state-update.js new file mode 100644 index 0000000..9e6fa74 --- /dev/null +++ b/src/events/voice-state-update.js @@ -0,0 +1,33 @@ +import { Events } from 'discord.js'; +import { createLogger } from '../core/logger.js'; +import { cleanupVoiceChannel, createFromTrigger, getVoiceSettings } from '../services/voice/voice-service.js'; + +const log = createLogger('voice'); + +export const name = Events.VoiceStateUpdate; + +/** + * Joining the trigger channel creates a private channel and moves the member in; + * leaving a temporary channel deletes it once the last member is gone (M14-T02 / M14-T04). + */ +export async function execute(_client, oldState, newState) { + const member = newState.member ?? oldState.member; + if (!member || member.user.bot) return; + + try { + const joinedId = + newState.channelId && newState.channelId !== oldState.channelId ? newState.channelId : null; + if (joinedId) { + const settings = getVoiceSettings(newState.guild.id); + if (settings.triggerId && joinedId === settings.triggerId) { + await createFromTrigger(member); + } + } + + if (oldState.channelId && oldState.channelId !== newState.channelId) { + await cleanupVoiceChannel(oldState.guild, oldState.channelId); + } + } catch (error) { + log.error('Voice state handling failed', error); + } +} diff --git a/src/services/voice/voice-service.js b/src/services/voice/voice-service.js new file mode 100644 index 0000000..c4c0430 --- /dev/null +++ b/src/services/voice/voice-service.js @@ -0,0 +1,715 @@ +import { + ActionRowBuilder, + ChannelType, + MessageFlags, + ModalBuilder, + PermissionFlagsBits, + TextInputBuilder, + TextInputStyle, +} from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; +import { createLogger } from '../../core/logger.js'; +import { getAccessLevel } from '../../core/permissions.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { resolveSetting, setSetting } from '../../database/repositories/settings-repository.js'; +import { + addVoiceChannel, + countVoiceChannels, + getVoiceChannel, + listOwnedVoiceChannels, + listVoiceChannels, + removeVoiceChannel, + setVoiceLimit, + setVoiceLocked, + setVoiceName, + setVoiceOwner, +} from '../../database/repositories/voice-repository.js'; +import { voicePanelComponents } from '../../ui/buttons.js'; +import { baseEmbed, successEmbed } from '../../ui/embeds.js'; + +const log = createLogger('voice'); + +export const DEFAULT_TEMPLATE = '🔊 Salon de {user}'; +/** Discord caps the user limit of a voice channel at 99 (0 means unlimited). */ +export const LIMIT_MAX = 99; +export const NAME_MAX = 100; +/** Delay before an empty temporary channel is deleted, so a quick move does not destroy it. */ +const EMPTY_GRACE_MS = 5_000; + +/** Creation in flight per member, to never create two channels for the same person (M14-T02). */ +const pendingCreations = new Set(); +/** Channel id -> panel message id, so buttons can be refreshed after a change (M14-T05). */ +const panelMessages = new Map(); + +const VIEW = PermissionFlagsBits.ViewChannel; +const CONNECT = PermissionFlagsBits.Connect; +const SPEAK = PermissionFlagsBits.Speak; +const MEMBER_ALLOW = [VIEW, CONNECT, SPEAK]; +const OWNER_ALLOW = [...MEMBER_ALLOW, PermissionFlagsBits.ManageChannels, PermissionFlagsBits.MoveMembers]; +/** Named form required by `permissionOverwrites.edit()` (permission bits are not keys). */ +const OWNER_OVERWRITE = Object.freeze({ + ViewChannel: true, + Connect: true, + Speak: true, + ManageChannels: true, + MoveMembers: true, +}); + +/** Strips control characters without a control-character regex, then collapses spaces. */ +const clean = (value) => + [...String(value ?? '')] + .map((char) => { + const code = char.codePointAt(0); + return code <= 31 || code === 127 ? ' ' : char; + }) + .join('') + .replace(/\s+/g, ' ') + .trim(); + +/** Channel names are normalised and truncated before they reach Discord (M14-T08). */ +export function sanitizeChannelName(value) { + const name = clean(value); + if (!name) throw new UserFacingError('Le nom du salon ne peut pas être vide.'); + return name.slice(0, NAME_MAX); +} + +/** `🔊 Salon de {user}` -> the name of the channel created for a member. */ +export function buildChannelName(template, member) { + const replaced = String(template || DEFAULT_TEMPLATE).replaceAll( + '{user}', + member.displayName ?? member.user?.username ?? '', + ); + return clean(replaced).slice(0, NAME_MAX) || '🔊 Salon vocal'; +} + +/** `0` means unlimited; anything outside 0..99 is rejected or ignored (M14-T06). */ +export function clampLimit(value, { strict = false } = {}) { + const limit = Number(value); + if (!Number.isInteger(limit) || limit < 0 || limit > LIMIT_MAX) { + if (strict) { + throw new UserFacingError(`La limite doit être un entier entre 0 (illimité) et ${LIMIT_MAX}.`); + } + return 0; + } + return limit; +} + +/** Per-guild voice configuration, falling back to the environment (M14-T01). */ +export function getVoiceSettings(guildId) { + return { + triggerId: resolveSetting(guildId, 'voice.trigger', env.channels.voiceTrigger), + categoryId: resolveSetting(guildId, 'voice.category', env.channels.voiceCategory), + template: resolveSetting(guildId, 'voice.template', DEFAULT_TEMPLATE) || DEFAULT_TEMPLATE, + defaultLimit: clampLimit(resolveSetting(guildId, 'voice.limit', 0)), + }; +} + +export function saveVoiceSettings(guildId, patch, updatedBy = null) { + const keys = { + trigger: 'voice.trigger', + category: 'voice.category', + template: 'voice.template', + limit: 'voice.limit', + }; + for (const [name, key] of Object.entries(keys)) { + if (patch[name] !== undefined) setSetting(guildId, key, patch[name], updatedBy); + } +} + +export function isStaff(member, roles = env.roles) { + return getAccessLevel(member, roles) >= ACCESS_LEVELS.STAFF; +} + +export function isManagedChannel(channelId) { + return Boolean(getVoiceChannel(channelId)); +} + +/** Embed shown in the panel and by `/voice info` (M14-T05). */ +export function voicePanelEmbed(channel, row) { + const ownerId = row?.owner_id ?? null; + return baseEmbed(COLORS.primary) + .setTitle(`Gestion de ${channel.name}`) + .setDescription( + 'Les boutons ci-dessous agissent sur ce salon uniquement. Les commandes `/voice` offrent les mêmes options.', + ) + .addFields( + { name: 'Propriétaire', value: ownerId ? `<@${ownerId}>` : 'Personne', inline: true }, + { name: 'Statut', value: row?.locked ? '🔒 Verrouillé' : '🔓 Ouvert', inline: true }, + { name: 'Limite', value: row?.user_limit ? `${row.user_limit} places` : 'Illimitée', inline: true }, + { + name: 'Membres', + value: row?.user_limit ? `${channel.members.size} / ${row.user_limit}` : String(channel.members.size), + inline: true, + }, + ); +} + +export function voiceInfoEmbed(channel, row) { + const embed = baseEmbed(COLORS.primary) + .setTitle(channel.name) + .addFields( + { name: 'Propriétaire', value: row?.owner_id ? `<@${row.owner_id}>` : 'Personne', inline: true }, + { name: 'Statut', value: row?.locked ? '🔒 Verrouillé' : '🔓 Ouvert', inline: true }, + { name: 'Limite', value: row?.user_limit ? `${row.user_limit} places` : 'Illimitée', inline: true }, + { + name: 'Membres', + value: + channel.members.size === 0 + ? 'Aucun' + : channel.members + .first(10) + .map((member) => `<@${member.id}>`) + .join(', '), + }, + ) + .addFields({ name: 'Créé', value: ``, inline: true }); + + if (row?.trigger_id) embed.setFooter({ text: `Salon temporaire · déclencheur ${row.trigger_id}` }); + return embed; +} + +/** Posts the control panel in the text chat of the voice channel (M14-T05). */ +async function postPanel(channel, row) { + if (!channel.isSendable?.()) return; + + const message = await channel + .send({ + embeds: [voicePanelEmbed(channel, row)], + components: voicePanelComponents({ locked: Boolean(row.locked) }), + }) + .catch((error) => { + log.warn('Could not post the voice panel', error); + return null; + }); + if (message) panelMessages.set(channel.id, message.id); +} + +/** Refreshes the panel buttons after a change, best effort (M14-T05). */ +export async function refreshPanel(channel) { + const messageId = panelMessages.get(channel.id); + const row = getVoiceChannel(channel.id); + if (!messageId || !row || !channel.isSendable?.()) return; + + const message = await channel.messages.fetch(messageId).catch(() => null); + await message + ?.edit({ + embeds: [voicePanelEmbed(channel, row)], + components: voicePanelComponents({ locked: Boolean(row.locked) }), + }) + .catch(() => {}); +} + +async function findReusableChannel(guild, ownerId) { + for (const row of listOwnedVoiceChannels(guild.id, ownerId)) { + const channel = guild.channels.cache.get(row.channel_id); + if (!channel) { + removeVoiceChannel(row.channel_id); + panelMessages.delete(row.channel_id); + continue; + } + const full = channel.userLimit > 0 && channel.members.size >= channel.userLimit; + if (!full) return { channel, row }; + } + return null; +} + +function buildOverwrites(guild, client, ownerId) { + return [ + { id: guild.roles.everyone.id, allow: MEMBER_ALLOW }, + { id: ownerId, allow: OWNER_ALLOW }, + { id: client.user.id, allow: OWNER_ALLOW }, + ]; +} + +/** + * Called when a member joins the trigger channel: creates their channel (or moves them + * back into the one they already own) and hands it over (M14-T02 / M14-T03). + */ +export async function createFromTrigger(member) { + const settings = getVoiceSettings(member.guild.id); + if (!settings.triggerId || pendingCreations.has(member.id)) return null; + + const reusable = await findReusableChannel(member.guild, member.id); + if (reusable) { + await member.voice + .setChannel(reusable.channel, 'Retour dans son salon vocal temporaire') + .catch((error) => log.warn('Could not move the member back into their channel', error)); + return reusable.channel; + } + + pendingCreations.add(member.id); + try { + const parent = settings.categoryId + ? await member.guild.channels.fetch(settings.categoryId).catch(() => null) + : null; + + const channel = await member.guild.channels.create({ + name: buildChannelName(settings.template, member), + type: ChannelType.GuildVoice, + userLimit: settings.defaultLimit, + ...(parent?.type === ChannelType.GuildCategory && { parent: parent.id }), + reason: `Salon vocal temporaire de ${member.user.tag}`, + permissionOverwrites: buildOverwrites(member.guild, member.client, member.id), + }); + + addVoiceChannel({ + channelId: channel.id, + guildId: member.guild.id, + ownerId: member.id, + triggerId: settings.triggerId, + name: channel.name, + userLimit: settings.defaultLimit, + }); + + await member.voice + .setChannel(channel, 'Salon vocal temporaire créé') + .catch((error) => log.warn('Could not move the member into their new channel', error)); + + await postPanel(channel, getVoiceChannel(channel.id)); + logEvent({ + guildId: member.guild.id, + type: 'voice.created', + actorId: member.id, + payload: { channelId: channel.id, ownerId: member.id }, + }); + return channel; + } finally { + pendingCreations.delete(member.id); + } +} + +/** Deletes a temporary channel and forgets it. */ +export async function deleteVoiceChannel(channel, reason = 'Salon vocal temporaire supprimé') { + removeVoiceChannel(channel.id); + panelMessages.delete(channel.id); + return channel.delete(reason).catch((error) => log.warn('Could not delete the voice channel', error)); +} + +/** + * Deletes an empty temporary channel after a short grace period, so that a member + * moving between channels does not lose their channel (M14-T04). + */ +export async function cleanupVoiceChannel(guild, channelId) { + const row = getVoiceChannel(channelId); + if (!row) return; + + const channel = + guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null)); + if (!channel) { + removeVoiceChannel(channelId); + return; + } + if (channel.members.size > 0) return; + + setTimeout(async () => { + try { + const fresh = + guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null)); + if (!fresh || fresh.members.size > 0) return; + + await deleteVoiceChannel(fresh, 'Salon vocal temporaire vide').catch(() => {}); + logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId } }); + } catch (error) { + log.warn('Could not clean up an empty voice channel', error); + } + }, EMPTY_GRACE_MS).unref(); +} + +/** Startup sweep: forget deleted channels, remove the ones left empty by a restart (M14-T07). */ +export async function sweepVoiceChannels(client) { + for (const guild of client.guilds.cache.values()) { + let rows = []; + try { + rows = listVoiceChannels(guild.id); + } catch (error) { + log.warn('Could not read the stored voice channels', error); + continue; + } + + for (const row of rows) { + const channel = + guild.channels.cache.get(row.channel_id) ?? + (await guild.channels.fetch(row.channel_id).catch(() => null)); + if (!channel) { + removeVoiceChannel(row.channel_id); + panelMessages.delete(row.channel_id); + continue; + } + if (channel.members.size === 0) { + await deleteVoiceChannel(channel, 'Salon vocal temporaire vide après redémarrage'); + } + } + } +} + +export function activeChannelCount(guildId) { + return countVoiceChannels(guildId); +} + +/** Channel of the interaction itself, when it is a temporary voice channel (panel buttons and modals). */ +function managedChannelOf(interaction) { + return interaction.channelId && isManagedChannel(interaction.channelId) ? interaction.channelId : null; +} + +/** + * Resolves the temporary channel an action applies to: the explicit option first, then the + * channel the interaction happened in (panel, modal), then the voice channel of the caller (M14-T05). + */ +export async function resolveManagedChannel(interaction, { channelId = null } = {}) { + const id = channelId ?? managedChannelOf(interaction) ?? interaction.member?.voice?.channelId ?? null; + const row = id ? getVoiceChannel(id) : null; + if (!row) { + throw new UserFacingError( + 'Rejoins ton salon vocal temporaire pour le gérer, ou précise l’option `channel`.', + ); + } + if (channelId && channelId !== interaction.member?.voice?.channelId && !isStaff(interaction.member)) { + // An explicit channel is a staff convenience only: a member manages their own channel. + throw new PermissionDeniedError('Seul le staff peut cibler le salon d’un autre membre.'); + } + + const channel = await interaction.guild.channels.fetch(row.channel_id).catch(() => null); + if (!channel) { + removeVoiceChannel(row.channel_id); + throw new UserFacingError('Ce salon vocal n’existe plus.'); + } + return { channel, row }; +} + +/** Only the owner may manage a channel; staff can always step in (M14-T06). */ +export function assertVoiceOwner(interaction, row, action = 'gérer ce salon') { + if (row.owner_id === interaction.user.id || isStaff(interaction.member)) return; + throw new PermissionDeniedError(`Seul le propriétaire du salon (ou le staff) peut ${action}.`); +} + +const ephemeral = (payload) => ({ ...payload, flags: MessageFlags.Ephemeral }); + +export async function renameChannel(interaction, name) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'renommer le salon'); + + const sanitized = sanitizeChannelName(name); + await channel.setName(sanitized, `Renommé par ${interaction.user.tag}`); + setVoiceName(channel.id, sanitized); + await refreshPanel(channel); + + await interaction.reply(ephemeral({ embeds: [successEmbed(`Salon renommé en **${sanitized}**.`)] })); +} + +export async function setChannelLimit(interaction, limit) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'changer la limite'); + + const value = clampLimit(limit, { strict: true }); + await channel.setUserLimit(value, `Limite modifiée par ${interaction.user.tag}`); + setVoiceLimit(channel.id, value); + await refreshPanel(channel); + + await interaction.reply( + ephemeral({ + embeds: [ + successEmbed( + value === 0 ? 'Le salon redevient **sans limite** de places.' : `Limite : **${value} places**.`, + ), + ], + }), + ); +} + +export async function toggleLock(interaction, { locked = null } = {}) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'verrouiller le salon'); + + const next = locked === null ? !row.locked : Boolean(locked); + if (next === Boolean(row.locked)) { + throw new UserFacingError(next ? 'Le salon est déjà verrouillé.' : 'Le salon est déjà déverrouillé.'); + } + await channel.permissionOverwrites.edit( + interaction.guild.roles.everyone.id, + { Connect: next ? false : null }, + { reason: `${next ? 'Verrouillé' : 'Déverrouillé'} par ${interaction.user.tag}` }, + ); + setVoiceLocked(channel.id, next); + await refreshPanel(channel); + + await interaction.reply( + ephemeral({ + embeds: [ + successEmbed( + next + ? '🔒 Salon verrouillé : seuls les membres autorisés peuvent le rejoindre.' + : '🔓 Salon déverrouillé : tout le monde peut rejoindre.', + ), + ], + }), + ); +} + +export async function permitUser(interaction, userId) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'autoriser un membre'); + + await channel.permissionOverwrites.edit( + userId, + { ViewChannel: true, Connect: true }, + { + reason: `Autorisé par ${interaction.user.tag}`, + }, + ); + await interaction.reply(ephemeral({ embeds: [successEmbed(`<@${userId}> peut rejoindre le salon.`)] })); +} + +export async function rejectUser(interaction, userId) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'refuser un membre'); + + await channel.permissionOverwrites.edit( + userId, + { ViewChannel: false, Connect: false }, + { + reason: `Refusé par ${interaction.user.tag}`, + }, + ); + const member = channel.members.get(userId); + await member?.voice.disconnect(`Refusé par ${interaction.user.tag}`).catch(() => {}); + + await interaction.reply( + ephemeral({ embeds: [successEmbed(`<@${userId}> ne peut plus rejoindre le salon.`)] }), + ); +} + +export async function kickUser(interaction, userId) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'exclure un membre'); + + const member = channel.members.get(userId); + if (!member) throw new UserFacingError('Ce membre n’est pas dans le salon.'); + if (member.id === row.owner_id) throw new UserFacingError('Le propriétaire ne peut pas être exclu.'); + + await member.voice.disconnect(`Exclu par ${interaction.user.tag}`); + await interaction.reply(ephemeral({ embeds: [successEmbed(`<@${userId}> a été exclu du salon.`)] })); +} + +export async function transferOwnership(interaction, userId) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'transférer le salon'); + + const member = channel.members.get(userId); + if (!member) throw new UserFacingError('Le nouveau propriétaire doit déjà être dans le salon.'); + if (member.id === row.owner_id) throw new UserFacingError('Ce membre est déjà propriétaire du salon.'); + + await channel.permissionOverwrites + .edit(row.owner_id, { ManageChannels: null, MoveMembers: null }, { reason: 'Nouveau propriétaire' }) + .catch(() => {}); + await channel.permissionOverwrites.edit(member.id, OWNER_OVERWRITE, { + reason: `Salon transféré par ${interaction.user.tag}`, + }); + + setVoiceOwner(channel.id, member.id); + await refreshPanel(channel); + logEvent({ + guildId: interaction.guildId, + type: 'voice.transferred', + actorId: interaction.user.id, + payload: { channelId: channel.id, ownerId: member.id }, + }); + + await interaction.reply( + ephemeral({ + embeds: [successEmbed(`<@${member.id}> est désormais propriétaire de **${channel.name}**.`)], + }), + ); +} + +/** A member may take over a channel whose owner is gone (M14-T03). */ +export async function claimOwnership(interaction) { + const { channel, row } = await resolveManagedChannel(interaction); + if (row.owner_id === interaction.user.id) { + throw new UserFacingError('Tu es déjà propriétaire de ce salon.'); + } + if (channel.members.has(row.owner_id)) { + throw new UserFacingError('Le propriétaire est toujours dans le salon.'); + } + if (!channel.members.has(interaction.user.id)) { + throw new UserFacingError('Rejoins d’abord le salon pour en réclamer la propriété.'); + } + + await channel.permissionOverwrites.edit(interaction.user.id, OWNER_OVERWRITE, { + reason: `Salon réclamé par ${interaction.user.tag}`, + }); + setVoiceOwner(channel.id, interaction.user.id); + await refreshPanel(channel); + logEvent({ + guildId: interaction.guildId, + type: 'voice.claimed', + actorId: interaction.user.id, + payload: { channelId: channel.id }, + }); + + await interaction.reply(ephemeral({ embeds: [successEmbed('Tu es désormais propriétaire de ce salon.')] })); +} + +export async function removeChannel(interaction, { channelId = null } = {}) { + const { channel, row } = await resolveManagedChannel(interaction, { channelId }); + assertVoiceOwner(interaction, row, 'supprimer le salon'); + + await interaction.reply( + ephemeral({ embeds: [successEmbed(`Le salon **${channel.name}** va être supprimé.`)] }), + ); + logEvent({ + guildId: interaction.guildId, + type: 'voice.deleted', + actorId: interaction.user.id, + payload: { channelId: channel.id }, + }); + setTimeout( + () => deleteVoiceChannel(channel, `Supprimé par ${interaction.user.tag}`).catch(() => {}), + 3_000, + ).unref(); +} + +export async function showInfo(interaction, { channelId = null } = {}) { + const { channel, row } = await resolveManagedChannel(interaction, { channelId }); + await interaction.reply(ephemeral({ embeds: [voiceInfoEmbed(channel, row)] })); +} + +/** Posts the "join to create" panel in the trigger channel (M14-T01). */ +export async function postSetupPanel(interaction) { + const settings = getVoiceSettings(interaction.guildId); + if (!settings.triggerId) { + throw new UserFacingError('Aucun salon vocal déclencheur n’est configuré : lance `/voice setup`.'); + } + + const trigger = await interaction.guild.channels.fetch(settings.triggerId).catch(() => null); + if (!trigger?.isVoiceBased?.()) { + throw new UserFacingError('Le salon déclencheur configuré n’est pas un salon vocal.'); + } + + const embed = baseEmbed(COLORS.primary) + .setTitle('🎧 Salons vocaux temporaires') + .setDescription( + `Rejoins ${trigger} pour obtenir ton propre salon vocal.\n\n` + + 'Tu en deviens le propriétaire : renomme-le, limite le nombre de places, verrouille-le, ' + + 'autorise ou exclus des membres, ou transfère-le — depuis les boutons du salon ou les commandes `/voice`.', + ) + .addFields({ name: 'Limite par défaut', value: settings.defaultLimit || 'Illimitée', inline: true }); + + if (!trigger.isSendable()) { + throw new UserFacingError('Je n’ai pas la permission d’écrire dans le salon déclencheur.'); + } + await trigger.send({ embeds: [embed] }); + + await interaction.reply(ephemeral({ embeds: [successEmbed('Panneau publié dans le salon déclencheur.')] })); +} + +/** Button and select menu routing (M14-T05). */ +export async function handleVoiceComponent(interaction) { + const action = interaction.customId.split(':')[1]; + + if (interaction.isUserSelectMenu()) { + const userId = interaction.values[0]; + switch (action) { + case 'permit': + await permitUser(interaction, userId); + return; + case 'kick': + await kickUser(interaction, userId); + return; + case 'transfer': + await transferOwnership(interaction, userId); + return; + default: + log.debug(`Ignored voice select ${interaction.customId}`); + return; + } + } + + switch (action) { + case 'rename': + await openRenameModal(interaction); + return; + case 'limit': + await openLimitModal(interaction); + return; + case 'lock': + await toggleLock(interaction); + return; + case 'claim': + await claimOwnership(interaction); + return; + case 'info': + await showInfo(interaction); + return; + case 'delete': + await removeChannel(interaction); + return; + default: + log.debug(`Ignored voice component ${interaction.customId}`); + } +} + +async function openRenameModal(interaction) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'renommer le salon'); + + await interaction.showModal( + new ModalBuilder() + .setCustomId('voice:rename:modal') + .setTitle('Renommer le salon') + .addComponents( + new ActionRowBuilder().addComponents( + new TextInputBuilder() + .setCustomId('name') + .setLabel('Nouveau nom') + .setStyle(TextInputStyle.Short) + .setMaxLength(NAME_MAX) + .setValue(channel.name.slice(0, NAME_MAX)) + .setRequired(true), + ), + ), + ); +} + +async function openLimitModal(interaction) { + const { row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'changer la limite'); + + await interaction.showModal( + new ModalBuilder() + .setCustomId('voice:limit:modal') + .setTitle('Limite de places') + .addComponents( + new ActionRowBuilder().addComponents( + new TextInputBuilder() + .setCustomId('limit') + .setLabel(`Entre 0 (illimité) et ${LIMIT_MAX}`) + .setStyle(TextInputStyle.Short) + .setMaxLength(2) + .setValue(String(row.user_limit ?? 0)) + .setRequired(true), + ), + ), + ); +} + +/** Modal submissions opened from the panel (M14-T05). */ +export async function handleVoiceModal(interaction) { + if (interaction.customId === 'voice:rename:modal') { + await renameChannel(interaction, interaction.fields.getTextInputValue('name')); + return; + } + + if (interaction.customId === 'voice:limit:modal') { + const raw = interaction.fields.getTextInputValue('limit').trim(); + const limit = Number.parseInt(raw, 10); + if (!/^\d{1,2}$/.test(raw)) { + throw new UserFacingError(`Indique un nombre entier entre 0 (illimité) et ${LIMIT_MAX}.`); + } + await setChannelLimit(interaction, limit); + return; + } + + log.debug(`Ignored voice modal ${interaction.customId}`); +} diff --git a/src/ui/buttons.js b/src/ui/buttons.js index 317b94d..5bc08d3 100644 --- a/src/ui/buttons.js +++ b/src/ui/buttons.js @@ -1,4 +1,4 @@ -import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js'; +import { ActionRowBuilder, ButtonBuilder, ButtonStyle, UserSelectMenuBuilder } from 'discord.js'; /** Discord label and custom id limits. */ const LABEL_MAX = 80; @@ -31,6 +31,55 @@ export function ticketButtons() { ]; } +/** + * Control panel posted in a temporary voice channel (M14-T05): + * buttons for the whole channel, select menus for a specific member. + */ +export function voicePanelComponents({ locked = false } = {}) { + return [ + new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId('voice:rename') + .setLabel('Renommer') + .setEmoji('✏️') + .setStyle(ButtonStyle.Secondary), + new ButtonBuilder() + .setCustomId('voice:limit') + .setLabel('Limiter') + .setEmoji('👥') + .setStyle(ButtonStyle.Secondary), + new ButtonBuilder() + .setCustomId('voice:lock') + .setLabel(locked ? 'Déverrouiller' : 'Verrouiller') + .setEmoji(locked ? '🔓' : '🔒') + .setStyle(locked ? ButtonStyle.Success : ButtonStyle.Secondary), + new ButtonBuilder() + .setCustomId('voice:claim') + .setLabel('Réclamer') + .setEmoji('👑') + .setStyle(ButtonStyle.Primary), + new ButtonBuilder() + .setCustomId('voice:delete') + .setLabel('Supprimer') + .setEmoji('🗑️') + .setStyle(ButtonStyle.Danger), + ), + memberSelect('voice:permit', 'Autoriser un membre à rejoindre...'), + memberSelect('voice:kick', 'Exclure un membre du salon...'), + memberSelect('voice:transfer', 'Transférer la propriété du salon...'), + ]; +} + +function memberSelect(customId, placeholder) { + return new ActionRowBuilder().addComponents( + new UserSelectMenuBuilder() + .setCustomId(customId) + .setPlaceholder(placeholder) + .setMinValues(1) + .setMaxValues(1), + ); +} + /** One button per choice, 5 per row at most (M10-T02). */ export function pollButtons(pollId, choices) { const rows = []; diff --git a/tests/voice.test.js b/tests/voice.test.js new file mode 100644 index 0000000..8c7dbb9 --- /dev/null +++ b/tests/voice.test.js @@ -0,0 +1,139 @@ +import assert from 'node:assert/strict'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + addVoiceChannel, + countVoiceChannels, + getVoiceChannel, + listOwnedVoiceChannels, + listVoiceChannels, + removeVoiceChannel, + setVoiceLimit, + setVoiceLocked, + setVoiceName, + setVoiceOwner, +} from '../src/database/repositories/voice-repository.js'; +import { PermissionDeniedError, UserFacingError } from '../src/core/errors.js'; +import { + assertVoiceOwner, + buildChannelName, + clampLimit, + isStaff, + sanitizeChannelName, +} from '../src/services/voice/voice-service.js'; + +const member = (roleIds = [], { id = 'u1', guildOwnerId = 'someone-else' } = {}) => ({ + id, + guild: { ownerId: guildOwnerId }, + roles: { cache: new Set(roleIds) }, +}); + +describe('voice repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM voice_channels')); + + const add = (channelId, ownerId = 'u1') => + addVoiceChannel({ + channelId, + guildId: 'g', + ownerId, + triggerId: 'trigger', + name: 'Salon de u1', + userLimit: 0, + }); + + it('stores a temporary channel and reads it back', () => { + add('c1'); + const row = getVoiceChannel('c1'); + assert.equal(row.owner_id, 'u1'); + assert.equal(row.trigger_id, 'trigger'); + assert.equal(row.locked, 0); + assert.equal(row.user_limit, 0); + assert.ok(row.created_at); + }); + + it('keeps several channels per guild and per owner, without any limit', () => { + add('c1'); + add('c2'); + add('c3', 'u2'); + assert.equal(countVoiceChannels('g'), 3); + assert.equal(listVoiceChannels('g').length, 3); + assert.deepEqual( + listOwnedVoiceChannels('g', 'u1').map((row) => row.channel_id), + ['c1', 'c2'], + ); + }); + + it('updates the owner, the name, the lock and the limit', () => { + add('c1'); + setVoiceOwner('c1', 'u2'); + setVoiceName('c1', 'Nouveau nom'); + setVoiceLocked('c1', true); + setVoiceLimit('c1', 5); + + const row = getVoiceChannel('c1'); + assert.equal(row.owner_id, 'u2'); + assert.equal(row.name, 'Nouveau nom'); + assert.equal(row.locked, 1); + assert.equal(row.user_limit, 5); + }); + + it('forgets a channel once deleted', () => { + add('c1'); + assert.equal(removeVoiceChannel('c1'), 1); + assert.equal(getVoiceChannel('c1'), null); + assert.equal(removeVoiceChannel('c1'), 0); + }); +}); + +describe('voice helpers', () => { + it('normalises a channel name', () => { + assert.equal(sanitizeChannelName(' Salon de Léa '), 'Salon de Léa'); + assert.equal(sanitizeChannelName('a\nb'), 'a b'); + assert.equal(sanitizeChannelName('x'.repeat(150)).length, 100); + assert.throws(() => sanitizeChannelName(' '), UserFacingError); + }); + + it('builds the channel name from the template', () => { + const member = { displayName: 'Léa', user: { username: 'lea' } }; + assert.equal(buildChannelName('🔊 Salon de {user}', member), '🔊 Salon de Léa'); + assert.equal(buildChannelName('', member), '🔊 Salon de Léa'); + assert.equal(buildChannelName('{user} {user}', member), 'Léa Léa'); + assert.equal(buildChannelName(' ', member), '🔊 Salon vocal'); + }); + + it('accepts 0..99 as a user limit and rejects anything else', () => { + assert.equal(clampLimit(0), 0); + assert.equal(clampLimit(99), 99); + assert.equal(clampLimit('12'), 12); + assert.equal(clampLimit(150), 0); + assert.equal(clampLimit('abc'), 0); + assert.throws(() => clampLimit(150, { strict: true }), UserFacingError); + assert.throws(() => clampLimit(-1, { strict: true }), UserFacingError); + }); +}); + +describe('voice ownership', () => { + const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff' }; + const row = { owner_id: 'u1' }; + const context = (id, roleIds = [], overrides = {}) => ({ + user: { id }, + member: member(roleIds, { id, ...overrides }), + }); + + it('lets the owner manage their channel', () => { + assert.doesNotThrow(() => assertVoiceOwner(context('u1'), row)); + }); + + it('refuses a plain member', () => { + assert.throws(() => assertVoiceOwner(context('u2'), row), PermissionDeniedError); + }); + + it('recognises staff from the configured roles', () => { + assert.equal(isStaff(member(['r-staff']), roles), true); + assert.equal(isStaff(member(['r-dev']), roles), true); + assert.equal(isStaff(member(['r-member']), roles), false); + assert.equal(isStaff(member([], { id: 'u9', guildOwnerId: 'u9' }), roles), true); + }); +});