feat(music): add inactivity watchdog warning, out-of-band radio titles

- add inactivity warning event and embed prompt before autoleave in Player & PlayerLifecycleMixin
- implement out-of-band ICY/Icecast metadata poller in RadioMetadata to track live radio titles without stream corruption
- wire live radio title updates into nowPlaying and announceSong in DisplayMixin and PlaybackMixin
This commit is contained in:
NoLogicAlan committed 2026-11-20 23:07:50 +03:00
1 parent e501fc62fb
commit a99e5bca37
13 files changed
+276 -17

No files matched your search

+34
View File
@@ -413,6 +413,40 @@ const PlayerLifecycleMixin = {
guildId: cleanId(channel.guildId ?? getMessageGuildId(message)),
});
player.on("inactivityWarning", ({ timeoutMs }) => {
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
const ch = player.textChannel;
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
const prefix = this.commands.getPrefix(guildId);
const minutes = Math.max(1, Math.round((timeoutMs || 180000) / 60000));
const autoleaveChMgr = this.commands?.client?.channels ?? null;
let targetCh = (ch && typeof ch === "object" && typeof ch.send !== "function" && ch.id &&
autoleaveChMgr && typeof autoleaveChMgr.send === "function")
? (() => { const t = { id: ch.id, type: ch.type }; t.send = (o) => autoleaveChMgr.send(ch.id, o); return t; })()
: ch;
if (typeof targetCh?.send === "function") {
const title = this.locale?.translate(guildId, "responses.join.inactivityWarningTitle") ?? "Leaving Voice Soon";
const desc = this.locale?.translate(guildId, "responses.join.inactivityWarningDesc", {
channel: activeChannelId,
minutes,
prefix,
}) ?? `Voice session is currently inactive. Disconnecting from <#${activeChannelId}> in **${minutes} minute(s)**.\n\nUse \`${prefix}247\` to keep me in voice 24/7!`;
const footer = this.locale?.translate(guildId, "responses.join.inactivityWarningFooter", { prefix }) ?? `Play a song with ${prefix}play to resume`;
const warnEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor({ name: this.locale?.translate(guildId, "responses.join.autoLeaveAuthor") ?? "⏱️ Voice Watchdog • Session Inactive" })
.setTitle(title)
.setDescription(desc)
.setFooter({ text: footer });
targetCh.send({ embeds: [warnEmbed], allowedMentions: { parse: [] } }).catch(err => {
if (err.code === "MISSING_PERMISSIONS" || err.statusCode === 403) {
logger.warn(`[PlayerManager] Cannot send inactivity warning message in channel ${targetCh.id} — missing permissions`);
}
});
}
});
player.on("autoleave", () => {
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
+138
View File
@@ -0,0 +1,138 @@
/**
* @module src/music/audio/RadioMetadata
* @description Out-of-band Shoutcast and Icecast metadata extractor.
* Polls stream headers and interleaved ICY metadata frames or Icecast status
* JSON out-of-band without corrupting or interfering with audio streaming.
*/
import http from "node:http";
import https from "node:https";
import { URL } from "node:url";
/**
* Extract live song title from Shoutcast/Icecast ICY metadata frames out-of-band.
* @param {string} url - Stream URL to probe.
* @param {number} [timeoutMs=6000] - Socket timeout in milliseconds.
* @returns {Promise<string|null>}
*/
export function fetchIcyStreamTitle(url, timeoutMs = 6000) {
return new Promise((resolve) => {
try {
const parsed = new URL(url);
const client = parsed.protocol === "https:" ? https : http;
const req = client.get(parsed, {
headers: {
"Icy-MetaData": "1",
"User-Agent": "FluxerBot/1.0 (Radio Title Poller)",
},
}, (res) => {
const metaint = parseInt(res.headers["icy-metaint"], 10);
if (!metaint || isNaN(metaint)) {
req.destroy();
return resolve(null);
}
let totalBytes = 0;
let metaLen = 0;
let metaBuffer = null;
let metaBytesRead = 0;
let state = 0;
res.on("data", (chunk) => {
let pos = 0;
while (pos < chunk.length) {
if (state === 0) {
const needed = metaint - totalBytes;
const available = chunk.length - pos;
if (available < needed) {
totalBytes += available;
pos = chunk.length;
} else {
pos += needed;
totalBytes = 0;
state = 1;
}
} else if (state === 1) {
metaLen = chunk[pos] * 16;
pos += 1;
if (metaLen === 0) {
state = 0;
} else {
metaBuffer = Buffer.alloc(metaLen);
metaBytesRead = 0;
state = 2;
}
} else if (state === 2) {
const needed = metaLen - metaBytesRead;
const available = chunk.length - pos;
const toCopy = Math.min(needed, available);
chunk.copy(metaBuffer, metaBytesRead, pos, pos + toCopy);
metaBytesRead += toCopy;
pos += toCopy;
if (metaBytesRead >= metaLen) {
const metaStr = metaBuffer.toString("utf8");
const match = metaStr.match(/StreamTitle='([^']*)'/i);
req.destroy();
return resolve(match && match[1] ? match[1].trim() : null);
}
}
}
});
res.on("error", () => {
try { req.destroy(); } catch (_) {}
resolve(null);
});
});
req.on("error", () => resolve(null));
req.setTimeout(timeoutMs, () => {
try { req.destroy(); } catch (_) {}
resolve(null);
});
} catch (_) {
resolve(null);
}
});
}
/**
* Fetch current track title from Icecast status-json.xsl endpoint.
* @param {string} streamUrl - Stream URL.
* @param {number} [timeoutMs=3000] - Request timeout.
* @returns {Promise<string|null>}
*/
export async function fetchIcecastJsonTitle(streamUrl, timeoutMs = 3000) {
try {
const parsed = new URL(streamUrl);
const jsonUrl = `${parsed.protocol}//${parsed.host}/status-json.xsl`;
const res = await fetch(jsonUrl, {
signal: AbortSignal.timeout(timeoutMs),
headers: { "User-Agent": "FluxerBot/1.0" },
});
if (!res.ok) return null;
const data = await res.json();
const sources = Array.isArray(data?.icestats?.source)
? data.icestats.source
: [data?.icestats?.source].filter(Boolean);
const mount = parsed.pathname;
const match = sources.find((s) => s.listenurl?.endsWith(mount) || s.server_name);
const raw = match?.title || match?.yp_currently_playing;
return raw && typeof raw === "string" ? raw.trim() : null;
} catch (_) {
return null;
}
}
/**
* Resolve radio stream title using out-of-band ICY frames with status-json fallback.
* @param {string} url - Stream URL.
* @param {number} [timeoutMs=6000] - Timeout.
* @returns {Promise<string|null>}
*/
export async function fetchRadioStreamTitle(url, timeoutMs = 6000) {
if (!url || typeof url !== "string") return null;
const icyTitle = await fetchIcyStreamTitle(url, timeoutMs);
if (icyTitle) return icyTitle;
return fetchIcecastJsonTitle(url, 3000);
}
+13 -8
View File
@@ -217,14 +217,18 @@ const DisplayMixin = {
let radioLiveTitle = null;
if (current.type === "radio") {
try {
const data = await meta(current.url);
radioLiveTitle = data?.title || null;
textMsg = `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n${current.description || ""}\n\n🎵 Now playing: ${radioLiveTitle || "Unknown"}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`;
} catch (_) {
/* Radio live metadata probe is optional — gracefully fall back to station display */
textMsg = `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`;
radioLiveTitle = current.currentStreamTitle || null;
if (!radioLiveTitle) {
try {
const data = await meta(current.url);
radioLiveTitle = data?.title || null;
} catch (_) {
/* Radio live metadata probe is optional — gracefully fall back to station display */
}
}
if (radioLiveTitle) current.currentStreamTitle = radioLiveTitle;
const titleLine = radioLiveTitle ? `\n\n🎵 Now playing: ${radioLiveTitle}` : "";
textMsg = `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n${current.description || ""}${titleLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`;
} else if (current.type === "external" || current.type === "stream" || current.type === "attachment") {
const totalMs = this._getTrackDurationMs(current);
const progressLine = totalMs > 0 ? `\n${this._createProgressBar(20)}` : "";
@@ -428,12 +432,13 @@ const DisplayMixin = {
const prefix = this._getPrefix?.(this._guildId) ?? "%";
if (s.type === "radio") {
const liveTitle = s.currentStreamTitle ? `🎶 **Now Playing:** ${s.currentStreamTitle}\n\n` : "";
const embed = new EmbedBuilder()
.setColor(0xe9196c)
.setAuthor({ name: `📻 ${this._t("responses.play.autoNowPlaying")}` })
.setTitle(Utils.truncate(s.title || this._t("responses.play.sourceRadio"), 250))
.setURL(s.author?.url || s.url || undefined)
.setDescription(`🎵 **${s.description || this._t("responses.play.liveBroadcast")}**\n\n🔊 <#${this._channelId}>`)
.setDescription(`${liveTitle}🎵 **${s.description || this._t("responses.play.liveBroadcast")}**\n\n🔊 <#${this._channelId}>`)
.setFooter({ text: this._t("responses.play.controlsHint", { prefix }) });
if (s.thumbnail) embed.setThumbnail(s.thumbnail);
this.emit("message", { embeds: [embed] });
+51 -1
View File
@@ -14,6 +14,7 @@ import { Utils, cleanId } from "../../utils/Utils.mjs";
import { isPlayerConnectionDead } from "../../utils/Helpers247.mjs";
import { logger } from "../../core/Logger.mjs";
import { getBilibiliStreamUrl } from "../bilibili/index.mjs";
import { fetchRadioStreamTitle } from "../audio/RadioMetadata.mjs";
/**
* @type {object}
@@ -33,6 +34,7 @@ const PlaybackMixin = {
this._clearTrackEndTimer();
if (songData.type === "radio") {
this._stopRadioTitlePolling();
logger.player(`[Player] Radio track ended: ${songData.title}`);
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
this.queue.current = null;
@@ -235,7 +237,10 @@ const PlaybackMixin = {
if (!dup) this.announceSong(songData);
else logger.player(`[Player:${this._guildId}] Suppressed duplicate now-playing for: ${songData.title}`);
this._lastAnnounce = { key: songData.url || songData.title, at: now };
if (songData.type === "radio") this._radioAnnounced = true;
if (songData.type === "radio") {
this._radioAnnounced = true;
this._startRadioTitlePolling(songData);
}
}
this._skipVotes.clear();
this.emit("startplay", songData);
@@ -508,6 +513,51 @@ const PlaybackMixin = {
}, 3_000).unref?.();
},
/**
* Start polling out-of-band ICY and Icecast metadata for live radio stations.
* Updates songData.currentStreamTitle when changed and triggers dashboard update.
* @param {object} songData
* @private
*/
_startRadioTitlePolling(songData) {
this._stopRadioTitlePolling();
if (!songData || songData.type !== "radio" || !songData.url) return;
const poll = async () => {
try {
const current = this.queue.getCurrent();
if (!current || current.type !== "radio" || current.url !== songData.url) {
this._stopRadioTitlePolling();
return;
}
const liveTitle = await fetchRadioStreamTitle(songData.url);
if (liveTitle && liveTitle !== current.currentStreamTitle) {
current.currentStreamTitle = liveTitle;
songData.currentStreamTitle = liveTitle;
logger.player(`[Player:${this._guildId}] Radio live title updated: ${liveTitle}`);
this.emit("radioTitleUpdate", { track: current, title: liveTitle });
this.dashboard?.playerUpdate?.({ type: "update" }, this);
}
} catch (e) {
logger.player(`[Player:${this._guildId}] Radio metadata poll error: ${e?.message}`);
}
};
poll();
this._radioPollInterval = setInterval(poll, 25_000);
},
/**
* Stop the active radio metadata polling timer.
* @private
*/
_stopRadioTitlePolling() {
if (this._radioPollInterval) {
clearInterval(this._radioPollInterval);
this._radioPollInterval = null;
}
},
/**
* @private Clear the track-end timer.
* @this {import('./Player.mjs').Player}
+8
View File
@@ -348,6 +348,10 @@ class Player extends EventEmitter {
}
logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`);
if (!this._inactivityWarned) {
this._inactivityWarned = true;
this.emit("inactivityWarning", { timeoutMs: this._inactivityLimit });
}
this._inactivityTimer = setTimeout(() => {
const currentMode = this._get247Mode();
if (currentMode === "on") {
@@ -370,6 +374,7 @@ class Player extends EventEmitter {
/** Clear the inactivity timer if running. */
_stopInactivityTimer() {
this._pendingInactivityCheck = false;
this._inactivityWarned = false;
if (this._inactivityTimer) {
logger.inactivity(`[Player] Stopping inactivity timer for guild ${this._guildId}`);
clearTimeout(this._inactivityTimer);
@@ -735,6 +740,8 @@ class Player extends EventEmitter {
if (this._stateHeartbeat) { clearInterval(this._stateHeartbeat); this._stateHeartbeat = null; }
this._clearTrackEndTimer();
this._stopRadioTitlePolling?.();
this._inactivityWarned = false;
this._activeTrackOpt = null;
try {
@@ -1087,6 +1094,7 @@ class Player extends EventEmitter {
_bridgeStop() {
this._playSessionGen = (this._playSessionGen ?? 0) + 1;
this._clearPrefetchTimer?.();
this._stopRadioTitlePolling?.();
if (this._audioBridge) {
try { this._audioBridge.stop(); } catch (_) {}
}