feat(stats): add persistent tracks played counter with redis sync

This commit is contained in:
NoLogicAlan committed 2026-10-23 01:32:38 +03:00
1 parent 1e02478fb6
commit 7bd80e62f7
10 files changed
+147 -6

No files matched your search

+6
View File
@@ -11,6 +11,7 @@ import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/ui/index.mjs"; import { getGlobalColor } from "../src/ui/index.mjs";
import { logger } from "../src/core/Logger.mjs"; import { logger } from "../src/core/Logger.mjs";
import * as ShardingUtils from "../src/utils/ShardingUtils.mjs"; import * as ShardingUtils from "../src/utils/ShardingUtils.mjs";
import { TrackStats } from "../src/music/TrackStats.mjs";
/** /**
* @type {CommandBuilder} * @type {CommandBuilder}
@@ -366,6 +367,7 @@ function buildEmbed(t, msg, s, pending = []) {
const musicLines = [ const musicLines = [
`### ${tOr(t, msg, "responses.stats.categoryMusic", "🎧 Music Activity")}`, `### ${tOr(t, msg, "responses.stats.categoryMusic", "🎧 Music Activity")}`,
`${t(msg, "responses.stats.players")} — ${field("players", playerVal)}`, `${t(msg, "responses.stats.players")} — ${field("players", playerVal)}`,
`${tOr(t, msg, "responses.stats.tracksPlayed", "▶️ **Tracks Played**")} — ${field("tracksPlayed", num(s.tracksPlayed))}`,
]; ];
if (s.queuedTracks > 0) { if (s.queuedTracks > 0) {
musicLines.push(`${tOr(t, msg, "responses.stats.queuedTracks", "🎶 **Queued Tracks**")} — ${field("queuedTracks", num(s.queuedTracks))}`); musicLines.push(`${tOr(t, msg, "responses.stats.queuedTracks", "🎶 **Queued Tracks**")} — ${field("queuedTracks", num(s.queuedTracks))}`);
@@ -437,6 +439,7 @@ export async function run(message) {
const totals = getTotals(this.client); const totals = getTotals(this.client);
const music = getMusicStats(this.players?.playerMap); const music = getMusicStats(this.players?.playerMap);
const shard = getShardInfo(this.client, message.guildId ?? message.guild?.id); const shard = getShardInfo(this.client, message.guildId ?? message.guild?.id);
const tracksPlayed = await TrackStats.getTracksPlayed();
let botIcon = null; let botIcon = null;
try { try {
const raw = this.client?.user?.displayAvatarURL?.() || this.client?.user?.avatarURL?.(); const raw = this.client?.user?.displayAvatarURL?.() || this.client?.user?.avatarURL?.();
@@ -460,6 +463,7 @@ export async function run(message) {
playingCount: music.playingCount, playingCount: music.playingCount,
queuedTracks: music.queuedTracks, queuedTracks: music.queuedTracks,
radios247: music.radios247, radios247: music.radios247,
tracksPlayed,
shard, shard,
botIcon, botIcon,
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0, scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
@@ -505,6 +509,7 @@ export async function run(message) {
const fresh = getTotals(this.client); const fresh = getTotals(this.client);
const freshMusic = getMusicStats(this.players?.playerMap); const freshMusic = getMusicStats(this.players?.playerMap);
const freshTracks = await TrackStats.getTracksPlayed();
const fill = { const fill = {
...embedData, ...embedData,
guildCount: fresh.guildCount, guildCount: fresh.guildCount,
@@ -513,6 +518,7 @@ export async function run(message) {
playingCount: freshMusic.playingCount, playingCount: freshMusic.playingCount,
queuedTracks: freshMusic.queuedTracks, queuedTracks: freshMusic.queuedTracks,
radios247: freshMusic.radios247, radios247: freshMusic.radios247,
tracksPlayed: freshTracks,
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0, scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0, linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
ping: lastPing ?? 0, ping: lastPing ?? 0,
+8
View File
@@ -30,6 +30,7 @@ import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs";
import { LastFmManager } from "../services/lastfm/LastFmManager.mjs"; import { LastFmManager } from "../services/lastfm/LastFmManager.mjs";
import { FluxerListManager } from "../services/FluxerListManager.mjs"; import { FluxerListManager } from "../services/FluxerListManager.mjs";
import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs"; import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs";
import { TrackStats } from "../music/TrackStats.mjs";
import { configureBilibili } from "../music/bilibili/index.mjs"; import { configureBilibili } from "../music/bilibili/index.mjs";
import { configureAudio } from "../music/audio/AudioSettings.mjs"; import { configureAudio } from "../music/audio/AudioSettings.mjs";
import { applyMixins } from "../utils/mixins.mjs"; import { applyMixins } from "../utils/mixins.mjs";
@@ -145,6 +146,9 @@ class Remix {
redis: config.dashboard?.redis, redis: config.dashboard?.redis,
mysql: sharedPromisePool, mysql: sharedPromisePool,
}); });
if (this.dashboard?.redis) {
TrackStats.setRedis(this.dashboard.redis);
}
const presenceContents = config.presenceContents ?? []; const presenceContents = config.presenceContents ?? [];
const presenceInterval = config.presenceInterval ?? 30_000; const presenceInterval = config.presenceInterval ?? 30_000;
@@ -686,6 +690,10 @@ class Remix {
logger.warn("[Shutdown] Lavalink cleanup error:", e?.message); logger.warn("[Shutdown] Lavalink cleanup error:", e?.message);
} }
try {
TrackStats.save();
} catch (_) {}
// 4. Close Redis if dashboard enabled // 4. Close Redis if dashboard enabled
try { try {
if (this.dashboard?.redis?.destroy) { if (this.dashboard?.redis?.destroy) {
+5
View File
@@ -13,6 +13,7 @@
import { cleanId } from "../utils/Utils.mjs"; import { cleanId } from "../utils/Utils.mjs";
import { getMessageGuildId } from "../ui/index.mjs"; import { getMessageGuildId } from "../ui/index.mjs";
import { Dashboard } from "../dashboard/Dashboard.mjs"; import { Dashboard } from "../dashboard/Dashboard.mjs";
import { TrackStats } from "./TrackStats.mjs";
/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */ /** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */
function getPlayerGuildId(player, fallbackChannel = null) { function getPlayerGuildId(player, fallbackChannel = null) {
@@ -95,6 +96,10 @@ const PlayerEventsMixin = {
emit("streamStartPlay", Date.now()); emit("streamStartPlay", Date.now());
this.dashboard.playerUpdate({ type: "startplay" }, player); this.dashboard.playerUpdate({ type: "startplay" }, player);
if (!player._radioReconnects) {
TrackStats.increment();
}
if (this._lastfm?.enabled && song) { if (this._lastfm?.enabled && song) {
this._handleLastFmStartPlay(player, song); this._handleLastFmStartPlay(player, song);
} }
+116
View File
@@ -0,0 +1,116 @@
/**
* @module src/music/TrackStats
* @description Persistent playback counter tracking total songs and tracks played across shards.
* Backed by Redis with atomic INCR and debounced local storage in storage/stats.json.
*/
import fs from "node:fs";
import path from "node:path";
import { logger } from "../core/Logger.mjs";
const STATS_FILE = path.join(process.cwd(), "storage", "stats.json");
const REDIS_KEY = "fluxer:stats:tracks_played";
class TrackStatsManager {
constructor() {
this._tracksPlayed = 0;
this._extraData = {};
this._redis = null;
this._saveTimer = null;
this._loadFromFile();
}
_loadFromFile() {
try {
if (fs.existsSync(STATS_FILE)) {
const raw = JSON.parse(fs.readFileSync(STATS_FILE, "utf8"));
if (raw && typeof raw === "object") {
this._extraData = { ...raw };
const count = typeof raw.songs === "number"
? raw.songs
: (typeof raw.tracksPlayed === "number" ? raw.tracksPlayed : 0);
this._tracksPlayed = Math.max(0, count);
}
}
} catch (e) {
logger.warn("[TrackStats] Failed to read stats.json:", e?.message);
}
}
setRedis(redisHandler) {
this._redis = redisHandler;
this._syncRedis();
}
async _syncRedis() {
const client = this._redis?.client;
if (!client || !client.isOpen) return;
try {
await client.set(REDIS_KEY, String(this._tracksPlayed), { NX: true });
const val = await client.get(REDIS_KEY);
if (val != null) {
const parsed = parseInt(val, 10);
if (Number.isFinite(parsed)) {
this._tracksPlayed = Math.max(this._tracksPlayed, parsed);
}
}
} catch (e) {
logger.warn("[TrackStats] Redis sync error:", e?.message);
}
}
increment(delta = 1) {
this._tracksPlayed += delta;
const client = this._redis?.client;
if (client && client.isOpen) {
client.incrBy(REDIS_KEY, delta).catch((e) => {
logger.warn("[TrackStats] Redis incr error:", e?.message);
});
}
this._scheduleSave();
}
_scheduleSave() {
if (this._saveTimer) return;
this._saveTimer = setTimeout(() => {
this._saveTimer = null;
this.save();
}, 5000);
this._saveTimer.unref?.();
}
save() {
try {
fs.mkdirSync(path.dirname(STATS_FILE), { recursive: true });
const payload = {
...this._extraData,
songs: this._tracksPlayed,
};
fs.writeFileSync(STATS_FILE, JSON.stringify(payload, null, 2));
} catch (e) {
logger.warn("[TrackStats] Failed to save stats.json:", e?.message);
}
}
async getTracksPlayed() {
const client = this._redis?.client;
if (client && client.isOpen) {
try {
const val = await client.get(REDIS_KEY);
if (val != null) {
const parsed = parseInt(val, 10);
if (Number.isFinite(parsed)) {
this._tracksPlayed = Math.max(this._tracksPlayed, parsed);
return this._tracksPlayed;
}
}
} catch (_) {}
}
return this._tracksPlayed;
}
}
export const TrackStats = new TrackStatsManager();
+2 -1
View File
@@ -630,7 +630,8 @@
"build": "🔧 **الإصدار**", "build": "🔧 **الإصدار**",
"lastRestart": "🪛 **آخر إعادة تشغيل**", "lastRestart": "🪛 **آخر إعادة تشغيل**",
"supportKofi": "☕ [ادعمنا على Ko-fi](https://ko-fi.com/remixbot)", "supportKofi": "☕ [ادعمنا على Ko-fi](https://ko-fi.com/remixbot)",
"community": "💬 [المجتمع](https://fluxer.gg/Remix)" "community": "💬 [المجتمع](https://fluxer.gg/Remix)",
"tracksPlayed": "▶️ **المسارات المشغلة**"
}, },
"support": { "support": {
"title": "💬 الدعم", "title": "💬 الدعم",
+2 -1
View File
@@ -630,7 +630,8 @@
"build": "🔧 **بەرنامە**", "build": "🔧 **بەرنامە**",
"lastRestart": "🪛 **دوایین دەستپێکردنەوە**", "lastRestart": "🪛 **دوایین دەستپێکردنەوە**",
"supportKofi": "☕ [پشتگیری ئێمە لە Ko-fi](https://ko-fi.com/remixbot)", "supportKofi": "☕ [پشتگیری ئێمە لە Ko-fi](https://ko-fi.com/remixbot)",
"community": "💬 [کۆمەڵگە](https://fluxer.gg/Remix)" "community": "💬 [کۆمەڵگە](https://fluxer.gg/Remix)",
"tracksPlayed": "▶️ **گۆرانییە لێدراوەکان**"
}, },
"support": { "support": {
"title": "💬 پشتگیری", "title": "💬 پشتگیری",
+2 -1
View File
@@ -630,7 +630,8 @@
"build": "🔧 **Build**", "build": "🔧 **Build**",
"lastRestart": "🪛 **Letzter Neustart**", "lastRestart": "🪛 **Letzter Neustart**",
"supportKofi": "☕ [Unterstütze uns auf Ko-fi](https://ko-fi.com/remixbot)", "supportKofi": "☕ [Unterstütze uns auf Ko-fi](https://ko-fi.com/remixbot)",
"community": "💬 [Community](https://fluxer.gg/Remix)" "community": "💬 [Community](https://fluxer.gg/Remix)",
"tracksPlayed": "▶️ **Gespielte Titel**"
}, },
"support": { "support": {
"title": "💬 Support", "title": "💬 Support",
+2 -1
View File
@@ -747,7 +747,8 @@
"build": "🔧 **Build**", "build": "🔧 **Build**",
"lastRestart": "🪛 **Last restart**", "lastRestart": "🪛 **Last restart**",
"supportKofi": "☕ [Support us on Ko-fi](https://ko-fi.com/remixbot)", "supportKofi": "☕ [Support us on Ko-fi](https://ko-fi.com/remixbot)",
"community": "💬 [Community](https://fluxer.gg/Remix)" "community": "💬 [Community](https://fluxer.gg/Remix)",
"tracksPlayed": "▶️ **Tracks Played**"
}, },
"support": { "support": {
"title": "💬 Support", "title": "💬 Support",
+2 -1
View File
@@ -630,7 +630,8 @@
"build": "🔧 **Build**", "build": "🔧 **Build**",
"lastRestart": "🪛 **Último Reinício**", "lastRestart": "🪛 **Último Reinício**",
"supportKofi": "☕ [Apoie-nos no Ko-fi](https://ko-fi.com/remixbot)", "supportKofi": "☕ [Apoie-nos no Ko-fi](https://ko-fi.com/remixbot)",
"community": "💬 [Comunidade](https://fluxer.gg/Remix)" "community": "💬 [Comunidade](https://fluxer.gg/Remix)",
"tracksPlayed": "▶️ **Faixas Tocadas**"
}, },
"support": { "support": {
"title": "💬 Suporte", "title": "💬 Suporte",
+2 -1
View File
@@ -736,7 +736,8 @@
"build": "🔧 **Yapı**", "build": "🔧 **Yapı**",
"lastRestart": "🪛 **Son yeniden başlatma**", "lastRestart": "🪛 **Son yeniden başlatma**",
"supportKofi": "☕ [Bizi Ko-fi'de destekleyin](https://ko-fi.com/remixbot)", "supportKofi": "☕ [Bizi Ko-fi'de destekleyin](https://ko-fi.com/remixbot)",
"community": "💬 [Topluluk](https://fluxer.gg/Remix)" "community": "💬 [Topluluk](https://fluxer.gg/Remix)",
"tracksPlayed": "▶️ **Oynatılan Parçalar**"
}, },
"support": { "support": {
"title": "💬 Destek", "title": "💬 Destek",