mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
...
This commit is contained in:
1 parent
e529114c31
commit
6ba7b33a05
4 files changed
+123
-15
No files matched your search
+103
-14
@@ -24,6 +24,12 @@ const HISTORY_SIZE = 30;
|
|||||||
/** Sanity bounds for candidate durations (ms) — skip hour-long mixes and jingles. */
|
/** Sanity bounds for candidate durations (ms) — skip hour-long mixes and jingles. */
|
||||||
const MIN_DURATION_MS = 45_000;
|
const MIN_DURATION_MS = 45_000;
|
||||||
const MAX_DURATION_MS = 15 * 60_000;
|
const MAX_DURATION_MS = 15 * 60_000;
|
||||||
|
/** Resolved mix candidate pools older than this are discarded. */
|
||||||
|
const MIX_POOL_TTL_MS = 5 * 60_000;
|
||||||
|
/** Max mix pools cached per player (LRU-style eviction). */
|
||||||
|
const MAX_MIX_POOLS = 4;
|
||||||
|
/** Minimum time between fill runs — absorbs event bursts without extra Lavalink searches. */
|
||||||
|
const FILL_COOLDOWN_MS = 1_200;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Extract a YouTube video ID from a track's videoId field or URL.
|
* Extract a YouTube video ID from a track's videoId field or URL.
|
||||||
@@ -62,7 +68,7 @@ function rememberTrack(p, track) {
|
|||||||
*/
|
*/
|
||||||
function isCandidateOk(p, t) {
|
function isCandidateOk(p, t) {
|
||||||
if (!t) return false;
|
if (!t) return false;
|
||||||
const ms = Number(t._durationMs ?? t.duration?.seconds * 1000 ?? 0);
|
const ms = Number(t._durationMs) || (Number(t.duration?.seconds) * 1000) || 0;
|
||||||
if (ms && (ms < MIN_DURATION_MS || ms > MAX_DURATION_MS)) return false;
|
if (ms && (ms < MIN_DURATION_MS || ms > MAX_DURATION_MS)) return false;
|
||||||
const vid = extractVideoId(t);
|
const vid = extractVideoId(t);
|
||||||
if (vid && (p._autoplayHistory ?? []).some(h => h.vid === vid)) return false;
|
if (vid && (p._autoplayHistory ?? []).some(h => h.vid === vid)) return false;
|
||||||
@@ -71,6 +77,62 @@ function isCandidateOk(p, t) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Take a random acceptable candidate from a cached mix pool, if one exists and
|
||||||
|
* is fresh. Candidates already picked are excluded via the autoplay history.
|
||||||
|
* @param {object} p - The player instance.
|
||||||
|
* @param {string} videoId - The video ID the pool was resolved from.
|
||||||
|
* @returns {object|null} An acceptable track from the pool, or null.
|
||||||
|
*/
|
||||||
|
function takeFromPool(p, videoId) {
|
||||||
|
const pools = p._autoplayMixPools;
|
||||||
|
if (!pools) return null;
|
||||||
|
const pool = pools.get(videoId);
|
||||||
|
if (!pool) return null;
|
||||||
|
if (Date.now() - pool.ts > MIX_POOL_TTL_MS) {
|
||||||
|
pools.delete(videoId);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const ok = pool.tracks.filter(t => isCandidateOk(p, t));
|
||||||
|
if (!ok.length) {
|
||||||
|
pools.delete(videoId);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return ok[Math.floor(Math.random() * Math.min(PICK_POOL, ok.length))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Store resolved mix candidates on the player for reuse across picks.
|
||||||
|
* @param {object} p - The player instance.
|
||||||
|
* @param {string} videoId - The video ID the candidates were resolved from.
|
||||||
|
* @param {Array<object>} candidates - Acceptable candidate tracks.
|
||||||
|
* @returns {void}
|
||||||
|
*/
|
||||||
|
function storePool(p, videoId, candidates) {
|
||||||
|
if (!videoId || !candidates.length) return;
|
||||||
|
const pools = p._autoplayMixPools ?? new Map();
|
||||||
|
if (!p._autoplayMixPools) p._autoplayMixPools = pools;
|
||||||
|
if (pools.size >= MAX_MIX_POOLS) {
|
||||||
|
pools.delete(pools.keys().next().value);
|
||||||
|
}
|
||||||
|
pools.set(videoId, { tracks: candidates, ts: Date.now() });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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", ...).
|
||||||
|
* @returns {Promise<Array<object>>} Acceptable candidate tracks.
|
||||||
|
*/
|
||||||
|
async function resolveCandidates(p, query, provider = "ytm") {
|
||||||
|
const resolved = await p.generalQuery({ query, provider });
|
||||||
|
const list = resolved?.type === "list" ? (resolved.data ?? [])
|
||||||
|
: resolved?.type === "video" && resolved.data ? [resolved.data] : [];
|
||||||
|
return list.filter(t => isCandidateOk(p, t));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve a query via the player's Lavalink search and return a random acceptable
|
* Resolve a query via the player's Lavalink search and return a random acceptable
|
||||||
* candidate from the top results.
|
* candidate from the top results.
|
||||||
@@ -80,16 +142,12 @@ function isCandidateOk(p, t) {
|
|||||||
* @returns {Promise<object|null>} An acceptable track, or null.
|
* @returns {Promise<object|null>} An acceptable track, or null.
|
||||||
*/
|
*/
|
||||||
async function pickFromQuery(p, query, provider = "ytm") {
|
async function pickFromQuery(p, query, provider = "ytm") {
|
||||||
const resolved = await p.generalQuery({ query, provider });
|
const ok = await resolveCandidates(p, query, provider);
|
||||||
const list = resolved?.type === "list" ? (resolved.data ?? [])
|
|
||||||
: resolved?.type === "video" && resolved.data ? [resolved.data] : [];
|
|
||||||
const ok = list.filter(t => isCandidateOk(p, t));
|
|
||||||
if (!ok.length) return null;
|
if (!ok.length) return null;
|
||||||
return ok[Math.floor(Math.random() * Math.min(PICK_POOL, ok.length))];
|
return ok[Math.floor(Math.random() * Math.min(PICK_POOL, ok.length))];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pick the next autoplay track using the strategy chain.
|
|
||||||
* @param {object} p - The player instance.
|
* @param {object} p - The player instance.
|
||||||
* @param {object} ctx - The bot context (needs .lastfm).
|
* @param {object} ctx - The bot context (needs .lastfm).
|
||||||
* @param {object|null} lastTrack - The last played internal track.
|
* @param {object|null} lastTrack - The last played internal track.
|
||||||
@@ -100,11 +158,27 @@ async function pickAutoplayTrack(p, ctx, lastTrack) {
|
|||||||
const name = lastTrack?.lastfm?.name ?? lastTrack?.requestedTitle ?? lastTrack?.title ?? lastTrack?.name ?? null;
|
const name = lastTrack?.lastfm?.name ?? lastTrack?.requestedTitle ?? lastTrack?.title ?? lastTrack?.name ?? null;
|
||||||
const videoId = extractVideoId(lastTrack);
|
const videoId = extractVideoId(lastTrack);
|
||||||
|
|
||||||
|
if (p._autoplayPreferredPoolVid) {
|
||||||
|
const pooled = takeFromPool(p, p._autoplayPreferredPoolVid);
|
||||||
|
if (pooled) return pooled;
|
||||||
|
p._autoplayPreferredPoolVid = null;
|
||||||
|
}
|
||||||
|
|
||||||
if (videoId) {
|
if (videoId) {
|
||||||
|
const cached = takeFromPool(p, videoId);
|
||||||
|
if (cached) {
|
||||||
|
p._autoplayPreferredPoolVid = videoId;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const mixUrl = `https://www.youtube.com/watch?v=${videoId}&list=RD${videoId}`;
|
const mixUrl = `https://www.youtube.com/watch?v=${videoId}&list=RD${videoId}`;
|
||||||
const track = await pickFromQuery(p, mixUrl, "yt");
|
const candidates = await resolveCandidates(p, mixUrl, "yt");
|
||||||
if (track) return track;
|
if (candidates.length) {
|
||||||
|
storePool(p, videoId, candidates);
|
||||||
|
p._autoplayPreferredPoolVid = videoId;
|
||||||
|
return candidates[Math.floor(Math.random() * Math.min(PICK_POOL, candidates.length))];
|
||||||
|
}
|
||||||
} catch (e) { logger.warn("[Autoplay] Mix strategy failed:", e?.message); }
|
} catch (e) { logger.warn("[Autoplay] Mix strategy failed:", e?.message); }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +189,10 @@ async function pickAutoplayTrack(p, ctx, lastTrack) {
|
|||||||
for (let i = 0; i < Math.min(4, similar.length); i++) {
|
for (let i = 0; i < Math.min(4, similar.length); i++) {
|
||||||
const pick = similar[Math.floor(Math.random() * Math.min(3, similar.length))];
|
const pick = similar[Math.floor(Math.random() * Math.min(3, similar.length))];
|
||||||
const track = await pickFromQuery(p, `${pick.name} ${pick.artist}`.trim(), "ytm");
|
const track = await pickFromQuery(p, `${pick.name} ${pick.artist}`.trim(), "ytm");
|
||||||
if (track) return track;
|
if (track) {
|
||||||
|
p._autoplayPreferredPoolVid = null;
|
||||||
|
return track;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (e) { logger.warn("[Autoplay] Last.fm strategy failed:", e?.message); }
|
} catch (e) { logger.warn("[Autoplay] Last.fm strategy failed:", e?.message); }
|
||||||
}
|
}
|
||||||
@@ -123,13 +200,19 @@ async function pickAutoplayTrack(p, ctx, lastTrack) {
|
|||||||
if (artist) {
|
if (artist) {
|
||||||
try {
|
try {
|
||||||
const track = await pickFromQuery(p, `${artist} songs`, "ytm");
|
const track = await pickFromQuery(p, `${artist} songs`, "ytm");
|
||||||
if (track) return track;
|
if (track) {
|
||||||
|
p._autoplayPreferredPoolVid = null;
|
||||||
|
return track;
|
||||||
|
}
|
||||||
} catch (e) { logger.warn("[Autoplay] Artist strategy failed:", e?.message); }
|
} catch (e) { logger.warn("[Autoplay] Artist strategy failed:", e?.message); }
|
||||||
}
|
}
|
||||||
if (name) {
|
if (name) {
|
||||||
try {
|
try {
|
||||||
const track = await pickFromQuery(p, `${name}`, "ytm");
|
const track = await pickFromQuery(p, `${name}`, "ytm");
|
||||||
if (track) return track;
|
if (track) {
|
||||||
|
p._autoplayPreferredPoolVid = null;
|
||||||
|
return track;
|
||||||
|
}
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,13 +221,16 @@ async function pickAutoplayTrack(p, ctx, lastTrack) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Fill the queue ahead while autoplay is enabled. Debounced and guarded so it
|
* Fill the queue ahead while autoplay is enabled. Debounced and guarded so it
|
||||||
* never runs concurrently or fights the queueEnd handler.
|
|
||||||
* @param {object} p - The player instance.
|
* @param {object} p - The player instance.
|
||||||
* @param {object} ctx - The bot context.
|
* @param {object} ctx - The bot context.
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
async function fillQueue(p, ctx) {
|
async function fillQueue(p, ctx) {
|
||||||
if (!p._autoplay || p._destroyed || p._autoplayFilling) return;
|
if (!p._autoplay || p._destroyed || p._autoplayFilling) return;
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - (p._autoplayLastFillAt ?? 0) < FILL_COOLDOWN_MS) return;
|
||||||
|
p._autoplayLastFillAt = now;
|
||||||
|
|
||||||
const current = p.queue?.getCurrent();
|
const current = p.queue?.getCurrent();
|
||||||
if (!current) return; // queueEnd handler owns the "nothing playing" case.
|
if (!current) return; // queueEnd handler owns the "nothing playing" case.
|
||||||
const upcoming = p.queue?.data?.length ?? 0;
|
const upcoming = p.queue?.data?.length ?? 0;
|
||||||
@@ -216,7 +302,7 @@ function attachAutoplay(p, ctx) {
|
|||||||
p.on("queueEnd", p._autoplayHandler);
|
p.on("queueEnd", p._autoplayHandler);
|
||||||
|
|
||||||
p._autoplayFillHandler = () => { fillQueue(p, ctx).catch(() => {}); };
|
p._autoplayFillHandler = () => { fillQueue(p, ctx).catch(() => {}); };
|
||||||
p.on("queue", p._autoplayFillHandler);
|
p.on("startplay", p._autoplayFillHandler);
|
||||||
p.on("update", p._autoplayFillHandler);
|
p.on("update", p._autoplayFillHandler);
|
||||||
p.on("playback", p._autoplayFillHandler);
|
p.on("playback", p._autoplayFillHandler);
|
||||||
}
|
}
|
||||||
@@ -232,7 +318,7 @@ function detachAutoplay(p) {
|
|||||||
p._autoplayHandler = null;
|
p._autoplayHandler = null;
|
||||||
}
|
}
|
||||||
if (p._autoplayFillHandler) {
|
if (p._autoplayFillHandler) {
|
||||||
p.removeListener("queue", p._autoplayFillHandler);
|
p.removeListener("startplay", p._autoplayFillHandler);
|
||||||
p.removeListener("update", p._autoplayFillHandler);
|
p.removeListener("update", p._autoplayFillHandler);
|
||||||
p.removeListener("playback", p._autoplayFillHandler);
|
p.removeListener("playback", p._autoplayFillHandler);
|
||||||
p._autoplayFillHandler = null;
|
p._autoplayFillHandler = null;
|
||||||
@@ -266,6 +352,9 @@ export async function run(msg, data) {
|
|||||||
} else {
|
} else {
|
||||||
detachAutoplay(p);
|
detachAutoplay(p);
|
||||||
p._autoplayHistory = [];
|
p._autoplayHistory = [];
|
||||||
|
p._autoplayMixPools?.clear();
|
||||||
|
p._autoplayPreferredPoolVid = null;
|
||||||
|
p._autoplayLastFillAt = 0;
|
||||||
|
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
|
|||||||
+15
-1
@@ -227,6 +227,8 @@ export async function run(msg) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let editFailures = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @private
|
* @private
|
||||||
* Rebuild and edit the player panel embed with updated state.
|
* Rebuild and edit the player panel embed with updated state.
|
||||||
@@ -235,7 +237,14 @@ export async function run(msg) {
|
|||||||
*/
|
*/
|
||||||
const refresh = (extra = {}) => {
|
const refresh = (extra = {}) => {
|
||||||
const embed = buildEmbed(extra);
|
const embed = buildEmbed(extra);
|
||||||
message.edit({ embeds: [embed] }).catch(() => {});
|
message.edit({ embeds: [embed] })
|
||||||
|
.then(() => { editFailures = 0; })
|
||||||
|
.catch(() => {
|
||||||
|
if (++editFailures >= 3) {
|
||||||
|
clearInterval(updateInterval);
|
||||||
|
updateInterval = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
lastState = extra;
|
lastState = extra;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -300,6 +309,11 @@ export async function run(msg) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
updateInterval = setInterval(() => {
|
updateInterval = setInterval(() => {
|
||||||
|
if (player._destroyed || player.leaving) {
|
||||||
|
clearInterval(updateInterval);
|
||||||
|
updateInterval = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!player.paused && player.queue.getCurrent()) {
|
if (!player.paused && player.queue.getCurrent()) {
|
||||||
refresh(lastState);
|
refresh(lastState);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ import { REQUIRED_BOT_PERMISSIONS } from "./MessageHandler.mjs";
|
|||||||
import { cleanId } from "./Utils.mjs";
|
import { cleanId } from "./Utils.mjs";
|
||||||
import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "./constants/VoiceStateResolver.mjs";
|
import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "./constants/VoiceStateResolver.mjs";
|
||||||
|
|
||||||
|
const RAW_GATEWAY_INTEREST =
|
||||||
|
/"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED)"|(?:7|9|10|12)\b)/;
|
||||||
|
|
||||||
/** @class GatewayHandler @description Handles all Discord gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. Key responsibilities include voice state cache seeding and updates, bot move-away detection with 24/7 rejoin scheduling, boot recovery with sequential rejoin of 24/7 channels, inactivity timer management on human join/leave, and guild create/delete handling with startup grace period. */
|
/** @class GatewayHandler @description Handles all Discord gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. Key responsibilities include voice state cache seeding and updates, bot move-away detection with 24/7 rejoin scheduling, boot recovery with sequential rejoin of 24/7 channels, inactivity timer management on human join/leave, and guild create/delete handling with startup grace period. */
|
||||||
export class GatewayHandler {
|
export class GatewayHandler {
|
||||||
/**
|
/**
|
||||||
@@ -366,6 +369,7 @@ export class GatewayHandler {
|
|||||||
if (wsObj && wsObj !== remix._rawGatewayWsObj) {
|
if (wsObj && wsObj !== remix._rawGatewayWsObj) {
|
||||||
remix._rawGatewayHandler = (data) => {
|
remix._rawGatewayHandler = (data) => {
|
||||||
try {
|
try {
|
||||||
|
if (typeof data === "string" && !RAW_GATEWAY_INTEREST.test(data)) return;
|
||||||
const payload = typeof data === "string" ? JSON.parse(data) : data;
|
const payload = typeof data === "string" ? JSON.parse(data) : data;
|
||||||
|
|
||||||
if (payload?.op === GatewayOpcodes.GatewayError || payload?.op === 12) {
|
if (payload?.op === GatewayOpcodes.GatewayError || payload?.op === 12) {
|
||||||
|
|||||||
@@ -211,6 +211,7 @@ export default class Player extends EventEmitter {
|
|||||||
super();
|
super();
|
||||||
|
|
||||||
this.queue = new Queue();
|
this.queue = new Queue();
|
||||||
|
this.queue.on("queue", (...args) => this.emit("queue", ...args));
|
||||||
this.client = opts.client;
|
this.client = opts.client;
|
||||||
this.config = opts.config ?? {};
|
this.config = opts.config ?? {};
|
||||||
this.settings = opts.settings ?? null;
|
this.settings = opts.settings ?? null;
|
||||||
|
|||||||
Reference in new issue
Block a user