Add seek validation, autoplay system, progress bar & codebase cleanup

- Add seek duration validation — seeks beyond track length are rejected
  with clear error showing max allowed position
- Add autoplay system with Last.fm similar tracks + YouTube search
  fallback — automatically queues similar tracks when queue ends
- Add live progress bar to now playing with elapsed/total time display
- Add robust ffmpeg cleanup to prevent race conditions during
  seek/skip/filter operations
- Add proper queue advancement after seek so bot stays in voice
- Add queueEnd event emission on skip/skipTo for autoplay trigger
- Add _lastPlayedTrack preservation for autoplay recommendations
This commit is contained in:
NoLogicAlan committed 2026-05-21 02:04:05 +03:00
1 parent bc1fe82919
commit 0f2ee99f1e
23 files changed
+665 -170

No files matched your search

+8 -2
View File
@@ -64,7 +64,10 @@ We believe music features shouldn't be locked behind paywalls — **all commands
- **Interactive emoji player** — reaction-based control panel with play, pause, skip, volume, shuffle, and more - **Interactive emoji player** — reaction-based control panel with play, pause, skip, volume, shuffle, and more
- **Lyrics** — fetch synced lyrics via NodeLink - **Lyrics** — fetch synced lyrics via NodeLink
- **Radio stations** — built-in support for custom radio streams with keyword-based search - **Radio stations** — built-in support for custom radio streams with keyword-based search
- **Last.fm integration** — auto-scrobble songs, play loved/top/recent tracks, and view your Last.fm profile - **Last.fm integration** — auto-scrobble songs, play loved/top/recent tracks, love/unlove tracks, view top artists, and view your Last.fm profile
- **Autoplay** — automatically play similar tracks when the queue ends (powered by Last.fm)
- **Seek** — jump to a specific position in the current track
- **Queue move** — reorder tracks by moving them to a different position
- **Server settings** — per-guild configuration for prefix, volume, locale, 24/7 channels, and more - **Server settings** — per-guild configuration for prefix, volume, locale, 24/7 channels, and more
- **Web dashboard** — optional browser-based control panel with Redis-backed sessions and Fluxer OAuth2 login - **Web dashboard** — optional browser-based control panel with Redis-backed sessions and Fluxer OAuth2 login
- **Multi-language support** — available in English, Arabic, German, Kurdish (Sorani), and Brazilian Portuguese - **Multi-language support** — available in English, Arabic, German, Kurdish (Sorani), and Brazilian Portuguese
@@ -114,6 +117,9 @@ Below is the complete list of Remix's commands. The default prefix is `%`.
| `join` | Make the bot join a specific voice channel | `%join 123456789` | | | `join` | Make the bot join a specific voice channel | `%join 123456789` | |
| `leave` | Make the bot leave the current voice channel | `%leave` | `l`, `stop` | | `leave` | Make the bot leave the current voice channel | `%leave` | `l`, `stop` |
| `forceleave` | Force the bot to leave any channel (requires Manage Channels) | `%forceleave` | `fl` | | `forceleave` | Force the bot to leave any channel (requires Manage Channels) | `%forceleave` | `fl` |
| `seek` | Seek to a specific position in the current track | `%seek 1:30` / `%seek 90` | |
| `move` | Move a track from one position to another in the queue | `%move 2 5` | `mv`, `m` |
| `autoplay` | Toggle autoplay — automatically play similar tracks when queue ends | `%autoplay` | `ap` |
### Utility ### Utility
@@ -123,7 +129,7 @@ Below is the complete list of Remix's commands. The default prefix is `%`.
| `stats` | Display bot stats (uptime, ping, player count, stored scrobbles) | `%stats` | `info` | | `stats` | Display bot stats (uptime, ping, player count, stored scrobbles) | `%stats` | `info` |
| `invite` | Get the bot invite link | `%invite` | `addbot`, `remix` | | `invite` | Get the bot invite link | `%invite` | `addbot`, `remix` |
| `support` | Get an invite to the support server | `%support` | `server` | | `support` | Get an invite to the support server | `%support` | `server` |
| `lastfm` | Link Last.fm, toggle scrobbling, view profile, play tracks, leaderboard | `%lastfm link` / `%lastfm play loved` / `%lastfm lb` | `lf`, `lfm` | | `lastfm` | Link Last.fm, toggle scrobbling, view profile, love/unlove tracks, top artists, play tracks, leaderboard | `%lastfm link` / `%lastfm love` / `%lastfm artists` / `%lastfm lb` | `lf`, `lfm` |
| `reload` | Reload commands or modules at runtime (owner) | `%reload` | | | `reload` | Reload commands or modules at runtime (owner) | `%reload` | |
| `servers` | List servers the bot is in (owner) | `%servers` | | | `servers` | List servers the bot is in (owner) | `%servers` | |
| `eval` | Evaluate JavaScript (owner only) | `%eval 1+1` | | | `eval` | Evaluate JavaScript (owner only) | `%eval 1+1` | |
+111
View File
@@ -0,0 +1,111 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("autoplay")
.setDescription("Toggle autoplay — automatically play similar tracks when the queue ends.", "commands.autoplay")
.setCategory("music")
.addAliases("ap");
export async function run(msg, data) {
const prefix = this.handler?.getPrefix?.(msg.message?.guildId) ?? "%";
const p = await this.getPlayer(msg, true, true, false);
if (!p) return;
p._autoplay = !p._autoplay;
if (p._autoplay) {
if (!p._autoplayHandler) {
p._autoplayHandler = async () => {
if (!p._autoplay) return;
if (p.queue?.getCurrent() || !p.queue?.isEmpty()) return;
const lastTrack = p._lastPlayedTrack;
if (!lastTrack) return;
const artist = lastTrack.lastfm?.artist ?? lastTrack.requestedArtist ?? lastTrack.artist ?? lastTrack.artists?.[0]?.name;
const name = lastTrack.lastfm?.name ?? lastTrack.requestedTitle ?? lastTrack.title ?? lastTrack.name;
try {
p._stopInactivityTimer();
let query = null;
const lf = this.lastfm;
if (lf?.enabled && artist && name) {
try {
const similar = await lf.getSimilarTracks(artist, name, 5);
if (similar.length) {
const pick = similar[Math.floor(Math.random() * Math.min(3, similar.length))];
query = `${pick.name} ${pick.artist}`.trim();
}
} catch (_) {
}
}
if (!query) {
if (artist && name) {
query = `${artist} music`;
} else if (name) {
query = `${name} similar`;
} else {
if (!p._is247Enabled()) {
p._startInactivityTimer();
}
return;
}
}
const resolved = await p.workerJob("generalQuery", {
query,
provider: "yt",
});
let track = null;
if (resolved?.type === "video" && resolved.data) {
track = resolved.data;
} else if (resolved?.type === "list" && resolved.data?.length) {
const idx = Math.floor(Math.random() * Math.min(5, resolved.data.length));
track = resolved.data[idx];
}
if (track) {
p.addToQueue(track, false);
if (!p.queue.getCurrent()) {
p.playNext().catch(() => {});
}
} else {
if (!p._is247Enabled()) {
p._startInactivityTimer();
}
}
} catch (err) {
if (!p.queue?.getCurrent() && p.queue?.isEmpty() && !p._is247Enabled()) {
p._startInactivityTimer();
}
}
};
p.on("queueEnd", p._autoplayHandler);
}
const lfStatus = this.lastfm?.enabled ? " with Last.fm recommendations" : " using YouTube search";
return msg.reply({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(`🔁 Autoplay **enabled**${lfStatus} — similar tracks will be added automatically when the queue ends.`)]
});
} else {
if (p._autoplayHandler) {
p.removeListener("queueEnd", p._autoplayHandler);
p._autoplayHandler = null;
}
return msg.reply({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(`➡️ Autoplay **disabled** — the bot will stop when the queue ends.`)]
});
}
}
-16
View File
@@ -368,23 +368,7 @@ export async function run(msg) {
const filter = FILTERS.find(f => f.emoji === emoji); const filter = FILTERS.find(f => f.emoji === emoji);
if (!filter) return; if (!filter) return;
const track = player.queue.getCurrent();
const previousActiveKeys = [...activeKeys]; const previousActiveKeys = [...activeKeys];
if (!track && false) {
await menuMsg.edit({
embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)]
}).catch(() => {});
const errEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(this.t(msg, "responses.filter.nothingPlaying"))
;
await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {});
await Utils.sleep(1000);
await menuMsg.edit({
embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)]
}).catch(() => {});
return;
}
if (filter.key === "off") { if (filter.key === "off") {
activeKeys = []; activeKeys = [];
+98 -5
View File
@@ -14,7 +14,7 @@ export const command = new CommandBuilder()
.addChoiceOption(o => .addChoiceOption(o =>
o.setName("action") o.setName("action")
.setDescription("The action to perform: link, unlink, np, profile, loved, top, recent, playlists, play, scrobble, leaderboard", "options.lastfm.action") .setDescription("The action to perform: link, unlink, np, profile, loved, top, recent, playlists, play, scrobble, leaderboard", "options.lastfm.action")
.addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "playlists", "play", "scrobble", "leaderboard", "lb") .addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "playlists", "play", "scrobble", "leaderboard", "lb", "love", "unlove", "artists")
.setRequired(false) .setRequired(false)
) )
.addTextOption(o => .addTextOption(o =>
@@ -23,7 +23,6 @@ export const command = new CommandBuilder()
.setRequired(false) .setRequired(false)
); );
function notConfigured(msg) { function notConfigured(msg) {
return { return {
embeds: [new EmbedBuilder() embeds: [new EmbedBuilder()
@@ -255,7 +254,6 @@ function parsePlayArgs(msg, data) {
return { category: "" }; return { category: "" };
} }
export async function run(msg, data) { export async function run(msg, data) {
const lastfm = this.lastfm; const lastfm = this.lastfm;
if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(msg)); if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(msg));
@@ -689,6 +687,100 @@ export async function run(msg, data) {
return msg.reply({ embeds: [buildTrackList(user.username, "🕐 Recent Tracks", tracks, false, prefix)] }); return msg.reply({ embeds: [buildTrackList(user.username, "🕐 Recent Tracks", tracks, false, prefix)] });
} }
case "artists": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
let artists;
try {
artists = await lastfm.getTopArtists(userId, "overall", 15);
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to fetch top artists: ${err.message}`)]
});
}
if (!artists.length) {
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🎤 No top artists found for **${user.username}**.`)]
});
}
const lines = artists.map((a, i) => {
const num = String(i + 1).padStart(2, " ");
let name = a.name;
if (name.length > 40) name = name.slice(0, 37) + "...";
const link = a.url ? `[${name}](${a.url})` : name;
return `\`${num}.\` ${link} — **${a.playcount}** plays`;
});
const desc = lines.join("\n").slice(0, 4096);
return msg.reply({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(`🎤 Top Artists — ${user.username}`)
.setDescription(desc)
.setFooter({ text: `💡 Use ${prefix}lastfm play top to play your top tracks!` })]
});
}
case "love": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
const pLove = await this.getPlayer(msg, false, false, false);
if (!pLove) return;
const track = pLove.queue?.getCurrent();
if (!track) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Nothing is playing right now. Play a song first to love it!`)]
});
}
const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? "Unknown";
const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown";
try {
await lastfm.loveTrack(userId, artist, name);
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`❤️ Loved **${name}** by **${artist}** on Last.fm!`)]
});
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to love track: ${err.message}`)]
});
}
}
case "unlove": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
const pUnlove = await this.getPlayer(msg, false, false, false);
if (!pUnlove) return;
const track = pUnlove.queue?.getCurrent();
if (!track) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Nothing is playing right now. Play a song first to unlove it!`)]
});
}
const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? "Unknown";
const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown";
try {
await lastfm.unloveTrack(userId, artist, name);
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`💔 Unloved **${name}** by **${artist}** on Last.fm.`)]
});
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to unlove track: ${err.message}`)]
});
}
}
default: default:
return msg.reply({ return msg.reply({
embeds: [new EmbedBuilder() embeds: [new EmbedBuilder()
@@ -703,9 +795,12 @@ export async function run(msg, data) {
`\`${prefix}lastfm profile\` — View your Last.fm profile`, `\`${prefix}lastfm profile\` — View your Last.fm profile`,
`\`${prefix}lastfm loved\` — View your loved tracks`, `\`${prefix}lastfm loved\` — View your loved tracks`,
`\`${prefix}lastfm top\` — View your top tracks`, `\`${prefix}lastfm top\` — View your top tracks`,
`\`${prefix}lastfm artists\` — View your top artists`,
`\`${prefix}lastfm recent\` — View your recent tracks`, `\`${prefix}lastfm recent\` — View your recent tracks`,
`\`${prefix}lastfm playlists\` — View your Last.fm playlists`, `\`${prefix}lastfm playlists\` — View your Last.fm playlists`,
`\`${prefix}lastfm leaderboard\` — Scrobble leaderboard`, `\`${prefix}lastfm leaderboard\` — Scrobble leaderboard`,
`\`${prefix}lastfm love\` — Love the current track`,
`\`${prefix}lastfm unlove\` — Unlove the current track`,
``, ``,
`🎶 **Play from Last.fm:**`, `🎶 **Play from Last.fm:**`,
`\`${prefix}lastfm play loved\` — Play your loved tracks`, `\`${prefix}lastfm play loved\` — Play your loved tracks`,
@@ -732,7 +827,6 @@ export async function run(msg, data) {
} }
} }
function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") { function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") {
const lines = tracks.map((t, i) => { const lines = tracks.map((t, i) => {
const num = String(i + 1).padStart(2, " "); const num = String(i + 1).padStart(2, " ");
@@ -752,7 +846,6 @@ function buildTrackList(username, title, tracks, showPlaycount = false, prefix =
.setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` }); .setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` });
} }
function buildLeaderboardEmbed(lb, pageIdx, prefix) { function buildLeaderboardEmbed(lb, pageIdx, prefix) {
const MEDALS = ["🥇", "🥈", "🥉"]; const MEDALS = ["🥇", "🥈", "🥉"];
const startRank = pageIdx * lb.perPage; const startRank = pageIdx * lb.perPage;
+28
View File
@@ -0,0 +1,28 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
export const command = new CommandBuilder()
.setName("move")
.setDescription("Move a track from one position to another in the queue.", "commands.move")
.setCategory("music")
.addAliases("mv", "m")
.addNumberOption(o =>
o.setName("from")
.setDescription("The current position of the track in the queue. You can view the indices with the 'list' command.", "options.move.from")
.setRequired(true)
)
.addNumberOption(o =>
o.setName("to")
.setDescription("The target position to move the track to in the queue.", "options.move.to")
.setRequired(true)
);
export async function run(message, data) {
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const from = data.get("from")?.value;
const to = data.get("to")?.value;
if (from == null || from < 1) return message.replyEmbed("Source position must be 1 or greater.");
if (to == null || to < 1) return message.replyEmbed("Target position must be 1 or greater.");
const res = p.move(from, to);
message.replyEmbed(res);
}
+91
View File
@@ -0,0 +1,91 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("seek")
.setDescription("Seek to a specific position in the current track.", "commands.seek")
.setCategory("music")
.addTextOption(o =>
o.setName("position")
.setDescription("Position to seek to (e.g. 1:30, 90, or 1:30:00 for hours)")
.setRequired(true)
);
export async function run(msg, data) {
const positionInput = data.get("position")?.value;
const p = await this.getPlayer(msg, true, true, false);
if (!p) return;
if (!p.queue?.getCurrent()) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ There's nothing playing at the moment!")] });
}
if (p._paused) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Can't seek while paused. Resume first.")] });
}
let seekMs = parseSeekPosition(positionInput);
if (seekMs === null || seekMs < 0) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Invalid position format. Use \`mm:ss\`, \`hh:mm:ss\`, or seconds (e.g. \`1:30\`, \`90\`, \`0:30\`).`)] });
}
const trackDuration = p._getTrackDurationMs(p.queue.getCurrent());
if (trackDuration > 0 && seekMs >= trackDuration) {
const maxStr = formatDuration(trackDuration);
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Position exceeds track duration (**${maxStr}**). Use a value between \`0:00\` and \`${maxStr}\`.`)] });
}
try {
const result = await p.seekToPosition(seekMs);
if (result) {
const seekStr = formatDuration(seekMs);
const totalStr = trackDuration > 0 ? formatDuration(trackDuration) : "∞";
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`⏩ Seeked to **${seekStr}** / ${totalStr}`)] });
} else {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Seeking is not supported by the current audio node.")] });
}
} catch (err) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to seek: ${err.message}`)] });
}
}
function parseSeekPosition(str) {
if (!str || typeof str !== "string") return null;
str = str.trim();
if (/^\d+$/.test(str)) {
return parseInt(str, 10) * 1000;
}
const parts = str.split(":").map(Number);
if (parts.some(isNaN)) return null;
if (parts.length === 2) {
const [minutes, seconds] = parts;
if (seconds >= 60) return null;
return (minutes * 60 + seconds) * 1000;
}
if (parts.length === 3) {
const [hours, minutes, seconds] = parts;
if (minutes >= 60 || seconds >= 60) return null;
return (hours * 3600 + minutes * 60 + seconds) * 1000;
}
return null;
}
function formatDuration(ms) {
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) {
return `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
}
return `${minutes}:${String(seconds).padStart(2, "0")}`;
}
-7
View File
@@ -29,7 +29,6 @@ function richEmbed(fields, opts = {}) {
return { embeds: [raw] }; return { embeds: [raw] };
} }
const SHORTCUTS = { const SHORTCUTS = {
prefix: "prefix", prefix: "prefix",
pfx: "prefix", pfx: "prefix",
@@ -51,7 +50,6 @@ const VOLUME_MIN = 1;
const VOLUME_MAX = 200; const VOLUME_MAX = 200;
const MAX_247_CHANNELS = 10; const MAX_247_CHANNELS = 10;
/** Extract clean numeric channel ID from any format */ /** Extract clean numeric channel ID from any format */
function cleanId(raw) { function cleanId(raw) {
return String(raw).replace(/\D/g, ""); return String(raw).replace(/\D/g, "");
@@ -99,7 +97,6 @@ function getGuildName(message) {
return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server"; return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server";
} }
/** /**
* Get the 24/7 mode for a specific channel. * Get the 24/7 mode for a specific channel.
* Reads from the per-channel map (stay_247_modes) first, * Reads from the per-channel map (stay_247_modes) first,
@@ -521,7 +518,6 @@ async function handle247(ctx, message, value) {
} }
} }
/** /**
* Validate and save a setting value. * Validate and save a setting value.
* @returns {string|null} Error message string, or null on success. * @returns {string|null} Error message string, or null on success.
@@ -582,7 +578,6 @@ async function applySet(ctx, message, set, key, rawValue) {
return null; return null;
} }
async function handleShortcut(ctx, message, settingKey, valueTokens) { async function handleShortcut(ctx, message, settingKey, valueTokens) {
const set = ctx.getSettings(message); const set = ctx.getSettings(message);
@@ -605,7 +600,6 @@ async function handleShortcut(ctx, message, settingKey, valueTokens) {
} }
} }
export const command = function() { export const command = function() {
if (this.locale) { if (this.locale) {
VALID_LOCALES = this.locale.availableLocales(); VALID_LOCALES = this.locale.availableLocales();
@@ -702,7 +696,6 @@ export const command = function() {
); );
}; };
export async function run(message, data) { export async function run(message, data) {
const set = this.getSettings(message); const set = this.getSettings(message);
const cmd = data.commandId || "getSettings"; const cmd = data.commandId || "getSettings";
-4
View File
@@ -9,7 +9,6 @@ export const command = new CommandBuilder()
.addAliases("info") .addAliases("info")
.setCategory("util"); .setCategory("util");
const CACHE_TTL_MS = 5 * 60 * 1000; const CACHE_TTL_MS = 5 * 60 * 1000;
let cachedUserCount = null; let cachedUserCount = null;
@@ -96,7 +95,6 @@ function getLivePlayerCount(playerMap) {
return live; return live;
} }
let cachedGuildCount = null; let cachedGuildCount = null;
let guildCacheExpiresAt = 0; let guildCacheExpiresAt = 0;
@@ -131,7 +129,6 @@ async function getGuildCount(client) {
} }
} }
function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) { function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) {
const num = (v) => Utils.formatNumber(v); const num = (v) => Utils.formatNumber(v);
const ld = (v) => loading ? "..." : v; const ld = (v) => loading ? "..." : v;
@@ -169,7 +166,6 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount,
return builder; return builder;
} }
export async function run(message) { export async function run(message) {
const lastfm = this.lastfm; const lastfm = this.lastfm;
const lastfmEnabled = lastfm?.enabled ?? false; const lastfmEnabled = lastfm?.enabled ?? false;
-2
View File
@@ -34,7 +34,6 @@ export const command = new CommandBuilder()
.setRequired(false) .setRequired(false)
); );
function notConfigured(prefix) { function notConfigured(prefix) {
return { return {
embeds: [new EmbedBuilder() embeds: [new EmbedBuilder()
@@ -95,7 +94,6 @@ function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired
return { embeds: [embed] }; return { embeds: [embed] };
} }
export async function run(msg, data) { export async function run(msg, data) {
const fluxerlist = this.fluxerlist; const fluxerlist = this.fluxerlist;
const prefix = this.handler?.getPrefix?.(msg.message?.guildId) ?? "%"; const prefix = this.handler?.getPrefix?.(msg.message?.guildId) ?? "%";
-5
View File
@@ -252,7 +252,6 @@ export class Remix {
this._attachWsErrorHandlers(); this._attachWsErrorHandlers();
const botId = client.user?.id ?? "0"; const botId = client.user?.id ?? "0";
await this.settingsMgr.setBotId(botId); await this.settingsMgr.setBotId(botId);
@@ -554,7 +553,6 @@ export class Remix {
}); });
} }
/** /**
* Attach error handlers on all @fluxerjs/ws shard WebSockets. * Attach error handlers on all @fluxerjs/ws shard WebSockets.
* *
@@ -931,13 +929,10 @@ export class Remix {
); );
} }
} }
const remix = new Remix(); const remix = new Remix();
const isIgnorableWsCrash = (err) => { const isIgnorableWsCrash = (err) => {
const message = String(err?.message ?? err ?? ""); const message = String(err?.message ?? err ?? "");
const stack = String(err?.stack ?? ""); const stack = String(err?.stack ?? "");
-4
View File
@@ -18,7 +18,6 @@ import {
buildFluxerListUrl, buildFluxerListUrl,
} from "./constants/API.mjs"; } from "./constants/API.mjs";
export class FluxerListManager { export class FluxerListManager {
/** /**
* @param {object} config - The `fluxerlist` section from config.json * @param {object} config - The `fluxerlist` section from config.json
@@ -45,7 +44,6 @@ export class FluxerListManager {
} }
} }
/** /**
* Generate a cache key from the request parameters. * Generate a cache key from the request parameters.
* @param {"server"|"bot"} type * @param {"server"|"bot"} type
@@ -93,7 +91,6 @@ export class FluxerListManager {
} }
} }
/** /**
* Fetch the list of voters for a server or bot. * Fetch the list of voters for a server or bot.
* *
@@ -218,7 +215,6 @@ export class FluxerListManager {
return allVoters; return allVoters;
} }
_assertEnabled() { _assertEnabled() {
if (!this.enabled) { if (!this.enabled) {
throw new Error("FluxerList integration is not configured (missing apiKey in config.json)."); throw new Error("FluxerList integration is not configured (missing apiKey in config.json).");
-12
View File
@@ -6,7 +6,6 @@ import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.
import { VoiceStateCache } from "./constants/VoiceStateCache.mjs"; import { VoiceStateCache } from "./constants/VoiceStateCache.mjs";
import { REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS } from "./MessageHandler.mjs"; import { REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS } from "./MessageHandler.mjs";
/** /**
* GatewayHandler — manages raw WebSocket gateway events, voice-state tracking, * GatewayHandler — manages raw WebSocket gateway events, voice-state tracking,
* presence rotation, and high-level Fluxer event handlers (GuildCreate, * presence rotation, and high-level Fluxer event handlers (GuildCreate,
@@ -47,7 +46,6 @@ export class GatewayHandler {
this._deferredDeleteCount = 0; this._deferredDeleteCount = 0;
} }
/** /**
* Generate a composite key for bots in the observedVoiceBots map. * Generate a composite key for bots in the observedVoiceBots map.
* Bots can be in multiple guilds so we namespace by guildId. * Bots can be in multiple guilds so we namespace by guildId.
@@ -82,7 +80,6 @@ export class GatewayHandler {
return { key: null, value: null }; return { key: null, value: null };
} }
/** /**
* Check if the bot has all required permissions in a newly joined guild. * Check if the bot has all required permissions in a newly joined guild.
* If critical permissions are missing, log a warning and attempt to send * If critical permissions are missing, log a warning and attempt to send
@@ -151,7 +148,6 @@ export class GatewayHandler {
} }
} }
/** /**
* Seed observedVoiceUsers / observedVoiceBots from all cached guild voice * Seed observedVoiceUsers / observedVoiceBots from all cached guild voice
* states. Called once on Ready after the guild cache is populated. * states. Called once on Ready after the guild cache is populated.
@@ -225,7 +221,6 @@ export class GatewayHandler {
} }
} }
/** /**
* Re-read the guild's voice_states cache and update observedVoiceUsers * Re-read the guild's voice_states cache and update observedVoiceUsers
* for any human users found in the specified channel. * for any human users found in the specified channel.
@@ -400,7 +395,6 @@ export class GatewayHandler {
return humansFound; return humansFound;
} }
/** /**
* Attach a raw "message" listener to the shard-0 WebSocket so we can * Attach a raw "message" listener to the shard-0 WebSocket so we can
* process gateway opcodes (READY, GUILD_CREATE, VOICE_STATE_UPDATE, etc.) * process gateway opcodes (READY, GUILD_CREATE, VOICE_STATE_UPDATE, etc.)
@@ -526,7 +520,6 @@ export class GatewayHandler {
} catch (_) {} } catch (_) {}
} }
setupPresenceRotation() { setupPresenceRotation() {
if (this.presenceContents.length === 0) return; if (this.presenceContents.length === 0) return;
@@ -575,7 +568,6 @@ export class GatewayHandler {
this.presenceTimer = setInterval(setPresence, this.presenceInterval); this.presenceTimer = setInterval(setPresence, this.presenceInterval);
} }
/** /**
* Register all high-level Fluxer event listeners on the Fluxer client. * Register all high-level Fluxer event listeners on the Fluxer client.
* Call once during bot startup. * Call once during bot startup.
@@ -853,7 +845,6 @@ export class GatewayHandler {
return; return;
} }
const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) => const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) =>
String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "") String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "")
); );
@@ -1101,7 +1092,6 @@ export class GatewayHandler {
} }
} }
/** @type {Set<string>} Channel IDs currently being rejoined (dedup guard) */ /** @type {Set<string>} Channel IDs currently being rejoined (dedup guard) */
_rejoinInProgress = new Set(); _rejoinInProgress = new Set();
@@ -1202,7 +1192,6 @@ export class GatewayHandler {
} }
} }
/** /**
* Invoke after the bot has connected and Moonlink has been initialised. * Invoke after the bot has connected and Moonlink has been initialised.
* Seeds voice states, attaches raw WS listener, kicks off presence rotation, * Seeds voice states, attaches raw WS listener, kicks off presence rotation,
@@ -1511,7 +1500,6 @@ export class GatewayHandler {
); );
} }
/** /**
* Perform the actual cleanup for a guild that the bot was removed from. * Perform the actual cleanup for a guild that the bot was removed from.
* Extracted from the GuildDelete handler so it can be called after the * Extracted from the GuildDelete handler so it can be called after the
+110 -11
View File
@@ -25,7 +25,6 @@ function normalizeTrackText(value) {
.toLowerCase(); .toLowerCase();
} }
/** /**
* Build the API signature required by Last.fm for authenticated calls. * Build the API signature required by Last.fm for authenticated calls.
* See: https: * See: https:
@@ -71,7 +70,6 @@ async function apiCall(params, apiSecret, post = false) {
return data; return data;
} }
export class LastFmManager { export class LastFmManager {
/** /**
* @param {object} config - The `lastfm` section from config.json * @param {object} config - The `lastfm` section from config.json
@@ -103,7 +101,6 @@ export class LastFmManager {
} }
} }
/** /**
* Set the bot ID for multi-bot database isolation. * Set the bot ID for multi-bot database isolation.
* Ensures bot_id column exists in lastfm tables, then clears caches. * Ensures bot_id column exists in lastfm tables, then clears caches.
@@ -198,7 +195,6 @@ export class LastFmManager {
return { where: " AND bot_id = ?", params: [String(this.botId)] }; return { where: " AND bot_id = ?", params: [String(this.botId)] };
} }
async _getPool() { async _getPool() {
if (this._pool) return this._pool; if (this._pool) return this._pool;
const mysql = await import("mysql2/promise"); const mysql = await import("mysql2/promise");
@@ -243,7 +239,6 @@ export class LastFmManager {
`); `);
} }
async getUser(userId) { async getUser(userId) {
const cached = this._userCache.get(userId); const cached = this._userCache.get(userId);
if (cached) return cached; if (cached) return cached;
@@ -308,7 +303,6 @@ export class LastFmManager {
if (cached) cached.scrobbleEnabled = enabled; if (cached) cached.scrobbleEnabled = enabled;
} }
/** /**
* Step 1: Get an auth token. The user must visit the Last.fm auth URL to approve it. * Step 1: Get an auth token. The user must visit the Last.fm auth URL to approve it.
* @returns {Promise<string>} The auth token * @returns {Promise<string>} The auth token
@@ -342,7 +336,6 @@ export class LastFmManager {
return data.session; return data.session;
} }
/** /**
* Send a "now playing" notification to Last.fm (does NOT count as a scrobble). * Send a "now playing" notification to Last.fm (does NOT count as a scrobble).
* Called immediately when a track starts. * Called immediately when a track starts.
@@ -404,7 +397,6 @@ export class LastFmManager {
} }
} }
/** /**
* Get the user's loved tracks. * Get the user's loved tracks.
* @param {number} [limit=20] - Max tracks to return * @param {number} [limit=20] - Max tracks to return
@@ -516,6 +508,54 @@ export class LastFmManager {
} }
} }
/**
* Love a track on Last.fm for the given user.
* @param {string} userId - The Fluxer user ID
* @param {string} artist - Track artist
* @param {string} track - Track name
*/
async loveTrack(userId, artist, track) {
if (!this.enabled) return;
const user = await this.getUser(userId);
if (!user) throw new Error("NOT_LINKED");
await apiCall(
{
method: "track.love",
api_key: this.apiKey,
sk: user.sessionKey,
artist,
track,
},
this.apiSecret,
true
);
}
/**
* Unlove a track on Last.fm for the given user.
* @param {string} userId - The Fluxer user ID
* @param {string} artist - Track artist
* @param {string} track - Track name
*/
async unloveTrack(userId, artist, track) {
if (!this.enabled) return;
const user = await this.getUser(userId);
if (!user) throw new Error("NOT_LINKED");
await apiCall(
{
method: "track.unlove",
api_key: this.apiKey,
sk: user.sessionKey,
artist,
track,
},
this.apiSecret,
true
);
}
/** /**
* Search Last.fm for a freeform track query and return the best match. * Search Last.fm for a freeform track query and return the best match.
* Useful for `%play lastfm: kendrick lamar luther` where artist/title * Useful for `%play lastfm: kendrick lamar luther` where artist/title
@@ -644,6 +684,39 @@ export class LastFmManager {
return scored[0]?.track ?? null; return scored[0]?.track ?? null;
} }
/**
* Get similar tracks from Last.fm for a given track.
* @param {string} artist
* @param {string} track
* @param {number} [limit=5]
* @returns {Promise<Array<{ artist: string, name: string, url: string, match: number }>>}
*/
async getSimilarTracks(artist, track, limit = 5) {
if (!this.enabled) return [];
try {
const data = await apiCall(
{
method: "track.getsimilar",
api_key: this.apiKey,
artist,
track,
limit,
},
this.apiSecret
);
return (data.similartracks?.track ?? []).map(t => ({
artist: t.artist?.name ?? "Unknown",
name: t.name,
url: t.url ?? "",
match: parseFloat(t.match ?? 0),
})).filter(t => t.match > 0.1);
} catch {
return [];
}
}
/** /**
* Parse a Last.fm music URL and extract artist and track info. * Parse a Last.fm music URL and extract artist and track info.
* Supports: * Supports:
@@ -717,7 +790,6 @@ export class LastFmManager {
return data.user; return data.user;
} }
/** /**
* Get a list of the user's Last.fm playlists by scraping their profile page. * Get a list of the user's Last.fm playlists by scraping their profile page.
* The Last.fm API removed user.getplaylists, so we fetch the HTML page. * The Last.fm API removed user.getplaylists, so we fetch the HTML page.
@@ -893,6 +965,35 @@ export class LastFmManager {
})); }));
} }
/**
* Get the user's top artists.
* @param {string} userId
* @param {string} [period="overall"] - overall | 7day | 1month | 3month | 6month | 12month
* @param {number} [limit=15]
* @returns {Promise<Array<{ name: string, url: string, playcount: number, image: string }>>}
*/
async getTopArtists(userId, period = "overall", limit = 15) {
const user = await this.getUser(userId);
if (!user) throw new Error("NOT_LINKED");
const data = await apiCall(
{
method: "user.gettopartists",
api_key: this.apiKey,
user: user.username,
period,
limit,
},
this.apiSecret
);
return (data.topartists?.artist ?? []).map(a => ({
name: a.name,
url: a.url ?? "",
playcount: a.playcount ?? 0,
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
}));
}
/** /**
* Fetch tracks from Last.fm by category and return search queries * Fetch tracks from Last.fm by category and return search queries
@@ -956,7 +1057,6 @@ export class LastFmManager {
}; };
} }
/** /**
* Get the total lifetime scrobbles across ALL linked Last.fm users. * Get the total lifetime scrobbles across ALL linked Last.fm users.
* Syncs each user's scrobble count from the Last.fm API, then sums them up. * Syncs each user's scrobble count from the Last.fm API, then sums them up.
@@ -1104,7 +1204,6 @@ export class LastFmManager {
} }
} }
_assertEnabled() { _assertEnabled() {
if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret)."); if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret).");
} }
-2
View File
@@ -1080,7 +1080,6 @@ export class QueuePaginator {
} }
} }
const HELP_CMDS_PER_PAGE = 10; const HELP_CMDS_PER_PAGE = 10;
const HELP_SESSION_MS = 30 * 1000; const HELP_SESSION_MS = 30 * 1000;
@@ -1254,7 +1253,6 @@ export class HelpCommand {
}); });
} }
_handle(msg, args, prefix) { _handle(msg, args, prefix) {
const allCmds = this._commands.commands; const allCmds = this._commands.commands;
const query = (args[0] ?? "").trim(); const query = (args[0] ?? "").trim();
-1
View File
@@ -9,7 +9,6 @@ import { logger } from "./constants/Logger.mjs";
import { EventEmitter } from "node:events"; import { EventEmitter } from "node:events";
import { Events } from "@fluxerjs/core"; import { Events } from "@fluxerjs/core";
export class MoonlinkManager extends EventEmitter { export class MoonlinkManager extends EventEmitter {
/** @type {Manager} */ /** @type {Manager} */
manager = null; manager = null;
+181 -53
View File
@@ -84,7 +84,6 @@ function isIgnorableMediaStateError(err) {
return msg.includes("InvalidState") || msg.includes("failed to capture frame") || msg.includes("capture frame"); return msg.includes("InvalidState") || msg.includes("failed to capture frame") || msg.includes("capture frame");
} }
class PlayerWorkerPool { class PlayerWorkerPool {
constructor(size, workerPath, nlConfig = {}) { constructor(size, workerPath, nlConfig = {}) {
this._size = size; this._size = size;
@@ -194,7 +193,6 @@ class PlayerWorkerPool {
} }
} }
export class Queue extends EventEmitter { export class Queue extends EventEmitter {
data = []; data = [];
current = null; current = null;
@@ -292,7 +290,6 @@ export class Queue extends EventEmitter {
} }
} }
export default class Player extends EventEmitter { export default class Player extends EventEmitter {
/** @type {import("revoice.js").VoiceConnection|null} */ /** @type {import("revoice.js").VoiceConnection|null} */
connection = null; connection = null;
@@ -325,10 +322,15 @@ export default class Player extends EventEmitter {
_streamingStopped = false; _streamingStopped = false;
_skipping = false; _skipping = false;
_seeking = false;
_currentPassthrough = null; _currentPassthrough = null;
_wasRadio = false; _wasRadio = false;
_radioAnnounced = false; _radioAnnounced = false;
_queueEndedSent = false; _queueEndedSent = false;
_lastPlayedTrack = null;
_autoplay = false;
_autoplayHandler = null;
activeFilter = null; activeFilter = null;
activeFilterPayload = null; activeFilterPayload = null;
@@ -395,7 +397,6 @@ export default class Player extends EventEmitter {
} }
} }
/** /**
* Check if 24/7 mode is enabled for this player's channel. * Check if 24/7 mode is enabled for this player's channel.
* Returns true for both "on" and "auto" modes. * Returns true for both "on" and "auto" modes.
@@ -465,7 +466,6 @@ export default class Player extends EventEmitter {
return null; return null;
} }
_restoreVolume() { _restoreVolume() {
if (!this._guildId) return; if (!this._guildId) return;
let savedVol = null; let savedVol = null;
@@ -491,7 +491,6 @@ export default class Player extends EventEmitter {
} }
} }
_hasHumansInChannel() { _hasHumansInChannel() {
if (!this._channelId || !this._guildId) return false; if (!this._channelId || !this._guildId) return false;
const cleanChan = String(this._channelId).replace(/\D/g, ""); const cleanChan = String(this._channelId).replace(/\D/g, "");
@@ -605,7 +604,6 @@ export default class Player extends EventEmitter {
} }
} }
async _ensureMediaPlayer() { async _ensureMediaPlayer() {
if (this._destroyed) return false; if (this._destroyed) return false;
if (!this.connection) return false; if (!this.connection) return false;
@@ -625,7 +623,12 @@ export default class Player extends EventEmitter {
return true; return true;
} }
logger.mediaplayer("[Player] Existing MediaPlayer unhealthy, cleaning up..."); logger.mediaplayer("[Player] Existing MediaPlayer unhealthy, cleaning up...");
try { await this._mediaPlayer.stop(); } catch (_) {} try {
if (this._mediaPlayer.fProc) {
try { this._mediaPlayer.fProc.removeAllListeners(); } catch (_) {}
}
await this._mediaPlayer.stop();
} catch (_) {}
this._mediaPlayer = null; this._mediaPlayer = null;
} }
@@ -647,7 +650,7 @@ export default class Player extends EventEmitter {
if (mp.source && typeof mp.source.captureFrame === "function") { if (mp.source && typeof mp.source.captureFrame === "function") {
const _orig = mp.source.captureFrame.bind(mp.source); const _orig = mp.source.captureFrame.bind(mp.source);
mp.source.captureFrame = async (frame) => { mp.source.captureFrame = async (frame) => {
if (this._streamingStopped || this._skipping || this.leaving || this._destroyed) { if (this._streamingStopped || this._skipping || this._seeking || this.leaving || this._destroyed) {
return; return;
} }
try { try {
@@ -708,19 +711,25 @@ export default class Player extends EventEmitter {
if (this._mediaPlayer) { if (this._mediaPlayer) {
try { try {
if (this._mediaPlayer.fProc && !this._mediaPlayer.ffmpegFinished) { if (this._mediaPlayer.fProc) {
try { this._mediaPlayer.fProc.kill("SIGKILL"); } catch (_) {} try { this._mediaPlayer.fProc.removeAllListeners(); } catch (_) {}
} }
await this._mediaPlayer.stop(); await this._mediaPlayer.stop();
} catch (e) { } catch (e) {
logger.error("[Player] Error stopping media player:", e.message); logger.error("[Player] Error stopping media player:", e.message);
} }
try {
if (this._mediaPlayer?.fProc && !this._mediaPlayer.ffmpegFinished) {
try { this._mediaPlayer.fProc.kill("SIGKILL"); } catch (_) {}
}
} catch (_) {}
this._mediaPlayer = null; this._mediaPlayer = null;
} }
} }
async _request(url, options = {}, returnStream = false) { async _request(url, options = {}, returnStream = false) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fetchUrl = (target, _redirects = 0) => { const fetchUrl = (target, _redirects = 0) => {
@@ -814,7 +823,6 @@ export default class Player extends EventEmitter {
return elapsedMs / totalMs >= 0.85 || remainingMs <= 15_000; return elapsedMs / totalMs >= 0.85 || remainingMs <= 15_000;
} }
async _streamViaRevoice(url, inputOptions = []) { async _streamViaRevoice(url, inputOptions = []) {
if (this._streamingStopped) return; if (this._streamingStopped) return;
@@ -839,7 +847,7 @@ export default class Player extends EventEmitter {
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
audioStream.on("error", (e) => { audioStream.on("error", (e) => {
cleanup(); cleanup();
if (this._streamingStopped || this._skipping) return resolve(); if (this._streamingStopped || this._skipping || this._seeking) return resolve();
const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"]; const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"];
if (graceful.some(g => e.code === g || e.message?.includes(g))) { if (graceful.some(g => e.code === g || e.message?.includes(g))) {
if (this._didTrackMostlyFinish(currentTrack)) return resolve(); if (this._didTrackMostlyFinish(currentTrack)) return resolve();
@@ -869,13 +877,13 @@ export default class Player extends EventEmitter {
return resolve(); return resolve();
} }
cleanup(); cleanup();
if (this._streamingStopped || this._skipping) return resolve(); if (this._streamingStopped || this._skipping || this._seeking) return resolve();
return reject(new Error(`FFmpeg stream ended early: ${ffMsg}`)); 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 || this._seeking) return resolve();
reject(new Error(`FFmpeg: ${ffMsg}`)); reject(new Error(`FFmpeg: ${ffMsg}`));
}; };
@@ -883,7 +891,7 @@ export default class Player extends EventEmitter {
const playResult = this._mediaPlayer.playStream(audioStream, inputOptions); const playResult = this._mediaPlayer.playStream(audioStream, inputOptions);
if (playResult && typeof playResult.catch === "function") { if (playResult && typeof playResult.catch === "function") {
playResult.catch((e) => { playResult.catch((e) => {
if (isIgnorableMediaStateError(e) || this._streamingStopped || this._skipping || this.leaving) { if (isIgnorableMediaStateError(e) || this._streamingStopped || this._skipping || this._seeking || this.leaving) {
logger.mediaplayer("[Player] Suppressed async playStream InvalidState rejection"); logger.mediaplayer("[Player] Suppressed async playStream InvalidState rejection");
cleanup(); cleanup();
resolve(); resolve();
@@ -978,7 +986,6 @@ export default class Player extends EventEmitter {
} }
} }
async join(channelId) { async join(channelId) {
if (this._destroyed) return; if (this._destroyed) return;
@@ -1259,6 +1266,11 @@ export default class Player extends EventEmitter {
this._paused = false; this._paused = false;
this._pausedAt = null; this._pausedAt = null;
this._playingNext = false; this._playingNext = false;
this._autoplay = false;
if (this._autoplayHandler) {
this.removeListener("queueEnd", this._autoplayHandler);
this._autoplayHandler = null;
}
this.leaving = false; this.leaving = false;
} catch (e) { } catch (e) {
logger.error("[Player] leave error:", e.message); logger.error("[Player] leave error:", e.message);
@@ -1280,6 +1292,11 @@ export default class Player extends EventEmitter {
this.leaving = true; this.leaving = true;
this._streamingStopped = true; this._streamingStopped = true;
this._stopInactivityTimer(); this._stopInactivityTimer();
this._autoplay = false;
if (this._autoplayHandler) {
this.removeListener("queueEnd", this._autoplayHandler);
this._autoplayHandler = null;
}
this.searches.clear(); this.searches.clear();
if (this._workerPool) { if (this._workerPool) {
@@ -1309,7 +1326,6 @@ export default class Player extends EventEmitter {
} }
} }
get paused() { return this._paused; } get paused() { return this._paused; }
pause() { pause() {
@@ -1346,20 +1362,24 @@ export default class Player extends EventEmitter {
skip() { skip() {
if (!this.connection || !this.queue.getCurrent()) if (!this.connection || !this.queue.getCurrent())
return ":negative_squared_cross_mark: There's nothing playing at the moment!"; return ":negative_squared_cross_mark: There's nothing playing at the moment!";
this._lastPlayedTrack = this.queue.getCurrent();
this._skipping = true; this._skipping = true;
this._radioAnnounced = false; this._radioAnnounced = false;
this.queue.current = null; this.queue.current = null;
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) { if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
this._queueEndedSent = true; this._queueEndedSent = true;
const prefix = (() => { this.emit("queueEnd");
try { if (!this._autoplay) {
return this.settingsMgr?.getServer?.(this._guildId)?.get?.("prefix") const prefix = (() => {
?? this.settings?.get?.("prefix") try {
?? "%"; return this.settingsMgr?.getServer?.(this._guildId)?.get?.("prefix")
} catch (_) { return "%"; } ?? this.settings?.get?.("prefix")
})(); ?? "%";
this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true }); } catch (_) { return "%"; }
})();
this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true });
}
} }
this._stopMediaPlayer().then(() => { this._stopMediaPlayer().then(() => {
@@ -1385,20 +1405,24 @@ export default class Player extends EventEmitter {
const idx = position - 1; const idx = position - 1;
if (idx < 0 || idx >= this.queue.size()) if (idx < 0 || idx >= this.queue.size())
return `:negative_squared_cross_mark: Position ${position} out of range (queue has ${this.queue.size()} tracks).`; return `:negative_squared_cross_mark: Position ${position} out of range (queue has ${this.queue.size()} tracks).`;
this._lastPlayedTrack = this.queue.getCurrent();
this.queue.data.splice(0, idx); this.queue.data.splice(0, idx);
this.queue.current = null; this.queue.current = null;
this._skipping = true; this._skipping = true;
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) { if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
this._queueEndedSent = true; this._queueEndedSent = true;
const prefix = (() => { this.emit("queueEnd");
try { if (!this._autoplay) {
return this.settingsMgr?.getServer?.(this._guildId)?.get?.("prefix") const prefix = (() => {
?? this.settings?.get?.("prefix") try {
?? "%"; return this.settingsMgr?.getServer?.(this._guildId)?.get?.("prefix")
} catch (_) { return "%"; } ?? this.settings?.get?.("prefix")
})(); ?? "%";
this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true }); } catch (_) { return "%"; }
})();
this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true });
}
} }
this._stopMediaPlayer().then(() => { this._stopMediaPlayer().then(() => {
@@ -1418,7 +1442,6 @@ export default class Player extends EventEmitter {
return `:track_next: Skipped to position ${position}`; return `:track_next: Skipped to position ${position}`;
} }
setVolume(v) { setVolume(v) {
this.preferredVolume = Utils.clamp(v, 0, 2); this.preferredVolume = Utils.clamp(v, 0, 2);
this.emit("volume", this.preferredVolume); this.emit("volume", this.preferredVolume);
@@ -1428,6 +1451,75 @@ export default class Player extends EventEmitter {
return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`; return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`;
} }
/**
* Seek to a specific position (in milliseconds) in the currently playing track.
*
* 1. Sends a PATCH to the NodeLink REST API so the session state is aware
* of the new position.
* 2. Adjusts `startedPlaying` so that elapsed-time calculations remain
* consistent after the seek.
* 3. Restarts the audio stream from the new position (re-uses the
* `_replayWithFilters` path so active filters are preserved).
*
* @param {number} ms Position in milliseconds to seek to.
* @returns {Promise<boolean>} true if the seek succeeded, false if the
* node doesn't support it or no session is available.
*/
async seekToPosition(ms) {
const guildId = this._guildId;
if (!guildId) return false;
const current = this.queue.getCurrent();
if (!current?.encoded) return false;
const liveSessionId = this._moonlink?.getLiveSessionId?.() ?? this._moonlink?.sessionId ?? this._nl.sessionId;
if (!liveSessionId) return false;
const { host, port } = this._nl;
const url = `http://${host}:${port}/v4/sessions/${liveSessionId}/players/${guildId}`;
const body = JSON.stringify({ position: ms });
this._seeking = true;
try {
await this._request(url, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body),
},
body,
});
if (liveSessionId !== this._nl.sessionId) {
this._nl.sessionId = liveSessionId;
logger.moonlink(`[Player] Synced session ID after seek: ${liveSessionId}`);
}
this.startedPlaying = Date.now() - ms;
logger.player(`[Player] Seeked to ${ms}ms — adjusted startedPlaying`);
if (this.connection && !this.leaving && !this._streamingStopped) {
this._replayWithFilters(ms).catch((e) => {
logger.warn("[Player] Seek replay failed (non-fatal):", e.message);
});
}
await Utils.sleep(500);
this._seeking = false;
return true;
} catch (e) {
this._seeking = false;
const errMsg = e?.message ?? "";
if (errMsg.includes("HTTP 404") || errMsg.includes("HTTP 405")) {
logger.warn("[Player] Seek not supported by audio node:", errMsg);
return false;
}
logger.error("[Player] Seek request failed:", errMsg);
throw new Error(sanitizeError(errMsg, this._nl));
}
}
async applyFilter(filterPayload, meta = null) { async applyFilter(filterPayload, meta = null) {
const guildId = this._guildId; const guildId = this._guildId;
@@ -1473,9 +1565,11 @@ export default class Player extends EventEmitter {
const elapsed = this.startedPlaying ? (Date.now() - this.startedPlaying) : 0; const elapsed = this.startedPlaying ? (Date.now() - this.startedPlaying) : 0;
const positionMs = Math.max(0, elapsed); const positionMs = Math.max(0, elapsed);
logger.player(`[Player] Filter applied — restarting stream from ${positionMs}ms`); logger.player(`[Player] Filter applied — restarting stream from ${positionMs}ms`);
this._seeking = true;
this._replayWithFilters(positionMs).catch((e) => { this._replayWithFilters(positionMs).catch((e) => {
logger.warn("[Player] Filter replay failed (non-fatal):", e.message); logger.warn("[Player] Filter replay failed (non-fatal):", e.message);
}); });
setTimeout(() => { this._seeking = false; }, 500);
} }
return { ok: true }; return { ok: true };
@@ -1519,8 +1613,26 @@ export default class Player extends EventEmitter {
} catch (e) { } catch (e) {
logger.warn("[Player] _replayWithFilters stream error:", e.message); logger.warn("[Player] _replayWithFilters stream error:", e.message);
} }
}
if (!this.leaving && !this._skipping && !this._seeking && !this._paused) {
const current = this.queue.getCurrent();
if (current?.type === "radio") {
logger.player("[Player] Radio stream ended after replay");
this._lastPlayedTrack = current;
this.queue.current = null;
this._streamingStopped = true;
this.emit("stopplay");
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
} else {
this._lastPlayedTrack = current;
if (!this.queue.songLoop) this.queue.current = null;
this._streamingStopped = false;
this.playNext().catch(e => logger.error("[Player] post-replay playNext error:", e.message));
}
}
}
isEmpty() { return this.queue.isEmpty(); } isEmpty() { return this.queue.isEmpty(); }
@@ -1589,10 +1701,15 @@ export default class Player extends EventEmitter {
return msg; return msg;
} }
_createProgressBar(length = 15) { _createProgressBar(length = 15) {
const current = this.queue.getCurrent(); const current = this.queue.getCurrent();
if (!current?.duration || !this.startedPlaying) return Utils.progressBar(0, 1, length); if (!current?.duration || !this.startedPlaying) {
const total = this._getTrackDurationMs(current);
if (total > 0) {
return `${Utils.progressBar(0, total, length)} \`0:00 / ${Utils.prettifyMS(total)}\``;
}
return Utils.progressBar(0, 1, length);
}
const totalMs = this._getTrackDurationMs(current); const totalMs = this._getTrackDurationMs(current);
let elapsed = Date.now() - this.startedPlaying; let elapsed = Date.now() - this.startedPlaying;
@@ -1693,36 +1810,43 @@ export default class Player extends EventEmitter {
const current = this.queue.getCurrent(); const current = this.queue.getCurrent();
if (!current) return { msg: "There's nothing playing at the moment." }; if (!current) return { msg: "There's nothing playing at the moment." };
const loopqueue = this.queue.loop ? "**enabled**" : "**disabled**"; const loopqueue = this.queue.loop ? "🔄" : "⏹️";
const songloop = this.queue.songLoop ? "**enabled**" : "**disabled**"; const songloop = this.queue.songLoop ? "🔂" : "⏹️";
const vol = `${Math.round((this.preferredVolume || 1) * 100)}%`; const vol = `${Math.round((this.preferredVolume || 1) * 100)}%`;
const autoplay = this._autoplay ? "🔁" : "⏹️";
const vcLine = this._channelId ? `🔊 **Now playing in:** <#${this._channelId}>\n\n` : ""; const vcLine = this._channelId ? `🔊 <#${this._channelId}>\n` : "";
if (current.type === "radio") { if (current.type === "radio") {
try { try {
const data = await meta(current.url); const data = await meta(current.url);
return { return {
msg: `${vcLine}📻 Streaming **[${current.title}](${current.author?.url || current.url})**\n\n${current.description || ""}\n\nCurrent song: ${data?.title || "Unknown"}\n\nVolume: ${vol}\n\nQueue loop: ${loopqueue}\nSong loop: ${songloop}`, msg: `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n${current.description || ""}\n\n🎵 Now playing: ${data?.title || "Unknown"}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
image: current.thumbnail image: current.thumbnail
}; };
} catch { } catch {
return { return {
msg: `${vcLine}📻 Streaming **[${current.title}](${current.author?.url || current.url})**\n\nVolume: ${vol}\n\nQueue loop: ${loopqueue}\nSong loop: ${songloop}`, msg: `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
image: current.thumbnail image: current.thumbnail
}; };
} }
} }
if (current.type === "external") { if (current.type === "external") {
const totalMs = this._getTrackDurationMs(current);
let progressLine = "";
if (totalMs > 0) {
progressLine = `\n${this._createProgressBar(20)}`;
}
return { return {
msg: `${vcLine}Playing **[${current.title}](${current.url}) by [${current.artist || "Unknown"}](${current.author?.url || ""})**\n\nVolume: ${vol}\n\nQueue loop: ${loopqueue}\nSong loop: ${songloop}`, msg: `${vcLine}🎵 **[${current.title}](${current.url})** by ${current.artist || "Unknown"}${progressLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
image: current.thumbnail image: current.thumbnail
}; };
} }
const progressBar = this._createProgressBar(20);
return { return {
msg: `${vcLine}🎵 Playing: **[${current.title}](${current.spotifyUrl || current.url})** (${this.getCurrentElapsedDuration()}/${this.getCurrentDuration()})\n\nVolume: ${vol}\n\nQueue loop: ${loopqueue}\nSong loop: ${songloop}`, msg: `${vcLine}🎵 **[${current.title}](${current.spotifyUrl || current.url})**\n${progressBar}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
image: current.thumbnail image: current.thumbnail
}; };
} }
@@ -1778,7 +1902,6 @@ export default class Player extends EventEmitter {
}))); })));
} }
_workerPool = null; _workerPool = null;
_getWorkerPool() { _getWorkerPool() {
@@ -1806,7 +1929,6 @@ export default class Player extends EventEmitter {
); );
} }
async fetchResults(query, id, provider = "ytm") { async fetchResults(query, id, provider = "ytm") {
try { try {
const data = await this.workerJob("searchResults", { query, provider, resultCount: this.resultLimit }); const data = await this.workerJob("searchResults", { query, provider, resultCount: this.resultLimit });
@@ -1892,7 +2014,6 @@ export default class Player extends EventEmitter {
return events; return events;
} }
_buildRadioTrack(radio) { _buildRadioTrack(radio) {
return { return {
type: "radio", type: "radio",
@@ -1935,7 +2056,6 @@ export default class Player extends EventEmitter {
if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} }
async playNext() { async playNext() {
if (this._playingNext) return; if (this._playingNext) return;
this._playingNext = true; this._playingNext = true;
@@ -1954,15 +2074,21 @@ export default class Player extends EventEmitter {
if (this._mediaPlayer) { if (this._mediaPlayer) {
try { try {
if (this._mediaPlayer.fProc) {
try { this._mediaPlayer.fProc.removeAllListeners(); } catch (_) {}
}
await this._mediaPlayer.stop(); await this._mediaPlayer.stop();
} catch (_) {} } catch (_) {}
} }
this._streamingStopped = false; this._streamingStopped = false;
const currentBeforeNext = this.queue.getCurrent();
if (currentBeforeNext) this._lastPlayedTrack = currentBeforeNext;
const songData = this.queue.next(); const songData = this.queue.next();
if (!songData) { if (!songData) {
this.emit("stopplay"); this.emit("stopplay");
this.emit("queueEnd");
if (!this._is247Enabled()) { if (!this._is247Enabled()) {
this._startInactivityTimer(); this._startInactivityTimer();
@@ -1970,7 +2096,7 @@ export default class Player extends EventEmitter {
logger.voice247("[Player] 24/7 enabled, staying in channel"); logger.voice247("[Player] 24/7 enabled, staying in channel");
} }
if (!this._wasRadio && !this._queueEndedSent) { if (!this._wasRadio && !this._queueEndedSent && !this._autoplay) {
this._queueEndedSent = true; this._queueEndedSent = true;
const prefix = (() => { const prefix = (() => {
try { try {
@@ -2105,9 +2231,10 @@ export default class Player extends EventEmitter {
} }
} }
if (!this.leaving && !this._skipping) { if (!this.leaving && !this._skipping && !this._seeking) {
if (songData.type === "radio") { if (songData.type === "radio") {
logger.player(`[Player] Radio stream ended: ${songData.title}`); logger.player(`[Player] Radio stream ended: ${songData.title}`);
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
this.queue.current = null; this.queue.current = null;
this._streamingStopped = true; this._streamingStopped = true;
this.emit("stopplay"); this.emit("stopplay");
@@ -2117,6 +2244,7 @@ export default class Player extends EventEmitter {
return; return;
} else { } else {
if (!this._paused) { if (!this._paused) {
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
if (!this.queue.songLoop) this.queue.current = null; if (!this.queue.songLoop) this.queue.current = null;
this._streamingStopped = false; this._streamingStopped = false;
return this._doPlayNext(); return this._doPlayNext();
@@ -2124,9 +2252,9 @@ export default class Player extends EventEmitter {
} }
} }
this._skipping = false; this._skipping = false;
if (this._seeking) this._seeking = false;
} }
async lyrics() { async lyrics() {
const current = this.queue.getCurrent(); const current = this.queue.getCurrent();
if (!current) return null; if (!current) return null;
-12
View File
@@ -163,7 +163,6 @@ export class PlayerManager {
this._lastfm = null; this._lastfm = null;
} }
/** /**
* Add a channel to the guild→player reverse index. * Add a channel to the guild→player reverse index.
* Called after a successful player join. * Called after a successful player join.
@@ -275,13 +274,11 @@ export class PlayerManager {
writable: true, writable: true,
}); });
const emit = (type, data) => { const emit = (type, data) => {
if (!this.dashboard?.enabled) return; if (!this.dashboard?.enabled) return;
this.dashboard.updatePlayer({ type, data }, player); this.dashboard.updatePlayer({ type, data }, player);
}; };
const emitGlobal = (type) => { const emitGlobal = (type) => {
if (!this.dashboard?.enabled) return; if (!this.dashboard?.enabled) return;
this.dashboard.playerUpdate({ type }, player); this.dashboard.playerUpdate({ type }, player);
@@ -315,7 +312,6 @@ export class PlayerManager {
} }
}; };
player.on("roomfetched", () => { player.on("roomfetched", () => {
emitGlobal("init"); emitGlobal("init");
sendUserUpdates("join"); sendUserUpdates("join");
@@ -374,7 +370,6 @@ export class PlayerManager {
emit("stopplay", null); emit("stopplay", null);
}); });
player.queue?.on("queue", (queueEvent) => { player.queue?.on("queue", (queueEvent) => {
const serialised = { type: queueEvent.type }; const serialised = { type: queueEvent.type };
switch (queueEvent.type) { switch (queueEvent.type) {
@@ -440,7 +435,6 @@ export class PlayerManager {
return this.locale.translate(guildId, key, replacements); return this.locale.translate(guildId, key, replacements);
} }
/** /**
* Attempt to detect the voice channel a user is currently in. * Attempt to detect the voice channel a user is currently in.
* @param {Message} message * @param {Message} message
@@ -562,7 +556,6 @@ export class PlayerManager {
return null; return null;
} }
/** /**
* Get or create a player for the user's voice channel. * Get or create a player for the user's voice channel.
* @param {Message} message * @param {Message} message
@@ -659,7 +652,6 @@ export class PlayerManager {
return null; return null;
} }
/** /**
* Prompt the user to select a voice channel. * Prompt the user to select a voice channel.
* @param {Message} msg * @param {Message} msg
@@ -749,7 +741,6 @@ export class PlayerManager {
}); });
} }
/** /**
* Make the player leave its current voice channel. * Make the player leave its current voice channel.
* @param {Message} msg * @param {Message} msg
@@ -789,7 +780,6 @@ export class PlayerManager {
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft"))); await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
} }
/** /**
* Create and register a new Player for the given voice channel. * Create and register a new Player for the given voice channel.
* @param {Message} message * @param {Message} message
@@ -972,7 +962,6 @@ export class PlayerManager {
}); });
}); });
(async () => { (async () => {
const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining"))); const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining")));
try { try {
@@ -1045,7 +1034,6 @@ export class PlayerManager {
})(); })();
} }
/** /**
* Handle the "startplay" event for Last.fm: send now-playing notification * Handle the "startplay" event for Last.fm: send now-playing notification
* to all linked users in the voice channel, and schedule a deferred scrobble * to all linked users in the voice channel, and schedule a deferred scrobble
+6 -13
View File
@@ -63,7 +63,6 @@ export class Utils {
return this.prettifyMS(seconds * 1000); return this.prettifyMS(seconds * 1000);
} }
/** /**
* Shuffles array in-place using Fisher-Yates algorithm * Shuffles array in-place using Fisher-Yates algorithm
* @template T * @template T
@@ -118,7 +117,6 @@ export class Utils {
return [...new Set(array)]; return [...new Set(array)];
} }
/** /**
* Truncate text with ellipsis * Truncate text with ellipsis
* @param {string} str - String to truncate * @param {string} str - String to truncate
@@ -210,7 +208,6 @@ export class Utils {
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`; return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
} }
/** /**
* Generate random unique ID * Generate random unique ID
* @param {number} [length=16] - Desired length of ID (8-32 recommended) * @param {number} [length=16] - Desired length of ID (8-32 recommended)
@@ -241,7 +238,6 @@ export class Utils {
}); });
} }
/** /**
* Check if a string represents a finite number * Check if a string represents a finite number
* @param {string} str * @param {string} str
@@ -296,7 +292,6 @@ export class Utils {
} }
} }
/** /**
* Sleep/delay promise * Sleep/delay promise
* @param {number} ms - Milliseconds to sleep * @param {number} ms - Milliseconds to sleep
@@ -350,7 +345,6 @@ export class Utils {
return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timerId)); return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timerId));
} }
/** /**
* Deep clone an object (JSON method - not suitable for circular refs) * Deep clone an object (JSON method - not suitable for circular refs)
* @template T * @template T
@@ -398,24 +392,23 @@ export class Utils {
return result; return result;
} }
/** /**
* Create progress bar string * Create progress bar string
* @param {number} current - Current position in ms or 0-1 ratio * @param {number} current - Current position in ms or 0-1 ratio
* @param {number} [total] - Total duration in ms (if omitted, current is treated as 0-1 ratio) * @param {number} [total] - Total duration in ms (if omitted, current is treated as 0-1 ratio)
* @param {number} [length=15] - Bar length in characters * @param {number} [length=15] - Bar length in characters
* @param {string} [filledChar="▬"] - Filled character * @param {string} [filledChar="━"] - Filled character
* @param {string} [emptyChar="▬"] - Empty character * @param {string} [emptyChar="─"] - Empty character
* @param {string} [indicator="🔘"] - Position indicator * @param {string} [indicator="⬤"] - Position indicator
* @returns {string} Progress bar string * @returns {string} Progress bar string
*/ */
static progressBar( static progressBar(
current, current,
total, total,
length = 15, length = 15,
filledChar = "▬", filledChar = "━",
emptyChar = "▬", emptyChar = "─",
indicator = "🔘" indicator = "⬤"
) { ) {
let progress; let progress;
if (total !== undefined && total > 0) { if (total !== undefined && total > 0) {
-1
View File
@@ -8,7 +8,6 @@
* Edit only here; FluxerListManager.mjs and commands/vote.mjs import from this file. * Edit only here; FluxerListManager.mjs and commands/vote.mjs import from this file.
*/ */
export const FLUXERLIST = { export const FLUXERLIST = {
/** Base URL for all FluxerList API v1 endpoints */ /** Base URL for all FluxerList API v1 endpoints */
BASE_URL: "https://fluxerlist.com/api/v1", BASE_URL: "https://fluxerlist.com/api/v1",
-5
View File
@@ -70,7 +70,6 @@ import { logger } from "./Logger.mjs";
} }
} }
/** Helper: returns a human-readable label for a ConnectionState value */ /** Helper: returns a human-readable label for a ConnectionState value */
function stateLabel(cs) { function stateLabel(cs) {
if (cs === ConnectionState?.CONN_CONNECTED) return "CONN_CONNECTED"; if (cs === ConnectionState?.CONN_CONNECTED) return "CONN_CONNECTED";
@@ -82,7 +81,6 @@ function stateLabel(cs) {
return String(cs); return String(cs);
} }
/** /**
* A voice connection that wraps a LiveKit Room obtained via the Fluxer * A voice connection that wraps a LiveKit Room obtained via the Fluxer
* gateway. Exposes the same interface as revoice.js's VoiceConnection: * gateway. Exposes the same interface as revoice.js's VoiceConnection:
@@ -183,7 +181,6 @@ export class FluxerVoiceConnection extends EventEmitter {
} }
} }
/** /**
* Revoice-compatible class that uses the Fluxer gateway for voice joins. * Revoice-compatible class that uses the Fluxer gateway for voice joins.
* *
@@ -510,7 +507,6 @@ export class FluxerRevoice extends EventEmitter {
nativeConnection, nativeConnection,
}); });
room.on(RoomEvent.Disconnected, (reason) => { room.on(RoomEvent.Disconnected, (reason) => {
const isIntentional = this._intentionalDisconnects.has(String(channelId)); const isIntentional = this._intentionalDisconnects.has(String(channelId));
const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected"); const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected");
@@ -532,7 +528,6 @@ export class FluxerRevoice extends EventEmitter {
connection.emit("disconnect"); connection.emit("disconnect");
}); });
room.on(RoomEvent.ParticipantConnected, (participant) => { room.on(RoomEvent.ParticipantConnected, (participant) => {
const userId = participant?.identity ?? participant?.sid; const userId = participant?.identity ?? participant?.sid;
if (userId) { if (userId) {
-7
View File
@@ -46,7 +46,6 @@ export class VoiceStateCache {
this._lruBotKeys = []; this._lruBotKeys = [];
} }
/** Build composite key "guildId:userId" (both cleaned to digits only) */ /** Build composite key "guildId:userId" (both cleaned to digits only) */
static userKey(guildId, userId) { static userKey(guildId, userId) {
return `${String(guildId ?? "").replace(/\D/g, "")}:${String(userId ?? "").replace(/\D/g, "")}`; return `${String(guildId ?? "").replace(/\D/g, "")}:${String(userId ?? "").replace(/\D/g, "")}`;
@@ -57,7 +56,6 @@ export class VoiceStateCache {
return `${String(guildId ?? "").replace(/\D/g, "")}:${String(channelId ?? "").replace(/\D/g, "")}`; return `${String(guildId ?? "").replace(/\D/g, "")}:${String(channelId ?? "").replace(/\D/g, "")}`;
} }
/** /**
* Update voice state for a user. * Update voice state for a user.
* *
@@ -130,7 +128,6 @@ export class VoiceStateCache {
} }
} }
/** /**
* Check if there are any human users in a specific channel. * Check if there are any human users in a specific channel.
* O(1) via channelMembers index. * O(1) via channelMembers index.
@@ -224,7 +221,6 @@ export class VoiceStateCache {
this.updateUser({ guildId, userId, channelId, isBot }); this.updateUser({ guildId, userId, channelId, isBot });
} }
/** /**
* Remove all entries for a specific guild (used on GuildDelete). * Remove all entries for a specific guild (used on GuildDelete).
* *
@@ -331,7 +327,6 @@ export class VoiceStateCache {
} }
} }
/** /**
* Get the "observedVoiceUsers" size (human count). * Get the "observedVoiceUsers" size (human count).
* Backward-compat with `this.observedVoiceUsers.size` * Backward-compat with `this.observedVoiceUsers.size`
@@ -480,7 +475,6 @@ export class VoiceStateCache {
return this.botLocations.has(compositeKey); return this.botLocations.has(compositeKey);
} }
/** /**
* Default iterator — iterates human users. * Default iterator — iterates human users.
* Yields [userId, {channelId, guildId}] — same shape as old observedVoiceUsers Map. * Yields [userId, {channelId, guildId}] — same shape as old observedVoiceUsers Map.
@@ -608,7 +602,6 @@ export class VoiceStateCache {
} }
} }
get stats() { get stats() {
return { return {
humanUsers: this.userLocations.size, humanUsers: this.userLocations.size,
-6
View File
@@ -12,7 +12,6 @@ import { Utils } from "./Utils.mjs";
import { PROVIDERS } from "./constants/providers.mjs"; import { PROVIDERS } from "./constants/providers.mjs";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
const nl = workerData?.data?.nodelink ?? {}; const nl = workerData?.data?.nodelink ?? {};
const NL_HOST = nl.host ?? "localhost"; const NL_HOST = nl.host ?? "localhost";
const NL_PORT = nl.port ?? 3000; const NL_PORT = nl.port ?? 3000;
@@ -46,7 +45,6 @@ function sanitizeError(msg) {
return s; return s;
} }
/** /**
* Make a GET request to NodeLink and return the parsed JSON body. * Make a GET request to NodeLink and return the parsed JSON body.
* @param {string} path - API path (e.g. "/v4/loadtracks?identifier=…") * @param {string} path - API path (e.g. "/v4/loadtracks?identifier=…")
@@ -97,7 +95,6 @@ async function loadTracks(identifier, nlGetFn = nlGet) {
return nlGetFn(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`); return nlGetFn(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`);
} }
/** /**
* Convert a NodeLink track object to the internal video format. * Convert a NodeLink track object to the internal video format.
* @param {object} track * @param {object} track
@@ -142,10 +139,8 @@ function tokenizeMatchText(value) {
return normalizeMatchText(value).split(" ").filter(Boolean); return normalizeMatchText(value).split(" ").filter(Boolean);
} }
const TYPE_MODIFIERS = ["track","playlist","album","artist","channel","user"]; const TYPE_MODIFIERS = ["track","playlist","album","artist","channel","user"];
class YTUtils extends EventEmitter { class YTUtils extends EventEmitter {
constructor() { super(); } constructor() { super(); }
@@ -451,7 +446,6 @@ class YTUtils extends EventEmitter {
} }
} }
const jobId = workerData?.jobId; const jobId = workerData?.jobId;
const data = workerData?.data; const data = workerData?.data;
+32 -2
View File
@@ -56,14 +56,17 @@
"test": "Shows how many people are in each voice channel.", "test": "Shows how many people are in each voice channel.",
"thumbnail": "Request the thumbnail of the currently playing song.", "thumbnail": "Request the thumbnail of the currently playing song.",
"volume": "Get or change the current volume.", "volume": "Get or change the current volume.",
"volumedefault": "View or set the server default volume. (Requires Manage Server to set)" "volumedefault": "View or set the server default volume. (Requires Manage Server to set)",
"seek": "Seek to a specific position in the currently playing track.",
"move": "Move a track from one position to another in the queue.",
"autoplay": "Toggle autoplay — automatically play similar tracks when the queue ends."
}, },
"options": { "options": {
"debug": { "debug": {
"target": "The target that should be examined." "target": "The target that should be examined."
}, },
"lastfm": { "lastfm": {
"action": "The action to perform: link, confirm, unlink, np, profile, loved, top, recent, scrobble", "action": "The action to perform: link, confirm, unlink, np, profile, loved, top, recent, artists, love, unlove, scrobble",
"token": "The auth token from Last.fm (used with 'confirm' action)" "token": "The auth token from Last.fm (used with 'confirm' action)"
}, },
"eval": { "eval": {
@@ -122,6 +125,13 @@
}, },
"volumedefault": { "volumedefault": {
"volume": "New volume in % (0–200) to save as server default. Leave empty to view current." "volume": "New volume in % (0–200) to save as server default. Leave empty to view current."
},
"seek": {
"position": "Position to seek to (e.g. 1:30, 90, or 1:30:00 for hours)"
},
"move": {
"from": "The current position of the track in the queue (1-based).",
"to": "The target position to move the track to (1-based)."
} }
}, },
"pagination": { "pagination": {
@@ -282,6 +292,13 @@
"profileScrobbles": "🎵 **{{playcount}}** scrobbles", "profileScrobbles": "🎵 **{{playcount}}** scrobbles",
"profileRegistered": "👤 Registered: {{date}}", "profileRegistered": "👤 Registered: {{date}}",
"profileLink": "🔗 [Open profile]({{url}})", "profileLink": "🔗 [Open profile]({{url}})",
"noArtists": "🎤 No top artists found for **{{username}}**.",
"artistsTitle": "🎤 Top Artists — {{username}}",
"lovedTrack": "❤️ Loved **{{name}}** by **{{artist}}** on Last.fm!",
"unlovedTrack": "💔 Unloved **{{name}}** by **${{artist}}** on Last.fm.",
"loveFailed": "❌ Failed to love track: {{error}}",
"unloveFailed": "❌ Failed to unlove track: {{error}}",
"nothingPlayingLove": "❌ Nothing is playing right now. Play a song first to love it!",
"fetchFailed": "❌ Failed to fetch data from Last.fm: {{error}}" "fetchFailed": "❌ Failed to fetch data from Last.fm: {{error}}"
}, },
"list": { "list": {
@@ -555,6 +572,19 @@
"noPermissionSet": "❌ You need **Manage Server** permission to set the server default volume.", "noPermissionSet": "❌ You need **Manage Server** permission to set the server default volume.",
"outOfRange": "❌ Volume must be between `0` and `{{max}}%`.", "outOfRange": "❌ Volume must be between `0` and `{{max}}%`.",
"saved": "🔊 Server default volume saved as `{{volume}}%`." "saved": "🔊 Server default volume saved as `{{volume}}%`."
},
"seek": {
"nothingPlaying": "❌ There's nothing playing at the moment!",
"paused": "❌ Can't seek while paused. Resume first.",
"invalidFormat": "❌ Invalid position format. Use `mm:ss`, `hh:mm:ss`, or seconds (e.g. `1:30`, `90`).",
"exceedsDuration": "❌ Seek position exceeds track duration (**{{duration}}**).",
"seeked": "⏩ Seeked to **{{position}}**",
"notSupported": "❌ Seeking is not supported by the current audio node.",
"failed": "❌ Failed to seek: {{error}}"
},
"autoplay": {
"enabled": "🔁 Autoplay **enabled** — similar tracks will be added automatically when the queue ends.",
"disabled": "➡️ Autoplay **disabled** — the bot will stop when the queue ends."
} }
} }
} }