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

+41 -3
View File
@@ -12,6 +12,11 @@ import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mj
import { playLastFmCategory } from "./lastfm.mjs";
import { parseLastFmUrl, isLastFmUrl } from "../src/services/lastfm/LastFmManager.mjs";
import { ERROR_COLOR } from "../src/utils/UI.mjs";
import {
getPlayableAttachment,
isFluxerAttachmentUrl,
extractMediaTitle,
} from "../src/utils/AttachmentUtils.mjs";
const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
@@ -102,7 +107,7 @@ const KNOWN_SERVICE_HOSTS = /(?:youtu(?:be\.com|\.be)|youtube\.com|music\.youtub
const NATIVE_AUDIO_EXTENSIONS = /\.(?:opus|webm|ogg)(?:\?|$)/i;
/** Audio file extensions that indicate any direct audio URL (broader set). */
const AUDIO_EXTENSIONS = /\.(?:mp3|m4a|aac|ogg|opus|flac|wav|wma|webm|stream|m3u8|pls)(?:\?|$)/i;
const AUDIO_EXTENSIONS = /\.(?:mp3|m4a|aac|ogg|opus|flac|wav|wma|webm|mp4|mkv|mov|stream|m3u8|pls)(?:\?|$)/i;
/** Common stream/radio content-type paths or patterns. */
const STREAM_PATH_HINTS = /\/(?:stream|live|radio|audio|playlist|play|listen|mp3|aac|ogg)/i;
@@ -139,6 +144,7 @@ function isDirectAudioUrl(str) {
try {
const url = new URL(trimmed);
if (KNOWN_SERVICE_HOSTS.test(url.hostname)) return false;
if (isFluxerAttachmentUrl(trimmed)) return true;
if (AUDIO_EXTENSIONS.test(url.pathname)) return true;
if (STREAM_PATH_HINTS.test(url.pathname) && !url.pathname.includes(".html") && !url.pathname.includes(".php")) {
return true;
@@ -185,7 +191,7 @@ export const command = new CommandBuilder()
.addTextOption(option =>
option.setName("query")
.setDescription("A search query, music genre (for example `pop`), URL, or provider-prefixed query like `sp: song name`.", "options.play.query")
.setRequired(true)
.setRequired(false)
)
.addChoiceOption(o =>
o.setName("provider")
@@ -229,7 +235,39 @@ function forwardPlayMessage(d, statusMsg, message) {
* @returns {Promise<void>}
*/
export async function run(message, data) {
const rawQuery = data.get("query").value;
const attachment = getPlayableAttachment(message);
const rawQuery = data.get("query")?.value?.trim() || "";
/* Handle case where neither a query nor an attachment was supplied */
if (!rawQuery && !attachment) {
const noQueryEmbed = new EmbedBuilder()
.setColor(ERROR_COLOR)
.setAuthor({ name: this.t(message, "responses.play.noQueryTitle") })
.setDescription(this.t(message, "responses.play.noQueryDesc"))
.setFooter({ text: this.t(message, "responses.play.noQueryFooter") });
return message.reply({ embeds: [noQueryEmbed] });
}
/* Handle direct Fluxer user attachment or fluxerusercontent.com URL */
const isAttachment = Boolean(attachment) || isFluxerAttachmentUrl(rawQuery);
if (isAttachment) {
const mediaUrl = attachment ? attachment.url : rawQuery;
const cleanTitle = attachment ? extractMediaTitle(attachment.filename) : extractMediaTitle(rawQuery);
const p = await this.getPlayer(message, true, true, true);
if (!p) return;
const statusEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor({ name: this.t(message, "responses.play.streamPipelineAuthor") })
.setDescription(this.t(message, "responses.play.loadingAttachmentStream"));
let statusMsg = null;
try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
const messages = p.playExternal(mediaUrl, cleanTitle, "Fluxer Attachment", false, "attachment");
messages.on("message", d => forwardPlayMessage(d, statusMsg, message));
return;
}
const flagProvider = data.get("provider")?.value;
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
const provider = inlineProvider ?? flagProvider ?? "ytm";
+49 -2
View File
@@ -8,6 +8,12 @@ import { CommandBuilder } from "../src/commands/index.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/ui/index.mjs";
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs";
import { ERROR_COLOR } from "../src/utils/UI.mjs";
import {
getPlayableAttachment,
isFluxerAttachmentUrl,
extractMediaTitle,
} from "../src/utils/AttachmentUtils.mjs";
/**
@@ -27,7 +33,7 @@ export const command = new CommandBuilder()
.addTextOption(option =>
option.setName("query")
.setDescription("A search query, URL, or provider-prefixed query like `sp: song name`.", "options.playnext.query")
.setRequired(true)
.setRequired(false)
)
.addChoiceOption(o =>
o.setName("provider")
@@ -50,7 +56,48 @@ export async function run(message, data) {
const p = await this.getPlayer(message, true, true, true);
if (!p) return;
const rawQuery = data.get("query").value;
const attachment = getPlayableAttachment(message);
const rawQuery = data.get("query")?.value?.trim() || "";
/* Handle case where neither a query nor an attachment was supplied */
if (!rawQuery && !attachment) {
const noQueryEmbed = new EmbedBuilder()
.setColor(ERROR_COLOR)
.setAuthor({ name: this.t(message, "responses.play.noQueryTitle") })
.setDescription(this.t(message, "responses.play.noQueryDesc"))
.setFooter({ text: this.t(message, "responses.play.noQueryFooter") });
return message.reply({ embeds: [noQueryEmbed] });
}
/* Handle direct Fluxer user attachment or fluxerusercontent.com URL */
const isAttachment = Boolean(attachment) || isFluxerAttachmentUrl(rawQuery);
if (isAttachment) {
const mediaUrl = attachment ? attachment.url : rawQuery;
const cleanTitle = attachment ? extractMediaTitle(attachment.filename) : extractMediaTitle(rawQuery);
const statusEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor({ name: this.t(message, "responses.playnext.playingNext") })
.setDescription(this.t(message, "responses.play.loadingAttachmentStream"));
let statusMsg = null;
try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch (_) {}
const messages = p.playExternal(mediaUrl, cleanTitle, "Fluxer Attachment", true, "attachment");
messages.on("message", d => {
let embed;
if (d instanceof EmbedBuilder) {
embed = d;
} else if (d?.embeds?.[0]) {
embed = d.embeds[0];
} else {
embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(String(d));
}
embed.setAuthor({ name: this.t(message, "responses.playnext.playingNext") });
if (statusMsg) statusMsg.edit({ embeds: [embed] }).catch(() => {});
});
return;
}
const flagProvider = data.get("provider")?.value;
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
const provider = inlineProvider ?? flagProvider ?? "ytm";
+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;
}
+6 -1
View File
@@ -540,7 +540,12 @@
"loadingDirectStream": "🔎 جاري تحميل البث المباشر...",
"resolvingLavalinkStream": "🔎 جاري حل البث عبر Lavalink...",
"lastfmPlaybackAuthor": "🎵 تشغيل Last.fm",
"lastfmSearchAuthor": "🔎 بحث Last.fm"
"lastfmSearchAuthor": "🔎 بحث Last.fm",
"loadingAttachmentStream": "جارٍ تحميل مرفق وسائط Fluxer...",
"sourceAttachment": "مرفق Fluxer",
"noQueryTitle": "الأغنية أو المرفق مطلوب",
"noQueryDesc": "يرجى تقديم استعلام بحث أو رابط وسائط مباشر أو تحميل ملف صوت/فيديو مع هذا الأمر.",
"noQueryFooter": "مشغّل الموسيقى • دعم المرفقات المباشرة"
},
"playnext": {
"searching": "🔍 جارٍ البحث...",
+6 -1
View File
@@ -540,7 +540,12 @@
"loadingDirectStream": "🔎 بارکردنی پەخشی ڕاستەوخۆ...",
"resolvingLavalinkStream": "🔎 شیکارکردنی پەخش لە ڕێگەی Lavalink...",
"lastfmPlaybackAuthor": "🎵 لێدانی Last.fm",
"lastfmSearchAuthor": "🔎 گەڕانی Last.fm"
"lastfmSearchAuthor": "🔎 گەڕانی Last.fm",
"loadingAttachmentStream": "بارکردنی هاوپێچی میدیای Fluxer...",
"sourceAttachment": "هاوپێچی Fluxer",
"noQueryTitle": "گۆرانی یان هاوپێچ پێویستە",
"noQueryDesc": "تکایە گەڕانێک بنووسە، یان بەستەرێکی ڕاستەوخۆی میدیا یان فایلێکی دەنگ/ڤیدیۆ باربکە لەگەڵ ئەم فەرمانەدا.",
"noQueryFooter": "لێدەری مۆسیقا • پشتگیری هاوپێچی ڕاستەوخۆ"
},
"playnext": {
"searching": "🔍 گەڕان...",
+6 -1
View File
@@ -540,7 +540,12 @@
"loadingDirectStream": "🔎 Direkter Stream wird geladen...",
"resolvingLavalinkStream": "🔎 Stream wird über Lavalink aufgelöst...",
"lastfmPlaybackAuthor": "🎵 Last.fm-Wiedergabe",
"lastfmSearchAuthor": "🔎 Last.fm-Suche"
"lastfmSearchAuthor": "🔎 Last.fm-Suche",
"loadingAttachmentStream": "Lade Fluxer-Medienanhang...",
"sourceAttachment": "Fluxer-Anhang",
"noQueryTitle": "Titel oder Anhang erforderlich",
"noQueryDesc": "Bitte gib einen Suchbegriff oder direkten Medienlink an oder lade eine Audio-/Videodatei mit diesem Befehl hoch.",
"noQueryFooter": "Musikplayer • Direkte Anhangsunterstützung"
},
"playnext": {
"searching": "🔍 Suche...",
+6 -1
View File
@@ -755,7 +755,12 @@
"loadingDirectStream": "🔎 Loading direct stream...",
"resolvingLavalinkStream": "🔎 Resolving stream via Lavalink...",
"lastfmPlaybackAuthor": "🎵 Last.fm Playback",
"lastfmSearchAuthor": "🔎 Last.fm Search"
"lastfmSearchAuthor": "🔎 Last.fm Search",
"loadingAttachmentStream": "Loading Fluxer media attachment...",
"sourceAttachment": "Fluxer Attachment",
"noQueryTitle": "Song or Attachment Required",
"noQueryDesc": "Please provide a search query, a direct media link, or upload an audio/video file with this command.",
"noQueryFooter": "Music Player • Direct Attachment Support"
},
"playnext": {
"searching": "🔍 Searching...",
+6 -1
View File
@@ -540,7 +540,12 @@
"loadingDirectStream": "🔎 Carregando transmissão direta...",
"resolvingLavalinkStream": "🔎 Resolvendo fluxo via Lavalink...",
"lastfmPlaybackAuthor": "🎵 Reprodução do Last.fm",
"lastfmSearchAuthor": "🔎 Pesquisa no Last.fm"
"lastfmSearchAuthor": "🔎 Pesquisa no Last.fm",
"loadingAttachmentStream": "Carregando anexo de mídia do Fluxer...",
"sourceAttachment": "Anexo do Fluxer",
"noQueryTitle": "Música ou Anexo Obrigatório",
"noQueryDesc": "Por favor, forneça um termo de pesquisa, um link direto de mídia ou envie um arquivo de áudio/vídeo com este comando.",
"noQueryFooter": "Reprodutor de Música • Suporte a Anexos Diretos"
},
"playnext": {
"searching": "🔍 Buscando...",
+6 -1
View File
@@ -744,7 +744,12 @@
"loadingDirectStream": "🔎 Doğrudan akış yükleniyor...",
"resolvingLavalinkStream": "🔎 Lavalink üzerinden akış çözülüyor...",
"lastfmPlaybackAuthor": "🎵 Last.fm Çalma",
"lastfmSearchAuthor": "🔎 Last.fm Arama"
"lastfmSearchAuthor": "🔎 Last.fm Arama",
"loadingAttachmentStream": "Fluxer medya eki yükleniyor...",
"sourceAttachment": "Fluxer Eki",
"noQueryTitle": "Şarkı veya Ek Gerekli",
"noQueryDesc": "Lütfen bir arama sorgusu, doğrudan medya bağlantısı girin veya bu komutla bir ses/video dosyası yükleyin.",
"noQueryFooter": "Müzik Çalar • Doğrudan Ek Desteği"
},
"playnext": {
"searching": "🔍 Aranıyor...",