mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
hotfix/added restore queue/added some good stuff to/removing some stuff to
This commit is contained in:
1 parent
ca98dc11aa
commit
8a8925653c
17 files changed
+429
-22
No files matched your search
@@ -108,8 +108,6 @@ function buildLeaderboardEmbed(lb, pageIdx, prefix, tr, opts = {}) {
|
|||||||
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||||
*/
|
*/
|
||||||
export async function runListeningActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
export async function runListeningActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||||
/* Translator bound to this message: every embed builder below renders in
|
|
||||||
the guild's locale instead of hardcoded English. */
|
|
||||||
const tr = (key, repl = {}) => this.t(msg, key, repl);
|
const tr = (key, repl = {}) => this.t(msg, key, repl);
|
||||||
|
|
||||||
switch (action) {
|
switch (action) {
|
||||||
|
|||||||
@@ -35,7 +35,6 @@ export const WHOKNOWS_ACTIONS = new Set([
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all non-bot user IDs in a guild.
|
* Get all non-bot user IDs in a guild.
|
||||||
* @export
|
|
||||||
* @async
|
* @async
|
||||||
* @param {object} guild - The guild object.
|
* @param {object} guild - The guild object.
|
||||||
* @returns {Promise<string[]>} Array of user ID strings.
|
* @returns {Promise<string[]>} Array of user ID strings.
|
||||||
|
|||||||
+2
-1
@@ -139,7 +139,8 @@
|
|||||||
"playerUpdateInterval": 5000,
|
"playerUpdateInterval": 5000,
|
||||||
"searchSessionTimeout": 30000,
|
"searchSessionTimeout": 30000,
|
||||||
"playerSessionTimeout": 300000,
|
"playerSessionTimeout": 300000,
|
||||||
"intentionalLeaveTTL": 8000
|
"intentionalLeaveTTL": 8000,
|
||||||
|
"stayInVoice": true
|
||||||
},
|
},
|
||||||
"sharding": {
|
"sharding": {
|
||||||
"totalShards": 1,
|
"totalShards": 1,
|
||||||
|
|||||||
@@ -101,6 +101,11 @@ process.on("uncaughtExceptionMonitor", (err, origin) => {
|
|||||||
*/
|
*/
|
||||||
const saveAndExit = async () => {
|
const saveAndExit = async () => {
|
||||||
logger.recovery("\n[Shutdown] Cleaning up before exit...");
|
logger.recovery("\n[Shutdown] Cleaning up before exit...");
|
||||||
|
try {
|
||||||
|
await remix.playerState?.saveAllFrom?.(remix.players);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Shutdown] Player state save failed:", e?.message);
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
if (remix.players?.playerMap) {
|
if (remix.players?.playerMap) {
|
||||||
for (const [channelId, player] of remix.players.playerMap) {
|
for (const [channelId, player] of remix.players.playerMap) {
|
||||||
|
|||||||
+5
-1
@@ -18,6 +18,7 @@ import { MessageHandler, HelpCommand, setGlobalColor } from "../ui/index.mjs";
|
|||||||
import { cleanId } from "../utils/Utils.mjs";
|
import { cleanId } from "../utils/Utils.mjs";
|
||||||
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
|
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
|
||||||
import { RemoteSettingsManager } from "../db/Settings.mjs";
|
import { RemoteSettingsManager } from "../db/Settings.mjs";
|
||||||
|
import { PlayerStateStore } from "../db/PlayerStateStore.mjs";
|
||||||
import { PlayerManager } from "../music/PlayerManager.mjs";
|
import { PlayerManager } from "../music/PlayerManager.mjs";
|
||||||
import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
||||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||||
@@ -176,6 +177,8 @@ class Remix {
|
|||||||
const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
|
const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
|
||||||
this.settingsMgr = settings;
|
this.settingsMgr = settings;
|
||||||
|
|
||||||
|
this.playerState = new PlayerStateStore(settings.db);
|
||||||
|
|
||||||
const configPrefix = config.prefix ?? null;
|
const configPrefix = config.prefix ?? null;
|
||||||
if (configPrefix && settings.defaults) {
|
if (configPrefix && settings.defaults) {
|
||||||
settings.defaults.prefix = configPrefix;
|
settings.defaults.prefix = configPrefix;
|
||||||
@@ -258,6 +261,7 @@ class Remix {
|
|||||||
|
|
||||||
await this.settingsMgr.setBotId(botId);
|
await this.settingsMgr.setBotId(botId);
|
||||||
await this.lastfm.setBotId(botId);
|
await this.lastfm.setBotId(botId);
|
||||||
|
this.playerState?.setBotId?.(botId);
|
||||||
this.dashboard.setBotId(botId);
|
this.dashboard.setBotId(botId);
|
||||||
this.trackOptions.setBotId(botId);
|
this.trackOptions.setBotId(botId);
|
||||||
|
|
||||||
@@ -493,7 +497,7 @@ class Remix {
|
|||||||
player._startInactivityTimer?.();
|
player._startInactivityTimer?.();
|
||||||
} else {
|
} else {
|
||||||
player._stopInactivityTimer?.();
|
player._stopInactivityTimer?.();
|
||||||
player.emit("autoleave");
|
if (!player._stayInVoice) player.emit("autoleave");
|
||||||
}
|
}
|
||||||
} else if (hasHuman) {
|
} else if (hasHuman) {
|
||||||
player._stopInactivityTimer?.();
|
player._stopInactivityTimer?.();
|
||||||
|
|||||||
@@ -413,6 +413,104 @@ const BotVoiceMixin = {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restore music players saved before a restart/crash (PlayerStateStore).
|
||||||
|
* Called from GatewayHandler.onReady after the 24/7 boot recovery.
|
||||||
|
* @this {import('./Bot.mjs').Remix}
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async restorePlayerState() {
|
||||||
|
const store = this.playerState;
|
||||||
|
if (!store) return;
|
||||||
|
|
||||||
|
let rows = [];
|
||||||
|
try {
|
||||||
|
rows = await store.loadAll();
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Restore] Could not load saved player state:", e?.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!rows.length) return;
|
||||||
|
|
||||||
|
const lava = this.lavalink;
|
||||||
|
if (lava?.hasConnectedNode && !lava.hasConnectedNode() && lava.waitForNode) {
|
||||||
|
logger.player("[Restore] Waiting up to 90s for an audio node...");
|
||||||
|
await lava.waitForNode({ timeoutMs: 90_000, intervalMs: 2_000 }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const local = rows.filter((r) => {
|
||||||
|
try { return !!this.client?.guilds?.get?.(r.guildId); } catch (_) { return false; }
|
||||||
|
});
|
||||||
|
logger.player(`[Restore] ${rows.length} saved player(s) found — restoring ${local.length} on this shard.`);
|
||||||
|
if (!local.length) return;
|
||||||
|
|
||||||
|
for (let i = 0; i < local.length; i++) {
|
||||||
|
const { guildId, data: snap } = local[i];
|
||||||
|
if (i > 0) await new Promise((r) => setTimeout(r, 1_500));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const channelId = cleanId(snap.channelId);
|
||||||
|
if (!channelId) { await store.clearSnapshot(guildId); continue; }
|
||||||
|
|
||||||
|
const channel = await resolveChannelCached(this.client, channelId);
|
||||||
|
if (!channel || channel.type !== 2) {
|
||||||
|
logger.player(`[Restore] Channel ${channelId} for guild ${guildId} is gone — dropping snapshot.`);
|
||||||
|
await store.clearSnapshot(guildId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const player = await this._spawnPlayer(guildId, channelId);
|
||||||
|
|
||||||
|
const tcId = cleanId(snap.textChannelId);
|
||||||
|
if (tcId) {
|
||||||
|
const tc = this.client?.channels?.get?.(tcId);
|
||||||
|
if (tc) player.textChannel = tc;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Number.isFinite(snap.volume) && snap.volume > 0) {
|
||||||
|
try { player.setVolume(Math.min(Number(snap.volume), 2)); } catch (_) {}
|
||||||
|
}
|
||||||
|
player.queue.loop = !!snap.loop;
|
||||||
|
player.queue.songLoop = !!snap.songLoop;
|
||||||
|
|
||||||
|
const restoredQueue = (Array.isArray(snap.queue) ? snap.queue : [])
|
||||||
|
.filter((t) => t && (t.url || t.encoded));
|
||||||
|
|
||||||
|
let current = (snap.current && (snap.current.url || snap.current.encoded)) ? snap.current : null;
|
||||||
|
const pos = Math.max(0, Number(snap.positionMs) || 0);
|
||||||
|
const dur = Number(current?._durationMs) || 0;
|
||||||
|
if (current && dur > 0 && pos > dur * 0.9) current = null;
|
||||||
|
|
||||||
|
player.queue.data = [];
|
||||||
|
if (current) player.queue.data.push(current);
|
||||||
|
for (const t of restoredQueue) player.queue.data.push(t);
|
||||||
|
|
||||||
|
if (!player.queue.data.length) {
|
||||||
|
await store.clearSnapshot(guildId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
player.emit("message", {
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||||
|
player._t?.("responses._common.queueRestored", { count: player.queue.data.length })
|
||||||
|
?? `Bot restarted — restored **${player.queue.data.length}** song(s) to the queue.`)],
|
||||||
|
system: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await player.playNext();
|
||||||
|
|
||||||
|
if (current && pos > 0) {
|
||||||
|
await new Promise((r) => setTimeout(r, 800)); // let the bridge settle
|
||||||
|
try { await player.seekToPosition(pos); } catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.player(`[Restore] Guild ${guildId}: ${player.queue.data.length} track(s) restored, resuming at ${pos}ms.`);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn(`[Restore] Failed to restore guild ${guildId}:`, e?.message ?? e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Leave a voice channel programmatically. Removes 24/7 if active, destroys
|
* Leave a voice channel programmatically. Removes 24/7 if active, destroys
|
||||||
* the player, and optionally sends a confirmation message.
|
* the player, and optionally sends a confirmation message.
|
||||||
|
|||||||
@@ -0,0 +1,266 @@
|
|||||||
|
/**
|
||||||
|
* @module src/db/PlayerStateStore
|
||||||
|
* @description MySQL-backed persistence for music player state so queues
|
||||||
|
* survive bot reboots/crashes. One row per (bot_id, guild_id) holding a JSON
|
||||||
|
* snapshot of the player: voice channel, text channel, queue tracks, current
|
||||||
|
* track, resume position, volume and loop modes.
|
||||||
|
*
|
||||||
|
* WHY MySQL AND NOT REDIS/FILES:
|
||||||
|
* - The bot already owns a MySQL pool (RemoteSettingsManager) that is flushed
|
||||||
|
* on graceful shutdown; snapshots ride the same healthy connection and are
|
||||||
|
* durable across restarts of ANY component.
|
||||||
|
* - The project's Redis handle (dashboard RedisHandler) is a pub/sub cache
|
||||||
|
* whose client is closed on shutdown — it is the wrong place for state
|
||||||
|
* that must outlive a reboot.
|
||||||
|
* - Local JSON files were audited and removed from the hot path years ago
|
||||||
|
* (storage/stats.json has no writer left); adding file writes would make
|
||||||
|
* the bot slower, not faster.
|
||||||
|
*
|
||||||
|
* Write pattern:
|
||||||
|
* - Full snapshot: debounced 3s per player, triggered by queue/playback
|
||||||
|
* events (see Player.mjs).
|
||||||
|
* - Position heartbeat: single cheap UPDATE of the position_ms column every
|
||||||
|
* 15s while a track is playing, so resume-after-crash lands within ~15s
|
||||||
|
* of where the song actually was.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
import { cleanId } from "../utils/Utils.mjs";
|
||||||
|
|
||||||
|
/** Maximum number of queued tracks persisted in one snapshot. */
|
||||||
|
const MAX_PERSISTED_TRACKS = 300;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reduce a track object to the plain fields needed to rebuild and replay it.
|
||||||
|
* Track objects are plain data already, but the whitelist keeps the payload
|
||||||
|
* small and guarantees JSON-safety (no circular refs from richer sources).
|
||||||
|
* @param {object|null} t - Track object.
|
||||||
|
* @returns {object|null} Slim track or null.
|
||||||
|
*/
|
||||||
|
function slimTrack(t) {
|
||||||
|
if (!t || typeof t !== "object") return null;
|
||||||
|
return {
|
||||||
|
encoded: typeof t.encoded === "string" ? t.encoded : null,
|
||||||
|
title: t.title ?? "Unknown",
|
||||||
|
url: t.url ?? null,
|
||||||
|
thumbnail: t.thumbnail ?? null,
|
||||||
|
artworkUrl: t.artworkUrl ?? null,
|
||||||
|
_durationMs: Number(t._durationMs) || 0,
|
||||||
|
duration: t.duration ?? null,
|
||||||
|
author: t.author ?? null,
|
||||||
|
requester: t.requester ?? null,
|
||||||
|
type: t.type ?? null,
|
||||||
|
identifier: t.identifier ?? null,
|
||||||
|
isStream: !!t.isStream,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute the playback position of a player's current track in ms.
|
||||||
|
* `startedPlaying` is kept in sync across seeks and pauses by the player
|
||||||
|
* (resume folds pause duration back in), so:
|
||||||
|
* - playing → Date.now() - startedPlaying
|
||||||
|
* - paused → _pausedAt - startedPlaying (elapsed at the pause moment)
|
||||||
|
* @param {object} player - Player instance.
|
||||||
|
* @param {object|null} current - Current track.
|
||||||
|
* @returns {number} Position in ms (0 when unknown).
|
||||||
|
*/
|
||||||
|
function computePosition(player, current) {
|
||||||
|
if (!current) return 0;
|
||||||
|
try {
|
||||||
|
if (player._paused && player._pausedAt && player.startedPlaying) {
|
||||||
|
return Math.max(0, player._pausedAt - player.startedPlaying);
|
||||||
|
}
|
||||||
|
if (player.startedPlaying) {
|
||||||
|
return Math.max(0, Date.now() - player.startedPlaying);
|
||||||
|
}
|
||||||
|
} catch (_) { /* fallthrough */ }
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class PlayerStateStore
|
||||||
|
* @description Persists and restores player snapshots in MySQL. Reuses the
|
||||||
|
* settings manager's mysql2 pool (callback API) — no extra connections.
|
||||||
|
*/
|
||||||
|
export class PlayerStateStore {
|
||||||
|
/** @private @type {object|null} mysql2 callback-style pool. */
|
||||||
|
db = null;
|
||||||
|
|
||||||
|
/** @private @type {string} Bot user id for multi-bot isolation. */
|
||||||
|
botId = "";
|
||||||
|
|
||||||
|
/** @private @type {Promise<void>|null} Memoized CREATE TABLE promise. */
|
||||||
|
_tableReady = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object|null} pool - mysql2 callback pool (RemoteSettingsManager.db).
|
||||||
|
*/
|
||||||
|
constructor(pool) {
|
||||||
|
this.db = pool ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the bot id (called once the gateway client is ready).
|
||||||
|
* @param {string} id - Bot user id.
|
||||||
|
*/
|
||||||
|
setBotId(id) {
|
||||||
|
this.botId = id ? String(id) : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Promisified pool.query with parameter binding.
|
||||||
|
* @private
|
||||||
|
* @param {string} sql - SQL with ? placeholders.
|
||||||
|
* @param {Array} [params=[]] - Bind parameters.
|
||||||
|
* @returns {Promise<any>} Result set.
|
||||||
|
*/
|
||||||
|
_exec(sql, params = []) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (!this.db) return reject(new Error("PlayerStateStore: no MySQL pool"));
|
||||||
|
this.db.query(sql, params, (err, results) => (err ? reject(err) : resolve(results)));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create the player_state table if needed (idempotent, memoized).
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
init() {
|
||||||
|
if (!this._tableReady) {
|
||||||
|
this._tableReady = this._exec(
|
||||||
|
`CREATE TABLE IF NOT EXISTS player_state (
|
||||||
|
bot_id VARCHAR(32) NOT NULL DEFAULT '',
|
||||||
|
guild_id VARCHAR(32) NOT NULL,
|
||||||
|
data MEDIUMTEXT NOT NULL,
|
||||||
|
position_ms BIGINT NOT NULL DEFAULT 0,
|
||||||
|
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (bot_id, guild_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
||||||
|
).catch((err) => {
|
||||||
|
this._tableReady = null; // allow retry on next call
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return this._tableReady;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persist a full snapshot of a player (debounce happens on the caller side).
|
||||||
|
* Deletes the row instead when the player has neither a current track nor
|
||||||
|
* queued songs (nothing worth restoring).
|
||||||
|
* @param {object} player - Player instance (duck-typed).
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async saveSnapshot(player) {
|
||||||
|
if (!player || player._destroyed || player.leaving) return;
|
||||||
|
|
||||||
|
const guildId = cleanId(player._guildId ?? "");
|
||||||
|
if (!guildId) return;
|
||||||
|
|
||||||
|
const current = player.queue?.getCurrent?.() ?? null;
|
||||||
|
const queued = Array.isArray(player.queue?.data) ? player.queue.data : [];
|
||||||
|
if (!current && queued.length === 0) {
|
||||||
|
return this.clearSnapshot(guildId);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.init();
|
||||||
|
|
||||||
|
const channelId = cleanId(player._channelId ?? player._home247Channel ?? "");
|
||||||
|
if (!channelId) return;
|
||||||
|
|
||||||
|
const positionMs = computePosition(player, current);
|
||||||
|
const textChannel = player.textChannel ?? null;
|
||||||
|
const payload = {
|
||||||
|
v: 1,
|
||||||
|
guildId,
|
||||||
|
channelId,
|
||||||
|
textChannelId: cleanId(textChannel?.id ?? textChannel?.channel?.id ?? ""),
|
||||||
|
volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume : null,
|
||||||
|
loop: !!player.queue?.loop,
|
||||||
|
songLoop: !!player.queue?.songLoop,
|
||||||
|
current: slimTrack(current),
|
||||||
|
positionMs,
|
||||||
|
queue: queued.slice(0, MAX_PERSISTED_TRACKS).map(slimTrack).filter(Boolean),
|
||||||
|
savedAt: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
await this._exec(
|
||||||
|
`INSERT INTO player_state (bot_id, guild_id, data, position_ms)
|
||||||
|
VALUES (?, ?, ?, ?)
|
||||||
|
ON DUPLICATE KEY UPDATE data = VALUES(data), position_ms = VALUES(position_ms)`,
|
||||||
|
[this.botId, guildId, JSON.stringify(payload), positionMs]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cheap heartbeat: update only the resume position of a guild's snapshot.
|
||||||
|
* @param {string} guildId - Guild id.
|
||||||
|
* @param {number} positionMs - Position within the current track in ms.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async updatePosition(guildId, positionMs) {
|
||||||
|
const gId = cleanId(guildId);
|
||||||
|
if (!gId) return;
|
||||||
|
await this.init();
|
||||||
|
await this._exec(
|
||||||
|
`UPDATE player_state SET position_ms = ? WHERE bot_id = ? AND guild_id = ?`,
|
||||||
|
[Math.max(0, Math.round(Number(positionMs) || 0)), this.botId, gId]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a guild's snapshot (intentional %leave, guild gone, empty queue).
|
||||||
|
* @param {string} guildId - Guild id.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async clearSnapshot(guildId) {
|
||||||
|
const gId = cleanId(guildId);
|
||||||
|
if (!gId || !this.db) return;
|
||||||
|
try {
|
||||||
|
await this.init();
|
||||||
|
await this._exec(`DELETE FROM player_state WHERE bot_id = ? AND guild_id = ?`, [this.botId, gId]);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[PlayerState] clearSnapshot failed:", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load every snapshot belonging to this bot.
|
||||||
|
* @returns {Promise<Array<{guildId: string, data: object, positionMs: number}>>}
|
||||||
|
*/
|
||||||
|
async loadAll() {
|
||||||
|
await this.init();
|
||||||
|
const rows = await this._exec(
|
||||||
|
`SELECT guild_id, data, position_ms FROM player_state WHERE bot_id = ?`,
|
||||||
|
[this.botId]
|
||||||
|
);
|
||||||
|
const out = [];
|
||||||
|
for (const row of Array.isArray(rows) ? rows : []) {
|
||||||
|
try {
|
||||||
|
const parsed = typeof row.data === "string" ? JSON.parse(row.data) : row.data;
|
||||||
|
if (parsed && parsed.channelId) {
|
||||||
|
out.push({ guildId: String(row.guild_id), data: parsed, positionMs: Number(row.position_ms) || 0 });
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[PlayerState] Skipping malformed snapshot for guild", row.guild_id, ":", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Snapshot every live player of a manager immediately (shutdown path).
|
||||||
|
* @param {object} playerManager - Object exposing playerMap (channelId → Player).
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async saveAllFrom(playerManager) {
|
||||||
|
const players = [...(playerManager?.playerMap?.values?.() ?? [])];
|
||||||
|
const alive = players.filter((p) => p && !p._destroyed && !p.leaving);
|
||||||
|
if (alive.length === 0) return;
|
||||||
|
logger.recovery(`[PlayerState] Saving ${alive.length} player snapshot(s) before shutdown...`);
|
||||||
|
await Promise.allSettled(alive.map((p) => this.saveSnapshot(p)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default PlayerStateStore;
|
||||||
@@ -146,8 +146,6 @@ const PlayerLifecycleMixin = {
|
|||||||
const guildId = getMessageGuildId(msg);
|
const guildId = getMessageGuildId(msg);
|
||||||
const cleanGuildId = cleanId(guildId);
|
const cleanGuildId = cleanId(guildId);
|
||||||
|
|
||||||
/* DMs have no voice channels — prompting for a channel selection would
|
|
||||||
be pointless (and hang until timeout). Tell the user directly. */
|
|
||||||
if (!cleanGuildId) {
|
if (!cleanGuildId) {
|
||||||
await msg.reply(this._t(msg, "responses._common.serverOnlyForMusic")).catch(() => {});
|
await msg.reply(this._t(msg, "responses._common.serverOnlyForMusic")).catch(() => {});
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -156,6 +156,32 @@ class Player extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this._stayInVoice = this.config?.timers?.stayInVoice ?? this.config?.stayInVoice ?? true;
|
||||||
|
|
||||||
|
this._snapSaveTimer = null;
|
||||||
|
this._scheduleStateSave = () => {
|
||||||
|
if (this._snapSaveTimer || this._destroyed || this.leaving) return;
|
||||||
|
this._snapSaveTimer = setTimeout(() => {
|
||||||
|
this._snapSaveTimer = null;
|
||||||
|
try {
|
||||||
|
this.client?._remix?.playerState?.saveSnapshot(this)?.catch?.(() => {});
|
||||||
|
} catch (_) { /* persistence must never break playback */ }
|
||||||
|
}, 3_000);
|
||||||
|
};
|
||||||
|
for (const evt of ["queue", "startplay", "stopplay", "playback"]) {
|
||||||
|
try { this.on(evt, this._scheduleStateSave); } catch (_) {}
|
||||||
|
}
|
||||||
|
this._stateHeartbeat = setInterval(() => {
|
||||||
|
try {
|
||||||
|
const current = this.queue?.getCurrent?.();
|
||||||
|
if (!current || this._destroyed || this.leaving || this._paused) return;
|
||||||
|
if (!this.startedPlaying) return;
|
||||||
|
const pos = Math.max(0, Date.now() - this.startedPlaying);
|
||||||
|
this.client?._remix?.playerState?.updatePosition?.(this._guildId, pos)?.catch?.(() => {});
|
||||||
|
} catch (_) { /* best effort */ }
|
||||||
|
}, 15_000);
|
||||||
|
this._stateHeartbeat.unref?.();
|
||||||
|
|
||||||
if (this._lavalink) {
|
if (this._lavalink) {
|
||||||
this._onLavalinkPlayerDisconnect = (lavaPlayer) => {
|
this._onLavalinkPlayerDisconnect = (lavaPlayer) => {
|
||||||
if (!lavaPlayer || String(lavaPlayer.guildId) !== String(this._guildId)) return;
|
if (!lavaPlayer || String(lavaPlayer.guildId) !== String(this._guildId)) return;
|
||||||
@@ -269,6 +295,11 @@ class Player extends EventEmitter {
|
|||||||
this._stopInactivityTimer();
|
this._stopInactivityTimer();
|
||||||
if (this._inactivityLimit <= 0) return;
|
if (this._inactivityLimit <= 0) return;
|
||||||
|
|
||||||
|
if (this._stayInVoice) {
|
||||||
|
logger.inactivity(`[Player] stay-in-voice active for guild ${this._guildId} — skipping inactivity auto-leave`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const mode = this._get247Mode();
|
const mode = this._get247Mode();
|
||||||
logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`);
|
logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`);
|
||||||
|
|
||||||
@@ -614,6 +645,10 @@ class Player extends EventEmitter {
|
|||||||
this.removeListener("queueEnd", this._autoplayHandler);
|
this.removeListener("queueEnd", this._autoplayHandler);
|
||||||
this._autoplayHandler = null;
|
this._autoplayHandler = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.client?._remix?.playerState?.clearSnapshot?.(this._guildId)?.catch?.(() => {});
|
||||||
|
} catch (_) { /* best effort */ }
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error("[Player] leave error:", e.message);
|
logger.error("[Player] leave error:", e.message);
|
||||||
this.leaving = false;
|
this.leaving = false;
|
||||||
@@ -632,6 +667,10 @@ class Player extends EventEmitter {
|
|||||||
if (this._destroyed) return;
|
if (this._destroyed) return;
|
||||||
this._destroyed = true;
|
this._destroyed = true;
|
||||||
|
|
||||||
|
this._scheduleStateSave = null;
|
||||||
|
if (this._snapSaveTimer) { clearTimeout(this._snapSaveTimer); this._snapSaveTimer = null; }
|
||||||
|
if (this._stateHeartbeat) { clearInterval(this._stateHeartbeat); this._stateHeartbeat = null; }
|
||||||
|
|
||||||
this._clearTrackEndTimer();
|
this._clearTrackEndTimer();
|
||||||
this._activeTrackOpt = null;
|
this._activeTrackOpt = null;
|
||||||
|
|
||||||
|
|||||||
@@ -321,11 +321,6 @@ const ServerStatsMixin = {
|
|||||||
async getLeaderboard(page = 0, perPage = 10) {
|
async getLeaderboard(page = 0, perPage = 10) {
|
||||||
if (!this.enabled) return { entries: [], totalUsers: 0, page: 0, perPage: 10, totalPages: 0 };
|
if (!this.enabled) return { entries: [], totalUsers: 0, page: 0, perPage: 10, totalPages: 0 };
|
||||||
|
|
||||||
/* Sync scrobble counts from Last.fm before ranking. The local counter
|
|
||||||
only advances on bot-made scrobbles, so listening done outside the
|
|
||||||
bot (phone/desktop clients) would never show up. getTotalScrobbles()
|
|
||||||
syncs every linked user, is deduped while in-flight, cached for 10
|
|
||||||
minutes, and resolves (never throws) even if the API is down. */
|
|
||||||
try {
|
try {
|
||||||
await this.getTotalScrobbles();
|
await this.getTotalScrobbles();
|
||||||
} catch (_) { /* stale counts are better than no leaderboard */ }
|
} catch (_) { /* stale counts are better than no leaderboard */ }
|
||||||
@@ -359,9 +354,6 @@ const ServerStatsMixin = {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Global rank (1-based) of one user on the all-time scrobble leaderboard.
|
* Global rank (1-based) of one user on the all-time scrobble leaderboard.
|
||||||
* Returns null when the user is not linked or has no scrobbles recorded
|
|
||||||
* yet (they are not ranked). Used so anyone can check whether they are
|
|
||||||
* top 1, 2, 3 ... even when their row is not on the visible page.
|
|
||||||
* @async
|
* @async
|
||||||
* @param {string} userId - Platform user ID to look up.
|
* @param {string} userId - Platform user ID to look up.
|
||||||
* @returns {Promise<{rank: number, scrobbleCount: number}|null>} Rank info or null.
|
* @returns {Promise<{rank: number, scrobbleCount: number}|null>} Rank info or null.
|
||||||
@@ -388,10 +380,7 @@ const ServerStatsMixin = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the scrobble leaderboard scoped to a set of platform user IDs
|
* Get the scrobble leaderboard scoped to a set of platform user IDs, with pagination.
|
||||||
* (typically the members of one guild), with pagination. Refreshes only
|
|
||||||
* these users' counts from Last.fm first (5-minute TTL, deduped while
|
|
||||||
* in-flight) so pagination turns don't hammer the API.
|
|
||||||
* @async
|
* @async
|
||||||
* @param {Array<string>} userIds - Platform user IDs to include.
|
* @param {Array<string>} userIds - Platform user IDs to include.
|
||||||
* @param {number} [page=0] - Zero-based page index.
|
* @param {number} [page=0] - Zero-based page index.
|
||||||
@@ -407,9 +396,6 @@ const ServerStatsMixin = {
|
|||||||
.filter(id => /^\d{5,25}$/.test(id)))];
|
.filter(id => /^\d{5,25}$/.test(id)))];
|
||||||
if (!ids.length) return empty;
|
if (!ids.length) return empty;
|
||||||
|
|
||||||
/* Refresh just these users' counts from Last.fm before ranking.
|
|
||||||
The local counter only advances on bot-made scrobbles, so listening
|
|
||||||
done outside the bot would never show up. TTL-gated + deduped. */
|
|
||||||
try {
|
try {
|
||||||
if (!this._lbServerSyncAt || Date.now() - this._lbServerSyncAt > 5 * 60 * 1000) {
|
if (!this._lbServerSyncAt || Date.now() - this._lbServerSyncAt > 5 * 60 * 1000) {
|
||||||
if (!this._lbServerSyncInflight) {
|
if (!this._lbServerSyncInflight) {
|
||||||
|
|||||||
@@ -448,6 +448,13 @@ class GatewayHandler {
|
|||||||
|
|
||||||
this.rejoin247Channels();
|
this.rejoin247Channels();
|
||||||
this.start247Watchdog();
|
this.start247Watchdog();
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.remix.restorePlayerState?.().catch?.((e) =>
|
||||||
|
logger.warn("[Restore] Player state restore failed:", e?.message));
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Restore] Player state restore could not start:", e?.message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -207,6 +207,7 @@
|
|||||||
"notInVoice": "أنا لست في قناة صوتية.",
|
"notInVoice": "أنا لست في قناة صوتية.",
|
||||||
"queueEmpty": "📭 قائمة الانتظار فارغة. استخدم `{{prefix}}play` لإضافة أغاني!",
|
"queueEmpty": "📭 قائمة الانتظار فارغة. استخدم `{{prefix}}play` لإضافة أغاني!",
|
||||||
"queueEnded": "🎵 قائمة الانتظار انتهت — لا يوجد شيء لتشغيله. أضف المزيد من الأغاني باستخدام `{{prefix}}play`!",
|
"queueEnded": "🎵 قائمة الانتظار انتهت — لا يوجد شيء لتشغيله. أضف المزيد من الأغاني باستخدام `{{prefix}}play`!",
|
||||||
|
"queueRestored": "🔁 استعادة بعد إعادة التشغيل — تم إرجاع **{{count}}** من الأغاني إلى قائمة الانتظار وإعادة الاتصال بالقناة الصوتية. يتم المتابعة من حيث توقف.",
|
||||||
"notConnected": "يبدو أننا لسنا في نفس القناة الصوتية.",
|
"notConnected": "يبدو أننا لسنا في نفس القناة الصوتية.",
|
||||||
"controlsExpired": "⌛ انتهت صلاحية عناصر التحكم",
|
"controlsExpired": "⌛ انتهت صلاحية عناصر التحكم",
|
||||||
"sessionEnded": "انتهت الجلسة",
|
"sessionEnded": "انتهت الجلسة",
|
||||||
|
|||||||
@@ -207,6 +207,7 @@
|
|||||||
"notInVoice": "من لە کەناڵێکی دەنگیدا نییم.",
|
"notInVoice": "من لە کەناڵێکی دەنگیدا نییم.",
|
||||||
"queueEmpty": "📭 ڕیزبەندییەکە بەتاڵە. `{{prefix}}play` بەکاربهێنە بۆ زیادکردنی گۆرانی!",
|
"queueEmpty": "📭 ڕیزبەندییەکە بەتاڵە. `{{prefix}}play` بەکاربهێنە بۆ زیادکردنی گۆرانی!",
|
||||||
"queueEnded": "🎵 ڕیزبەندییەکە تەواو بوو — هیچ شتێک نەماوە بۆ پەخشکردن. گۆرانی زیاتر زیاد بکە بە `{{prefix}}play`!",
|
"queueEnded": "🎵 ڕیزبەندییەکە تەواو بوو — هیچ شتێک نەماوە بۆ پەخشکردن. گۆرانی زیاتر زیاد بکە بە `{{prefix}}play`!",
|
||||||
|
"queueRestored": "🔁 دوای ریستارت ت۔ **{{count}}** گۆرانی گەرایەوە بۆ ڕیز و دووبارە پەیوەستا کرایەوە بە چەناڵی دەنگ. ڵە لای وەزگرای دەگەت.",
|
||||||
"notConnected": "پێناچێت لە یەک کەناڵی دەنگیدا بین.",
|
"notConnected": "پێناچێت لە یەک کەناڵی دەنگیدا بین.",
|
||||||
"controlsExpired": "⌛ کۆنتڕۆڵەکان بەسەرچوون",
|
"controlsExpired": "⌛ کۆنتڕۆڵەکان بەسەرچوون",
|
||||||
"sessionEnded": "دانیشتن تەواو بوو",
|
"sessionEnded": "دانیشتن تەواو بوو",
|
||||||
|
|||||||
@@ -207,6 +207,7 @@
|
|||||||
"notInVoice": "Ich bin in keinem Sprachkanal.",
|
"notInVoice": "Ich bin in keinem Sprachkanal.",
|
||||||
"queueEmpty": "📭 Die Warteschlange ist leer. Nutze `{{prefix}}play`, um Songs hinzuzufügen!",
|
"queueEmpty": "📭 Die Warteschlange ist leer. Nutze `{{prefix}}play`, um Songs hinzuzufügen!",
|
||||||
"queueEnded": "🎵 Die Warteschlange ist zu Ende — nichts mehr abzuspielen. Füge weitere Songs mit `{{prefix}}play` hinzu!",
|
"queueEnded": "🎵 Die Warteschlange ist zu Ende — nichts mehr abzuspielen. Füge weitere Songs mit `{{prefix}}play` hinzu!",
|
||||||
|
"queueRestored": "🔁 Neustart abgeschlossen — **{{count}}** Titel zurück in der Warteschlange und Sprachverbindung wiederhergestellt. Es wird dort fortgesetzt, wo es aufgehört hat.",
|
||||||
"notConnected": "Es scheint, als wären wir nicht im selben Sprachkanal.",
|
"notConnected": "Es scheint, als wären wir nicht im selben Sprachkanal.",
|
||||||
"controlsExpired": "⌛ Steuerung abgelaufen",
|
"controlsExpired": "⌛ Steuerung abgelaufen",
|
||||||
"sessionEnded": "Sitzung beendet",
|
"sessionEnded": "Sitzung beendet",
|
||||||
|
|||||||
@@ -208,6 +208,7 @@
|
|||||||
"notInVoice": "I'm not in a voice channel.",
|
"notInVoice": "I'm not in a voice channel.",
|
||||||
"queueEmpty": "📭 The queue is empty. Use `{{prefix}}play` to add songs!",
|
"queueEmpty": "📭 The queue is empty. Use `{{prefix}}play` to add songs!",
|
||||||
"queueEnded": "🎵 The queue has ended — nothing left to play. Add more songs with `{{prefix}}play`!",
|
"queueEnded": "🎵 The queue has ended — nothing left to play. Add more songs with `{{prefix}}play`!",
|
||||||
|
"queueRestored": "🔁 Bot restarted — restored **{{count}}** song(s) to the queue and reconnected to voice. Resuming where it stopped.",
|
||||||
"notConnected": "It doesn't look like we're in the same voice channel.",
|
"notConnected": "It doesn't look like we're in the same voice channel.",
|
||||||
"controlsExpired": "⌛ Controls expired",
|
"controlsExpired": "⌛ Controls expired",
|
||||||
"sessionEnded": "Session ended",
|
"sessionEnded": "Session ended",
|
||||||
|
|||||||
@@ -207,6 +207,7 @@
|
|||||||
"notInVoice": "Não estou em um canal de voz.",
|
"notInVoice": "Não estou em um canal de voz.",
|
||||||
"queueEmpty": "📭 A fila está vazia. Use `{{prefix}}play` para adicionar músicas!",
|
"queueEmpty": "📭 A fila está vazia. Use `{{prefix}}play` para adicionar músicas!",
|
||||||
"queueEnded": "🎵 A fila acabou — nada mais para tocar. Adicione mais músicas com `{{prefix}}play`!",
|
"queueEnded": "🎵 A fila acabou — nada mais para tocar. Adicione mais músicas com `{{prefix}}play`!",
|
||||||
|
"queueRestored": "🔁 Reinício concluído — **{{count}}** música(s) de volta na fila e reconectado ao canal de voz. Continuando de onde parou.",
|
||||||
"notConnected": "Parece que não estamos no mesmo canal de voz.",
|
"notConnected": "Parece que não estamos no mesmo canal de voz.",
|
||||||
"controlsExpired": "⌛ Controles expirados",
|
"controlsExpired": "⌛ Controles expirados",
|
||||||
"sessionEnded": "Sessão encerrada",
|
"sessionEnded": "Sessão encerrada",
|
||||||
|
|||||||
@@ -207,6 +207,7 @@
|
|||||||
"notInVoice": "Bir ses kanalında değilim.",
|
"notInVoice": "Bir ses kanalında değilim.",
|
||||||
"queueEmpty": "📭 Kuyruk boş. Şarkı eklemek için `{{prefix}}play` kullanın!",
|
"queueEmpty": "📭 Kuyruk boş. Şarkı eklemek için `{{prefix}}play` kullanın!",
|
||||||
"queueEnded": "🎵 Kuyruk bitti — çalacak bir şey kalmadı. Daha fazla şarkı eklemek için `{{prefix}}play` kullanın!",
|
"queueEnded": "🎵 Kuyruk bitti — çalacak bir şey kalmadı. Daha fazla şarkı eklemek için `{{prefix}}play` kullanın!",
|
||||||
|
"queueRestored": "🔁 Yeniden başlatma tamamlandı — **{{count}}** şarkı kuyruğa geri yüklendi ve ses kanalına yeniden bağlanıldı. Kaldığı yerden devam ediliyor.",
|
||||||
"notConnected": "Görünüşe göre aynı ses kanalında değiliz.",
|
"notConnected": "Görünüşe göre aynı ses kanalında değiliz.",
|
||||||
"controlsExpired": "⌛ Kontrollerin süresi doldu",
|
"controlsExpired": "⌛ Kontrollerin süresi doldu",
|
||||||
"sessionEnded": "Oturum sona erdi",
|
"sessionEnded": "Oturum sona erdi",
|
||||||
|
|||||||
Reference in new issue
Block a user