Fix jukebox playback getting stuck and make the web page reflect actions
- Adding a track or someone joining the voice channel now resumes a queue suspended because the bot was alone; before, only the Play button did. - Retry the voice connection with backoff instead of giving up after one failed attempt. - Keep playing when the head of the queue changes while connecting. - Requeue the interrupted track when the bot leaves an empty channel or loses its voice connection. - Removing the current track no longer answers 404; other bots no longer count as listeners. - Accept uploads whatever MIME type the browser sends (ffprobe validates the content) and clean temporary files hourly, sparing queued ones. - Web page: refresh again after an action instead of reusing a stale request, disable buttons while a request runs, show the real start time and custom titles, and support drag and drop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6ca17264e0
commit
a1cefe6da5
7 changed files with 363 additions and 77 deletions
|
|
@ -18,9 +18,12 @@ import {
|
|||
} 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 {
|
||||
constructor(client) {
|
||||
constructor(client, { retryDelays = CONNECT_RETRY_DELAYS } = {}) {
|
||||
super();
|
||||
this.client = client;
|
||||
this.queue = [];
|
||||
|
|
@ -29,6 +32,9 @@ class MusicQueue extends EventEmitter {
|
|||
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;
|
||||
|
|
@ -57,13 +63,10 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
});
|
||||
|
||||
// Après une erreur, le player passe toujours en Idle : le gestionnaire ci-dessus
|
||||
// termine le morceau et lance le suivant.
|
||||
this.audioPlayer.on("error", (error) => {
|
||||
console.error("Audio player encountered an error", error);
|
||||
handleTrackCompletion(this.currentTrack);
|
||||
this.currentTrack = null;
|
||||
if (!this.shuttingDown) {
|
||||
void this.playNext();
|
||||
}
|
||||
});
|
||||
|
||||
this.audioPlayer.on("stateChange", (oldState, newState) => {
|
||||
|
|
@ -80,6 +83,15 @@ class MusicQueue extends EventEmitter {
|
|||
};
|
||||
}
|
||||
|
||||
// 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 (
|
||||
|
|
@ -129,7 +141,7 @@ class MusicQueue extends EventEmitter {
|
|||
]);
|
||||
} catch {
|
||||
if (this.connection === connection) {
|
||||
this.destroyConnection("voice connection lost");
|
||||
this.destroyConnection("voice connection lost", { requeue: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -153,6 +165,10 @@ class MusicQueue extends EventEmitter {
|
|||
|
||||
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) {
|
||||
|
|
@ -174,7 +190,9 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
|
||||
async runPlayNext() {
|
||||
if (this.suspendedForAlone) {
|
||||
this.cancelConnectRetry();
|
||||
|
||||
if (this.shuttingDown || this.suspendedForAlone) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -189,26 +207,27 @@ class MusicQueue extends EventEmitter {
|
|||
|
||||
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 ||
|
||||
this.queue[0]?.id !== nextTrack.id
|
||||
) {
|
||||
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 stream = fs.createReadStream(nextTrack.path);
|
||||
const resource = createAudioResource(stream, {
|
||||
inlineVolume: true,
|
||||
});
|
||||
const resource = this.createResource(nextTrack);
|
||||
|
||||
this.currentTrack = {
|
||||
...nextTrack,
|
||||
|
|
@ -225,12 +244,45 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
createResource(track) {
|
||||
return createAudioResource(fs.createReadStream(track.path));
|
||||
}
|
||||
|
||||
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.skip();
|
||||
return this.currentTrack;
|
||||
return removed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -262,6 +314,7 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
|
||||
stop() {
|
||||
this.cancelConnectRetry();
|
||||
this.queue.forEach((track) => deleteTrackFile(track));
|
||||
this.queue = [];
|
||||
this.audioPlayer.stop(true);
|
||||
|
|
@ -278,6 +331,7 @@ class MusicQueue extends EventEmitter {
|
|||
|
||||
start() {
|
||||
this.suspendedForAlone = false;
|
||||
this.connectFailures = 0;
|
||||
this.cancelIdleDisconnect();
|
||||
if (!this.currentTrack) {
|
||||
return this.playNext();
|
||||
|
|
@ -314,7 +368,9 @@ class MusicQueue extends EventEmitter {
|
|||
return removed;
|
||||
}
|
||||
|
||||
destroyConnection(reason, { suspend = false } = {}) {
|
||||
// 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;
|
||||
}
|
||||
|
|
@ -328,6 +384,11 @@ class MusicQueue extends EventEmitter {
|
|||
|
||||
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 {
|
||||
|
|
@ -344,7 +405,9 @@ class MusicQueue extends EventEmitter {
|
|||
console.error("Failed to stop audio player", error);
|
||||
}
|
||||
|
||||
handleTrackCompletion(interruptedTrack);
|
||||
if (!requeued) {
|
||||
handleTrackCompletion(interruptedTrack);
|
||||
}
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})`
|
||||
|
|
@ -384,7 +447,7 @@ class MusicQueue extends EventEmitter {
|
|||
this.aloneDisconnectTimeout = setTimeout(() => {
|
||||
this.aloneDisconnectTimeout = null;
|
||||
if (this.connection && this.isBotAlone()) {
|
||||
this.destroyConnection("alone timeout", { suspend: true });
|
||||
this.destroyConnection("alone timeout", { suspend: true, requeue: true });
|
||||
}
|
||||
}, AUTO_DISCONNECT_DELAY);
|
||||
}
|
||||
|
|
@ -399,6 +462,11 @@ class MusicQueue extends EventEmitter {
|
|||
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;
|
||||
}
|
||||
|
||||
|
|
@ -414,29 +482,38 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
if (!channel) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const clientId = this.client.user?.id;
|
||||
if (!clientId) {
|
||||
if (!channel || !clientId || !channel.members.has(clientId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!channel.members.has(clientId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const others = channel.members.filter((member) => member.id !== clientId);
|
||||
return others.size === 0;
|
||||
return this.listeners().length === 0;
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
this.shuttingDown = true;
|
||||
this.cancelIdleDisconnect();
|
||||
this.cancelAloneDisconnect();
|
||||
this.cancelConnectRetry();
|
||||
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
|
||||
|
||||
this.queue.forEach((track) => deleteTrackFile(track));
|
||||
|
|
|
|||
|
|
@ -8,19 +8,9 @@ import {
|
|||
registerUploadedFile,
|
||||
} from "../storage/storageManager.js";
|
||||
|
||||
const ALLOWED_AUDIO_TYPES = new Set([
|
||||
"audio/aac",
|
||||
"audio/flac",
|
||||
"audio/mp4",
|
||||
"audio/mpeg",
|
||||
"audio/ogg",
|
||||
"audio/wav",
|
||||
"audio/webm",
|
||||
"audio/x-flac",
|
||||
"audio/x-m4a",
|
||||
"audio/x-wav",
|
||||
]);
|
||||
|
||||
// Pas de filtre sur le type MIME : il vient du navigateur et varie selon le système (un MP3
|
||||
// peut arriver en « audio/mp3 », un FLAC sans type). Les fichiers refusés disparaissaient sans
|
||||
// message clair ; ffprobe vérifie le contenu réel après l'envoi.
|
||||
const upload = multer({
|
||||
dest: TEMP_DIR,
|
||||
limits: {
|
||||
|
|
@ -35,7 +25,7 @@ const upload = multer({
|
|||
callback(error);
|
||||
return;
|
||||
}
|
||||
callback(null, ALLOWED_AUDIO_TYPES.has(file.mimetype));
|
||||
callback(null, true);
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -101,9 +101,17 @@ function createApp(
|
|||
return app;
|
||||
}
|
||||
|
||||
const TEMP_CLEANUP_INTERVAL = 60 * 60_000;
|
||||
|
||||
function startWebServer(dependencies) {
|
||||
ensureStorageLayout();
|
||||
cleanupTemporaryFiles();
|
||||
const cleanup = () =>
|
||||
cleanupTemporaryFiles(undefined, { keep: dependencies.queue.inUsePaths() });
|
||||
cleanup();
|
||||
// Les fichiers temporaires de plus de 24 h sont supprimés pendant que le bot tourne,
|
||||
// pas seulement à son démarrage.
|
||||
const cleanupInterval = setInterval(cleanup, TEMP_CLEANUP_INTERVAL);
|
||||
cleanupInterval.unref();
|
||||
|
||||
const app = createApp(dependencies);
|
||||
const port = Number(process.env.PORT || config.webServerPort || 3000);
|
||||
|
|
@ -113,6 +121,7 @@ function startWebServer(dependencies) {
|
|||
`[${new Date().toLocaleString()}] Web control server listening on port ${port}`
|
||||
);
|
||||
});
|
||||
server.on("close", () => clearInterval(cleanupInterval));
|
||||
|
||||
return { app, server };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -171,7 +171,8 @@ function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
|
|||
};
|
||||
}
|
||||
|
||||
function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE) {
|
||||
// keep : chemins encore utilisés (file d'attente, morceau en cours), jamais supprimés.
|
||||
function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE, { keep = new Set() } = {}) {
|
||||
ensureStorageLayout();
|
||||
const cutoff = Date.now() - maxAge;
|
||||
|
||||
|
|
@ -181,6 +182,9 @@ function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE) {
|
|||
}
|
||||
|
||||
const filePath = path.join(TEMP_DIR, entry.name);
|
||||
if (keep.has(filePath)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if (fs.statSync(filePath).mtimeMs < cutoff) {
|
||||
fs.unlinkSync(filePath);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue