feat(player): named aliases for per-track trimming

Extend %trackopt with named aliases — users can now save multiple
trim points per track and switch between them on the fly. Only the
"default" alias auto-applies on playback; others require
%trackopt play <name>.

Idea by noisy EVE
This commit is contained in:
NoLogicAlan committed 2026-05-21 18:31:14 +03:00
1 parent 6bbaf49a94
commit 5ba24bf1df
3 files changed
+219 -43

No files matched your search

+137 -21
View File
@@ -2,29 +2,46 @@ import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
const DEFAULT_ALIAS = "default";
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")
.setDescription("Set custom start/end times for tracks. Supports named aliases — save multiple trims per track for different sections.", "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")
.setDescription("Set a custom start/end time for the current track. Add alias:name for multiple trims.")
.addTextOption(o =>
o.setName("times")
.setDescription("Start and optional end time, e.g. '0:30' or '0:30 3:45'")
.setDescription("Start [end] [alias:name], e.g. '0:30 3:45' or '0:30 3:45 alias:hidden'")
.setRequired(true)
)
)
.addSubcommand(s =>
s.setName("get")
.setId("trackopt_get")
.setDescription("View your custom start/end time for the current track")
.setDescription("View your custom start/end times for the current track")
)
.addSubcommand(s =>
s.setName("play")
.setId("trackopt_play")
.setDescription("Apply a named alias trim to the currently playing track")
.addTextOption(o =>
o.setName("alias")
.setDescription("Name of the alias to play (e.g. 'hidden', 'outro')")
.setRequired(true)
)
)
.addSubcommand(s =>
s.setName("remove")
.setId("trackopt_remove")
.setDescription("Remove your custom start/end time for the current track")
.setDescription("Remove a custom trim for the current track. Specify alias or leave empty for all.")
.addTextOption(o =>
o.setName("alias")
.setDescription("Alias name to remove, or leave empty to remove all trims for this track")
.setRequired(false)
)
)
.addSubcommand(s =>
s.setName("list")
@@ -62,6 +79,17 @@ function formatMs(ms) {
return `${minutes}:${String(seconds).padStart(2, "0")}`;
}
function extractAlias(parts) {
for (let i = 0; i < parts.length; i++) {
if (parts[i].toLowerCase().startsWith("alias:")) {
const aliasVal = parts[i].slice(6);
parts.splice(i, 1);
return aliasVal;
}
}
return DEFAULT_ALIAS;
}
export async function run(msg, data) {
const trackOpts = this.trackOptions;
if (!trackOpts) {
@@ -86,10 +114,12 @@ export async function run(msg, data) {
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`")] });
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 alias:hidden`")] });
}
const parts = timesRaw.trim().split(/\s+/);
const aliasRaw = extractAlias(parts);
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.")] });
@@ -116,40 +146,118 @@ export async function run(msg, data) {
}
}
const result = await trackOpts.set(userId, current, startMs, endMs);
const result = await trackOpts.set(userId, current, startMs, endMs, aliasRaw);
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`;
const aliasLabel = result.alias === DEFAULT_ALIAS ? "" : ` [${result.alias}]`;
let desc = `✅ Track option saved for **${current.title}**${aliasLabel}\n`;
desc += `▶️ Start: **${formatMs(startMs)}**`;
if (endMs > 0) desc += ` | ⏹️ End: **${formatMs(endMs)}**`;
else desc += ` | ⏹️ End: **full track**`;
if (result.alias === DEFAULT_ALIAS) {
desc += `\n\nThis will apply automatically whenever this track plays in a channel you're in.`;
} else {
desc += `\n\nUse \`%trackopt play ${result.alias}\` to apply this trim while the track is playing.`;
}
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
}
if (subCommand === "get") {
const result = await trackOpts.get(userId, current);
if (!result) {
const rows = await trackOpts.getAllForTrack(userId, current);
if (!rows || rows.length === 0) {
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**`;
let desc = `📎 Track options for **${current.title}** (${rows.length})\n\n`;
for (const row of rows) {
const aliasLabel = row.alias === DEFAULT_ALIAS ? "default" : row.alias;
const endStr = row.end_ms > 0 ? formatMs(row.end_ms) : "end";
const autoTag = row.alias === DEFAULT_ALIAS ? " ← auto" : "";
desc += `• **${aliasLabel}** — ${formatMs(row.start_ms)} → ${endStr}${autoTag}\n`;
}
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}**.`)] });
if (subCommand === "play") {
const aliasRaw = data.get("alias")?.value;
if (!aliasRaw) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Provide an alias name. Usage: `%trackopt play hidden`")] });
}
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🗑️ Removed track option for **${current.title}**.`)] });
const safeAlias = aliasRaw.toLowerCase().replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 32);
if (!safeAlias) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Invalid alias name. Use letters, numbers, hyphens, or underscores.")] });
}
const result = await trackOpts.get(userId, current, safeAlias);
if (!result) {
const allAliases = await trackOpts.getAllForTrack(userId, current);
if (allAliases.length > 0) {
const names = allAliases.map(r => r.alias === DEFAULT_ALIAS ? "default" : r.alias).join(", ");
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ No alias **${safeAlias}** found for **${current.title}**.\nYour aliases: ${names}`)] });
}
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ No alias **${safeAlias}** found for **${current.title}**.`)] });
}
if (!p.connection || p._paused) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ The player must be actively playing to apply an alias.")] });
}
try {
if (result.startMs > 0) {
await p.seekToPosition(result.startMs);
}
p._clearTrackEndTimer();
p._activeTrackOpt = null;
if (result.endMs > 0) {
const elapsedMs = Date.now() - p.startedPlaying;
const remainingMs = result.endMs - elapsedMs;
if (remainingMs > 0) {
const match = result;
p._activeTrackOpt = match;
p._trackEndTimer = setTimeout(() => {
if (p._destroyed || p.leaving || !p._activeTrackOpt) return;
logger.player(`[Player] TrackOptions: end time reached (${match.endMs}ms), skipping track`);
p._activeTrackOpt = null;
p._trackEndTimer = null;
p._trackEndRemainingMs = null;
p._skipping = true;
p._stopMediaPlayer().then(() => {
p._doPlayNext();
}).catch(() => {
p._doPlayNext();
});
}, remainingMs);
}
} else {
p._activeTrackOpt = result;
}
const aliasLabel = safeAlias === DEFAULT_ALIAS ? "default" : safeAlias;
const endStr = result.endMs > 0 ? formatMs(result.endMs) : "end";
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`✂️ Applied alias **${aliasLabel}** — ${formatMs(result.startMs)} → ${endStr}`)] });
} catch (e) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to apply alias: ${e.message}`)] });
}
}
if (subCommand === "remove") {
const aliasRaw = data.get("alias")?.value;
const removed = await trackOpts.remove(userId, current, aliasRaw || null);
if (!removed) {
const aliasLabel = aliasRaw ? ` **${aliasRaw}**` : "";
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`No custom times found${aliasLabel} for **${current.title}**.`)] });
}
if (aliasRaw) {
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🗑️ Removed alias **${aliasRaw}** for **${current.title}**.`)] });
}
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🗑️ Removed all track options for **${current.title}**.`)] });
}
if (subCommand === "list") {
@@ -159,12 +267,20 @@ export async function run(msg, data) {
}
let desc = `📋 **Your Track Options** (${rows.length})\n\n`;
let lastTrack = "";
for (const row of rows) {
const title = row.track_title || row.track_identifier;
const aliasLabel = row.alias === DEFAULT_ALIAS ? "default" : row.alias;
const endStr = row.end_ms > 0 ? formatMs(row.end_ms) : "end";
desc += `• **${title}** — ${formatMs(row.start_ms)} → ${endStr}\n`;
if (title !== lastTrack) {
if (lastTrack) desc += "\n";
desc += `🎵 **${title}**\n`;
lastTrack = title;
}
desc += `\nUse \`%trackopt remove\` while a track is playing to delete its option.`;
const autoTag = row.alias === DEFAULT_ALIAS ? " ← auto" : "";
desc += ` • ${aliasLabel}: ${formatMs(row.start_ms)} → ${endStr}${autoTag}\n`;
}
desc += `\nUse \`%trackopt play <alias>\` to apply a named trim, or \`%trackopt remove [alias]\` to delete one.`;
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
}
+68 -18
View File
@@ -1,6 +1,9 @@
import mysql from "mysql2";
import { logger } from "./constants/Logger.mjs";
const DEFAULT_ALIAS = "default";
const MAX_ALIAS_LEN = 32;
export class TrackOptionsManager {
db = null;
botId = null;
@@ -30,14 +33,16 @@ export class TrackOptionsManager {
user_id VARCHAR(32) NOT NULL,
track_identifier VARCHAR(512) NOT NULL,
track_title VARCHAR(512) NOT NULL DEFAULT '',
alias VARCHAR(${MAX_ALIAS_LEN}) NOT NULL DEFAULT '${DEFAULT_ALIAS}',
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)
UNIQUE KEY uq_user_track_alias_bot (user_id, track_identifier, alias, bot_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
);
await this._migrateOldTable();
this._hasTable = true;
this._ready = true;
logger.player("[TrackOptions] Table ready.");
@@ -46,6 +51,19 @@ export class TrackOptionsManager {
}
}
async _migrateOldTable() {
try {
const cols = await this._query(`SHOW COLUMNS FROM track_options LIKE 'alias'`);
if (cols && cols.length > 0) return;
await this._query(`ALTER TABLE track_options ADD COLUMN alias VARCHAR(${MAX_ALIAS_LEN}) NOT NULL DEFAULT '${DEFAULT_ALIAS}' AFTER track_title`);
await this._query(`ALTER TABLE track_options DROP INDEX uq_user_track_bot`);
await this._query(`ALTER TABLE track_options ADD UNIQUE KEY uq_user_track_alias_bot (user_id, track_identifier, alias, bot_id)`);
logger.player("[TrackOptions] Migrated table — added alias column.");
} catch (err) {
logger.warn("[TrackOptions] Migration check:", err.message);
}
}
async setBotId(id) {
this.botId = id;
}
@@ -69,6 +87,12 @@ export class TrackOptionsManager {
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` };
}
static sanitizeAlias(raw) {
if (!raw || typeof raw !== "string") return DEFAULT_ALIAS;
const cleaned = raw.replace(/[^a-zA-Z0-9_-]/g, "").toLowerCase().slice(0, MAX_ALIAS_LEN);
return cleaned || DEFAULT_ALIAS;
}
static makeTrackIdentifier(track) {
if (!track) return null;
if (track.url) {
@@ -86,42 +110,44 @@ export class TrackOptionsManager {
return null;
}
async set(userId, track, startMs, endMs) {
async set(userId, track, startMs, endMs, alias = DEFAULT_ALIAS) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
if (!identifier) return null;
const safeAlias = TrackOptionsManager.sanitizeAlias(alias);
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})
`INSERT INTO track_options (user_id, track_identifier, track_title, alias, start_ms, end_ms${bi.col})
VALUES (${mysql.escape(userId)}, ${mysql.escape(identifier)}, ${mysql.escape(title)}, ${mysql.escape(safeAlias)}, ${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 };
this._cache.delete(`${userId}:${identifier}:${safeAlias}`);
return { identifier, startMs, endMs, alias: safeAlias };
} catch (err) {
logger.error("[TrackOptions] set error:", err.message);
return null;
}
}
async get(userId, track) {
async get(userId, track, alias = DEFAULT_ALIAS) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
if (!identifier) return null;
const cacheKey = `${userId}:${identifier}`;
const safeAlias = TrackOptionsManager.sanitizeAlias(alias);
const cacheKey = `${userId}:${identifier}:${safeAlias}`;
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()}`
`SELECT start_ms, end_ms, track_title, alias FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)} AND alias = ${mysql.escape(safeAlias)}${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 };
const result = { startMs: rows[0].start_ms, endMs: rows[0].end_ms, title: rows[0].track_title, alias: rows[0].alias };
if (this._cache.size >= this._cacheMaxSize) {
const firstKey = this._cache.keys().next().value;
this._cache.delete(firstKey);
@@ -134,16 +160,40 @@ export class TrackOptionsManager {
}
}
async remove(userId, track) {
async getAllForTrack(userId, track) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
if (!identifier) return [];
try {
const rows = await this._query(
`SELECT start_ms, end_ms, track_title, alias FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)}${this._botIdWhere()} ORDER BY alias`
);
return rows || [];
} catch (err) {
logger.error("[TrackOptions] getAllForTrack error:", err.message);
return [];
}
}
async remove(userId, track, alias = null) {
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}`);
let sql;
if (alias) {
const safeAlias = TrackOptionsManager.sanitizeAlias(alias);
sql = `DELETE FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)} AND alias = ${mysql.escape(safeAlias)}${this._botIdWhere()}`;
this._cache.delete(`${userId}:${identifier}:${safeAlias}`);
} else {
sql = `DELETE FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)}${this._botIdWhere()}`;
for (const key of this._cache.keys()) {
if (key.startsWith(`${userId}:${identifier}:`)) this._cache.delete(key);
}
}
const result = await this._query(sql);
return result.affectedRows > 0;
} catch (err) {
logger.error("[TrackOptions] remove error:", err.message);
@@ -155,7 +205,7 @@ export class TrackOptionsManager {
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)}`
`SELECT track_identifier, track_title, alias, start_ms, end_ms FROM track_options WHERE user_id = ${mysql.escape(userId)}${this._botIdWhere()} ORDER BY track_title, alias LIMIT ${Math.min(limit, 100)}`
);
return rows || [];
} catch (err) {
@@ -164,13 +214,13 @@ export class TrackOptionsManager {
}
}
async getBestMatchForChannel(userIds, track) {
async getBestMatchForChannel(userIds, track, alias = DEFAULT_ALIAS) {
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);
const result = await this.get(uid, track, alias);
if (result) return { ...result, userId: uid };
}
return null;
+14 -4
View File
@@ -60,7 +60,7 @@
"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.",
"trackopt": "Set custom start/end times for tracks. Great for album compilations and hidden tracks."
"trackopt": "Set custom start/end times for tracks. Supports named aliases — save multiple trims per track for different sections."
},
"options": {
"debug": {
@@ -597,16 +597,26 @@
"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.",
"saved": "✅ Track option saved for **{{title}}**{{aliasLabel}}\n▶️ Start: **{{start}}** | ⏹️ End: **{{end}}**\n\nThis will apply automatically whenever this track plays in a channel you're in.",
"savedAlias": "✅ Track option saved for **{{title}}** [{{alias}}]\n▶️ Start: **{{start}}** | ⏹️ End: **{{end}}**\n\nUse `{{prefix}}trackopt play {{alias}}` to apply this trim while the track is playing.",
"saveFailed": "❌ Failed to save track option.",
"notSet": "No custom times set for **{{title}}**.",
"current": "📎 Track option for **{{title}}**\n▶️ Start: **{{start}}** | ⏹️ End: **{{end}}**",
"current": "📎 Track options for **{{title}}** ({{count}})",
"currentEntry": "• **{{alias}}** — {{start}} → {{end}}{{autoTag}}",
"removed": "🗑️ Removed track option for **{{title}}**.",
"removedAlias": "🗑️ Removed alias **{{alias}}** for **{{title}}**.",
"removedAll": "🗑️ Removed all track options for **{{title}}**.",
"notFound": "No custom times found for **{{title}}**.",
"aliasNotFound": "❌ No alias **{{alias}}** found for **{{title}}**.\nYour aliases: {{names}}",
"applied": "✂️ Applied alias **{{alias}}** — {{start}} → {{end}}",
"applyFailed": "❌ Failed to apply alias: {{error}}",
"mustBePlaying": "❌ The player must be actively playing to apply an alias.",
"invalidAlias": "❌ Invalid alias name. Use letters, numbers, hyphens, or underscores.",
"provideAlias": "❌ Provide an alias name. Usage: `{{prefix}}trackopt play <alias>`",
"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."
"listHint": "Use `{{prefix}}trackopt play <alias>` to apply a named trim, or `{{prefix}}trackopt remove [alias]` to delete one."
}
}
}