diff --git a/README.md b/README.md index bb8880d..bb00643 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ We believe essential music features should never be locked behind a paywall — * 📈 **Comprehensive Last.fm Suite** — Real-time scrobbling, loved tracks synchronization, artist crowns, server leaderboards, profile cards, and automated similar-track autoplay. * 📑 **Massive Playlist Ingestion** — Asynchronous chunked ingestion for large Spotify and SoundCloud playlists (>100 tracks) with instant playback start on song #1. * 🌐 **Full 8-Language Localization** — English, Arabic, Kurdish (Sorani), Turkish, German, Brazilian Portuguese, Simplified Chinese, and Traditional Chinese. +* 💾 **Personal Saved Playlists & Favorites** — Bookmark favorite tracks (`%fav`) and save custom queue snapshots (`%playlist save `) stored per-user in MySQL for seamless playback across all servers. * 📊 **Community & Personal Music Analytics** — Server leaderboards (`%top`) with custom timeframes (`24h`, `week`, `month`, `year`, `all`, `global`), Server Music Wrapped (`%wrapped`), and personal listening recap profiles (`%mywrapped` / `%top me`) backed by permanent MySQL analytics. * 🛡️ **Hardened Security & Reliability** — Built-in SSRF protection with DNS-rebinding guards (`SafeHttp`) and automated credential redaction (`[REDACTED]`) in owner diagnostics. @@ -97,6 +98,13 @@ The default prefix is `%`. Server administrators can customize the prefix at any | `loop` | — | Toggle repeat mode (`song`, `queue`, or `off`) | `%loop queue` | | `trackopt` | `to` | Configure custom start/end timestamps | `%trackopt set 0:30 3:15` | +### 💾 Personal Playlists & Favorites + +| Command | Aliases | Description | Example | +| :--- | :--- | :--- | :--- | +| `fav` | `favorite`, `favorites`, `bookmark` | Save or remove playing track from personal favorites, list, or play | `%fav` / `%fav play` / `%fav list` | +| `playlist` | `pl`, `playlists` | Save active queue as a named playlist, play, list, or manage personal playlists | `%playlist save chill` / `%playlist play chill` / `%playlist list` | + ### 🎛️ Audio Effects & Filters | Command | Aliases | Description | Example | diff --git a/commands/fav.mjs b/commands/fav.mjs new file mode 100644 index 0000000..784d2d8 --- /dev/null +++ b/commands/fav.mjs @@ -0,0 +1,342 @@ +/** + * @module commands/fav + * @description Bookmark personal favorite tracks and queue them across any server. + */ + +import { CommandBuilder } from "../src/commands/index.mjs"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { Utils, cleanId } from "../src/utils/Utils.mjs"; +import { getGlobalColor, getMessageGuildId } from "../src/ui/index.mjs"; + +const PAGE_SIZE = 10; +const COLOR_PRIMARY = 0xe9196c; +const COLOR_SUCCESS = 0x2ecc71; +const COLOR_ERROR = 0xe74c3c; + +/** @type {CommandBuilder} */ +export const command = new CommandBuilder() + .setName("fav") + .setDescription("Bookmark your favorite tracks and load them into voice channels.", "commands.fav") + .addAliases("favorite", "favorites", "bookmark", "bookmarks") + .setCategory("music") + .addSubcommand((s) => + s + .setName("toggle") + .setId("fav_toggle") + .setDescription("Save or remove the currently playing song from your favorites.") + ) + .addSubcommand((s) => + s + .setName("list") + .setId("fav_list") + .setDescription("View your list of saved favorite tracks.") + .addNumberOption((o) => + o.setName("page").setDescription("Page number to view.").setRequired(false) + ) + ) + .addSubcommand((s) => + s + .setName("play") + .setId("fav_play") + .setDescription("Play all your favorites or a specific track number.") + .addNumberOption((o) => + o.setName("track").setDescription("Track number to play.").setRequired(false) + ) + ) + .addSubcommand((s) => + s + .setName("remove") + .setId("fav_remove") + .setDescription("Remove a track from your favorites by number or title.") + .addTextOption((o) => + o.setName("target").setDescription("Track number or title to remove.").setRequired(true) + ) + ) + .addSubcommand((s) => + s + .setName("clear") + .setId("fav_clear") + .setDescription("Clear all tracks from your personal favorites.") + ); + +/** + * Run handler for the fav command. + * @param {object} msg + * @param {object} [data] + * @returns {Promise} + */ +export async function run(msg, data) { + const pm = this.playlists; + if (!pm) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.fav.notAvailable")); + return msg.reply({ embeds: [embed] }); + } + + const userId = cleanId(msg.author?.id ?? msg.message?.author?.id ?? msg.member?.user?.id ?? msg.user?.id); + const authorName = msg.author?.username ?? msg.message?.author?.username ?? "User"; + const guildId = cleanId(getMessageGuildId(msg)); + const prefix = this.handler.getPrefix(guildId) || "%"; + const embedColor = getGlobalColor() || COLOR_PRIMARY; + + /* Parse raw arguments for text-command dispatch */ + const rawContent = (msg.message?.content || msg.content || "").trim(); + const rawParts = rawContent.split(/\s+/).slice(1); + const firstToken = (rawParts[0] || "").toLowerCase(); + + let sub = data?.command?.name || data?.commandId || ""; + if (!sub || sub === "fav") { + if (["list", "view", "all"].includes(firstToken)) sub = "list"; + else if (["play", "p", "queue"].includes(firstToken)) sub = "play"; + else if (["remove", "delete", "rm", "del"].includes(firstToken)) sub = "remove"; + else if (["clear", "reset"].includes(firstToken)) sub = "clear"; + else if (["add", "save"].includes(firstToken)) sub = "add"; + else sub = "toggle"; + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: PLAY + ------------------------------------------------------------------------- */ + if (sub === "play") { + const p = await this.getPlayer(msg); + if (!p) return; + + const favs = await pm.getFavorites(userId, 250, 0); + if (favs.length === 0) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.fav.empty", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + /* Check if a specific track number was requested */ + let trackNum = data?.get?.("track")?.value; + if (!trackNum && rawParts.length > 1) { + const parsedNum = parseInt(rawParts[1], 10); + if (!isNaN(parsedNum)) trackNum = parsedNum; + } + + if (trackNum != null) { + const idx = parseInt(trackNum, 10) - 1; + if (isNaN(idx) || idx < 0 || idx >= favs.length) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.fav.invalidIndex", { max: favs.length })); + return msg.reply({ embeds: [embed] }); + } + + const target = favs[idx]; + const video = { + videoId: "", + encoded: "", + sourceName: target.source_name || "unknown", + isLive: false, + isStream: false, + title: target.title, + url: target.uri, + thumbnail: target.thumbnail || null, + spotifyUrl: null, + _durationMs: Number(target.duration_ms) || 0, + duration: { + timestamp: Utils.prettifyMS(Number(target.duration_ms) || 0), + seconds: Math.floor((Number(target.duration_ms) || 0) / 1000), + }, + author: { + name: target.author || "Unknown", + url: target.uri || null, + }, + artists: null, + requester: userId, + requesterName: authorName, + }; + + p.addToQueue(video, false); + if (!p.queue.getCurrent()) { + p.playNext().catch((e) => logger.error("[fav] playNext error:", e?.message)); + } + + const embed = new EmbedBuilder() + .setColor(COLOR_SUCCESS) + .setDescription(this.t(msg, "responses.fav.queuedOne", { + title: target.title, + url: target.uri, + })); + return msg.reply({ embeds: [embed] }); + } + + /* Queue all favorite tracks */ + const videos = favs.map((f) => ({ + videoId: "", + encoded: "", + sourceName: f.source_name || "unknown", + isLive: false, + isStream: false, + title: f.title, + url: f.uri, + thumbnail: f.thumbnail || null, + spotifyUrl: null, + _durationMs: Number(f.duration_ms) || 0, + duration: { + timestamp: Utils.prettifyMS(Number(f.duration_ms) || 0), + seconds: Math.floor((Number(f.duration_ms) || 0) / 1000), + }, + author: { + name: f.author || "Unknown", + url: f.uri || null, + }, + artists: null, + requester: userId, + requesterName: authorName, + })); + + p.addManyToQueue(videos, false); + if (!p.queue.getCurrent()) { + p.playNext().catch((e) => logger.error("[fav] playNext error:", e?.message)); + } + + const embed = new EmbedBuilder() + .setColor(COLOR_SUCCESS) + .setDescription(this.t(msg, "responses.fav.queuedAll", { count: videos.length })); + return msg.reply({ embeds: [embed] }); + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: REMOVE + ------------------------------------------------------------------------- */ + if (sub === "remove") { + let target = data?.get?.("target")?.value; + if (!target && rawParts.length > 1) { + target = rawParts.slice(1).join(" "); + } + + if (!target) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.fav.removeUsage", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + const res = await pm.removeFavorite(userId, target); + if (!res.removed || !res.track) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.fav.notFound")); + return msg.reply({ embeds: [embed] }); + } + + const embed = new EmbedBuilder() + .setColor(COLOR_SUCCESS) + .setDescription(this.t(msg, "responses.fav.removed", { + title: res.track.title, + url: res.track.uri, + })); + return msg.reply({ embeds: [embed] }); + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: CLEAR + ------------------------------------------------------------------------- */ + if (sub === "clear") { + const count = await pm.clearFavorites(userId); + const embed = new EmbedBuilder() + .setColor(COLOR_SUCCESS) + .setDescription(this.t(msg, "responses.fav.cleared", { count })); + return msg.reply({ embeds: [embed] }); + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: LIST + ------------------------------------------------------------------------- */ + if (sub === "list") { + const totalCount = await pm.getFavoriteCount(userId); + if (totalCount === 0) { + const embed = new EmbedBuilder() + .setColor(embedColor) + .setAuthor({ name: this.t(msg, "responses.fav.listTitle", { user: authorName }) }) + .setDescription(this.t(msg, "responses.fav.empty", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE)); + let page = data?.get?.("page")?.value; + if (!page && rawParts.length > 1) { + const parsed = parseInt(rawParts[1], 10); + if (!isNaN(parsed)) page = parsed; + } + const safePage = Math.max(1, Math.min(parseInt(page, 10) || 1, totalPages)); + const offset = (safePage - 1) * PAGE_SIZE; + + const favs = await pm.getFavorites(userId, PAGE_SIZE, offset); + + let desc = ""; + favs.forEach((f, i) => { + const num = offset + i + 1; + const dur = Utils.prettifyMS(Number(f.duration_ms) || 0); + const authorText = f.author ? ` • ${f.author}` : ""; + desc += `\`${num}.\` **[${f.title}](${f.uri})**${authorText} \`[${dur}]\`\n`; + }); + + const embed = new EmbedBuilder() + .setColor(embedColor) + .setAuthor({ name: this.t(msg, "responses.fav.listTitle", { user: authorName }) }) + .setDescription(desc || this.t(msg, "responses.fav.empty", { prefix })) + .setFooter({ + text: this.t(msg, "responses.fav.listFooter", { + page: safePage, + totalPages, + total: totalCount, + prefix, + }), + }); + + return msg.reply({ embeds: [embed] }); + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: TOGGLE / DEFAULT + ------------------------------------------------------------------------- */ + const p = await this.getPlayer(msg, false); + const current = p?.queue?.getCurrent(); + + /* If no track is currently playing and user typed plain %fav, show the list */ + if (!current) { + const totalCount = await pm.getFavoriteCount(userId); + if (totalCount === 0) { + const embed = new EmbedBuilder() + .setColor(embedColor) + .setDescription(this.t(msg, "responses.fav.empty", { prefix })); + return msg.reply({ embeds: [embed] }); + } + return run.call(this, msg, { command: { name: "list" } }); + } + + /* Toggle the currently playing track in favorites */ + const toggleRes = await pm.toggleFavorite(userId, current); + + if (toggleRes.action === "limit") { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.fav.limitReached", { max: 250 })); + return msg.reply({ embeds: [embed] }); + } + + if (toggleRes.action === "added") { + const embed = new EmbedBuilder() + .setColor(COLOR_SUCCESS) + .setDescription(this.t(msg, "responses.fav.added", { + title: current.title, + url: current.url || current.uri, + count: toggleRes.count, + })); + return msg.reply({ embeds: [embed] }); + } + + const embed = new EmbedBuilder() + .setColor(COLOR_PRIMARY) + .setDescription(this.t(msg, "responses.fav.removed", { + title: current.title, + url: current.url || current.uri, + })); + return msg.reply({ embeds: [embed] }); +} diff --git a/commands/playlist.mjs b/commands/playlist.mjs new file mode 100644 index 0000000..97a9923 --- /dev/null +++ b/commands/playlist.mjs @@ -0,0 +1,508 @@ +/** + * @module commands/playlist + * @description Save the active queue or manage personal custom playlists across servers. + */ + +import { CommandBuilder } from "../src/commands/index.mjs"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { Utils, cleanId } from "../src/utils/Utils.mjs"; +import { getGlobalColor, getMessageGuildId } from "../src/ui/index.mjs"; +import { MAX_PLAYLISTS_PER_USER, MAX_TRACKS_PER_PLAYLIST } from "../src/services/PlaylistManager.mjs"; + +const PAGE_SIZE = 10; +const COLOR_PRIMARY = 0xe9196c; +const COLOR_SUCCESS = 0x2ecc71; +const COLOR_ERROR = 0xe74c3c; + +/** @type {CommandBuilder} */ +export const command = new CommandBuilder() + .setName("playlist") + .setDescription("Save the current queue or manage your personal custom playlists.", "commands.playlist") + .addAliases("pl", "playlists") + .setCategory("music") + .addSubcommand((s) => + s + .setName("save") + .setId("playlist_save") + .setDescription("Save the current queue as a named personal playlist.") + .addTextOption((o) => + o.setName("name").setDescription("Name for your playlist.").setRequired(true) + ) + ) + .addSubcommand((s) => + s + .setName("play") + .setId("playlist_play") + .setDescription("Queue a previously saved personal playlist.") + .addTextOption((o) => + o.setName("name").setDescription("Name of the playlist to play.").setRequired(true) + ) + ) + .addSubcommand((s) => + s + .setName("list") + .setId("playlist_list") + .setDescription("List all your saved personal playlists.") + .addNumberOption((o) => + o.setName("page").setDescription("Page number to view.").setRequired(false) + ) + ) + .addSubcommand((s) => + s + .setName("show") + .setId("playlist_show") + .setDescription("View the tracks inside a specific playlist.") + .addTextOption((o) => + o.setName("name").setDescription("Name of the playlist to view.").setRequired(true) + ) + .addNumberOption((o) => + o.setName("page").setDescription("Page number of tracks.").setRequired(false) + ) + ) + .addSubcommand((s) => + s + .setName("add") + .setId("playlist_add") + .setDescription("Add the currently playing track to an existing playlist.") + .addTextOption((o) => + o.setName("name").setDescription("Name of the target playlist.").setRequired(true) + ) + ) + .addSubcommand((s) => + s + .setName("remove") + .setId("playlist_remove") + .setDescription("Remove a track from a playlist by its track number.") + .addTextOption((o) => + o.setName("name").setDescription("Name of the playlist.").setRequired(true) + ) + .addNumberOption((o) => + o.setName("index").setDescription("Track number (1-based) to remove.").setRequired(true) + ) + ) + .addSubcommand((s) => + s + .setName("delete") + .setId("playlist_delete") + .setDescription("Delete a saved personal playlist.") + .addTextOption((o) => + o.setName("name").setDescription("Name of the playlist to delete.").setRequired(true) + ) + ); + +/** + * Run handler for the playlist command. + * @param {object} msg + * @param {object} [data] + * @returns {Promise} + */ +export async function run(msg, data) { + const pm = this.playlists; + if (!pm) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.notAvailable")); + return msg.reply({ embeds: [embed] }); + } + + const userId = cleanId(msg.author?.id ?? msg.message?.author?.id ?? msg.member?.user?.id ?? msg.user?.id); + const authorName = msg.author?.username ?? msg.message?.author?.username ?? "User"; + const guildId = cleanId(getMessageGuildId(msg)); + const prefix = this.handler.getPrefix(guildId) || "%"; + const embedColor = getGlobalColor() || COLOR_PRIMARY; + + /* Parse raw text tokens for fallback CLI syntax */ + const rawContent = (msg.message?.content || msg.content || "").trim(); + const rawParts = rawContent.split(/\s+/).slice(1); + const firstToken = (rawParts[0] || "").toLowerCase(); + + let sub = data?.command?.name || data?.commandId || ""; + if (!sub || sub === "playlist") { + if (["save", "create", "new"].includes(firstToken)) sub = "save"; + else if (["play", "p", "load"].includes(firstToken)) sub = "play"; + else if (["list", "all"].includes(firstToken)) sub = "list"; + else if (["show", "view", "info"].includes(firstToken)) sub = "show"; + else if (["add"].includes(firstToken)) sub = "add"; + else if (["remove", "rm"].includes(firstToken)) sub = "remove"; + else if (["delete", "del", "destroy"].includes(firstToken)) sub = "delete"; + else if (rawParts.length > 0) sub = "play"; + else sub = "list"; + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: SAVE + ------------------------------------------------------------------------- */ + if (sub === "save") { + let name = data?.get?.("name")?.value; + if (!name && rawParts.length > 1) { + name = rawParts[1]; + } + + if (!name) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.saveUsage", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + const p = await this.getPlayer(msg, false); + const current = p?.queue?.getCurrent(); + const queued = p?.queue?.data || []; + + const allTracks = []; + if (current) allTracks.push(current); + if (queued.length > 0) allTracks.push(...queued); + + if (allTracks.length === 0) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.emptyQueue", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + const res = await pm.savePlaylist(userId, name, allTracks); + if (!res.success) { + if (res.error === "LIMIT_REACHED") { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.limitReached", { max: MAX_PLAYLISTS_PER_USER })); + return msg.reply({ embeds: [embed] }); + } + if (res.error === "INVALID_NAME") { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.invalidName")); + return msg.reply({ embeds: [embed] }); + } + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.saveFailed")); + return msg.reply({ embeds: [embed] }); + } + + const embed = new EmbedBuilder() + .setColor(COLOR_SUCCESS) + .setDescription(this.t(msg, "responses.playlist.saved", { + name: res.name, + count: res.count, + prefix, + })); + return msg.reply({ embeds: [embed] }); + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: PLAY + ------------------------------------------------------------------------- */ + if (sub === "play") { + let name = data?.get?.("name")?.value; + if (!name && rawParts.length > 1) { + name = rawParts[1]; + } else if (!name && rawParts.length === 1 && !["play", "list"].includes(firstToken)) { + name = rawParts[0]; + } + + if (!name) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.playUsage", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + const playlist = await pm.getPlaylist(userId, name); + if (!playlist) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix })); + return msg.reply({ embeds: [embed] }); + } + + if (!playlist.tracks || playlist.tracks.length === 0) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.playlistEmpty", { name })); + return msg.reply({ embeds: [embed] }); + } + + const p = await this.getPlayer(msg); + if (!p) return; + + const videos = playlist.tracks.map((t) => ({ + videoId: "", + encoded: "", + sourceName: t.sourceName || "unknown", + isLive: false, + isStream: false, + title: t.title, + url: t.uri, + thumbnail: t.thumbnail || null, + spotifyUrl: null, + _durationMs: Number(t.durationMs) || 0, + duration: { + timestamp: Utils.prettifyMS(Number(t.durationMs) || 0), + seconds: Math.floor((Number(t.durationMs) || 0) / 1000), + }, + author: { + name: t.author || "Unknown", + url: t.uri || null, + }, + artists: null, + requester: userId, + requesterName: authorName, + })); + + p.addManyToQueue(videos, false); + if (!p.queue.getCurrent()) { + p.playNext().catch((e) => logger.error("[playlist] playNext error:", e?.message)); + } + + const embed = new EmbedBuilder() + .setColor(COLOR_SUCCESS) + .setDescription(this.t(msg, "responses.playlist.queued", { + name: playlist.name, + count: videos.length, + })); + return msg.reply({ embeds: [embed] }); + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: LIST + ------------------------------------------------------------------------- */ + if (sub === "list") { + const playlists = await pm.listPlaylists(userId); + if (playlists.length === 0) { + const embed = new EmbedBuilder() + .setColor(embedColor) + .setAuthor({ name: this.t(msg, "responses.playlist.listTitle", { user: authorName }) }) + .setDescription(this.t(msg, "responses.playlist.noPlaylists", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + const totalPages = Math.max(1, Math.ceil(playlists.length / PAGE_SIZE)); + let page = data?.get?.("page")?.value; + if (!page && rawParts.length > 1) { + const parsed = parseInt(rawParts[1], 10); + if (!isNaN(parsed)) page = parsed; + } + const safePage = Math.max(1, Math.min(parseInt(page, 10) || 1, totalPages)); + const offset = (safePage - 1) * PAGE_SIZE; + + const slice = playlists.slice(offset, offset + PAGE_SIZE); + + let desc = ""; + slice.forEach((pl, i) => { + const num = offset + i + 1; + desc += `\`${num}.\` **${pl.name}** — \`${pl.trackCount} tracks\`\n`; + }); + + const embed = new EmbedBuilder() + .setColor(embedColor) + .setAuthor({ name: this.t(msg, "responses.playlist.listTitle", { user: authorName }) }) + .setDescription(desc) + .setFooter({ + text: this.t(msg, "responses.playlist.listFooter", { + page: safePage, + totalPages, + total: playlists.length, + max: MAX_PLAYLISTS_PER_USER, + prefix, + }), + }); + + return msg.reply({ embeds: [embed] }); + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: SHOW / VIEW + ------------------------------------------------------------------------- */ + if (sub === "show") { + let name = data?.get?.("name")?.value; + if (!name && rawParts.length > 1) { + name = rawParts[1]; + } + + if (!name) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.showUsage", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + const playlist = await pm.getPlaylist(userId, name); + if (!playlist) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix })); + return msg.reply({ embeds: [embed] }); + } + + const tracks = playlist.tracks || []; + if (tracks.length === 0) { + const embed = new EmbedBuilder() + .setColor(embedColor) + .setDescription(this.t(msg, "responses.playlist.playlistEmpty", { name: playlist.name })); + return msg.reply({ embeds: [embed] }); + } + + const totalPages = Math.max(1, Math.ceil(tracks.length / PAGE_SIZE)); + let page = data?.get?.("page")?.value; + if (!page && rawParts.length > 2) { + const parsed = parseInt(rawParts[2], 10); + if (!isNaN(parsed)) page = parsed; + } + const safePage = Math.max(1, Math.min(parseInt(page, 10) || 1, totalPages)); + const offset = (safePage - 1) * PAGE_SIZE; + + const slice = tracks.slice(offset, offset + PAGE_SIZE); + + let desc = ""; + slice.forEach((t, i) => { + const num = offset + i + 1; + const dur = Utils.prettifyMS(Number(t.durationMs) || 0); + const authorText = t.author ? ` • ${t.author}` : ""; + desc += `\`${num}.\` **[${t.title}](${t.uri})**${authorText} \`[${dur}]\`\n`; + }); + + const embed = new EmbedBuilder() + .setColor(embedColor) + .setAuthor({ name: this.t(msg, "responses.playlist.showTitle", { name: playlist.name }) }) + .setDescription(desc) + .setFooter({ + text: this.t(msg, "responses.playlist.showFooter", { + page: safePage, + totalPages, + total: tracks.length, + name: playlist.name, + prefix, + }), + }); + + return msg.reply({ embeds: [embed] }); + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: ADD + ------------------------------------------------------------------------- */ + if (sub === "add") { + let name = data?.get?.("name")?.value; + if (!name && rawParts.length > 1) { + name = rawParts[1]; + } + + if (!name) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.addUsage", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + const p = await this.getPlayer(msg, false); + const current = p?.queue?.getCurrent(); + + if (!current) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.nothingPlaying")); + return msg.reply({ embeds: [embed] }); + } + + const res = await pm.addToPlaylist(userId, name, current); + if (!res.success) { + if (res.error === "NOT_FOUND") { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix })); + return msg.reply({ embeds: [embed] }); + } + if (res.error === "PLAYLIST_FULL") { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.playlistFull", { max: MAX_TRACKS_PER_PLAYLIST })); + return msg.reply({ embeds: [embed] }); + } + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.addFailed")); + return msg.reply({ embeds: [embed] }); + } + + const embed = new EmbedBuilder() + .setColor(COLOR_SUCCESS) + .setDescription(this.t(msg, "responses.playlist.trackAdded", { + title: current.title, + name: res.name, + count: res.count, + })); + return msg.reply({ embeds: [embed] }); + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: REMOVE + ------------------------------------------------------------------------- */ + if (sub === "remove") { + let name = data?.get?.("name")?.value; + let index = data?.get?.("index")?.value; + + if (!name && rawParts.length > 1) name = rawParts[1]; + if (index == null && rawParts.length > 2) index = parseInt(rawParts[2], 10); + + if (!name || index == null || isNaN(index)) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.removeUsage", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + const res = await pm.removeFromPlaylist(userId, name, index); + if (!res.success) { + if (res.error === "NOT_FOUND") { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix })); + return msg.reply({ embeds: [embed] }); + } + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.invalidIndex")); + return msg.reply({ embeds: [embed] }); + } + + const embed = new EmbedBuilder() + .setColor(COLOR_SUCCESS) + .setDescription(this.t(msg, "responses.playlist.trackRemoved", { + title: res.removedTrack?.title || "Track", + name: res.name, + count: res.count, + })); + return msg.reply({ embeds: [embed] }); + } + + /* ------------------------------------------------------------------------- + SUBCOMMAND: DELETE + ------------------------------------------------------------------------- */ + if (sub === "delete") { + let name = data?.get?.("name")?.value; + if (!name && rawParts.length > 1) { + name = rawParts[1]; + } + + if (!name) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.deleteUsage", { prefix })); + return msg.reply({ embeds: [embed] }); + } + + const deleted = await pm.deletePlaylist(userId, name); + if (!deleted) { + const embed = new EmbedBuilder() + .setColor(COLOR_ERROR) + .setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix })); + return msg.reply({ embeds: [embed] }); + } + + const embed = new EmbedBuilder() + .setColor(COLOR_SUCCESS) + .setDescription(this.t(msg, "responses.playlist.deleted", { name })); + return msg.reply({ embeds: [embed] }); + } +} diff --git a/src/core/Bot.mjs b/src/core/Bot.mjs index b31ab5c..624b774 100644 --- a/src/core/Bot.mjs +++ b/src/core/Bot.mjs @@ -31,6 +31,7 @@ import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs"; import { LastFmManager } from "../services/lastfm/LastFmManager.mjs"; import { FluxerListManager } from "../services/FluxerListManager.mjs"; import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs"; +import { PlaylistManager } from "../services/PlaylistManager.mjs"; import { StatusChannelManager } from "../services/StatusChannelManager.mjs"; import { TrackStats } from "../music/TrackStats.mjs"; import { GuildStats } from "../music/GuildStats.mjs"; @@ -288,6 +289,7 @@ class Remix { this.lastfm = new LastFmManager(config.lastfm, sharedPromisePool); this.fluxerlist = new FluxerListManager(config.fluxerlist); this.trackOptions = new TrackOptionsManager(sharedPool); + this.playlists = new PlaylistManager(sharedPromisePool); this.statusChannel = new StatusChannelManager(this, config.statusChannel); /* Gateway activity timestamps and status tracking */ diff --git a/src/services/PlaylistManager.mjs b/src/services/PlaylistManager.mjs new file mode 100644 index 0000000..4331b95 --- /dev/null +++ b/src/services/PlaylistManager.mjs @@ -0,0 +1,531 @@ +/** + * @module src/services/PlaylistManager + * @description Manages personal saved playlists and track bookmarks (favorites) in MySQL. + * All playlist and bookmark records are keyed per-user, making them accessible across all servers. + */ + +import { logger } from "../core/Logger.mjs"; + +export const MAX_PLAYLISTS_PER_USER = 25; +export const MAX_TRACKS_PER_PLAYLIST = 100; +export const MAX_FAVORITES_PER_USER = 250; +export const MAX_NAME_LENGTH = 32; + +/** + * Sanitize user-provided playlist name. + * @param {string} raw + * @returns {string} + */ +export function sanitizePlaylistName(raw) { + if (!raw || typeof raw !== "string") return ""; + return raw + .trim() + .toLowerCase() + .replace(/[\/\\]/g, "") + .slice(0, MAX_NAME_LENGTH); +} + +/** + * @class PlaylistManager + * @description Provides CRUD operations for user favorites and personal playlists stored in MySQL. + */ +export class PlaylistManager { + /** + * @param {import('mysql2/promise').Pool} pool - Shared promise-based MySQL pool. + */ + constructor(pool) { + this._pool = pool; + this._ready = false; + this._readyPromise = this._ensureTables(); + } + + /** + * Ensure database tables exist. + * @private + * @returns {Promise} + */ + async _ensureTables() { + if (!this._pool) return; + try { + await this._pool.execute(` + CREATE TABLE IF NOT EXISTS \`user_favorites\` ( + \`id\` INT AUTO_INCREMENT PRIMARY KEY, + \`user_id\` VARCHAR(32) NOT NULL, + \`title\` VARCHAR(512) NOT NULL, + \`author\` VARCHAR(255) NOT NULL DEFAULT '', + \`uri\` VARCHAR(1024) NOT NULL, + \`duration_ms\` BIGINT NOT NULL DEFAULT 0, + \`source_name\` VARCHAR(64) NOT NULL DEFAULT '', + \`thumbnail\` VARCHAR(1024) NOT NULL DEFAULT '', + \`created_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY \`uniq_user_uri\` (\`user_id\`, \`uri\`(255)), + INDEX \`idx_user_fav_created\` (\`user_id\`, \`created_at\` DESC) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + `); + + await this._pool.execute(` + CREATE TABLE IF NOT EXISTS \`user_playlists\` ( + \`id\` INT AUTO_INCREMENT PRIMARY KEY, + \`user_id\` VARCHAR(32) NOT NULL, + \`name\` VARCHAR(64) NOT NULL, + \`tracks\` JSON NOT NULL, + \`created_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + \`updated_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY \`uniq_user_pl_name\` (\`user_id\`, \`name\`), + INDEX \`idx_user_pl_updated\` (\`user_id\`, \`updated_at\` DESC) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + `); + + this._ready = true; + logger.info("[PlaylistManager] Database tables initialized successfully."); + } catch (err) { + logger.error("[PlaylistManager] Failed to initialize database tables:", err?.message); + } + } + + /** + * Wait for table initialization. + * @returns {Promise} + */ + async ready() { + if (this._ready) return; + await this._readyPromise; + } + + /* ========================================================================= + FAVORITES / BOOKMARKS API + ========================================================================= */ + + /** + * Add a track to the user's personal favorites. + * @param {string} userId + * @param {object} track + * @returns {Promise<{added: boolean, alreadySaved: boolean, limitReached: boolean, count: number}>} + */ + async addFavorite(userId, track) { + await this.ready(); + if (!this._pool || !userId || !track) { + return { added: false, alreadySaved: false, limitReached: false, count: 0 }; + } + + const count = await this.getFavoriteCount(userId); + if (count >= MAX_FAVORITES_PER_USER) { + return { added: false, alreadySaved: false, limitReached: true, count }; + } + + const title = String(track.title || "Unknown").slice(0, 512); + const author = String(track.author?.name || track.author || "").slice(0, 255); + const uri = String(track.url || track.uri || "").slice(0, 1024); + const durationMs = Number(track._durationMs || track.duration?.seconds * 1000 || 0) || 0; + const sourceName = String(track.sourceName || "unknown").slice(0, 64); + const thumbnail = String(track.thumbnail || "").slice(0, 1024); + + if (!uri) { + return { added: false, alreadySaved: false, limitReached: false, count }; + } + + try { + const [result] = await this._pool.execute(` + INSERT INTO \`user_favorites\` + (\`user_id\`, \`title\`, \`author\`, \`uri\`, \`duration_ms\`, \`source_name\`, \`thumbnail\`) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + \`title\` = VALUES(\`title\`), + \`author\` = VALUES(\`author\`), + \`duration_ms\` = VALUES(\`duration_ms\`), + \`thumbnail\` = VALUES(\`thumbnail\`); + `, [userId, title, author, uri, durationMs, sourceName, thumbnail]); + + /* affectedRows = 1 on insert, 2 on duplicate update, 0 if identical */ + const isNew = result.affectedRows === 1; + const newCount = isNew ? count + 1 : count; + return { added: isNew, alreadySaved: !isNew, limitReached: false, count: newCount }; + } catch (err) { + logger.error("[PlaylistManager] Error adding favorite:", err?.message); + return { added: false, alreadySaved: false, limitReached: false, count }; + } + } + + /** + * Remove a track from user favorites by URI or index. + * @param {string} userId + * @param {string|number} identifier + * @returns {Promise<{removed: boolean, track: object|null}>} + */ + async removeFavorite(userId, identifier) { + await this.ready(); + if (!this._pool || !userId) return { removed: false, track: null }; + + try { + /* If numeric index, resolve track at that position */ + if (typeof identifier === "number" || (/^\d+$/.test(String(identifier).trim()) && !String(identifier).includes("http"))) { + const idx = Math.max(0, parseInt(identifier, 10) - 1); + const favs = await this.getFavorites(userId, 1, idx); + if (favs.length === 0) return { removed: false, track: null }; + + const target = favs[0]; + await this._pool.execute( + "DELETE FROM `user_favorites` WHERE `id` = ? AND `user_id` = ?", + [target.id, userId] + ); + return { removed: true, track: target }; + } + + /* Otherwise match by URI or partial title */ + const query = String(identifier).trim(); + const [rows] = await this._pool.execute(` + SELECT * FROM \`user_favorites\` + WHERE \`user_id\` = ? AND (\`uri\` = ? OR \`title\` LIKE ?) + LIMIT 1 + `, [userId, query, `%${query}%`]); + + if (!rows || rows.length === 0) return { removed: false, track: null }; + + const target = rows[0]; + await this._pool.execute( + "DELETE FROM `user_favorites` WHERE `id` = ? AND `user_id` = ?", + [target.id, userId] + ); + return { removed: true, track: target }; + } catch (err) { + logger.error("[PlaylistManager] Error removing favorite:", err?.message); + return { removed: false, track: null }; + } + } + + /** + * Toggle a track in user favorites (heart/bookmark shortcut). + * @param {string} userId + * @param {object} track + * @returns {Promise<{action: "added"|"removed"|"limit", track: object, count: number}>} + */ + async toggleFavorite(userId, track) { + await this.ready(); + const uri = String(track?.url || track?.uri || "").trim(); + if (!uri) return { action: "removed", track: null, count: 0 }; + + const favs = await this.getFavorites(userId, 500, 0); + const existing = favs.find(f => f.uri === uri); + + if (existing) { + await this.removeFavorite(userId, existing.uri); + return { action: "removed", track: existing, count: Math.max(0, favs.length - 1) }; + } + + const res = await this.addFavorite(userId, track); + if (res.limitReached) { + return { action: "limit", track, count: favs.length }; + } + return { action: "added", track, count: res.count }; + } + + /** + * Get total count of favorites for a user. + * @param {string} userId + * @returns {Promise} + */ + async getFavoriteCount(userId) { + await this.ready(); + if (!this._pool || !userId) return 0; + try { + const [rows] = await this._pool.execute( + "SELECT COUNT(*) AS total FROM `user_favorites` WHERE `user_id` = ?", + [userId] + ); + return Number(rows?.[0]?.total || 0); + } catch (err) { + logger.error("[PlaylistManager] Error counting favorites:", err?.message); + return 0; + } + } + + /** + * Get all favorite tracks for a user with pagination. + * @param {string} userId + * @param {number} [limit=100] + * @param {number} [offset=0] + * @returns {Promise>} + */ + async getFavorites(userId, limit = 100, offset = 0) { + await this.ready(); + if (!this._pool || !userId) return []; + try { + const safeLimit = Math.max(1, Math.min(limit, 500)); + const safeOffset = Math.max(0, offset); + const [rows] = await this._pool.execute(` + SELECT \`id\`, \`title\`, \`author\`, \`uri\`, \`duration_ms\`, \`source_name\`, \`thumbnail\`, \`created_at\` + FROM \`user_favorites\` + WHERE \`user_id\` = ? + ORDER BY \`created_at\` DESC + LIMIT ${safeLimit} OFFSET ${safeOffset} + `, [userId]); + return Array.isArray(rows) ? rows : []; + } catch (err) { + logger.error("[PlaylistManager] Error fetching favorites:", err?.message); + return []; + } + } + + /** + * Clear all favorites for a user. + * @param {string} userId + * @returns {Promise} Number of cleared favorites. + */ + async clearFavorites(userId) { + await this.ready(); + if (!this._pool || !userId) return 0; + try { + const [result] = await this._pool.execute( + "DELETE FROM `user_favorites` WHERE `user_id` = ?", + [userId] + ); + return Number(result.affectedRows || 0); + } catch (err) { + logger.error("[PlaylistManager] Error clearing favorites:", err?.message); + return 0; + } + } + + /* ========================================================================= + PLAYLISTS API + ========================================================================= */ + + /** + * Save a list of tracks as a personal playlist. + * Overwrites if the playlist already exists. + * @param {string} userId + * @param {string} rawName + * @param {Array} rawTracks + * @returns {Promise<{success: boolean, name: string, count: number, isNew: boolean, error?: string}>} + */ + async savePlaylist(userId, rawName, rawTracks) { + await this.ready(); + const name = sanitizePlaylistName(rawName); + if (!name) { + return { success: false, name: "", count: 0, isNew: false, error: "INVALID_NAME" }; + } + + if (!Array.isArray(rawTracks) || rawTracks.length === 0) { + return { success: false, name, count: 0, isNew: false, error: "EMPTY_TRACKS" }; + } + + /* Check playlist count limit if creating new */ + const existing = await this.getPlaylist(userId, name); + if (!existing) { + const allPlaylists = await this.listPlaylists(userId); + if (allPlaylists.length >= MAX_PLAYLISTS_PER_USER) { + return { success: false, name, count: 0, isNew: false, error: "LIMIT_REACHED" }; + } + } + + /* Serialize tracks up to cap */ + const tracksToSave = rawTracks.slice(0, MAX_TRACKS_PER_PLAYLIST).map(t => ({ + title: String(t.title || "Unknown").slice(0, 512), + author: String(t.author?.name || t.author || "").slice(0, 255), + uri: String(t.url || t.uri || ""), + durationMs: Number(t._durationMs || t.duration?.seconds * 1000 || 0) || 0, + sourceName: String(t.sourceName || "unknown").slice(0, 64), + thumbnail: String(t.thumbnail || "").slice(0, 1024), + })).filter(t => t.uri.length > 0); + + if (tracksToSave.length === 0) { + return { success: false, name, count: 0, isNew: false, error: "EMPTY_TRACKS" }; + } + + try { + const jsonStr = JSON.stringify(tracksToSave); + const [res] = await this._pool.execute(` + INSERT INTO \`user_playlists\` (\`user_id\`, \`name\`, \`tracks\`) + VALUES (?, ?, ?) + ON DUPLICATE KEY UPDATE \`tracks\` = VALUES(\`tracks\`), \`updated_at\` = CURRENT_TIMESTAMP; + `, [userId, name, jsonStr]); + + const isNew = res.affectedRows === 1; + return { success: true, name, count: tracksToSave.length, isNew }; + } catch (err) { + logger.error("[PlaylistManager] Error saving playlist:", err?.message); + return { success: false, name, count: 0, isNew: false, error: "DB_ERROR" }; + } + } + + /** + * Get a saved playlist by name. + * @param {string} userId + * @param {string} rawName + * @returns {Promise<{id: number, name: string, tracks: Array, created_at: Date, updated_at: Date}|null>} + */ + async getPlaylist(userId, rawName) { + await this.ready(); + const name = sanitizePlaylistName(rawName); + if (!this._pool || !userId || !name) return null; + + try { + const [rows] = await this._pool.execute( + "SELECT * FROM `user_playlists` WHERE `user_id` = ? AND `name` = ? LIMIT 1", + [userId, name] + ); + if (!rows || rows.length === 0) return null; + + const record = rows[0]; + let tracks = []; + try { + tracks = typeof record.tracks === "string" ? JSON.parse(record.tracks) : (record.tracks || []); + } catch (_) { + tracks = []; + } + return { + id: record.id, + name: record.name, + tracks: Array.isArray(tracks) ? tracks : [], + created_at: record.created_at, + updated_at: record.updated_at, + }; + } catch (err) { + logger.error("[PlaylistManager] Error getting playlist:", err?.message); + return null; + } + } + + /** + * List all saved playlists for a user. + * @param {string} userId + * @returns {Promise>} + */ + async listPlaylists(userId) { + await this.ready(); + if (!this._pool || !userId) return []; + + try { + const [rows] = await this._pool.execute(` + SELECT \`name\`, \`tracks\`, \`created_at\`, \`updated_at\` + FROM \`user_playlists\` + WHERE \`user_id\` = ? + ORDER BY \`updated_at\` DESC + `, [userId]); + + if (!Array.isArray(rows)) return []; + + return rows.map(r => { + let count = 0; + try { + const parsed = typeof r.tracks === "string" ? JSON.parse(r.tracks) : r.tracks; + count = Array.isArray(parsed) ? parsed.length : 0; + } catch (_) { + count = 0; + } + return { + name: r.name, + trackCount: count, + created_at: r.created_at, + updated_at: r.updated_at, + }; + }); + } catch (err) { + logger.error("[PlaylistManager] Error listing playlists:", err?.message); + return []; + } + } + + /** + * Delete a saved playlist by name. + * @param {string} userId + * @param {string} rawName + * @returns {Promise} + */ + async deletePlaylist(userId, rawName) { + await this.ready(); + const name = sanitizePlaylistName(rawName); + if (!this._pool || !userId || !name) return false; + + try { + const [res] = await this._pool.execute( + "DELETE FROM `user_playlists` WHERE `user_id` = ? AND `name` = ?", + [userId, name] + ); + return Number(res.affectedRows || 0) > 0; + } catch (err) { + logger.error("[PlaylistManager] Error deleting playlist:", err?.message); + return false; + } + } + + /** + * Add a single track to an existing playlist. + * @param {string} userId + * @param {string} rawName + * @param {object} track + * @returns {Promise<{success: boolean, name: string, count: number, error?: string}>} + */ + async addToPlaylist(userId, rawName, track) { + await this.ready(); + const name = sanitizePlaylistName(rawName); + if (!name || !track) { + return { success: false, name, count: 0, error: "INVALID_ARG" }; + } + + const playlist = await this.getPlaylist(userId, name); + if (!playlist) { + return { success: false, name, count: 0, error: "NOT_FOUND" }; + } + + if (playlist.tracks.length >= MAX_TRACKS_PER_PLAYLIST) { + return { success: false, name, count: playlist.tracks.length, error: "PLAYLIST_FULL" }; + } + + const uri = String(track.url || track.uri || ""); + if (!uri) return { success: false, name, count: playlist.tracks.length, error: "NO_URI" }; + + playlist.tracks.push({ + title: String(track.title || "Unknown").slice(0, 512), + author: String(track.author?.name || track.author || "").slice(0, 255), + uri, + durationMs: Number(track._durationMs || track.duration?.seconds * 1000 || 0) || 0, + sourceName: String(track.sourceName || "unknown").slice(0, 64), + thumbnail: String(track.thumbnail || "").slice(0, 1024), + }); + + try { + await this._pool.execute( + "UPDATE `user_playlists` SET `tracks` = ?, `updated_at` = CURRENT_TIMESTAMP WHERE `user_id` = ? AND `name` = ?", + [JSON.stringify(playlist.tracks), userId, name] + ); + return { success: true, name, count: playlist.tracks.length }; + } catch (err) { + logger.error("[PlaylistManager] Error adding to playlist:", err?.message); + return { success: false, name, count: playlist.tracks.length, error: "DB_ERROR" }; + } + } + + /** + * Remove a track at 1-based index from a playlist. + * @param {string} userId + * @param {string} rawName + * @param {number} oneBasedIndex + * @returns {Promise<{success: boolean, name: string, removedTrack: object|null, count: number, error?: string}>} + */ + async removeFromPlaylist(userId, rawName, oneBasedIndex) { + await this.ready(); + const name = sanitizePlaylistName(rawName); + const playlist = await this.getPlaylist(userId, name); + if (!playlist) { + return { success: false, name, removedTrack: null, count: 0, error: "NOT_FOUND" }; + } + + const idx = parseInt(oneBasedIndex, 10) - 1; + if (isNaN(idx) || idx < 0 || idx >= playlist.tracks.length) { + return { success: false, name, removedTrack: null, count: playlist.tracks.length, error: "INVALID_INDEX" }; + } + + const removedTrack = playlist.tracks.splice(idx, 1)[0]; + try { + await this._pool.execute( + "UPDATE `user_playlists` SET `tracks` = ?, `updated_at` = CURRENT_TIMESTAMP WHERE `user_id` = ? AND `name` = ?", + [JSON.stringify(playlist.tracks), userId, name] + ); + return { success: true, name, removedTrack, count: playlist.tracks.length }; + } catch (err) { + logger.error("[PlaylistManager] Error removing track from playlist:", err?.message); + return { success: false, name, removedTrack: null, count: playlist.tracks.length, error: "DB_ERROR" }; + } + } +} diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index 3df645c..c256116 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -108,7 +108,9 @@ "statustest": "اختبار تحديثات قناة الحالة العامة والبطاقات المباشرة والحوادث.", "top": "عرض أكثر الأغاني والفنانين تشغيلاً في هذا السيرفر.", "wrapped": "إنشاء ملخص موسيقى المجتمع وإحصائيات الاستماع.", - "mywrapped": "عرض ملخص الموسيقى الشخصي الخاص بك، وأفضل أغانيك، ورتبتك كـ DJ في السيرفر." + "mywrapped": "عرض ملخص الموسيقى الشخصي الخاص بك، وأفضل أغانيك، ورتبتك كـ DJ في السيرفر.", + "fav": "حفظ المسارات المفضلة وتشغيلها في القنوات الصوتية.", + "playlist": "حفظ قائمة الانتظار الحالية أو إدارة قوائم التشغيل المخصصة." }, "options": { "debug": { @@ -1444,6 +1446,50 @@ "noDataOther": "لم يقم {{username}} بتشغيل أي أغانٍ في هذا السيرفر بعد.", "globalNotice": "🌐 إحصائيات عالمية • لم يتم تشغيل أغانٍ في هذا السيرفر بعد", "footer": "مشغل بواسطة Remix Music • {{prefix}}top لمخططات السيرفر" + }, + "fav": { + "notAvailable": "المفضلة الشخصية غير متوفرة (قاعدة البيانات غير متصلة).", + "empty": "ليس لديك أي مسارات مفضلة محفوظة بعد! استخدم `{prefix}fav` أثناء تشغيل أغنية لحفظها.", + "invalidIndex": "رقم المسار غير صالح. يرجى اختيار رقم بين 1 و {max}.", + "queuedOne": "تمت إضافة المسار المفضل إلى قائمة الانتظار: **[{title}]({url})**", + "queuedAll": "تمت إضافة **{count} مسار مفضل** إلى قائمة الانتظار!", + "removeUsage": "الاستخدام: `{prefix}fav remove <الرقم|العنوان>`", + "notFound": "لم يتم العثور على هذا المسار في مفضلتك.", + "removed": "تمت إزالة **[{title}]({url})** من مفضلتك.", + "cleared": "تم مسح جميع المسارات (**{count} مسار**) من مفضلتك.", + "listTitle": "مسارات {user} المفضلة", + "listFooter": "صفحة {page}/{totalPages} • {total} محفوظ • استخدم {prefix}fav play لتشغيل الكل", + "limitReached": "لقد وصلت إلى الحد الأقصى وهو {max} مسار مفضل.", + "added": "⭐ تمت إضافة **[{title}]({url})** إلى مفضلتك! (المجموع: {count})" + }, + "playlist": { + "notAvailable": "قوائم التشغيل الشخصية غير متوفرة (قاعدة البيانات غير متصلة).", + "saveUsage": "الاستخدام: `{prefix}playlist save <الاسم>`", + "playUsage": "الاستخدام: `{prefix}playlist play <الاسم>`", + "showUsage": "الاستخدام: `{prefix}playlist show <الاسم> [الصفحة]`", + "addUsage": "الاستخدام: `{prefix}playlist add <الاسم>`", + "removeUsage": "الاستخدام: `{prefix}playlist remove <الاسم> <رقم_المسار>`", + "deleteUsage": "الاستخدام: `{prefix}playlist delete <الاسم>`", + "emptyQueue": "لا يوجد شيء يتم تشغيله أو في قائمة الانتظار لحفظه! ابدأ بتشغيل الموسيقى أولاً باستخدام `{prefix}play`.", + "limitReached": "لقد وصلت إلى الحد الأقصى وهو {max} قائمة تشغيل مخصصة.", + "invalidName": "اسم قائمة التشغيل غير صالح. يجب أن يتراوح الاسم بين 1 و 32 حرفاً ولا يحتوي على فواصل مائلة.", + "saveFailed": "فشل حفظ قائمة التشغيل. يرجى المحاولة مرة أخرى.", + "saved": "💾 تم حفظ **{count} مسار** في قائمة التشغيل **{name}**! شغلها في أي وقت باستخدام `{prefix}playlist play {name}`.", + "notFound": "لم يتم العثور على قائمة التشغيل **{name}**. استخدم `{prefix}playlist list` لرؤية قوائمك.", + "playlistEmpty": "قائمة التشغيل **{name}** فارغة.", + "queued": "▶️ تم تحميل قائمة التشغيل **{name}** (**{count} مسار**) إلى قائمة الانتظار!", + "listTitle": "قوائم تشغيل {user} المخصصة", + "noPlaylists": "ليس لديك أي قوائم تشغيل محفوظة بعد! استخدم `{prefix}playlist save <الاسم>` لحفظ قائمة الانتظار الحالية.", + "listFooter": "صفحة {page}/{totalPages} • {total}/{max} قائمة تشغيل • للتشغيل: {prefix}playlist play <الاسم>", + "showTitle": "قائمة التشغيل: {name}", + "showFooter": "صفحة {page}/{totalPages} • {total} مسار في {name} • للتشغيل: {prefix}playlist play {name}", + "nothingPlaying": "لا يوجد مسار قيد التشغيل حالياً لإضافته.", + "playlistFull": "وصلت قائمة التشغيل هذه إلى الحد الأقصى وهو {max} مسار.", + "addFailed": "فشل إضافة المسار إلى قائمة التشغيل.", + "trackAdded": "تمت إضافة **{title}** إلى قائمة التشغيل **{name}**! (المجموع: {count} مسار)", + "invalidIndex": "فهرس المسار غير صالح.", + "trackRemoved": "تمت إزالة **{title}** من قائمة التشغيل **{name}**! (المتبقي: {count} مسار)", + "deleted": "🗑️ تم حذف قائمة التشغيل **{name}**." } } } diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index 97a677a..b633bca 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -108,7 +108,9 @@ "statustest": "تاقیکردنەوەی نوێکردنەوەکانی کەناڵی دۆخی گشتی، کارتی ڕاستەوخۆ و ڕووداوەکان.", "top": "بینینی زۆرترین گۆرانییە لێدراوەکان و هونەرمەندە سەرەکییەکان لەم سێرڤەرەدا.", "wrapped": "دروستکردنی پوختەی مۆسیقای کۆمەڵگە و ئامارەکانی گوێگرتن.", - "mywrapped": "پوختەی گوێگرتنی مۆسیقای تایبەتی خۆت، باشترین گۆرانییەکان، و پلەی DJی سێرڤەر ببینە." + "mywrapped": "پوختەی گوێگرتنی مۆسیقای تایبەتی خۆت، باشترین گۆرانییەکان، و پلەی DJی سێرڤەر ببینە.", + "fav": "تۆمارکردنی گۆرانییە دڵخوازەکان و لێدانیان لە کەناڵە دەنگییەکان.", + "playlist": "پاشەکەوتکردنی ڕیزی ئێستا یان بەڕێوەبردنی لیستە تایبەتەکانت." }, "options": { "debug": { @@ -1444,6 +1446,50 @@ "noDataOther": "{{username}} تا ئێستا هیچ گۆرانییەکی لەم سێرڤەرە داوا نەکردووە.", "globalNotice": "🌐 ئاماری جیهانی • تا ئێستا هیچ گۆرانییەک لەم سێرڤەرە لێنەدراوە", "footer": "پشتیوانیکراوە لەلایەن Remix Music • {{prefix}}top بۆ ڕیزبەندیی سێرڤەر" + }, + "fav": { + "notAvailable": "بەشی دڵخوازەکان بەردەست نییە (داتابەیس پەیوەست نەکراوە).", + "empty": "هێشتا هیچ گۆرانییەکی دڵخوازت پاشەکەوت نەکردووە! لە کاتی لێدانی گۆرانیدا `{prefix}fav` بەکاربهێنە بۆ نیشانەکردنی.", + "invalidIndex": "ژمارەی تراک هەڵەیە. تکایە ژمارەیەک لە نێوان 1 و {max} هەڵبژێرە.", + "queuedOne": "تراکی دڵخواز خرایە ڕیزەوە: **[{title}]({url})**", + "queuedAll": "**{count} تراکی دڵخواز** خرانە ڕیزەوە!", + "removeUsage": "بەکارهێنان: `{prefix}fav remove <ژمارە|ناونیشان>`", + "notFound": "ئەو تراکە لە لیستی دڵخوازەکانتدا نەدۆزرایەوە.", + "removed": "**[{title}]({url})** لە دڵخوازەکانت سڕایەوە.", + "cleared": "هەموو **{count} تراکەکە** لە دڵخوازەکانت سڕانەوە.", + "listTitle": "تراکە دڵخوازەکانی {user}", + "listFooter": "پەڕەی {page}/{totalPages} • {total} پاشەکەوتکراو • {prefix}fav play بەکاربهێنە بۆ لێدانی هەمووی", + "limitReached": "گەیشتوویتە ئەوپەڕی سنووری {max} تراکی دڵخواز.", + "added": "⭐ **[{title}]({url})** بۆ دڵخوازەکانت زیادکرا! (کۆی گشتی: {count})" + }, + "playlist": { + "notAvailable": "لیستە کەسییەکان بەردەست نین (داتابەیس پەیوەست نەکراوە).", + "saveUsage": "بەکارهێنان: `{prefix}playlist save <ناو>`", + "playUsage": "بەکارهێنان: `{prefix}playlist play <ناو>`", + "showUsage": "بەکارهێنان: `{prefix}playlist show <ناو> [پەڕە]`", + "addUsage": "بەکارهێنان: `{prefix}playlist add <ناو>`", + "removeUsage": "بەکارهێنان: `{prefix}playlist remove <ناو> <ژمارەی_تراک>`", + "deleteUsage": "بەکارهێنان: `{prefix}playlist delete <ناو>`", + "emptyQueue": "هیچ گۆرانییەک لێنادرێت یان لە ڕیزدا نییە بۆ پاشەکەوتکردن! سەرەتا بە `{prefix}play` گۆرانی لێبدە.", + "limitReached": "گەیشتوویتە ئەوپەڕی سنووری {max} لیستی کەسی.", + "invalidName": "ناوی لیست نادروستە. ناو دەبێت لە نێوان 1 بۆ 32 پیت بێت و هێڵی لاری تێدا نەبێت.", + "saveFailed": "پاشەکەوتکردنی لیست سەرکەوتوو نەبوو. تکایە دووبارە هەوڵبدەرەوە.", + "saved": "💾 **{count} تراک** پاشەکەوت کرا لە لیستی **{name}**! دەتوانی لە هەر کاتێکدا بە `{prefix}playlist play {name}` لێی بدەیتەوە.", + "notFound": "لیستی **{name}** نەدۆزرایەوە. `{prefix}playlist list` بەکاربهێنە بۆ بینینی لیستەکانت.", + "playlistEmpty": "لیستی **{name}** بەتاڵە.", + "queued": "▶️ لیستی **{name}** (**{count} تراک**) خرایە ناو ڕیزەوە!", + "listTitle": "لیستە تایبەتەکانی {user}", + "noPlaylists": "هێشتا هیچ لیستێکت پاشەکەوت نەکردووە! `{prefix}playlist save <ناو>` بەکاربهێنە بۆ پاشەکەوتکردنی ڕیزی ئێستات.", + "listFooter": "پەڕەی {page}/{totalPages} • {total}/{max} لیست • بۆ لێدان: {prefix}playlist play <ناو>", + "showTitle": "لیست: {name}", + "showFooter": "پەڕەی {page}/{totalPages} • {total} تراک لە {name} • بۆ لێدان: {prefix}playlist play {name}", + "nothingPlaying": "لە ئێستادا هیچ تراکێک لێنادرێت بۆ ئەوەی زیاد بکرێت.", + "playlistFull": "ئەم لیستە گەیشتووەتە ئەوپەڕی ڕادەی {max} تراک.", + "addFailed": "زیادکردنی تراک بۆ لیست سەرکەوتوو نەبوو.", + "trackAdded": "**{title}** زیادکرا بۆ لیستی **{name}**! (کۆی گشتی: {count} تراک)", + "invalidIndex": "ژمارەی تراک هەڵەیە.", + "trackRemoved": "**{title}** لە لیستی **{name}** سڕایەوە! ({count} تراک ماوەتەوە)", + "deleted": "🗑️ لیستی **{name}** سڕایەوە." } } } diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index 2bfd5ca..c466f00 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -108,7 +108,9 @@ "statustest": "Öffentliche Statuskanal-Aktualisierungen, Live-Karten und Vorfälle testen.", "top": "Zeige die meistgespielten Songs und Top-Künstler dieses Servers an.", "wrapped": "Erstelle einen Community-Musikrückblick und Hörstatistiken.", - "mywrapped": "Sieh dir deinen persönlichen Musik-Rückblick, Top-Tracks und Server-DJ-Rang an." + "mywrapped": "Sieh dir deinen persönlichen Musik-Rückblick, Top-Tracks und Server-DJ-Rang an.", + "fav": "Lieblingslieder speichern und in Sprachkanälen abspielen.", + "playlist": "Aktuelle Warteschlange speichern oder eigene Playlists verwalten." }, "options": { "debug": { @@ -1444,6 +1446,50 @@ "noDataOther": "{{username}} hat auf diesem Server noch keine Songs abgespielt.", "globalNotice": "🌐 Globale Statistiken • Noch keine Songs auf diesem Server", "footer": "Unterstützt von Remix Music • {{prefix}}top für Server-Charts" + }, + "fav": { + "notAvailable": "Persönliche Favoriten sind nicht verfügbar (Datenbank getrennt).", + "empty": "Du hast noch keine Favoriten gespeichert! Nutze `{prefix}fav`, während ein Song läuft, um ihn zu speichern.", + "invalidIndex": "Ungültige Titelnummer. Bitte wähle eine Zahl zwischen 1 und {max}.", + "queuedOne": "Favoritentitel zur Warteschlange hinzugefügt: **[{title}]({url})**", + "queuedAll": "**{count} Favoritentitel** zur Warteschlange hinzugefügt!", + "removeUsage": "Verwendung: `{prefix}fav remove `", + "notFound": "Dieser Titel wurde in deinen Favoriten nicht gefunden.", + "removed": "**[{title}]({url})** aus deinen Favoriten entfernt.", + "cleared": "Alle **{count} Titel** aus deinen Favoriten gelöscht.", + "listTitle": "Favoritentitel von {user}", + "listFooter": "Seite {page}/{totalPages} • {total} gespeichert • Nutze {prefix}fav play, um alle abzuspielen", + "limitReached": "Du hast das Limit von {max} Favoritentiteln erreicht.", + "added": "⭐ **[{title}]({url})** zu deinen Favoriten hinzugefügt! (Gesamt: {count})" + }, + "playlist": { + "notAvailable": "Eigene Playlists sind nicht verfügbar (Datenbank getrennt).", + "saveUsage": "Verwendung: `{prefix}playlist save `", + "playUsage": "Verwendung: `{prefix}playlist play `", + "showUsage": "Verwendung: `{prefix}playlist show [Seite]`", + "addUsage": "Verwendung: `{prefix}playlist add `", + "removeUsage": "Verwendung: `{prefix}playlist remove `", + "deleteUsage": "Verwendung: `{prefix}playlist delete `", + "emptyQueue": "Es wird nichts abgespielt und die Warteschlange ist leer! Starte zuerst Musik mit `{prefix}play`.", + "limitReached": "Du hast das Limit von {max} eigenen Playlists erreicht.", + "invalidName": "Ungültiger Playlist-Name. Namen müssen 1–32 Zeichen lang sein und dürfen keine Schrägstriche enthalten.", + "saveFailed": "Playlist konnte nicht gespeichert werden. Bitte versuche es erneut.", + "saved": "💾 **{count} Titel** in Playlist **{name}** gespeichert! Spiele sie jederzeit mit `{prefix}playlist play {name}` ab.", + "notFound": "Playlist **{name}** wurde nicht gefunden. Nutze `{prefix}playlist list`, um deine Playlists zu sehen.", + "playlistEmpty": "Playlist **{name}** ist leer.", + "queued": "▶️ Playlist **{name}** (**{count} Titel**) in die Warteschlange geladen!", + "listTitle": "Eigene Playlists von {user}", + "noPlaylists": "Du hast noch keine Playlists gespeichert! Nutze `{prefix}playlist save `, um die Warteschlange zu speichern.", + "listFooter": "Seite {page}/{totalPages} • {total}/{max} Playlists • Abspielen mit: {prefix}playlist play ", + "showTitle": "Playlist: {name}", + "showFooter": "Seite {page}/{totalPages} • {total} Titel in {name} • Abspielen mit: {prefix}playlist play {name}", + "nothingPlaying": "Aktuell wird kein Song abgespielt, der hinzugefügt werden könnte.", + "playlistFull": "Diese Playlist hat das Maximum von {max} Titeln erreicht.", + "addFailed": "Titel konnte nicht zur Playlist hinzugefügt werden.", + "trackAdded": "**{title}** zur Playlist **{name}** hinzugefügt! (Gesamt: {count} Titel)", + "invalidIndex": "Ungültiger Titel-Index.", + "trackRemoved": "**{title}** aus Playlist **{name}** entfernt! ({count} Titel verbleibend)", + "deleted": "🗑️ Playlist **{name}** gelöscht." } } } diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index 0607eab..ccf2bac 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -108,7 +108,9 @@ "statustest": "Test public status channel updates, live cards, and incidents.", "top": "View the most played songs and top artists in this server.", "wrapped": "Generate a community music recap and listening statistics.", - "mywrapped": "View your personal music listening recap, top tracks, and server DJ rank." + "mywrapped": "View your personal music listening recap, top tracks, and server DJ rank.", + "fav": "Bookmark your favorite tracks and load them into voice channels.", + "playlist": "Save the current queue or manage your personal custom playlists." }, "options": { "debug": { @@ -1444,6 +1446,50 @@ "noDataOther": "{{username}} hasn't queued any songs in this server yet.", "globalNotice": "🌐 Global Stats • No songs queued on this server yet", "footer": "Powered by Remix Music • {{prefix}}top for server charts" + }, + "fav": { + "notAvailable": "Personal favorites are not available (database disconnected).", + "empty": "You have no saved favorites yet! Use `{prefix}fav` while a song is playing to bookmark it.", + "invalidIndex": "Invalid track number. Please choose a number between 1 and {max}.", + "queuedOne": "Added favorite track to the queue: **[{title}]({url})**", + "queuedAll": "Added **{count} favorite track(s)** to the queue!", + "removeUsage": "Usage: `{prefix}fav remove `", + "notFound": "Could not find that track in your favorites.", + "removed": "Removed **[{title}]({url})** from your favorites.", + "cleared": "Cleared all **{count} track(s)** from your favorites.", + "listTitle": "{user}'s Favorite Tracks", + "listFooter": "Page {page}/{totalPages} • {total} saved • Use {prefix}fav play to queue all", + "limitReached": "You have reached the maximum limit of {max} favorite tracks.", + "added": "⭐ Added **[{title}]({url})** to your favorites! (Total: {count})" + }, + "playlist": { + "notAvailable": "Personal playlists are not available (database disconnected).", + "saveUsage": "Usage: `{prefix}playlist save `", + "playUsage": "Usage: `{prefix}playlist play `", + "showUsage": "Usage: `{prefix}playlist show [page]`", + "addUsage": "Usage: `{prefix}playlist add `", + "removeUsage": "Usage: `{prefix}playlist remove `", + "deleteUsage": "Usage: `{prefix}playlist delete `", + "emptyQueue": "There is nothing playing or in the queue to save! Start playing music first with `{prefix}play`.", + "limitReached": "You have reached the limit of {max} custom playlists.", + "invalidName": "Invalid playlist name. Names must be 1–32 characters and cannot contain slashes.", + "saveFailed": "Failed to save playlist. Please try again.", + "saved": "💾 Saved **{count} track(s)** to playlist **{name}**! Play it anytime with `{prefix}playlist play {name}`.", + "notFound": "Playlist **{name}** was not found. Use `{prefix}playlist list` to see your playlists.", + "playlistEmpty": "Playlist **{name}** is empty.", + "queued": "▶️ Loaded playlist **{name}** (**{count} tracks**) into the queue!", + "listTitle": "{user}'s Custom Playlists", + "noPlaylists": "You have no saved playlists yet! Use `{prefix}playlist save ` to save your current queue.", + "listFooter": "Page {page}/{totalPages} • {total}/{max} playlists • Play with {prefix}playlist play ", + "showTitle": "Playlist: {name}", + "showFooter": "Page {page}/{totalPages} • {total} tracks in {name} • Play with {prefix}playlist play {name}", + "nothingPlaying": "There is no track currently playing to add.", + "playlistFull": "This playlist has reached the maximum cap of {max} tracks.", + "addFailed": "Failed to add track to playlist.", + "trackAdded": "Added **{title}** to playlist **{name}**! (Total: {count} tracks)", + "invalidIndex": "Invalid track index.", + "trackRemoved": "Removed **{title}** from playlist **{name}**! ({count} tracks remaining)", + "deleted": "🗑️ Deleted playlist **{name}**." } } } diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index a1fba6a..fb28fc9 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -108,7 +108,9 @@ "statustest": "Testar atualizações do canal de status público, cartões ao vivo e incidentes.", "top": "Veja as músicas e os artistas mais tocados neste servidor.", "wrapped": "Gere uma retrospectiva musical e estatísticas da comunidade.", - "mywrapped": "Veja sua retrospectiva musical pessoal, melhores faixas e classificação de DJ no servidor." + "mywrapped": "Veja sua retrospectiva musical pessoal, melhores faixas e classificação de DJ no servidor.", + "fav": "Salve suas músicas favoritas e reproduza-as em canais de voz.", + "playlist": "Salve a fila atual ou gerencie suas playlists personalizadas." }, "options": { "debug": { @@ -1444,6 +1446,50 @@ "noDataOther": "{{username}} ainda não colocou músicas na fila neste servidor.", "globalNotice": "🌐 Estatísticas Globais • Nenhuma música tocada neste servidor ainda", "footer": "Desenvolvido por Remix Music • {{prefix}}top para paradas do servidor" + }, + "fav": { + "notAvailable": "Favoritos pessoais indisponíveis (banco de dados desconectado).", + "empty": "Você ainda não possui favoritos salvos! Use `{prefix}fav` enquanto uma música toca para favoritá-la.", + "invalidIndex": "Número de faixa inválido. Escolha um número entre 1 e {max}.", + "queuedOne": "Música favorita adicionada à fila: **[{title}]({url})**", + "queuedAll": "**{count} música(s) favorita(s)** adicionada(s) à fila!", + "removeUsage": "Uso: `{prefix}fav remove `", + "notFound": "Essa música não foi encontrada nos seus favoritos.", + "removed": "Removido **[{title}]({url})** dos seus favoritos.", + "cleared": "Todas as **{count} música(s)** foram removidas dos seus favoritos.", + "listTitle": "Músicas Favoritas de {user}", + "listFooter": "Página {page}/{totalPages} • {total} salvas • Use {prefix}fav play para tocar todas", + "limitReached": "Você atingiu o limite máximo de {max} músicas favoritas.", + "added": "⭐ **[{title}]({url})** adicionada aos seus favoritos! (Total: {count})" + }, + "playlist": { + "notAvailable": "Playlists pessoais indisponíveis (banco de dados desconectado).", + "saveUsage": "Uso: `{prefix}playlist save `", + "playUsage": "Uso: `{prefix}playlist play `", + "showUsage": "Uso: `{prefix}playlist show [página]`", + "addUsage": "Uso: `{prefix}playlist add `", + "removeUsage": "Uso: `{prefix}playlist remove `", + "deleteUsage": "Uso: `{prefix}playlist delete `", + "emptyQueue": "Nada está tocando ou na fila para salvar! Toque alguma música primeiro com `{prefix}play`.", + "limitReached": "Você atingiu o limite máximo de {max} playlists personalizadas.", + "invalidName": "Nome de playlist inválido. Deve ter entre 1 e 32 caracteres e não conter barras.", + "saveFailed": "Falha ao salvar a playlist. Tente novamente.", + "saved": "💾 **{count} música(s)** salvas na playlist **{name}**! Toque quando quiser com `{prefix}playlist play {name}`.", + "notFound": "Playlist **{name}** não encontrada. Use `{prefix}playlist list` para ver suas playlists.", + "playlistEmpty": "A playlist **{name}** está vazia.", + "queued": "▶️ Playlist **{name}** (**{count} faixas**) carregada na fila!", + "listTitle": "Playlists Personalizadas de {user}", + "noPlaylists": "Você ainda não tem playlists salvas! Use `{prefix}playlist save ` para salvar a fila atual.", + "listFooter": "Página {page}/{totalPages} • {total}/{max} playlists • Toque com: {prefix}playlist play ", + "showTitle": "Playlist: {name}", + "showFooter": "Página {page}/{totalPages} • {total} faixas em {name} • Toque com: {prefix}playlist play {name}", + "nothingPlaying": "Nenhuma música tocando no momento para adicionar.", + "playlistFull": "Esta playlist atingiu o limite máximo de {max} faixas.", + "addFailed": "Falha ao adicionar música à playlist.", + "trackAdded": "**{title}** adicionada à playlist **{name}**! (Total: {count} faixas)", + "invalidIndex": "Índice de faixa inválido.", + "trackRemoved": "**{title}** removida da playlist **{name}**! ({count} faixas restantes)", + "deleted": "🗑️ Playlist **{name}** excluída." } } } diff --git a/storage/locales/bot/tr.json b/storage/locales/bot/tr.json index b679e04..3732656 100644 --- a/storage/locales/bot/tr.json +++ b/storage/locales/bot/tr.json @@ -108,7 +108,9 @@ "statustest": "Herkese açık durum kanalı güncellemelerini, canlı kartları ve olayları test edin.", "top": "Bu sunucuda en çok çalınan şarkıları ve en popüler sanatçıları görüntüleyin.", "wrapped": "Bir topluluk müzik özeti ve dinleme istatistikleri oluşturun.", - "mywrapped": "Kişisel müzik özetinizi, en çok dinlenen parçalarınızı ve sunucu DJ sıralamanızı görüntüleyin." + "mywrapped": "Kişisel müzik özetinizi, en çok dinlenen parçalarınızı ve sunucu DJ sıralamanızı görüntüleyin.", + "fav": "Favori parçalarınızı kaydedin ve ses kanallarına yükleyin.", + "playlist": "Mevcut sırayı kaydedin veya kişisel çalma listelerinizi yönetin." }, "options": { "debug": { @@ -1444,6 +1446,50 @@ "noDataOther": "{{username}} bu sunucuda henüz şarkı çalmadı.", "globalNotice": "🌐 Küresel İstatistikler • Bu sunucuda henüz şarkı çalınmadı", "footer": "Remix Music tarafından desteklenmektedir • Sunucu listeleri için {{prefix}}top" + }, + "fav": { + "notAvailable": "Kişisel favoriler kullanılamıyor (veritabanı bağlantısı kesildi).", + "empty": "Henüz kayıtlı favoriniz yok! Çalmakta olan bir şarkıyı favorilere eklemek için `{prefix}fav` kullanın.", + "invalidIndex": "Geçersiz parça numarası. Lütfen 1 ile {max} arasında bir sayı seçin.", + "queuedOne": "Favori parça sıraya eklendi: **[{title}]({url})**", + "queuedAll": "**{count} favori parça** sıraya eklendi!", + "removeUsage": "Kullanım: `{prefix}fav remove `", + "notFound": "Bu parça favorilerinizde bulunamadı.", + "removed": "**[{title}]({url})** favorilerinizden kaldırıldı.", + "cleared": "Tüm **{count} parça** favorilerinizden temizlendi.", + "listTitle": "{user} kullanıcısının Favori Parçaları", + "listFooter": "Sayfa {page}/{totalPages} • {total} kayıtlı • Hepsini çalmak için {prefix}fav play kullanın", + "limitReached": "Maksimum {max} favori parça sınırına ulaştınız.", + "added": "⭐ **[{title}]({url})** favorilerinize eklendi! (Toplam: {count})" + }, + "playlist": { + "notAvailable": "Kişisel çalma listeleri kullanılamıyor (veritabanı bağlantısı kesildi).", + "saveUsage": "Kullanım: `{prefix}playlist save `", + "playUsage": "Kullanım: `{prefix}playlist play `", + "showUsage": "Kullanım: `{prefix}playlist show [sayfa]`", + "addUsage": "Kullanım: `{prefix}playlist add `", + "removeUsage": "Kullanım: `{prefix}playlist remove `", + "deleteUsage": "Kullanım: `{prefix}playlist delete `", + "emptyQueue": "Kaydedilecek hiçbir şey çalmıyor veya sırada parça yok! Önce `{prefix}play` ile müzik başlatın.", + "limitReached": "Maksimum {max} özel çalma listesi sınırına ulaştınız.", + "invalidName": "Geçersiz çalma listesi adı. İsimler 1-32 karakter olmalı ve eğik çizgi içermemelidir.", + "saveFailed": "Çalma listesi kaydedilemedi. Lütfen tekrar deneyin.", + "saved": "💾 **{count} parça** **{name}** listesine kaydedildi! `{prefix}playlist play {name}` ile dilediğiniz zaman çalın.", + "notFound": "**{name}** isimli çalma listesi bulunamadı. Listelerinizi görmek için `{prefix}playlist list` kullanın.", + "playlistEmpty": "**{name}** çalma listesi boş.", + "queued": "▶️ **{name}** listesinden **{count} parça** sıraya yüklendi!", + "listTitle": "{user} kullanıcısının Özel Çalma Listeleri", + "noPlaylists": "Henüz kayıtlı çalma listeniz yok! Mevcut sırayı kaydetmek için `{prefix}playlist save ` kullanın.", + "listFooter": "Sayfa {page}/{totalPages} • {total}/{max} liste • Çalmak için: {prefix}playlist play ", + "showTitle": "Çalma Listesi: {name}", + "showFooter": "Sayfa {page}/{totalPages} • {name} içinde {total} parça • Çalmak için: {prefix}playlist play {name}", + "nothingPlaying": "Eklemek için şu anda çalan bir parça yok.", + "playlistFull": "Bu çalma listesi maksimum {max} parça sınırına ulaştı.", + "addFailed": "Parça çalma listesine eklenemedi.", + "trackAdded": "**{title}**, **{name}** listesine eklendi! (Toplam: {count} parça)", + "invalidIndex": "Geçersiz parça indeksi.", + "trackRemoved": "**{title}**, **{name}** listesinden kaldırıldı! ({count} parça kaldı)", + "deleted": "🗑️ **{name}** çalma listesi silindi." } } } diff --git a/storage/locales/bot/zh-CN.json b/storage/locales/bot/zh-CN.json index c3264bb..b6a5531 100644 --- a/storage/locales/bot/zh-CN.json +++ b/storage/locales/bot/zh-CN.json @@ -108,7 +108,9 @@ "statustest": "测试公开状态频道更新、实时卡片和事件报告。", "top": "查看此服务器中播放次数最多的歌曲和热门艺术家。", "wrapped": "生成社区音乐回顾和收听统计数据。", - "mywrapped": "查看您的个人音乐回顾、最爱曲目和服务器 DJ 排名。" + "mywrapped": "查看您的个人音乐回顾、最爱曲目和服务器 DJ 排名。", + "fav": "收藏您喜爱的音乐并在语音频道中播放。", + "playlist": "保存当前队列或管理您的个人自定义歌单。" }, "options": { "debug": { @@ -1444,6 +1446,50 @@ "noDataOther": "{{username}} 在此服务器上尚未播放过歌曲。", "globalNotice": "🌐 全球统计 • 此服务器上尚未播放过歌曲", "footer": "由 Remix Music 提供支持 • 输入 {{prefix}}top 查看服务器排行榜" + }, + "fav": { + "notAvailable": "个人收藏暂不可用(数据库未连接)。", + "empty": "您还没有收藏任何歌曲!在歌曲播放时使用 `{prefix}fav` 即可收藏。", + "invalidIndex": "无效的歌曲编号。请选择 1 到 {max} 之间的数字。", + "queuedOne": "已将收藏歌曲加入队列:**[{title}]({url})**", + "queuedAll": "已将 **{count} 首收藏歌曲**加入队列!", + "removeUsage": "用法:`{prefix}fav remove <编号|歌名>`", + "notFound": "在您的收藏中未找到该歌曲。", + "removed": "已从收藏中移除 **[{title}]({url})**。", + "cleared": "已清空收藏中的全部 **{count} 首歌曲**。", + "listTitle": "{user} 的收藏音乐", + "listFooter": "第 {page}/{totalPages} 页 • 已收藏 {total} 首 • 使用 {prefix}fav play 播放全部", + "limitReached": "您已达到 {max} 首收藏歌曲的上限。", + "added": "⭐ 已将 **[{title}]({url})** 添加到您的收藏!(总计:{count})" + }, + "playlist": { + "notAvailable": "个人歌单暂不可用(数据库未连接)。", + "saveUsage": "用法:`{prefix}playlist save <名称>`", + "playUsage": "用法:`{prefix}playlist play <名称>`", + "showUsage": "用法:`{prefix}playlist show <名称> [页码]`", + "addUsage": "用法:`{prefix}playlist add <名称>`", + "removeUsage": "用法:`{prefix}playlist remove <名称> <序号>`", + "deleteUsage": "用法:`{prefix}playlist delete <名称>`", + "emptyQueue": "当前没有正在播放或排队的歌曲可供保存!请先使用 `{prefix}play` 播放音乐。", + "limitReached": "您已达到 {max} 个自定义歌单的上限。", + "invalidName": "无效的歌单名称。名称长度必须在 1–32 个字符之间且不能包含斜杠。", + "saveFailed": "保存歌单失败,请重试。", + "saved": "💾 已将 **{count} 首歌曲**保存到歌单 **{name}**!随时使用 `{prefix}playlist play {name}` 播放。", + "notFound": "未找到歌单 **{name}**。使用 `{prefix}playlist list` 查看您的所有歌单。", + "playlistEmpty": "歌单 **{name}** 是空的。", + "queued": "▶️ 已将歌单 **{name}**(**{count} 首歌曲**)加载到播放队列!", + "listTitle": "{user} 的自定义歌单", + "noPlaylists": "您还没有保存任何歌单!使用 `{prefix}playlist save <名称>` 保存当前队列。", + "listFooter": "第 {page}/{totalPages} 页 • {total}/{max} 个歌单 • 播放:{prefix}playlist play <名称>", + "showTitle": "歌单:{name}", + "showFooter": "第 {page}/{totalPages} 页 • {name} 共有 {total} 首歌曲 • 播放:{prefix}playlist play {name}", + "nothingPlaying": "当前没有正在播放的歌曲可供添加。", + "playlistFull": "该歌单已达到 {max} 首歌曲的上限。", + "addFailed": "添加歌曲到歌单失败。", + "trackAdded": "已将 **{title}** 添加到歌单 **{name}**!(共 {count} 首)", + "invalidIndex": "无效的歌曲编号。", + "trackRemoved": "已从歌单 **{name}** 移除 **{title}**!(剩余 {count} 首)", + "deleted": "🗑️ 已删除歌单 **{name}**。" } } } diff --git a/storage/locales/bot/zh-TW.json b/storage/locales/bot/zh-TW.json index 5861057..bc79bdb 100644 --- a/storage/locales/bot/zh-TW.json +++ b/storage/locales/bot/zh-TW.json @@ -108,7 +108,9 @@ "statustest": "測試公開狀態頻道更新、即時卡片與事件報告。", "top": "檢視此伺服器中播放次數最多的歌曲和熱門演出者。", "wrapped": "產生社群音樂回顧和收聽統計資料。", - "mywrapped": "查看您的個人音樂回顧、最愛曲目和伺服器 DJ 排名。" + "mywrapped": "查看您的個人音樂回顧、最愛曲目和伺服器 DJ 排名。", + "fav": "收藏您喜愛的音樂並在語音頻道中播放。", + "playlist": "儲存目前佇列或管理您的個人自訂播放清單。" }, "options": { "debug": { @@ -1444,6 +1446,50 @@ "noDataOther": "{{username}} 在此伺服器上尚未播放過歌曲。", "globalNotice": "🌐 全球統計 • 此伺服器上尚未播放過歌曲", "footer": "由 Remix Music 提供支援 • 輸入 {{prefix}}top 查看伺服器排行榜" + }, + "fav": { + "notAvailable": "個人收藏暫不可用(資料庫未連線)。", + "empty": "您尚未收藏任何歌曲!在歌曲播放時使用 `{prefix}fav` 即可收藏。", + "invalidIndex": "無效的歌曲編號。請選擇 1 到 {max} 之間的數字。", + "queuedOne": "已將收藏歌曲加入佇列:**[{title}]({url})**", + "queuedAll": "已將 **{count} 首收藏歌曲**加入佇列!", + "removeUsage": "用法:`{prefix}fav remove <編號|歌名>`", + "notFound": "在您的收藏中未找到該歌曲。", + "removed": "已從收藏中移除 **[{title}]({url})**。", + "cleared": "已清空收藏中的全部 **{count} 首歌曲**。", + "listTitle": "{user} 的收藏音樂", + "listFooter": "第 {page}/{totalPages} 頁 • 已收藏 {total} 首 • 使用 {prefix}fav play 播放全部", + "limitReached": "您已達到 {max} 首收藏歌曲的上限。", + "added": "⭐ 已將 **[{title}]({url})** 加入您的收藏!(總計:{count})" + }, + "playlist": { + "notAvailable": "個人播放清單暫不可用(資料庫未連線)。", + "saveUsage": "用法:`{prefix}playlist save <名稱>`", + "playUsage": "用法:`{prefix}playlist play <名稱>`", + "showUsage": "用法:`{prefix}playlist show <名稱> [頁碼]`", + "addUsage": "用法:`{prefix}playlist add <名稱>`", + "removeUsage": "用法:`{prefix}playlist remove <名稱> <序號>`", + "deleteUsage": "用法:`{prefix}playlist delete <名稱>`", + "emptyQueue": "目前沒有正在播放或佇列中的歌曲可儲存!請先使用 `{prefix}play` 播放音樂。", + "limitReached": "您已達到 {max} 個自訂播放清單的上限。", + "invalidName": "無效的播放清單名稱。名稱長度必須在 1–32 個字元之間且不能包含斜線。", + "saveFailed": "儲存播放清單失敗,請重試。", + "saved": "💾 已將 **{count} 首歌曲**儲存至播放清單 **{name}**!隨時使用 `{prefix}playlist play {name}` 播放。", + "notFound": "未找到播放清單 **{name}**。使用 `{prefix}playlist list` 查看您的所有播放清單。", + "playlistEmpty": "播放清單 **{name}** 是空的。", + "queued": "▶️ 已將播放清單 **{name}**(**{count} 首歌曲**)載入播放佇列!", + "listTitle": "{user} 的自訂播放清單", + "noPlaylists": "您尚未儲存任何播放清單!使用 `{prefix}playlist save <名稱>` 儲存目前的佇列。", + "listFooter": "第 {page}/{totalPages} 頁 • {total}/{max} 個播放清單 • 播放:{prefix}playlist play <名稱>", + "showTitle": "播放清單:{name}", + "showFooter": "第 {page}/{totalPages} 頁 • {name} 共有 {total} 首歌曲 • 播放:{prefix}playlist play {name}", + "nothingPlaying": "目前沒有正在播放的歌曲可供加入。", + "playlistFull": "該播放清單已達到 {max} 首歌曲的上限。", + "addFailed": "加入歌曲到播放清單失敗。", + "trackAdded": "已將 **{title}** 加入播放清單 **{name}**!(共 {count} 首)", + "invalidIndex": "無效的歌曲編號。", + "trackRemoved": "已從播放清單 **{name}** 移除 **{title}**!(剩餘 {count} 首)", + "deleted": "🗑️ 已刪除播放清單 **{name}**。" } } }