diff --git a/README.md b/README.md index eec6d0d..51aa909 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ Below is the complete list of Remix's commands. The default prefix is `%`. | Command | Description | Usage | Aliases | | :--- | :--- | :--- | :--- | | `settings` | View or change server settings (requires Manage Server) | `%settings set` | `prefix`, `pfx`, `247` | -| `stats` | Display bot stats (uptime, ping, player count) | `%stats` | `info` | +| `stats` | Display bot stats (uptime, ping, player count, stored scrobbles) | `%stats` | `info` | | `invite` | Get the bot invite link | `%invite` | `addbot`, `remix` | | `support` | Get an invite to the support server | `%support` | `server` | | `lastfm` | Link Last.fm, toggle scrobbling, view profile, play tracks | `%lastfm link` / `%lastfm play loved` | `lf`, `lfm` | @@ -306,7 +306,7 @@ fluxer/ │ ├── Settings.mjs # RemoteSettingsManager + ServerSettings export │ ├── GatewayHandler.mjs # Raw WS events, voice-state tracking, presence rotation │ ├── RecoveryManager.mjs # Session persistence, crash recovery, 24/7 auto-join -│ ├── LastFmManager.mjs # Last.fm API client — auth, scrobbling, user data +│ ├── LastFmManager.mjs # Last.fm API client — auth, scrobbling, user data, stored scrobble stats │ ├── Utils.mjs # Shared utilities │ ├── worker.mjs # Background task worker │ ├── probe.mjs # FFprobe wrapper for audio stream info diff --git a/commands/stats.mjs b/commands/stats.mjs index 86b012f..b25011e 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -115,7 +115,7 @@ function getLivePlayerCount(playerMap) { // ── Embed builder ───────────────────────────────────────────────────────────── -function buildEmbed(t, msg, { guildCount, userCount, playerCount, ping, uptime, comHash, comLink, reason, footer, loading }) { +function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) { const num = (v) => Utils.formatNumber(v); const ld = (v) => loading ? "..." : v; @@ -123,6 +123,15 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, ping, uptime, `${t(msg, "responses.stats.servers")} — \`${num(guildCount)}\``, `${t(msg, "responses.stats.users")} — \`${ld(num(userCount))}\``, `${t(msg, "responses.stats.players")} — \`${num(playerCount)}\``, + ]; + + // Add Last.fm stats if the integration is enabled + if (lastfmEnabled) { + description.push(`${t(msg, "responses.stats.scrobbles")} — \`${ld(num(scrobbleCount))}\``); + description.push(`${t(msg, "responses.stats.linkedUsers")} — \`${ld(num(linkedUsers))}\``); + } + + description.push( `${t(msg, "responses.stats.ping")} — \`${ld(`${num(ping)}ms`)}\``, `${t(msg, "responses.stats.uptime")} — \`${uptime}\``, `${t(msg, "responses.stats.build")} — [\`${comHash}\`](${comLink})`, @@ -130,12 +139,14 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, ping, uptime, ``, t(msg, "responses.stats.supportKofi"), t(msg, "responses.stats.community"), - ].filter(l => l !== null).join("\n"); + ); + + const desc = description.filter(l => l !== null).join("\n"); const builder = new EmbedBuilder() .setColor(getGlobalColor()) .setAuthor({ name: t(msg, "responses.stats.title") }) - .setDescription(description) + .setDescription(desc) .setFooter({ text: footer || t(msg, "responses.stats.title") }); if (typeof builder.setTimestamp === "function") builder.setTimestamp(); @@ -145,9 +156,15 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, ping, uptime, // ── Runner ──────────────────────────────────────────────────────────────────── export async function run(message) { + const lastfm = this.lastfm; + const lastfmEnabled = lastfm?.enabled ?? false; + const shared = { guildCount: this.client.guilds.size, playerCount: getLivePlayerCount(this.players.playerMap), + scrobbleCount: 0, + linkedUsers: 0, + lastfmEnabled, uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000), comHash: this.comHash, comLink: this.comLink, @@ -155,6 +172,10 @@ export async function run(message) { footer: this.config.customStatsFooter || null, }; + // Fetch Last.fm stats in the background (non-blocking for initial reply) + const scrobblePromise = lastfmEnabled ? lastfm.getStoredScrobbles() : Promise.resolve(0); + const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0); + const hasCached = cachedUserCount !== null; // Measure real round-trip latency @@ -164,9 +185,13 @@ export async function run(message) { }); const ping = Date.now() - start; - const users = await getUserCount(this.client); + const [users, scrobbleCount, linkedUsers] = await Promise.all([ + getUserCount(this.client), + scrobblePromise, + linkedPromise, + ]); await msg.edit({ - embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, userCount: users, ping, loading: false })] + embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, userCount: users, scrobbleCount, linkedUsers, ping, loading: false })] }).catch((err) => console.error("[stats] editEmbed failed:", err)); } \ No newline at end of file diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index 18618de..b8eaceb 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -89,6 +89,10 @@ export class LastFmManager { // In-memory user cache: Map this._userCache = new Map(); + // In-memory scrobble counter (persisted to MySQL) + this._storedScrobbles = 0; + this._scrobblesLoaded = false; + if (!this.enabled) { logger.settings("[LastFm] Disabled — apiKey or apiSecret missing in config."); } @@ -122,6 +126,19 @@ export class LastFmManager { \`linked_at\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; `); + + // Stats table — single row tracking global scrobble counts + await pool.execute(` + CREATE TABLE IF NOT EXISTS \`lastfm_stats\` ( + \`id\` TINYINT(1) NOT NULL PRIMARY KEY DEFAULT 1, + \`stored_scrobbles\` BIGINT NOT NULL DEFAULT 0, + \`linked_users\` INT NOT NULL DEFAULT 0 + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + `); + // Ensure the single row exists + await pool.execute(` + INSERT IGNORE INTO \`lastfm_stats\` (id, stored_scrobbles, linked_users) VALUES (1, 0, 0) + `); } // ── User persistence ─────────────────────────────────────────────────────── @@ -158,6 +175,17 @@ export class LastFmManager { ); const data = { sessionKey, username: username ?? "", scrobbleEnabled: true }; this._userCache.set(userId, data); + + // Increment linked_users counter (only on new links, not re-links) + try { + await pool.execute( + "UPDATE lastfm_stats SET linked_users = linked_users + 1 WHERE id = 1 AND NOT EXISTS (SELECT 1 FROM (SELECT 1 FROM lastfm_users WHERE user_id = ? AND linked_at < NOW()) AS tmp)", + [String(userId)] + ); + } catch { + // Non-critical — don't fail the save + } + return data; } @@ -268,6 +296,9 @@ export class LastFmManager { true // POST ); logger.settings(`[LastFm] Scrobbled "${track.title}" for ${userId}`); + + // Increment stored scrobbles counter (non-blocking) + this._incrementScrobbleCount(); } catch (err) { logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`); } @@ -667,12 +698,71 @@ export class LastFmManager { }; } + // ── Global stats ──────────────────────────────────────────────────────────── + + /** + * Get the total number of scrobbles the bot has stored (across all users). + * Uses an in-memory counter that is lazy-loaded from MySQL on first call. + * @returns {Promise} + */ + async getStoredScrobbles() { + if (!this.enabled) return 0; + + if (!this._scrobblesLoaded) { + try { + const pool = await this._getPool(); + const [rows] = await pool.execute( + "SELECT stored_scrobbles FROM lastfm_stats WHERE id = 1" + ); + this._storedScrobbles = Number(rows[0]?.stored_scrobbles ?? 0); + this._scrobblesLoaded = true; + } catch { + // Table might not exist yet — return 0 + this._storedScrobbles = 0; + this._scrobblesLoaded = true; + } + } + + return this._storedScrobbles; + } + + /** + * Get the total number of linked Last.fm users. + * @returns {Promise} + */ + async getLinkedUsersCount() { + if (!this.enabled) return 0; + try { + const pool = await this._getPool(); + const [rows] = await pool.execute( + "SELECT linked_users FROM lastfm_stats WHERE id = 1" + ); + return Number(rows[0]?.linked_users ?? 0); + } catch { + return 0; + } + } + // ── Internal helpers ─────────────────────────────────────────────────────── _assertEnabled() { if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret)."); } + /** + * Increment the stored scrobbles counter (in-memory + MySQL). + * Called after a successful scrobble. Non-blocking — fire-and-forget. + */ + _incrementScrobbleCount() { + this._storedScrobbles++; + // Persist to MySQL in the background (don't await) + this._getPool().then(pool => { + pool.execute( + "UPDATE lastfm_stats SET stored_scrobbles = stored_scrobbles + 1 WHERE id = 1" + ).catch(() => {}); + }).catch(() => {}); + } + _extractArtist(track) { return track.artists?.[0]?.name ?? track.author?.name diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index d0209fa..d9e7442 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -478,6 +478,8 @@ "servers": "📂 **الخوادم**", "users": "👥 **المستخدمون**", "players": "🎧 **المشغّلات**", + "scrobbles": "🎵 **اسكروبلات**", + "linkedUsers": "🔗 **حسابات Last.fm**", "ping": "🏓 **البينغ**", "uptime": "⏱️ **وقت التشغيل**", "build": "🔧 **الإصدار**", diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index ad5d974..cb9e7eb 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -478,6 +478,8 @@ "servers": "📂 **سێرڤەرەکان**", "users": "👥 **بەکارهێنەران**", "players": "🎧 **پەخشکەرەکان**", + "scrobbles": "🎵 **سکرۆبلەکان**", + "linkedUsers": "🔗 **هەژمارەکانی Last.fm**", "ping": "🏓 **پینگ**", "uptime": "⏱️ **کاتی چالاک**", "build": "🔧 **بەرنامە**", diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index a0dca06..aabf44d 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -478,6 +478,8 @@ "servers": "📂 **Server**", "users": "👥 **Benutzer**", "players": "🎧 **Player**", + "scrobbles": "🎵 **Scrobbles**", + "linkedUsers": "🔗 **Verknüpfte Last.fm**", "ping": "🏓 **Ping**", "uptime": "⏱️ **Uptime**", "build": "🔧 **Build**", diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index 094486a..6f41e8b 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -483,6 +483,8 @@ "servers": "📂 **Servers**", "users": "👥 **Users**", "players": "🎧 **Players**", + "scrobbles": "🎵 **Scrobbles**", + "linkedUsers": "🔗 **Linked Last.fm**", "ping": "🏓 **Ping**", "uptime": "⏱️ **Uptime**", "build": "🔧 **Build**", diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index d32df3e..97e85a5 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -478,6 +478,8 @@ "servers": "📂 **Servidores**", "users": "👥 **Usuários**", "players": "🎧 **Players**", + "scrobbles": "🎵 **Scrobbles**", + "linkedUsers": "🔗 **Last.fm Vinculadas**", "ping": "🏓 **Ping**", "uptime": "⏱️ **Tempo de Atividade**", "build": "🔧 **Build**",