mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
...test
This commit is contained in:
1 parent
6ba7b33a05
commit
fe5f0e8d8c
4 files changed
+137
-24
No files matched your search
+97
-18
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* @module commands/autoplay
|
||||
* @description Toggle autoplay mode — automatically keeps the music going when the queue ends.
|
||||
* @description Toggle autoplay mode — keeps the music going forever:
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
@@ -120,7 +120,6 @@ function storePool(p, videoId, candidates) {
|
||||
|
||||
/**
|
||||
* Resolve a query via the player's Lavalink search and return all acceptable
|
||||
* candidates from the results (unshuffled, top-first).
|
||||
* @param {object} p - The player instance.
|
||||
* @param {string} query - The search query or URL.
|
||||
* @param {string} provider - Provider shorthand key ("yt", "ytm", ...).
|
||||
@@ -154,7 +153,8 @@ async function pickFromQuery(p, query, provider = "ytm") {
|
||||
* @returns {Promise<object|null>} The chosen track, or null if all strategies failed.
|
||||
*/
|
||||
async function pickAutoplayTrack(p, ctx, lastTrack) {
|
||||
const artist = lastTrack?.lastfm?.artist ?? lastTrack?.requestedArtist ?? lastTrack?.artist ?? lastTrack?.artists?.[0]?.name ?? null;
|
||||
const artist = lastTrack?.lastfm?.artist ?? lastTrack?.requestedArtist ?? lastTrack?.artist
|
||||
?? lastTrack?.artists?.[0]?.name ?? lastTrack?.author?.name ?? null;
|
||||
const name = lastTrack?.lastfm?.name ?? lastTrack?.requestedTitle ?? lastTrack?.title ?? lastTrack?.name ?? null;
|
||||
const videoId = extractVideoId(lastTrack);
|
||||
|
||||
@@ -219,30 +219,61 @@ async function pickAutoplayTrack(p, ctx, lastTrack) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialized track picking. All autoplay picks go through a per-player promise
|
||||
* chain so concurrent triggers (e.g. a skip firing "trackSkip" + "queueEnd" at
|
||||
* the same time) never race each other into picking the same track twice.
|
||||
* The picked track is recorded in history immediately after selection.
|
||||
* @param {object} p - The player instance.
|
||||
* @param {object} ctx - The bot context.
|
||||
* @param {object|null} lastTrack - Track to base the recommendation on.
|
||||
* @returns {Promise<object|null>} The chosen track, or null.
|
||||
*/
|
||||
function pickSerialized(p, ctx, lastTrack) {
|
||||
const run = async () => {
|
||||
try {
|
||||
const track = await pickAutoplayTrack(p, ctx, lastTrack);
|
||||
if (track) rememberTrack(p, track);
|
||||
return track;
|
||||
} catch (e) {
|
||||
logger.warn("[Autoplay] Pick error:", e?.message);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const prev = p._autoplayPickChain ?? Promise.resolve();
|
||||
const next = prev.then(run, run);
|
||||
// Keep the chain alive even if a caller lets a rejection slip through.
|
||||
p._autoplayPickChain = next.catch(() => {});
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill the queue ahead while autoplay is enabled. Debounced and guarded so it
|
||||
* never runs concurrently or hammers Lavalink when events arrive in bursts.
|
||||
* @param {object} p - The player instance.
|
||||
* @param {object} ctx - The bot context.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function fillQueue(p, ctx) {
|
||||
if (!p._autoplay || p._destroyed || p._autoplayFilling) return;
|
||||
const now = Date.now();
|
||||
if (now - (p._autoplayLastFillAt ?? 0) < FILL_COOLDOWN_MS) return;
|
||||
p._autoplayLastFillAt = now;
|
||||
// Loop modes mean the user's own queue repeats forever — don't grow it.
|
||||
if (p.queue?.loop || p.queue?.songLoop) return;
|
||||
|
||||
const current = p.queue?.getCurrent();
|
||||
if (!current) return; // queueEnd handler owns the "nothing playing" case.
|
||||
const upcoming = p.queue?.data?.length ?? 0;
|
||||
if (upcoming >= QUEUE_KEEP_AHEAD) return;
|
||||
|
||||
const now = Date.now();
|
||||
if (now - (p._autoplayLastFillAt ?? 0) < FILL_COOLDOWN_MS) return;
|
||||
p._autoplayLastFillAt = now;
|
||||
|
||||
p._autoplayFilling = true;
|
||||
try {
|
||||
while (p._autoplay && !p._destroyed && (p.queue?.data?.length ?? 0) < QUEUE_KEEP_AHEAD) {
|
||||
const last = p.queue?.data?.at?.(-1) ?? p._lastPlayedTrack ?? current;
|
||||
const track = await pickAutoplayTrack(p, ctx, last);
|
||||
if (!track) break;
|
||||
rememberTrack(p, track);
|
||||
const track = await pickSerialized(p, ctx, last);
|
||||
if (!track || !p._autoplay || p._destroyed) break;
|
||||
p.addToQueue(track, false);
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -253,7 +284,8 @@ async function fillQueue(p, ctx) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the queueEnd handler: pick and immediately play a similar track.
|
||||
* Build the queueEnd handler: the last song just ended and nothing is queued —
|
||||
* pick a similar track, add it, and start playing it right away.
|
||||
* @param {object} p - The player instance.
|
||||
* @param {object} ctx - The bot context.
|
||||
* @returns {Function} The handler.
|
||||
@@ -270,14 +302,14 @@ function buildQueueEndHandler(p, ctx) {
|
||||
p._stopInactivityTimer();
|
||||
rememberTrack(p, lastTrack);
|
||||
|
||||
const track = await pickAutoplayTrack(p, ctx, lastTrack);
|
||||
if (track) {
|
||||
rememberTrack(p, track);
|
||||
const track = await pickSerialized(p, ctx, lastTrack);
|
||||
if (track && p._autoplay && !p._destroyed) {
|
||||
p.addToQueue(track, false);
|
||||
logger.player(`[Autoplay] Queue ended — added and playing: ${track.title}`);
|
||||
if (!p.queue.getCurrent()) {
|
||||
p.playNext().catch(() => {});
|
||||
}
|
||||
} else if (!p._is247Enabled()) {
|
||||
} else if (!track && !p.queue?.getCurrent() && p.queue?.isEmpty() && !p._is247Enabled() && p._autoplay) {
|
||||
p._startInactivityTimer();
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -290,17 +322,55 @@ function buildQueueEndHandler(p, ctx) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach autoplay listeners (queueEnd + pre-fill hooks) to a player.
|
||||
* Build the trackSkip handler: a song was skipped — add a new similar song to
|
||||
* the queue so the music never runs dry. This fires on every skip (command,
|
||||
* control panel, dashboard, custom end-time cut) while autoplay is enabled.
|
||||
* @param {object} p - The player instance.
|
||||
* @param {object} ctx - The bot context.
|
||||
* @returns {Function} The handler.
|
||||
*/
|
||||
function buildTrackSkipHandler(p, ctx) {
|
||||
return async (skippedTrack) => {
|
||||
try {
|
||||
if (!p._autoplay || p._destroyed) return;
|
||||
// Loop modes mean the user wants their own queue repeated — don't grow it.
|
||||
if (p.queue?.loop || p.queue?.songLoop) return;
|
||||
|
||||
const basis = skippedTrack ?? p._lastPlayedTrack;
|
||||
if (!basis) return;
|
||||
rememberTrack(p, basis); // never re-pick the song that was just skipped
|
||||
|
||||
const track = await pickSerialized(p, ctx, basis);
|
||||
if (!track || !p._autoplay || p._destroyed) return;
|
||||
|
||||
p.addToQueue(track, false);
|
||||
logger.player(`[Autoplay] Skipped — replenished queue with: ${track.title}`);
|
||||
} catch (e) {
|
||||
logger.warn("[Autoplay] Skip-refill error:", e?.message);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach autoplay listeners (queueEnd, trackSkip + pre-fill hooks) to a player.
|
||||
* Exported so other modules (e.g. debug rebuilds) can restore autoplay state.
|
||||
* Note: the pre-fill hooks onto "startplay" — the Player never re-emits its
|
||||
* Queue's "queue" events as "queue" on itself, so listening for "queue" here
|
||||
* would be a dead listener and the keep-ahead fill would only run on manual
|
||||
* queue edits.
|
||||
* @param {object} p - The player instance.
|
||||
* @param {object} ctx - The bot context.
|
||||
* @returns {void}
|
||||
*/
|
||||
function attachAutoplay(p, ctx) {
|
||||
export function attachAutoplay(p, ctx) {
|
||||
detachAutoplay(p);
|
||||
|
||||
p._autoplayHandler = buildQueueEndHandler(p, ctx);
|
||||
p.on("queueEnd", p._autoplayHandler);
|
||||
|
||||
p._autoplaySkipHandler = buildTrackSkipHandler(p, ctx);
|
||||
p.on("trackSkip", p._autoplaySkipHandler);
|
||||
|
||||
p._autoplayFillHandler = () => { fillQueue(p, ctx).catch(() => {}); };
|
||||
p.on("startplay", p._autoplayFillHandler);
|
||||
p.on("update", p._autoplayFillHandler);
|
||||
@@ -312,11 +382,15 @@ function attachAutoplay(p, ctx) {
|
||||
* @param {object} p - The player instance.
|
||||
* @returns {void}
|
||||
*/
|
||||
function detachAutoplay(p) {
|
||||
export function detachAutoplay(p) {
|
||||
if (p._autoplayHandler) {
|
||||
p.removeListener("queueEnd", p._autoplayHandler);
|
||||
p._autoplayHandler = null;
|
||||
}
|
||||
if (p._autoplaySkipHandler) {
|
||||
p.removeListener("trackSkip", p._autoplaySkipHandler);
|
||||
p._autoplaySkipHandler = null;
|
||||
}
|
||||
if (p._autoplayFillHandler) {
|
||||
p.removeListener("startplay", p._autoplayFillHandler);
|
||||
p.removeListener("update", p._autoplayFillHandler);
|
||||
@@ -342,7 +416,11 @@ export async function run(msg, data) {
|
||||
p._autoplayHistory = p._autoplayHistory ?? [];
|
||||
attachAutoplay(p, this);
|
||||
|
||||
fillQueue(p, this).catch(() => {});
|
||||
if (!p.queue.getCurrent() && p.queue.isEmpty() && p._lastPlayedTrack) {
|
||||
p._autoplayHandler().catch(() => {});
|
||||
} else {
|
||||
fillQueue(p, this).catch(() => {});
|
||||
}
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
@@ -355,6 +433,7 @@ export async function run(msg, data) {
|
||||
p._autoplayMixPools?.clear();
|
||||
p._autoplayPreferredPoolVid = null;
|
||||
p._autoplayLastFillAt = 0;
|
||||
p._autoplayPickChain = null;
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
|
||||
+10
-1
@@ -230,7 +230,16 @@ async function forceRejoinPlayer(ctx, player) {
|
||||
} catch (e) { logger.warn("[Debug] queue restore:", e?.message); }
|
||||
}
|
||||
|
||||
if (wasAutoplay) newPlayer._autoplay = true;
|
||||
if (wasAutoplay) {
|
||||
newPlayer._autoplay = true;
|
||||
newPlayer._autoplayHistory = player._autoplayHistory ?? [];
|
||||
try {
|
||||
const { attachAutoplay } = await import("./autoplay.mjs");
|
||||
attachAutoplay(newPlayer, ctx);
|
||||
} catch (e) {
|
||||
logger.warn("[Debug] autoplay re-attach failed:", e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
const newRoom = newPlayer.connection?.room;
|
||||
return {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"node": ">=22.13.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@fluxerjs/core": "^2.2.0",
|
||||
"@fluxerjs/util": "^2.2.0",
|
||||
"@fluxerjs/voice": "^2.2.0",
|
||||
|
||||
+29
-5
@@ -875,7 +875,8 @@ export default class Player extends EventEmitter {
|
||||
return ":arrow_forward: Resumed";
|
||||
}
|
||||
|
||||
/** Skip the current track and advance to the next. @returns {string} Status message. */
|
||||
/** Skip the current track and advance to the next. Emits "trackSkip" with the skipped
|
||||
* track so autoplay (when enabled) can replenish the queue with a new song. @returns {string} Status message. */
|
||||
skip() {
|
||||
if (!this._voiceConn || !this.queue.getCurrent())
|
||||
return ":negative_squared_cross_mark: There's nothing playing at the moment!";
|
||||
@@ -888,6 +889,8 @@ export default class Player extends EventEmitter {
|
||||
|
||||
this._bridgeStop();
|
||||
|
||||
this.emit("trackSkip", this._lastPlayedTrack);
|
||||
|
||||
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
|
||||
this._queueEndedSent = true;
|
||||
this.emit("queueEnd");
|
||||
@@ -925,6 +928,8 @@ export default class Player extends EventEmitter {
|
||||
|
||||
this._bridgeStop();
|
||||
|
||||
this.emit("trackSkip", this._lastPlayedTrack);
|
||||
|
||||
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
|
||||
this._queueEndedSent = true;
|
||||
this.emit("queueEnd");
|
||||
@@ -1322,12 +1327,17 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
|
||||
|
||||
/** @async Resolve a free-text query to track data via Lavalink, for internal consumers (autoplay, Last.fm). @param {{query: string, provider?: string, trackMeta?: object}} opts - Query, optional provider key, optional track metadata to attach. @returns {Promise<{type: "video"|"list"|"error", data?: object}|null>} Resolved track shape, or null on failure. */
|
||||
/** @async Resolve a free-text query or URL to track data via Lavalink, for internal consumers (autoplay, Last.fm).
|
||||
* URL queries are loaded directly (like play()) instead of being prefixed with a search
|
||||
* source, so playlist/mix URLs resolve to their full track lists. @param {{query: string, provider?: string, trackMeta?: object}} opts - Query, optional provider key, optional track metadata to attach. @returns {Promise<{type: "video"|"list"|"error", data?: object}|null>} Resolved track shape, or null on failure. */
|
||||
async generalQuery({ query, provider = "yt", trackMeta = null }) {
|
||||
try {
|
||||
if (!this._lavalink) return { type: "error", data: "Audio node not ready." };
|
||||
await this._lavalink.waitForNode({ timeoutMs: 15_000 });
|
||||
const result = await this._lavalink.search(query, { source: this._getSource(provider) });
|
||||
const isUrl = typeof query === "string" && Utils.isValidUrl(query);
|
||||
const result = isUrl
|
||||
? await this._lavalink.search(query)
|
||||
: await this._lavalink.search(query, { source: this._getSource(provider) });
|
||||
const tracks = (result?.tracks ?? []).map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean);
|
||||
if (!tracks.length) return null;
|
||||
return tracks.length === 1 ? { type: "video", data: tracks[0] } : { type: "list", data: tracks };
|
||||
@@ -1636,12 +1646,15 @@ export default class Player extends EventEmitter {
|
||||
return events;
|
||||
}
|
||||
|
||||
/** @private @async Advance to the next track. */
|
||||
/** @private @async Advance to the next track. Guarded against overlapping runs: a
|
||||
* generation counter ensures an older run's cleanup never clears the in-flight
|
||||
* flag of a newer run (which previously allowed double-advances). */
|
||||
async playNext() {
|
||||
if (this._playingNext) return;
|
||||
this._playingNext = true;
|
||||
const generation = (this._playNextGeneration = (this._playNextGeneration ?? 0) + 1);
|
||||
try { await this._doPlayNext(); }
|
||||
finally { this._playingNext = false; }
|
||||
finally { if (generation === this._playNextGeneration) this._playingNext = false; }
|
||||
}
|
||||
|
||||
/** @private @async Core logic for advancing to the next track. */
|
||||
@@ -1853,9 +1866,20 @@ export default class Player extends EventEmitter {
|
||||
this._skipping = true;
|
||||
this._bridgeStop();
|
||||
this._playingNext = false;
|
||||
this._lastPlayedTrack = this.queue.getCurrent() ?? this._lastPlayedTrack;
|
||||
this.emit("trackSkip", this._lastPlayedTrack);
|
||||
if (!this.queue.isEmpty() && !this.leaving) {
|
||||
this.playNext().catch(e => logger.error("[Player] TrackEnd playNext error:", e.message));
|
||||
} else {
|
||||
this.queue.current = null;
|
||||
if (!this._wasRadio && !this._queueEndedSent) {
|
||||
this._queueEndedSent = true;
|
||||
this.emit("queueEnd");
|
||||
if (!this._autoplay) {
|
||||
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
||||
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
|
||||
}
|
||||
}
|
||||
this.emit("stopplay");
|
||||
if (!this._is247Enabled()) {
|
||||
this._startInactivityTimer();
|
||||
|
||||
Reference in new issue
Block a user