mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
rollback
This commit is contained in:
1 parent
2f51b7e1d7
commit
97fe282bb3
29 files changed
+84
-414
No files matched your search
@@ -8,4 +8,3 @@ download/
|
|||||||
config.json
|
config.json
|
||||||
docker/config.json
|
docker/config.json
|
||||||
docker/.env
|
docker/.env
|
||||||
scripts/
|
|
||||||
@@ -4,35 +4,8 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches: [ "main" ]
|
branches: [ "main" ]
|
||||||
|
|
||||||
# Two quick pushes must not race each other's rollout.
|
|
||||||
concurrency:
|
|
||||||
group: deploy-main
|
|
||||||
cancel-in-progress: false
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# Nothing is built or deployed unless the project still parses, links and has complete translations.
|
|
||||||
check:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up Node.js
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: "22"
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm install
|
|
||||||
|
|
||||||
- name: Syntax, module-link, JSON and translation check
|
|
||||||
run: npm run check
|
|
||||||
|
|
||||||
build-and-push:
|
build-and-push:
|
||||||
needs: check
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
@@ -57,7 +30,6 @@ jobs:
|
|||||||
tags: |
|
tags: |
|
||||||
type=raw,value=latest
|
type=raw,value=latest
|
||||||
type=ref,event=branch
|
type=ref,event=branch
|
||||||
type=sha,format=long
|
|
||||||
|
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v5
|
||||||
@@ -67,8 +39,6 @@ jobs:
|
|||||||
push: true
|
push: true
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
build-args: |
|
|
||||||
GIT_SHA=${{ github.sha }}
|
|
||||||
|
|
||||||
- name: Set up kubectl
|
- name: Set up kubectl
|
||||||
uses: azure/setup-kubectl@v4
|
uses: azure/setup-kubectl@v4
|
||||||
@@ -76,16 +46,13 @@ jobs:
|
|||||||
version: "latest"
|
version: "latest"
|
||||||
|
|
||||||
- name: Configure kubeconfig
|
- name: Configure kubeconfig
|
||||||
env:
|
|
||||||
KUBE_CONFIG: ${{ secrets.KUBE_CONFIG }}
|
|
||||||
run: |
|
run: |
|
||||||
if [ -z "$KUBE_CONFIG" ]; then
|
if [ -z "${{ secrets.KUBE_CONFIG }}" ]; then
|
||||||
echo "::error::KUBE_CONFIG secret is not set. Add it under Settings > Secrets and variables > Actions."
|
echo "::error::KUBE_CONFIG secret is not set. Add it under Settings > Secrets and variables > Actions."
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
mkdir -p "$HOME/.kube"
|
mkdir -p "$HOME/.kube"
|
||||||
echo "$KUBE_CONFIG" | base64 --decode > "$HOME/.kube/config"
|
echo "${{ secrets.KUBE_CONFIG }}" | base64 --decode > "$HOME/.kube/config"
|
||||||
chmod 600 "$HOME/.kube/config"
|
|
||||||
|
|
||||||
- name: Verify cluster connectivity
|
- name: Verify cluster connectivity
|
||||||
run: kubectl get deployment fluxer -n fh-nologicalan-remix
|
run: kubectl get deployment fluxer -n fh-nologicalan-remix
|
||||||
|
|||||||
@@ -216,9 +216,9 @@ The fastest way to self-host Remix is with Docker. Everything — the bot, MySQL
|
|||||||
cp .env.example .env # optional — compose has working defaults
|
cp .env.example .env # optional — compose has working defaults
|
||||||
```
|
```
|
||||||
|
|
||||||
2. **Edit `config.json`** — fill in your bot token, MySQL credentials (defaults match the compose MySQL service), NodeLink details (defaults match the compose NodeLink service), and your owner IDs. Spotify/Deezer/Apple Music credentials are configured on the **NodeLink side** (`NODELINK_*` environment variables on the `nodelink` service in `docker/docker-compose.yml`; see NodeLink's docs), not in the bot config.
|
2. **Edit `config.json`** — fill in your bot token, MySQL credentials (defaults match the compose MySQL service), NodeLink details (defaults match the compose NodeLink service), and your owner IDs. Spotify/Deezer/Apple Music credentials are configured on the **NodeLink side** (`nodelink.config.json`), not in the bot config.
|
||||||
|
|
||||||
3. **Edit `.env`** (optional) — MySQL passwords, the NodeLink password (`NODELINK_PASSWORD`, required; use the same value in `config.json`), and timezone.
|
3. **Edit `.env`** (optional) — MySQL passwords, host port mappings (`WEB_PORT`, `NODELINK_PORT`), and timezone.
|
||||||
|
|
||||||
4. **Start everything:**
|
4. **Start everything:**
|
||||||
```bash
|
```bash
|
||||||
@@ -243,17 +243,17 @@ docker/
|
|||||||
├── config_example.json # Docker-friendly config template
|
├── config_example.json # Docker-friendly config template
|
||||||
├── config.json # You create this (gitignored)
|
├── config.json # You create this (gitignored)
|
||||||
├── .env # You create this (gitignored)
|
├── .env # You create this (gitignored)
|
||||||
└── healthcheck.mjs # container healthcheck (reads the bot's heartbeat file)
|
└── nodelink.config.json # NodeLink audio node config
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Docker services
|
#### Docker services
|
||||||
|
|
||||||
| Service | Container | Port | Purpose |
|
| Service | Container | Port | Purpose |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| `bot` | remix-bot | none (the bot runs no HTTP server) | The Remix bot (+ optional dashboard backend) |
|
| `bot` | remix-bot | `${WEB_PORT:-8080}` → 80 | The Remix bot (+ optional dashboard backend) |
|
||||||
| `mysql` | remix-mysql | — | Settings, Last.fm users, and track options storage |
|
| `mysql` | remix-mysql | — | Settings, Last.fm users, and track options storage |
|
||||||
| `redis` | remix-redis | — | Dashboard RPC pub/sub (optional) |
|
| `redis` | remix-redis | — | Dashboard RPC pub/sub (optional) |
|
||||||
| `nodelink` | remix-nodelink | internal only (3000), built from the official NodeLink repo | Lavalink-compatible audio node |
|
| `nodelink` | remix-nodelink | `${NODELINK_PORT:-3000}` | Lavalink-compatible audio node |
|
||||||
|
|
||||||
#### Useful Docker commands
|
#### Useful Docker commands
|
||||||
|
|
||||||
@@ -285,7 +285,7 @@ docker compose up -d --build bot
|
|||||||
If you prefer to keep your config in an environment variable (useful for CI/CD or secret managers), set `CONFIG_JSON` in your `.env`:
|
If you prefer to keep your config in an environment variable (useful for CI/CD or secret managers), set `CONFIG_JSON` in your `.env`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
CONFIG_JSON={"token":"YOUR_TOKEN","mysql":{"host":"mysql","port":3306,"user":"remix","password":"remix_pw","database":"remix"},"nodelink":{"host":"nodelink","port":3000,"password":"change-me-nodelink"}}
|
CONFIG_JSON={"token":"YOUR_TOKEN","mysql":{"host":"mysql","port":3306,"user":"remix","password":"remix_pw","database":"remix"},"nodelink":{"host":"nodelink","port":3000,"password":"youshallnotpass"}}
|
||||||
```
|
```
|
||||||
|
|
||||||
The entrypoint will write it to `/app/config.json` on first boot if no config file is mounted.
|
The entrypoint will write it to `/app/config.json` on first boot if no config file is mounted.
|
||||||
|
|||||||
+3
-20
@@ -1,11 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* @module commands/eval
|
* @module commands/eval
|
||||||
* @description Owner-only command to evaluate arbitrary JavaScript code and display the result.
|
* @description Owner-only command to evaluate arbitrary JavaScript code and display the result.
|
||||||
*
|
|
||||||
* SECURITY: this is NOT a sandbox. The code runs with the full privileges of the bot process
|
|
||||||
* (filesystem, network, database, `await import("node:child_process")`...). Treat every ID in
|
|
||||||
* config.owners as root access to the host. Every use is written to the audit log, and known
|
|
||||||
* secret values from the config are masked in the output to prevent ACCIDENTAL leaks only.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
@@ -14,7 +9,6 @@ import { getGlobalColor } from "../src/ui/index.mjs";
|
|||||||
import { logger } from "../src/core/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { inspect } from "node:util";
|
import { inspect } from "node:util";
|
||||||
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||||
import { collectSecrets, redactSecrets } from "../src/utils/Redact.mjs";
|
|
||||||
|
|
||||||
/** @private @type {string[]} Property name substrings that indicate sensitive/secret data. */
|
/** @private @type {string[]} Property name substrings that indicate sensitive/secret data. */
|
||||||
const RESTRICTED = [
|
const RESTRICTED = [
|
||||||
@@ -96,10 +90,9 @@ function removeSensitive(obj, level = 0, visited = new WeakSet()) {
|
|||||||
* Sanitize a value for safe display: await promises, redact sensitive keys,
|
* Sanitize a value for safe display: await promises, redact sensitive keys,
|
||||||
* inspect with node:util, and escape markup characters.
|
* inspect with node:util, and escape markup characters.
|
||||||
* @param {*} value - The raw eval result.
|
* @param {*} value - The raw eval result.
|
||||||
* @param {string[]} [secrets=[]] - Secret VALUES to mask anywhere in the output (see Redact.mjs).
|
|
||||||
* @returns {Promise<string>} The sanitized output string.
|
* @returns {Promise<string>} The sanitized output string.
|
||||||
*/
|
*/
|
||||||
async function clean(value, secrets = []) {
|
async function clean(value) {
|
||||||
if (value instanceof Promise) value = await value;
|
if (value instanceof Promise) value = await value;
|
||||||
|
|
||||||
if (typeof value === "object" && value !== null) {
|
if (typeof value === "object" && value !== null) {
|
||||||
@@ -115,8 +108,6 @@ async function clean(value, secrets = []) {
|
|||||||
output = `[Inspection Error]: ${err.message}`;
|
output = `[Inspection Error]: ${err.message}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
output = redactSecrets(output, secrets);
|
|
||||||
|
|
||||||
return output
|
return output
|
||||||
.replace(/`/g, "`\u200b")
|
.replace(/`/g, "`\u200b")
|
||||||
.replace(/@/g, "@\u200b") || "undefined";
|
.replace(/@/g, "@\u200b") || "undefined";
|
||||||
@@ -153,8 +144,7 @@ function isSingleExpression(code) {
|
|||||||
/**
|
/**
|
||||||
* @private
|
* @private
|
||||||
* @async
|
* @async
|
||||||
* Execute a JavaScript expression/statement in an async function. NOT a sandbox: shadowing
|
* Execute a JavaScript expression/statement in a sandboxed async context.
|
||||||
* `process`/`require` below only hides the usual globals, it does not restrict anything.
|
|
||||||
* @param {string} expression - The code to evaluate.
|
* @param {string} expression - The code to evaluate.
|
||||||
* @param {object} context - The `this` context for the eval.
|
* @param {object} context - The `this` context for the eval.
|
||||||
* @returns {Promise<{output: string, isError: boolean, type: string, elapsed: number}>} Eval result.
|
* @returns {Promise<{output: string, isError: boolean, type: string, elapsed: number}>} Eval result.
|
||||||
@@ -163,11 +153,6 @@ async function runEval(expression, context) {
|
|||||||
const start = Date.now();
|
const start = Date.now();
|
||||||
let result, isError = false, type = "undefined";
|
let result, isError = false, type = "undefined";
|
||||||
|
|
||||||
const secrets = collectSecrets(context?.config);
|
|
||||||
for (const t of [context?.client?.token, context?.config?.token]) {
|
|
||||||
if (typeof t === "string" && t.length >= 6 && !secrets.includes(t)) secrets.push(t);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const code = isSingleExpression(expression)
|
const code = isSingleExpression(expression)
|
||||||
? `return (${expression});`
|
? `return (${expression});`
|
||||||
@@ -183,7 +168,7 @@ async function runEval(expression, context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const elapsed = Date.now() - start;
|
const elapsed = Date.now() - start;
|
||||||
const output = await clean(result, secrets);
|
const output = await clean(result);
|
||||||
|
|
||||||
return { output, isError, type, elapsed };
|
return { output, isError, type, elapsed };
|
||||||
}
|
}
|
||||||
@@ -212,8 +197,6 @@ export const command = new CommandBuilder()
|
|||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const expression = data.get("expression").value;
|
const expression = data.get("expression").value;
|
||||||
|
|
||||||
logger.warn(`[eval] ${msg?.message?.author?.id ?? msg?.author?.id ?? "unknown"} ran: ${String(expression).replace(/\s+/g, " ").slice(0, 200)}`);
|
|
||||||
|
|
||||||
const context = Object.assign({
|
const context = Object.assign({
|
||||||
message: msg?.message,
|
message: msg?.message,
|
||||||
msg,
|
msg,
|
||||||
|
|||||||
@@ -160,7 +160,7 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
|
|
||||||
const tokenText = data.get("token")?.value;
|
const tokenText = data.get("token")?.value;
|
||||||
if (tokenText) {
|
if (tokenText) {
|
||||||
const dashMatch = tokenText.length <= 300 ? tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/) : null;
|
const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||||
if (dashMatch) {
|
if (dashMatch) {
|
||||||
artistName = dashMatch[1].trim();
|
artistName = dashMatch[1].trim();
|
||||||
albumName = dashMatch[2].trim();
|
albumName = dashMatch[2].trim();
|
||||||
@@ -249,7 +249,7 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
|
|
||||||
const tokenText = data.get("token")?.value;
|
const tokenText = data.get("token")?.value;
|
||||||
if (tokenText) {
|
if (tokenText) {
|
||||||
const dashMatch = tokenText.length <= 300 ? tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/) : null;
|
const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||||
if (dashMatch) {
|
if (dashMatch) {
|
||||||
artistName = dashMatch[1].trim();
|
artistName = dashMatch[1].trim();
|
||||||
trackName = dashMatch[2].trim();
|
trackName = dashMatch[2].trim();
|
||||||
|
|||||||
@@ -73,7 +73,6 @@ function parseLastFmSubProvider(query) {
|
|||||||
function parseLastFmTrackQuery(raw) {
|
function parseLastFmTrackQuery(raw) {
|
||||||
const value = String(raw ?? "").trim();
|
const value = String(raw ?? "").trim();
|
||||||
if (!value) return null;
|
if (!value) return null;
|
||||||
if (value.length > 300) return null;
|
|
||||||
|
|
||||||
const byMatch = value.match(/^(.+?)\s+by\s+(.+)$/i);
|
const byMatch = value.match(/^(.+?)\s+by\s+(.+)$/i);
|
||||||
if (byMatch) {
|
if (byMatch) {
|
||||||
|
|||||||
@@ -55,14 +55,8 @@
|
|||||||
"requestTimeout": 60000,
|
"requestTimeout": 60000,
|
||||||
"Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors. All audio sources (Spotify, Deezer, Apple Music, etc.) are resolved by NodeLink, so configure source credentials in nodelink.config.json, not here."
|
"Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors. All audio sources (Spotify, Deezer, Apple Music, etc.) are resolved by NodeLink, so configure source credentials in nodelink.config.json, not here."
|
||||||
},
|
},
|
||||||
"restore": {
|
|
||||||
"maxAgeHours": 12,
|
|
||||||
"Comment": "After a restart the bot resumes the players it saved in MySQL. Snapshots whose last heartbeat is older than maxAgeHours (measured by the database clock) are discarded instead of resumed. Optional extras: spacingMs (pause between guilds, default 1500), spawnTimeoutMs (voice-join limit per guild, default 60000)."
|
|
||||||
},
|
|
||||||
"audio": {
|
"audio": {
|
||||||
"allowLoadstream": false,
|
"allowLoadstream": false,
|
||||||
"allowPrivateUrls": false,
|
|
||||||
"CommentPrivateUrls": "Direct audio URLs typed into %play are fetched by the bot itself. By default addresses on private networks (127.0.0.0/8, 10/8, 172.16/12, 192.168/16, 169.254/16, ...) are refused, including via redirects, so users cannot make the bot probe your internal services. Set true ONLY if you deliberately stream from your LAN (e.g. a home Icecast). Radio stations from config.radio and the local Bilibili proxy are always allowed.",
|
|
||||||
"Comment": "Playback runs on NodeLink's /v4/trackstream endpoint only: WebM/Opus zero-re-encode passthrough, stale URLs auto-retried with a fresh resolve, and seeks handled in-process by the bot (no FFmpeg anywhere). Leave allowLoadstream = false unless you specifically need the legacy /v4/loadstream route. Set it to true only if your audio node exposes /v4/loadstream — it re-enables: server-side audio filters (bassboost, nightcore, ...), MP3/AAC/PCM sources (radio stations, Bilibili's AAC audio), and NodeLink-side seeking. loadstream is what required FFmpeg in the past."
|
"Comment": "Playback runs on NodeLink's /v4/trackstream endpoint only: WebM/Opus zero-re-encode passthrough, stale URLs auto-retried with a fresh resolve, and seeks handled in-process by the bot (no FFmpeg anywhere). Leave allowLoadstream = false unless you specifically need the legacy /v4/loadstream route. Set it to true only if your audio node exposes /v4/loadstream — it re-enables: server-side audio filters (bassboost, nightcore, ...), MP3/AAC/PCM sources (radio stations, Bilibili's AAC audio), and NodeLink-side seeking. loadstream is what required FFmpeg in the past."
|
||||||
},
|
},
|
||||||
"bilibili": {
|
"bilibili": {
|
||||||
|
|||||||
+6
-10
@@ -7,19 +7,15 @@ MYSQL_DATABASE=remix
|
|||||||
MYSQL_USER=remix
|
MYSQL_USER=remix
|
||||||
MYSQL_PASSWORD=remix_pw
|
MYSQL_PASSWORD=remix_pw
|
||||||
|
|
||||||
# --- NodeLink (audio node) ---
|
# --- Host port mappings ---
|
||||||
# REQUIRED. Use the same value in config.json -> nodelink.password. NodeLink is reachable from the
|
# Port exposed on the host for the bot (dashboard backend / health endpoint)
|
||||||
# compose network only (no host port is published), but still pick something unguessable.
|
WEB_PORT=8080
|
||||||
NODELINK_PASSWORD=change-me-nodelink
|
# Port exposed on the host for NodeLink (audio node)
|
||||||
# Optional: git tag or commit of https://github.com/PerformanC/NodeLink to build (default v3.9.0).
|
NODELINK_PORT=3000
|
||||||
# NODELINK_REF=v3.9.0
|
|
||||||
|
|
||||||
# --- Optional: commit shown by the bot (the image has no .git). CI passes the commit SHA. ---
|
|
||||||
# GIT_SHA=
|
|
||||||
|
|
||||||
# --- Timezone applied to all containers ---
|
# --- Timezone applied to all containers ---
|
||||||
TZ=UTC
|
TZ=UTC
|
||||||
|
|
||||||
# --- Optional: raw JSON config written to /app/config.json on first boot ---
|
# --- Optional: raw JSON config written to /app/config.json on first boot ---
|
||||||
# Takes precedence over docker/config_example.json when no config.json is mounted.
|
# Takes precedence over docker/config_example.json when no config.json is mounted.
|
||||||
# CONFIG_JSON={"token":"YOUR_TOKEN","mysql":{"host":"mysql","port":3306,"user":"remix","password":"remix_pw","database":"remix"},"nodelink":{"host":"nodelink","port":3000,"password":"change-me-nodelink"}}
|
# CONFIG_JSON={"token":"YOUR_TOKEN","mysql":{"host":"mysql","port":3306,"user":"remix","password":"remix_pw","database":"remix"},"nodelink":{"host":"nodelink","port":3000,"password":"youshallnotpass"}}
|
||||||
+7
-15
@@ -5,20 +5,18 @@ FROM node:22-bookworm-slim AS builder
|
|||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# .npmrc carries legacy-peer-deps (the @fluxerjs peer ranges conflict); package-lock.json pins versions.
|
COPY package.json package-lock.json* ./
|
||||||
COPY package.json package-lock.json* .npmrc ./
|
|
||||||
|
|
||||||
RUN npm ci --omit=dev --legacy-peer-deps || npm install --omit=dev --legacy-peer-deps
|
RUN npm ci --omit=dev --legacy-peer-deps 2>/dev/null || npm install --omit=dev --legacy-peer-deps
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# ---- Runtime stage: minimal image ----
|
# ---- Runtime stage: minimal image with ffmpeg ----
|
||||||
# No ffmpeg: audio goes through NodeLink and the in-process Opus/WebM pipeline; ffprobe comes from
|
|
||||||
# the bundled ffprobe-static package.
|
|
||||||
FROM node:22-bookworm-slim AS runtime
|
FROM node:22-bookworm-slim AS runtime
|
||||||
|
|
||||||
RUN apt-get update && \
|
RUN apt-get update && \
|
||||||
apt-get install -y --no-install-recommends \
|
apt-get install -y --no-install-recommends \
|
||||||
|
ffmpeg \
|
||||||
tini \
|
tini \
|
||||||
curl \
|
curl \
|
||||||
ca-certificates \
|
ca-certificates \
|
||||||
@@ -34,18 +32,12 @@ COPY --from=builder --chown=10001:10001 /app ./
|
|||||||
RUN chmod +x docker/docker-entrypoint.sh && \
|
RUN chmod +x docker/docker-entrypoint.sh && \
|
||||||
mkdir -p /app/storage && chown -R 10001:10001 /app
|
mkdir -p /app/storage && chown -R 10001:10001 /app
|
||||||
|
|
||||||
# Commit shown by the bot (the image has no .git). CI passes it with --build-arg GIT_SHA=<sha>.
|
|
||||||
ARG GIT_SHA=""
|
|
||||||
ENV GIT_SHA=${GIT_SHA}
|
|
||||||
|
|
||||||
# The bot touches this file every 15s while its event loop is running and it is logged in.
|
|
||||||
# docker/healthcheck.mjs reports unhealthy when it is missing or stale (no procps needed).
|
|
||||||
ENV HEARTBEAT_FILE=/tmp/remix-heartbeat
|
|
||||||
|
|
||||||
USER 10001:10001
|
USER 10001:10001
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||||
CMD ["node", "docker/healthcheck.mjs"]
|
CMD pgrep -f "node .*index.mjs" >/dev/null 2>&1 || pgrep -f "node .*shard.mjs" >/dev/null 2>&1 || exit 1
|
||||||
|
|
||||||
ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"]
|
ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"]
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
"nodelink": {
|
"nodelink": {
|
||||||
"host": "nodelink",
|
"host": "nodelink",
|
||||||
"port": 3000,
|
"port": 3000,
|
||||||
"password": "change-me-nodelink",
|
"password": "youshallnotpass",
|
||||||
"requestTimeout": 60000
|
"requestTimeout": 60000
|
||||||
},
|
},
|
||||||
"lastfm": {
|
"lastfm": {
|
||||||
|
|||||||
+12
-20
@@ -3,9 +3,6 @@ services:
|
|||||||
build:
|
build:
|
||||||
context: ..
|
context: ..
|
||||||
dockerfile: docker/Dockerfile
|
dockerfile: docker/Dockerfile
|
||||||
args:
|
|
||||||
# Baked into the image so the bot can show a working commit link (the image has no .git).
|
|
||||||
GIT_SHA: ${GIT_SHA:-}
|
|
||||||
container_name: remix-bot
|
container_name: remix-bot
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -20,7 +17,8 @@ services:
|
|||||||
- ../storage:/app/storage
|
- ../storage:/app/storage
|
||||||
environment:
|
environment:
|
||||||
- TZ=${TZ:-UTC}
|
- TZ=${TZ:-UTC}
|
||||||
# No ports: the bot runs no HTTP server (the dashboard talks to it over Redis).
|
ports:
|
||||||
|
- "${WEB_PORT:-8080}:80"
|
||||||
networks:
|
networks:
|
||||||
- remix-net
|
- remix-net
|
||||||
|
|
||||||
@@ -36,8 +34,7 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- mysql_data:/var/lib/mysql
|
- mysql_data:/var/lib/mysql
|
||||||
healthcheck:
|
healthcheck:
|
||||||
# Password via MYSQL_PWD (not on the command line, so it is not visible in `ps` or warned about).
|
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD:-remix_root_pw}"]
|
||||||
test: ["CMD-SHELL", "MYSQL_PWD=\"$$MYSQL_ROOT_PASSWORD\" mysqladmin ping -h localhost -u root"]
|
|
||||||
interval: 10s
|
interval: 10s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 10
|
retries: 10
|
||||||
@@ -58,24 +55,18 @@ services:
|
|||||||
- remix-net
|
- remix-net
|
||||||
|
|
||||||
nodelink:
|
nodelink:
|
||||||
# NodeLink is NOT published on npm: it is built from the official repository using its own
|
image: node:22-bookworm-slim
|
||||||
# Dockerfile. NODELINK_REF is a git tag or commit (v3.9.0 = commit cdb02c6814fd...).
|
|
||||||
# Configuration is done with NODELINK_* environment variables (see NodeLink's docker-compose.yml
|
|
||||||
# for the full list, e.g. cluster, logging and per-source settings).
|
|
||||||
build:
|
|
||||||
context: https://github.com/PerformanC/NodeLink.git#${NODELINK_REF:-v3.9.0}
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
container_name: remix-nodelink
|
container_name: remix-nodelink
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
working_dir: /nodelink
|
||||||
|
command: sh -c "if [ ! -f package.json ]; then npm init -y && npm install @performanc/nodelink; fi; node node_modules/@performanc/nodelink/index.js || node index.js"
|
||||||
environment:
|
environment:
|
||||||
- TZ=${TZ:-UTC}
|
- TZ=${TZ:-UTC}
|
||||||
- NODELINK_SERVER_HOST=0.0.0.0
|
volumes:
|
||||||
- NODELINK_SERVER_PORT=3000
|
- nodelink_data:/nodelink
|
||||||
- NODELINK_SERVER_PASSWORD=${NODELINK_PASSWORD:?Set NODELINK_PASSWORD in docker/.env (and the same value in config.json -> nodelink.password)}
|
- ./nodelink.config.json:/nodelink/config.json:ro
|
||||||
# Reachable from the bot over the compose network only. It is deliberately NOT published on
|
ports:
|
||||||
# the host: anyone who can reach it with the password can use your server as an audio proxy.
|
- "${NODELINK_PORT:-3000}:3000"
|
||||||
expose:
|
|
||||||
- "3000"
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "node", "-e", "require('net').connect(3000,'127.0.0.1').on('connect',function(){process.exit(0)}).on('error',function(){process.exit(1)})"]
|
test: ["CMD", "node", "-e", "require('net').connect(3000,'127.0.0.1').on('connect',function(){process.exit(0)}).on('error',function(){process.exit(1)})"]
|
||||||
interval: 5s
|
interval: 5s
|
||||||
@@ -87,6 +78,7 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
mysql_data:
|
mysql_data:
|
||||||
|
nodelink_data:
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
remix-net:
|
remix-net:
|
||||||
|
|||||||
@@ -8,10 +8,8 @@
|
|||||||
import { logger } from "./src/core/Logger.mjs";
|
import { logger } from "./src/core/Logger.mjs";
|
||||||
import Remix from "./src/core/Bot.mjs";
|
import Remix from "./src/core/Bot.mjs";
|
||||||
import { initErrorChannel, reportCrash } from "./src/core/ErrorChannel.mjs";
|
import { initErrorChannel, reportCrash } from "./src/core/ErrorChannel.mjs";
|
||||||
import { startHeartbeat } from "./src/core/Heartbeat.mjs";
|
|
||||||
|
|
||||||
const remix = new Remix();
|
const remix = new Remix();
|
||||||
startHeartbeat({ isReady: () => Boolean(remix.client?.user) });
|
|
||||||
|
|
||||||
initErrorChannel({ config: remix.config, client: remix.client });
|
initErrorChannel({ config: remix.config, client: remix.client });
|
||||||
|
|
||||||
@@ -149,10 +147,6 @@ 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...");
|
||||||
setTimeout(() => {
|
|
||||||
logger.warn("[Shutdown] Cleanup timed out, forcing exit");
|
|
||||||
process.exit(1);
|
|
||||||
}, 8000).unref();
|
|
||||||
try {
|
try {
|
||||||
await remix.playerState?.saveAllFrom?.(remix.players);
|
await remix.playerState?.saveAllFrom?.(remix.players);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
+1
-2
@@ -20,7 +20,6 @@
|
|||||||
"dev": "node --inspect index.mjs --trace-warnings",
|
"dev": "node --inspect index.mjs --trace-warnings",
|
||||||
"start": "node index.mjs",
|
"start": "node index.mjs",
|
||||||
"shard": "node shard.mjs",
|
"shard": "node shard.mjs",
|
||||||
"migrate": "node settings/migrate.mjs",
|
"migrate": "node settings/migrate.mjs"
|
||||||
"check": "node scripts/check.mjs"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
/**
|
|
||||||
* Fast project gate for CI and local use (`npm run check`):
|
|
||||||
* 1. every .mjs file parses (node --check)
|
|
||||||
* 2. every module links (catches broken imports / missing exports without starting the bot)
|
|
||||||
* 3. every JSON file is valid
|
|
||||||
* 4. all translations have exactly the keys of en.json
|
|
||||||
* Exits 1 on any failure.
|
|
||||||
*/
|
|
||||||
import { spawnSync } from "node:child_process";
|
|
||||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
||||||
import { join, relative } from "node:path";
|
|
||||||
import { pathToFileURL } from "node:url";
|
|
||||||
|
|
||||||
const root = process.cwd();
|
|
||||||
const SKIP_DIRS = new Set(["node_modules", ".git", "test", "scripts"]);
|
|
||||||
const ENTRY_POINTS = new Set(["index.mjs", "shard.mjs", "settings/migrate.mjs", "settings/runnables.mjs", "docker/healthcheck.mjs"]);
|
|
||||||
|
|
||||||
function walk(dir, ext, out = []) {
|
|
||||||
for (const name of readdirSync(dir)) {
|
|
||||||
if (SKIP_DIRS.has(name) || name.startsWith(".")) continue;
|
|
||||||
const p = join(dir, name);
|
|
||||||
if (statSync(p).isDirectory()) walk(p, ext, out);
|
|
||||||
else if (name.endsWith(ext)) out.push(p);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
const rel = (p) => relative(root, p).split("\\").join("/");
|
|
||||||
const failures = [];
|
|
||||||
|
|
||||||
const mjs = walk(root, ".mjs").map(rel).sort();
|
|
||||||
for (const f of mjs) {
|
|
||||||
const r = spawnSync(process.execPath, ["--check", f], { encoding: "utf8" });
|
|
||||||
if (r.status !== 0) failures.push(`syntax ${f}: ${(r.stderr || "").split("\n").find((l) => l.trim()) ?? "error"}`);
|
|
||||||
}
|
|
||||||
console.log(`syntax ${mjs.length} files checked`);
|
|
||||||
|
|
||||||
let linked = 0;
|
|
||||||
const realExit = process.exit;
|
|
||||||
process.exit = (code) => { throw new Error(`called process.exit(${code}) while being imported`); };
|
|
||||||
for (const f of mjs.filter((f) => !ENTRY_POINTS.has(f))) {
|
|
||||||
try { await import(pathToFileURL(join(root, f)).href); linked++; }
|
|
||||||
catch (e) { failures.push(`link ${f}: ${String(e.message).split("\n")[0]}`); }
|
|
||||||
}
|
|
||||||
process.exit = realExit;
|
|
||||||
console.log(`link ${linked} modules loaded`);
|
|
||||||
|
|
||||||
const jsons = walk(root, ".json").map(rel).sort();
|
|
||||||
for (const f of jsons) {
|
|
||||||
try { JSON.parse(readFileSync(join(root, f), "utf8")); }
|
|
||||||
catch (e) { failures.push(`json ${f}: ${e.message}`); }
|
|
||||||
}
|
|
||||||
console.log(`json ${jsons.length} files checked`);
|
|
||||||
|
|
||||||
const localeDir = join(root, "storage", "locales", "bot");
|
|
||||||
try {
|
|
||||||
const flat = (o, p = "", out = {}) => { for (const [k, v] of Object.entries(o)) { const key = p ? p + "." + k : k; v && typeof v === "object" && !Array.isArray(v) ? flat(v, key, out) : (out[key] = v); } return out; };
|
|
||||||
const load = (f) => flat(JSON.parse(readFileSync(join(localeDir, f), "utf8")));
|
|
||||||
const base = load("en.json");
|
|
||||||
let locales = 0;
|
|
||||||
for (const f of readdirSync(localeDir).filter((f) => f.endsWith(".json") && f !== "en.json")) {
|
|
||||||
const d = load(f); locales++;
|
|
||||||
const missing = Object.keys(base).filter((k) => !(k in d));
|
|
||||||
if (missing.length) failures.push(`locale ${f}: ${missing.length} key(s) missing, e.g. ${missing.slice(0, 3).join(", ")}`);
|
|
||||||
}
|
|
||||||
console.log(`locales ${locales} translations compared with en.json (${Object.keys(base).length} keys)`);
|
|
||||||
} catch (e) { failures.push(`locale could not compare translations: ${e.message}`); }
|
|
||||||
|
|
||||||
if (failures.length) {
|
|
||||||
console.error(`\n${failures.length} problem(s):\n ` + failures.join("\n "));
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
console.log("\nall checks passed");
|
|
||||||
process.exit(0);
|
|
||||||
@@ -33,8 +33,6 @@ export class CommandHandler extends EventEmitter {
|
|||||||
pingPrefix = true;
|
pingPrefix = true;
|
||||||
/** @type {string[]} Bot owner user IDs. */
|
/** @type {string[]} Bot owner user IDs. */
|
||||||
owners = [];
|
owners = [];
|
||||||
/** When false (default) messages from other bots/webhooks never trigger commands (set config.allowBotCommands = true to allow). */
|
|
||||||
allowBotCommands = false;
|
|
||||||
|
|
||||||
/** @type {import('../ui/MessageHandler.mjs').MessageHandler} */
|
/** @type {import('../ui/MessageHandler.mjs').MessageHandler} */
|
||||||
messages;
|
messages;
|
||||||
@@ -133,8 +131,6 @@ export class CommandHandler extends EventEmitter {
|
|||||||
*/
|
*/
|
||||||
messageHandler(msg) {
|
messageHandler(msg) {
|
||||||
if (!msg || !msg.content) return;
|
if (!msg || !msg.content) return;
|
||||||
const author = msg.message?.author ?? msg.author;
|
|
||||||
if (author?.bot && !this.allowBotCommands) return;
|
|
||||||
const trimmed = msg.content.trim();
|
const trimmed = msg.content.trim();
|
||||||
if (/^<@!?\d+>$/.test(trimmed)) {
|
if (/^<@!?\d+>$/.test(trimmed)) {
|
||||||
const botId = this.client.user?.id;
|
const botId = this.client.user?.id;
|
||||||
@@ -248,7 +244,7 @@ export class CommandHandler extends EventEmitter {
|
|||||||
* @param {boolean} [external=false] - When true, errors are returned instead of replied.
|
* @param {boolean} [external=false] - When true, errors are returned instead of replied.
|
||||||
* @returns {object|undefined} The command run payload.
|
* @returns {object|undefined} The command run payload.
|
||||||
*/
|
*/
|
||||||
processCommand(cmd, args, msg, previous = false, external = false, requirementsChecked = false) {
|
processCommand(cmd, args, msg, previous = false, external = false) {
|
||||||
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
||||||
|
|
||||||
if (!external) {
|
if (!external) {
|
||||||
@@ -270,8 +266,8 @@ export class CommandHandler extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cmd.requirements.length > 0 && !external && !requirementsChecked) {
|
if (cmd.requirements.length > 0 && !external) {
|
||||||
if (!this.assertRequirements(cmd, msg, args, previous)) return;
|
if (!this.assertRequirements(cmd, msg)) return;
|
||||||
}
|
}
|
||||||
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
|
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
|
||||||
if (!external) this.emit("command", { command: cmd, message: msg });
|
if (!external) this.emit("command", { command: cmd, message: msg });
|
||||||
@@ -448,7 +444,7 @@ export class CommandHandler extends EventEmitter {
|
|||||||
* @param {Message} msg
|
* @param {Message} msg
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
assertRequirements(cmd, msg, args = null, previous = false) {
|
assertRequirements(cmd, msg) {
|
||||||
const authorId = msg.message?.author?.id;
|
const authorId = msg.message?.author?.id;
|
||||||
const isOwner = this.owners.includes(authorId);
|
const isOwner = this.owners.includes(authorId);
|
||||||
const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
@@ -481,19 +477,12 @@ export class CommandHandler extends EventEmitter {
|
|||||||
if (missing.length > 0) {
|
if (missing.length > 0) {
|
||||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||||
} else {
|
} else {
|
||||||
let dispatchArgs = args;
|
|
||||||
if (!dispatchArgs) {
|
|
||||||
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
const prefix2 = this.getPrefix(guildId2);
|
const prefix2 = this.getPrefix(guildId2);
|
||||||
const rawContent = msg.message.content;
|
const rawContent = msg.message.content;
|
||||||
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
||||||
dispatchArgs = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||||
}
|
this.processCommand(cmd, args, msg, false, true);
|
||||||
try {
|
|
||||||
this.processCommand(cmd, dispatchArgs, msg, previous, false, true);
|
|
||||||
} catch (e) {
|
|
||||||
logger.error("[CommandHandler] Command failed after async permission check:", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
|
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
+1
-15
@@ -25,7 +25,6 @@ import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
|||||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||||
import { VoiceStateCache } from "../voice/VoiceStateCache.mjs";
|
import { VoiceStateCache } from "../voice/VoiceStateCache.mjs";
|
||||||
import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs";
|
import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs";
|
||||||
import { RejoinBackoff } from "../voice/gateway/RejoinBackoff.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";
|
||||||
@@ -221,12 +220,7 @@ class Remix {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
const ownerList = [].concat(config.owners ?? []);
|
commands.owners = config.owners ?? [];
|
||||||
if (ownerList.some((id) => typeof id === "number")) {
|
|
||||||
logger.warn("[Config] owners contains a JSON number. Snowflake IDs exceed 2^53 and are corrupted as numbers: write each ID as a quoted string.");
|
|
||||||
}
|
|
||||||
commands.owners = ownerList.map((id) => String(id).trim()).filter(Boolean);
|
|
||||||
commands.allowBotCommands = config.allowBotCommands === true;
|
|
||||||
|
|
||||||
this.lavalink = null;
|
this.lavalink = null;
|
||||||
let lavalinkInitialised = false;
|
let lavalinkInitialised = false;
|
||||||
@@ -247,8 +241,6 @@ class Remix {
|
|||||||
this.intentionalLeaves = new Map();
|
this.intentionalLeaves = new Map();
|
||||||
/** Bot-level 24/7 rejoin timers (channelId → Timeout). Owned by Remix, not by Players. */
|
/** Bot-level 24/7 rejoin timers (channelId → Timeout). Owned by Remix, not by Players. */
|
||||||
this._247RejoinTimers = new Map();
|
this._247RejoinTimers = new Map();
|
||||||
/** Escalating per-channel cool-down so the 24/7 watchdog stops hammering channels it cannot join. */
|
|
||||||
this.rejoinBackoff = new RejoinBackoff();
|
|
||||||
|
|
||||||
this.gatewayHandler = new GatewayHandler(this);
|
this.gatewayHandler = new GatewayHandler(this);
|
||||||
this.gatewayHandler.setupEventHandlers();
|
this.gatewayHandler.setupEventHandlers();
|
||||||
@@ -341,16 +333,10 @@ class Remix {
|
|||||||
this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
||||||
this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const sha = process.env.GIT_SHA?.trim();
|
|
||||||
if (sha) {
|
|
||||||
this.comHash = sha.slice(0, 7);
|
|
||||||
this.comHashLong = sha;
|
|
||||||
} else {
|
|
||||||
logger.warn("[Git] comhash error:", e?.message);
|
logger.warn("[Git] comhash error:", e?.message);
|
||||||
this.comHash = "Newest";
|
this.comHash = "Newest";
|
||||||
this.comHashLong = null;
|
this.comHashLong = null;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
||||||
|
|
||||||
|
|||||||
@@ -17,15 +17,6 @@ import { remove247ChannelMode, isPlayerConnectionDead, detachPlayerFromManager,
|
|||||||
import { logger } from "./Logger.mjs";
|
import { logger } from "./Logger.mjs";
|
||||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||||
|
|
||||||
/** Reject if `promise` has not settled within `ms` (the timer is always cleared). */
|
|
||||||
function withTimeout(promise, ms, label) {
|
|
||||||
let timer;
|
|
||||||
return Promise.race([
|
|
||||||
promise,
|
|
||||||
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms); }),
|
|
||||||
]).finally(() => clearTimeout(timer));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {object}
|
* @type {object}
|
||||||
* @description Voice/channel mixin — applied to Remix.
|
* @description Voice/channel mixin — applied to Remix.
|
||||||
@@ -399,7 +390,6 @@ const BotVoiceMixin = {
|
|||||||
|
|
||||||
this.players.playerMap.set(cleanChannelId, player);
|
this.players.playerMap.set(cleanChannelId, player);
|
||||||
this.players._indexPlayer(cleanGuildId, cleanChannelId);
|
this.players._indexPlayer(cleanGuildId, cleanChannelId);
|
||||||
this.rejoinBackoff?.recordSuccess(cleanChannelId);
|
|
||||||
if (this.players._pendingJoins) {
|
if (this.players._pendingJoins) {
|
||||||
this.players._pendingJoins.delete(cleanChannelId);
|
this.players._pendingJoins.delete(cleanChannelId);
|
||||||
}
|
}
|
||||||
@@ -454,29 +444,9 @@ const BotVoiceMixin = {
|
|||||||
logger.player(`[Restore] ${rows.length} saved player(s) found — restoring ${local.length} on this shard.`);
|
logger.player(`[Restore] ${rows.length} saved player(s) found — restoring ${local.length} on this shard.`);
|
||||||
if (!local.length) return;
|
if (!local.length) return;
|
||||||
|
|
||||||
const rc = this.config?.restore ?? {};
|
for (let i = 0; i < local.length; i++) {
|
||||||
const num = (v, d) => (Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : d);
|
const { guildId, data: snap } = local[i];
|
||||||
const spacingMs = num(rc.spacingMs, 1_500);
|
if (i > 0) await new Promise((r) => setTimeout(r, 1_500));
|
||||||
const startTimeoutMs = num(rc.startTimeoutMs, 20_000);
|
|
||||||
const seekSettleMs = num(rc.seekSettleMs, 800);
|
|
||||||
const spawnTimeoutMs = num(rc.spawnTimeoutMs, 60_000);
|
|
||||||
const rawHours = Number(rc.maxAgeHours);
|
|
||||||
const maxAgeHours = rawHours > 0 ? rawHours : 12;
|
|
||||||
|
|
||||||
const toRestore = [];
|
|
||||||
for (const r of local) {
|
|
||||||
if (Number.isFinite(r.ageMs) && r.ageMs > maxAgeHours * 3_600_000) {
|
|
||||||
logger.player(`[Restore] Snapshot for guild ${r.guildId} is ${(r.ageMs / 3_600_000).toFixed(1)}h old (limit ${maxAgeHours}h), dropping it.`);
|
|
||||||
try { await store.clearSnapshot(r.guildId); } catch (_) {}
|
|
||||||
} else {
|
|
||||||
toRestore.push(r);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!toRestore.length) return;
|
|
||||||
|
|
||||||
for (let i = 0; i < toRestore.length; i++) {
|
|
||||||
const { guildId, data: snap } = toRestore[i];
|
|
||||||
if (i > 0) await new Promise((r) => setTimeout(r, spacingMs));
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const channelId = cleanId(snap.channelId);
|
const channelId = cleanId(snap.channelId);
|
||||||
@@ -489,7 +459,7 @@ const BotVoiceMixin = {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const player = await withTimeout(this._spawnPlayer(guildId, channelId), spawnTimeoutMs, "Voice join");
|
const player = await this._spawnPlayer(guildId, channelId);
|
||||||
|
|
||||||
const tcId = cleanId(snap.textChannelId);
|
const tcId = cleanId(snap.textChannelId);
|
||||||
if (tcId) {
|
if (tcId) {
|
||||||
@@ -527,25 +497,11 @@ const BotVoiceMixin = {
|
|||||||
system: true,
|
system: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
await new Promise((resolve) => {
|
await player.playNext();
|
||||||
const timer = setTimeout(() => { player.off("startplay", onStart); resolve(); }, startTimeoutMs);
|
|
||||||
const onStart = () => { clearTimeout(timer); player.off("startplay", onStart); resolve(); };
|
|
||||||
player.once("startplay", onStart);
|
|
||||||
player.playNext().then(onStart, (e) => {
|
|
||||||
logger.warn(`[Restore] playNext failed for guild ${guildId}:`, e?.message ?? e);
|
|
||||||
onStart();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
if (current && pos > 0 && dur > 0) {
|
if (current && pos > 0 && dur > 0) {
|
||||||
(async () => {
|
await new Promise((r) => setTimeout(r, 800)); // let the bridge settle
|
||||||
const deadline = Date.now() + 15_000;
|
|
||||||
while (Date.now() < deadline && player._audioBridge?._playing !== true) {
|
|
||||||
await new Promise((r) => setTimeout(r, 250));
|
|
||||||
}
|
|
||||||
await new Promise((r) => setTimeout(r, seekSettleMs)); // let the bridge settle
|
|
||||||
try { await player.seekToPosition(pos); } catch (_) {}
|
try { await player.seekToPosition(pos); } catch (_) {}
|
||||||
})().catch(() => {});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.player(`[Restore] Guild ${guildId}: ${player.queue.data.length} track(s) restored, resuming at ${pos}ms.`);
|
logger.player(`[Restore] Guild ${guildId}: ${player.queue.data.length} track(s) restored, resuming at ${pos}ms.`);
|
||||||
|
|||||||
@@ -209,14 +209,12 @@ export class PlayerStateStore {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Load every snapshot belonging to this bot.
|
* Load every snapshot belonging to this bot.
|
||||||
* @returns {Promise<Array<{guildId: string, data: object, positionMs: number, ageMs: number|null}>>}
|
* @returns {Promise<Array<{guildId: string, data: object, positionMs: number}>>}
|
||||||
* ageMs = time since the row was last written, measured by the DATABASE clock (immune to
|
|
||||||
* bot/DB clock skew); null when it cannot be determined.
|
|
||||||
*/
|
*/
|
||||||
async loadAll() {
|
async loadAll() {
|
||||||
await this.init();
|
await this.init();
|
||||||
const rows = await this._exec(
|
const rows = await this._exec(
|
||||||
`SELECT guild_id, data, position_ms, TIMESTAMPDIFF(SECOND, updated_at, NOW()) AS age_s FROM player_state WHERE bot_id = ?`,
|
`SELECT guild_id, data, position_ms FROM player_state WHERE bot_id = ?`,
|
||||||
[this.botId]
|
[this.botId]
|
||||||
);
|
);
|
||||||
const out = [];
|
const out = [];
|
||||||
@@ -224,11 +222,7 @@ export class PlayerStateStore {
|
|||||||
try {
|
try {
|
||||||
const parsed = typeof row.data === "string" ? JSON.parse(row.data) : row.data;
|
const parsed = typeof row.data === "string" ? JSON.parse(row.data) : row.data;
|
||||||
if (parsed && parsed.channelId) {
|
if (parsed && parsed.channelId) {
|
||||||
const ageS = row.age_s == null ? NaN : Number(row.age_s);
|
out.push({ guildId: String(row.guild_id), data: parsed, positionMs: Number(row.position_ms) || 0 });
|
||||||
out.push({
|
|
||||||
guildId: String(row.guild_id), data: parsed, positionMs: Number(row.position_ms) || 0,
|
|
||||||
ageMs: Number.isFinite(ageS) ? Math.max(0, ageS) * 1000 : null,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[PlayerState] Skipping malformed snapshot for guild", row.guild_id, ":", e?.message);
|
logger.warn("[PlayerState] Skipping malformed snapshot for guild", row.guild_id, ":", e?.message);
|
||||||
|
|||||||
+3
-16
@@ -172,9 +172,6 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
/** @private @type {Map<string, setTimeout>} Debounce timers keyed by guild ID. */
|
/** @private @type {Map<string, setTimeout>} Debounce timers keyed by guild ID. */
|
||||||
_debounceTimers = new Map();
|
_debounceTimers = new Map();
|
||||||
|
|
||||||
/** @private @type {Map<string, Set<string>>} Keys changed since the last flush, per guild: one debounce window can span several keys. */
|
|
||||||
_dirtyKeys = new Map();
|
|
||||||
|
|
||||||
/** @private @type {boolean} True after shutdown() is called. */
|
/** @private @type {boolean} True after shutdown() is called. */
|
||||||
_shuttingDown = false;
|
_shuttingDown = false;
|
||||||
|
|
||||||
@@ -213,7 +210,6 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
for (const [, timer] of this._debounceTimers) clearTimeout(timer);
|
for (const [, timer] of this._debounceTimers) clearTimeout(timer);
|
||||||
this._debounceTimers.clear();
|
this._debounceTimers.clear();
|
||||||
this._dirtyKeys?.clear();
|
|
||||||
if (pendingServers.length > 0) {
|
if (pendingServers.length > 0) {
|
||||||
logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`);
|
logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`);
|
||||||
}
|
}
|
||||||
@@ -479,28 +475,20 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
}
|
}
|
||||||
const s = this.guilds.get(server.id);
|
const s = this.guilds.get(server.id);
|
||||||
s.data[key] = server.data[key];
|
s.data[key] = server.data[key];
|
||||||
this._dirtyKeys ??= new Map();
|
|
||||||
if (key === 'stay_247') {
|
if (key === 'stay_247') {
|
||||||
const existing = this._debounceTimers.get(server.id);
|
const existing = this._debounceTimers.get(server.id);
|
||||||
if (existing) { clearTimeout(existing); this._debounceTimers.delete(server.id); }
|
if (existing) { clearTimeout(existing); this._debounceTimers.delete(server.id); }
|
||||||
this._dirtyKeys.delete(server.id);
|
|
||||||
this.remoteSave(s).catch(e => logger.error('[Settings] immediate save error:', e.message));
|
this.remoteSave(s).catch(e => logger.error('[Settings] immediate save error:', e.message));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let dirty = this._dirtyKeys.get(server.id);
|
|
||||||
if (!dirty) { dirty = new Set(); this._dirtyKeys.set(server.id, dirty); }
|
|
||||||
dirty.add(key);
|
|
||||||
const existing = this._debounceTimers.get(server.id);
|
const existing = this._debounceTimers.get(server.id);
|
||||||
if (existing) clearTimeout(existing);
|
if (existing) clearTimeout(existing);
|
||||||
this._debounceTimers.set(server.id, setTimeout(() => {
|
this._debounceTimers.set(server.id, setTimeout(() => {
|
||||||
this._debounceTimers.delete(server.id);
|
this._debounceTimers.delete(server.id);
|
||||||
const keys = [...(this._dirtyKeys.get(server.id) ?? [])];
|
|
||||||
this._dirtyKeys.delete(server.id);
|
|
||||||
const target = this.guilds.get(server.id);
|
const target = this.guilds.get(server.id);
|
||||||
if (!target) return;
|
if (target) {
|
||||||
for (const k of keys) {
|
this.remoteUpdate(target, key).catch(e =>
|
||||||
this.remoteUpdate(target, k).catch(e =>
|
logger.error(`[Settings] debounced update error (guild ${server.id}, key "${key}"):`, e?.message)
|
||||||
logger.error(`[Settings] debounced update error (guild ${server.id}, key "${k}"):`, e?.message)
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}, 80));
|
}, 80));
|
||||||
@@ -541,7 +529,6 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
removeServer(id) {
|
removeServer(id) {
|
||||||
const timer = this._debounceTimers.get(id);
|
const timer = this._debounceTimers.get(id);
|
||||||
if (timer) { clearTimeout(timer); this._debounceTimers.delete(id); }
|
if (timer) { clearTimeout(timer); this._debounceTimers.delete(id); }
|
||||||
this._dirtyKeys?.delete(id);
|
|
||||||
this.guilds.delete(id);
|
this.guilds.delete(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -32,10 +32,6 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
this._client = client;
|
this._client = client;
|
||||||
const requestSignalTimeoutMS = Number(nodeCfg.requestTimeout ?? 60_000);
|
const requestSignalTimeoutMS = Number(nodeCfg.requestTimeout ?? 60_000);
|
||||||
|
|
||||||
if (["youshallnotpass", "change-me-nodelink"].includes(nodeCfg.password ?? "youshallnotpass")) {
|
|
||||||
logger.warn("[Lavalink] NodeLink is using a well-known/placeholder password. Set a strong one in config.json (nodelink.password) and as NODELINK_PASSWORD in docker/.env.");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.lavalink = new LavalinkClientManager({
|
this.lavalink = new LavalinkClientManager({
|
||||||
nodes: [
|
nodes: [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -220,10 +220,7 @@ export class PlayerManager {
|
|||||||
try {
|
try {
|
||||||
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
||||||
if (guildId && textChannelId) {
|
if (guildId && textChannelId) {
|
||||||
const announceSrv = this.settings.getServer(guildId);
|
this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId);
|
||||||
if (announceSrv && announceSrv.get("announcementChannelId") !== textChannelId) {
|
|
||||||
announceSrv.set("announcementChannelId", textChannelId);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||||
@@ -259,10 +256,7 @@ export class PlayerManager {
|
|||||||
try {
|
try {
|
||||||
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
||||||
if (cleanGuildId && textChannelId) {
|
if (cleanGuildId && textChannelId) {
|
||||||
const announceSrv = this.settings.getServer(cleanGuildId);
|
this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId);
|
||||||
if (announceSrv && announceSrv.get("announcementChannelId") !== textChannelId) {
|
|
||||||
announceSrv.set("announcementChannelId", textChannelId);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||||
|
|||||||
@@ -4,8 +4,6 @@
|
|||||||
const _settings = {
|
const _settings = {
|
||||||
/** @type {boolean} @description Whether the legacy /v4/loadstream route may be used (server-side seek, filters, MP3/AAC decode). Disabled by default: playback runs on /v4/trackstream only. */
|
/** @type {boolean} @description Whether the legacy /v4/loadstream route may be used (server-side seek, filters, MP3/AAC decode). Disabled by default: playback runs on /v4/trackstream only. */
|
||||||
allowLoadstream: false,
|
allowLoadstream: false,
|
||||||
/** @type {boolean} @description Whether direct audio URLs typed by users may point at private/loopback/link-local addresses (LAN radio, a home Icecast...). Off by default so %play cannot be used to probe internal services. Admin-configured radio stations and the local Bilibili proxy are always trusted. */
|
|
||||||
allowPrivateUrls: false,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -17,8 +15,6 @@ const _settings = {
|
|||||||
export function configureAudio(section = null) {
|
export function configureAudio(section = null) {
|
||||||
const raw = section?.allowLoadstream;
|
const raw = section?.allowLoadstream;
|
||||||
_settings.allowLoadstream = raw === true || raw === "true";
|
_settings.allowLoadstream = raw === true || raw === "true";
|
||||||
const rawPrivate = section?.allowPrivateUrls;
|
|
||||||
_settings.allowPrivateUrls = rawPrivate === true || rawPrivate === "true";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,11 +33,4 @@ export function isLoadstreamEnabled() {
|
|||||||
return _settings.allowLoadstream === true;
|
return _settings.allowLoadstream === true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export default { configureAudio, getAudioSettings, isLoadstreamEnabled };
|
||||||
* @returns {boolean} Whether user-supplied direct URLs may target private/internal addresses.
|
|
||||||
*/
|
|
||||||
export function isPrivateUrlsAllowed() {
|
|
||||||
return _settings.allowPrivateUrls === true;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default { configureAudio, getAudioSettings, isLoadstreamEnabled, isPrivateUrlsAllowed };
|
|
||||||
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
|
import { Readable } from "node:stream";
|
||||||
import { applyMixins } from "../../utils/mixins.mjs";
|
import { applyMixins } from "../../utils/mixins.mjs";
|
||||||
import { isLoadstreamEnabled, isPrivateUrlsAllowed } from "./AudioSettings.mjs";
|
import { isLoadstreamEnabled } from "./AudioSettings.mjs";
|
||||||
import { openPublicStream } from "./SafeHttp.mjs";
|
|
||||||
import StreamPipeline from "./StreamPipeline.mjs";
|
import StreamPipeline from "./StreamPipeline.mjs";
|
||||||
import HttpStreams from "./HttpStreams.mjs";
|
import HttpStreams from "./HttpStreams.mjs";
|
||||||
|
|
||||||
@@ -168,12 +168,15 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
// source page.
|
// source page.
|
||||||
if (!trackInfo.encoded && trackInfo.url && trackInfo.url.startsWith("http")) {
|
if (!trackInfo.encoded && trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||||
logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "...");
|
logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "...");
|
||||||
const { stream, req: sourceReq } = await openPublicStream(trackInfo.url, {
|
const response = await fetch(trackInfo.url, {
|
||||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" },
|
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" },
|
||||||
allowPrivate: trackInfo.trusted === true || isPrivateUrlsAllowed(),
|
redirect: "follow",
|
||||||
});
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("HTTP " + response.status + " for " + trackInfo.url);
|
||||||
|
}
|
||||||
|
const stream = Readable.fromWeb(response.body);
|
||||||
this._sourceStream = stream;
|
this._sourceStream = stream;
|
||||||
this._sourceReq = sourceReq;
|
|
||||||
|
|
||||||
const routed = await this._routeByMagic(stream);
|
const routed = await this._routeByMagic(stream);
|
||||||
if (routed.kind === "webm") {
|
if (routed.kind === "webm") {
|
||||||
|
|||||||
@@ -26,11 +26,6 @@ const PCM_FRAME_SIZE = 960;
|
|||||||
/** @type {number} @description Opus encoding bitrate. */
|
/** @type {number} @description Opus encoding bitrate. */
|
||||||
const OPUS_BITRATE = 128000;
|
const OPUS_BITRATE = 128000;
|
||||||
|
|
||||||
/** @type {number} @description Max wait for the first bytes of a stream when sniffing its container. */
|
|
||||||
const PEEK_TIMEOUT_MS = 15_000;
|
|
||||||
/** @type {number} @description Max wait for an OpusHead before an Ogg stream is declared "not Ogg/Opus". */
|
|
||||||
const OGG_HEAD_TIMEOUT_MS = 10_000;
|
|
||||||
|
|
||||||
/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */
|
/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */
|
||||||
const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
|
const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
|
||||||
/** @type {Buffer} @description OGG container magic bytes ("OggS"). */
|
/** @type {Buffer} @description OGG container magic bytes ("OggS"). */
|
||||||
@@ -173,7 +168,7 @@ const StreamPipeline = {
|
|||||||
* @returns {Promise<Buffer>}
|
* @returns {Promise<Buffer>}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
_peek(stream, n, timeoutMs = PEEK_TIMEOUT_MS) {
|
_peek(stream, n) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const tryRead = () => {
|
const tryRead = () => {
|
||||||
const chunks = [];
|
const chunks = [];
|
||||||
@@ -194,9 +189,7 @@ const StreamPipeline = {
|
|||||||
const onReadable = () => { cleanup(); tryRead(); };
|
const onReadable = () => { cleanup(); tryRead(); };
|
||||||
const onEnd = () => { cleanup(); tryRead(); };
|
const onEnd = () => { cleanup(); tryRead(); };
|
||||||
const onError = (err) => { cleanup(); reject(err); };
|
const onError = (err) => { cleanup(); reject(err); };
|
||||||
let timer = null;
|
|
||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
if (timer) { clearTimeout(timer); timer = null; }
|
|
||||||
stream.off("readable", onReadable);
|
stream.off("readable", onReadable);
|
||||||
stream.off("end", onEnd);
|
stream.off("end", onEnd);
|
||||||
stream.off("error", onError);
|
stream.off("error", onError);
|
||||||
@@ -204,10 +197,6 @@ const StreamPipeline = {
|
|||||||
stream.once("readable", onReadable);
|
stream.once("readable", onReadable);
|
||||||
stream.once("end", onEnd);
|
stream.once("end", onEnd);
|
||||||
stream.once("error", onError);
|
stream.once("error", onError);
|
||||||
timer = setTimeout(() => {
|
|
||||||
cleanup();
|
|
||||||
reject(new Error("Timed out waiting for stream data (" + timeoutMs + "ms)"));
|
|
||||||
}, timeoutMs);
|
|
||||||
tryRead();
|
tryRead();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -259,37 +248,20 @@ const StreamPipeline = {
|
|||||||
* @returns {Promise<{stream: WebMOpusMuxer, getDurationMs: function}>}
|
* @returns {Promise<{stream: WebMOpusMuxer, getDurationMs: function}>}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
async _remuxOggToWebM(oggStream, { headTimeoutMs = OGG_HEAD_TIMEOUT_MS } = {}) {
|
async _remuxOggToWebM(oggStream) {
|
||||||
const demuxer = new PrismOggDemuxer();
|
const demuxer = new PrismOggDemuxer();
|
||||||
const muxer = new WebMOpusMuxer();
|
const muxer = new WebMOpusMuxer();
|
||||||
muxer.on("error", () => {});
|
|
||||||
oggStream.on("error", (err) => demuxer.destroy(err));
|
oggStream.on("error", (err) => demuxer.destroy(err));
|
||||||
demuxer.on("error", (err) => muxer.destroy(err));
|
demuxer.on("error", (err) => muxer.destroy(err));
|
||||||
let frameCount = 0;
|
let frameCount = 0;
|
||||||
demuxer.on("data", () => { frameCount++; });
|
demuxer.on("data", () => { frameCount++; });
|
||||||
let headTimer = null;
|
|
||||||
const headPromise = new Promise((resolve, reject) => {
|
const headPromise = new Promise((resolve, reject) => {
|
||||||
demuxer.once("head", () => resolve());
|
demuxer.once("head", () => resolve());
|
||||||
demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message)));
|
demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message)));
|
||||||
oggStream.once("error", (err) => reject(new Error("OGG source: " + err.message)));
|
oggStream.once("error", (err) => reject(new Error("OGG source: " + err.message)));
|
||||||
demuxer.once("end", () => reject(new Error("Ogg stream ended without an OpusHead (not Ogg/Opus)")));
|
|
||||||
demuxer.once("close", () => reject(new Error("Ogg demuxer closed before an OpusHead was seen")));
|
|
||||||
headTimer = setTimeout(
|
|
||||||
() => reject(new Error("Timed out waiting for an OpusHead (" + headTimeoutMs + "ms): not Ogg/Opus or the source stalled")),
|
|
||||||
headTimeoutMs
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
oggStream.pipe(demuxer).pipe(muxer);
|
oggStream.pipe(demuxer).pipe(muxer);
|
||||||
try {
|
|
||||||
await headPromise;
|
await headPromise;
|
||||||
} catch (err) {
|
|
||||||
try { oggStream.destroy(); } catch (_) {}
|
|
||||||
try { demuxer.destroy(); } catch (_) {}
|
|
||||||
try { muxer.destroy(); } catch (_) {}
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
clearTimeout(headTimer);
|
|
||||||
}
|
|
||||||
const wrapper = Object.create(muxer);
|
const wrapper = Object.create(muxer);
|
||||||
wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS;
|
wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS;
|
||||||
return wrapper;
|
return wrapper;
|
||||||
|
|||||||
@@ -122,7 +122,6 @@ const PlaybackMixin = {
|
|||||||
if (currentBeforeNext) this._lastPlayedTrack = currentBeforeNext;
|
if (currentBeforeNext) this._lastPlayedTrack = currentBeforeNext;
|
||||||
const songData = this.queue.next();
|
const songData = this.queue.next();
|
||||||
if (!songData) {
|
if (!songData) {
|
||||||
this._consecutiveErrors = 0;
|
|
||||||
this.emit("stopplay");
|
this.emit("stopplay");
|
||||||
this.emit("queueEnd");
|
this.emit("queueEnd");
|
||||||
|
|
||||||
@@ -172,6 +171,7 @@ const PlaybackMixin = {
|
|||||||
this._paused = false;
|
this._paused = false;
|
||||||
this._pausedAt = null;
|
this._pausedAt = null;
|
||||||
this._queueEndedSent = false;
|
this._queueEndedSent = false;
|
||||||
|
this._consecutiveErrors = 0;
|
||||||
this._radioReconnects = 0;
|
this._radioReconnects = 0;
|
||||||
|
|
||||||
if (songData.type !== "radio" || !this._radioAnnounced) {
|
if (songData.type !== "radio" || !this._radioAnnounced) {
|
||||||
@@ -214,8 +214,6 @@ const PlaybackMixin = {
|
|||||||
await this._playTrackViaBridge(songData, { seekSeconds: seekSec });
|
await this._playTrackViaBridge(songData, { seekSeconds: seekSec });
|
||||||
}
|
}
|
||||||
|
|
||||||
this._consecutiveErrors = 0;
|
|
||||||
|
|
||||||
if (trackOptMatch && trackOptMatch.endMs > 0) {
|
if (trackOptMatch && trackOptMatch.endMs > 0) {
|
||||||
const elapsedMs = Date.now() - this.startedPlaying;
|
const elapsedMs = Date.now() - this.startedPlaying;
|
||||||
const remainingMs = trackOptMatch.endMs - elapsedMs;
|
const remainingMs = trackOptMatch.endMs - elapsedMs;
|
||||||
@@ -315,7 +313,6 @@ const PlaybackMixin = {
|
|||||||
url: bridgeUrl,
|
url: bridgeUrl,
|
||||||
title: songData.title,
|
title: songData.title,
|
||||||
guildId: this._guildId,
|
guildId: this._guildId,
|
||||||
trusted: songData.type === "radio" || songData.type === "bilibili",
|
|
||||||
}, {
|
}, {
|
||||||
seekSeconds: options.seekSeconds ?? 0,
|
seekSeconds: options.seekSeconds ?? 0,
|
||||||
durationMs,
|
durationMs,
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ export class Queue extends EventEmitter {
|
|||||||
* @returns {string} Result message indicating success or out-of-bounds error.
|
* @returns {string} Result message indicating success or out-of-bounds error.
|
||||||
*/
|
*/
|
||||||
remove(idx) {
|
remove(idx) {
|
||||||
if (!Number.isInteger(idx) || idx < 0 || idx >= this.data.length) return "Index out of bounds";
|
if (idx < 0 || idx >= this.data.length) return "Index out of bounds";
|
||||||
const title = this.data[idx].title;
|
const title = this.data[idx].title;
|
||||||
const removed = this.data.splice(idx, 1);
|
const removed = this.data.splice(idx, 1);
|
||||||
this.emit("queue", { type: "remove", data: { index: idx, old: this.data.slice(), removed, new: this.data } });
|
this.emit("queue", { type: "remove", data: { index: idx, old: this.data.slice(), removed, new: this.data } });
|
||||||
@@ -81,8 +81,8 @@ export class Queue extends EventEmitter {
|
|||||||
* @returns {string} Result message indicating success or error.
|
* @returns {string} Result message indicating success or error.
|
||||||
*/
|
*/
|
||||||
move(from, to) {
|
move(from, to) {
|
||||||
if (!Number.isInteger(from) || from < 0 || from >= this.data.length) return "Source index out of bounds";
|
if (from < 0 || from >= this.data.length) return "Source index out of bounds";
|
||||||
if (!Number.isInteger(to) || to < 0 || to >= this.data.length) return "Target index out of bounds";
|
if (to < 0 || to >= this.data.length) return "Target index out of bounds";
|
||||||
if (from === to) return "Track is already in that position";
|
if (from === to) return "Track is already in that position";
|
||||||
const [track] = this.data.splice(from, 1);
|
const [track] = this.data.splice(from, 1);
|
||||||
this.data.splice(to, 0, track);
|
this.data.splice(to, 0, track);
|
||||||
|
|||||||
@@ -34,10 +34,6 @@ export class LastFmManager {
|
|||||||
|
|
||||||
this._mysqlConfig = mysqlConfig;
|
this._mysqlConfig = mysqlConfig;
|
||||||
this._pool = null;
|
this._pool = null;
|
||||||
/** @private True once the tables exist (a pool without ready tables is never handed out). */
|
|
||||||
this._poolReady = false;
|
|
||||||
/** @private In-flight pool+table initialisation shared by concurrent callers. */
|
|
||||||
this._poolInit = null;
|
|
||||||
|
|
||||||
this.botId = null;
|
this.botId = null;
|
||||||
this._hasBotIdColumn = false;
|
this._hasBotIdColumn = false;
|
||||||
@@ -142,41 +138,19 @@ export class LastFmManager {
|
|||||||
|
|
||||||
/** @private @async Get or create the MySQL connection pool. @returns {Promise<object>} */
|
/** @private @async Get or create the MySQL connection pool. @returns {Promise<object>} */
|
||||||
async _getPool() {
|
async _getPool() {
|
||||||
if (this._pool && this._poolReady) return this._pool;
|
if (this._pool) return this._pool;
|
||||||
if (!this._poolInit) {
|
|
||||||
this._poolInit = (async () => {
|
|
||||||
if (!this._pool) {
|
|
||||||
const mysql = await import("mysql2/promise");
|
const mysql = await import("mysql2/promise");
|
||||||
const cfg = this._mysqlConfig ?? {};
|
|
||||||
const extra = {};
|
|
||||||
for (const k of ["ssl", "socketPath", "charset", "timezone", "connectTimeout", "localAddress", "flags"]) {
|
|
||||||
if (cfg[k] !== undefined) extra[k] = cfg[k];
|
|
||||||
}
|
|
||||||
this._pool = mysql.createPool({
|
this._pool = mysql.createPool({
|
||||||
...MYSQL_POOL_DEFAULTS,
|
...MYSQL_POOL_DEFAULTS,
|
||||||
...extra,
|
host: this._mysqlConfig.host,
|
||||||
host: cfg.host,
|
port: this._mysqlConfig.port ?? 3306,
|
||||||
port: cfg.port ?? 3306,
|
user: this._mysqlConfig.user,
|
||||||
user: cfg.user,
|
password: this._mysqlConfig.password,
|
||||||
password: cfg.password,
|
database: this._mysqlConfig.database,
|
||||||
database: cfg.database,
|
|
||||||
});
|
});
|
||||||
attachMysqlPoolGuard(this._pool, "LastFm");
|
attachMysqlPoolGuard(this._pool, "LastFm");
|
||||||
}
|
|
||||||
try {
|
|
||||||
await this._initTable();
|
await this._initTable();
|
||||||
this._poolReady = true;
|
|
||||||
} catch (err) {
|
|
||||||
const failed = this._pool;
|
|
||||||
this._pool = null;
|
|
||||||
this._poolReady = false;
|
|
||||||
try { await failed?.end(); } catch (_) {}
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
return this._pool;
|
return this._pool;
|
||||||
})().finally(() => { this._poolInit = null; });
|
|
||||||
}
|
|
||||||
return this._poolInit;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @private @async Create the lastfm_users and lastfm_stats tables if they don't exist. */
|
/** @private @async Create the lastfm_users and lastfm_stats tables if they don't exist. */
|
||||||
|
|||||||
@@ -129,14 +129,10 @@ const RejoinManager = {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const player = await this._attemptRejoin(cleanChannelId, cleanGuildId, maxRetries, 5_000, "Rejoin");
|
const player = await this._attemptRejoin(cleanChannelId, cleanGuildId, maxRetries, 5_000, "Rejoin");
|
||||||
this._rejoinAttempts.delete(cleanChannelId);
|
|
||||||
if (player) {
|
if (player) {
|
||||||
remix.rejoinBackoff?.recordSuccess(cleanChannelId);
|
this._rejoinAttempts.delete(cleanChannelId);
|
||||||
} else {
|
} else {
|
||||||
const { failures, delayMs } = remix.rejoinBackoff?.recordFailure(cleanChannelId) ?? {};
|
this._rejoinAttempts.delete(cleanChannelId);
|
||||||
if (failures) {
|
|
||||||
logger.warn(`[Rejoin] Channel ${cleanChannelId} failed ${failures} attempt cycle(s) in a row; the watchdog will wait ${Math.round(delayMs / 60_000)} min before retrying (missing Connect permission or a full channel?).`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return player;
|
return player;
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -213,11 +213,6 @@ const Watchdog247 = {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((remix.rejoinBackoff?.remainingMs(channelId) ?? 0) > 0) {
|
|
||||||
skipped++;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof remix.schedule247Rejoin === "function") {
|
if (typeof remix.schedule247Rejoin === "function") {
|
||||||
remix.schedule247Rejoin(channelId, guildId);
|
remix.schedule247Rejoin(channelId, guildId);
|
||||||
healed++;
|
healed++;
|
||||||
|
|||||||
Reference in new issue
Block a user