From c9332a15af86fe1bafe7b00c2a2490233d142b83 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Sat, 21 Nov 2026 02:02:04 +0300 Subject: [PATCH] feat(music): persist music analytics to MySQL with 24h/year timeframes and personal recap --- commands/mywrapped.mjs | 8 +- commands/top.mjs | 65 ++++++-- commands/wrapped.mjs | 4 +- src/music/GuildStats.mjs | 246 ++++++++++++++++------------- src/music/PlayerEventsMixin.mjs | 31 +++- src/music/PlayerLifecycleMixin.mjs | 2 +- src/music/player/Player.mjs | 4 +- storage/locales/bot/ar-SA.json | 10 +- storage/locales/bot/ckb.json | 10 +- storage/locales/bot/de-DE.json | 10 +- storage/locales/bot/en.json | 10 +- storage/locales/bot/pt-BR.json | 10 +- storage/locales/bot/tr.json | 10 +- storage/locales/bot/zh-CN.json | 10 +- storage/locales/bot/zh-TW.json | 10 +- 15 files changed, 274 insertions(+), 166 deletions(-) diff --git a/commands/mywrapped.mjs b/commands/mywrapped.mjs index 4449e68..4228883 100644 --- a/commands/mywrapped.mjs +++ b/commands/mywrapped.mjs @@ -7,7 +7,7 @@ import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { GuildStats } from "../src/music/GuildStats.mjs"; import { cleanId, Utils } from "../src/utils/Utils.mjs"; -import { getGlobalColor } from "../src/ui/index.mjs"; +import { getGlobalColor, getMessageGuildId } from "../src/ui/index.mjs"; /** @type {CommandBuilder} */ export const command = new CommandBuilder() @@ -29,11 +29,11 @@ export const command = new CommandBuilder() * @returns {Promise} */ export async function run(message, data) { - const guildId = cleanId(message.message?.guildId ?? message.channel?.guildId); + const guildId = cleanId(getMessageGuildId(message)); const prefix = this.handler.getPrefix(guildId) || "%"; const rawAuthor = message.message?.author ?? message.author; - const authorId = cleanId(rawAuthor?.id); + const authorId = cleanId(rawAuthor?.id ?? message.authorId ?? message.message?.authorId ?? ""); const rawArg = ( data?.get?.("target")?.value ?? @@ -73,6 +73,8 @@ export async function run(message, data) { if (stats) { isGlobalFallback = true; } + } else if (stats.isGlobalFallback) { + isGlobalFallback = true; } if (!stats || stats.totalTracks === 0) { diff --git a/commands/top.mjs b/commands/top.mjs index 9e0a32e..a7ba987 100644 --- a/commands/top.mjs +++ b/commands/top.mjs @@ -7,7 +7,7 @@ import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { GuildStats } from "../src/music/GuildStats.mjs"; import { cleanId, Utils } from "../src/utils/Utils.mjs"; -import { getGlobalColor } from "../src/ui/index.mjs"; +import { getGlobalColor, getMessageGuildId } from "../src/ui/index.mjs"; import { run as runMyWrapped } from "./mywrapped.mjs"; const PAGE_SIZE = 10; @@ -23,7 +23,7 @@ export const command = new CommandBuilder() .addTextOption((o) => o .setName("timeframe") - .setDescription("Filter timeframe: week, month, all, or global, or page number.", "options.top.timeframe") + .setDescription("Filter timeframe: 24h, week, month, year, all, or global, or page number.", "options.top.timeframe") .setRequired(false) ); @@ -34,7 +34,7 @@ export const command = new CommandBuilder() * @returns {Promise} */ export async function run(message, data) { - const guildId = cleanId(message.message?.guildId ?? message.channel?.guildId); + const guildId = cleanId(getMessageGuildId(message)); const prefix = this.handler.getPrefix(guildId) || "%"; const rawArg = ( @@ -55,6 +55,7 @@ export async function run(message, data) { let isGlobal = false; let timeframe = "month"; + let explicitTimeframe = false; let targetPage = 1; for (const token of tokens) { @@ -64,21 +65,52 @@ export async function run(message, data) { } else if (token === "global" || token === "network") { isGlobal = true; timeframe = "global"; + explicitTimeframe = true; + } else if (token === "day" || token === "today" || token === "24h" || token === "d" || token === "1d") { + timeframe = "day"; + explicitTimeframe = true; } else if (token === "week" || token === "w" || token === "7d") { timeframe = "week"; - } else if (token === "all" || token === "alltime" || token === "total") { - timeframe = "all"; + explicitTimeframe = true; } else if (token === "month" || token === "m" || token === "30d") { timeframe = "month"; + explicitTimeframe = true; + } else if (token === "year" || token === "y" || token === "1y" || token === "365d") { + timeframe = "year"; + explicitTimeframe = true; + } else if (token === "all" || token === "alltime" || token === "total") { + timeframe = "all"; + explicitTimeframe = true; } } - let { tracks, topArtist } = isGlobal - ? await GuildStats.getGlobalTopTracks(MAX_TRACKS) - : await GuildStats.getTopTracks(guildId, timeframe, MAX_TRACKS); + let tracks = []; + let topArtist = null; + + if (isGlobal) { + const res = await GuildStats.getGlobalTopTracks(MAX_TRACKS); + tracks = res.tracks || []; + topArtist = res.topArtist; + } else if (explicitTimeframe) { + const res = await GuildStats.getTopTracks(guildId, timeframe, MAX_TRACKS); + tracks = res.tracks || []; + topArtist = res.topArtist; + } else { + /* If no explicit timeframe passed, cascade: day -> week -> month -> year -> all */ + const tfList = ["day", "week", "month", "year", "all"]; + for (const tf of tfList) { + const res = await GuildStats.getTopTracks(guildId, tf, MAX_TRACKS); + if (res?.tracks && res.tracks.length > 0) { + tracks = res.tracks; + topArtist = res.topArtist; + timeframe = tf; + break; + } + } + } let fallbackGlobal = false; - if ((!tracks || tracks.length === 0) && !isGlobal) { + if ((!tracks || tracks.length === 0) && !isGlobal && !explicitTimeframe) { const globalRes = await GuildStats.getGlobalTopTracks(MAX_TRACKS); if (globalRes?.tracks && globalRes.tracks.length > 0) { tracks = globalRes.tracks; @@ -91,11 +123,16 @@ export async function run(message, data) { ? `🌐 ${this.t(message, "responses.top.globalAuthor")}` : `🏆 ${this.t(message, "responses.top.topAuthor")}`; - const timeframeLabel = (isGlobal || fallbackGlobal) - ? "Global" - : (timeframe === "week" - ? this.t(message, "responses.top.timeframeWeek") - : (timeframe === "all" ? this.t(message, "responses.top.timeframeAll") : this.t(message, "responses.top.timeframeMonth"))); + const getTimeframeLabel = (tf) => { + if (isGlobal || fallbackGlobal) return "Global"; + if (tf === "day") return this.t(message, "responses.top.timeframeDay"); + if (tf === "week") return this.t(message, "responses.top.timeframeWeek"); + if (tf === "month") return this.t(message, "responses.top.timeframeMonth"); + if (tf === "year") return this.t(message, "responses.top.timeframeYear"); + return this.t(message, "responses.top.timeframeAll"); + }; + + const timeframeLabel = getTimeframeLabel(timeframe); const titleName = (isGlobal || fallbackGlobal) ? this.t(message, "responses.top.globalTitle") diff --git a/commands/wrapped.mjs b/commands/wrapped.mjs index d84415d..0bba76c 100644 --- a/commands/wrapped.mjs +++ b/commands/wrapped.mjs @@ -7,7 +7,7 @@ import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { GuildStats } from "../src/music/GuildStats.mjs"; import { cleanId, Utils } from "../src/utils/Utils.mjs"; -import { getGlobalColor } from "../src/ui/index.mjs"; +import { getGlobalColor, getMessageGuildId } from "../src/ui/index.mjs"; import { run as runMyWrapped } from "./mywrapped.mjs"; /** @type {CommandBuilder} */ @@ -30,7 +30,7 @@ export const command = new CommandBuilder() * @returns {Promise} */ export async function run(message, data) { - const guildId = cleanId(message.message?.guildId ?? message.channel?.guildId); + const guildId = cleanId(getMessageGuildId(message)); const prefix = this.handler.getPrefix(guildId) || "%"; const rawArg = ( diff --git a/src/music/GuildStats.mjs b/src/music/GuildStats.mjs index 64e92ff..21ea344 100644 --- a/src/music/GuildStats.mjs +++ b/src/music/GuildStats.mjs @@ -1,15 +1,11 @@ /** * @module src/music/GuildStats * @description Persistent per-guild and global music analytics engine. - * Backed by MySQL relational tables, Redis atomic counters/sorted sets, and - * debounced local JSON storage as a zero-downtime fallback. + * Backed by MySQL relational tables and Redis atomic counters/sorted sets. */ -import fs from "node:fs"; -import path from "node:path"; import { logger } from "../core/Logger.mjs"; -const STATS_DIR = path.join(process.cwd(), "storage", "guild_stats"); const REDIS_GUILD_PREFIX = "fluxer:stats:guild:"; const REDIS_GLOBAL_PLAYS = "fluxer:stats:global:plays"; const REDIS_GLOBAL_SONGS = "fluxer:stats:global:songs"; @@ -30,8 +26,6 @@ class GuildStatsManager { constructor() { /** @type {Map} */ this._cache = new Map(); - /** @type {Map} */ - this._saveTimers = new Map(); this._pool = null; this._redis = null; } @@ -73,7 +67,9 @@ class GuildStatsManager { \`hour_played\` TINYINT NOT NULL DEFAULT 0, \`played_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX \`idx_guild_time\` (\`guild_id\`, \`played_at\`), - INDEX \`idx_global_time\` (\`played_at\`) + INDEX \`idx_global_time\` (\`played_at\`), + INDEX \`idx_guild_user\` (\`guild_id\`, \`user_id\`), + INDEX \`idx_user_time\` (\`user_id\`, \`played_at\`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; `); @@ -90,13 +86,21 @@ class GuildStatsManager { INDEX \`idx_guild_plays\` (\`guild_id\`, \`play_count\` DESC) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; `); + + /* Add supplementary indexes if tables already exist */ + try { + await this._pool.execute("CREATE INDEX `idx_guild_user` ON `guild_track_stats` (`guild_id`, `user_id`);"); + } catch (_) {} + try { + await this._pool.execute("CREATE INDEX `idx_user_time` ON `guild_track_stats` (`user_id`, `played_at`);"); + } catch (_) {} } catch (e) { logger.warn("[GuildStats] Failed to initialize MySQL tables:", e?.message); } } /** - * Get or load guild stats object from cache or disk. + * Get or load in-memory guild stats object. * @param {string} guildId * @returns {object} */ @@ -116,31 +120,6 @@ class GuildStatsManager { recent: [], }; - try { - const filePath = path.join(STATS_DIR, `${guildId}.json`); - if (fs.existsSync(filePath)) { - const parsed = JSON.parse(fs.readFileSync(filePath, "utf8")); - if (parsed && typeof parsed === "object") { - data.totalPlays = Number(parsed.totalPlays) || 0; - data.totalDurationMs = Number(parsed.totalDurationMs) || 0; - if (Array.isArray(parsed.hourly) && parsed.hourly.length === 24) { - data.hourly = parsed.hourly; - } - if (parsed.users && typeof parsed.users === "object") { - data.users = parsed.users; - } - if (parsed.songs && typeof parsed.songs === "object") { - data.songs = parsed.songs; - } - if (Array.isArray(parsed.recent)) { - data.recent = parsed.recent; - } - } - } - } catch (e) { - logger.warn(`[GuildStats] Failed to load stats for ${guildId}:`, e?.message); - } - this._cache.set(guildId, data); return data; } @@ -195,8 +174,6 @@ class GuildStatsManager { data.recent.length = 1000; } - this._scheduleSave(guildId); - if (guildId !== "global") { const globalData = this._getGuildData("global"); if (globalData) { @@ -205,33 +182,52 @@ class GuildStatsManager { globalData.hourly[currentHour] = (globalData.hourly[currentHour] || 0) + 1; if (!globalData.guilds) globalData.guilds = {}; globalData.guilds[guildId] = (globalData.guilds[guildId] || 0) + 1; + if (userId && typeof userId === "string" && userId !== "system") { + if (!globalData.users) globalData.users = {}; + globalData.users[userId] = (globalData.users[userId] || 0) + 1; + } if (!globalData.songs[songKey]) { globalData.songs[songKey] = { title, artist, count: 0, durationMs }; } globalData.songs[songKey].count += 1; - this._scheduleSave("global"); + globalData.recent.unshift({ + title, + artist, + durationMs, + userId: userId || null, + guildId, + ts: Date.now(), + }); + if (globalData.recent.length > 2000) { + globalData.recent.length = 2000; + } } } /* Asynchronous MySQL persistence */ if (this._pool) { this._pool.execute(` - INSERT INTO \`guild_track_stats\` (\`guild_id\`, \`title\`, \`artist\`, \`duration_ms\`, \`user_id\`, \`hour_played\`) - VALUES (?, ?, ?, ?, ?, ?); + INSERT INTO \`guild_track_stats\` (\`guild_id\`, \`title\`, \`artist\`, \`duration_ms\`, \`user_id\`, \`hour_played\`, \`played_at\`) + VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP); `, [guildId, title.slice(0, 255), artist.slice(0, 255), durationMs, userId || null, currentHour]).catch((err) => { logger.warn("[GuildStats] MySQL insert error:", err?.message); }); this._pool.execute(` - INSERT INTO \`guild_song_counts\` (\`guild_id\`, \`song_key\`, \`title\`, \`artist\`, \`play_count\`, \`duration_ms\`) - VALUES (?, ?, ?, ?, 1, ?) + INSERT INTO \`guild_song_counts\` (\`guild_id\`, \`song_key\`, \`title\`, \`artist\`, \`play_count\`, \`duration_ms\`, \`last_played\`) + VALUES (?, ?, ?, ?, 1, ?, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE \`play_count\` = \`play_count\` + 1, \`last_played\` = CURRENT_TIMESTAMP; `, [guildId, songKey.slice(0, 255), title.slice(0, 255), artist.slice(0, 255), durationMs]).catch(() => {}); if (guildId !== "global") { this._pool.execute(` - INSERT INTO \`guild_song_counts\` (\`guild_id\`, \`song_key\`, \`title\`, \`artist\`, \`play_count\`, \`duration_ms\`) - VALUES ('global', ?, ?, ?, 1, ?) + INSERT INTO \`guild_track_stats\` (\`guild_id\`, \`title\`, \`artist\`, \`duration_ms\`, \`user_id\`, \`hour_played\`, \`played_at\`) + VALUES ('global', ?, ?, ?, ?, ?, CURRENT_TIMESTAMP); + `, [title.slice(0, 255), artist.slice(0, 255), durationMs, userId || null, currentHour]).catch(() => {}); + + this._pool.execute(` + INSERT INTO \`guild_song_counts\` (\`guild_id\`, \`song_key\`, \`title\`, \`artist\`, \`play_count\`, \`duration_ms\`, \`last_played\`) + VALUES ('global', ?, ?, ?, 1, ?, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE \`play_count\` = \`play_count\` + 1, \`last_played\` = CURRENT_TIMESTAMP; `, [songKey.slice(0, 255), title.slice(0, 255), artist.slice(0, 255), durationMs]).catch(() => {}); } @@ -261,7 +257,17 @@ class GuildStatsManager { try { let sql = ""; let params = []; - if (timeframe === "week") { + if (timeframe === "day") { + sql = ` + SELECT \`title\`, \`artist\`, COUNT(*) as count, MAX(\`duration_ms\`) as durationMs + FROM \`guild_track_stats\` + WHERE \`guild_id\` = ? AND \`played_at\` >= DATE_SUB(NOW(), INTERVAL 24 HOUR) + GROUP BY \`title\`, \`artist\` + ORDER BY count DESC + LIMIT ?; + `; + params = [guildId, lim]; + } else if (timeframe === "week") { sql = ` SELECT \`title\`, \`artist\`, COUNT(*) as count, MAX(\`duration_ms\`) as durationMs FROM \`guild_track_stats\` @@ -281,6 +287,16 @@ class GuildStatsManager { LIMIT ?; `; params = [guildId, lim]; + } else if (timeframe === "year") { + sql = ` + SELECT \`title\`, \`artist\`, COUNT(*) as count, MAX(\`duration_ms\`) as durationMs + FROM \`guild_track_stats\` + WHERE \`guild_id\` = ? AND \`played_at\` >= DATE_SUB(NOW(), INTERVAL 365 DAY) + GROUP BY \`title\`, \`artist\` + ORDER BY count DESC + LIMIT ?; + `; + params = [guildId, lim]; } else { sql = ` SELECT \`title\`, \`artist\`, \`play_count\` as count, \`duration_ms\` as durationMs @@ -293,18 +309,6 @@ class GuildStatsManager { } let [rows] = await this._pool.execute(sql, params); - if ((!rows || rows.length === 0) && (timeframe === "month" || timeframe === "week")) { - const [allRows] = await this._pool.execute(` - SELECT \`title\`, \`artist\`, \`play_count\` as count, \`duration_ms\` as durationMs - FROM \`guild_song_counts\` - WHERE \`guild_id\` = ? - ORDER BY count DESC - LIMIT ?; - `, [guildId, lim]); - if (allRows && allRows.length > 0) { - rows = allRows; - } - } if (rows && rows.length > 0) { const artistMap = {}; const tracks = rows.map((r) => { @@ -346,7 +350,14 @@ class GuildStatsManager { } } else { const now = Date.now(); - const cutoff = timeframe === "week" ? now - 7 * 86_400_000 : now - 30 * 86_400_000; + let cutoff = now - 30 * 86_400_000; + if (timeframe === "day") { + cutoff = now - 86_400_000; + } else if (timeframe === "week") { + cutoff = now - 7 * 86_400_000; + } else if (timeframe === "year") { + cutoff = now - 365 * 86_400_000; + } for (const p of data.recent) { if (p.ts >= cutoff) { const k = `${p.title}:::${p.artist}`; @@ -392,7 +403,7 @@ class GuildStatsManager { if (this._pool) { try { - const [rows] = await this._pool.execute(` + let [rows] = await this._pool.execute(` SELECT \`title\`, \`artist\`, \`play_count\` as count, \`duration_ms\` as durationMs FROM \`guild_song_counts\` WHERE \`guild_id\` = 'global' @@ -400,6 +411,20 @@ class GuildStatsManager { LIMIT ?; `, [lim]); + if (!rows || rows.length === 0) { + const [aggRows] = await this._pool.execute(` + SELECT \`title\`, \`artist\`, SUM(\`play_count\`) as count, MAX(\`duration_ms\`) as durationMs + FROM \`guild_song_counts\` + WHERE \`guild_id\` != 'global' + GROUP BY \`title\`, \`artist\` + ORDER BY count DESC + LIMIT ?; + `, [lim]); + if (aggRows && aggRows.length > 0) { + rows = aggRows; + } + } + if (rows && rows.length > 0) { const artistMap = {}; const tracks = rows.map((r) => { @@ -584,13 +609,26 @@ class GuildStatsManager { `); const peakHour = hourRows?.[0] ? formatHour(hourRows[0].hour_played) : "12:00 PM"; - const [trackRows] = await this._pool.execute(` + let [trackRows] = await this._pool.execute(` SELECT \`title\`, \`artist\`, \`play_count\` as count, \`duration_ms\` as durationMs FROM \`guild_song_counts\` WHERE \`guild_id\` = 'global' ORDER BY count DESC LIMIT 5; `); + if (!trackRows || trackRows.length === 0) { + const [aggRows] = await this._pool.execute(` + SELECT \`title\`, \`artist\`, SUM(\`play_count\`) as count, MAX(\`duration_ms\`) as durationMs + FROM \`guild_song_counts\` + WHERE \`guild_id\` != 'global' + GROUP BY \`title\`, \`artist\` + ORDER BY count DESC + LIMIT 5; + `); + if (aggRows && aggRows.length > 0) { + trackRows = aggRows; + } + } const topTracks = (trackRows || []).map((r) => ({ title: r.title, @@ -665,25 +703,39 @@ class GuildStatsManager { : "SELECT COUNT(*) as totalTracks, COALESCE(SUM(`duration_ms`), 0) as totalDurationMs FROM `guild_track_stats` WHERE `guild_id` = ? AND `user_id` = ?;"; const sumParams = isGlobalScope ? [userId] : [guildId, userId]; - const [sumRows] = await this._pool.execute(sumSql, sumParams); - const totalTracks = Number(sumRows?.[0]?.totalTracks) || 0; + let [sumRows] = await this._pool.execute(sumSql, sumParams); + let totalTracks = Number(sumRows?.[0]?.totalTracks) || 0; + let isGlobalFallback = false; + + if (totalTracks === 0 && !isGlobalScope) { + const [globalSumRows] = await this._pool.execute( + "SELECT COUNT(*) as totalTracks, COALESCE(SUM(`duration_ms`), 0) as totalDurationMs FROM `guild_track_stats` WHERE `user_id` = ?;", + [userId] + ); + if (Number(globalSumRows?.[0]?.totalTracks) > 0) { + sumRows = globalSumRows; + totalTracks = Number(globalSumRows[0].totalTracks); + isGlobalFallback = true; + } + } if (totalTracks > 0) { const totalDurationMs = Number(sumRows?.[0]?.totalDurationMs) || 0; const totalHours = Math.round((totalDurationMs / 3_600_000) * 10) / 10; + const effectiveGlobal = isGlobalScope || isGlobalFallback; - const hourSql = isGlobalScope + const hourSql = effectiveGlobal ? "SELECT `hour_played`, COUNT(*) as count FROM `guild_track_stats` WHERE `user_id` = ? GROUP BY `hour_played` ORDER BY count DESC LIMIT 1;" : "SELECT `hour_played`, COUNT(*) as count FROM `guild_track_stats` WHERE `guild_id` = ? AND `user_id` = ? GROUP BY `hour_played` ORDER BY count DESC LIMIT 1;"; - const hourParams = isGlobalScope ? [userId] : [guildId, userId]; + const hourParams = effectiveGlobal ? [userId] : [guildId, userId]; const [hourRows] = await this._pool.execute(hourSql, hourParams); const peakHour = hourRows?.[0] ? formatHour(hourRows[0].hour_played) : "12:00 PM"; - const trackSql = isGlobalScope + const trackSql = effectiveGlobal ? "SELECT `title`, `artist`, COUNT(*) as count, MAX(`duration_ms`) as durationMs FROM `guild_track_stats` WHERE `user_id` = ? GROUP BY `title`, `artist` ORDER BY count DESC LIMIT 5;" : "SELECT `title`, `artist`, COUNT(*) as count, MAX(`duration_ms`) as durationMs FROM `guild_track_stats` WHERE `guild_id` = ? AND `user_id` = ? GROUP BY `title`, `artist` ORDER BY count DESC LIMIT 5;"; - const trackParams = isGlobalScope ? [userId] : [guildId, userId]; + const trackParams = effectiveGlobal ? [userId] : [guildId, userId]; const [trackRows] = await this._pool.execute(trackSql, trackParams); const topTracks = (trackRows || []).map((r) => ({ @@ -702,10 +754,10 @@ class GuildStatsManager { const sortedArtists = Object.entries(artistMap).sort((a, b) => b[1] - a[1]); const topArtist = sortedArtists.length > 0 ? { name: sortedArtists[0][0], count: sortedArtists[0][1] } : null; - const lbSql = isGlobalScope + const lbSql = effectiveGlobal ? "SELECT `user_id`, COUNT(*) as plays FROM `guild_track_stats` WHERE `user_id` IS NOT NULL AND `user_id` != 'system' GROUP BY `user_id` ORDER BY plays DESC;" : "SELECT `user_id`, COUNT(*) as plays FROM `guild_track_stats` WHERE `guild_id` = ? AND `user_id` IS NOT NULL AND `user_id` != 'system' GROUP BY `user_id` ORDER BY plays DESC;"; - const lbParams = isGlobalScope ? [] : [guildId]; + const lbParams = effectiveGlobal ? [] : [guildId]; const [leaderboardRows] = await this._pool.execute(lbSql, lbParams); let djRank = 1; @@ -726,6 +778,7 @@ class GuildStatsManager { topArtist, djRank, totalDjs, + isGlobalFallback, }; } } catch (err) { @@ -734,11 +787,20 @@ class GuildStatsManager { } /* Fallback to local memory/file cache */ - const data = this._getGuildData(guildId); - if (!data) return null; + let data = this._getGuildData(guildId); + let totalTracks = Number(data?.users?.[userId]) || 0; + let isGlobalFallback = false; - const totalTracks = Number(data.users?.[userId]) || 0; - if (totalTracks === 0) return null; + if (totalTracks === 0 && guildId !== "global") { + const globalData = this._getGuildData("global"); + if (Number(globalData?.users?.[userId]) > 0) { + data = globalData; + totalTracks = Number(globalData.users[userId]); + isGlobalFallback = true; + } + } + + if (!data || totalTracks === 0) return null; const userTracks = (data.recent || []).filter((r) => String(r.userId) === String(userId)); let totalDurationMs = 0; @@ -791,53 +853,23 @@ class GuildStatsManager { topArtist, djRank, totalDjs, + isGlobalFallback, }; } /** - * Schedule a debounced file save for a guild. - * @param {string} guildId - * @private - */ - _scheduleSave(guildId) { - if (this._saveTimers.has(guildId)) return; - const timer = setTimeout(() => { - this._saveTimers.delete(guildId); - this.save(guildId); - }, 5000); - timer.unref?.(); - this._saveTimers.set(guildId, timer); - } - - /** - * Flush guild data to disk. - * @param {string} guildId + * Flush guild data (no-op: data is stored in MySQL). + * @param {string} [guildId] */ save(guildId) { - const data = this._cache.get(guildId); - if (!data) return; - try { - if (!fs.existsSync(STATS_DIR)) { - fs.mkdirSync(STATS_DIR, { recursive: true }); - } - const filePath = path.join(STATS_DIR, `${guildId}.json`); - fs.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf8"); - } catch (e) { - logger.warn(`[GuildStats] Failed to save stats for ${guildId}:`, e?.message); - } + /* No-op: Data is stored permanently in MySQL relational tables */ } /** - * Flush all active guild caches to disk immediately. + * Flush all active guild caches (no-op: data is stored in MySQL). */ flushAll() { - for (const [guildId, timer] of this._saveTimers) { - clearTimeout(timer); - } - this._saveTimers.clear(); - for (const guildId of this._cache.keys()) { - this.save(guildId); - } + /* No-op: Data is stored permanently in MySQL relational tables */ } } diff --git a/src/music/PlayerEventsMixin.mjs b/src/music/PlayerEventsMixin.mjs index a50da07..c54d25e 100644 --- a/src/music/PlayerEventsMixin.mjs +++ b/src/music/PlayerEventsMixin.mjs @@ -98,18 +98,39 @@ const PlayerEventsMixin = { this.dashboard.playerUpdate({ type: "startplay" }, player); if (!player._radioReconnects) { - let userId = song?.requester ?? null; + let userId = null; + if (typeof song?.requester === "string") { + userId = cleanId(song.requester); + } else if (song?.requester && typeof song.requester === "object") { + userId = cleanId(song.requester.id ?? song.requester.requester ?? song.requester.userId ?? ""); + } else if (song?.userId) { + userId = cleanId(song.userId); + } if (!userId) { const humans = player._getHumanParticipantIdentities?.() ?? []; - if (humans.length === 1) userId = humans[0]; + if (humans.length === 1) userId = cleanId(humans[0]); } - TrackStats.increment(userId); - const resolvedGuildId = player._resolveGuildId?.() ?? cleanId(player._guildId ?? player.channel?.guildId ?? ""); + + TrackStats.increment(userId || null); + + const resolvedGuildId = cleanId( + player._resolveGuildId?.() ?? + player._guildId ?? + context.guildId ?? + getMessageGuildId({ channel: player.channel }) ?? + getMessageGuildId({ channel: player.textChannel }) ?? + player.channel?.guildId ?? + player.channel?.guild?.id ?? + player.channel?.serverId ?? + player.channel?.server_id ?? + "" + ); + if (resolvedGuildId && song) { GuildStats.recordPlay({ guildId: resolvedGuildId, track: song, - userId, + userId: userId || null, }); } } diff --git a/src/music/PlayerLifecycleMixin.mjs b/src/music/PlayerLifecycleMixin.mjs index e9092e0..49fe5ae 100644 --- a/src/music/PlayerLifecycleMixin.mjs +++ b/src/music/PlayerLifecycleMixin.mjs @@ -410,7 +410,7 @@ const PlayerLifecycleMixin = { } this.setupEvents(player, { channelId: cleanChannelId, - guildId: cleanId(channel.guildId ?? getMessageGuildId(message)), + guildId: cleanId(channel.guildId ?? channel.guild?.id ?? channel.serverId ?? channel.server_id ?? getMessageGuildId(message)), }); player.on("inactivityWarning", ({ timeoutMs }) => { diff --git a/src/music/player/Player.mjs b/src/music/player/Player.mjs index fbea452..9c3744b 100644 --- a/src/music/player/Player.mjs +++ b/src/music/player/Player.mjs @@ -266,7 +266,7 @@ class Player extends EventEmitter { const channelId = this._channelId ?? this._home247Channel; if (channelId) { const ch = this.client?.channels?.get?.(channelId); - const fromChannel = ch?.guildId ?? ch?.guild?.id ?? null; + const fromChannel = ch?.guildId ?? ch?.guild?.id ?? ch?.serverId ?? ch?.server_id ?? null; if (fromChannel) return cleanId(fromChannel); } } catch(e) { logger.warn("[Player] Guild resolution failed:", e?.message); } @@ -525,7 +525,7 @@ class Player extends EventEmitter { } this._channelId = channelId; - this._guildId = cleanId(channel.guildId); + this._guildId = cleanId(channel.guildId ?? channel.guild?.id ?? channel.serverId ?? channel.server_id ?? ""); this._lastConnectedAt = Date.now(); this.leaving = false; diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index 92a3c12..3df645c 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -209,7 +209,7 @@ "position": "رقم الأغنية في قائمة الانتظار للانتقال إليها." }, "top": { - "timeframe": "تصفية الإطار الزمني: week أو month أو all أو global.", + "timeframe": "تصفية الإطار الزمني: 24h أو week أو month أو year أو all أو global، أو رقم الصفحة.", "page": "رقم الصفحة للانتقال إليها." }, "wrapped": { @@ -1404,13 +1404,15 @@ "timeframeWeek": "هذا الأسبوع", "timeframeMonth": "هذا الشهر", "timeframeAll": "كل الأوقات", - "topFooter": "تصفية بـ: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all", + "topFooter": "تصفية عبر: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all", "plays": "تشغيلات", "globalAuthor": "لوحة المتصدرين العالمية • كل السيرفرات", "globalTitle": "أكثر الأغاني تشغيلاً عبر كل السيرفرات", - "globalFooter": "تصفية بـ: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all • {{prefix}}top global", + "globalFooter": "تصفية عبر: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global", "pageFooter": "الصفحة {{page}}/{{totalPages}} • {{timeframe}}", - "serverFallbackNote": "ℹ️ _لم يتم تشغيل أي أغانٍ في هذا السيرفر بعد — عرض مخططات الشبكة العالمية:_" + "serverFallbackNote": "ℹ️ _لم يتم تشغيل أي أغانٍ في هذا السيرفر بعد — عرض مخططات الشبكة العالمية:_", + "timeframeDay": "آخر 24 ساعة", + "timeframeYear": "هذه السنة" }, "wrapped": { "wrappedAuthor": "ملخص موسيقى المجتمع", diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index 41b6aeb..97a677a 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -209,7 +209,7 @@ "position": "ژمارەی گۆرانییەکە لە ڕیزبەندی بۆ پەڕینەوە بۆی." }, "top": { - "timeframe": "فلتەرکردنی کات: week، month، all، یان global.", + "timeframe": "فلتەرکردنی کات: 24h یان week یان month یان year یان all یان global، یان ژمارەی پەڕە.", "page": "ژمارەی پەڕە بۆ بازدان." }, "wrapped": { @@ -1404,13 +1404,15 @@ "timeframeWeek": "ئەم هەفتەیە", "timeframeMonth": "ئەم مانگە", "timeframeAll": "هەموو کاتێک", - "topFooter": "فلتەر بکە بە: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all", + "topFooter": "فلتەرکردن بە: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all", "plays": "لێدان", "globalAuthor": "ڕیزبەندی جیهانی • هەموو سێرڤەرەکان", "globalTitle": "زۆرترین گۆرانی لێدراو لە هەموو سێرڤەرەکاندا", - "globalFooter": "فلتەر بکە بە: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all • {{prefix}}top global", + "globalFooter": "فلتەرکردن بە: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global", "pageFooter": "پەڕەی {{page}}/{{totalPages}} • {{timeframe}}", - "serverFallbackNote": "ℹ️ _تا ئێستا هیچ گۆرانییەک لەم سێرڤەرە لێنەدراوە — پیشاندانی ڕیزبەندیی تۆڕی جیهانی:_" + "serverFallbackNote": "ℹ️ _تا ئێستا هیچ گۆرانییەک لەم سێرڤەرە لێنەدراوە — پیشاندانی ڕیزبەندیی تۆڕی جیهانی:_", + "timeframeDay": "٢٤ کاتژمێری ڕابردوو", + "timeframeYear": "ئەمساڵ" }, "wrapped": { "wrappedAuthor": "پوختەی مۆسیقای کۆمەڵگە", diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index e4eddfc..2bfd5ca 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -209,7 +209,7 @@ "position": "Die Nummer des Titels in der Warteschlange, zu dem gesprungen werden soll." }, "top": { - "timeframe": "Zeitraum filtern: week, month, all oder global.", + "timeframe": "Zeitraum filtern: 24h, week, month, year, all oder global, oder Seitenzahl.", "page": "Seitennummer, zu der gesprungen werden soll." }, "wrapped": { @@ -1404,13 +1404,15 @@ "timeframeWeek": "Diese Woche", "timeframeMonth": "Dieser Monat", "timeframeAll": "Gesamte Zeit", - "topFooter": "Filtern mit: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all", + "topFooter": "Filtern mit: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all", "plays": "Wiedergaben", "globalAuthor": "Globale Bestenliste • Alle Server", "globalTitle": "Meistgespielte Songs auf allen Servern", - "globalFooter": "Filtern mit: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all • {{prefix}}top global", + "globalFooter": "Filtern mit: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global", "pageFooter": "Seite {{page}}/{{totalPages}} • {{timeframe}}", - "serverFallbackNote": "ℹ️ _Noch keine Tracks auf diesem Server gespielt — globale Charts werden angezeigt:_" + "serverFallbackNote": "ℹ️ _Noch keine Tracks auf diesem Server gespielt — globale Charts werden angezeigt:_", + "timeframeDay": "Letzte 24 Stunden", + "timeframeYear": "Dieses Jahr" }, "wrapped": { "wrappedAuthor": "Community Music Wrapped", diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index dd654dc..0607eab 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -209,7 +209,7 @@ "position": "The track number in the queue to jump to." }, "top": { - "timeframe": "Filter timeframe: week, month, all, or global.", + "timeframe": "Filter timeframe: 24h, week, month, year, all, or global, or page number.", "page": "Page number to jump to." }, "wrapped": { @@ -1404,13 +1404,15 @@ "timeframeWeek": "This Week", "timeframeMonth": "This Month", "timeframeAll": "All Time", - "topFooter": "Filter with: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all", + "topFooter": "Filter with: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all", "plays": "plays", "globalAuthor": "Global Leaderboard • All Servers", "globalTitle": "Top Played Tracks Across All Servers", - "globalFooter": "Filter with: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all • {{prefix}}top global", + "globalFooter": "Filter with: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global", "pageFooter": "Page {{page}}/{{totalPages}} • {{timeframe}}", - "serverFallbackNote": "ℹ️ _No tracks played in this server yet — showing Global Network charts:_" + "serverFallbackNote": "ℹ️ _No tracks played in this server yet — showing Global Network charts:_", + "timeframeDay": "Past 24 Hours", + "timeframeYear": "This Year" }, "wrapped": { "wrappedAuthor": "Community Music Wrapped", diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index d5dce23..a1fba6a 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -209,7 +209,7 @@ "position": "O número da faixa na fila para onde pular." }, "top": { - "timeframe": "Filtrar período: week, month, all ou global.", + "timeframe": "Filtrar período: 24h, week, month, year, all ou global, ou número da página.", "page": "Número da página para pular." }, "wrapped": { @@ -1404,13 +1404,15 @@ "timeframeWeek": "Esta Semana", "timeframeMonth": "Este Mês", "timeframeAll": "Todo o Período", - "topFooter": "Filtrar com: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all", + "topFooter": "Filtrar com: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all", "plays": "reproduções", "globalAuthor": "Classificação Global • Todos os Servidores", "globalTitle": "Músicas Mais Tocadas em Todos os Servidores", - "globalFooter": "Filtrar com: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all • {{prefix}}top global", + "globalFooter": "Filtrar com: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global", "pageFooter": "Página {{page}}/{{totalPages}} • {{timeframe}}", - "serverFallbackNote": "ℹ️ _Nenhuma música tocada neste servidor ainda — exibindo paradas globais da rede:_" + "serverFallbackNote": "ℹ️ _Nenhuma música tocada neste servidor ainda — exibindo paradas globais da rede:_", + "timeframeDay": "Últimas 24 Horas", + "timeframeYear": "Este Ano" }, "wrapped": { "wrappedAuthor": "Retrospectiva Musical da Comunidade", diff --git a/storage/locales/bot/tr.json b/storage/locales/bot/tr.json index cd936bf..b679e04 100644 --- a/storage/locales/bot/tr.json +++ b/storage/locales/bot/tr.json @@ -209,7 +209,7 @@ "position": "Atlanacak şarkının kuyruktaki sıra numarası." }, "top": { - "timeframe": "Zaman aralığını filtrele: week, month, all veya global.", + "timeframe": "Zaman aralığını filtrele: 24h, week, month, year, all veya global ya da sayfa numarası.", "page": "Atlanacak sayfa numarası." }, "wrapped": { @@ -1404,13 +1404,15 @@ "timeframeWeek": "Bu Hafta", "timeframeMonth": "Bu Ay", "timeframeAll": "Tüm Zamanlar", - "topFooter": "Filtrele: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all", + "topFooter": "Şununla filtrele: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all", "plays": "çalma", "globalAuthor": "Küresel Lider Tablosu • Tüm Sunucular", "globalTitle": "Tüm Sunucularda En Çok Çalınan Şarkılar", - "globalFooter": "Filtrele: {{prefix}}top week • {{prefix}}top month • {{prefix}}top all • {{prefix}}top global", + "globalFooter": "Şununla filtrele: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global", "pageFooter": "Sayfa {{page}}/{{totalPages}} • {{timeframe}}", - "serverFallbackNote": "ℹ️ _Bu sunucuda henüz şarkı çalınmadı — Küresel Ağ listeleri gösteriliyor:_" + "serverFallbackNote": "ℹ️ _Bu sunucuda henüz şarkı çalınmadı — Küresel Ağ listeleri gösteriliyor:_", + "timeframeDay": "Son 24 Saat", + "timeframeYear": "Bu Yıl" }, "wrapped": { "wrappedAuthor": "Topluluk Müzik Özeti", diff --git a/storage/locales/bot/zh-CN.json b/storage/locales/bot/zh-CN.json index 2a5a85e..c3264bb 100644 --- a/storage/locales/bot/zh-CN.json +++ b/storage/locales/bot/zh-CN.json @@ -209,7 +209,7 @@ "position": "要跳转到的队列曲目序号。" }, "top": { - "timeframe": "筛选时间范围:week、month、all 或 global。", + "timeframe": "过滤时间范围:24h、week、month、year、all 或 global,或页码。", "page": "要跳转到的页码。" }, "wrapped": { @@ -1404,13 +1404,15 @@ "timeframeWeek": "本周", "timeframeMonth": "本月", "timeframeAll": "全部时间", - "topFooter": "筛选方式:{{prefix}}top week • {{prefix}}top month • {{prefix}}top all", + "topFooter": "筛选命令:{{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all", "plays": "次播放", "globalAuthor": "全球排行榜 • 所有服务器", "globalTitle": "所有服务器中最多播放的曲目", - "globalFooter": "筛选方式:{{prefix}}top week • {{prefix}}top month • {{prefix}}top all • {{prefix}}top global", + "globalFooter": "筛选命令:{{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global", "pageFooter": "第 {{page}}/{{totalPages}} 页 • {{timeframe}}", - "serverFallbackNote": "ℹ️ _此服务器尚未播放任何曲目 — 显示全球网络排行榜:_" + "serverFallbackNote": "ℹ️ _此服务器尚未播放任何曲目 — 显示全球网络排行榜:_", + "timeframeDay": "过去 24 小时", + "timeframeYear": "今年" }, "wrapped": { "wrappedAuthor": "社区年度音乐回顾", diff --git a/storage/locales/bot/zh-TW.json b/storage/locales/bot/zh-TW.json index 074e934..5861057 100644 --- a/storage/locales/bot/zh-TW.json +++ b/storage/locales/bot/zh-TW.json @@ -209,7 +209,7 @@ "position": "要跳轉到的佇列曲目序號。" }, "top": { - "timeframe": "篩選時間範圍:week、month、all 或 global。", + "timeframe": "篩選時間範圍:24h、week、month、year、all 或 global,或頁碼。", "page": "要跳轉到的頁碼。" }, "wrapped": { @@ -1404,13 +1404,15 @@ "timeframeWeek": "本週", "timeframeMonth": "本月", "timeframeAll": "全部時間", - "topFooter": "篩選方式:{{prefix}}top week • {{prefix}}top month • {{prefix}}top all", + "topFooter": "篩選指令:{{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all", "plays": "次播放", "globalAuthor": "全球排行榜 • 所有伺服器", "globalTitle": "所有伺服器中最多播放的曲目", - "globalFooter": "篩選方式:{{prefix}}top week • {{prefix}}top month • {{prefix}}top all • {{prefix}}top global", + "globalFooter": "篩選指令:{{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global", "pageFooter": "第 {{page}}/{{totalPages}} 頁 • {{timeframe}}", - "serverFallbackNote": "ℹ️ _此伺服器尚未播放任何曲目 — 顯示全球網路排行榜:_" + "serverFallbackNote": "ℹ️ _此伺服器尚未播放任何曲目 — 顯示全球網路排行榜:_", + "timeframeDay": "過去 24 小時", + "timeframeYear": "今年" }, "wrapped": { "wrappedAuthor": "社區年度音樂回顧",