feat(music): support direct media playback from Fluxer attachments and uploaded files (#24)

- Add AttachmentUtils for detecting fluxerusercontent.com URLs and chat file attachments
- Support playing uploaded audio/video files directly via %play and %playnext
- Add Route 3d in-process ffmpeg decoding for container formats (.mp4, .mkv, .mov, etc.)
- Add native zero-re-encode passthrough for .opus, .webm, and .ogg attachments
- Add 📎 Fluxer Attachment source badges and embeds across all 6 locales
- Fixes #24
This commit is contained in:
NoLogicAlan committed 2026-10-29 03:08:20 +03:00
1 parent 91e7812c30
commit 7c5fb1e468
14 files changed
+300 -18

No files matched your search

+49 -1
View File
@@ -35,6 +35,7 @@ export class FluxerAudioBridge extends EventEmitter {
_endResolve = null;
_endReject = null;
_usedTrackstream = false;
_ffmpegProc = null;
/** @type {boolean} @description Whether audio is currently playing. */
get playing() { return this._playing; }
@@ -259,8 +260,51 @@ export class FluxerAudioBridge extends EventEmitter {
}
}
/* Route 3d: In-process FFmpeg decode fallback for MP4, AAC, MP3, WAV, and direct media */
try {
logger.player("[AudioBridge] Route 3d: Decoding direct media via in-process ffmpeg: " + trackInfo.url.substring(0, 80));
const { spawn } = await import("node:child_process");
const ffmpegArgs = [
"-reconnect", "1",
"-reconnect_streamed", "1",
"-reconnect_delay_max", "5",
"-i", trackInfo.url,
"-vn",
"-filter:a", "volume=1.0",
"-f", "s16le",
"-ar", "48000",
"-ac", "2",
"pipe:1"
];
const proc = spawn("ffmpeg", ffmpegArgs, { stdio: ["ignore", "pipe", "pipe"] });
this._ffmpegProc = proc;
proc.on("error", (err) => {
logger.warn("[AudioBridge] Route 3d FFmpeg process error: " + err.message);
});
proc.stderr.on("data", () => {
/* Drain stderr so ffmpeg does not block on full pipe buffer */
});
this._stream = this._buildPcmPipeline(proc.stdout);
await conn.play(this._stream);
if (generation !== this._playGeneration) return "stopped";
await this._awaitEnd(durationMs);
if (generation !== this._playGeneration) return "stopped";
if (this._playing && !this._stopped) {
this._playing = false;
logger.player("[AudioBridge] Track finished naturally (Route 3d in-process ffmpeg)");
return "finished";
}
return "stopped";
} catch (ffmpegErr) {
logger.warn("[AudioBridge] Route 3d ffmpeg playback failed: " + ffmpegErr?.message);
}
throw new Error(
"[AudioBridge] Direct stream is " + routed.kind + " (MP3/AAC/PCM?) — this format needs server-side decoding. " +
"[AudioBridge] Direct stream is " + routed.kind + " (MP3/AAC/PCM?) — this format needs server-side decoding or ffmpeg. " +
"Set audio.allowLoadstream to true in config.json (requires a NodeLink exposing /v4/loadstream), " +
"or play a WebM/Opus source."
);
@@ -637,6 +681,10 @@ export class FluxerAudioBridge extends EventEmitter {
if (this._sourceReq) {
try { this._sourceReq.destroy(); } catch (_) {}
}
if (this._ffmpegProc) {
try { this._ffmpegProc.kill("SIGKILL"); } catch (_) {}
this._ffmpegProc = null;
}
this._stream = null;
this._encoder = null;
this._sourceStream = null;
+5 -2
View File
@@ -73,7 +73,7 @@ const DisplayMixin = {
? `[Radio]: ${vid.title} - ${vid.author?.url || ""}`
: `[Radio] [${vid.title} by ${vid.author?.name || "Unknown"}](${vid.author?.url || ""})`;
}
if (vid.type === "external" || vid.type === "stream") {
if (vid.type === "external" || vid.type === "stream" || vid.type === "attachment") {
return code
? `${vid.title} - ${vid.url}`
: `[${vid.title}](${vid.url})`;
@@ -185,6 +185,9 @@ const DisplayMixin = {
if (current.type === "radio") {
sourceName = this._t("responses.play.sourceRadio");
sourceIcon = "📻";
} else if (current.type === "attachment" || current.url?.includes("fluxerusercontent.com") || current.url?.includes("cdn.fluxer.app")) {
sourceName = this._t("responses.play.sourceAttachment");
sourceIcon = "📎";
} else if (current.spotifyUrl || current.type === "spotify") {
sourceName = this._t("responses.play.sourceSpotify");
sourceIcon = "🟢";
@@ -222,7 +225,7 @@ const DisplayMixin = {
/* 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`;
}
} else if (current.type === "external" || current.type === "stream") {
} else if (current.type === "external" || current.type === "stream" || current.type === "attachment") {
const totalMs = this._getTrackDurationMs(current);
const progressLine = totalMs > 0 ? `\n${this._createProgressBar(20)}` : "";
textMsg = `${vcLine}🎵 **[${current.title}](${current.url})** by ${artistName}${progressLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`;
+1 -1
View File
@@ -336,7 +336,7 @@ const PlaybackMixin = {
bridgeUrl = stream.url;
}
if (!songData.encoded && bridgeUrl && bridgeUrl.startsWith("http") && this._lavalink && songData.type !== "external") {
if (!songData.encoded && bridgeUrl && bridgeUrl.startsWith("http") && this._lavalink && songData.type !== "external" && songData.type !== "attachment") {
try {
const nlInfo = this._lavalink.getNodeLinkInfo?.();
if (nlInfo) {
+7 -3
View File
@@ -13,6 +13,7 @@ import { Utils } from "../../utils/Utils.mjs";
import { logger } from "../../core/Logger.mjs";
import { PROVIDERS, PROVIDER_NAMES } from "../providers.mjs";
import { bilibiliEnabled, isBilibiliUrl, resolveBilibiliVideo } from "../bilibili/index.mjs";
import { isFluxerAttachmentUrl, extractMediaTitle } from "../../utils/AttachmentUtils.mjs";
/**
* Broad music genres are ambiguous when used by themselves: searching for
@@ -743,12 +744,15 @@ const SearchMixin = {
* @returns {object}
*/
_buildExternalTrack(url, title = null, artist = null, trackType = "external") {
const displayTitle = title || this._extractFilenameFromUrl(url);
const isAttachment = isFluxerAttachmentUrl(url);
const resolvedType = isAttachment ? "attachment" : trackType;
const displayTitle = title || (isAttachment ? extractMediaTitle(url) : this._extractFilenameFromUrl(url));
const displayArtist = artist || (isAttachment ? "Fluxer Attachment" : null);
return {
type: trackType,
type: resolvedType,
title: displayTitle,
url: url,
artist: artist || null,
artist: displayArtist,
thumbnail: null,
};
},
+2
View File
@@ -128,6 +128,8 @@ export class Message {
get authorId() { return this.message.author?.id; }
/** @returns {object|null} The guild member, if available. */
get member() { return this.message.member ?? null; }
/** @returns {Array|object} Raw attachments attached to this message. */
get attachments() { return this.message.attachments ?? []; }
/** @returns {Channel} The wrapped channel this message was sent in. */
get channel() { return this.handler.getChannel(this.message.channelId); }
+110
View File
@@ -0,0 +1,110 @@
/**
* @module src/utils/AttachmentUtils
* @description Utilities for detecting, inspecting, and extracting media from
* Fluxer attachments, uploaded message files, and direct fluxerusercontent.com URLs.
*/
/**
* Common media file extensions supported for direct streaming or decoding.
* Includes native zero-re-encode formats (WebM, Opus, OGG) and container formats (MP4, MP3, AAC, FLAC, WAV).
*/
export const MEDIA_EXTENSIONS = /\.(?:mp4|webm|mkv|mov|opus|ogg|mp3|m4a|aac|flac|wav|wma)(?:\?|$)/i;
/**
* Formats handled natively by FluxerAudioBridge without re-encoding (WebM/Opus, OGG/Opus).
*/
export const NATIVE_MEDIA_EXTENSIONS = /\.(?:opus|webm|ogg)(?:\?|$)/i;
/**
* Check if a URL originates from the official Fluxer user-content CDN.
* @param {string} str
* @returns {boolean}
*/
export function isFluxerAttachmentUrl(str) {
if (!str || typeof str !== "string") return false;
return /fluxerusercontent\.com\/attachments\//i.test(str) ||
/cdn\.fluxer\.app\/attachments\//i.test(str);
}
/**
* Check if a string is a direct playable media link (Fluxer attachment or audio/video extension).
* Excludes standard service hosts (YouTube, Spotify, etc.) which use search/catalog resolvers.
* @param {string} str
* @returns {boolean}
*/
export function isPlayableMediaUrl(str) {
if (!str || typeof str !== "string") return false;
const trimmed = str.trim();
if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return false;
if (isFluxerAttachmentUrl(trimmed)) return true;
return MEDIA_EXTENSIONS.test(trimmed);
}
/**
* Extract all attachments from a message or message wrapper.
* Safely handles arrays, Collections, Maps, and object dictionaries.
* @param {object} msg
* @returns {Array<object>}
*/
export function getMessageAttachments(msg) {
const raw = msg?.attachments ?? msg?.message?.attachments;
if (!raw) return [];
if (Array.isArray(raw)) return raw;
if (typeof raw.values === "function") return [...raw.values()];
if (typeof raw === "object") return Object.values(raw);
return [];
}
/**
* Find the first playable media attachment in a message.
* @param {object} msg
* @returns {{ url: string, filename: string, size: number, contentType: string }|null}
*/
export function getPlayableAttachment(msg) {
const list = getMessageAttachments(msg);
for (const att of list) {
if (!att || typeof att !== "object") continue;
const url = att.url || att.proxy_url || att.proxyUrl;
const filename = att.filename || att.name || "";
const contentType = att.content_type || att.contentType || "";
const isMedia = MEDIA_EXTENSIONS.test(filename) ||
MEDIA_EXTENSIONS.test(url) ||
contentType.startsWith("audio/") ||
contentType.startsWith("video/") ||
contentType === "application/ogg" ||
isFluxerAttachmentUrl(url);
if (url && isMedia) {
return {
url,
filename: filename || "Attachment",
size: Number(att.size ?? 0),
contentType,
};
}
}
return null;
}
/**
* Extract a clean, human-readable display title from a media URL or filename.
* Removes URL query parameters, directory paths, and file extensions.
* @param {string} urlOrFilename
* @param {string} [fallback="Attachment"]
* @returns {string}
*/
export function extractMediaTitle(urlOrFilename, fallback = "Attachment") {
if (!urlOrFilename || typeof urlOrFilename !== "string") return fallback;
try {
let clean = urlOrFilename;
if (clean.startsWith("http://") || clean.startsWith("https://")) {
clean = new URL(clean).pathname;
}
const filename = clean.split("/").pop();
if (filename && filename.includes(".")) {
const decoded = decodeURIComponent(filename.replace(/\.[^.]+$/, "").trim());
if (decoded) return decoded;
}
} catch (_) { }
return fallback;
}