This commit is contained in:
NoLogicAlan committed 2026-05-12 17:05:55 +03:00
1 parent feaf57546e
commit 7a4009f5c3
2 files changed
+7 -67

No files matched your search

+4 -26
View File
@@ -74,43 +74,22 @@ function getUserCount(client) {
function getLivePlayerCount(playerMap) { function getLivePlayerCount(playerMap) {
let live = 0; let live = 0;
const seenGuilds = new Set();
for (const [mapKey, player] of playerMap ?? []) { for (const [, player] of playerMap ?? []) {
// Skip null / destroyed / leaving entries
if (!player || player._destroyed || player.leaving) continue; if (!player || player._destroyed || player.leaving) continue;
// Skip players still in the join() phase — they don't have a voice
// connection yet and may fail to connect.
if (player._isJoining) continue; if (player._isJoining) continue;
// A player is only "live" if it has an actual voice connection.
// Stale entries (gateway disconnect, LiveKit drop) that haven't been
// cleaned up yet will have connection = null or a dead room state.
const conn = player.connection; const conn = player.connection;
if (conn) { if (!conn) continue;
const room = conn.room; const room = conn.room;
if (room) { if (room) {
// Use @livekit/rtc-node Node.js SDK API:
// room.isConnected — boolean getter (true when connected)
// room.connectionState — ConnectionState enum (0=disconnected, 1=connected, 2=reconnecting)
// room.state does NOT exist in the Node.js SDK (browser-only API)
const isConnected = room.isConnected; const isConnected = room.isConnected;
const connectionState = room.connectionState; const connectionState = room.connectionState;
// Explicitly dead states → skip
if (!isConnected && (connectionState === 0 || connectionState === "disconnected")) continue; if (!isConnected && (connectionState === 0 || connectionState === "disconnected")) continue;
} }
// conn exists but no room → still a valid LiveKit connection reference
} else {
// No connection at all → not live
continue;
}
live++; live++;
// Also track unique guilds so we can report server count
const guildId = String(player._guildId ?? "").replace(/\D/g, "");
if (guildId) seenGuilds.add(guildId);
} }
return live; return live;
@@ -175,8 +154,7 @@ export async function run(message) {
footer: this.config.customStatsFooter || null, footer: this.config.customStatsFooter || null,
}; };
// Fetch Last.fm stats in the background (non-blocking for initial reply) // Fetch Last.fm stats (non-blocking for initial reply)
// getTotalScrobbles() syncs all linked users' lifetime scrobble counts from Last.fm
const scrobblePromise = lastfmEnabled ? lastfm.getTotalScrobbles() : Promise.resolve(0); const scrobblePromise = lastfmEnabled ? lastfm.getTotalScrobbles() : Promise.resolve(0);
const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0); const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0);
+3 -41
View File
@@ -89,15 +89,10 @@ export class LastFmManager {
// In-memory user cache: Map<userId, { sessionKey, username, scrobbleEnabled }> // In-memory user cache: Map<userId, { sessionKey, username, scrobbleEnabled }>
this._userCache = new Map(); this._userCache = new Map();
// In-memory scrobble counter (persisted to MySQL)
this._storedScrobbles = 0;
this._scrobblesLoaded = false;
// Cache for total synced scrobbles (sum of all users' lifetime scrobble counts) // Cache for total synced scrobbles (sum of all users' lifetime scrobble counts)
this._totalScrobblesCache = null; this._totalScrobblesCache = null;
this._totalScrobblesCacheExpiry = 0; this._totalScrobblesCacheExpiry = 0;
this._totalScrobblesInflight = null; this._totalScrobblesInflight = null;
const TOTAL_SCROBBLES_TTL_MS = 10 * 60 * 1000; // refresh every 10 minutes
if (!this.enabled) { if (!this.enabled) {
logger.settings("[LastFm] Disabled — apiKey or apiSecret missing in config."); logger.settings("[LastFm] Disabled — apiKey or apiSecret missing in config.");
@@ -714,32 +709,6 @@ export class LastFmManager {
// ── Global stats ──────────────────────────────────────────────────────────── // ── 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<number>}
*/
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 lifetime scrobbles across ALL linked Last.fm users. * 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. * Syncs each user's scrobble count from the Last.fm API, then sums them up.
@@ -895,23 +864,16 @@ export class LastFmManager {
} }
/** /**
* Increment the stored scrobbles counter (in-memory + MySQL). * Increment per-user scrobble_count after a successful scrobble.
* Also increments per-user scrobble_count. * Non-blocking — fire-and-forget.
* Called after a successful scrobble. Non-blocking — fire-and-forget.
*/ */
_incrementScrobbleCount(userId) { _incrementScrobbleCount(userId) {
this._storedScrobbles++; if (!userId) return;
// Persist to MySQL in the background (don't await)
this._getPool().then(pool => { this._getPool().then(pool => {
pool.execute(
"UPDATE lastfm_stats SET stored_scrobbles = stored_scrobbles + 1 WHERE id = 1"
).catch(() => {});
if (userId) {
pool.execute( pool.execute(
"UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?", "UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?",
[String(userId)] [String(userId)]
).catch(() => {}); ).catch(() => {});
}
}).catch(() => {}); }).catch(() => {});
} }