This commit is contained in:
NoLogicAlan committed 2026-05-16 23:20:05 +03:00
1 parent e966b6ce20
commit db0ca569ee
9 files changed
+426 -42

No files matched your search

+7 -2
View File
@@ -217,8 +217,13 @@ export class Flag extends Option {
export class PrefixManager {
/** @type {SettingsManager} */
settings;
constructor(settings) { this.settings = settings; }
getPrefix(guildId) { return this.settings.getServer(guildId).get("prefix"); }
/** @type {string|null} Prefix from config.json — used as fallback when DB has no value */
configPrefix;
constructor(settings, configPrefix = null) { this.settings = settings; this.configPrefix = configPrefix; }
getPrefix(guildId) {
const serverPrefix = this.settings.getServer(guildId).get("prefix");
return serverPrefix ?? this.configPrefix ?? "%";
}
}
export class HelpHandler {
+2 -4
View File
@@ -5,7 +5,7 @@ import { ServerSettings } from "./Settings.mjs";
import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs";
import { VoiceStateCache } from "./constants/VoiceStateCache.mjs";
import { REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS } from "./MessageHandler.mjs";
import mysql from "mysql2";
/**
* GatewayHandler — manages raw WebSocket gateway events, voice-state tracking,
@@ -732,9 +732,7 @@ export class GatewayHandler {
try {
const cleanGuildId = String(guildId).replace(/\D/g, "");
if (!cleanGuildId) throw new Error("Invalid guildId: " + guildId);
const res = await remix.settingsMgr.query(
`SELECT * FROM settings WHERE id=${mysql.escape(cleanGuildId)}`
);
const res = await remix.settingsMgr.selectGuild(cleanGuildId);
if (res?.results?.length) {
const row = res.results[0];
const server = new ServerSettings(guildId, remix.settingsMgr);
+96 -20
View File
@@ -95,6 +95,11 @@ export class LastFmManager {
this._mysqlConfig = mysqlConfig;
this._pool = null;
/** @type {string|null} Bot user ID — used to isolate rows per-bot in shared databases */
this.botId = null;
/** @type {boolean} Whether the bot_id column exists in the lastfm tables */
this._hasBotIdColumn = false;
// In-memory user cache: Map<userId, { sessionKey, username, scrobbleEnabled }>
this._userCache = new Map();
@@ -108,6 +113,64 @@ export class LastFmManager {
}
}
// ── Bot ID isolation ─────────────────────────────────────────────────────
/**
* Set the bot ID for multi-bot database isolation.
* Ensures bot_id column exists in lastfm tables, then clears caches.
* @param {string} id - The bot's Discord user ID
*/
async setBotId(id) {
const changed = this.botId !== id;
this.botId = id;
if (changed) {
await this._ensureBotIdColumn();
this._userCache.clear();
}
}
/**
* Auto-migrate: add bot_id column to lastfm_users and lastfm_stats if missing.
*/
async _ensureBotIdColumn() {
if (this._hasBotIdColumn) return;
const pool = await this._getPool();
// Check lastfm_users
const [cols] = await pool.execute(
`SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_users' AND COLUMN_NAME = 'bot_id'`
);
if (cols.length === 0) {
logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_users...");
await pool.execute("ALTER TABLE `lastfm_users` ADD COLUMN `bot_id` VARCHAR(32) DEFAULT NULL");
await pool.execute("ALTER TABLE `lastfm_users` DROP PRIMARY KEY, ADD PRIMARY KEY (user_id, bot_id)");
logger.settings("[LastFm] Auto-migration complete: lastfm_users.bot_id added.");
}
// Check lastfm_stats
const [statsCols] = await pool.execute(
`SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_stats' AND COLUMN_NAME = 'bot_id'`
);
if (statsCols.length === 0) {
logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_stats...");
await pool.execute("ALTER TABLE `lastfm_stats` ADD COLUMN `bot_id` VARCHAR(32) DEFAULT NULL");
await pool.execute("ALTER TABLE `lastfm_stats` DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)");
logger.settings("[LastFm] Auto-migration complete: lastfm_stats.bot_id added.");
}
this._hasBotIdColumn = true;
}
/**
* Returns SQL WHERE fragment for bot_id filtering.
* Uses prepared statement placeholder (?) for safety.
* @returns {{ where: string, params: string[] }}
*/
_botIdFilter() {
if (!this.botId || !this._hasBotIdColumn) return { where: "", params: [] };
return { where: " AND bot_id = ?", params: [String(this.botId)] };
}
// ── MySQL ──────────────────────────────────────────────────────────────────
async _getPool() {
@@ -166,9 +229,10 @@ export class LastFmManager {
if (cached) return cached;
const pool = await this._getPool();
const f = this._botIdFilter();
const [rows] = await pool.execute(
"SELECT session_key, username, scrobble FROM lastfm_users WHERE user_id = ?",
[String(userId)]
`SELECT session_key, username, scrobble FROM lastfm_users WHERE user_id = ?${f.where}`,
[String(userId), ...f.params]
);
if (!rows.length) return null;
@@ -185,11 +249,12 @@ export class LastFmManager {
async saveUser(userId, sessionKey, username) {
const pool = await this._getPool();
const f = this._botIdFilter();
await pool.execute(
`INSERT INTO lastfm_users (user_id, session_key, username, scrobble)
VALUES (?, ?, ?, 1)
`INSERT INTO lastfm_users (user_id, session_key, username, scrobble${f.where ? ', bot_id' : ''})
VALUES (?, ?, ?, 1${f.where ? ', ?' : ''})
ON DUPLICATE KEY UPDATE session_key = VALUES(session_key), username = VALUES(username)`,
[String(userId), sessionKey, username ?? ""]
[String(userId), sessionKey, username ?? "", ...f.params]
);
const data = { sessionKey, username: username ?? "", scrobbleEnabled: true };
this._userCache.set(userId, data);
@@ -197,8 +262,8 @@ export class LastFmManager {
// 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)]
`UPDATE lastfm_stats SET linked_users = linked_users + 1 WHERE id = 1${f.where} AND NOT EXISTS (SELECT 1 FROM (SELECT 1 FROM lastfm_users WHERE user_id = ?${f.where} AND linked_at < NOW()) AS tmp)`,
[...f.params, String(userId), ...f.params]
);
} catch {
// Non-critical — don't fail the save
@@ -209,15 +274,17 @@ export class LastFmManager {
async removeUser(userId) {
const pool = await this._getPool();
await pool.execute("DELETE FROM lastfm_users WHERE user_id = ?", [String(userId)]);
const f = this._botIdFilter();
await pool.execute(`DELETE FROM lastfm_users WHERE user_id = ?${f.where}`, [String(userId), ...f.params]);
this._userCache.delete(userId);
}
async setScrobble(userId, enabled) {
const pool = await this._getPool();
const f = this._botIdFilter();
await pool.execute(
"UPDATE lastfm_users SET scrobble = ? WHERE user_id = ?",
[enabled ? 1 : 0, String(userId)]
`UPDATE lastfm_users SET scrobble = ? WHERE user_id = ?${f.where}`,
[enabled ? 1 : 0, String(userId), ...f.params]
);
const cached = this._userCache.get(userId);
if (cached) cached.scrobbleEnabled = enabled;
@@ -818,8 +885,10 @@ export class LastFmManager {
const pool = await this._getPool();
// Get all linked user IDs
const f = this._botIdFilter();
const [rows] = await pool.execute(
"SELECT user_id FROM lastfm_users"
`SELECT user_id FROM lastfm_users WHERE 1=1${f.where}`,
[...f.params]
);
if (!rows.length) {
@@ -839,7 +908,8 @@ export class LastFmManager {
// 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"
`SELECT COALESCE(SUM(scrobble_count), 0) AS total FROM lastfm_users WHERE 1=1${f.where}`,
[...f.params]
);
const total = Number(sumRows[0]?.total ?? 0);
@@ -863,8 +933,10 @@ export class LastFmManager {
if (!this.enabled) return 0;
try {
const pool = await this._getPool();
const f = this._botIdFilter();
const [rows] = await pool.execute(
"SELECT linked_users FROM lastfm_stats WHERE id = 1"
`SELECT linked_users FROM lastfm_stats WHERE id = 1${f.where}`,
[...f.params]
);
return Number(rows[0]?.linked_users ?? 0);
} catch {
@@ -882,10 +954,12 @@ export class LastFmManager {
if (!this.enabled) return { entries: [], totalUsers: 0, page: 0, perPage: 10, totalPages: 0 };
const pool = await this._getPool();
const f = this._botIdFilter();
// Get total count
const [countRows] = await pool.execute(
"SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0"
`SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0${f.where}`,
[...f.params]
);
const totalUsers = Number(countRows[0]?.total ?? 0);
const totalPages = Math.max(1, Math.ceil(totalUsers / perPage));
@@ -895,8 +969,8 @@ export class LastFmManager {
const offset = page * perPage;
const [rows] = await pool.execute(
"SELECT user_id, username, scrobble_count FROM lastfm_users WHERE scrobble_count > 0 ORDER BY scrobble_count DESC LIMIT ? OFFSET ?",
[String(perPage), String(offset)]
`SELECT user_id, username, scrobble_count FROM lastfm_users WHERE scrobble_count > 0${f.where} ORDER BY scrobble_count DESC LIMIT ? OFFSET ?`,
[...f.params, String(perPage), String(offset)]
);
const entries = rows.map(r => ({
@@ -921,9 +995,10 @@ export class LastFmManager {
const info = await this.getUserInfo(userId);
const playcount = Number(info.playcount ?? 0);
const pool = await this._getPool();
const f = this._botIdFilter();
await pool.execute(
"UPDATE lastfm_users SET scrobble_count = ? WHERE user_id = ?",
[String(playcount), String(userId)]
`UPDATE lastfm_users SET scrobble_count = ? WHERE user_id = ?${f.where}`,
[String(playcount), String(userId), ...f.params]
);
return playcount;
} catch {
@@ -943,10 +1018,11 @@ export class LastFmManager {
*/
_incrementScrobbleCount(userId) {
if (!userId) return;
const f = this._botIdFilter();
this._getPool().then(pool => {
pool.execute(
"UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?",
[String(userId)]
`UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?${f.where}`,
[String(userId), ...f.params]
).catch(() => {});
}).catch(() => {});
}
+118 -6
View File
@@ -37,17 +37,24 @@ export class RemoteSettingsManager extends EventEmitter {
descriptions = {};
defaults = {};
db = null;
/** @type {string|null} Bot user ID — used to isolate rows per-bot in shared databases */
botId = null;
/** @type {boolean} Whether the bot_id column exists in the settings table */
_hasBotIdColumn = false;
// track retry count and apply exponential backoff on load failures
_loadAttempts = 0;
/** @type {Promise|null} Tracks the in-flight load() so setBotId() can wait for it */
_loadPromise = null;
// Per-server debounce timers: serverId → NodeJS.Timeout
// Batches rapid set() calls (e.g. 24/7 mode changes that write stay_247 + stay_247_mode)
// into a single remoteSave() 80ms after the last write, rather than firing one UPDATE
// per key.
_debounceTimers = new Map();
constructor(config, defaultsPath) {
constructor(config, defaultsPath, botId = null) {
super();
this.botId = botId;
this.db = mysql.createPool({ connectionLimit: 15, ...config });
// Without this listener, any pool-level error (connection drop, timeout, protocol error)
// fires an unhandled 'error' event which crashes the entire process with no log output.
@@ -55,7 +62,111 @@ export class RemoteSettingsManager extends EventEmitter {
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
});
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err));
this._loadPromise = this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err));
}
/**
* Check whether the `bot_id` column exists in the settings table.
* If it doesn't, auto-migrate by adding the column and updating the primary key.
* This ensures old databases work seamlessly with the new multi-bot code.
*/
async _ensureBotIdColumn() {
if (this._hasBotIdColumn) return; // already checked, column exists
const res = await this.query(
`SELECT COLUMN_NAME FROM information_schema.COLUMNS `
+ `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'`
);
if (res.error) {
logger.error("[Settings] Failed to check bot_id column:", res.error);
return;
}
if (res.results.length > 0) {
// Column already exists
this._hasBotIdColumn = true;
return;
}
// Auto-migrate: add bot_id column and update primary key
logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table...");
const alterRes = await this.query(
`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) DEFAULT NULL`
);
if (alterRes.error) {
logger.error("[Settings] Failed to add bot_id column:", alterRes.error);
return;
}
// Update primary key from (id) to (id, bot_id)
const pkRes = await this.query(
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
);
if (pkRes.error) {
logger.error("[Settings] Failed to update primary key:", pkRes.error);
// Column was added but PK update failed — still mark as available
// since the column exists and queries will work
}
this._hasBotIdColumn = true;
logger.settings("[Settings] Auto-migration complete: bot_id column added.");
}
/**
* Set or update the bot ID used for database row isolation.
* Called after login when the bot user ID becomes available.
* Ensures the bot_id column exists (auto-migrates if needed), then
* reloads guild data filtered by the bot's ID.
* @param {string} id
*/
async setBotId(id) {
const changed = this.botId !== id;
this.botId = id;
if (changed) {
// Wait for the initial load to finish before clearing and reloading
if (this._loadPromise) await this._loadPromise;
// Ensure the DB schema supports bot_id before querying with it
await this._ensureBotIdColumn();
// Reload with the new botId so we pick up this bot's rows
this.guilds.clear();
this._loadPromise = this.load();
await this._loadPromise;
}
}
/**
* Returns the SQL WHERE clause fragment for bot_id filtering.
* When botId is set AND the bot_id column exists in the table,
* includes "AND bot_id = <escaped>" in queries.
* Otherwise no filter is applied (backward-compatible with old schemas).
* @returns {string}
*/
_botIdWhere() {
if (!this.botId || !this._hasBotIdColumn) return "";
return ` AND bot_id = ${mysql.escape(String(this.botId))}`;
}
/**
* Returns the bot_id column + value for INSERT statements.
* Only includes bot_id when both the botId is set AND the column exists.
* @returns {{ col: string, val: string }}
*/
_botIdInsert() {
if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" };
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` };
}
/**
* Fetch a single guild's settings row from the database, filtered by bot_id.
* Used by GatewayHandler when a guild is (re-)joined and not in the cache.
* @param {string} guildId
* @returns {Promise<{error: object|null, results: Array, fields: Array}>}
*/
selectGuild(guildId) {
const escapedId = mysql.escape(String(guildId));
return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`);
}
query(q) {
@@ -65,7 +176,7 @@ export class RemoteSettingsManager extends EventEmitter {
}
async load() {
const res = await this.query("SELECT * FROM settings");
const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`);
if (res.error) {
this._loadAttempts++;
// exponential backoff with a cap of 30s instead of forever-at-2s
@@ -105,14 +216,14 @@ export class RemoteSettingsManager extends EventEmitter {
? mysql.escape(val)
: mysql.escape(String(val));
const escapedId = mysql.escape(server.id);
const r = await this.query(`UPDATE settings SET data = JSON_SET(data, ${escapedPath}, ${escapedVal}) WHERE id=${escapedId}`);
const r = await this.query(`UPDATE settings SET data = JSON_SET(data, ${escapedPath}, ${escapedVal}) WHERE id=${escapedId}${this._botIdWhere()}`);
if (r.error) logger.error("[Settings] remoteUpdate error:", r.error);
}
async remoteSave(server) {
const escapedData = mysql.escape(JSON.stringify(server.data));
const escapedId = mysql.escape(server.id);
const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}`);
const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}${this._botIdWhere()}`);
if (r.error) logger.error("[Settings] remoteSave error:", r.error);
}
@@ -136,7 +247,8 @@ export class RemoteSettingsManager extends EventEmitter {
async create(id, server) {
const escapedId = mysql.escape(id);
const escapedData = mysql.escape(JSON.stringify(server.data));
const r = await this.query(`INSERT INTO settings (id, data) VALUES (${escapedId}, ${escapedData})`);
const bi = this._botIdInsert();
const r = await this.query(`INSERT INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})`);
if (r.error) logger.error("[Settings] create error:", r.error);
}
+14
View File
@@ -92,6 +92,20 @@ export class Dashboard {
}
// ═══════════════════════════════════════════════════════════════════════════
// ── Bot ID isolation ──────────────────────────────────────────────────────
/**
* Set the bot ID for multi-bot Redis namespace isolation.
* Updates the Redis platform string so each bot uses its own channel namespace.
* @param {string} botId - The bot's Discord user ID
*/
setBotId(botId) {
if (!this.enabled || !this.redis) return;
// Use "fluxer_<botId>" as the platform so each bot's Redis messages
// are isolated. The dashboard backend must also be configured to match.
this.redis.platform = `fluxer_${botId}`;
}
// Dashboard Function Dispatch
// ═══════════════════════════════════════════════════════════════════════════