mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
adding scrobbles
This commit is contained in:
1 parent
e2e39b52ad
commit
3e84002b79
8 files changed
+132
-7
No files matched your search
@@ -120,7 +120,7 @@ Below is the complete list of Remix's commands. The default prefix is `%`.
|
|||||||
| Command | Description | Usage | Aliases |
|
| Command | Description | Usage | Aliases |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| `settings` | View or change server settings (requires Manage Server) | `%settings set` | `prefix`, `pfx`, `247` |
|
| `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` |
|
| `invite` | Get the bot invite link | `%invite` | `addbot`, `remix` |
|
||||||
| `support` | Get an invite to the support server | `%support` | `server` |
|
| `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` |
|
| `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
|
│ ├── Settings.mjs # RemoteSettingsManager + ServerSettings export
|
||||||
│ ├── GatewayHandler.mjs # Raw WS events, voice-state tracking, presence rotation
|
│ ├── GatewayHandler.mjs # Raw WS events, voice-state tracking, presence rotation
|
||||||
│ ├── RecoveryManager.mjs # Session persistence, crash recovery, 24/7 auto-join
|
│ ├── 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
|
│ ├── Utils.mjs # Shared utilities
|
||||||
│ ├── worker.mjs # Background task worker
|
│ ├── worker.mjs # Background task worker
|
||||||
│ ├── probe.mjs # FFprobe wrapper for audio stream info
|
│ ├── probe.mjs # FFprobe wrapper for audio stream info
|
||||||
|
|||||||
+30
-5
@@ -115,7 +115,7 @@ function getLivePlayerCount(playerMap) {
|
|||||||
|
|
||||||
// ── Embed builder ─────────────────────────────────────────────────────────────
|
// ── 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 num = (v) => Utils.formatNumber(v);
|
||||||
const ld = (v) => loading ? "..." : 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.servers")} — \`${num(guildCount)}\``,
|
||||||
`${t(msg, "responses.stats.users")} — \`${ld(num(userCount))}\``,
|
`${t(msg, "responses.stats.users")} — \`${ld(num(userCount))}\``,
|
||||||
`${t(msg, "responses.stats.players")} — \`${num(playerCount)}\``,
|
`${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.ping")} — \`${ld(`${num(ping)}ms`)}\``,
|
||||||
`${t(msg, "responses.stats.uptime")} — \`${uptime}\``,
|
`${t(msg, "responses.stats.uptime")} — \`${uptime}\``,
|
||||||
`${t(msg, "responses.stats.build")} — [\`${comHash}\`](${comLink})`,
|
`${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.supportKofi"),
|
||||||
t(msg, "responses.stats.community"),
|
t(msg, "responses.stats.community"),
|
||||||
].filter(l => l !== null).join("\n");
|
);
|
||||||
|
|
||||||
|
const desc = description.filter(l => l !== null).join("\n");
|
||||||
|
|
||||||
const builder = new EmbedBuilder()
|
const builder = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setAuthor({ name: t(msg, "responses.stats.title") })
|
.setAuthor({ name: t(msg, "responses.stats.title") })
|
||||||
.setDescription(description)
|
.setDescription(desc)
|
||||||
.setFooter({ text: footer || t(msg, "responses.stats.title") });
|
.setFooter({ text: footer || t(msg, "responses.stats.title") });
|
||||||
|
|
||||||
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
||||||
@@ -145,9 +156,15 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, ping, uptime,
|
|||||||
// ── Runner ────────────────────────────────────────────────────────────────────
|
// ── Runner ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
|
const lastfm = this.lastfm;
|
||||||
|
const lastfmEnabled = lastfm?.enabled ?? false;
|
||||||
|
|
||||||
const shared = {
|
const shared = {
|
||||||
guildCount: this.client.guilds.size,
|
guildCount: this.client.guilds.size,
|
||||||
playerCount: getLivePlayerCount(this.players.playerMap),
|
playerCount: getLivePlayerCount(this.players.playerMap),
|
||||||
|
scrobbleCount: 0,
|
||||||
|
linkedUsers: 0,
|
||||||
|
lastfmEnabled,
|
||||||
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
|
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
|
||||||
comHash: this.comHash,
|
comHash: this.comHash,
|
||||||
comLink: this.comLink,
|
comLink: this.comLink,
|
||||||
@@ -155,6 +172,10 @@ 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)
|
||||||
|
const scrobblePromise = lastfmEnabled ? lastfm.getStoredScrobbles() : Promise.resolve(0);
|
||||||
|
const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0);
|
||||||
|
|
||||||
const hasCached = cachedUserCount !== null;
|
const hasCached = cachedUserCount !== null;
|
||||||
|
|
||||||
// Measure real round-trip latency
|
// Measure real round-trip latency
|
||||||
@@ -164,9 +185,13 @@ export async function run(message) {
|
|||||||
});
|
});
|
||||||
const ping = Date.now() - start;
|
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({
|
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));
|
}).catch((err) => console.error("[stats] editEmbed failed:", err));
|
||||||
}
|
}
|
||||||
@@ -89,6 +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;
|
||||||
|
|
||||||
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.");
|
||||||
}
|
}
|
||||||
@@ -122,6 +126,19 @@ export class LastFmManager {
|
|||||||
\`linked_at\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
\`linked_at\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) 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 ───────────────────────────────────────────────────────
|
// ── User persistence ───────────────────────────────────────────────────────
|
||||||
@@ -158,6 +175,17 @@ export class LastFmManager {
|
|||||||
);
|
);
|
||||||
const data = { sessionKey, username: username ?? "", scrobbleEnabled: true };
|
const data = { sessionKey, username: username ?? "", scrobbleEnabled: true };
|
||||||
this._userCache.set(userId, data);
|
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;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,6 +296,9 @@ export class LastFmManager {
|
|||||||
true // POST
|
true // POST
|
||||||
);
|
);
|
||||||
logger.settings(`[LastFm] Scrobbled "${track.title}" for ${userId}`);
|
logger.settings(`[LastFm] Scrobbled "${track.title}" for ${userId}`);
|
||||||
|
|
||||||
|
// Increment stored scrobbles counter (non-blocking)
|
||||||
|
this._incrementScrobbleCount();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`);
|
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<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 number of linked Last.fm users.
|
||||||
|
* @returns {Promise<number>}
|
||||||
|
*/
|
||||||
|
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 ───────────────────────────────────────────────────────
|
// ── Internal helpers ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
_assertEnabled() {
|
_assertEnabled() {
|
||||||
if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret).");
|
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) {
|
_extractArtist(track) {
|
||||||
return track.artists?.[0]?.name
|
return track.artists?.[0]?.name
|
||||||
?? track.author?.name
|
?? track.author?.name
|
||||||
|
|||||||
@@ -478,6 +478,8 @@
|
|||||||
"servers": "📂 **الخوادم**",
|
"servers": "📂 **الخوادم**",
|
||||||
"users": "👥 **المستخدمون**",
|
"users": "👥 **المستخدمون**",
|
||||||
"players": "🎧 **المشغّلات**",
|
"players": "🎧 **المشغّلات**",
|
||||||
|
"scrobbles": "🎵 **اسكروبلات**",
|
||||||
|
"linkedUsers": "🔗 **حسابات Last.fm**",
|
||||||
"ping": "🏓 **البينغ**",
|
"ping": "🏓 **البينغ**",
|
||||||
"uptime": "⏱️ **وقت التشغيل**",
|
"uptime": "⏱️ **وقت التشغيل**",
|
||||||
"build": "🔧 **الإصدار**",
|
"build": "🔧 **الإصدار**",
|
||||||
|
|||||||
@@ -478,6 +478,8 @@
|
|||||||
"servers": "📂 **سێرڤەرەکان**",
|
"servers": "📂 **سێرڤەرەکان**",
|
||||||
"users": "👥 **بەکارهێنەران**",
|
"users": "👥 **بەکارهێنەران**",
|
||||||
"players": "🎧 **پەخشکەرەکان**",
|
"players": "🎧 **پەخشکەرەکان**",
|
||||||
|
"scrobbles": "🎵 **سکرۆبلەکان**",
|
||||||
|
"linkedUsers": "🔗 **هەژمارەکانی Last.fm**",
|
||||||
"ping": "🏓 **پینگ**",
|
"ping": "🏓 **پینگ**",
|
||||||
"uptime": "⏱️ **کاتی چالاک**",
|
"uptime": "⏱️ **کاتی چالاک**",
|
||||||
"build": "🔧 **بەرنامە**",
|
"build": "🔧 **بەرنامە**",
|
||||||
|
|||||||
@@ -478,6 +478,8 @@
|
|||||||
"servers": "📂 **Server**",
|
"servers": "📂 **Server**",
|
||||||
"users": "👥 **Benutzer**",
|
"users": "👥 **Benutzer**",
|
||||||
"players": "🎧 **Player**",
|
"players": "🎧 **Player**",
|
||||||
|
"scrobbles": "🎵 **Scrobbles**",
|
||||||
|
"linkedUsers": "🔗 **Verknüpfte Last.fm**",
|
||||||
"ping": "🏓 **Ping**",
|
"ping": "🏓 **Ping**",
|
||||||
"uptime": "⏱️ **Uptime**",
|
"uptime": "⏱️ **Uptime**",
|
||||||
"build": "🔧 **Build**",
|
"build": "🔧 **Build**",
|
||||||
|
|||||||
@@ -483,6 +483,8 @@
|
|||||||
"servers": "📂 **Servers**",
|
"servers": "📂 **Servers**",
|
||||||
"users": "👥 **Users**",
|
"users": "👥 **Users**",
|
||||||
"players": "🎧 **Players**",
|
"players": "🎧 **Players**",
|
||||||
|
"scrobbles": "🎵 **Scrobbles**",
|
||||||
|
"linkedUsers": "🔗 **Linked Last.fm**",
|
||||||
"ping": "🏓 **Ping**",
|
"ping": "🏓 **Ping**",
|
||||||
"uptime": "⏱️ **Uptime**",
|
"uptime": "⏱️ **Uptime**",
|
||||||
"build": "🔧 **Build**",
|
"build": "🔧 **Build**",
|
||||||
|
|||||||
@@ -478,6 +478,8 @@
|
|||||||
"servers": "📂 **Servidores**",
|
"servers": "📂 **Servidores**",
|
||||||
"users": "👥 **Usuários**",
|
"users": "👥 **Usuários**",
|
||||||
"players": "🎧 **Players**",
|
"players": "🎧 **Players**",
|
||||||
|
"scrobbles": "🎵 **Scrobbles**",
|
||||||
|
"linkedUsers": "🔗 **Last.fm Vinculadas**",
|
||||||
"ping": "🏓 **Ping**",
|
"ping": "🏓 **Ping**",
|
||||||
"uptime": "⏱️ **Tempo de Atividade**",
|
"uptime": "⏱️ **Tempo de Atividade**",
|
||||||
"build": "🔧 **Build**",
|
"build": "🔧 **Build**",
|
||||||
|
|||||||
Reference in new issue
Block a user