mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
rollback yes
This commit is contained in:
1 parent
73c290e59c
commit
f402237ad3
9 files changed
+506
-189
No files matched your search
+36
-6
@@ -26,6 +26,34 @@ function mkEmbed(desc) {
|
||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip NodeLink host, port, and password from a string so they are never
|
||||
* shown to end-users in Discord messages.
|
||||
* @param {string} msg
|
||||
* @param {Object} nl - The player's _nl config object { host, port, password }
|
||||
* @returns {string}
|
||||
*/
|
||||
function sanitizeError(msg, nl = {}) {
|
||||
if (!msg) return msg;
|
||||
let s = String(msg);
|
||||
const host = nl.host;
|
||||
const port = nl.port;
|
||||
const password = nl.password;
|
||||
if (host && host !== "localhost") {
|
||||
const escapedHost = host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
s = s.replace(new RegExp(`https?://${escapedHost}(:\\d+)?[^\\s"']*`, "gi"), "[internal]");
|
||||
if (port) s = s.replace(new RegExp(`${escapedHost}:${port}`, "g"), "[internal]");
|
||||
}
|
||||
if (port) {
|
||||
s = s.replace(new RegExp(`https?://localhost:${port}[^\\s"']*`, "gi"), "[internal]");
|
||||
}
|
||||
if (password && password !== "youshallnotpass") {
|
||||
const escapedPw = password.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
s = s.replace(new RegExp(escapedPw, "g"), "[redacted]");
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Queue Class
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
@@ -539,7 +567,7 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
if (res.statusCode !== 200 && res.statusCode !== 204) {
|
||||
res.resume();
|
||||
return reject(new Error(`HTTP ${res.statusCode} at NodeLink Server`));
|
||||
return reject(new Error(`HTTP ${res.statusCode} at ${target}`));
|
||||
}
|
||||
if (returnStream) return resolve(res);
|
||||
|
||||
@@ -547,11 +575,11 @@ export default class Player extends EventEmitter {
|
||||
res.on("data", d => chunks.push(d));
|
||||
res.on("end", () => {
|
||||
try { resolve(JSON.parse(Buffer.concat(chunks).toString())); }
|
||||
catch (e) { reject(new Error(`JSON parse error from NodeLink Server`)); }
|
||||
catch (e) { reject(new Error(`JSON parse error from ${target}`)); }
|
||||
});
|
||||
});
|
||||
|
||||
req.on("error", () => reject(new Error("Request error to NodeLink Server")));
|
||||
req.on("error", reject);
|
||||
req.setTimeout(options.timeout || 30_000, () => {
|
||||
req.destroy();
|
||||
reject(new Error("Request timeout"));
|
||||
@@ -694,7 +722,9 @@ export default class Player extends EventEmitter {
|
||||
return this._streamViaRevoice(json.url);
|
||||
} catch (err) {
|
||||
logger.error("[Player] NodeLink resolve error:", err.message);
|
||||
throw err;
|
||||
// Sanitize before re-throwing — this error eventually becomes a user-visible
|
||||
// "Error streaming X — skipping..." message, so the NodeLink URL must not appear.
|
||||
throw new Error(sanitizeError(err.message, this._nl));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1309,7 +1339,7 @@ export default class Player extends EventEmitter {
|
||||
|
||||
if (data.type === "error") {
|
||||
logger.worker("[Player] Worker returned error:", data.error);
|
||||
events.emit("message", data.error || "Failed to load track.");
|
||||
events.emit("message", sanitizeError(data.error, this._nl) || "Failed to load track.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1329,7 +1359,7 @@ export default class Player extends EventEmitter {
|
||||
})
|
||||
.catch((reason) => {
|
||||
logger.error("[Player] Worker job failed:", reason);
|
||||
events.emit("message", reason?.message || "An error occurred while loading the track.");
|
||||
events.emit("message", sanitizeError(reason?.message, this._nl) || "An error occurred while loading the track.");
|
||||
});
|
||||
return events;
|
||||
}
|
||||
|
||||
+53
-125
@@ -1,14 +1,18 @@
|
||||
/**
|
||||
* PlayerManager.mjs — Manages voice channel players across servers
|
||||
*
|
||||
* Updated for moonlink.js: passes the MoonlinkManager instance into every
|
||||
* new Player so it can resolve tracks and retrieve session IDs.
|
||||
*/
|
||||
|
||||
import Player from "./Player.mjs";
|
||||
import { CommandHandler } from "./CommandHandler.mjs";
|
||||
import { Message } from "./MessageHandler.mjs";
|
||||
import { SettingsManager } from "./Settings.mjs";
|
||||
import { Utils } from "./Utils.mjs";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "./MessageHandler.mjs";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
|
||||
/** Helper — build a plain embed payload from a description string */
|
||||
function mkEmbed(desc) {
|
||||
@@ -31,147 +35,58 @@ export class PlayerManager {
|
||||
/** @type {Object} */
|
||||
playerConfig;
|
||||
|
||||
/** @type {Map<string, Object>} */
|
||||
observedVoiceUsers = null;
|
||||
|
||||
/** @type {import('@fluxerjs/core').Client} */
|
||||
client = null;
|
||||
|
||||
/**
|
||||
* @param {SettingsManager} settings
|
||||
* @param {CommandHandler} commands
|
||||
* @param {Object} config
|
||||
* @param {Object} config.config - Parsed config.json
|
||||
* @param {Object} config.player - Config data passed to new Player instances
|
||||
*/
|
||||
constructor(settings, commands, config) {
|
||||
this.commands = commands;
|
||||
this.settings = settings;
|
||||
this.config = config.config;
|
||||
this.playerConfig = config.player;
|
||||
// Fix: Ensure we get the client from commands or config
|
||||
this.client = commands.client || config.player?.client || config.config?.client;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Voice Channel Detection
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Attempt to detect the voice channel a user is currently in.
|
||||
* Now async to support API fallback when cache is empty after reboot.
|
||||
* @param {Message} message
|
||||
* @returns {Promise<string|null>} Voice channel ID or null
|
||||
* @returns {string|null} Voice channel ID or null
|
||||
*/
|
||||
async checkVoiceChannels(message) {
|
||||
checkVoiceChannels(message) {
|
||||
if (!message) return null;
|
||||
|
||||
const userId = message.author?.id ?? message.message?.author?.id;
|
||||
const guildId = message.channel?.server_id ??
|
||||
const userId = message.author?.id;
|
||||
const serverId = message.channel?.server_id ??
|
||||
message.channel?.serverId ??
|
||||
message.channel?.guild?.id ??
|
||||
message.message?.server_id ??
|
||||
message.message?.serverId ??
|
||||
message.message?.guildId;
|
||||
message.message?.serverId;
|
||||
|
||||
if (!userId || !guildId) {
|
||||
logger.voiceState(`[checkVoiceChannels] Missing userId or guildId`);
|
||||
return null;
|
||||
}
|
||||
if (!userId) return null;
|
||||
|
||||
logger.voiceState(`[checkVoiceChannels] Checking for user ${userId} in guild ${guildId}`);
|
||||
|
||||
// Helper to seed observedVoiceUsers cache
|
||||
const seed = (channelId) => {
|
||||
if (!this.observedVoiceUsers) return channelId;
|
||||
if (!this.observedVoiceUsers.has(userId)) {
|
||||
this.observedVoiceUsers.set(userId, { channelId, guildId });
|
||||
logger.voiceState(`[checkVoiceChannels] Seeded cache: ${userId} -> ${channelId}`);
|
||||
}
|
||||
return this.observedVoiceUsers.get(userId)?.channelId ?? channelId;
|
||||
};
|
||||
|
||||
// 1. Check observedVoiceUsers cache first (populated by GuildCreate)
|
||||
if (this.observedVoiceUsers) {
|
||||
const observed = this.observedVoiceUsers.get(userId);
|
||||
if (observed && observed.guildId === guildId) {
|
||||
logger.voiceState(`[checkVoiceChannels] Found in cache: ${observed.channelId}`);
|
||||
return observed.channelId;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Try VoiceManager
|
||||
try {
|
||||
const vm = getVoiceManager(this.client);
|
||||
const channelId = vm?.getVoiceChannelId?.(guildId, userId);
|
||||
if (channelId) {
|
||||
logger.voiceState(`[checkVoiceChannels] Found via VoiceManager: ${channelId}`);
|
||||
return seed(channelId);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.voiceState(`[checkVoiceChannels] VoiceManager failed: ${e.message}`);
|
||||
}
|
||||
|
||||
// 3. Try message member voice (if available)
|
||||
const memberVoice =
|
||||
message?.member?.voice?.channelId ??
|
||||
message?.member?.voice?.channel?.id ??
|
||||
message?.message?.member?.voice?.channelId ??
|
||||
null;
|
||||
if (memberVoice) {
|
||||
logger.voiceState(`[checkVoiceChannels] Found via message.member.voice: ${memberVoice}`);
|
||||
return seed(memberVoice);
|
||||
}
|
||||
|
||||
// 4. Check guild voice states cache
|
||||
try {
|
||||
const guild = this.client?.guilds?.cache?.get(guildId);
|
||||
if (!guild) {
|
||||
logger.voiceState(`[checkVoiceChannels] Guild ${guildId} not in cache`);
|
||||
} else {
|
||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates?.cache ?? guild?.voiceStates ?? null;
|
||||
if (voiceStates) {
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.values(voiceStates);
|
||||
|
||||
logger.voiceState(`[checkVoiceChannels] Checking ${entries.length} voice states in cache`);
|
||||
|
||||
for (const state of entries) {
|
||||
const sid = state.userId ?? state.user_id ?? state.id;
|
||||
const sch = state.channelId ?? state.channel_id;
|
||||
const sgid = state.guildId ?? state.guild_id ?? guildId;
|
||||
if (sid === userId && sgid === guildId && sch) {
|
||||
logger.voiceState(`[checkVoiceChannels] Found in guild cache: ${sch}`);
|
||||
return seed(sch);
|
||||
}
|
||||
}
|
||||
// Fallback: find any existing player in this server
|
||||
if (serverId) {
|
||||
for (const [channelId] of this.playerMap) {
|
||||
const channel = this.commands.client?.channels?.get(channelId) ??
|
||||
this.commands.client?.channels?.cache?.get(channelId);
|
||||
if (channel?.guildId === serverId || channel?.server_id === serverId || channel?.serverId === serverId) {
|
||||
return channelId;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.voiceState(`[checkVoiceChannels] Guild cache check failed: ${e.message}`);
|
||||
}
|
||||
|
||||
// 5. CRITICAL FIX: Fetch fresh member data from API when cache misses
|
||||
try {
|
||||
const guild = this.client?.guilds?.cache?.get(guildId);
|
||||
if (guild?.members?.fetch) {
|
||||
logger.voiceState(`[checkVoiceChannels] Fetching member ${userId} from API...`);
|
||||
const member = await guild.members.fetch(userId);
|
||||
const voiceChannelId = member?.voice?.channelId ?? member?.voice?.channel?.id ?? null;
|
||||
if (voiceChannelId) {
|
||||
logger.voiceState(`[checkVoiceChannels] API returned voice channel: ${voiceChannelId}`);
|
||||
return seed(voiceChannelId);
|
||||
} else {
|
||||
logger.voiceState(`[checkVoiceChannels] API returned no voice channel for user`);
|
||||
}
|
||||
} else {
|
||||
logger.voiceState(`[checkVoiceChannels] Cannot fetch members - no fetch method`);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.voiceState(`[checkVoiceChannels] API fetch failed: ${err.message}`);
|
||||
}
|
||||
|
||||
logger.voiceState(`[checkVoiceChannels] Could not find voice channel for ${userId}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Player Retrieval
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Get or create a player for the user's voice channel.
|
||||
* @param {Message} message
|
||||
@@ -186,8 +101,7 @@ export class PlayerManager {
|
||||
message.message?.server_id ??
|
||||
message.message?.serverId;
|
||||
|
||||
// Added await here
|
||||
const userChannelId = await this.checkVoiceChannels(message);
|
||||
const userChannelId = this.checkVoiceChannels(message);
|
||||
|
||||
if (userChannelId) {
|
||||
const player = this.playerMap.get(userChannelId);
|
||||
@@ -209,9 +123,14 @@ export class PlayerManager {
|
||||
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
|
||||
|
||||
if (!userChannelId) {
|
||||
if (promptJoin) {
|
||||
message.replyEmbed(mkEmbed(`⚠️ Please join a voice channel to use this command.`));
|
||||
// verifyUser=false: allow controlling the bot without being in voice
|
||||
// (e.g. volume, clear, remove — admin-style controls).
|
||||
if (!verifyUser) {
|
||||
const first = serverPlayers[0];
|
||||
first[1].textChannel = message.channel;
|
||||
return first[1];
|
||||
}
|
||||
message.replyEmbed(mkEmbed(`⚠️ You need to join a voice channel to use this command.`));
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -233,19 +152,16 @@ export class PlayerManager {
|
||||
return this.settings.getServer(serverId)?.get("prefix") ?? "%";
|
||||
} catch (_) { return "%"; }
|
||||
})();
|
||||
if (promptJoin) {
|
||||
message.replyEmbed(mkEmbed(`⚠️ I'm already playing in ${channelList}. Join that channel or use \`${prefix}play\` to start music in your channel.`));
|
||||
}
|
||||
message.replyEmbed(mkEmbed(`⚠️ I'm already playing in ${channelList}. Join that channel or use \`${prefix}play\` to start music in your channel.`));
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!userChannelId) {
|
||||
if (shouldJoin) {
|
||||
// Auto-detect failed — fall back to interactive channel selection prompt
|
||||
return this.promptVC(message);
|
||||
}
|
||||
if (promptJoin) {
|
||||
message.replyEmbed(mkEmbed("⚠️ Please join a voice channel first."));
|
||||
}
|
||||
message.replyEmbed(mkEmbed("⚠️ Please join a voice channel first."));
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -258,13 +174,17 @@ export class PlayerManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Channel Selection Prompt
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Prompt the user to select a voice channel.
|
||||
* @param {Message} msg
|
||||
* @returns {Promise<Player|false>}
|
||||
* @returns {Promise<string|false>}
|
||||
*/
|
||||
async promptVC(msg) {
|
||||
const autoDetected = await this.checkVoiceChannels(msg);
|
||||
const autoDetected = this.checkVoiceChannels(msg);
|
||||
if (autoDetected) {
|
||||
return new Promise(resolve => this.initPlayer(msg, autoDetected, (p) => resolve(p)));
|
||||
}
|
||||
@@ -345,6 +265,10 @@ export class PlayerManager {
|
||||
});
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Leave
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Make the player leave its current voice channel.
|
||||
* @param {Message} msg
|
||||
@@ -372,6 +296,10 @@ export class PlayerManager {
|
||||
player.destroy();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Player Initialisation
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Create and register a new Player for the given voice channel.
|
||||
* @param {Message} message
|
||||
|
||||
+97
-7
@@ -1,5 +1,7 @@
|
||||
/**
|
||||
*
|
||||
* worker.mjs — NodeLink REST edition (moonlink.js session-aware)
|
||||
*
|
||||
*/
|
||||
|
||||
import { workerData, parentPort } from "worker_threads";
|
||||
@@ -10,13 +12,54 @@ import { Utils } from "./Utils.mjs";
|
||||
import { PROVIDERS } from "./constants/providers.mjs";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// NodeLink Configuration (forwarded from Player via workerData)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const nl = workerData?.data?.nodelink ?? {};
|
||||
const NL_HOST = nl.host ?? "localhost";
|
||||
const NL_PORT = nl.port ?? 3000;
|
||||
const NL_PASSWORD = nl.password ?? "youshallnotpass";
|
||||
const NL_SESSION_ID = nl.sessionId ?? null;
|
||||
const NL_SESSION_ID = nl.sessionId ?? null; // provided by moonlink.js Manager
|
||||
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
|
||||
|
||||
// ─── Error sanitizer ──────────────────────────────────────────────────────────
|
||||
// Strips the NodeLink host, port, and password from any string so they are
|
||||
// never shown to end-users in Discord messages. Called on every user-visible
|
||||
// error string before it is emitted or returned.
|
||||
function sanitizeError(msg) {
|
||||
if (!msg) return msg;
|
||||
let s = String(msg);
|
||||
// Remove full URLs containing the NodeLink host (http://host:port/...)
|
||||
if (NL_HOST && NL_HOST !== "localhost") {
|
||||
// Escape special regex chars in the host string
|
||||
const escapedHost = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
s = s.replace(new RegExp(`https?://${escapedHost}(:\\d+)?[^\\s"']*`, "gi"), "[internal]");
|
||||
}
|
||||
// Remove localhost:port combos
|
||||
s = s.replace(new RegExp(`https?://localhost:${NL_PORT}[^\\s"']*`, "gi"), "[internal]");
|
||||
// Remove bare host:port if it somehow appears without a protocol
|
||||
if (NL_HOST && NL_HOST !== "localhost") {
|
||||
const escapedHost = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
s = s.replace(new RegExp(`${escapedHost}:${NL_PORT}`, "g"), "[internal]");
|
||||
}
|
||||
// Remove the password just in case it ever leaks into an error message
|
||||
if (NL_PASSWORD && NL_PASSWORD !== "youshallnotpass") {
|
||||
const escapedPw = NL_PASSWORD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
s = s.replace(new RegExp(escapedPw, "g"), "[redacted]");
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HTTP Helper
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Make a GET request to NodeLink and return the parsed JSON body.
|
||||
* @param {string} path - API path (e.g. "/v4/loadtracks?identifier=…")
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
function nlGet(path) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const isHttps = NL_PORT === 443;
|
||||
@@ -45,7 +88,7 @@ function nlGet(path) {
|
||||
}
|
||||
);
|
||||
|
||||
req.on("error", () => reject(new Error("NodeLink connection failed.")));
|
||||
req.on("error", reject);
|
||||
req.setTimeout(30_000, () => {
|
||||
req.destroy();
|
||||
reject(new Error("NodeLink request timeout"));
|
||||
@@ -53,10 +96,24 @@ function nlGet(path) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Call NodeLink /v4/loadtracks.
|
||||
* @param {string} identifier
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
async function loadTracks(identifier) {
|
||||
return nlGet(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Track Conversion
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Convert a NodeLink track object to the internal video format.
|
||||
* @param {object} track
|
||||
* @returns {object|null}
|
||||
*/
|
||||
function trackToVideo(track) {
|
||||
if (!track || typeof track !== "object") return null;
|
||||
|
||||
@@ -68,7 +125,7 @@ function trackToVideo(track) {
|
||||
encoded: track.encoded ?? "",
|
||||
sourceName: info.sourceName ?? "unknown",
|
||||
title: Utils.cleanTitle(info.title ?? "Unknown"),
|
||||
url: info.uri ?? info.identifier ?? "",
|
||||
url: info.uri ?? `https://www.youtube.com/watch?v=${info.identifier}`,
|
||||
thumbnail: info.artworkUrl ?? null,
|
||||
spotifyUrl: null,
|
||||
duration: {
|
||||
@@ -83,8 +140,16 @@ function trackToVideo(track) {
|
||||
};
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Provider Configuration (imported from constants/providers.mjs)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const TYPE_MODIFIERS = ["track","playlist","album","artist","channel","user"];
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// YTUtils Class
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class YTUtils extends EventEmitter {
|
||||
constructor() { super(); }
|
||||
|
||||
@@ -102,21 +167,31 @@ class YTUtils extends EventEmitter {
|
||||
return `${prefix}:track:${query}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean YouTube Radio/Mix URLs to extract just the video
|
||||
* YouTube Radio URLs (list=RD...) often cause metadata mismatches
|
||||
*/
|
||||
_cleanYouTubeUrl(url) {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
|
||||
// Check if it's a YouTube Radio/Mix URL
|
||||
const list = urlObj.searchParams.get("list");
|
||||
if (list && list.startsWith("RD")) {
|
||||
// Extract just the video ID and create clean URL
|
||||
const videoId = urlObj.searchParams.get("v");
|
||||
if (videoId) {
|
||||
logger.worker(`[Worker] Cleaning YouTube Radio URL, extracted video: ${videoId}`);
|
||||
return `https://www.youtube.com/watch?v=${videoId}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove start_radio parameter if present
|
||||
if (urlObj.searchParams.has("start_radio")) {
|
||||
urlObj.searchParams.delete("start_radio");
|
||||
return urlObj.toString();
|
||||
}
|
||||
|
||||
return url;
|
||||
} catch (e) {
|
||||
return url;
|
||||
@@ -148,9 +223,11 @@ class YTUtils extends EventEmitter {
|
||||
}
|
||||
|
||||
async getVideoData(query, provider = "ytm") {
|
||||
// Handle URLs (including YouTube Radio/Mix)
|
||||
if (this.isValidUrl(query)) {
|
||||
this.emit("message", "Loading...");
|
||||
|
||||
// Clean YouTube Radio URLs to prevent metadata mismatches
|
||||
const cleanedUrl = this._cleanYouTubeUrl(query);
|
||||
if (cleanedUrl !== query) {
|
||||
logger.worker(`[Worker] URL cleaned: ${query} -> ${cleanedUrl}`);
|
||||
@@ -160,10 +237,11 @@ class YTUtils extends EventEmitter {
|
||||
try {
|
||||
data = await loadTracks(cleanedUrl);
|
||||
} catch (e) {
|
||||
this.emit("message", `**Failed to load: ${e.message}**`);
|
||||
return { type: "error", data: null, error: e.message };
|
||||
this.emit("message", `**Failed to load that track.**`);
|
||||
return { type: "error", data: null, error: sanitizeError(e.message) };
|
||||
}
|
||||
|
||||
// Handle playlist results
|
||||
if (data.loadType === "playlist") {
|
||||
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
|
||||
tracks.forEach(t => { t.playlistName = data.data?.info?.name ?? null; });
|
||||
@@ -171,32 +249,37 @@ class YTUtils extends EventEmitter {
|
||||
return { type: "list", data: tracks };
|
||||
}
|
||||
|
||||
// Handle single track
|
||||
if (data.loadType === "track") {
|
||||
const video = trackToVideo(data.data);
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
// Handle search results (take first)
|
||||
if (data.loadType === "search" && data.data?.length) {
|
||||
const video = trackToVideo(data.data[0]);
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
// No recognizable loadType
|
||||
this.emit("message", `**Could not load that URL.** (loadType: ${data.loadType || "unknown"})`);
|
||||
return { type: "error", data: null, error: "Unknown loadType: " + (data.loadType || "none") };
|
||||
}
|
||||
|
||||
// Handle search queries (non-URLs)
|
||||
this.emit("message", `Searching ${this._providerLabel(provider)}...`);
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await loadTracks(this._buildIdentifier(provider, query));
|
||||
} catch (e) {
|
||||
this.emit("message", `**Search failed: ${e.message}**`);
|
||||
return { type: "error", data: null, error: e.message };
|
||||
this.emit("message", `**Search failed. Please try again.**`);
|
||||
return { type: "error", data: null, error: sanitizeError(e.message) };
|
||||
}
|
||||
|
||||
// Handle search results
|
||||
if (data.loadType === "search" && data.data?.length) {
|
||||
const validTrack = data.data.find(track => {
|
||||
const info = track.info ?? {};
|
||||
@@ -212,6 +295,7 @@ class YTUtils extends EventEmitter {
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
// Handle playlist from search
|
||||
if (data.loadType === "playlist") {
|
||||
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
|
||||
if (tracks.length > 0) {
|
||||
@@ -220,17 +304,23 @@ class YTUtils extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// Single track from search
|
||||
if (data.loadType === "track") {
|
||||
const video = trackToVideo(data.data);
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
// Nothing found
|
||||
this.emit("message", `**No results found for '${query}'.**`);
|
||||
return { type: "error", data: null, error: "No results found" };
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Worker Entry Point
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const jobId = workerData?.jobId;
|
||||
const data = workerData?.data;
|
||||
|
||||
|
||||
Reference in new issue
Block a user