From feaf57546ef87a03d0a709dc0024f7f62d7272c1 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Tue, 12 May 2026 16:53:24 +0300 Subject: [PATCH] fix(lastfm): sync live scrobble counts & raise volume ceiling to 200% --- commands/stats.mjs | 3 +- src/LastFmManager.mjs | 78 +++++++++++++++++++++++++++++++++++++++++++ src/Player.mjs | 4 +-- 3 files changed, 82 insertions(+), 3 deletions(-) diff --git a/commands/stats.mjs b/commands/stats.mjs index 00a696f..337eafe 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -176,7 +176,8 @@ export async function run(message) { }; // Fetch Last.fm stats in the background (non-blocking for initial reply) - const scrobblePromise = lastfmEnabled ? lastfm.getStoredScrobbles() : Promise.resolve(0); + // getTotalScrobbles() syncs all linked users' lifetime scrobble counts from Last.fm + const scrobblePromise = lastfmEnabled ? lastfm.getTotalScrobbles() : Promise.resolve(0); const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0); const hasCached = cachedUserCount !== null; diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index f28fc74..4e01619 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -93,6 +93,12 @@ export class LastFmManager { this._storedScrobbles = 0; this._scrobblesLoaded = false; + // Cache for total synced scrobbles (sum of all users' lifetime scrobble counts) + this._totalScrobblesCache = null; + this._totalScrobblesCacheExpiry = 0; + this._totalScrobblesInflight = null; + const TOTAL_SCROBBLES_TTL_MS = 10 * 60 * 1000; // refresh every 10 minutes + if (!this.enabled) { logger.settings("[LastFm] Disabled — apiKey or apiSecret missing in config."); } @@ -734,6 +740,78 @@ export class LastFmManager { return this._storedScrobbles; } + /** + * Get the total lifetime scrobbles across ALL linked Last.fm users. + * Syncs each user's scrobble count from the Last.fm API, then sums them up. + * Results are cached for 10 minutes to avoid hammering the API. + * + * @param {number} [concurrency=3] - How many users to sync in parallel + * @returns {Promise} Total scrobbles across all linked users + */ + async getTotalScrobbles(concurrency = 3) { + if (!this.enabled) return 0; + + // Return cached value if still fresh + if (this._totalScrobblesCache !== null && Date.now() < this._totalScrobblesCacheExpiry) { + return this._totalScrobblesCache; + } + + // Deduplicate concurrent calls + if (this._totalScrobblesInflight) return this._totalScrobblesInflight; + + this._totalScrobblesInflight = this._refreshTotalScrobbles(concurrency); + try { + return await this._totalScrobblesInflight; + } finally { + this._totalScrobblesInflight = null; + } + } + + /** + * Internal: sync all users' scrobble counts from Last.fm and return the sum. + */ + async _refreshTotalScrobbles(concurrency) { + try { + const pool = await this._getPool(); + + // Get all linked user IDs + const [rows] = await pool.execute( + "SELECT user_id FROM lastfm_users" + ); + + if (!rows.length) { + this._totalScrobblesCache = 0; + this._totalScrobblesCacheExpiry = Date.now() + 10 * 60 * 1000; + return 0; + } + + // Sync each user's scrobble count from the Last.fm API (with concurrency limit) + const userIds = rows.map(r => r.user_id); + + // Batch the sync calls to avoid overloading the Last.fm API + for (let i = 0; i < userIds.length; i += concurrency) { + const batch = userIds.slice(i, i + concurrency); + await Promise.allSettled(batch.map(uid => this.syncUserScrobbleCount(uid))); + } + + // Now sum up all scrobble_count values from the DB + const [sumRows] = await pool.execute( + "SELECT COALESCE(SUM(scrobble_count), 0) AS total FROM lastfm_users" + ); + + const total = Number(sumRows[0]?.total ?? 0); + this._totalScrobblesCache = total; + this._totalScrobblesCacheExpiry = Date.now() + 10 * 60 * 1000; + + logger.settings(`[LastFm] Total synced scrobbles across ${userIds.length} users: ${total}`); + return total; + } catch (err) { + logger.warn(`[LastFm] _refreshTotalScrobbles failed: ${err.message}`); + // Return stale cache if available, otherwise 0 + return this._totalScrobblesCache ?? 0; + } + } + /** * Get the total number of linked Last.fm users. * @returns {Promise} diff --git a/src/Player.mjs b/src/Player.mjs index 190a7a8..a306429 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -516,7 +516,7 @@ export default class Player extends EventEmitter { } if (savedVol !== undefined && savedVol !== null) { - this.preferredVolume = Utils.clamp(savedVol / 100, 0, 1); + this.preferredVolume = Utils.clamp(savedVol / 100, 0, 2); logger.player(`[Player] Restored volume ${savedVol}% for guild ${this._guildId}`); } } @@ -1735,7 +1735,7 @@ export default class Player extends EventEmitter { // ═══════════════════════════════════════════════════════════════════════════ setVolume(v) { - this.preferredVolume = Utils.clamp(v, 0, 1); + this.preferredVolume = Utils.clamp(v, 0, 2); this.emit("volume", this.preferredVolume); this._mediaPlayer?.setVolume(this.preferredVolume); if (!this.connection)