palico-bot/src/music/queue.js
Shinuwa 25f22dd363
All checks were successful
Deploy Palico Bot / check (push) Successful in 9s
Deploy Palico Bot / deploy (push) Successful in 7s
Make the jukebox the home page, add seeking and redesign the site
Seeking: the progress bar is now a slider. Releasing it calls
POST /api/player/seek, which restarts ffmpeg at that position and swaps
the audio resource without going through Idle, so the track is neither
finished nor requeued in loop mode.

Structure: the jukebox is served at / and the old home page is gone.
/jukebox/ redirects to / with its query string, and the Discord login
callback now returns to /.

Redesign: a login screen until the visitor is signed in, then an app
layout with a top bar, the library on the left and the player and queue
on the right (sticky, two columns from 1000 px). Small screens get a
mini player while the main one is out of view. Icon buttons, a single
play/pause button, a drop zone for uploads, toast messages and a
refined violet palette with checked contrast. A refused password now
returns to the login screen instead of leaving an empty page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:04:03 +01:00

722 lines
22 KiB
JavaScript

/**
* @file File d'attente et lecteur du jukebox : joue les morceaux dans le salon vocal configuré et
* prévient les pages web à chaque changement.
*
* Contexte : une seule instance, créée par index.js et partagée par les commandes Discord
* (client.musicQueue) et le serveur web.
* Points d'entrée : enqueue, remove, move, skip, seek, stop, start, snapshot ; événements « queueUpdate »
* (état de la file, émis ici) et « libraryUpdate » (bibliothèque modifiée, émis par les routes).
* Utilisé par : index.js, /play, /queue, /skip, web/routes/ et music/ingest.js.
* Dépend de : @discordjs/voice, media/validateAudioFile.js (flux Opus),
* web/storage/storageManager.js (fichiers), une persistance passée au constructeur.
* Attention :
* - Sans morceau ou sans auditeur pendant 5 min, le bot quitte le salon. Parti faute d'auditeurs,
* il revient dès que quelqu'un le rejoint.
* - Un morceau temporaire est supprimé une fois joué, retiré ou en erreur, sauf en mode boucle.
* - Un morceau interrompu sans qu'on l'ait demandé (connexion vocale perdue, bot seul dans le
* salon, redémarrage) revient en tête de file avec `resumeAt` : il reprend 2 s avant l'endroit
* où il s'était arrêté. Le lecteur joue même sans connexion (NoSubscriberBehavior.Play) : la
* position d'une coupure est donc relevée dès la déconnexion, pas quand on abandonne.
* - Toute modification de la file émet « queueUpdate » : c'est aussi ce qui l'enregistre.
* @see README.md#jukebox
*/
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 { shuffle } from "../features/utilities.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];
// Secondes rejouées à la reprise d'un morceau interrompu, pour retrouver le fil.
const RESUME_REWIND = 2;
// Pendant la lecture, la position est enregistrée à cet intervalle : après un arrêt brutal du
// bot (sans arrêt propre), le morceau reprend à peu près où il en était.
const POSITION_SAVE_INTERVAL = 30_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, du début, fichier conservé.
const { startedAt: _startedAt, resumeAt: _resumeAt, ...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();
if (this.persistence) {
this.positionSaveInterval = setInterval(() => {
if (this.playbackStatus === AudioPlayerStatus.Playing) this.scheduleSave();
}, POSITION_SAVE_INTERVAL);
this.positionSaveInterval.unref?.();
}
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,
// Position dans le morceau en cours, en millisecondes (pauses exclues).
position: this.currentPosition(),
};
}
// Position dans le fichier du morceau en cours (ms), reprise comprise : playbackDuration ne
// compte que ce qui a été joué depuis le départ du flux.
currentPosition() {
if (!this.currentTrack) return 0;
const played = this.audioPlayer?.state?.resource?.playbackDuration ?? 0;
return (this.currentTrack.resumeAt ?? 0) * 1000 + played;
}
// Copie d'un morceau interrompu à `position` (ms), à remettre en file pour qu'il reprenne un
// peu avant cet endroit.
resumableTrack(track, position) {
const { startedAt: _startedAt, resumeAt: _resumeAt, ...rest } = track;
const resumeAt = Math.floor(position / 1000) - RESUME_REWIND;
return resumeAt > 0 ? { ...rest, resumeAt } : rest;
}
// 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 () => {
// Le lecteur continue sans connexion : la reprise se fera depuis l'instant de la coupure.
const position = this.currentPosition();
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, position });
}
}
});
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, { startAt: track.resumeAt }), {
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;
}
}
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() {
shuffle(this.queue);
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());
}
// Déplace la lecture du morceau en cours à `seconds`, bornée à sa durée connue. Un nouveau flux
// ffmpeg, qui démarre à cette position (resumeAt), remplace l'ancien : le lecteur ne passe pas
// par Idle, le morceau n'est donc ni terminé ni remis en boucle. En pause, la lecture repart.
// Renvoie null sans morceau en cours.
seek(seconds) {
if (!this.currentTrack) return null;
let position = Math.max(0, Math.floor(Number(seconds) || 0));
const duration = Number(this.currentTrack.duration);
if (duration > 0) {
position = Math.min(position, Math.max(0, Math.floor(duration) - 1));
}
const { resumeAt: _resumeAt, ...track } = this.currentTrack;
this.currentTrack = position > 0 ? { ...track, resumeAt: position } : track;
this.audioPlayer.play(this.createResource(this.currentTrack));
this.emit("queueUpdate", this.snapshot());
return 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, pour qu'il reprenne où il en était
// (à `position` ms si elle est donnée, sinon à la position actuelle), au lieu de le perdre,
// quand la coupure ne vient pas d'une demande d'arrêt.
destroyConnection(reason, { suspend = false, requeue = false, position } = {}) {
if (!this.connection && this.playbackStatus === AudioPlayerStatus.Idle) {
return;
}
if (suspend) {
this.suspendedForAlone = true;
}
this.cancelIdleDisconnect();
this.cancelAloneDisconnect();
const interruptedTrack = this.currentTrack;
const interruptedAt = position ?? this.currentPosition();
this.currentTrack = null;
const requeued = Boolean(requeue && interruptedTrack);
if (requeued) {
this.queue.unshift(this.resumableTrack(interruptedTrack, interruptedAt));
}
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.
humanListeners() {
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.humanListeners()?.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.humanListeners().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);
clearInterval(this.positionSaveInterval);
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() {
const current = this.currentTrack
? this.resumableTrack(this.currentTrack, this.currentPosition())
: null;
return {
// Le morceau en cours reprendra en tête de file, à peu près où il en était.
queue: [current, ...this.queue].filter(Boolean),
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 };