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
+219
-52
No files matched your search
+11
-3
@@ -362,7 +362,8 @@ export async function run(msg) {
|
|||||||
if (!filter) return;
|
if (!filter) return;
|
||||||
|
|
||||||
const track = player.queue.getCurrent();
|
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({
|
await menuMsg.editEmbed({
|
||||||
embeds: [buildPageEmbed(page, activeKeys, null)]
|
embeds: [buildPageEmbed(page, activeKeys, null)]
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
@@ -401,9 +402,10 @@ export async function run(msg) {
|
|||||||
}
|
}
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
const { ok, reason } = await player.applyFilter(mergedPayload, meta);
|
const { ok, reason, pending } = await player.applyFilter(mergedPayload, meta);
|
||||||
|
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
|
activeKeys = previousActiveKeys;
|
||||||
const errEmbed = new EmbedBuilder()
|
const errEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(
|
.setDescription(
|
||||||
@@ -422,7 +424,13 @@ export async function run(msg) {
|
|||||||
// Update active key and refresh embed (player.activeFilter is already updated by applyFilter)
|
// Update active key and refresh embed (player.activeFilter is already updated by applyFilter)
|
||||||
activeKeys = meta ? meta.key.split("+") : [];
|
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."
|
? "🔇 Filters cleared — original audio restored."
|
||||||
: activeKeys.includes(filter.key)
|
: activeKeys.includes(filter.key)
|
||||||
? `${filter.emoji} **${filter.label}** applied!`
|
? `${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")
|
.setDescription("The search provider. Default: YouTube Music. Or use inline prefix: sp:, dz:, am:, yt:, sc: etc.", "options.play.provider")
|
||||||
.addFlagAliases("p", "u", "use")
|
.addFlagAliases("p", "u", "use")
|
||||||
.addChoices(...PROVIDER_CHOICES)
|
.addChoices(...PROVIDER_CHOICES)
|
||||||
.setDefault("yt")
|
.setDefault("ytm")
|
||||||
, true)
|
, true)
|
||||||
.addAlias("p");
|
.addAlias("p");
|
||||||
|
|
||||||
|
|||||||
+111
-26
@@ -75,6 +75,11 @@ function sanitizeError(msg, nl = {}) {
|
|||||||
return s;
|
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
|
// Queue Class
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
@@ -224,6 +229,7 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
// Active audio filter — { key, label, payload } or null
|
// Active audio filter — { key, label, payload } or null
|
||||||
activeFilter = null;
|
activeFilter = null;
|
||||||
|
activeFilterPayload = null;
|
||||||
|
|
||||||
// Inactivity timeout
|
// Inactivity timeout
|
||||||
_inactivityTimer = null;
|
_inactivityTimer = null;
|
||||||
@@ -626,13 +632,36 @@ export default class Player extends EventEmitter {
|
|||||||
}, true);
|
}, 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)
|
// Audio Streaming (revoice.js)
|
||||||
// ═══════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
async _streamViaRevoice(url) {
|
async _streamViaRevoice(url, options = {}) {
|
||||||
this._streamingStopped = false;
|
this._streamingStopped = false;
|
||||||
let audioStream = null;
|
let audioStream = null;
|
||||||
|
const currentTrack = this.queue.getCurrent();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
audioStream = await this._fetchStream(url);
|
audioStream = await this._fetchStream(url);
|
||||||
@@ -654,7 +683,10 @@ export default class Player extends EventEmitter {
|
|||||||
if (this._streamingStopped || this._skipping) return resolve();
|
if (this._streamingStopped || this._skipping) return resolve();
|
||||||
const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"];
|
const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"];
|
||||||
// Use substring matching so "Input stream error: aborted" (from NodeLink) is also caught
|
// 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);
|
reject(e);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -667,12 +699,16 @@ export default class Player extends EventEmitter {
|
|||||||
const ffMsg = err?.message ?? String(err);
|
const ffMsg = err?.message ?? String(err);
|
||||||
// "Input stream error: aborted" means NodeLink dropped the HTTP stream
|
// "Input stream error: aborted" means NodeLink dropped the HTTP stream
|
||||||
// (e.g. filter PATCH restarted the player before voice state arrived).
|
// (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")) {
|
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();
|
cleanup();
|
||||||
return resolve();
|
return resolve();
|
||||||
}
|
}
|
||||||
|
cleanup();
|
||||||
|
return reject(new Error(`FFmpeg stream ended early: ${ffMsg}`));
|
||||||
|
}
|
||||||
logger.error("[Player] FFmpeg error:", ffMsg);
|
logger.error("[Player] FFmpeg error:", ffMsg);
|
||||||
cleanup();
|
cleanup();
|
||||||
if (this._streamingStopped || this._skipping) return resolve();
|
if (this._streamingStopped || this._skipping) return resolve();
|
||||||
@@ -680,13 +716,25 @@ export default class Player extends EventEmitter {
|
|||||||
};
|
};
|
||||||
|
|
||||||
try {
|
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) {
|
if (this._mediaPlayer.fProc) {
|
||||||
this._mediaPlayer.fProc.once("error", onFfmpegError);
|
this._mediaPlayer.fProc.once("error", onFfmpegError);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
cleanup();
|
cleanup();
|
||||||
if (e.message?.includes("InvalidState") || e.message?.includes("capture frame")) {
|
if (isIgnorableMediaStateError(e)) {
|
||||||
logger.mediaplayer("[Player] Suppressed InvalidState during stream start");
|
logger.mediaplayer("[Player] Suppressed InvalidState during stream start");
|
||||||
return resolve();
|
return resolve();
|
||||||
}
|
}
|
||||||
@@ -710,10 +758,9 @@ export default class Player extends EventEmitter {
|
|||||||
clearTimeout(safetyTimer);
|
clearTimeout(safetyTimer);
|
||||||
if (this._mediaPlayer?.fProc) this._mediaPlayer.fProc.removeListener("error", onFfmpegError);
|
if (this._mediaPlayer?.fProc) this._mediaPlayer.fProc.removeListener("error", onFfmpegError);
|
||||||
cleanup();
|
cleanup();
|
||||||
if (e.message?.includes("InvalidState") || e.message?.includes("capture frame")) {
|
if (isIgnorableMediaStateError(e)) {
|
||||||
logger.mediaplayer("[Player] Suppressed InvalidState during playback");
|
logger.mediaplayer("[Player] Suppressed InvalidState during playback");
|
||||||
if (this._streamingStopped) return resolve();
|
return resolve();
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
if (this._streamingStopped) return resolve();
|
if (this._streamingStopped) return resolve();
|
||||||
reject(e);
|
reject(e);
|
||||||
@@ -725,7 +772,7 @@ export default class Player extends EventEmitter {
|
|||||||
try { audioStream.destroy(); } catch (_) {}
|
try { audioStream.destroy(); } catch (_) {}
|
||||||
}
|
}
|
||||||
this._currentPassthrough = null;
|
this._currentPassthrough = null;
|
||||||
if (e.message?.includes("InvalidState") || e.message?.includes("capture frame")) {
|
if (isIgnorableMediaStateError(e)) {
|
||||||
logger.mediaplayer("[Player] Suppressed InvalidState in stream setup");
|
logger.mediaplayer("[Player] Suppressed InvalidState in stream setup");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -736,10 +783,32 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
async _streamUrl(url) {
|
async _streamUrl(url) {
|
||||||
const isNodeLink = url.includes(`${this._nl.host}:${this._nl.port}`) ||
|
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 (!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 {
|
try {
|
||||||
const json = await this._request(url, {
|
const json = await this._request(url, {
|
||||||
headers: {
|
headers: {
|
||||||
@@ -846,14 +915,15 @@ export default class Player extends EventEmitter {
|
|||||||
connection.on("error", (err) => {
|
connection.on("error", (err) => {
|
||||||
const causeStr = err?.cause ? ` (Cause: ${err.cause})` : "";
|
const causeStr = err?.cause ? ` (Cause: ${err.cause})` : "";
|
||||||
logger.error("[Player] Voice error:", err?.message ?? err, causeStr);
|
logger.error("[Player] Voice error:", err?.message ?? err, causeStr);
|
||||||
this._cleanupMediaPlayer();
|
this._stopMediaPlayer().catch(() => {});
|
||||||
});
|
});
|
||||||
|
|
||||||
connection.on("disconnected", () => {
|
connection.on("disconnected", () => {
|
||||||
if (!this.leaving) {
|
if (!this.leaving) {
|
||||||
logger.mediaplayer("[Player] Unexpected disconnect detected");
|
logger.mediaplayer("[Player] Unexpected disconnect detected");
|
||||||
this._cleanupMediaPlayer();
|
this._stopMediaPlayer()
|
||||||
this._recoverConnection();
|
.catch(() => {})
|
||||||
|
.finally(() => this._recoverConnection());
|
||||||
} else {
|
} else {
|
||||||
try { connection.destroy(); } catch (_) {}
|
try { connection.destroy(); } catch (_) {}
|
||||||
}
|
}
|
||||||
@@ -1055,20 +1125,21 @@ export default class Player extends EventEmitter {
|
|||||||
return { ok: false, reason: "Player not bound to a guild." };
|
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;
|
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 { host, port } = this._nl;
|
||||||
|
|
||||||
const url = `http://${host}:${port}/v4/sessions/${liveSessionId}/players/${guildId}?noReplace=true`;
|
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.
|
// Send ONLY filters. With noReplace=true, NodeLink won't touch the track.
|
||||||
// Including track.encoded causes NodeLink to restart the Voice Worker,
|
// Including track.encoded causes NodeLink to restart the Voice Worker,
|
||||||
// which aborts the current stream and causes the "Input stream error: aborted" FFmpeg error.
|
// 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.activeFilter = meta ?? null;
|
||||||
|
this.activeFilterPayload = meta ? filterPayload : null;
|
||||||
this.emit("filter", this.activeFilter);
|
this.emit("filter", this.activeFilter);
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -1584,6 +1656,15 @@ export default class Player extends EventEmitter {
|
|||||||
return;
|
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) {
|
if (this._mediaPlayer && this.preferredVolume !== 1) {
|
||||||
this._mediaPlayer.setVolume(this.preferredVolume);
|
this._mediaPlayer.setVolume(this.preferredVolume);
|
||||||
}
|
}
|
||||||
@@ -1597,9 +1678,13 @@ export default class Player extends EventEmitter {
|
|||||||
streamUrl = songData.url;
|
streamUrl = songData.url;
|
||||||
} else if (songData.encoded) {
|
} else if (songData.encoded) {
|
||||||
const nlBase = `http://${this._nl.host}:${this._nl.port}`;
|
const nlBase = `http://${this._nl.host}:${this._nl.port}`;
|
||||||
const sessionParam = this._nl.sessionId ? `&sessionId=${encodeURIComponent(this._nl.sessionId)}` : "";
|
const positionMs = this.queue.songLoop ? 0 : Math.max(0, Date.now() - (this.startedPlaying ?? Date.now()));
|
||||||
const guildParam = this._guildId ? `&guildId=${this._guildId}` : "";
|
const filters = this.activeFilterPayload ?? {};
|
||||||
streamUrl = `${nlBase}/v4/trackstream?encodedTrack=${encodeURIComponent(songData.encoded)}${guildParam}${sessionParam}`;
|
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)) {
|
} else if (songData.url && Utils.isValidUrl(songData.url)) {
|
||||||
streamUrl = songData.url;
|
streamUrl = songData.url;
|
||||||
} else {
|
} else {
|
||||||
@@ -1639,7 +1724,7 @@ export default class Player extends EventEmitter {
|
|||||||
this.emit("startplay", songData);
|
this.emit("startplay", songData);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Utils.retry(() => this._streamUrl(streamUrl), 2, 1000);
|
await this._streamUrl(streamUrl);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error("[Player] Stream error:", err.message);
|
logger.error("[Player] Stream error:", err.message);
|
||||||
this._streamingStopped = true;
|
this._streamingStopped = true;
|
||||||
|
|||||||
+96
-22
@@ -160,6 +160,7 @@ class YTUtils extends EventEmitter {
|
|||||||
isValidUrl(str) { return Utils.isValidUrl(str); }
|
isValidUrl(str) { return Utils.isValidUrl(str); }
|
||||||
_prefix(p) { return PROVIDERS[p]?.prefix ?? "ytmsearch"; }
|
_prefix(p) { return PROVIDERS[p]?.prefix ?? "ytmsearch"; }
|
||||||
_providerLabel(p) { return PROVIDERS[p]?.label ?? "YouTube Music"; }
|
_providerLabel(p) { return PROVIDERS[p]?.label ?? "YouTube Music"; }
|
||||||
|
_isAudioPreferredProvider(p) { return p === "ytm"; }
|
||||||
|
|
||||||
_buildIdentifier(provider, query) {
|
_buildIdentifier(provider, query) {
|
||||||
const prefix = this._prefix(provider);
|
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") {
|
async getResults(query, limit = 5, provider = "ytm") {
|
||||||
const id = this.isValidUrl(query) ? query : this._buildIdentifier(provider, query);
|
const id = this.isValidUrl(query) ? query : this._buildIdentifier(provider, query);
|
||||||
const data = await loadTracks(id);
|
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 === "track") tracks = [data.data];
|
||||||
else if (data.loadType === "playlist") tracks = data.data?.tracks ?? [];
|
else if (data.loadType === "playlist") tracks = data.data?.tracks ?? [];
|
||||||
|
|
||||||
const validTracks = tracks.filter(track => {
|
const resultTracks = this._rankTracks(tracks, provider);
|
||||||
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;
|
|
||||||
return { data: resultTracks.slice(0, limit).map(trackToVideo) };
|
return { data: resultTracks.slice(0, limit).map(trackToVideo) };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,7 +343,8 @@ class YTUtils extends EventEmitter {
|
|||||||
|
|
||||||
// Handle search results (take first)
|
// Handle search results (take first)
|
||||||
if (data.loadType === "search" && data.data?.length) {
|
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.`);
|
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||||
return { type: "video", data: video };
|
return { type: "video", data: video };
|
||||||
}
|
}
|
||||||
@@ -285,15 +367,7 @@ class YTUtils extends EventEmitter {
|
|||||||
|
|
||||||
// Handle search results
|
// Handle search results
|
||||||
if (data.loadType === "search" && data.data?.length) {
|
if (data.loadType === "search" && data.data?.length) {
|
||||||
const validTrack = data.data.find(track => {
|
const trackToUse = this._pickBestTrack(data.data, provider) ?? data.data[0];
|
||||||
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 video = trackToVideo(trackToUse);
|
const video = trackToVideo(trackToUse);
|
||||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||||
return { type: "video", data: video };
|
return { type: "video", data: video };
|
||||||
|
|||||||
Reference in new issue
Block a user