feat(player): per-track custom start/end trimming

Allow users to save custom start and end points for any track.
Options persist in MySQL and auto-apply on playback — the player
seeks to the configured start time and skips when the end time is
reached. Supports pause/resume and manual seek with timer recalc.

Idea by noisy EVE
This commit is contained in:
NoLogicAlan committed 2026-05-21 17:43:48 +03:00
1 parent 0f2ee99f1e
commit 6bbaf49a94
7 files changed
+617 -4

No files matched your search

+22 -1
View File
@@ -67,6 +67,7 @@ We believe music features shouldn't be locked behind paywalls — **all commands
- **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
- **Track options** — set custom start/end times per track (like old iTunes), great for album compilations and hidden tracks
- **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
- **Web dashboard** — optional browser-based control panel with Redis-backed sessions and Fluxer OAuth2 login
@@ -120,6 +121,7 @@ Below is the complete list of Remix's commands. The default prefix is `%`.
| `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` |
| `trackopt` | Set custom start/end times for tracks | `%trackopt set 0:30 3:45` | `to` |
### Utility
@@ -216,7 +218,24 @@ Remix requires a MySQL database to store per-guild settings.
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
```
4. *(Optional)* If migrating from the legacy settings system, run:
4. Create the track options table (for the `%trackopt` command):
```sql
CREATE TABLE IF NOT EXISTS `track_options` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`user_id` VARCHAR(32) NOT NULL,
`track_identifier` VARCHAR(512) NOT NULL,
`track_title` VARCHAR(512) NOT NULL DEFAULT '',
`start_ms` INT UNSIGNED NOT NULL DEFAULT 0,
`end_ms` INT UNSIGNED NOT NULL DEFAULT 0,
`bot_id` VARCHAR(32) NOT NULL DEFAULT '',
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `uq_user_track_bot` (`user_id`, `track_identifier`, `bot_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
This table is auto-created on startup if it doesn't exist, so manual creation is optional.
5. *(Optional)* If migrating from the legacy settings system, run:
```bash
npm run migrate
```
@@ -302,6 +321,7 @@ fluxer/
│ ├── debug.mjs # Voice connection debugger (owner only, paginated)
│ ├── stats.mjs # Bot stats with live player count
│ ├── lastfm.mjs # Last.fm account linking, scrobbling, and profile
│ ├── trackopt.mjs # Per-track start/end time options (set/get/remove/list)
│ └── ... # All other commands
├── src/
│ ├── CommandHandler.mjs # Command loader, prefix manager, registry
@@ -313,6 +333,7 @@ fluxer/
│ ├── GatewayHandler.mjs # Raw WS events, voice-state tracking, presence rotation
│ ├── RecoveryManager.mjs # Session persistence, crash recovery, 24/7 auto-join
│ ├── LastFmManager.mjs # Last.fm API client — auth, scrobbling, user data, stored scrobble stats
│ ├── TrackOptionsManager.mjs # Per-user track start/end time preferences (auto-seek, auto-skip)
│ ├── Utils.mjs # Shared utilities
│ ├── worker.mjs # Background task worker
│ ├── probe.mjs # FFprobe wrapper for audio stream info
+171
View File
@@ -0,0 +1,171 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("trackopt")
.setDescription("Set custom start/end times for tracks. Like iTunes used to have — great for album compilations and hidden tracks.", "commands.trackopt")
.setCategory("music")
.addSubcommand(s =>
s.setName("set")
.setId("trackopt_set")
.setDescription("Set a custom start and/or end time for the current track")
.addTextOption(o =>
o.setName("times")
.setDescription("Start and optional end time, e.g. '0:30' or '0:30 3:45'")
.setRequired(true)
)
)
.addSubcommand(s =>
s.setName("get")
.setId("trackopt_get")
.setDescription("View your custom start/end time for the current track")
)
.addSubcommand(s =>
s.setName("remove")
.setId("trackopt_remove")
.setDescription("Remove your custom start/end time for the current track")
)
.addSubcommand(s =>
s.setName("list")
.setId("trackopt_list")
.setDescription("List all your saved track options")
)
.addAlias("to");
function parseTimeInput(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 formatMs(ms) {
if (ms == null || ms < 0) return "0:00";
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")}`;
}
export async function run(msg, data) {
const trackOpts = this.trackOptions;
if (!trackOpts) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Track options feature is not available.")] });
}
const subCommand = data.command.name || data.commandId || "get";
const p = await this.getPlayer(msg, true, true, false);
if (!p) return;
const current = p.queue?.getCurrent();
if (!current && subCommand !== "list") {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ There's nothing playing at the moment!")] });
}
const userId = msg.message?.author?.id ?? msg.author?.id;
if (!userId) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Could not identify your user.")] });
}
if (subCommand === "set") {
const timesRaw = data.get("times")?.value;
if (!timesRaw) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Provide start and optional end time. Usage: `%trackopt set 0:30` or `%trackopt set 0:30 3:45`")] });
}
const parts = timesRaw.trim().split(/\s+/);
const startMs = parseTimeInput(parts[0]);
if (startMs === null || startMs < 0) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Invalid start time format. Use `mm:ss`, `hh:mm:ss`, or seconds.")] });
}
let endMs = 0;
if (parts.length > 1) {
endMs = parseTimeInput(parts[1]);
if (endMs === null || endMs <= 0) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Invalid end time format. Use `mm:ss`, `hh:mm:ss`, or seconds.")] });
}
if (endMs <= startMs) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ End time must be after start time.")] });
}
}
const trackDuration = p._getTrackDurationMs(current);
if (trackDuration > 0) {
if (startMs >= trackDuration) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Start time exceeds track duration (**${formatMs(trackDuration)}**).`)] });
}
if (endMs > 0 && endMs > trackDuration) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ End time exceeds track duration (**${formatMs(trackDuration)}**).`)] });
}
}
const result = await trackOpts.set(userId, current, startMs, endMs);
if (!result) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Failed to save track option.")] });
}
let desc = `✅ Track option saved for **${current.title}**\n`;
desc += `▶️ Start: **${formatMs(startMs)}**`;
if (endMs > 0) desc += ` | ⏹️ End: **${formatMs(endMs)}**`;
else desc += ` | ⏹️ End: **full track**`;
desc += `\n\nThis will apply automatically whenever this track plays in a channel you're in.`;
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
}
if (subCommand === "get") {
const result = await trackOpts.get(userId, current);
if (!result) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`No custom times set for **${current.title}**.`)] });
}
let desc = `📎 Track option for **${current.title}**\n`;
desc += `▶️ Start: **${formatMs(result.startMs)}**`;
if (result.endMs > 0) desc += ` | ⏹️ End: **${formatMs(result.endMs)}**`;
else desc += ` | ⏹️ End: **full track**`;
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
}
if (subCommand === "remove") {
const removed = await trackOpts.remove(userId, current);
if (!removed) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`No custom times found for **${current.title}**.`)] });
}
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🗑️ Removed track option for **${current.title}**.`)] });
}
if (subCommand === "list") {
const rows = await trackOpts.list(userId);
if (!rows || rows.length === 0) {
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription("📭 You have no saved track options. Use `%trackopt set <start> [end]` to add one!")] });
}
let desc = `📋 **Your Track Options** (${rows.length})\n\n`;
for (const row of rows) {
const title = row.track_title || row.track_identifier;
const endStr = row.end_ms > 0 ? formatMs(row.end_ms) : "end";
desc += `• **${title}** — ${formatMs(row.start_ms)} → ${endStr}\n`;
}
desc += `\nUse \`%trackopt remove\` while a track is playing to delete its option.`;
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
}
}
+6
View File
@@ -17,6 +17,7 @@ import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs";
import { GatewayHandler } from "./src/GatewayHandler.mjs";
import { LastFmManager } from "./src/LastFmManager.mjs";
import { FluxerListManager } from "./src/FluxerListManager.mjs";
import { TrackOptionsManager } from "./src/TrackOptionsManager.mjs";
/**
* Create a backward-compatible "bot view" wrapper around VoiceStateCache.
@@ -206,6 +207,8 @@ export class Remix {
this.fluxerlist = new FluxerListManager(config.fluxerlist);
this.trackOptions = new TrackOptionsManager(config.mysql);
settings.on("ready", () => {
initLogger(config);
logger.settings("[settings] Loaded from DB.");
@@ -257,6 +260,7 @@ export class Remix {
await this.settingsMgr.setBotId(botId);
await this.lastfm.setBotId(botId);
this.dashboard.setBotId(botId);
this.trackOptions.setBotId(botId);
if (!moonlinkInitialised) {
moonlinkInitialised = true;
@@ -305,6 +309,7 @@ export class Remix {
dashboard: this.dashboard,
locale: this.locale,
timers: this.T,
trackOptions: this.trackOptions,
});
this.players.observedVoiceUsers = this.observedVoiceUsers;
this.players.voiceCache = this.voiceCache;
@@ -670,6 +675,7 @@ export class Remix {
observedVoiceUsers: this.observedVoiceUsers ?? null,
voiceCache: this.voiceCache ?? null,
locale: this.locale ?? null,
trackOptions: this.trackOptions ?? null,
});
player._home247Channel = cleanChannelId;
+215 -2
View File
@@ -33,6 +33,16 @@ function mkEmbed(desc) {
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] };
}
function formatMsHelper(ms) {
if (ms == null || ms < 0) return "0:00";
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")}`;
}
/** NodeLink default password — centralised so it doesn't need to be hardcoded in two places. */
const NL_DEFAULT_PASSWORD = "youshallnotpass";
@@ -362,6 +372,8 @@ export default class Player extends EventEmitter {
this._observedVoiceUsers = opts.observedVoiceUsers ?? null;
this._voiceCache = opts.voiceCache ?? null;
this.locale = opts.locale ?? null;
this.trackOptions = opts.trackOptions ?? null;
this._activeTrackOpt = null;
this._nl = {
...this._nl,
@@ -1242,6 +1254,8 @@ export default class Player extends EventEmitter {
this.leaving = true;
this._stopInactivityTimer();
this._streamingStopped = true;
this._clearTrackEndTimer();
this._activeTrackOpt = null;
if (this._mediaPlayer) {
this._mediaPlayer.destroy();
@@ -1284,6 +1298,9 @@ export default class Player extends EventEmitter {
if (this._destroyed) return;
this._destroyed = true;
this._clearTrackEndTimer();
this._activeTrackOpt = null;
try {
if (this._moonlink && this._onMoonlinkReady) {
try { this._moonlink.off("ready", this._onMoonlinkReady); } catch (_) {}
@@ -1336,6 +1353,7 @@ export default class Player extends EventEmitter {
this._paused = true;
this._pausedAt = Date.now();
this._mediaPlayer?.pause();
this._pauseTrackEndTimer();
this.emit("playback", false);
this._stopInactivityTimer();
return ":pause_button: Paused";
@@ -1354,6 +1372,7 @@ export default class Player extends EventEmitter {
this._paused = false;
this._pausedAt = null;
this._mediaPlayer?.resume();
this._resumeTrackEndTimer();
this.emit("playback", true);
this._stopInactivityTimer();
return ":arrow_forward: Resumed";
@@ -1365,6 +1384,8 @@ export default class Player extends EventEmitter {
this._lastPlayedTrack = this.queue.getCurrent();
this._skipping = true;
this._radioAnnounced = false;
this._activeTrackOpt = null;
this._clearTrackEndTimer();
this.queue.current = null;
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
@@ -1499,6 +1520,8 @@ export default class Player extends EventEmitter {
this.startedPlaying = Date.now() - ms;
logger.player(`[Player] Seeked to ${ms}ms — adjusted startedPlaying`);
this._recalcTrackEndTimer();
if (this.connection && !this.leaving && !this._streamingStopped) {
this._replayWithFilters(ms).catch((e) => {
logger.warn("[Player] Seek replay failed (non-fatal):", e.message);
@@ -1629,6 +1652,8 @@ export default class Player extends EventEmitter {
this._lastPlayedTrack = current;
if (!this.queue.songLoop) this.queue.current = null;
this._streamingStopped = false;
this._clearTrackEndTimer();
this._activeTrackOpt = null;
this.playNext().catch(e => logger.error("[Player] post-replay playNext error:", e.message));
}
}
@@ -1845,8 +1870,14 @@ export default class Player extends EventEmitter {
}
const progressBar = this._createProgressBar(20);
let trackOptLine = "";
if (this._activeTrackOpt) {
const optStart = formatMsHelper(this._activeTrackOpt.startMs);
const optEnd = this._activeTrackOpt.endMs > 0 ? formatMsHelper(this._activeTrackOpt.endMs) : "end";
trackOptLine = `\n✂️ Custom: ${optStart} → ${optEnd}`;
}
return {
msg: `${vcLine}🎵 **[${current.title}](${current.spotifyUrl || current.url})**\n${progressBar}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
msg: `${vcLine}🎵 **[${current.title}](${current.spotifyUrl || current.url})**\n${progressBar}${trackOptLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
image: current.thumbnail
};
}
@@ -2164,6 +2195,7 @@ export default class Player extends EventEmitter {
if (!this.connection || this.leaving) return;
let streamUrl = null;
let startOffsetMs = 0;
if (songData.type === "radio" || songData.type === "external") {
streamUrl = songData.url;
@@ -2206,9 +2238,28 @@ export default class Player extends EventEmitter {
return;
}
this._activeTrackOpt = null;
this._clearTrackEndTimer();
let trackOptMatch = null;
try {
trackOptMatch = await this._lookupTrackOptions(songData);
} catch (e) {
logger.warn("[Player] TrackOptions lookup error:", e.message);
}
if (trackOptMatch) {
this._activeTrackOpt = trackOptMatch;
if (trackOptMatch.startMs > 0 && songData.encoded && streamUrl.includes("/v4/loadstream")) {
startOffsetMs = trackOptMatch.startMs;
streamUrl = streamUrl.replace(/position=\d+/, `position=${startOffsetMs}`);
logger.player(`[Player] TrackOptions: starting from ${startOffsetMs}ms via loadstream position param`);
}
}
logger.player(`[Player:${this._guildId}] Streaming: ${songData.title}`);
this.startedPlaying = Date.now();
this.startedPlaying = Date.now() - startOffsetMs;
this._paused = false;
this._pausedAt = null;
this._queueEndedSent = false;
@@ -2219,6 +2270,33 @@ export default class Player extends EventEmitter {
}
this.emit("startplay", songData);
if (trackOptMatch && trackOptMatch.startMs > 0 && startOffsetMs === 0) {
this._applyTrackOptionsSeek(trackOptMatch).catch((e) => {
logger.warn("[Player] TrackOptions auto-seek error:", e.message);
});
}
if (trackOptMatch && trackOptMatch.endMs > 0) {
const elapsedMs = Date.now() - this.startedPlaying;
const remainingMs = trackOptMatch.endMs - elapsedMs;
if (remainingMs > 0) {
const match = trackOptMatch;
this._trackEndTimer = setTimeout(() => {
if (this._destroyed || this.leaving || !this._activeTrackOpt) return;
logger.player(`[Player] TrackOptions: end time reached (${match.endMs}ms), skipping track`);
this._activeTrackOpt = null;
this._trackEndTimer = null;
this._trackEndRemainingMs = null;
this._skipping = true;
this._stopMediaPlayer().then(() => {
this._doPlayNext();
}).catch(() => {
this._doPlayNext();
});
}, remainingMs);
}
}
try {
await this._streamUrl(streamUrl);
} catch (err) {
@@ -2231,6 +2309,8 @@ export default class Player extends EventEmitter {
}
}
this._clearTrackEndTimer();
if (!this.leaving && !this._skipping && !this._seeking) {
if (songData.type === "radio") {
logger.player(`[Player] Radio stream ended: ${songData.title}`);
@@ -2255,6 +2335,139 @@ export default class Player extends EventEmitter {
if (this._seeking) this._seeking = false;
}
_trackEndTimer = null;
_trackEndRemainingMs = null;
_clearTrackEndTimer() {
if (this._trackEndTimer) {
clearTimeout(this._trackEndTimer);
this._trackEndTimer = null;
}
this._trackEndRemainingMs = null;
}
_pauseTrackEndTimer() {
if (!this._trackEndTimer || !this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) return;
clearTimeout(this._trackEndTimer);
const elapsedMs = Date.now() - this.startedPlaying;
this._trackEndRemainingMs = Math.max(0, this._activeTrackOpt.endMs - elapsedMs);
this._trackEndTimer = null;
}
_resumeTrackEndTimer() {
if (this._trackEndRemainingMs == null || this._trackEndRemainingMs <= 0 || !this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) {
this._trackEndRemainingMs = null;
return;
}
const remainingMs = this._trackEndRemainingMs;
const match = this._activeTrackOpt;
this._trackEndTimer = setTimeout(() => {
if (this._destroyed || this.leaving || !this._activeTrackOpt) return;
logger.player(`[Player] TrackOptions: end time reached (${match.endMs}ms), skipping track`);
this._activeTrackOpt = null;
this._trackEndTimer = null;
this._trackEndRemainingMs = null;
this._skipping = true;
this._stopMediaPlayer().then(() => {
this._doPlayNext();
}).catch(() => {
this._doPlayNext();
});
}, remainingMs);
this._trackEndRemainingMs = null;
}
_recalcTrackEndTimer() {
if (!this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) return;
this._clearTrackEndTimer();
const elapsedMs = Date.now() - this.startedPlaying;
const remainingMs = this._activeTrackOpt.endMs - elapsedMs;
if (remainingMs <= 0) {
this._activeTrackOpt = null;
this._skipping = true;
this._stopMediaPlayer().then(() => {
this._doPlayNext();
}).catch(() => {
this._doPlayNext();
});
return;
}
const match = this._activeTrackOpt;
this._trackEndTimer = setTimeout(() => {
if (this._destroyed || this.leaving || !this._activeTrackOpt) return;
logger.player(`[Player] TrackOptions: end time reached (${match.endMs}ms), skipping track`);
this._activeTrackOpt = null;
this._trackEndTimer = null;
this._trackEndRemainingMs = null;
this._skipping = true;
this._stopMediaPlayer().then(() => {
this._doPlayNext();
}).catch(() => {
this._doPlayNext();
});
}, remainingMs);
}
async _lookupTrackOptions(songData) {
if (!this.trackOptions || !songData || songData.type === "radio") return null;
if (!this._guildId || !this._channelId) return null;
const userIds = [];
if (this._voiceCache) {
const humans = this._voiceCache.getHumansInChannel(
String(this._guildId).replace(/\D/g, ""),
String(this._channelId).replace(/\D/g, "")
);
userIds.push(...humans);
}
if (userIds.length === 0) {
try {
const guild = this.client?.guilds?.get?.(this._guildId);
const voiceStates = guild?.voice_states ?? guild?.voiceStates;
if (voiceStates) {
const entries = Array.isArray(voiceStates) ? voiceStates
: typeof voiceStates.values === "function" ? [...voiceStates.values()]
: Object.values(voiceStates);
for (const state of entries) {
const ch = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
if (ch === String(this._channelId).replace(/\D/g, "")) {
const uid = state?.userId ?? state?.user_id;
const member = guild?.members?.get?.(uid);
if (uid && !member?.user?.bot) userIds.push(uid);
}
}
}
} catch (_) {}
}
if (userIds.length === 0) return null;
const match = await this.trackOptions.getBestMatchForChannel(userIds, songData);
return match || null;
}
async _applyTrackOptionsSeek(match) {
if (!match || match.startMs <= 0) return;
let seeked = false;
for (let attempt = 0; attempt < 10; attempt++) {
await Utils.sleep(500);
try {
const result = await this.seekToPosition(match.startMs);
if (result) {
seeked = true;
logger.player(`[Player] TrackOptions: auto-seeked to ${match.startMs}ms for user ${match.userId} (attempt ${attempt + 1})`);
break;
}
} catch (e) {
logger.warn(`[Player] TrackOptions auto-seek attempt ${attempt + 1} error:`, e.message);
}
}
if (!seeked) {
logger.warn(`[Player] TrackOptions: auto-seek to ${match.startMs}ms failed after all retries`);
}
}
async lyrics() {
const current = this.queue.getCurrent();
if (!current) return null;
+2
View File
@@ -161,6 +161,7 @@ export class PlayerManager {
this.locale = config.locale ?? null;
this.timers = config.timers ?? {};
this._lastfm = null;
this.trackOptions = config.trackOptions ?? null;
}
/**
@@ -831,6 +832,7 @@ export class PlayerManager {
observedVoiceUsers: this.observedVoiceUsers ?? null,
voiceCache: this.voiceCache ?? null,
locale: this.locale ?? null,
trackOptions: this.trackOptions ?? null,
});
player.textChannel = message.channel;
+178
View File
@@ -0,0 +1,178 @@
import mysql from "mysql2";
import { logger } from "./constants/Logger.mjs";
export class TrackOptionsManager {
db = null;
botId = null;
_hasTable = false;
_ready = false;
_readyPromise = null;
_cache = new Map();
_cacheMaxSize = 2000;
constructor(mysqlConfig) {
this.db = mysql.createPool({ connectionLimit: 10, ...mysqlConfig });
this.db.on("error", (err) => {
logger.error("[TrackOptions] MySQL pool error:", err.code ?? err.message);
});
this._readyPromise = this._ensureTable();
}
async ready() {
await this._readyPromise;
}
async _ensureTable() {
try {
await this._query(
`CREATE TABLE IF NOT EXISTS track_options (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id VARCHAR(32) NOT NULL,
track_identifier VARCHAR(512) NOT NULL,
track_title VARCHAR(512) NOT NULL DEFAULT '',
start_ms INT UNSIGNED NOT NULL DEFAULT 0,
end_ms INT UNSIGNED NOT NULL DEFAULT 0,
bot_id VARCHAR(32) NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uq_user_track_bot (user_id, track_identifier, bot_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
);
this._hasTable = true;
this._ready = true;
logger.player("[TrackOptions] Table ready.");
} catch (err) {
logger.error("[TrackOptions] Failed to create table:", err.message);
}
}
async setBotId(id) {
this.botId = id;
}
_query(q) {
return new Promise((resolve, reject) => {
this.db.query(q, (error, results) => {
if (error) return reject(error);
resolve(results);
});
});
}
_botIdWhere() {
if (!this.botId) return "";
return ` AND bot_id = ${mysql.escape(String(this.botId))}`;
}
_botIdInsert() {
if (!this.botId) return { col: "", val: "" };
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` };
}
static makeTrackIdentifier(track) {
if (!track) return null;
if (track.url) {
try {
const u = new URL(track.url);
return `${u.hostname}${u.pathname}`.replace(/\/+$/, "").toLowerCase().trim();
} catch {
return track.url.toLowerCase().trim();
}
}
const artist = track.artist || track.author?.name || "";
const title = track.title || "";
if (artist && title) return `${artist} - ${title}`.toLowerCase().trim();
if (title) return title.toLowerCase().trim();
return null;
}
async set(userId, track, startMs, endMs) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
if (!identifier) return null;
const title = (track.title || "").slice(0, 512);
const bi = this._botIdInsert();
try {
await this._query(
`INSERT INTO track_options (user_id, track_identifier, track_title, start_ms, end_ms${bi.col})
VALUES (${mysql.escape(userId)}, ${mysql.escape(identifier)}, ${mysql.escape(title)}, ${startMs}, ${endMs}${bi.val})
ON DUPLICATE KEY UPDATE start_ms = ${startMs}, end_ms = ${endMs}, track_title = ${mysql.escape(title)}`
);
this._cache.delete(`${userId}:${identifier}`);
return { identifier, startMs, endMs };
} catch (err) {
logger.error("[TrackOptions] set error:", err.message);
return null;
}
}
async get(userId, track) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
if (!identifier) return null;
const cacheKey = `${userId}:${identifier}`;
if (this._cache.has(cacheKey)) return this._cache.get(cacheKey);
try {
const rows = await this._query(
`SELECT start_ms, end_ms, track_title FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)}${this._botIdWhere()}`
);
if (!rows || rows.length === 0) return null;
const result = { startMs: rows[0].start_ms, endMs: rows[0].end_ms, title: rows[0].track_title };
if (this._cache.size >= this._cacheMaxSize) {
const firstKey = this._cache.keys().next().value;
this._cache.delete(firstKey);
}
this._cache.set(cacheKey, result);
return result;
} catch (err) {
logger.error("[TrackOptions] get error:", err.message);
return null;
}
}
async remove(userId, track) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
if (!identifier) return false;
try {
const result = await this._query(
`DELETE FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)}${this._botIdWhere()}`
);
this._cache.delete(`${userId}:${identifier}`);
return result.affectedRows > 0;
} catch (err) {
logger.error("[TrackOptions] remove error:", err.message);
return false;
}
}
async list(userId, limit = 25) {
await this.ready();
try {
const rows = await this._query(
`SELECT track_identifier, track_title, start_ms, end_ms FROM track_options WHERE user_id = ${mysql.escape(userId)}${this._botIdWhere()} ORDER BY updated_at DESC LIMIT ${Math.min(limit, 100)}`
);
return rows || [];
} catch (err) {
logger.error("[TrackOptions] list error:", err.message);
return [];
}
}
async getBestMatchForChannel(userIds, track) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
if (!identifier || !userIds || userIds.length === 0) return null;
for (const uid of userIds) {
const result = await this.get(uid, track);
if (result) return { ...result, userId: uid };
}
return null;
}
}
+23 -1
View File
@@ -59,7 +59,8 @@
"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."
"autoplay": "Toggle autoplay — automatically play similar tracks when the queue ends.",
"trackopt": "Set custom start/end times for tracks. Great for album compilations and hidden tracks."
},
"options": {
"debug": {
@@ -132,6 +133,9 @@
"move": {
"from": "The current position of the track in the queue (1-based).",
"to": "The target position to move the track to (1-based)."
},
"trackopt": {
"times": "Start and optional end time, e.g. '0:30' or '0:30 3:45'"
}
},
"pagination": {
@@ -585,6 +589,24 @@
"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."
},
"trackopt": {
"notAvailable": "❌ Track options feature is not available.",
"nothingPlaying": "❌ There's nothing playing at the moment!",
"invalidFormat": "❌ Invalid time format. Use `mm:ss`, `hh:mm:ss`, or seconds.",
"invalidEndAfterStart": "❌ End time must be after start time.",
"startExceedsDuration": "❌ Start time exceeds track duration (**{{duration}}**).",
"endExceedsDuration": "❌ End time exceeds track duration (**{{duration}}**).",
"saved": "✅ Track option saved for **{{title}}**\n▶️ Start: **{{start}}** | ⏹️ End: **{{end}}**\n\nThis will apply automatically whenever this track plays in a channel you're in.",
"saveFailed": "❌ Failed to save track option.",
"notSet": "No custom times set for **{{title}}**.",
"current": "📎 Track option for **{{title}}**\n▶️ Start: **{{start}}** | ⏹️ End: **{{end}}**",
"removed": "🗑️ Removed track option for **{{title}}**.",
"notFound": "No custom times found for **{{title}}**.",
"listEmpty": "📭 You have no saved track options. Use `{{prefix}}trackopt set <start> [end]` to add one!",
"listTitle": "📋 **Your Track Options** ({{count}})",
"listEntry": "• **{{title}}** — {{start}} → {{end}}",
"listHint": "Use `{{prefix}}trackopt remove` while a track is playing to delete its option."
}
}
}