diff --git a/commands/lastfm.mjs b/commands/lastfm.mjs index 3c00fb4..fd5b113 100644 --- a/commands/lastfm.mjs +++ b/commands/lastfm.mjs @@ -6,6 +6,8 @@ import { PROVIDER_CHOICES } from "../src/constants/providers.mjs"; const EMOJI_REMOVE_TIMEOUT = 60_000; +const VALID_PERIODS = ["7day", "1month", "3month", "6month", "12month", "overall"]; + export const command = new CommandBuilder() .setName("lastfm") .setDescription("Link your Last.fm account, toggle scrobbling, or view your profile.", "commands.lastfm") @@ -13,13 +15,31 @@ export const command = new CommandBuilder() .addAliases("lf", "lfm") .addChoiceOption(o => o.setName("action") - .setDescription("The action to perform: link, unlink, np, profile, loved, top, recent, playlists, play, scrobble, leaderboard", "options.lastfm.action") - .addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "playlists", "play", "scrobble", "leaderboard", "lb", "love", "unlove", "artists") + .setDescription("The action to perform: link, unlink, np, profile, loved, top, recent, playlists, play, scrobble, leaderboard, whoknows, artistinfo, albuminfo, trackinfo, topalbums, toptags, tag, compare, cover, refreshmembers, affinity, crowns, whoknowstrack, whoknowsalbum, artisttags, albumtags, tracktags, friends, weekly, trending, geo, tagalbums, artisttracks, search", "options.lastfm.action") + .addChoices( + "link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", + "playlists", "play", "scrobble", "leaderboard", "lb", "love", "unlove", + "artists", "whoknows", "wk", "artistinfo", "ai", "albuminfo", "ali", + "trackinfo", "ti", "topalbums", "toptags", "tags", "tag", "compare", + "fmc", "cover", "art", "refreshmembers", "rm", "affinity", "af", + "crowns", "cr", "whoknowstrack", "wkt", "whoknowsalbum", "wka", + "artisttags", "at", "albumtags", "alt", "tracktags", "tt", + "friends", "fr", "weekly", "wc", "trending", "tr", + "geo", "g", "tagalbums", "ta", "artisttracks", "atr", + "search", "s" + ) .setRequired(false) ) + .addUserOption(o => + o.setName("user") + .setDescription("Another user (for compare/profile). Use: -user @mention or -u @mention") + .setRequired(false) + .addFlagAliases("u"), + true + ) .addTextOption(o => o.setName("token") - .setDescription("The auth token from Last.fm (used with 'confirm' action)") + .setDescription("The auth token from Last.fm (used with 'confirm' action), or a search query / period") .setRequired(false) ); @@ -39,7 +59,7 @@ function notLinked(prefix) { }; } -const SIMPLE_CATEGORIES = ["loved", "top", "recent", "albums"]; +const SIMPLE_CATEGORIES = ["loved", "top", "recent", "albums", "artists"]; function buildLastFmTrackMeta(track) { return { @@ -63,6 +83,60 @@ async function resolveLastFmTrack(player, track, resolveProvider = "yt") { return null; } +/** + * Extract current track info from the player for Last.fm lookups. + * @param {object} player + * @returns {{ artist: string|null, name: string|null, album: string|null, track: object|null } | null} + */ +function extractCurrentTrack(player) { + const track = player?.queue?.getCurrent(); + if (!track) return null; + const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? null; + const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? null; + const album = track.album ?? track.lastfm?.album ?? null; + return { artist, name, album, track }; +} + +/** + * Get all human member IDs from a guild for whoknows lookups. + * @param {object} guild + * @returns {Promise>} + */ +async function getGuildLinkedUsers(guild) { + const memberIds = []; + try { + const members = guild?.members; + if (members) { + const iter = typeof members.values === "function" ? members.values() : Object.values(members); + for (const m of iter) { + const userId = m.user?.id ?? m.id; + if (userId && !m.user?.bot) memberIds.push(String(userId)); + } + } + } catch {} + return memberIds; +} + +/** + * Parse a period string from token option or message content. + * @param {object} data + * @param {object} msg + * @returns {string} A valid period string + */ +function extractPeriod(data, msg) { + let raw = data.get("token")?.value; + if (!raw) { + const content = msg.message?.content ?? ""; + const args = content.split(/\s+/); + const last = args[args.length - 1]; + if (last && VALID_PERIODS.includes(last.toLowerCase())) raw = last; + } + if (raw && VALID_PERIODS.includes(raw.toLowerCase().trim())) { + return raw.toLowerCase().trim(); + } + return "overall"; +} + /** * Resolve a Last.fm category (loved/top/recent/playlist) into playable tracks. * Shared between `%lastfm play ` and `%play lastfm:`. @@ -88,7 +162,7 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = { if (!validCategories.includes(category)) { return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( - `โŒ Unknown category \`${category}\`. Use \`loved\`, \`top\`, \`recent\`, \`albums\`, or \`playlist\`.` + `โŒ Unknown category \`${category}\`. Use \`loved\`, \`top\`, \`recent\`, \`albums\`, \`artists\`, or \`playlist\`.` )] }); } @@ -107,8 +181,8 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = { const p = await ctx.getPlayer(msg, true, true, true); if (!p) return; - const categoryEmoji = { loved: "โค๏ธ", top: "๐Ÿ“Š", recent: "๐Ÿ•", playlist: "๐Ÿ“‹", albums: "๐Ÿ’ฟ" }[category]; - const categoryLabel = { loved: "Loved", top: "Top", recent: "Recent", playlist: "Playlist", albums: "Top Albums" }[category]; + const categoryEmoji = { loved: "โค๏ธ", top: "๐Ÿ“Š", recent: "๐Ÿ•", playlist: "๐Ÿ“‹", albums: "๐Ÿ’ฟ", artists: "๐ŸŽค" }[category]; + const categoryLabel = { loved: "Loved", top: "Top", recent: "Recent", playlist: "Playlist", albums: "Top Albums", artists: "Top Artists" }[category]; const resolveLabel = resolveProvider !== "yt" ? ` via ${resolveProvider.toUpperCase()}` : ""; @@ -261,6 +335,7 @@ export async function run(msg, data) { const prefix = this.handler?.getPrefix?.(msg.message?.guildId) ?? "%"; const action = data.get("action")?.value ?? "profile"; const userId = msg.message?.author?.id ?? msg.author?.id; + const targetUserId = data.get("user")?.value ?? null; switch (action) { case "link": { @@ -409,19 +484,20 @@ export async function run(msg, data) { } case "profile": { - const user = await lastfm.getUser(userId); + const profileUserId = targetUserId || userId; + const user = await lastfm.getUser(profileUserId); if (!user) return msg.reply(notLinked(prefix)); let info; try { - info = await lastfm.getUserInfo(userId); + info = await lastfm.getUserInfo(profileUserId); } catch (err) { return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch profile: ${err.message}`)] }); } - lastfm.syncUserScrobbleCount(userId).catch(() => {}); + lastfm.syncUserScrobbleCount(profileUserId).catch(() => {}); const embed = new EmbedBuilder() .setColor(getGlobalColor()) @@ -498,6 +574,7 @@ export async function run(msg, data) { `\`top\` โ€” Play your top tracks`, `\`recent\` โ€” Play your recent tracks`, `\`albums\` โ€” Play your top albums`, + `\`artists\` โ€” Play your top artists' tracks`, `\`playlist \` โ€” Play a playlist (use \`${prefix}lastfm playlists\` to list)`, ``, `**With a search provider (defaults to \`top\`):**`, @@ -511,6 +588,7 @@ export async function run(msg, data) { `\`${prefix}lastfm play lf:top\` โ€” Play top tracks, search on Last.fm`, `\`${prefix}lastfm play lf:recent\` โ€” Play recent tracks, search on Last.fm`, `\`${prefix}lastfm play lf:albums\` โ€” Play top albums, search on Last.fm`, + `\`${prefix}lastfm play lf:artists\` โ€” Play top artists, search on Last.fm`, ``, `**Examples:**`, `\`${prefix}lastfm play loved\``, @@ -555,9 +633,11 @@ export async function run(msg, data) { const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); + const period = extractPeriod(data, msg); + let tracks; try { - tracks = await lastfm.getTopTracks(userId, "overall", 15); + tracks = await lastfm.getTopTracks(userId, period, 15); } catch (err) { return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch top tracks: ${err.message}`)] @@ -570,7 +650,8 @@ export async function run(msg, data) { }); } - return msg.reply({ embeds: [buildTrackList(user.username, "๐Ÿ“Š Top Tracks", tracks, true, prefix)] }); + const periodLabel = period !== "overall" ? ` (${period})` : ""; + return msg.reply({ embeds: [buildTrackList(user.username, `๐Ÿ“Š Top Tracks${periodLabel}`, tracks, true, prefix)] }); } case "leaderboard": @@ -691,9 +772,11 @@ export async function run(msg, data) { const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); + const period = extractPeriod(data, msg); + let artists; try { - artists = await lastfm.getTopArtists(userId, "overall", 15); + artists = await lastfm.getTopArtists(userId, period, 15); } catch (err) { return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch top artists: ${err.message}`)] @@ -706,6 +789,7 @@ export async function run(msg, data) { }); } + const periodLabel = period !== "overall" ? ` (${period})` : ""; const lines = artists.map((a, i) => { const num = String(i + 1).padStart(2, " "); let name = a.name; @@ -719,7 +803,7 @@ export async function run(msg, data) { return msg.reply({ embeds: [new EmbedBuilder() .setColor(getGlobalColor()) - .setTitle(`๐ŸŽค Top Artists โ€” ${user.username}`) + .setTitle(`๐ŸŽค Top Artists${periodLabel} โ€” ${user.username}`) .setDescription(desc) .setFooter({ text: `๐Ÿ’ก Use ${prefix}lastfm play top to play your top tracks!` })] }); @@ -781,6 +865,1517 @@ export async function run(msg, data) { } } + case "whoknows": + case "wk": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + let artistName = null; + const tokenTextWk = data.get("token")?.value; + if (tokenTextWk) { + artistName = tokenTextWk.trim(); + } else { + const pWk = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pWk); + if (current?.artist) { + artistName = current.artist; + } + } + + if (!artistName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Nothing is playing right now and no artist specified. Play a song or provide an artist name!`)] + }); + } + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `๐Ÿ” Checking who listens to **${artistName}** in this server...` + )] + }); + } catch { statusMsg = null; } + + const guild = msg.message?.guild ?? msg.message?.member?.guild; + const memberIds = await getGuildLinkedUsers(guild); + + let listeners; + try { + listeners = await lastfm.getWhoKnows(artistName, memberIds); + } catch (err) { + const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to check who knows: ${err.message}`)] }; + if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); + else msg.reply(errEmbed); + return; + } + + if (!listeners.length) { + const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `๐Ÿ‘ค Nobody in this server has listened to **${artistName}** on Last.fm.` + )] }; + if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); + else msg.reply(noData); + return; + } + + const MEDALS = ["๐Ÿฅ‡", "๐Ÿฅˆ", "๐Ÿฅ‰"]; + const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0); + + const lines = listeners.map((l, i) => { + const medal = i < 3 ? MEDALS[i] : ` `; + return `${medal} ${i + 1}. **${l.username}** โ€” **${Utils.formatNumber(l.playcount)}** plays`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ‘ค Who knows ${artistName}?`) + .setDescription(desc) + .setFooter({ text: `${listeners.length} listener${listeners.length !== 1 ? "s" : ""} ยท ${Utils.formatNumber(totalPlays)} total plays` }); + + const replyPayload = { embeds: [embed] }; + if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); + else msg.reply(replyPayload); + return; + } + + case "artistinfo": + case "ai": { + const user = await lastfm.getUser(userId); + + let artistName = null; + + const pAi = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pAi); + if (current?.artist) { + artistName = current.artist; + } + + const tokenText = data.get("token")?.value; + if (tokenText) { + artistName = tokenText.trim(); + } + + if (!artistName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + `โŒ No artist specified. Play a song or provide an artist name via the token option.` + )] + }); + } + + let info; + try { + info = await lastfm.getArtistInfo(artistName, userId); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch artist info: ${err.message}`)] + }); + } + + if (!info) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Artist **${artistName}** not found on Last.fm.`)] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐ŸŽค ${info.name}`) + .setURL(info.url || undefined) + .setThumbnail(info.image || undefined); + + const fields = []; + fields.push({ name: "Listeners", value: Utils.formatNumber(info.stats?.listeners ?? 0), inline: true }); + fields.push({ name: "Global Plays", value: Utils.formatNumber(info.stats?.playcount ?? 0), inline: true }); + + if (info.userplaycount !== null && user) { + fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true }); + } + + if (info.tags?.length) { + const tagStr = info.tags.slice(0, 8).map(t => { + const tagLower = String(t).toLowerCase().replace(/\s+/g, "+"); + return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`; + }).join(" ยท "); + fields.push({ name: "Tags", value: tagStr, inline: false }); + } + + if (info.similar?.length) { + const simStr = info.similar.slice(0, 5).map(s => { + return s.url ? `[${s.name}](${s.url})` : s.name; + }).join(" ยท "); + fields.push({ name: "Similar Artists", value: simStr, inline: false }); + } + + embed.addFields(fields); + + if (info.bio) { + const cleanBio = info.bio.replace(/<[^>]*>/g, "").trim(); + if (cleanBio.length > 0) { + const truncated = cleanBio.length > 300 ? cleanBio.slice(0, 297) + "..." : cleanBio; + embed.setDescription(truncated); + } + } + + embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" }); + + return msg.reply({ embeds: [embed] }); + } + + case "albuminfo": + case "ali": { + const user = await lastfm.getUser(userId); + + let artistName = null; + let albumName = null; + + const pAli = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pAli); + if (current?.album && current?.artist) { + artistName = current.artist; + albumName = current.album; + } + + const tokenText = data.get("token")?.value; + if (tokenText) { + const dashMatch = tokenText.match(/^(.+?)\s*[-โ€“โ€”]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + albumName = dashMatch[2].trim(); + } else { + albumName = tokenText.trim(); + } + } + + if (!albumName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + `โŒ No album specified. Play a song or provide an album name (e.g. \`artist - album\`) via the token option.` + )] + }); + } + + let info; + try { + info = await lastfm.getAlbumInfo(artistName || "", albumName, userId); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch album info: ${err.message}`)] + }); + } + + if (!info) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Album **${albumName}** not found on Last.fm.`)] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ’ฟ ${info.name}`) + .setURL(info.url || undefined) + .setThumbnail(info.image || undefined); + + const fields = []; + + if (info.artist) { + fields.push({ name: "Artist", value: info.artist, inline: true }); + } + + if (info.userplaycount !== null && user) { + fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true }); + } + + if (info.tags?.length) { + const tagStr = info.tags.slice(0, 8).map(t => { + const tagLower = String(t).toLowerCase().replace(/\s+/g, "+"); + return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`; + }).join(" ยท "); + fields.push({ name: "Tags", value: tagStr, inline: false }); + } + + if (info.tracks?.length) { + const trackLines = info.tracks.slice(0, 15).map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const dur = t.duration > 0 ? ` (${formatDuration(t.duration)})` : ""; + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `\`${num}.\` ${link}${dur}`; + }); + fields.push({ name: "Tracklist", value: trackLines.join("\n").slice(0, 1024), inline: false }); + } + + embed.addFields(fields); + embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" }); + + return msg.reply({ embeds: [embed] }); + } + + case "trackinfo": + case "ti": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + let artistName = null; + let trackName = null; + + const pTi = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pTi); + if (current?.artist && current?.name) { + artistName = current.artist; + trackName = current.name; + } + + const tokenText = data.get("token")?.value; + if (tokenText) { + const dashMatch = tokenText.match(/^(.+?)\s*[-โ€“โ€”]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + trackName = dashMatch[2].trim(); + } else { + try { + const searchResult = await lastfm.searchTrack(tokenText.trim()); + if (searchResult) { + artistName = searchResult.artist; + trackName = searchResult.name; + } + } catch {} + } + } + + if (!artistName || !trackName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + `โŒ No track specified. Play a song or provide a track name (e.g. \`artist - track\`) via the token option.` + )] + }); + } + + let info; + try { + info = await lastfm.getTrackInfo(artistName, trackName, userId); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch track info: ${err.message}`)] + }); + } + + if (!info) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Track **${trackName}** by **${artistName}** not found on Last.fm.`)] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐ŸŽต ${info.name}`) + .setURL(info.url || undefined); + + if (info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]) { + embed.setThumbnail(info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]); + } + + const fields = []; + + if (info.artist?.name || info.artist?.["#text"]) { + fields.push({ name: "Artist", value: String(info.artist?.name ?? info.artist?.["#text"] ?? "Unknown"), inline: true }); + } + + if (info.album?.title) { + fields.push({ name: "Album", value: info.album.title, inline: true }); + } + + if (info.listeners) { + fields.push({ name: "Listeners", value: Utils.formatNumber(Number(info.listeners)), inline: true }); + } + + if (info.playcount) { + fields.push({ name: "Global Plays", value: Utils.formatNumber(Number(info.playcount)), inline: true }); + } + + if (info.userplaycount) { + fields.push({ name: "Your Plays", value: Utils.formatNumber(Number(info.userplaycount)), inline: true }); + } + + const userLoved = info.userloved === "1" || info.userloved === 1 || info.userloved === true; + fields.push({ name: "Loved", value: userLoved ? "โค๏ธ Yes" : "๐Ÿ–ค No", inline: true }); + + if (info.toptags?.tag?.length) { + const tagStr = info.toptags.tag.slice(0, 8).map(t => { + const tagName = t.name ?? t; + const tagLower = String(tagName).toLowerCase().replace(/\s+/g, "+"); + return `[${tagName}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`; + }).join(" ยท "); + fields.push({ name: "Tags", value: tagStr, inline: false }); + } + + embed.addFields(fields); + + if (info.wiki?.summary) { + const cleanSummary = info.wiki.summary.replace(/<[^>]*>/g, "").trim(); + if (cleanSummary.length > 0) { + const truncated = cleanSummary.length > 200 ? cleanSummary.slice(0, 197) + "..." : cleanSummary; + embed.setDescription(truncated); + } + } + + let similarTracks = []; + try { + similarTracks = await lastfm.getSimilarTracks(artistName, trackName, 5); + } catch {} + + if (similarTracks.length) { + const simStr = similarTracks.map(t => { + const matchPct = Math.round(t.match * 100); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `${link} by **${t.artist}** (${matchPct}%)`; + }).join("\n"); + embed.addFields([{ name: "Similar Tracks", value: simStr.slice(0, 1024), inline: false }]); + } + + embed.setFooter({ text: `Last.fm: ${user.username}` }); + + return msg.reply({ embeds: [embed] }); + } + + case "topalbums": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + const period = extractPeriod(data, msg); + + let albums; + try { + albums = await lastfm.getTopAlbums(userId, period, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch top albums: ${err.message}`)] + }); + } + + if (!albums.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ’ฟ No top albums found for **${user.username}**.`)] + }); + } + + const periodLabel = period !== "overall" ? ` (${period})` : ""; + + const lines = albums.map((a, i) => { + const num = String(i + 1).padStart(2, " "); + let albumTitle = a.name; + if (albumTitle.length > 30) albumTitle = albumTitle.slice(0, 27) + "..."; + const link = a.url ? `[${albumTitle}](${a.url})` : albumTitle; + return `\`${num}.\` ${link} โ€” **${a.artist}** (**${a.playcount}** plays)`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ’ฟ Top Albums${periodLabel} โ€” ${user.username}`) + .setDescription(desc); + + if (albums[0]?.image) { + embed.setThumbnail(albums[0].image); + } + + embed.setFooter({ text: `๐Ÿ’ก Use ${prefix}lastfm play albums to play your top albums!` }); + + return msg.reply({ embeds: [embed] }); + } + + case "toptags": + case "tags": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + let tags; + try { + tags = await lastfm.getUserTopTags(userId, 20); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch top tags: ${err.message}`)] + }); + } + + if (!tags.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿท๏ธ No top tags found for **${user.username}**.`)] + }); + } + + const lines = tags.map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `\`${num}.\` ${link} โ€” **${t.count}**`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿท๏ธ Top Tags โ€” ${user.username}`) + .setDescription(desc) + .setFooter({ text: `๐Ÿ’ก Use ${prefix}lastfm tag to view info about a tag!` })] + }); + } + + case "tag": { + const tagName = data.get("token")?.value; + if (!tagName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + `โŒ Provide a tag name via the token option. Example: \`${prefix}lastfm tag rock\`` + )] + }); + } + + let tagInfo; + let topTracks; + let topArtists; + + try { + [tagInfo, topTracks, topArtists] = await Promise.all([ + lastfm.getTagInfo(tagName), + lastfm.getTagTopTracks(tagName, 5), + lastfm.getTagTopArtists(tagName, 5), + ]); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch tag info: ${err.message}`)] + }); + } + + if (!tagInfo) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Tag **${tagName}** not found on Last.fm.`)] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿท๏ธ ${tagInfo.name}`) + .setURL(tagInfo.url || undefined); + + const fields = []; + fields.push({ name: "Reach", value: Utils.formatNumber(tagInfo.reach), inline: true }); + fields.push({ name: "Total Taggings", value: Utils.formatNumber(tagInfo.count), inline: true }); + + if (topArtists.length) { + const artistStr = topArtists.map((a, i) => { + const link = a.url ? `[${a.name}](${a.url})` : a.name; + return `${i + 1}. ${link} (**${Utils.formatNumber(a.playcount)}** plays)`; + }).join("\n"); + fields.push({ name: "Top Artists", value: artistStr.slice(0, 1024), inline: false }); + } + + if (topTracks.length) { + const trackStr = topTracks.map((t, i) => { + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `${i + 1}. ${link} by **${t.artist}**`; + }).join("\n"); + fields.push({ name: "Top Tracks", value: trackStr.slice(0, 1024), inline: false }); + } + + embed.addFields(fields); + + if (tagInfo.summary) { + const cleanSummary = tagInfo.summary.replace(/<[^>]*>/g, "").trim(); + if (cleanSummary.length > 0) { + const truncated = cleanSummary.length > 300 ? cleanSummary.slice(0, 297) + "..." : cleanSummary; + embed.setDescription(truncated); + } + } + + return msg.reply({ embeds: [embed] }); + } + + case "compare": + case "fmc": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + if (!targetUserId) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + `โŒ Specify another user to compare with. Example: \`${prefix}lastfm compare -user @user\`` + )] + }); + } + + const targetUser = await lastfm.getUser(targetUserId); + if (!targetUser) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + `โŒ That user doesn't have a Last.fm account linked.` + )] + }); + } + + let comparison; + try { + comparison = await lastfm.compareUsers(userId, targetUserId); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to compare users: ${err.message}`)] + }); + } + + if (!comparison) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Could not compare profiles. Make sure both users are linked.`)] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿค Taste Comparison`) + .setDescription([ + `**${comparison.user1.username}** vs **${comparison.user2.username}**`, + ``, + `๐Ÿ“Š **${comparison.matchPercentage}%** match`, + ``, + `๐Ÿ‘ค ${comparison.user1.username}: ${comparison.user1.totalArtists} top artists`, + `๐Ÿ‘ค ${comparison.user2.username}: ${comparison.user2.totalArtists} top artists`, + ].join("\n")); + + if (comparison.commonArtists?.length) { + const commonStr = comparison.commonArtists.slice(0, 15).map((a, i) => { + const num = String(i + 1).padStart(2, " "); + const link = a.url ? `[${a.name}](${a.url})` : a.name; + return `\`${num}.\` ${link} (**${a.playcount}** plays)`; + }).join("\n"); + embed.addFields([{ name: `Common Artists (${comparison.commonArtists.length})`, value: commonStr.slice(0, 1024), inline: false }]); + } + + return msg.reply({ embeds: [embed] }); + } + + case "cover": + case "art": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + const pCover = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pCover); + if (!current || !current.name) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Nothing is playing right now. Play a song to get its album cover!`)] + }); + } + + const artistName = current.artist ?? "Unknown"; + const trackName = current.name; + const albumName = current.album; + + let coverUrl = null; + let albumTitle = albumName ?? "Unknown Album"; + + if (albumName) { + try { + const albumInfo = await lastfm.getAlbumInfo(artistName, albumName, userId); + if (albumInfo?.image) { + coverUrl = albumInfo.image; + albumTitle = `${albumInfo.name} by ${albumInfo.artist}`; + } + } catch {} + } + + if (!coverUrl) { + try { + const trackInfo = await lastfm.getTrackInfo(artistName, trackName, userId); + if (trackInfo?.album?.image) { + const images = trackInfo.album.image; + coverUrl = images?.[2]?.["#text"] || images?.[1]?.["#text"] || images?.[0]?.["#text"] || null; + if (trackInfo.album?.title) { + albumTitle = trackInfo.album.title; + } + } + } catch {} + } + + if (!coverUrl) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ–ผ๏ธ No album cover found for **${trackName}** by **${artistName}**.`)] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ–ผ๏ธ ${albumTitle}`) + .setImage(coverUrl) + .setFooter({ text: `๐ŸŽต ${trackName} by ${artistName}` }); + + return msg.reply({ embeds: [embed] }); + } + + case "refreshmembers": + case "rm": { + const guild = msg.message?.guild ?? msg.message?.member?.guild; + if (!guild) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Could not access the server.`)] + }); + } + let count = 0; + try { + if (guild.members && typeof guild.members.fetch === "function") { + const fetched = await guild.members.fetch(); + count = fetched.size; + } else { + const memberIds = await getGuildLinkedUsers(guild); + count = memberIds.length; + } + } catch { + const memberIds = await getGuildLinkedUsers(guild); + count = memberIds.length; + } + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`โœ… Member list refreshed! Found **${Utils.formatNumber(count)}** members in this server.`)] + }); + } + + case "affinity": + case "af": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + const guild = msg.message?.guild ?? msg.message?.member?.guild; + const memberIds = await getGuildLinkedUsers(guild); + + if (memberIds.length < 2) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ‘ฅ Need at least 2 linked users in this server to check affinity.`)] + }); + } + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ” Checking music affinity among server members...`)] + }); + } catch { statusMsg = null; } + + let affinityResults; + try { + affinityResults = await lastfm.getAffinity(memberIds, 10); + } catch (err) { + const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to check affinity: ${err.message}`)] }; + if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); + else msg.reply(errEmbed); + return; + } + + if (!affinityResults.length) { + const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ‘ฅ No common artists found between any server members.`)] }; + if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); + else msg.reply(noData); + return; + } + + const lines = affinityResults.map(r => { + const topCommon = r.commonArtists.slice(0, 3).map(a => a.name).join(", "); + return `**${r.users[0]}** & **${r.users[1]}** โ€” ${r.matchCount} common artists (${topCommon}${r.commonArtists.length > 3 ? "..." : ""})`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ‘ฅ Music Affinity`) + .setDescription(desc) + .setFooter({ text: `${memberIds.length} members checked` }); + + const replyPayload = { embeds: [embed] }; + if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); + else msg.reply(replyPayload); + return; + } + + case "crowns": + case "cr": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + const guild = msg.message?.guild ?? msg.message?.member?.guild; + const memberIds = await getGuildLinkedUsers(guild); + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ‘‘ Checking your artist crowns...`)] + }); + } catch { statusMsg = null; } + + let crowns; + try { + crowns = await lastfm.getCrowns(userId, memberIds); + } catch (err) { + const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch crowns: ${err.message}`)] }; + if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); + else msg.reply(errEmbed); + return; + } + + if (!crowns.length) { + const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ‘‘ You don't hold any artist crowns in this server. Keep listening!`)] }; + if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); + else msg.reply(noData); + return; + } + + const tokenFilter = data.get("token")?.value?.toLowerCase().trim(); + + let filteredCrowns = crowns; + if (tokenFilter === "stolen") { + filteredCrowns = crowns.filter(c => c.nextBest && c.nextBest.playcount > 0); + } else if (tokenFilter === "recent") { + filteredCrowns = crowns.slice(0, 10); + } + + const lines = filteredCrowns.slice(0, 20).map(c => { + const link = c.artistUrl ? `[${c.artist}](${c.artistUrl})` : c.artist; + const nextStr = c.nextBest ? ` (next: **${c.nextBest.username}** with ${Utils.formatNumber(c.nextBest.playcount)})` : ""; + return `๐Ÿ‘‘ ${link} โ€” **${Utils.formatNumber(c.userPlaycount)}** plays${nextStr}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ‘‘ Artist Crowns โ€” ${user.username}`) + .setDescription(desc) + .setFooter({ text: `${filteredCrowns.length} crown${filteredCrowns.length !== 1 ? "s" : ""} held` }); + + if (filteredCrowns[0]?.image) { + embed.setThumbnail(filteredCrowns[0].image); + } + + const replyPayload = { embeds: [embed] }; + if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); + else msg.reply(replyPayload); + return; + } + + case "whoknowstrack": + case "wkt": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + let artistName = null; + let trackName = null; + + const pWkt = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pWkt); + if (current?.artist && current?.name) { + artistName = current.artist; + trackName = current.name; + } + + const tokenTextWkt = data.get("token")?.value; + if (tokenTextWkt) { + const dashMatch = tokenTextWkt.match(/^(.+?)\s*[-โ€“โ€”]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + trackName = dashMatch[2].trim(); + } else { + try { + const searchResult = await lastfm.searchTrack(tokenTextWkt.trim()); + if (searchResult) { + artistName = searchResult.artist; + trackName = searchResult.name; + } + } catch {} + } + } + + if (!artistName || !trackName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ No track specified. Play a song or provide a track name (e.g. \`artist - track\`) via the token option.`)] + }); + } + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ” Checking who knows **${trackName}** by **${artistName}** in this server...`)] + }); + } catch { statusMsg = null; } + + const guild = msg.message?.guild ?? msg.message?.member?.guild; + const memberIds = await getGuildLinkedUsers(guild); + + let listeners; + try { + listeners = await lastfm.getWhoKnowsTrack(artistName, trackName, memberIds); + } catch (err) { + const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to check who knows: ${err.message}`)] }; + if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); + else msg.reply(errEmbed); + return; + } + + if (!listeners.length) { + const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ‘ค Nobody in this server has listened to **${trackName}** by **${artistName}** on Last.fm.`)] }; + if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); + else msg.reply(noData); + return; + } + + const MEDALS = ["๐Ÿฅ‡", "๐Ÿฅˆ", "๐Ÿฅ‰"]; + const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0); + + const lines = listeners.map((l, i) => { + const medal = i < 3 ? MEDALS[i] : ` `; + return `${medal} ${i + 1}. **${l.username}** โ€” **${Utils.formatNumber(l.playcount)}** plays`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ‘ค Who knows ${trackName}?`) + .setDescription(desc) + .setFooter({ text: `${listeners.length} listener${listeners.length !== 1 ? "s" : ""} ยท ${Utils.formatNumber(totalPlays)} total plays ยท by ${artistName}` }); + + const replyPayload = { embeds: [embed] }; + if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); + else msg.reply(replyPayload); + return; + } + + case "whoknowsalbum": + case "wka": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + let artistName = null; + let albumName = null; + + const pWka = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pWka); + if (current?.album && current?.artist) { + artistName = current.artist; + albumName = current.album; + } + + const tokenTextWka = data.get("token")?.value; + if (tokenTextWka) { + const dashMatch = tokenTextWka.match(/^(.+?)\s*[-โ€“โ€”]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + albumName = dashMatch[2].trim(); + } else { + albumName = tokenTextWka.trim(); + } + } + + if (!albumName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ No album specified. Play a song or provide an album name (e.g. \`artist - album\`) via the token option.`)] + }); + } + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ” Checking who knows **${albumName}**${artistName ? ` by **${artistName}**` : ""} in this server...`)] + }); + } catch { statusMsg = null; } + + const guild = msg.message?.guild ?? msg.message?.member?.guild; + const memberIds = await getGuildLinkedUsers(guild); + + let listeners; + try { + listeners = await lastfm.getWhoKnowsAlbum(artistName || "", albumName, memberIds); + } catch (err) { + const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to check who knows: ${err.message}`)] }; + if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); + else msg.reply(errEmbed); + return; + } + + if (!listeners.length) { + const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ‘ค Nobody in this server has listened to **${albumName}** on Last.fm.`)] }; + if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); + else msg.reply(noData); + return; + } + + const MEDALS = ["๐Ÿฅ‡", "๐Ÿฅˆ", "๐Ÿฅ‰"]; + const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0); + + const lines = listeners.map((l, i) => { + const medal = i < 3 ? MEDALS[i] : ` `; + return `${medal} ${i + 1}. **${l.username}** โ€” **${Utils.formatNumber(l.playcount)}** plays`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ‘ค Who knows ${albumName}?`) + .setDescription(desc) + .setFooter({ text: `${listeners.length} listener${listeners.length !== 1 ? "s" : ""} ยท ${Utils.formatNumber(totalPlays)} total plays` }); + + const replyPayload = { embeds: [embed] }; + if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); + else msg.reply(replyPayload); + return; + } + + case "artisttags": + case "at": { + let artistName = null; + + const pAt = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pAt); + if (current?.artist) { + artistName = current.artist; + } + + const tokenTextAt = data.get("token")?.value; + if (tokenTextAt) { + artistName = tokenTextAt.trim(); + } + + if (!artistName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ No artist specified. Play a song or provide an artist name via the token option.`)] + }); + } + + let tags; + try { + tags = await lastfm.getArtistTopTags(artistName, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch artist tags: ${err.message}`)] + }); + } + + if (!tags.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿท๏ธ No tags found for artist **${artistName}**.`)] + }); + } + + const lines = tags.map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `\`${num}.\` ${link}${t.count > 0 ? ` โ€” **${Utils.formatNumber(t.count)}**` : ""}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿท๏ธ Top Tags for ${artistName}`) + .setDescription(desc)] + }); + } + + case "albumtags": + case "alt": { + let artistName = null; + let albumName = null; + + const pAlt = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pAlt); + if (current?.album && current?.artist) { + artistName = current.artist; + albumName = current.album; + } + + const tokenTextAlt = data.get("token")?.value; + if (tokenTextAlt) { + const dashMatch = tokenTextAlt.match(/^(.+?)\s*[-โ€“โ€”]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + albumName = dashMatch[2].trim(); + } else { + albumName = tokenTextAlt.trim(); + } + } + + if (!albumName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ No album specified. Play a song or provide an album name (e.g. \`artist - album\`) via the token option.`)] + }); + } + + let tags; + try { + tags = await lastfm.getAlbumTopTags(artistName || "", albumName, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch album tags: ${err.message}`)] + }); + } + + if (!tags.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿท๏ธ No tags found for album **${albumName}**.`)] + }); + } + + const lines = tags.map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `\`${num}.\` ${link}${t.count > 0 ? ` โ€” **${Utils.formatNumber(t.count)}**` : ""}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿท๏ธ Top Tags for ${albumName}`) + .setDescription(desc)] + }); + } + + case "tracktags": + case "tt": { + let artistName = null; + let trackName = null; + + const pTt = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pTt); + if (current?.artist && current?.name) { + artistName = current.artist; + trackName = current.name; + } + + const tokenTextTt = data.get("token")?.value; + if (tokenTextTt) { + const dashMatch = tokenTextTt.match(/^(.+?)\s*[-โ€“โ€”]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + trackName = dashMatch[2].trim(); + } else { + try { + const searchResult = await lastfm.searchTrack(tokenTextTt.trim()); + if (searchResult) { + artistName = searchResult.artist; + trackName = searchResult.name; + } + } catch {} + } + } + + if (!artistName || !trackName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ No track specified. Play a song or provide a track name (e.g. \`artist - track\`) via the token option.`)] + }); + } + + let tags; + try { + tags = await lastfm.getTrackTopTags(artistName, trackName, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch track tags: ${err.message}`)] + }); + } + + if (!tags.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿท๏ธ No tags found for **${trackName}** by **${artistName}**.`)] + }); + } + + const lines = tags.map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `\`${num}.\` ${link}${t.count > 0 ? ` โ€” **${Utils.formatNumber(t.count)}**` : ""}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿท๏ธ Top Tags for ${trackName}`) + .setDescription(desc)] + }); + } + + case "friends": + case "fr": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + let friends; + try { + friends = await lastfm.getUserFriends(userId, 20); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch friends: ${err.message}`)] + }); + } + + if (!friends.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ‘ฅ No friends found for **${user.username}**.`)] + }); + } + + const lines = friends.map((f, i) => { + const num = String(i + 1).padStart(2, " "); + const link = f.url ? `[${f.name}](${f.url})` : f.name; + const details = []; + if (f.realname) details.push(f.realname); + if (f.country) details.push(f.country); + const detailStr = details.length > 0 ? ` (${details.join(", ")})` : ""; + return `\`${num}.\` ${link}${detailStr}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ‘ฅ Friends โ€” ${user.username}`) + .setDescription(desc)] + }); + } + + case "weekly": + case "wc": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + const tokenTextWc = data.get("token")?.value?.toLowerCase().trim() ?? "artists"; + let chartData; + let chartTitle; + + try { + if (tokenTextWc === "tracks") { + chartData = await lastfm.getUserWeeklyTrackChart(userId); + chartTitle = `๐Ÿ“… Weekly Track Chart โ€” ${user.username}`; + } else if (tokenTextWc === "albums") { + chartData = await lastfm.getUserWeeklyAlbumChart(userId); + chartTitle = `๐Ÿ“… Weekly Album Chart โ€” ${user.username}`; + } else { + chartData = await lastfm.getUserWeeklyArtistChart(userId); + chartTitle = `๐Ÿ“… Weekly Artist Chart โ€” ${user.username}`; + } + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch weekly chart: ${err.message}`)] + }); + } + + if (!chartData.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ“… No weekly chart data found for **${user.username}**.`)] + }); + } + + const lines = chartData.slice(0, 15).map((item, i) => { + const num = String(i + 1).padStart(2, " "); + const link = item.url ? `[${item.name}](${item.url})` : item.name; + const artistStr = item.artist ? ` by **${item.artist}**` : ""; + return `\`${num}.\` ${link}${artistStr} โ€” **${Utils.formatNumber(item.playcount)}** plays`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(chartTitle) + .setDescription(desc) + .setFooter({ text: `๐Ÿ’ก Use token option: artists, tracks, or albums` })] + }); + } + + case "trending": + case "tr": { + const tokenTextTr = data.get("token")?.value?.toLowerCase().trim() ?? "tracks"; + let trendingData; + let trendingTitle; + + try { + if (tokenTextTr === "artists") { + trendingData = await lastfm.getChartTopArtists(15); + trendingTitle = "๐Ÿ”ฅ Trending Artists on Last.fm"; + } else { + trendingData = await lastfm.getChartTopTracks(15); + trendingTitle = "๐Ÿ”ฅ Trending Tracks on Last.fm"; + } + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch trending: ${err.message}`)] + }); + } + + if (!trendingData.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ”ฅ No trending data found.`)] + }); + } + + const lines = trendingData.map((item, i) => { + const num = String(i + 1).padStart(2, " "); + const link = item.url ? `[${item.name}](${item.url})` : item.name; + const artistStr = item.artist ? ` by **${item.artist}**` : ""; + const extra = item.listeners ? ` โ€” ${Utils.formatNumber(item.listeners)} listeners` : item.playcount ? ` โ€” ${Utils.formatNumber(item.playcount)} plays` : ""; + return `\`${num}.\` ${link}${artistStr}${extra}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(trendingTitle) + .setDescription(desc) + .setFooter({ text: `๐Ÿ’ก Use token option: tracks or artists` })] + }); + } + + case "geo": + case "g": { + const tokenTextG = data.get("token")?.value?.trim() ?? ""; + if (!tokenTextG) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Provide a query like \`artists \` or \`tracks \`. Example: \`${prefix}lastfm geo artists united states\`.`)] + }); + } + + const lowerToken = tokenTextG.toLowerCase(); + let type = "artists"; + let country = tokenTextG; + + if (lowerToken.startsWith("artists ")) { + type = "artists"; + country = tokenTextG.slice(8).trim(); + } else if (lowerToken.startsWith("tracks ")) { + type = "tracks"; + country = tokenTextG.slice(7).trim(); + } + + if (!country) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Please specify a country name. Example: \`${prefix}lastfm geo artists united states\`.`)] + }); + } + + let geoData; + let geoTitle; + + try { + if (type === "tracks") { + geoData = await lastfm.getGeoTopTracks(country, 15); + geoTitle = `๐ŸŒ Top Tracks in ${country}`; + } else { + geoData = await lastfm.getGeoTopArtists(country, 15); + geoTitle = `๐ŸŒ Top Artists in ${country}`; + } + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch geo data: ${err.message}`)] + }); + } + + if (!geoData.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐ŸŒ No data found for **${country}**.`)] + }); + } + + const lines = geoData.map((item, i) => { + const num = String(i + 1).padStart(2, " "); + const link = item.url ? `[${item.name}](${item.url})` : item.name; + const artistStr = item.artist ? ` by **${item.artist}**` : ""; + const extra = item.listeners ? ` โ€” ${Utils.formatNumber(item.listeners)} listeners` : ""; + return `\`${num}.\` ${link}${artistStr}${extra}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(geoTitle) + .setDescription(desc)] + }); + } + + case "tagalbums": + case "ta": { + const tagName = data.get("token")?.value; + if (!tagName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Provide a tag name via the token option. Example: \`${prefix}lastfm tagalbums rock\``)] + }); + } + + let albums; + try { + albums = await lastfm.getTagTopAlbums(tagName.trim(), 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch tag albums: ${err.message}`)] + }); + } + + if (!albums.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ’ฟ No top albums found for tag **${tagName}**.`)] + }); + } + + const lines = albums.map((a, i) => { + const num = String(i + 1).padStart(2, " "); + const link = a.url ? `[${a.name}](${a.url})` : a.name; + return `\`${num}.\` ${link} by **${a.artist}**${a.playcount > 0 ? ` (${Utils.formatNumber(a.playcount)} plays)` : ""}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ’ฟ Top Albums โ€” ${tagName}`) + .setDescription(desc); + + if (albums[0]?.image) { + embed.setThumbnail(albums[0].image); + } + + return msg.reply({ embeds: [embed] }); + } + + case "artisttracks": + case "atr": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + let artistName = null; + + const pAtr = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pAtr); + if (current?.artist) { + artistName = current.artist; + } + + const tokenTextAtr = data.get("token")?.value; + if (tokenTextAtr) { + artistName = tokenTextAtr.trim(); + } + + if (!artistName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ No artist specified. Play a song or provide an artist name via the token option.`)] + }); + } + + let recentTracks; + try { + recentTracks = await lastfm.getRecentTracks(userId, 200); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch recent tracks: ${err.message}`)] + }); + } + + const artistTracks = recentTracks.filter(t => + t.artist.toLowerCase() === artistName.toLowerCase() + ); + + if (!artistTracks.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐ŸŽต No scrobbles found for **${artistName}** in your recent history.`)] + }); + } + + const lines = artistTracks.slice(0, 15).map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + const nowStr = t.now ? " ๐ŸŽต" : ""; + return `\`${num}.\` ${link}${nowStr}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐ŸŽต ${artistName} Scrobbles โ€” ${user.username}`) + .setDescription(desc) + .setFooter({ text: `${artistTracks.length} scrobble${artistTracks.length !== 1 ? "s" : ""} found` })] + }); + } + + case "search": + case "s": { + const query = data.get("token")?.value; + if (!query) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Provide a search query via the token option. Example: \`${prefix}lastfm search radiohead\``)] + }); + } + + let artistResults, albumResults, trackResult; + try { + [artistResults, albumResults, trackResult] = await Promise.all([ + lastfm.searchArtist(query, 5), + lastfm.searchAlbum(query, 5), + lastfm.searchTrack(query), + ]); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to search: ${err.message}`)] + }); + } + + const sections = []; + + if (artistResults.length) { + const artistLines = artistResults.map((a, i) => { + const link = a.url ? `[${a.name}](${a.url})` : a.name; + const listeners = a.listeners ? ` โ€” ${Utils.formatNumber(a.listeners)} listeners` : ""; + return `${i + 1}. ${link}${listeners}`; + }); + sections.push(`**๐ŸŽค Artists:**\n${artistLines.join("\n")}`); + } + + if (albumResults.length) { + const albumLines = albumResults.map((a, i) => { + const link = a.url ? `[${a.name}](${a.url})` : a.name; + return `${i + 1}. ${link} by **${a.artist}**`; + }); + sections.push(`**๐Ÿ’ฟ Albums:**\n${albumLines.join("\n")}`); + } + + if (trackResult) { + sections.push(`**๐ŸŽต Best Track Match:**\n[${trackResult.name}](${trackResult.url}) by **${trackResult.artist}**`); + } + + if (!sections.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`๐Ÿ” No results found for **${query}**.`)] + }); + } + + const desc = sections.join("\n\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`๐Ÿ” Search Results for "${query}"`) + .setDescription(desc)] + }); + } + default: return msg.reply({ embeds: [new EmbedBuilder() @@ -792,21 +2387,54 @@ export async function run(msg, data) { `\`${prefix}lastfm unlink\` โ€” Disconnect your account`, `\`${prefix}lastfm scrobble\` โ€” Toggle auto-scrobbling`, `\`${prefix}lastfm np\` โ€” Show your Last.fm now playing`, - `\`${prefix}lastfm profile\` โ€” View your Last.fm profile`, + `\`${prefix}lastfm profile\` โ€” View your Last.fm profile (or another user's with user option)`, `\`${prefix}lastfm loved\` โ€” View your loved tracks`, - `\`${prefix}lastfm top\` โ€” View your top tracks`, - `\`${prefix}lastfm artists\` โ€” View your top artists`, + `\`${prefix}lastfm top\` โ€” View your top tracks (supports period)`, + `\`${prefix}lastfm artists\` โ€” View your top artists (supports period)`, `\`${prefix}lastfm recent\` โ€” View your recent tracks`, `\`${prefix}lastfm playlists\` โ€” View your Last.fm playlists`, `\`${prefix}lastfm leaderboard\` โ€” Scrobble leaderboard`, `\`${prefix}lastfm love\` โ€” Love the current track`, `\`${prefix}lastfm unlove\` โ€” Unlove the current track`, ``, + `๐Ÿ” **Info Commands:**`, + `\`${prefix}lastfm whoknows [artist]\` โ€” Who in the server listens to an artist`, + `\`${prefix}lastfm whoknowstrack\` โ€” Who knows a specific track`, + `\`${prefix}lastfm whoknowsalbum\` โ€” Who knows a specific album`, + `\`${prefix}lastfm artistinfo\` โ€” Detailed info about an artist`, + `\`${prefix}lastfm albuminfo\` โ€” Detailed info about an album`, + `\`${prefix}lastfm trackinfo\` โ€” Detailed info about a track`, + `\`${prefix}lastfm topalbums\` โ€” View your top albums (supports period)`, + `\`${prefix}lastfm toptags\` โ€” View your top tags/genres`, + `\`${prefix}lastfm tag \` โ€” View info about a specific tag`, + `\`${prefix}lastfm compare @user\` โ€” Compare your taste with another user`, + `\`${prefix}lastfm cover\` โ€” Get album cover art for the current track`, + ``, + `๐Ÿท๏ธ **Tag Commands:**`, + `\`${prefix}lastfm artisttags\` โ€” Top tags for an artist`, + `\`${prefix}lastfm albumtags\` โ€” Top tags for an album`, + `\`${prefix}lastfm tracktags\` โ€” Top tags for a track`, + `\`${prefix}lastfm tagalbums \` โ€” Top albums for a tag`, + ``, + `๐Ÿ‘ฅ **Social Commands:**`, + `\`${prefix}lastfm affinity\` โ€” Find users with similar taste`, + `\`${prefix}lastfm crowns\` โ€” View your artist crowns (#1 listener)`, + `\`${prefix}lastfm friends\` โ€” View your Last.fm friends`, + `\`${prefix}lastfm refreshmembers\` โ€” Refresh server member cache`, + ``, + `๐Ÿ“Š **Charts & Discovery:**`, + `\`${prefix}lastfm weekly [artists|tracks|albums]\` โ€” Weekly charts`, + `\`${prefix}lastfm trending [tracks|artists]\` โ€” Global trending on Last.fm`, + `\`${prefix}lastfm geo [artists|tracks] \` โ€” Top by country`, + `\`${prefix}lastfm artisttracks\` โ€” Your scrobbles for an artist`, + `\`${prefix}lastfm search \` โ€” Universal search`, + ``, `๐ŸŽถ **Play from Last.fm:**`, `\`${prefix}lastfm play loved\` โ€” Play your loved tracks`, `\`${prefix}lastfm play top\` โ€” Play your top tracks`, `\`${prefix}lastfm play recent\` โ€” Play your recent tracks`, `\`${prefix}lastfm play albums\` โ€” Play your top albums`, + `\`${prefix}lastfm play artists\` โ€” Play your top artists' tracks`, `\`${prefix}lastfm play playlist 1\` โ€” Play a playlist`, ``, `๐ŸŽง **Play with a specific provider (defaults to \`top\`):**`, @@ -820,6 +2448,7 @@ export async function run(msg, data) { `\`${prefix}lastfm play lf:top\` โ€” Play top tracks, search on Last.fm`, `\`${prefix}lastfm play lf:recent\` โ€” Play recent tracks, search on Last.fm`, `\`${prefix}lastfm play lf:albums\` โ€” Play top albums, search on Last.fm`, + `\`${prefix}lastfm play lf:artists\` โ€” Play top artists, search on Last.fm`, ``, `๐Ÿ’ก Or use inline: \`${prefix}play lastfm:loved\` or \`${prefix}play lastfm:sp\` or \`${prefix}play lastfm:td:top\``, ].join("\n"))] @@ -866,3 +2495,19 @@ function buildLeaderboardEmbed(lb, pageIdx, prefix) { .setDescription(desc) .setFooter({ text: `๐Ÿ’ก View & sync your count: ${prefix}lastfm profile` }); } + +/** + * Format seconds into mm:ss or h:mm:ss. + * @param {number} seconds + * @returns {string} + */ +function formatDuration(seconds) { + if (!seconds || seconds <= 0) return ""; + const h = Math.floor(seconds / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = seconds % 60; + if (h > 0) { + return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`; + } + return `${m}:${String(s).padStart(2, "0")}`; +} diff --git a/config_example.json b/config_example.json index 086c3b5..e852714 100644 --- a/config_example.json +++ b/config_example.json @@ -96,11 +96,11 @@ "geniusToken": "Genius access token (Used for lyrics); optional", "lastfm": { "Comment": "Last.fm integration: auto-scrobble songs, play loved/top/recent tracks. Register at https://www.last.fm/api/account/create", + "enabled": true, "apiKey": "your_lastfm_api_key", "apiSecret": "your_lastfm_api_secret", "scrobbleThreshold": 0.5, - "scrobbleMinMs": 240000, - "Comment2": "scrobbleThreshold: fraction of track duration before scrobbling (0.5 = 50%). scrobbleMinMs: minimum ms played before scrobble (default 4 min). Both must be met." + "scrobbleMinMs": 240000 }, "fluxerlist": { "Comment": "FluxerList integration: check voters for your server/bot. API keys are allocated by site admins, prefixed with fl_, and visible in your Dashboard. To request access, open a ticket in the Fluxer server.", diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index bdfa4b7..f763f72 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -78,7 +78,7 @@ export class LastFmManager { constructor(config, mysqlConfig) { this.apiKey = config?.apiKey ?? ""; this.apiSecret = config?.apiSecret ?? ""; - this.enabled = !!(this.apiKey && this.apiSecret); + this.enabled = config?.enabled !== false && !!(this.apiKey && this.apiSecret); this.scrobbleThreshold = config?.scrobbleThreshold ?? 0.5; this.scrobbleMinMs = config?.scrobbleMinMs ?? 240_000; @@ -97,7 +97,11 @@ export class LastFmManager { this._totalScrobblesInflight = null; if (!this.enabled) { - logger.settings("[LastFm] Disabled โ€” apiKey or apiSecret missing in config."); + if (config?.enabled === false) { + logger.settings("[LastFm] Disabled โ€” \"enabled\" is set to false in config."); + } else { + logger.settings("[LastFm] Disabled โ€” apiKey or apiSecret missing in config."); + } } } @@ -717,6 +721,534 @@ export class LastFmManager { } } + /** + * Get detailed artist info from Last.fm. + * @param {string} artist - Artist name + * @param {string} [userId=null] - Optional user ID for user-specific playcount + * @returns {Promise} Parsed artist object or null on error + */ + async getArtistInfo(artist, userId = null) { + if (!this.enabled) return null; + + const params = { + method: "artist.getinfo", + api_key: this.apiKey, + artist, + }; + + if (userId) { + const user = await this.getUser(userId); + if (user) params.username = user.username; + } + + try { + const data = await apiCall(params, this.apiSecret); + const a = data.artist; + if (!a) return null; + + return { + name: a.name ?? "", + url: a.url ?? "", + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + tags: (a.tags?.tag ?? []).map(t => t.name ?? t), + bio: a.bio?.summary ?? a.bio?.content ?? "", + stats: { + listeners: Number(a.stats?.listeners ?? 0), + playcount: Number(a.stats?.playcount ?? 0), + }, + similar: (a.similar?.artist ?? []).map(s => ({ + name: s.name ?? "", + url: s.url ?? "", + image: s.image?.[2]?.["#text"] ?? s.image?.[1]?.["#text"] ?? "", + })), + userplaycount: a.stats?.userplaycount ? Number(a.stats.userplaycount) : null, + }; + } catch { + return null; + } + } + + /** + * Get detailed album info from Last.fm. + * @param {string} artist - Artist name + * @param {string} album - Album name + * @param {string} [userId=null] - Optional user ID for user-specific playcount + * @returns {Promise} Parsed album object or null on error + */ + async getAlbumInfo(artist, album, userId = null) { + if (!this.enabled) return null; + + const params = { + method: "album.getinfo", + api_key: this.apiKey, + artist, + album, + }; + + if (userId) { + const user = await this.getUser(userId); + if (user) params.username = user.username; + } + + try { + const data = await apiCall(params, this.apiSecret); + const a = data.album; + if (!a) return null; + + return { + name: a.name ?? "", + artist: a.artist ?? "", + url: a.url ?? "", + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + tags: (a.tags?.tag ?? []).map(t => t.name ?? t), + tracks: (a.tracks?.track ?? []).map(t => ({ + name: t.name ?? "", + url: t.url ?? "", + duration: Number(t.duration ?? 0), + playcount: Number(t.playcount ?? 0), + })), + userplaycount: a.userplaycount ? Number(a.userplaycount) : null, + }; + } catch { + return null; + } + } + + /** + * Get an artist's top tracks from Last.fm. + * @param {string} artist - Artist name + * @param {number} [limit=10] - Max tracks to return + * @returns {Promise>} Array of top tracks + */ + async getArtistTopTracks(artist, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "artist.gettoptracks", + api_key: this.apiKey, + artist, + limit, + }, + this.apiSecret + ); + + return (data.toptracks?.track ?? []).map(t => ({ + artist: t.artist?.name ?? artist, + name: t.name ?? "", + url: t.url ?? "", + playcount: Number(t.playcount ?? 0), + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + } catch { + return []; + } + } + + /** + * Get an artist's top albums from Last.fm. + * @param {string} artist - Artist name + * @param {number} [limit=10] - Max albums to return + * @returns {Promise>} Array of top albums + */ + async getArtistTopAlbums(artist, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "artist.gettopalbums", + api_key: this.apiKey, + artist, + limit, + }, + this.apiSecret + ); + + return (data.topalbums?.album ?? []).map(a => ({ + name: a.name ?? "", + artist: a.artist?.name ?? artist, + url: a.url ?? "", + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch { + return []; + } + } + + /** + * Get similar artists from Last.fm. + * @param {string} artist - Artist name + * @param {number} [limit=10] - Max similar artists to return + * @returns {Promise>} Array of similar artists with match percentage + */ + async getSimilarArtists(artist, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "artist.getsimilar", + api_key: this.apiKey, + artist, + limit, + }, + this.apiSecret + ); + + return (data.similarartists?.artist ?? []).map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + match: parseFloat(a.match ?? 0), + })); + } catch { + return []; + } + } + + /** + * Get a user's top tags from Last.fm. + * @param {string} userId - The Fluxer user ID + * @param {number} [limit=20] - Max tags to return + * @returns {Promise>} Array of top tags with count + */ + async getUserTopTags(userId, limit = 20) { + if (!this.enabled) return []; + + const user = await this.getUser(userId); + if (!user) return []; + + try { + const data = await apiCall( + { + method: "user.gettoptags", + api_key: this.apiKey, + user: user.username, + limit, + }, + this.apiSecret + ); + + return (data.toptags?.tag ?? []).map(t => ({ + name: t.name ?? "", + url: t.url ?? "", + count: Number(t.count ?? 0), + })); + } catch { + return []; + } + } + + /** + * Get detailed tag info from Last.fm. + * @param {string} tag - Tag name + * @returns {Promise} Tag info or null on error + */ + async getTagInfo(tag) { + if (!this.enabled) return null; + + try { + const data = await apiCall( + { + method: "tag.getinfo", + api_key: this.apiKey, + tag, + }, + this.apiSecret + ); + + const t = data.tag; + if (!t) return null; + + return { + name: t.name ?? "", + url: t.url ?? "", + reach: Number(t.reach ?? 0), + count: Number(t.taggings?.total ?? t.total ?? 0), + summary: t.wiki?.summary ?? "", + }; + } catch { + return null; + } + } + + /** + * Get top tracks for a tag from Last.fm. + * @param {string} tag - Tag name + * @param {number} [limit=10] - Max tracks to return + * @returns {Promise>} Array of tracks + */ + async getTagTopTracks(tag, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "tag.gettoptracks", + api_key: this.apiKey, + tag, + limit, + }, + this.apiSecret + ); + + return (data.tracks?.track ?? []).map(t => ({ + artist: t.artist?.name ?? "Unknown", + name: t.name ?? "", + url: t.url ?? "", + playcount: Number(t.playcount ?? 0), + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + } catch { + return []; + } + } + + /** + * Get top artists for a tag from Last.fm. + * @param {string} tag - Tag name + * @param {number} [limit=10] - Max artists to return + * @returns {Promise>} Array of artists + */ + async getTagTopArtists(tag, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "tag.gettopartists", + api_key: this.apiKey, + tag, + limit, + }, + this.apiSecret + ); + + return (data.topartists?.artist ?? []).map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch { + return []; + } + } + + /** + * Get play counts for an artist across multiple users ("who knows"). + * Processes users in batches of 5 for concurrency control. + * @param {string} artist - Artist name + * @param {Array} userIds - Array of Fluxer user IDs to check + * @returns {Promise>} + * Sorted by playcount descending, only includes users with playcount > 0 + */ + async getWhoKnows(artist, userIds) { + if (!this.enabled) return []; + if (!Array.isArray(userIds) || !userIds.length) return []; + + const concurrency = 5; + const results = []; + + for (let i = 0; i < userIds.length; i += concurrency) { + const batch = userIds.slice(i, i + concurrency); + + const batchResults = await Promise.allSettled( + batch.map(async (uid) => { + const user = await this.getUser(uid); + if (!user) return null; + + try { + const info = await this.getArtistInfo(artist, uid); + const playcount = info?.userplaycount ?? 0; + return { + userId: uid, + username: user.username, + playcount, + }; + } catch { + return { + userId: uid, + username: user.username, + playcount: 0, + }; + } + }) + ); + + for (const r of batchResults) { + if (r.status === "fulfilled" && r.value && r.value.playcount > 0) { + results.push(r.value); + } + } + } + + results.sort((a, b) => b.playcount - a.playcount); + return results; + } + + /** + * Compare two Last.fm users by their top artists overlap. + * @param {string} userId1 - First Fluxer user ID + * @param {string} userId2 - Second Fluxer user ID + * @returns {Promise} Comparison result or null on error + */ + async compareUsers(userId1, userId2) { + if (!this.enabled) return null; + + try { + const user1Data = await this.getUser(userId1); + const user2Data = await this.getUser(userId2); + if (!user1Data || !user2Data) return null; + + const [artists1, artists2] = await Promise.all([ + this.getTopArtists(userId1, "overall", 50), + this.getTopArtists(userId2, "overall", 50), + ]); + + const names1 = new Set(artists1.map(a => a.name.toLowerCase())); + const names2 = new Set(artists2.map(a => a.name.toLowerCase())); + + const commonNames = [...names1].filter(n => names2.has(n)); + const commonArtists = artists1 + .filter(a => names2.has(a.name.toLowerCase())) + .map(a => ({ + name: a.name, + url: a.url, + playcount: a.playcount, + })); + + const totalUnique = new Set([...names1, ...names2]).size; + const matchPercentage = totalUnique > 0 + ? Math.round((commonNames.length / totalUnique) * 100) + : 0; + + return { + user1: { + username: user1Data.username, + totalArtists: names1.size, + }, + user2: { + username: user2Data.username, + totalArtists: names2.size, + }, + commonArtists, + matchPercentage, + }; + } catch { + return null; + } + } + + /** + * Get a user's weekly chart list from Last.fm. + * @param {string} userId - The Fluxer user ID + * @returns {Promise>} Array of chart periods + */ + async getUserWeeklyChartList(userId) { + if (!this.enabled) return []; + + const user = await this.getUser(userId); + if (!user) return []; + + try { + const data = await apiCall( + { + method: "user.getweeklychartlist", + api_key: this.apiKey, + user: user.username, + }, + this.apiSecret + ); + + return (data.weeklychartlist?.chart ?? []).map(c => ({ + from: Number(c.from ?? 0), + to: Number(c.to ?? 0), + })); + } catch { + return []; + } + } + + /** + * Search Last.fm for artists matching a query. + * @param {string} query - Search query + * @param {number} [limit=10] - Max results to return + * @returns {Promise>} Array of matching artists + */ + async searchArtist(query, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "artist.search", + api_key: this.apiKey, + artist: query, + limit, + }, + this.apiSecret + ); + + const matches = data?.results?.artistmatches?.artist; + const artists = Array.isArray(matches) + ? matches + : matches + ? [matches] + : []; + + return artists.map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + listeners: Number(a.listeners ?? 0), + })); + } catch { + return []; + } + } + + /** + * Search Last.fm for albums matching a query. + * @param {string} query - Search query + * @param {number} [limit=10] - Max results to return + * @returns {Promise>} Array of matching albums + */ + async searchAlbum(query, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "album.search", + api_key: this.apiKey, + album: query, + limit, + }, + this.apiSecret + ); + + const matches = data?.results?.albummatches?.album; + const albums = Array.isArray(matches) + ? matches + : matches + ? [matches] + : []; + + return albums.map(a => ({ + name: a.name ?? "", + artist: a.artist ?? "", + url: a.url ?? "", + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch { + return []; + } + } + /** * Parse a Last.fm music URL and extract artist and track info. * Supports: @@ -1042,8 +1574,40 @@ export class LastFmManager { username: user.username, tracks, }; + case "artists": + const topArtistsList = await this.getTopArtists(userId, options.period ?? "overall", limit); + const artistTrackResults = []; + const artistConcurrency = 3; + for (let ai = 0; ai < topArtistsList.length; ai += artistConcurrency) { + const artistBatch = topArtistsList.slice(ai, ai + artistConcurrency); + const artistResults = await Promise.allSettled( + artistBatch.map(async (ar) => { + try { + const topTracks = await this.getArtistTopTracks(ar.name, 3); + return topTracks.map(t => ({ + artist: t.artist ?? ar.name, + name: t.name, + url: t.url, + query: `${t.name} ${t.artist ?? ar.name}`, + image: t.image ?? ar.image ?? "", + })); + } catch { + return []; + } + }) + ); + for (const r of artistResults) { + if (r.status === "fulfilled" && r.value) { + artistTrackResults.push(...r.value); + } + } + } + return { + username: user.username, + tracks: artistTrackResults.slice(0, limit * 3), + }; default: - throw new Error(`Unknown Last.fm category: ${category}. Use loved, top, recent, playlist, or albums.`); + throw new Error(`Unknown Last.fm category: ${category}. Use loved, top, recent, playlist, albums, or artists.`); } return { @@ -1204,6 +1768,523 @@ export class LastFmManager { } } + /** + * Get a user's Last.fm friends list. + * @param {string} userId - The Fluxer user ID + * @param {number} [limit=20] - Max friends to return + * @returns {Promise>} Array of friend objects + */ + async getUserFriends(userId, limit = 20) { + if (!this.enabled) return []; + const user = await this.getUser(userId); + if (!user) return []; + try { + const data = await apiCall({ + method: "user.getfriends", + api_key: this.apiKey, + user: user.username, + limit, + }, this.apiSecret); + return (data.friends?.user ?? []).map(f => ({ + name: f.name ?? "", + url: f.url ?? "", + image: f.image?.[2]?.["#text"] ?? f.image?.[1]?.["#text"] ?? "", + realname: f.realname ?? "", + country: f.country ?? "", + })); + } catch { return []; } + } + + /** + * Get a user's weekly artist chart. + * @param {string} userId - The Fluxer user ID + * @param {number|null} [from=null] - Start timestamp + * @param {number|null} [to=null] - End timestamp + * @returns {Promise>} Array of artist objects + */ + async getUserWeeklyArtistChart(userId, from = null, to = null) { + if (!this.enabled) return []; + const user = await this.getUser(userId); + if (!user) return []; + try { + const params = { + method: "user.getweeklyartistchart", + api_key: this.apiKey, + user: user.username, + }; + if (from) params.from = from; + if (to) params.to = to; + const data = await apiCall(params, this.apiSecret); + return (data.weeklyartistchart?.artist ?? []).map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch { return []; } + } + + /** + * Get a user's weekly track chart. + * @param {string} userId - The Fluxer user ID + * @param {number|null} [from=null] - Start timestamp + * @param {number|null} [to=null] - End timestamp + * @returns {Promise>} Array of track objects + */ + async getUserWeeklyTrackChart(userId, from = null, to = null) { + if (!this.enabled) return []; + const user = await this.getUser(userId); + if (!user) return []; + try { + const params = { + method: "user.getweeklytrackchart", + api_key: this.apiKey, + user: user.username, + }; + if (from) params.from = from; + if (to) params.to = to; + const data = await apiCall(params, this.apiSecret); + return (data.weeklytrackchart?.track ?? []).map(t => ({ + name: t.name ?? "", + artist: t.artist?.["#text"] ?? t.artist ?? "", + url: t.url ?? "", + playcount: Number(t.playcount ?? 0), + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + } catch { return []; } + } + + /** + * Get a user's weekly album chart. + * @param {string} userId - The Fluxer user ID + * @param {number|null} [from=null] - Start timestamp + * @param {number|null} [to=null] - End timestamp + * @returns {Promise>} Array of album objects + */ + async getUserWeeklyAlbumChart(userId, from = null, to = null) { + if (!this.enabled) return []; + const user = await this.getUser(userId); + if (!user) return []; + try { + const params = { + method: "user.getweeklyalbumchart", + api_key: this.apiKey, + user: user.username, + }; + if (from) params.from = from; + if (to) params.to = to; + const data = await apiCall(params, this.apiSecret); + return (data.weeklyalbumchart?.album ?? []).map(a => ({ + name: a.name ?? "", + artist: a.artist?.["#text"] ?? a.artist ?? "", + url: a.url ?? "", + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch { return []; } + } + + /** + * Get top tags for an artist. + * @param {string} artist - Artist name + * @param {number} [limit=10] - Max tags to return + * @returns {Promise>} Array of tag objects + */ + async getArtistTopTags(artist, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "artist.gettoptags", + api_key: this.apiKey, + artist, + limit, + }, this.apiSecret); + return (data.toptags?.tag ?? []).map(t => ({ + name: t.name ?? "", + url: t.url ?? "", + count: Number(t.count ?? 0), + })); + } catch { return []; } + } + + /** + * Get top tags for an album. + * @param {string} artist - Artist name + * @param {string} album - Album name + * @param {number} [limit=10] - Max tags to return + * @returns {Promise>} Array of tag objects + */ + async getAlbumTopTags(artist, album, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "album.gettoptags", + api_key: this.apiKey, + artist, + album, + limit, + }, this.apiSecret); + return (data.toptags?.tag ?? []).map(t => ({ + name: t.name ?? "", + url: t.url ?? "", + count: Number(t.count ?? 0), + })); + } catch { return []; } + } + + /** + * Get top tags for a track. + * @param {string} artist - Artist name + * @param {string} track - Track name + * @param {number} [limit=10] - Max tags to return + * @returns {Promise>} Array of tag objects + */ + async getTrackTopTags(artist, track, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "track.gettoptags", + api_key: this.apiKey, + artist, + track, + limit, + }, this.apiSecret); + return (data.toptags?.tag ?? []).map(t => ({ + name: t.name ?? "", + url: t.url ?? "", + count: Number(t.count ?? 0), + })); + } catch { return []; } + } + + /** + * Get top albums for a tag. + * @param {string} tag - Tag name + * @param {number} [limit=10] - Max albums to return + * @returns {Promise>} Array of album objects + */ + async getTagTopAlbums(tag, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "tag.gettopalbums", + api_key: this.apiKey, + tag, + limit, + }, this.apiSecret); + return (data.albums?.album ?? []).map(a => ({ + name: a.name ?? "", + artist: a.artist?.name ?? "Unknown", + url: a.url ?? "", + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch { return []; } + } + + /** + * Get top artists by country. + * @param {string} country - Country name + * @param {number} [limit=10] - Max artists to return + * @returns {Promise>} Array of artist objects + */ + async getGeoTopArtists(country, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "geo.gettopartists", + api_key: this.apiKey, + country, + limit, + }, this.apiSecret); + return (data.topartists?.artist ?? []).map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + listeners: Number(a.listeners ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch { return []; } + } + + /** + * Get top tracks by country. + * @param {string} country - Country name + * @param {number} [limit=10] - Max tracks to return + * @returns {Promise>} Array of track objects + */ + async getGeoTopTracks(country, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "geo.gettoptracks", + api_key: this.apiKey, + country, + limit, + }, this.apiSecret); + return (data.tracks?.track ?? []).map(t => ({ + name: t.name ?? "", + artist: t.artist?.name ?? "Unknown", + url: t.url ?? "", + listeners: Number(t.listeners ?? 0), + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + } catch { return []; } + } + + /** + * Get global trending tracks from Last.fm charts. + * @param {number} [limit=10] - Max tracks to return + * @returns {Promise>} Array of trending track objects + */ + async getChartTopTracks(limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "chart.gettoptracks", + api_key: this.apiKey, + limit, + }, this.apiSecret); + return (data.tracks?.track ?? []).map(t => ({ + name: t.name ?? "", + artist: t.artist?.name ?? "Unknown", + url: t.url ?? "", + listeners: Number(t.listeners ?? 0), + playcount: Number(t.playcount ?? 0), + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + } catch { return []; } + } + + /** + * Get global trending artists from Last.fm charts. + * @param {number} [limit=10] - Max artists to return + * @returns {Promise>} Array of trending artist objects + */ + async getChartTopArtists(limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "chart.gettopartists", + api_key: this.apiKey, + limit, + }, this.apiSecret); + return (data.artists?.artist ?? []).map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + listeners: Number(a.listeners ?? 0), + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch { return []; } + } + + /** + * Get play counts for a specific track across multiple users ("who knows track"). + * @param {string} artist - Artist name + * @param {string} track - Track name + * @param {Array} userIds - Array of Fluxer user IDs to check + * @returns {Promise>} + */ + async getWhoKnowsTrack(artist, track, userIds) { + if (!this.enabled) return []; + if (!Array.isArray(userIds) || !userIds.length) return []; + + const concurrency = 5; + const results = []; + + for (let i = 0; i < userIds.length; i += concurrency) { + const batch = userIds.slice(i, i + concurrency); + + const batchResults = await Promise.allSettled( + batch.map(async (uid) => { + const user = await this.getUser(uid); + if (!user) return null; + + try { + const info = await this.getTrackInfo(artist, track, uid); + const playcount = Number(info?.userplaycount ?? 0); + return { + userId: uid, + username: user.username, + playcount, + }; + } catch { + return { + userId: uid, + username: user.username, + playcount: 0, + }; + } + }) + ); + + for (const r of batchResults) { + if (r.status === "fulfilled" && r.value && r.value.playcount > 0) { + results.push(r.value); + } + } + } + + results.sort((a, b) => b.playcount - a.playcount); + return results; + } + + /** + * Get play counts for a specific album across multiple users ("who knows album"). + * @param {string} artist - Artist name + * @param {string} album - Album name + * @param {Array} userIds - Array of Fluxer user IDs to check + * @returns {Promise>} + */ + async getWhoKnowsAlbum(artist, album, userIds) { + if (!this.enabled) return []; + if (!Array.isArray(userIds) || !userIds.length) return []; + + const concurrency = 5; + const results = []; + + for (let i = 0; i < userIds.length; i += concurrency) { + const batch = userIds.slice(i, i + concurrency); + + const batchResults = await Promise.allSettled( + batch.map(async (uid) => { + const user = await this.getUser(uid); + if (!user) return null; + + try { + const info = await this.getAlbumInfo(artist, album, uid); + const playcount = Number(info?.userplaycount ?? 0); + return { + userId: uid, + username: user.username, + playcount, + }; + } catch { + return { + userId: uid, + username: user.username, + playcount: 0, + }; + } + }) + ); + + for (const r of batchResults) { + if (r.status === "fulfilled" && r.value && r.value.playcount > 0) { + results.push(r.value); + } + } + } + + results.sort((a, b) => b.playcount - a.playcount); + return results; + } + + /** + * Find users with similar top artists (affinity). + * For each pair of users, compute overlap of their top artists. + * @param {Array} userIds - Array of Fluxer user IDs + * @param {number} [limit=10] - Max results to return + * @returns {Promise>} Array of affinity results + */ + async getAffinity(userIds, limit = 10) { + if (!this.enabled) return []; + if (!Array.isArray(userIds) || userIds.length < 2) return []; + + const userArtistsMap = new Map(); + const concurrency = 5; + + for (let i = 0; i < userIds.length; i += concurrency) { + const batch = userIds.slice(i, i + concurrency); + const results = await Promise.allSettled( + batch.map(async (uid) => { + const user = await this.getUser(uid); + if (!user) return null; + try { + const artists = await this.getTopArtists(uid, "overall", 50); + return { uid, username: user.username, artists }; + } catch { + return null; + } + }) + ); + for (const r of results) { + if (r.status === "fulfilled" && r.value) { + userArtistsMap.set(r.value.uid, r.value); + } + } + } + + const entries = [...userArtistsMap.values()]; + const affinityResults = []; + + for (let i = 0; i < entries.length; i++) { + for (let j = i + 1; j < entries.length; j++) { + const a = entries[i]; + const b = entries[j]; + const namesA = new Set(a.artists.map(ar => ar.name.toLowerCase())); + const namesB = new Set(b.artists.map(ar => ar.name.toLowerCase())); + const common = [...namesA].filter(n => namesB.has(n)); + if (common.length > 0) { + const commonArtists = a.artists + .filter(ar => namesB.has(ar.name.toLowerCase())) + .map(ar => ({ name: ar.name, url: ar.url, playcount: ar.playcount })); + affinityResults.push({ + users: [a.username, b.username], + userIds: [a.uid, b.uid], + matchCount: common.length, + commonArtists, + }); + } + } + } + + affinityResults.sort((a, b) => b.matchCount - a.matchCount); + return affinityResults.slice(0, limit); + } + + /** + * Get artist crowns for a user โ€” artists where they are the #1 listener in the server. + * @param {string} userId - The Fluxer user ID + * @param {Array} userIds - Array of Fluxer user IDs in the server + * @returns {Promise>} Array of crown objects + */ + async getCrowns(userId, userIds) { + if (!this.enabled) return []; + const user = await this.getUser(userId); + if (!user) return []; + try { + const topArtists = await this.getTopArtists(userId, "overall", 50); + const crowns = []; + const concurrency = 3; + + for (let i = 0; i < topArtists.length; i += concurrency) { + const batch = topArtists.slice(i, i + concurrency); + const results = await Promise.allSettled( + batch.map(async (artist) => { + const listeners = await this.getWhoKnows(artist.name, userIds); + if (listeners.length > 0 && listeners[0].userId === String(userId)) { + return { + artist: artist.name, + artistUrl: artist.url, + userPlaycount: artist.playcount, + nextBest: listeners.length > 1 ? listeners[1] : null, + image: artist.image ?? "", + }; + } + return null; + }) + ); + for (const r of results) { + if (r.status === "fulfilled" && r.value) crowns.push(r.value); + } + } + + crowns.sort((a, b) => b.userPlaycount - a.userPlaycount); + return crowns; + } catch { return []; } + } + _assertEnabled() { if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret)."); }