mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
full test
This commit is contained in:
1 parent
3c938c5c32
commit
c330a7b605
4 files changed
+221
-54
No files matched your search
+11
-3
@@ -362,7 +362,8 @@ export async function run(msg) {
|
||||
if (!filter) return;
|
||||
|
||||
const track = player.queue.getCurrent();
|
||||
if (!track) {
|
||||
const previousActiveKeys = [...activeKeys];
|
||||
if (!track && false) { // pending filters are allowed; keep old fallback block unreachable
|
||||
await menuMsg.editEmbed({
|
||||
embeds: [buildPageEmbed(page, activeKeys, null)]
|
||||
}).catch(() => {});
|
||||
@@ -401,9 +402,10 @@ export async function run(msg) {
|
||||
}
|
||||
: null;
|
||||
|
||||
const { ok, reason } = await player.applyFilter(mergedPayload, meta);
|
||||
const { ok, reason, pending } = await player.applyFilter(mergedPayload, meta);
|
||||
|
||||
if (!ok) {
|
||||
activeKeys = previousActiveKeys;
|
||||
const errEmbed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription(
|
||||
@@ -422,7 +424,13 @@ export async function run(msg) {
|
||||
// Update active key and refresh embed (player.activeFilter is already updated by applyFilter)
|
||||
activeKeys = meta ? meta.key.split("+") : [];
|
||||
|
||||
const successMsg = filter.key === "off"
|
||||
const successMsg = pending
|
||||
? (filter.key === "off"
|
||||
? "Filter cleared. Original audio will be used on the next playable track."
|
||||
: activeKeys.includes(filter.key)
|
||||
? `${filter.label} saved. It will apply on the next playable track.`
|
||||
: `${filter.label} removed. The next playable track will use the updated filters.`)
|
||||
: filter.key === "off"
|
||||
? "🔇 Filters cleared — original audio restored."
|
||||
: activeKeys.includes(filter.key)
|
||||
? `${filter.emoji} **${filter.label}** applied!`
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ export const command = new CommandBuilder()
|
||||
.setDescription("The search provider. Default: YouTube Music. Or use inline prefix: sp:, dz:, am:, yt:, sc: etc.", "options.play.provider")
|
||||
.addFlagAliases("p", "u", "use")
|
||||
.addChoices(...PROVIDER_CHOICES)
|
||||
.setDefault("yt")
|
||||
.setDefault("ytm")
|
||||
, true)
|
||||
.addAlias("p");
|
||||
|
||||
|
||||
+112
-27
@@ -75,6 +75,11 @@ function sanitizeError(msg, nl = {}) {
|
||||
return s;
|
||||
}
|
||||
|
||||
function isIgnorableMediaStateError(err) {
|
||||
const msg = err?.message ?? String(err ?? "");
|
||||
return msg.includes("InvalidState") || msg.includes("failed to capture frame") || msg.includes("capture frame");
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Queue Class
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
@@ -224,6 +229,7 @@ export default class Player extends EventEmitter {
|
||||
|
||||
// Active audio filter — { key, label, payload } or null
|
||||
activeFilter = null;
|
||||
activeFilterPayload = null;
|
||||
|
||||
// Inactivity timeout
|
||||
_inactivityTimer = null;
|
||||
@@ -626,13 +632,36 @@ export default class Player extends EventEmitter {
|
||||
}, true);
|
||||
}
|
||||
|
||||
_getTrackDurationMs(track) {
|
||||
if (!track?.duration) return 0;
|
||||
if (typeof track.duration === "object" && track.duration?.seconds != null) {
|
||||
return track.duration.seconds * 1000;
|
||||
}
|
||||
if (typeof track.duration === "string" && track.duration.startsWith("PT")) {
|
||||
return Utils.parseISODuration(track.duration);
|
||||
}
|
||||
if (typeof track.duration === "number") return track.duration;
|
||||
return 0;
|
||||
}
|
||||
|
||||
_didTrackMostlyFinish(track) {
|
||||
const totalMs = this._getTrackDurationMs(track);
|
||||
if (!totalMs || !this.startedPlaying) return false;
|
||||
|
||||
const elapsedMs = Math.max(0, Date.now() - this.startedPlaying);
|
||||
const remainingMs = Math.max(0, totalMs - elapsedMs);
|
||||
|
||||
return elapsedMs / totalMs >= 0.85 || remainingMs <= 15_000;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Audio Streaming (revoice.js)
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
async _streamViaRevoice(url) {
|
||||
async _streamViaRevoice(url, options = {}) {
|
||||
this._streamingStopped = false;
|
||||
let audioStream = null;
|
||||
const currentTrack = this.queue.getCurrent();
|
||||
|
||||
try {
|
||||
audioStream = await this._fetchStream(url);
|
||||
@@ -654,7 +683,10 @@ export default class Player extends EventEmitter {
|
||||
if (this._streamingStopped || this._skipping) return resolve();
|
||||
const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"];
|
||||
// Use substring matching so "Input stream error: aborted" (from NodeLink) is also caught
|
||||
if (graceful.some(g => e.code === g || e.message?.includes(g))) return resolve();
|
||||
if (graceful.some(g => e.code === g || e.message?.includes(g))) {
|
||||
if (this._didTrackMostlyFinish(currentTrack)) return resolve();
|
||||
return reject(new Error(`Stream ended early for ${currentTrack?.title || "track"}: ${e.message ?? e.code ?? "stream aborted"}`));
|
||||
}
|
||||
reject(e);
|
||||
});
|
||||
|
||||
@@ -667,11 +699,15 @@ export default class Player extends EventEmitter {
|
||||
const ffMsg = err?.message ?? String(err);
|
||||
// "Input stream error: aborted" means NodeLink dropped the HTTP stream
|
||||
// (e.g. filter PATCH restarted the player before voice state arrived).
|
||||
// Treat it as graceful so the queue can advance normally.
|
||||
// Only treat it as graceful if the track was already close to ending.
|
||||
if (ffMsg.includes("aborted") || ffMsg.includes("Input stream error")) {
|
||||
logger.player("[Player] FFmpeg stream aborted gracefully (NodeLink stream closed)");
|
||||
if (this._didTrackMostlyFinish(currentTrack)) {
|
||||
logger.player("[Player] FFmpeg stream ended near track completion");
|
||||
cleanup();
|
||||
return resolve();
|
||||
}
|
||||
cleanup();
|
||||
return resolve();
|
||||
return reject(new Error(`FFmpeg stream ended early: ${ffMsg}`));
|
||||
}
|
||||
logger.error("[Player] FFmpeg error:", ffMsg);
|
||||
cleanup();
|
||||
@@ -680,13 +716,25 @@ export default class Player extends EventEmitter {
|
||||
};
|
||||
|
||||
try {
|
||||
this._mediaPlayer.playStream(audioStream);
|
||||
const playResult = this._mediaPlayer.playStream(audioStream, options);
|
||||
if (playResult && typeof playResult.catch === "function") {
|
||||
playResult.catch((e) => {
|
||||
if (isIgnorableMediaStateError(e) || this._streamingStopped || this._skipping || this.leaving) {
|
||||
logger.mediaplayer("[Player] Suppressed async playStream InvalidState rejection");
|
||||
cleanup();
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
cleanup();
|
||||
reject(e);
|
||||
});
|
||||
}
|
||||
if (this._mediaPlayer.fProc) {
|
||||
this._mediaPlayer.fProc.once("error", onFfmpegError);
|
||||
}
|
||||
} catch (e) {
|
||||
cleanup();
|
||||
if (e.message?.includes("InvalidState") || e.message?.includes("capture frame")) {
|
||||
if (isIgnorableMediaStateError(e)) {
|
||||
logger.mediaplayer("[Player] Suppressed InvalidState during stream start");
|
||||
return resolve();
|
||||
}
|
||||
@@ -710,10 +758,9 @@ export default class Player extends EventEmitter {
|
||||
clearTimeout(safetyTimer);
|
||||
if (this._mediaPlayer?.fProc) this._mediaPlayer.fProc.removeListener("error", onFfmpegError);
|
||||
cleanup();
|
||||
if (e.message?.includes("InvalidState") || e.message?.includes("capture frame")) {
|
||||
if (isIgnorableMediaStateError(e)) {
|
||||
logger.mediaplayer("[Player] Suppressed InvalidState during playback");
|
||||
if (this._streamingStopped) return resolve();
|
||||
return;
|
||||
return resolve();
|
||||
}
|
||||
if (this._streamingStopped) return resolve();
|
||||
reject(e);
|
||||
@@ -725,7 +772,7 @@ export default class Player extends EventEmitter {
|
||||
try { audioStream.destroy(); } catch (_) {}
|
||||
}
|
||||
this._currentPassthrough = null;
|
||||
if (e.message?.includes("InvalidState") || e.message?.includes("capture frame")) {
|
||||
if (isIgnorableMediaStateError(e)) {
|
||||
logger.mediaplayer("[Player] Suppressed InvalidState in stream setup");
|
||||
return;
|
||||
}
|
||||
@@ -736,10 +783,32 @@ export default class Player extends EventEmitter {
|
||||
|
||||
async _streamUrl(url) {
|
||||
const isNodeLink = url.includes(`${this._nl.host}:${this._nl.port}`) ||
|
||||
url.includes("/v4/trackstream");
|
||||
url.includes("/v4/trackstream") ||
|
||||
url.includes("/v4/loadstream");
|
||||
|
||||
if (!isNodeLink) return this._streamViaRevoice(url);
|
||||
|
||||
if (url.includes("/v4/loadstream")) {
|
||||
logger.player(`[Player] NodeLink loadStream PCM active`);
|
||||
try {
|
||||
return await this._streamViaRevoice(url, { rawPcm: true });
|
||||
} catch (err) {
|
||||
const msg = err?.message ?? String(err ?? "");
|
||||
// Fall back on any HTTP error (404, 500, etc) — NodeLink may return JSON error
|
||||
// bodies which would be played as PCM causing loud buzzing
|
||||
if (msg.includes("HTTP ")) {
|
||||
logger.warn(`[Player] NodeLink loadStream failed (${msg}), falling back to trackstream URL mode`);
|
||||
const parsed = new URL(url);
|
||||
const encodedTrack = parsed.searchParams.get("encodedTrack");
|
||||
if (!encodedTrack) throw err;
|
||||
const nlBase = `http://${this._nl.host}:${this._nl.port}`;
|
||||
const fallbackUrl = `${nlBase}/v4/trackstream?encodedTrack=${encodeURIComponent(encodedTrack)}`;
|
||||
return this._streamUrl(fallbackUrl);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const json = await this._request(url, {
|
||||
headers: {
|
||||
@@ -846,14 +915,15 @@ export default class Player extends EventEmitter {
|
||||
connection.on("error", (err) => {
|
||||
const causeStr = err?.cause ? ` (Cause: ${err.cause})` : "";
|
||||
logger.error("[Player] Voice error:", err?.message ?? err, causeStr);
|
||||
this._cleanupMediaPlayer();
|
||||
this._stopMediaPlayer().catch(() => {});
|
||||
});
|
||||
|
||||
connection.on("disconnected", () => {
|
||||
if (!this.leaving) {
|
||||
logger.mediaplayer("[Player] Unexpected disconnect detected");
|
||||
this._cleanupMediaPlayer();
|
||||
this._recoverConnection();
|
||||
this._stopMediaPlayer()
|
||||
.catch(() => {})
|
||||
.finally(() => this._recoverConnection());
|
||||
} else {
|
||||
try { connection.destroy(); } catch (_) {}
|
||||
}
|
||||
@@ -1055,20 +1125,21 @@ export default class Player extends EventEmitter {
|
||||
return { ok: false, reason: "Player not bound to a guild." };
|
||||
}
|
||||
|
||||
const current = this.queue.getCurrent();
|
||||
const liveSessionId = this._moonlink?.getLiveSessionId?.() ?? this._moonlink?.sessionId ?? this._nl.sessionId;
|
||||
if (!liveSessionId) {
|
||||
return { ok: false, reason: "No active NodeLink session. Try again in a few seconds." };
|
||||
|
||||
// Allow filters to be selected before a playable encoded track is active.
|
||||
// They will be applied automatically on the next track start.
|
||||
if (!liveSessionId || !current?.encoded) {
|
||||
this.activeFilter = meta ?? null;
|
||||
this.activeFilterPayload = meta ? filterPayload : null;
|
||||
this.emit("filter", this.activeFilter);
|
||||
return { ok: true, pending: true };
|
||||
}
|
||||
|
||||
const { host, port } = this._nl;
|
||||
|
||||
const url = `http://${host}:${port}/v4/sessions/${liveSessionId}/players/${guildId}?noReplace=true`;
|
||||
|
||||
const current = this.queue.getCurrent();
|
||||
if (!current?.encoded) {
|
||||
return { ok: false, reason: "No active track loaded. Start playback first." };
|
||||
}
|
||||
|
||||
// Send ONLY filters. With noReplace=true, NodeLink won't touch the track.
|
||||
// Including track.encoded causes NodeLink to restart the Voice Worker,
|
||||
// which aborts the current stream and causes the "Input stream error: aborted" FFmpeg error.
|
||||
@@ -1090,6 +1161,7 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
|
||||
this.activeFilter = meta ?? null;
|
||||
this.activeFilterPayload = meta ? filterPayload : null;
|
||||
this.emit("filter", this.activeFilter);
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
@@ -1584,6 +1656,15 @@ export default class Player extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
if (songData.encoded && this.activeFilter) {
|
||||
const { ok, pending, reason } = await this.applyFilter(this.activeFilterPayload ?? {}, this.activeFilter);
|
||||
if (!ok) {
|
||||
logger.warn(`[Player] Failed to apply active filter before playback: ${reason}`);
|
||||
} else if (!pending) {
|
||||
logger.mediaplayer(`[Player] Applied active filter before playback: ${this.activeFilter.label}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (this._mediaPlayer && this.preferredVolume !== 1) {
|
||||
this._mediaPlayer.setVolume(this.preferredVolume);
|
||||
}
|
||||
@@ -1597,9 +1678,13 @@ export default class Player extends EventEmitter {
|
||||
streamUrl = songData.url;
|
||||
} else if (songData.encoded) {
|
||||
const nlBase = `http://${this._nl.host}:${this._nl.port}`;
|
||||
const sessionParam = this._nl.sessionId ? `&sessionId=${encodeURIComponent(this._nl.sessionId)}` : "";
|
||||
const guildParam = this._guildId ? `&guildId=${this._guildId}` : "";
|
||||
streamUrl = `${nlBase}/v4/trackstream?encodedTrack=${encodeURIComponent(songData.encoded)}${guildParam}${sessionParam}`;
|
||||
const positionMs = this.queue.songLoop ? 0 : Math.max(0, Date.now() - (this.startedPlaying ?? Date.now()));
|
||||
const filters = this.activeFilterPayload ?? {};
|
||||
const filtersParam =
|
||||
Object.keys(filters).length > 0
|
||||
? `&filters=${encodeURIComponent(JSON.stringify(filters))}`
|
||||
: "";
|
||||
streamUrl = `${nlBase}/v4/loadstream?encodedTrack=${encodeURIComponent(songData.encoded)}&position=${positionMs}&volume=100${filtersParam}`;
|
||||
} else if (songData.url && Utils.isValidUrl(songData.url)) {
|
||||
streamUrl = songData.url;
|
||||
} else {
|
||||
@@ -1639,7 +1724,7 @@ export default class Player extends EventEmitter {
|
||||
this.emit("startplay", songData);
|
||||
|
||||
try {
|
||||
await Utils.retry(() => this._streamUrl(streamUrl), 2, 1000);
|
||||
await this._streamUrl(streamUrl);
|
||||
} catch (err) {
|
||||
logger.error("[Player] Stream error:", err.message);
|
||||
this._streamingStopped = true;
|
||||
|
||||
+97
-23
@@ -160,6 +160,7 @@ class YTUtils extends EventEmitter {
|
||||
isValidUrl(str) { return Utils.isValidUrl(str); }
|
||||
_prefix(p) { return PROVIDERS[p]?.prefix ?? "ytmsearch"; }
|
||||
_providerLabel(p) { return PROVIDERS[p]?.label ?? "YouTube Music"; }
|
||||
_isAudioPreferredProvider(p) { return p === "ytm"; }
|
||||
|
||||
_buildIdentifier(provider, query) {
|
||||
const prefix = this._prefix(provider);
|
||||
@@ -202,6 +203,97 @@ class YTUtils extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
_isPlayableTrack(track) {
|
||||
const info = track?.info ?? {};
|
||||
const uri = info.uri || "";
|
||||
if (uri.includes("/channel/")) return false;
|
||||
if (uri.includes("/c/") && !uri.includes("/watch")) return false;
|
||||
if (uri.includes("/playlist?")) return false;
|
||||
if (uri.includes("/user/")) return false;
|
||||
if (!info.length || info.length === 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
_scoreTrackForAudio(track, provider = "ytm") {
|
||||
if (!this._isPlayableTrack(track)) return Number.NEGATIVE_INFINITY;
|
||||
|
||||
if (!this._isAudioPreferredProvider(provider)) return 0;
|
||||
|
||||
const info = track?.info ?? {};
|
||||
const title = String(info.title ?? "").toLowerCase();
|
||||
const author = String(info.author ?? "").toLowerCase();
|
||||
const uri = String(info.uri ?? "").toLowerCase();
|
||||
const source = String(info.sourceName ?? "").toLowerCase();
|
||||
const text = `${title} ${author} ${uri} ${source}`;
|
||||
|
||||
let score = 0;
|
||||
|
||||
const positiveHints = [
|
||||
/\bofficial audio\b/,
|
||||
/\baudio\b/,
|
||||
/\bsong\b/,
|
||||
/\bprovided to youtube by\b/,
|
||||
/\btopic\b/,
|
||||
/\bart track\b/,
|
||||
/\blyrics?\b/,
|
||||
];
|
||||
|
||||
const negativeHints = [
|
||||
/\bofficial music video\b/,
|
||||
/\bmusic video\b/,
|
||||
/\bofficial video\b/,
|
||||
/\bvideo\b/,
|
||||
/\bmv\b/,
|
||||
/\bvisuali[sz]er\b/,
|
||||
/\blive\b/,
|
||||
/\bperformance\b/,
|
||||
/\bconcert\b/,
|
||||
/\bkaraoke\b/,
|
||||
/\bsped up\b/,
|
||||
/\bslowed\b/,
|
||||
/\breverb\b/,
|
||||
/\bnightcore\b/,
|
||||
/\b8d\b/,
|
||||
/\bremix\b/,
|
||||
/\bcover\b/,
|
||||
/\bfan cam\b/,
|
||||
];
|
||||
|
||||
for (const re of positiveHints) {
|
||||
if (re.test(text)) score += 3;
|
||||
}
|
||||
for (const re of negativeHints) {
|
||||
if (re.test(text)) score -= 4;
|
||||
}
|
||||
|
||||
if (author.endsWith(" - topic") || author.includes("topic")) score += 4;
|
||||
if (uri.includes("music.youtube.com")) score += 3;
|
||||
if (source === "youtube music") score += 3;
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
_pickBestTrack(tracks, provider = "ytm") {
|
||||
const playable = tracks.filter(track => this._isPlayableTrack(track));
|
||||
const candidates = playable.length > 0 ? playable : tracks;
|
||||
if (!candidates.length) return null;
|
||||
|
||||
return candidates
|
||||
.map((track, index) => ({ track, index, score: this._scoreTrackForAudio(track, provider) }))
|
||||
.sort((a, b) => b.score - a.score || a.index - b.index)[0]
|
||||
?.track ?? null;
|
||||
}
|
||||
|
||||
_rankTracks(tracks, provider = "ytm") {
|
||||
const playable = tracks.filter(track => this._isPlayableTrack(track));
|
||||
const candidates = playable.length > 0 ? playable : tracks;
|
||||
|
||||
return candidates
|
||||
.map((track, index) => ({ track, index, score: this._scoreTrackForAudio(track, provider) }))
|
||||
.sort((a, b) => b.score - a.score || a.index - b.index)
|
||||
.map(item => item.track);
|
||||
}
|
||||
|
||||
async getResults(query, limit = 5, provider = "ytm") {
|
||||
const id = this.isValidUrl(query) ? query : this._buildIdentifier(provider, query);
|
||||
const data = await loadTracks(id);
|
||||
@@ -211,18 +303,7 @@ class YTUtils extends EventEmitter {
|
||||
else if (data.loadType === "track") tracks = [data.data];
|
||||
else if (data.loadType === "playlist") tracks = data.data?.tracks ?? [];
|
||||
|
||||
const validTracks = tracks.filter(track => {
|
||||
const info = track.info ?? {};
|
||||
const uri = info.uri || "";
|
||||
if (uri.includes("/channel/")) return false;
|
||||
if (uri.includes("/c/") && !uri.includes("/watch")) return false;
|
||||
if (uri.includes("/playlist?")) return false;
|
||||
if (uri.includes("/user/")) return false;
|
||||
if (!info.length || info.length === 0) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const resultTracks = validTracks.length > 0 ? validTracks : tracks;
|
||||
const resultTracks = this._rankTracks(tracks, provider);
|
||||
return { data: resultTracks.slice(0, limit).map(trackToVideo) };
|
||||
}
|
||||
|
||||
@@ -262,7 +343,8 @@ class YTUtils extends EventEmitter {
|
||||
|
||||
// Handle search results (take first)
|
||||
if (data.loadType === "search" && data.data?.length) {
|
||||
const video = trackToVideo(data.data[0]);
|
||||
const bestTrack = this._pickBestTrack(data.data, provider) ?? data.data[0];
|
||||
const video = trackToVideo(bestTrack);
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
@@ -285,15 +367,7 @@ class YTUtils extends EventEmitter {
|
||||
|
||||
// Handle search results
|
||||
if (data.loadType === "search" && data.data?.length) {
|
||||
const validTrack = data.data.find(track => {
|
||||
const info = track.info ?? {};
|
||||
const uri = info.uri || "";
|
||||
if (uri.includes("/channel/")) return false;
|
||||
if (uri.includes("/c/") && !uri.includes("/watch")) return false;
|
||||
if (!info.length || info.length === 0) return false;
|
||||
return true;
|
||||
});
|
||||
const trackToUse = validTrack || data.data[0];
|
||||
const trackToUse = this._pickBestTrack(data.data, provider) ?? data.data[0];
|
||||
const video = trackToVideo(trackToUse);
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
@@ -386,4 +460,4 @@ utils.on("error", (m) => {
|
||||
} finally {
|
||||
process.exit(0);
|
||||
}
|
||||
})();
|
||||
})();
|
||||
Reference in new issue
Block a user