diff --git a/commands/lastfm/listening.mjs b/commands/lastfm/listening.mjs index 0a310be..c6aa01e 100644 --- a/commands/lastfm/listening.mjs +++ b/commands/lastfm/listening.mjs @@ -10,7 +10,6 @@ import { Utils } from "../../src/utils/Utils.mjs"; import { logger } from "../../src/core/Logger.mjs"; import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs"; import { notLinked, extractPeriod } from "./shared.mjs"; -import { getGuildLinkedUsers } from "./whoknows.mjs"; /** * Action names dispatched to this module. @@ -67,6 +66,7 @@ function buildTrackList(username, title, tracks, tr, showPlaycount = false, pref * @param {function(string, object=): string} tr - Translator bound to the invoking message. * @param {object} [opts] - Extra options. * @param {string|null} [opts.requesterId] - Invoking user's ID for the "you" marker. + * @param {string|null} [opts.extraLine] - Extra description line (e.g. the requester's rank) appended below the list. * @returns {EmbedBuilder} The constructed embed. */ function buildLeaderboardEmbed(lb, pageIdx, prefix, tr, opts = {}) { @@ -84,7 +84,7 @@ function buildLeaderboardEmbed(lb, pageIdx, prefix, tr, opts = {}) { return `${medal} **${rank}.** ${who}${lfName} — **${count}** ${tr("responses.lastfm.leaderboardScrobbles")}${marker}`; }); - const desc = lines.join("\n").slice(0, 4096); + const desc = (lines.join("\n") + (opts.extraLine ? `\n\n${opts.extraLine}` : "")).slice(0, 4096); const title = lb.scope === "server" ? tr("responses.lastfm.leaderboardTitleServer") : tr("responses.lastfm.leaderboardTitleGlobal"); @@ -162,18 +162,9 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar case "leaderboard": case "lb": { - /* Server scope when the guild's members are resolvable (ranks only - people actually in this server), global fallback for DMs. */ - const guild = msg.message?.guild ?? msg.message?.member?.guild ?? null; - const guildIds = guild ? await getGuildLinkedUsers(guild).catch(() => []) : []; - const useServer = guildIds.length > 0; - const fetchLb = (page, perPage = 10) => useServer - ? lastfm.getServerLeaderboard(guildIds, page, perPage) - : lastfm.getLeaderboard(page, perPage); - let lb; try { - lb = await fetchLb(0); + lb = await lastfm.getLeaderboard(0, 10); } catch (err) { return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] @@ -188,8 +179,14 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar }); } + let myRank = null; + try { myRank = await lastfm.getUserRank?.(userId) ?? null; } catch (_) { myRank = null; } + const rankLine = () => (myRank && !lb.entries.some(e => String(e.userId) === String(userId)) + ? tr("responses.lastfm.leaderboardYourRank", { rank: myRank.rank, count: Utils.formatNumber(myRank.scrobbleCount) }) + : null); + if (lb.totalPages <= 1) { - const embed = buildLeaderboardEmbed(lb, 0, prefix, tr, { requesterId: userId }); + const embed = buildLeaderboardEmbed(lb, 0, prefix, tr, { requesterId: userId, extraLine: rankLine() }); return msg.reply({ embeds: [embed] }); } @@ -199,7 +196,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar const footerText = expired ? tr("responses.lastfm.leaderboardControlsExpired") : tr("responses.lastfm.leaderboardPageFooter", { current: pageIdx + 1, total: lb.totalPages }); - const embed = buildLeaderboardEmbed(lb, pageIdx, prefix, tr, { requesterId: userId }); + const embed = buildLeaderboardEmbed(lb, pageIdx, prefix, tr, { requesterId: userId, extraLine: rankLine() }); embed.setFooter({ text: footerText }); return { embeds: [embed] }; }; @@ -249,7 +246,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar } try { - lb = await fetchLb(currentPage); + lb = await lastfm.getLeaderboard(currentPage, 10); } catch(e) { logger.warn("[LastFm] Error:", e?.message); } await replyMsg.edit(buildPage(currentPage)).catch(() => {}); diff --git a/src/services/lastfm/ServerStatsMixin.mjs b/src/services/lastfm/ServerStatsMixin.mjs index 705a293..e3f18c5 100644 --- a/src/services/lastfm/ServerStatsMixin.mjs +++ b/src/services/lastfm/ServerStatsMixin.mjs @@ -357,6 +357,36 @@ const ServerStatsMixin = { return { entries, totalUsers, page, perPage, totalPages }; }, + /** + * Global rank (1-based) of one user on the all-time scrobble leaderboard. + * Returns null when the user is not linked or has no scrobbles recorded + * yet (they are not ranked). Used so anyone can check whether they are + * top 1, 2, 3 ... even when their row is not on the visible page. + * @async + * @param {string} userId - Platform user ID to look up. + * @returns {Promise<{rank: number, scrobbleCount: number}|null>} Rank info or null. + */ + async getUserRank(userId) { + if (!this.enabled || !userId) return null; + + const pool = await this._getPool(); + const f = this._botIdFilter(); + + const [mine] = await pool.execute( + `SELECT scrobble_count FROM lastfm_users WHERE user_id = ?${f.where}`, + [String(userId), ...f.params] + ); + const count = Number(mine[0]?.scrobble_count ?? 0); + if (!(count > 0)) return null; + + const [ahead] = await pool.execute( + `SELECT COUNT(*) AS n FROM lastfm_users WHERE scrobble_count > ?${f.where}`, + [count, ...f.params] + ); + + return { rank: Number(ahead[0]?.n ?? 0) + 1, scrobbleCount: count }; + }, + /** * Get the scrobble leaderboard scoped to a set of platform user IDs * (typically the members of one guild), with pagination. Refreshes only diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index d7ce6d5..97c5c83 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -734,7 +734,8 @@ "crownsFooter": "يمتلك {{count}} تاجاً", "noArtistTags": "🏷️ لا توجد وسوم للفنان **{{artist}}**.", "artistTagsTitle": "🏷️ وسوم أعلى لـ {{artist}}", - "listeners": "مستمع" + "listeners": "مستمع", + "leaderboardYourRank": "📍 ترتيبك: **#{{rank}}** ({{count}} سكرابل)" }, "messages": { "missingCriticalPermsTitle": "صلاحيات مفقودة — البوت لا يستطيع العمل بشكل صحيح", diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index ec16d7f..64a7c43 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -734,7 +734,8 @@ "crownsFooter": "{{count}} تاج هەڵگیراوە", "noArtistTags": "🏷️ هیچ تاگێک بۆ هونەرمەندی **{{artist}}** نەدۆزرایەوە.", "artistTagsTitle": "🏷️ تاگە سەرەکییەکان بۆ {{artist}}", - "listeners": "گوێگر" + "listeners": "گوێگر", + "leaderboardYourRank": "📍 پلەی تۆ: **#{{rank}}** ({{count}} scrobble)" }, "messages": { "missingCriticalPermsTitle": "مۆڵەتە کەمەکان — بۆت ناتوانێت بە دروستی کار بکات", diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index 1a05f59..426c93e 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -734,7 +734,8 @@ "crownsFooter": "{{count}} Krone(n) im Besitz", "noArtistTags": "🏷️ Keine Tags für Künstler **{{artist}}** gefunden.", "artistTagsTitle": "🏷️ Top-Tags für {{artist}}", - "listeners": "Hörer" + "listeners": "Hörer", + "leaderboardYourRank": "📍 Dein Rang: **#{{rank}}** ({{count}} Scrobbles)" }, "messages": { "missingCriticalPermsTitle": "Fehlende Berechtigungen — Bot kann nicht ordnungsgemäß arbeiten", diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index 23a6e35..b906bf5 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -409,7 +409,8 @@ "whoknowsAlbumTitle": "👤 Who knows {{album}}?", "noArtistTags": "🏷️ No tags found for artist **{{artist}}**.", "artistTagsTitle": "🏷️ Top Tags for {{artist}}", - "listeners": "listeners" + "listeners": "listeners", + "leaderboardYourRank": "📍 Your rank: **#{{rank}}** ({{count}} scrobbles)" }, "list": { "empty": "📭 The queue is empty. Use `{{prefix}}play` to add songs!", diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index 27d3495..8caddac 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -734,7 +734,8 @@ "crownsFooter": "{{count}} coroa{{plural}} mantida{{plural}}", "noArtistTags": "🏷️ Nenhuma tag encontrada para o artista **{{artist}}**.", "artistTagsTitle": "🏷️ Tags Populares para {{artist}}", - "listeners": "ouvintes" + "listeners": "ouvintes", + "leaderboardYourRank": "📍 Sua posição: **#{{rank}}** ({{count}} scrobbles)" }, "messages": { "missingCriticalPermsTitle": "Permissões Ausentes — Bot Não Pode Funcionar Corretamente", diff --git a/storage/locales/bot/tr.json b/storage/locales/bot/tr.json index 7eb3ebe..9f811d7 100644 --- a/storage/locales/bot/tr.json +++ b/storage/locales/bot/tr.json @@ -405,7 +405,8 @@ "crownsFooter": "{{count}} taç elde tutuluyor", "noArtistTags": "🏷️ Sanatçı **{{artist}}** için etiket bulunamadı.", "artistTagsTitle": "🏷️ {{artist}} için En Çok Dinlenen Etiketler", - "listeners": "dinleyici" + "listeners": "dinleyici", + "leaderboardYourRank": "📍 Sıralan: **#{{rank}}** ({{count}} scrobble)" }, "list": { "empty": "📭 Kuyruk boş. Şarkı eklemek için `{{prefix}}play` kullanın!",