- Save the queue to storage/runtime/queue.json and restore it at startup, the interrupted track first; playback resumes once someone is in the voice channel. Shutdown keeps the queued files instead of deleting them. - Shuffle the upcoming tracks; loop mode sends finished tracks back to the end of the queue, except removed or failed ones. - Rename library tracks (queued copies follow), enqueue the whole library, optionally shuffled. - Stream queue and library changes to the web page with Server-Sent Events (GET /api/events). - Sanitise the requester name sent when queueing a library track. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
653 lines
18 KiB
JavaScript
653 lines
18 KiB
JavaScript
import { EventEmitter } from "events";
|
|
import { randomUUID } from "node:crypto";
|
|
import {
|
|
AudioPlayerStatus,
|
|
NoSubscriberBehavior,
|
|
StreamType,
|
|
VoiceConnectionStatus,
|
|
createAudioPlayer,
|
|
createAudioResource,
|
|
entersState,
|
|
joinVoiceChannel,
|
|
} from "@discordjs/voice";
|
|
import { Events } from "discord.js";
|
|
import { config } from "../config.js";
|
|
import { createOpusStream } from "../media/validateAudioFile.js";
|
|
import { serializeTrack, serializeTracks } from "../web/serializers.js";
|
|
import {
|
|
deleteTrackFile,
|
|
handleTrackCompletion,
|
|
} from "../web/storage/storageManager.js";
|
|
|
|
const AUTO_DISCONNECT_DELAY = 5 * 60 * 1000;
|
|
// Délais entre les nouvelles tentatives quand le salon vocal est injoignable. Au-delà, la
|
|
// file attend une action (ajout d'un morceau, bouton Play).
|
|
const CONNECT_RETRY_DELAYS = [5_000, 15_000, 30_000, 60_000, 60_000];
|
|
|
|
class MusicQueue extends EventEmitter {
|
|
// persistence : { load() → état | null, save(état) } pour garder la file d'un démarrage à
|
|
// l'autre (voir queuePersistence.js). Sans elle, la file est perdue à l'arrêt.
|
|
constructor(
|
|
client,
|
|
{ retryDelays = CONNECT_RETRY_DELAYS, persistence = null } = {}
|
|
) {
|
|
super();
|
|
this.setMaxListeners(50); // une écoute par page web ouverte (flux d'événements)
|
|
this.client = client;
|
|
this.queue = [];
|
|
this.currentTrack = null;
|
|
this.loop = false;
|
|
// Le morceau en cours ne doit pas revenir en fin de file en mode boucle (retiré, en
|
|
// erreur, file vidée).
|
|
this.discardCurrent = false;
|
|
this.persistence = persistence;
|
|
this.saveTimeout = null;
|
|
this.connection = null;
|
|
this.playbackStatus = AudioPlayerStatus.Idle;
|
|
this.idleDisconnectTimeout = null;
|
|
this.aloneDisconnectTimeout = null;
|
|
this.connectRetryTimeout = null;
|
|
this.connectFailures = 0;
|
|
this.retryDelays = retryDelays;
|
|
this.suspendedForAlone = false;
|
|
this.playNextPromise = null;
|
|
this.shuttingDown = false;
|
|
this.audioPlayer = createAudioPlayer({
|
|
behaviors: {
|
|
noSubscriber: NoSubscriberBehavior.Play,
|
|
},
|
|
});
|
|
this.voiceStateListener = (oldState, newState) => {
|
|
if (
|
|
oldState.channelId === config.voiceChannelId ||
|
|
newState.channelId === config.voiceChannelId
|
|
) {
|
|
this.evaluateAloneStatus();
|
|
}
|
|
};
|
|
this.client.on(Events.VoiceStateUpdate, this.voiceStateListener);
|
|
|
|
this.audioPlayer.on(AudioPlayerStatus.Idle, () => {
|
|
const finished = this.currentTrack;
|
|
this.currentTrack = null;
|
|
if (finished) {
|
|
if (this.loop && !this.discardCurrent && !this.shuttingDown) {
|
|
// Mode boucle : le morceau repart en fin de file, fichier conservé.
|
|
const { startedAt: _startedAt, ...track } = finished;
|
|
this.queue.push({ ...track, id: randomUUID() });
|
|
} else {
|
|
handleTrackCompletion(finished);
|
|
}
|
|
}
|
|
this.discardCurrent = false;
|
|
if (!this.shuttingDown) {
|
|
void this.playNext();
|
|
}
|
|
});
|
|
|
|
// Après une erreur, le player passe toujours en Idle : le gestionnaire ci-dessus
|
|
// termine le morceau et lance le suivant (sans le remettre en boucle).
|
|
this.audioPlayer.on("error", (error) => {
|
|
console.error("Audio player encountered an error", error);
|
|
this.discardCurrent = true;
|
|
});
|
|
|
|
this.on("queueUpdate", () => this.scheduleSave());
|
|
this.restore();
|
|
|
|
this.audioPlayer.on("stateChange", (oldState, newState) => {
|
|
this.playbackStatus = newState.status;
|
|
this.emit("queueUpdate", this.snapshot());
|
|
});
|
|
}
|
|
|
|
snapshot() {
|
|
return {
|
|
current: serializeTrack(this.currentTrack),
|
|
upcoming: serializeTracks(this.queue),
|
|
status: this.playbackStatus,
|
|
loop: this.loop,
|
|
// Millisecondes déjà jouées du morceau en cours (pauses exclues).
|
|
position: this.audioPlayer?.state?.resource?.playbackDuration ?? 0,
|
|
};
|
|
}
|
|
|
|
// Fichiers encore utiles (file d'attente et morceau en cours), à ne pas nettoyer.
|
|
inUsePaths() {
|
|
return new Set(
|
|
[this.currentTrack, ...this.queue]
|
|
.map((track) => track?.path)
|
|
.filter(Boolean)
|
|
);
|
|
}
|
|
|
|
async ensureConnection() {
|
|
if (this.connection) {
|
|
if (
|
|
this.connection.joinConfig.channelId === config.voiceChannelId &&
|
|
this.connection.state.status === VoiceConnectionStatus.Ready
|
|
) {
|
|
return this.connection;
|
|
}
|
|
|
|
try {
|
|
this.connection.destroy();
|
|
} catch {
|
|
// The connection may already be destroyed.
|
|
}
|
|
this.connection = null;
|
|
}
|
|
|
|
let channel = this.client.channels.cache.get(config.voiceChannelId);
|
|
|
|
if (!channel) {
|
|
try {
|
|
channel = await this.client.channels.fetch(config.voiceChannelId);
|
|
} catch (error) {
|
|
console.error("Unable to fetch voice channel", error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
if (!channel) {
|
|
throw new Error("Voice channel configured for music playback was not found");
|
|
}
|
|
|
|
const connection = joinVoiceChannel({
|
|
channelId: channel.id,
|
|
guildId: channel.guild.id,
|
|
adapterCreator: channel.guild.voiceAdapterCreator,
|
|
selfDeaf: false,
|
|
});
|
|
|
|
this.connection = connection;
|
|
connection.subscribe(this.audioPlayer);
|
|
connection.on(VoiceConnectionStatus.Disconnected, async () => {
|
|
try {
|
|
await Promise.race([
|
|
entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
|
|
entersState(connection, VoiceConnectionStatus.Connecting, 5_000),
|
|
]);
|
|
} catch {
|
|
if (this.connection === connection) {
|
|
this.destroyConnection("voice connection lost", { requeue: true });
|
|
}
|
|
}
|
|
});
|
|
|
|
try {
|
|
await entersState(connection, VoiceConnectionStatus.Ready, 30_000);
|
|
} catch (error) {
|
|
if (this.connection === connection) {
|
|
try {
|
|
connection.destroy();
|
|
} catch {
|
|
// The connection may have been destroyed by the voice adapter.
|
|
}
|
|
this.connection = null;
|
|
}
|
|
throw error;
|
|
}
|
|
this.evaluateAloneStatus();
|
|
return connection;
|
|
}
|
|
|
|
enqueue(track) {
|
|
this.queue.push(track);
|
|
// Ajouter un morceau est une demande de lecture explicite : elle lève la suspension
|
|
// (bot parti faute d'auditeurs) et relance les tentatives de connexion.
|
|
this.suspendedForAlone = false;
|
|
this.connectFailures = 0;
|
|
this.cancelIdleDisconnect();
|
|
this.emit("queueUpdate", this.snapshot());
|
|
if (!this.currentTrack) {
|
|
void this.playNext();
|
|
}
|
|
|
|
return track;
|
|
}
|
|
|
|
playNext() {
|
|
if (this.playNextPromise) {
|
|
return this.playNextPromise;
|
|
}
|
|
|
|
this.playNextPromise = this.runPlayNext().finally(() => {
|
|
this.playNextPromise = null;
|
|
});
|
|
return this.playNextPromise;
|
|
}
|
|
|
|
async runPlayNext() {
|
|
this.cancelConnectRetry();
|
|
|
|
if (this.shuttingDown || this.suspendedForAlone) {
|
|
return;
|
|
}
|
|
|
|
if (this.queue.length === 0) {
|
|
this.scheduleIdleDisconnect();
|
|
this.emit("queueUpdate", this.snapshot());
|
|
return;
|
|
}
|
|
this.cancelIdleDisconnect();
|
|
|
|
const nextTrack = this.queue[0];
|
|
|
|
try {
|
|
await this.ensureConnection();
|
|
this.connectFailures = 0;
|
|
} catch (error) {
|
|
console.error("Unable to connect to the configured voice channel", error);
|
|
this.currentTrack = null;
|
|
this.scheduleConnectRetry();
|
|
return;
|
|
}
|
|
|
|
if (this.shuttingDown || this.suspendedForAlone) {
|
|
return;
|
|
}
|
|
|
|
// La file a pu changer pendant la connexion (morceau retiré ou déplacé) : on repart
|
|
// de la nouvelle tête de file au lieu d'abandonner.
|
|
if (this.queue[0]?.id !== nextTrack.id) {
|
|
return this.runPlayNext();
|
|
}
|
|
|
|
try {
|
|
this.queue.shift();
|
|
const resource = this.createResource(nextTrack);
|
|
|
|
this.currentTrack = {
|
|
...nextTrack,
|
|
startedAt: new Date().toISOString(),
|
|
};
|
|
this.audioPlayer.play(resource);
|
|
this.emit("trackStart", this.currentTrack);
|
|
this.emit("queueUpdate", this.snapshot());
|
|
} catch (error) {
|
|
console.error("Unable to play track", error);
|
|
deleteTrackFile(nextTrack);
|
|
this.currentTrack = null;
|
|
return this.runPlayNext();
|
|
}
|
|
}
|
|
|
|
createResource(track) {
|
|
return createAudioResource(createOpusStream(track.path), {
|
|
inputType: StreamType.OggOpus,
|
|
});
|
|
}
|
|
|
|
scheduleConnectRetry() {
|
|
if (this.shuttingDown || this.queue.length === 0 || this.connectRetryTimeout) {
|
|
return;
|
|
}
|
|
|
|
if (this.connectFailures >= this.retryDelays.length) {
|
|
console.error(
|
|
`[${new Date().toLocaleString()}] MusicQueue gave up connecting after ${this.connectFailures} retries; the next enqueue or Play will try again`
|
|
);
|
|
return;
|
|
}
|
|
|
|
const delay = this.retryDelays[this.connectFailures];
|
|
this.connectFailures += 1;
|
|
this.connectRetryTimeout = setTimeout(() => {
|
|
this.connectRetryTimeout = null;
|
|
void this.playNext();
|
|
}, delay);
|
|
}
|
|
|
|
cancelConnectRetry() {
|
|
if (this.connectRetryTimeout) {
|
|
clearTimeout(this.connectRetryTimeout);
|
|
this.connectRetryTimeout = null;
|
|
}
|
|
}
|
|
|
|
async remove(trackId) {
|
|
const index = this.queue.findIndex((track) => track.id === trackId);
|
|
if (index === -1) {
|
|
if (this.currentTrack && this.currentTrack.id === trackId) {
|
|
// skip() repasse le player en Idle tout de suite, ce qui efface currentTrack.
|
|
const removed = this.currentTrack;
|
|
this.discardCurrent = true;
|
|
this.skip();
|
|
return removed;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
const [removed] = this.queue.splice(index, 1);
|
|
deleteTrackFile(removed);
|
|
this.emit("queueUpdate", this.snapshot());
|
|
if (this.queue.length === 0 && !this.currentTrack) {
|
|
this.scheduleIdleDisconnect();
|
|
}
|
|
return removed;
|
|
}
|
|
|
|
move(trackId, newPosition) {
|
|
const index = this.queue.findIndex((track) => track.id === trackId);
|
|
if (index === -1) {
|
|
return null;
|
|
}
|
|
|
|
const [track] = this.queue.splice(index, 1);
|
|
const boundedPosition = Math.max(0, Math.min(newPosition, this.queue.length));
|
|
this.queue.splice(boundedPosition, 0, track);
|
|
this.emit("queueUpdate", this.snapshot());
|
|
return this.snapshot();
|
|
}
|
|
|
|
skip() {
|
|
return this.audioPlayer.stop(true);
|
|
}
|
|
|
|
stop() {
|
|
this.cancelConnectRetry();
|
|
this.queue.forEach((track) => deleteTrackFile(track));
|
|
this.queue = [];
|
|
this.discardCurrent = Boolean(this.currentTrack);
|
|
this.audioPlayer.stop(true);
|
|
this.emit("queueUpdate", this.snapshot());
|
|
}
|
|
|
|
// Mélange les morceaux à venir (le morceau en cours n'est pas touché).
|
|
shuffle() {
|
|
for (let index = this.queue.length - 1; index > 0; index--) {
|
|
const randomIndex = Math.floor(Math.random() * (index + 1));
|
|
[this.queue[index], this.queue[randomIndex]] = [
|
|
this.queue[randomIndex],
|
|
this.queue[index],
|
|
];
|
|
}
|
|
this.emit("queueUpdate", this.snapshot());
|
|
return this.snapshot();
|
|
}
|
|
|
|
setLoop(enabled) {
|
|
this.loop = Boolean(enabled);
|
|
this.emit("queueUpdate", this.snapshot());
|
|
return this.snapshot();
|
|
}
|
|
|
|
// Met à jour le titre des morceaux en file venant d'une entrée de bibliothèque renommée.
|
|
renameLibraryTrack(libraryTrackId, title) {
|
|
for (const track of [this.currentTrack, ...this.queue]) {
|
|
if (track && track.libraryTrackId === libraryTrackId) {
|
|
track.title = title;
|
|
}
|
|
}
|
|
this.emit("queueUpdate", this.snapshot());
|
|
}
|
|
|
|
pause() {
|
|
this.audioPlayer.pause(true);
|
|
}
|
|
|
|
resume() {
|
|
this.audioPlayer.unpause();
|
|
}
|
|
|
|
start() {
|
|
this.suspendedForAlone = false;
|
|
this.connectFailures = 0;
|
|
this.cancelIdleDisconnect();
|
|
if (!this.currentTrack) {
|
|
return this.playNext();
|
|
}
|
|
return this.currentTrack;
|
|
}
|
|
|
|
removeByLibraryId(libraryTrackId) {
|
|
if (!libraryTrackId) {
|
|
return [];
|
|
}
|
|
|
|
const removed = this.queue.filter(
|
|
(track) => track.libraryTrackId === libraryTrackId
|
|
);
|
|
|
|
this.queue = this.queue.filter(
|
|
(track) => track.libraryTrackId !== libraryTrackId
|
|
);
|
|
|
|
removed.forEach((track) => deleteTrackFile(track));
|
|
|
|
if (
|
|
this.currentTrack &&
|
|
this.currentTrack.libraryTrackId === libraryTrackId
|
|
) {
|
|
this.discardCurrent = true;
|
|
this.skip();
|
|
}
|
|
|
|
if (removed.length > 0) {
|
|
this.emit("queueUpdate", this.snapshot());
|
|
}
|
|
|
|
return removed;
|
|
}
|
|
|
|
// requeue : remet le morceau interrompu en tête de file (il reprendra du début) au lieu
|
|
// de le perdre, quand la coupure ne vient pas d'une demande d'arrêt.
|
|
destroyConnection(reason, { suspend = false, requeue = false } = {}) {
|
|
if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) {
|
|
return;
|
|
}
|
|
|
|
if (suspend) {
|
|
this.suspendedForAlone = true;
|
|
}
|
|
|
|
this.cancelIdleDisconnect();
|
|
this.cancelAloneDisconnect();
|
|
|
|
const interruptedTrack = this.currentTrack;
|
|
this.currentTrack = null;
|
|
const requeued = Boolean(requeue && interruptedTrack);
|
|
if (requeued) {
|
|
const { startedAt: _startedAt, ...track } = interruptedTrack;
|
|
this.queue.unshift(track);
|
|
}
|
|
|
|
if (this.connection) {
|
|
try {
|
|
this.connection.destroy();
|
|
} catch (error) {
|
|
console.error("Failed to destroy voice connection", error);
|
|
}
|
|
this.connection = null;
|
|
}
|
|
|
|
try {
|
|
this.audioPlayer.stop(true);
|
|
} catch (error) {
|
|
console.error("Failed to stop audio player", error);
|
|
}
|
|
|
|
if (!requeued) {
|
|
handleTrackCompletion(interruptedTrack);
|
|
}
|
|
this.emit("queueUpdate", this.snapshot());
|
|
console.log(
|
|
`[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})`
|
|
);
|
|
}
|
|
|
|
scheduleIdleDisconnect() {
|
|
if (
|
|
this.idleDisconnectTimeout ||
|
|
this.queue.length > 0 ||
|
|
this.currentTrack ||
|
|
!this.connection
|
|
) {
|
|
return;
|
|
}
|
|
|
|
this.idleDisconnectTimeout = setTimeout(() => {
|
|
this.idleDisconnectTimeout = null;
|
|
if (!this.currentTrack && this.queue.length === 0 && this.connection) {
|
|
this.destroyConnection("idle timeout");
|
|
}
|
|
}, AUTO_DISCONNECT_DELAY);
|
|
}
|
|
|
|
cancelIdleDisconnect() {
|
|
if (this.idleDisconnectTimeout) {
|
|
clearTimeout(this.idleDisconnectTimeout);
|
|
this.idleDisconnectTimeout = null;
|
|
}
|
|
}
|
|
|
|
scheduleAloneDisconnect() {
|
|
if (this.aloneDisconnectTimeout || !this.connection) {
|
|
return;
|
|
}
|
|
|
|
this.aloneDisconnectTimeout = setTimeout(() => {
|
|
this.aloneDisconnectTimeout = null;
|
|
if (this.connection && this.isBotAlone()) {
|
|
this.destroyConnection("alone timeout", { suspend: true, requeue: true });
|
|
}
|
|
}, AUTO_DISCONNECT_DELAY);
|
|
}
|
|
|
|
cancelAloneDisconnect() {
|
|
if (this.aloneDisconnectTimeout) {
|
|
clearTimeout(this.aloneDisconnectTimeout);
|
|
this.aloneDisconnectTimeout = null;
|
|
}
|
|
}
|
|
|
|
evaluateAloneStatus() {
|
|
if (!this.connection) {
|
|
this.cancelAloneDisconnect();
|
|
// Parti faute d'auditeurs : revenir dès que quelqu'un rejoint le salon.
|
|
if (this.suspendedForAlone && this.queue.length > 0 && this.hasListeners()) {
|
|
this.suspendedForAlone = false;
|
|
void this.playNext();
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (this.isBotAlone()) {
|
|
this.scheduleAloneDisconnect();
|
|
} else {
|
|
const wasSuspended = this.suspendedForAlone;
|
|
this.suspendedForAlone = false;
|
|
this.cancelAloneDisconnect();
|
|
if (wasSuspended && !this.currentTrack && this.queue.length > 0) {
|
|
void this.playNext();
|
|
}
|
|
}
|
|
}
|
|
|
|
// Membres humains du salon configuré, sans le bot lui-même ni les autres bots.
|
|
listeners() {
|
|
const channel = this.client.channels.cache.get(config.voiceChannelId);
|
|
const clientId = this.client.user?.id;
|
|
if (!channel || !clientId) {
|
|
return null;
|
|
}
|
|
|
|
return [...channel.members.values()].filter(
|
|
(member) => member.id !== clientId && !member.user?.bot
|
|
);
|
|
}
|
|
|
|
hasListeners() {
|
|
return (this.listeners()?.length ?? 0) > 0;
|
|
}
|
|
|
|
isBotAlone() {
|
|
const channel = this.client.channels.cache.get(config.voiceChannelId);
|
|
const clientId = this.client.user?.id;
|
|
if (!channel || !clientId || !channel.members.has(clientId)) {
|
|
return false;
|
|
}
|
|
|
|
return this.listeners().length === 0;
|
|
}
|
|
|
|
// Avec la persistance, la file (morceau en cours en tête) est enregistrée et ses fichiers
|
|
// gardés pour le prochain démarrage ; sans elle, les fichiers temporaires sont supprimés.
|
|
shutdown() {
|
|
this.shuttingDown = true;
|
|
this.cancelIdleDisconnect();
|
|
this.cancelAloneDisconnect();
|
|
this.cancelConnectRetry();
|
|
clearTimeout(this.saveTimeout);
|
|
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
|
|
|
|
if (this.persistence) {
|
|
this.destroyConnection("shutdown", { requeue: true });
|
|
this.save();
|
|
return;
|
|
}
|
|
|
|
this.queue.forEach((track) => deleteTrackFile(track));
|
|
this.queue = [];
|
|
this.destroyConnection("shutdown");
|
|
}
|
|
|
|
persistedState() {
|
|
return {
|
|
// Le morceau en cours reprendra du début, en tête de file.
|
|
queue: [this.currentTrack, ...this.queue]
|
|
.filter(Boolean)
|
|
.map(({ startedAt: _startedAt, ...track }) => track),
|
|
loop: this.loop,
|
|
};
|
|
}
|
|
|
|
scheduleSave() {
|
|
if (!this.persistence || this.saveTimeout || this.shuttingDown) {
|
|
return;
|
|
}
|
|
this.saveTimeout = setTimeout(() => {
|
|
this.saveTimeout = null;
|
|
this.save();
|
|
}, 500);
|
|
this.saveTimeout.unref?.();
|
|
}
|
|
|
|
save() {
|
|
if (!this.persistence) return;
|
|
try {
|
|
this.persistence.save(this.persistedState());
|
|
} catch (error) {
|
|
console.error("Unable to save the music queue", error);
|
|
}
|
|
}
|
|
|
|
// Recharge la file enregistrée. Elle reste en attente (comme quand le bot est parti faute
|
|
// d'auditeurs) : la lecture reprend dès qu'il y a quelqu'un dans le salon, avec un ajout
|
|
// ou avec le bouton Play.
|
|
restore() {
|
|
if (!this.persistence) return;
|
|
let state;
|
|
try {
|
|
state = this.persistence.load();
|
|
} catch (error) {
|
|
console.error("Unable to restore the music queue", error);
|
|
return;
|
|
}
|
|
if (!state) return;
|
|
|
|
this.queue = (Array.isArray(state.queue) ? state.queue : []).filter(
|
|
(track) => track && typeof track.id === "string" && typeof track.path === "string"
|
|
);
|
|
this.loop = Boolean(state.loop);
|
|
if (this.queue.length > 0) {
|
|
this.suspendedForAlone = true;
|
|
console.log(
|
|
`[${new Date().toLocaleString()}] MusicQueue restored ${this.queue.length} track(s)`
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
export { MusicQueue };
|