This commit is contained in:
NoLogicAlan committed 2026-05-06 17:26:37 +03:00
1 parent b50e0bac83
commit 33ff2632f9
10 files changed
+222 -166

No files matched your search

+11 -33
View File
@@ -516,22 +516,25 @@ export class PlayerManager {
*/
async leave(msg, cid) {
if (!cid) {
const serverId = msg.channel?.server_id ?? msg.channel?.serverId ??
msg.message?.server_id ?? msg.message?.serverId;
if (serverId) {
const guildId = getMessageGuildId(msg);
if (guildId) {
const matchedEntry = [...this.playerMap.entries()].find(([, player]) =>
String(player?._guildId ?? "").replace(/\D/g, "") === String(serverId).replace(/\D/g, "")
getPlayerGuildId(player) === cleanId(guildId)
);
cid = matchedEntry?.[0] ?? null;
cid = getPlayerChannelId(matchedEntry?.[1], matchedEntry?.[0]) || matchedEntry?.[0] || null;
}
}
const player = cid ? this.playerMap.get(cid) : null;
const cleanChannelId = cleanId(cid);
const player = cleanChannelId
? this.playerMap.get(cleanChannelId) ??
[...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId)
: null;
if (!player) return msg.reply(mkEmbed(this._t(msg, "responses._common.notInVoice")));
const activeChannelId = String(player._channelId ?? cid).replace(/\D/g, "") || cid;
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
this.playerMap.delete(activeChannelId);
if (activeChannelId !== cid) this.playerMap.delete(cid);
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
await player.leave();
player.destroy();
@@ -652,29 +655,4 @@ export class PlayerManager {
})();
}
async leave(msg, cid) {
if (!cid) {
const guildId = getMessageGuildId(msg);
if (guildId) {
const matchedEntry = [...this.playerMap.entries()].find(([, player]) =>
getPlayerGuildId(player) === cleanId(guildId)
);
cid = getPlayerChannelId(matchedEntry?.[1], matchedEntry?.[0]) || matchedEntry?.[0] || null;
}
}
const cleanChannelId = cleanId(cid);
const player = cleanChannelId
? this.playerMap.get(cleanChannelId) ??
[...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId)
: null;
if (!player) return msg.reply(mkEmbed(this._t(msg, "responses._common.notInVoice")));
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
this.playerMap.delete(activeChannelId);
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
await player.leave();
player.destroy();
}
}
+204 -58
View File
@@ -2,30 +2,58 @@ import { Remix } from "../../index.mjs";
import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
import Player from "../Player.mjs";
import { Utils } from "../Utils.mjs";
import { DatabaseManager } from "./DatabaseManager.mjs";
import { RedisHandler } from "./RedisHandler.mjs";
/**
* Fluxer OAuth2 configuration (standard OAuth2 authorization code flow).
* @typedef {Object} FluxerOAuth2Config
* @property {string} id OAuth2 client ID
* @property {string} secret OAuth2 client secret
* @property {string} redirectUri Redirect URI registered on the Fluxer app
* @property {string} [apiBase] Fluxer API base URL (default: https://api.fluxer.app)
*/
/** Default Fluxer API endpoints derived from the Fluxer platform docs */
const FLUXER_API_DEFAULTS = {
apiBase: "https://api.fluxer.app/v1",
tokenEndpoint: "https://api.fluxer.app/v1/oauth2/token",
authorizeEndpoint: "https://fluxer.app/oauth2/authorize",
userinfoEndpoint: "https://api.fluxer.app/v1/users/@me",
};
export class Dashboard {
enabled = false;
expiryTime = 1000 * 60 * 60 * 6;
/**
* @param {Remix} remix
* @param {Object} opts
* @param {boolean} opts.enabled Whether the Dashboard is enabled and connections should be attempted
* @param {Object} opts.redis Connection options passed directly to redis createClient
* @param {Object} opts.mysql mysql2 pool options
* @param {FluxerOAuth2Config} [opts.fluxer] Fluxer OAuth2 credentials
*/
constructor(remix, opts) {
this.enabled = opts?.enabled;
this.remix = remix;
if (!this.enabled) return this;
// Fluxer OAuth2 config
const fluxer = opts?.fluxer ?? {};
this.fluxer = {
clientId: fluxer.id,
clientSecret: fluxer.secret,
redirectUri: fluxer.redirectUri,
apiBase: fluxer.apiBase ?? FLUXER_API_DEFAULTS.apiBase,
tokenEndpoint: fluxer.tokenEndpoint ?? FLUXER_API_DEFAULTS.tokenEndpoint,
authorizeEndpoint: fluxer.authorizeEndpoint ?? FLUXER_API_DEFAULTS.authorizeEndpoint,
userinfoEndpoint: fluxer.userinfoEndpoint ?? FLUXER_API_DEFAULTS.userinfoEndpoint,
};
this.db = new DatabaseManager(opts.mysql);
if (!this.enabled) return this;
this.redis = new RedisHandler(opts.redis);
this.redis.setRequestHandler(async (data) => {
switch (data.type) {
// ── Existing request types ─────────────────────────────────────────────
case "fetchPlayers":
return [...this.remix.players.playerMap.values()].map(p => Dashboard.convertPlayer(p));
@@ -36,7 +64,9 @@ export class Dashboard {
}
case "sharedServers":
return await this.remix.getSharedServers(await this.remix.client.users.fetch(data.key).catch(() => null));
return await this.remix.getSharedServers(
await this.remix.client.users.fetch(data.key).catch(() => null)
);
case "server": {
try {
@@ -53,20 +83,161 @@ export class Dashboard {
return server;
} catch (e) {
const id = Utils.uid();
console.log(e, id);
console.log("[Dashboard] Server error:", id, e);
return { error: "An error occurred. Id: " + id };
}
}
case "commands":
return this.remix.handler.commands.map(c => Dashboard.convertCommand(c, this.remix.handler));
return this.remix.handler.commands.map(c =>
Dashboard.convertCommand(c, this.remix.handler)
);
case "function":
return await this.runFunction(data.params);
// ── Fluxer OAuth2 request types ─────────────────────────────────────────
case "fluxerAuthorizeUrl": {
// Returns the full OAuth2 authorize URL for the dashboard frontend to redirect to
const scopes = (data.scopes ?? ["identify"]).join(" ");
const state = data.state ?? Utils.uid();
const url = new URL(this.fluxer.authorizeEndpoint);
url.searchParams.set("client_id", this.fluxer.clientId);
url.searchParams.set("redirect_uri", this.fluxer.redirectUri);
url.searchParams.set("response_type", "code");
url.searchParams.set("scope", scopes);
url.searchParams.set("state", state);
return { url: url.toString(), state };
}
case "fluxerVerify": {
// Backend sends a Fluxer access token — bot verifies it and returns user info.
// The bot calls the Fluxer API's /users/@me with the access token to
// confirm the user's identity, then cross-references with the bot's
// internal user cache to confirm the user is known.
const accessToken = data.accessToken;
if (!accessToken) return { error: "Missing access token" };
return await this.verifyFluxerToken(accessToken);
}
case "fluxerToken": {
// Backend sends an authorization code — bot exchanges it for tokens.
// This is useful if the bot wants to perform the code→token exchange
// itself rather than relying on the backend to do it.
const code = data.code;
if (!code) return { error: "Missing authorization code" };
return await this.exchangeFluxerCode(code);
}
}
});
}
// ═══════════════════════════════════════════════════════════════════════════
// Fluxer OAuth2 Methods
// ═══════════════════════════════════════════════════════════════════════════
/**
* Verify a Fluxer OAuth2 access token by calling the Fluxer /users/@me endpoint.
* Returns the user object from the Fluxer API, plus a `knownToBot` flag
* indicating whether this user is cached in the bot's client.
*
* @param {string} accessToken
* @returns {Promise<Object>} User data or error
*/
async verifyFluxerToken(accessToken) {
try {
const res = await fetch(this.fluxer.userinfoEndpoint, {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (!res.ok) {
const body = await res.text().catch(() => "");
console.log("[Dashboard] Fluxer token verification failed:", res.status, body);
return { error: "Invalid or expired access token", status: res.status };
}
const fluxerUser = await res.json();
if (!fluxerUser?.id) {
return { error: "Fluxer API returned no user ID" };
}
// Cross-reference with the bot's cached users to check if this user
// shares any servers with the bot (i.e. is a potential dashboard user).
let botUser = null;
try {
botUser = await this.remix.client.users.fetch(fluxerUser.id).catch(() => null);
} catch (_) {}
return {
id: fluxerUser.id,
username: fluxerUser.username,
displayName: fluxerUser.displayName ?? fluxerUser.globalName ?? fluxerUser.username,
avatar: {
url: fluxerUser.avatar
? `https://cdn.fluxer.app/avatars/${fluxerUser.id}/${fluxerUser.avatar}.webp`
: null,
},
knownToBot: !!botUser,
botUser: botUser ? Dashboard.convertUser(botUser) : null,
};
} catch (e) {
console.log("[Dashboard] Fluxer verify error:", e.message);
return { error: "Failed to verify with Fluxer API: " + e.message };
}
}
/**
* Exchange an OAuth2 authorization code for access/refresh tokens.
* This calls the Fluxer token endpoint directly.
*
* @param {string} code Authorization code from the OAuth2 redirect
* @returns {Promise<Object>} Token data or error
*/
async exchangeFluxerCode(code) {
try {
const body = new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: this.fluxer.redirectUri,
client_id: this.fluxer.clientId,
client_secret: this.fluxer.clientSecret,
});
const res = await fetch(this.fluxer.tokenEndpoint, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body,
});
if (!res.ok) {
const errorBody = await res.text().catch(() => "");
console.log("[Dashboard] Fluxer token exchange failed:", res.status, errorBody);
return { error: "Token exchange failed", status: res.status };
}
const tokens = await res.json();
if (!tokens.access_token) {
return { error: "No access_token in response" };
}
return {
accessToken: tokens.access_token,
tokenType: tokens.token_type ?? "Bearer",
expiresIn: tokens.expires_in ?? null,
refreshToken: tokens.refresh_token ?? null,
scope: tokens.scope ?? null,
};
} catch (e) {
console.log("[Dashboard] Fluxer token exchange error:", e.message);
return { error: "Failed to exchange code: " + e.message };
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Dashboard Function Dispatch
// ═══════════════════════════════════════════════════════════════════════════
/**
* @param {Object} params
* @param {string} params.func
@@ -74,7 +245,7 @@ export class Dashboard {
* @returns {Promise<any>}
*/
async runFunction(params) {
var user;
let user;
if (!!params.data.user) {
try {
user = await this.remix.client.users.fetch(params.data.user);
@@ -85,7 +256,7 @@ export class Dashboard {
}
switch (params.func) {
case "join": {
var voiceChannel, textChannel;
let voiceChannel, textChannel;
try {
voiceChannel = await this.remix.client.channels.fetch(params.data.channel);
textChannel = await this.remix.client.channels.fetch(params.data.text);
@@ -101,39 +272,39 @@ export class Dashboard {
}
case "pausePlayback": {
var player = this._getPlayerById(params.data.player);
let player = this._getPlayerById(params.data.player);
if (!player) return { error: "Player not found" };
var msg = player.pause() || "Paused successfully";
let msg = player.pause() || "Paused successfully";
return { message: msg };
}
case "resumePlayback": {
var player = this._getPlayerById(params.data.player);
let player = this._getPlayerById(params.data.player);
if (!player) return { error: "Player not found" };
var msg = player.resume() || "Resumed successfully";
let msg = player.resume() || "Resumed successfully";
return { message: msg };
}
case "skip": {
var player = this._getPlayerById(params.data.player);
let player = this._getPlayerById(params.data.player);
if (!player) return { error: "Player not found" };
var msg = player.skip() || "Skipped song";
let msg = player.skip() || "Skipped song";
return { message: msg };
}
case "volume": {
var player = this._getPlayerById(params.data.player);
let player = this._getPlayerById(params.data.player);
if (!player) return { error: "Player not found" };
var msg = player.setVolume(params.data.volume);
let msg = player.setVolume(params.data.volume);
return { message: msg };
}
case "addToQueue": {
var player = this._getPlayerById(params.data.player);
let player = this._getPlayerById(params.data.player);
if (!player) return { error: "Player not found" };
if (!user) return { error: "Invalid user" };
var type = params.data.type;
var query = params.data.query;
const type = params.data.type;
const query = params.data.query;
if (type === "radio") {
const radio = this.remix.config.radio.find(e => e.name === query);
if (!radio) return { error: "Invalid radio station" };
@@ -157,7 +328,9 @@ export class Dashboard {
*/
_getPlayerById(id) {
return this.remix.players.playerMap.get(id)
?? [...this.remix.players.playerMap.values()].find(p => p._channelId === id || p._guildId === id)
?? [...this.remix.players.playerMap.values()].find(
p => p._channelId === id || p._guildId === id
)
?? null;
}
@@ -181,7 +354,7 @@ export class Dashboard {
username: user.username,
displayName: user.displayName ?? user.globalName ?? user.username,
avatar: {
url: user.displayAvatarURL() ?? user.defaultAvatarURL
url: user.displayAvatarURL() ?? user.defaultAvatarURL,
},
};
}
@@ -204,9 +377,9 @@ export class Dashboard {
description: vid.description,
artist: {
name: vid.author?.name ?? vid.artist,
url: vid.author?.url
url: vid.author?.url,
},
thumbnail: vid.thumbnail
thumbnail: vid.thumbnail,
};
}
@@ -242,7 +415,7 @@ export class Dashboard {
isVoice,
voiceParticipants,
mature: channel.nsfw ?? false,
serverId: channel.guildId
serverId: channel.guildId,
};
}
@@ -283,7 +456,7 @@ export class Dashboard {
volume: (player.preferredVolume ?? 1) * 100,
queue: {
current: Dashboard.convertVideo(player.queue.current),
data: (player.queue.data ?? []).map(v => Dashboard.convertVideo(v))
data: (player.queue.data ?? []).map(v => Dashboard.convertVideo(v)),
},
users: (() => {
if (!channel) return [];
@@ -319,7 +492,7 @@ export class Dashboard {
required: opt.required,
uid: opt.uid,
defaultValue: opt.defaultValue,
dynamicDefaultPresent: !!opt.dynamicDefault
dynamicDefaultPresent: !!opt.dynamicDefault,
};
}
@@ -337,7 +510,7 @@ export class Dashboard {
category: com.category,
examples: com.examples,
usage: commands.helpHandler?.commandUsage?.(com, {
message: { guildId: null }
message: { guildId: null },
}) ?? null,
options: com.options.map(o => Dashboard.convertOption(o)),
};
@@ -355,7 +528,7 @@ export class Dashboard {
const serialised = Dashboard.convertPlayer(player);
this.redis.send(this.redis.platform + ":players", JSON.stringify({
...details,
player: serialised
player: serialised,
}));
}
@@ -380,7 +553,7 @@ export class Dashboard {
const channel = this.redis.platform + ":users";
this.redis.send(channel, JSON.stringify({
...details,
user: Dashboard.convertUser(user)
user: Dashboard.convertUser(user),
}));
}
@@ -389,31 +562,4 @@ export class Dashboard {
const channel = this.redis.platform + ":user_" + user.id;
this.redis.send(channel, JSON.stringify(details));
}
/**
* Verify a dashboard login code for a user
* @param {string} user User ID
* @param {string} code Plaintext code to check
* @returns {Promise<string|null>} null on success, error string on failure
*/
async confirmLogin(user, code) {
if (!this.enabled) return "Dashboard not enabled.";
var res;
try {
res = await this.db.execute("SELECT * FROM login_codes WHERE user=?", [user]);
} catch (e) {
const id = Utils.uid();
console.log("[Dashboard] MySQL error, id: ", id, e);
return "An error occurred, please contact an administrator. Error id: `" + id + "`";
}
if (res.length === 0) return "If this is a valid code, it was not created for your account.";
for (let i = 0; i < res.length; i++) {
if ((await this.db.compareHash(code, res[i].token))) {
if (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) return "Login token expired";
await this.db.execute("UPDATE login_codes SET verified=true WHERE id=?", [res[i].id]);
return null;
}
}
return "Invalid code.";
}
}