- Play every track through an ffmpeg process that normalises loudness (EBU R128) and outputs Ogg Opus, handed to Discord as is: no more Opus encoding in JavaScript with opusscript. Measured at over 40x real time, about 2% of a core while playing. Closing the stream kills ffmpeg. - Encoding at upload instead was ruled out: over two minutes for an 85-minute mix, during which the upload would hang. - Read duration, title and artist with ffprobe at upload; default the title to "Artist - Title" or the file name without extension. - Fill the duration of existing library entries at startup. - Expose the position of the current track in queue snapshots. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
148 lines
4.7 KiB
JavaScript
148 lines
4.7 KiB
JavaScript
import express from "express";
|
|
import helmet from "helmet";
|
|
import { rateLimit } from "express-rate-limit";
|
|
import multer from "multer";
|
|
import path from "path";
|
|
import { config } from "../config.js";
|
|
import {
|
|
authMiddleware,
|
|
createBearerAuth,
|
|
localOnly,
|
|
} from "./middlewares/auth.js";
|
|
import { libraryRouter } from "./routes/library.js";
|
|
import { notificationsRouter } from "./routes/notifications.js";
|
|
import { playerRouter } from "./routes/player.js";
|
|
import { queueRouter } from "./routes/queue.js";
|
|
import { uploadsRouter } from "./routes/uploads.js";
|
|
import { backfillLibraryMetadata } from "./storage/libraryMetadata.js";
|
|
import {
|
|
cleanupTemporaryFiles,
|
|
ensureStorageLayout,
|
|
} from "./storage/storageManager.js";
|
|
|
|
const PUBLIC_DIR = path.join(process.cwd(), "public");
|
|
|
|
function apiRateLimit(options) {
|
|
return rateLimit({
|
|
standardHeaders: "draft-8",
|
|
legacyHeaders: false,
|
|
...options,
|
|
});
|
|
}
|
|
|
|
// Freine les essais de clé : seules les réponses 401 comptent. Les autres erreurs (404 d'un
|
|
// utilisateur inconnu, 422 messages privés fermés…) ne doivent pas bloquer un client authentifié.
|
|
function authFailureLimit() {
|
|
return apiRateLimit({
|
|
windowMs: 15 * 60_000,
|
|
limit: 20,
|
|
skipSuccessfulRequests: true,
|
|
requestWasSuccessful: (_req, res) => res.statusCode !== 401,
|
|
message: { error: "Trop de tentatives d'authentification" },
|
|
});
|
|
}
|
|
|
|
function createApp(
|
|
dependencies,
|
|
{ notificationsApiKey = config.notificationsApiKey } = {}
|
|
) {
|
|
const app = express();
|
|
app.disable("x-powered-by");
|
|
app.set("trust proxy", config.webTrustedProxies);
|
|
app.use(helmet());
|
|
app.use(express.json({ limit: "32kb" }));
|
|
|
|
// /healthz : le processus répond (sonde de vie). /readyz : le bot est aussi connecté à
|
|
// Discord, sinon 503 (à utiliser pour la supervision).
|
|
const discordReady = () => dependencies.client?.isReady?.() ?? false;
|
|
app.get("/healthz", (_req, res) => {
|
|
res.json({ status: "ok", discord: discordReady() ? "ready" : "not-ready" });
|
|
});
|
|
app.get("/readyz", (_req, res) => {
|
|
const ready = discordReady();
|
|
res.status(ready ? 200 : 503).json({ status: ready ? "ready" : "not-ready" });
|
|
});
|
|
|
|
// Messages privés pour les applications de confiance : connexions locales uniquement,
|
|
// avec leur propre clé (pas celle du jukebox, connue de ses utilisateurs).
|
|
app.use(
|
|
"/api/notifications",
|
|
localOnly,
|
|
apiRateLimit({ windowMs: 60_000, limit: 60 }),
|
|
authFailureLimit(),
|
|
createBearerAuth(() => notificationsApiKey),
|
|
notificationsRouter(dependencies)
|
|
);
|
|
|
|
const apiRouter = express.Router();
|
|
apiRouter.use(apiRateLimit({ windowMs: 60_000, limit: 120 }));
|
|
apiRouter.use(authFailureLimit());
|
|
apiRouter.use(authMiddleware);
|
|
apiRouter.use(
|
|
"/uploads",
|
|
apiRateLimit({ windowMs: 15 * 60_000, limit: 10 }),
|
|
uploadsRouter(dependencies)
|
|
);
|
|
apiRouter.use("/queue", queueRouter(dependencies));
|
|
apiRouter.use("/library", libraryRouter(dependencies));
|
|
apiRouter.use("/player", playerRouter(dependencies));
|
|
|
|
app.use("/api", apiRouter);
|
|
app.get(["/jukebox", "/jukebox/"], (_req, res) =>
|
|
res.sendFile(path.join(PUBLIC_DIR, "jukebox.html"))
|
|
);
|
|
app.use(express.static(PUBLIC_DIR));
|
|
|
|
app.use((error, _req, res, _next) => {
|
|
let status = Number(error?.status) || 500;
|
|
if (error instanceof multer.MulterError) {
|
|
status = error.code === "LIMIT_FILE_SIZE" ? 413 : 400;
|
|
}
|
|
if (status >= 500) {
|
|
console.error("Unhandled HTTP error", error);
|
|
}
|
|
res.status(status).json({
|
|
error: status >= 500 ? "Erreur interne du serveur" : error.message,
|
|
});
|
|
});
|
|
|
|
return app;
|
|
}
|
|
|
|
const TEMP_CLEANUP_INTERVAL = 60 * 60_000;
|
|
|
|
function startWebServer(dependencies) {
|
|
ensureStorageLayout();
|
|
const cleanup = () =>
|
|
cleanupTemporaryFiles(undefined, { keep: dependencies.queue.inUsePaths() });
|
|
cleanup();
|
|
// Les fichiers temporaires de plus de 24 h sont supprimés pendant que le bot tourne,
|
|
// pas seulement à son démarrage.
|
|
const cleanupInterval = setInterval(cleanup, TEMP_CLEANUP_INTERVAL);
|
|
cleanupInterval.unref();
|
|
|
|
backfillLibraryMetadata()
|
|
.then((updated) => {
|
|
if (updated.length > 0) {
|
|
console.log(
|
|
`[${new Date().toLocaleString()}] Library metadata completed for ${updated.length} track(s)`
|
|
);
|
|
dependencies.queue.emit("libraryUpdate");
|
|
}
|
|
})
|
|
.catch((error) => console.error("Unable to complete library metadata", error));
|
|
|
|
const app = createApp(dependencies);
|
|
const port = Number(process.env.PORT || config.webServerPort || 3000);
|
|
|
|
const server = app.listen(port, () => {
|
|
console.log(
|
|
`[${new Date().toLocaleString()}] Web control server listening on port ${port}`
|
|
);
|
|
});
|
|
server.on("close", () => clearInterval(cleanupInterval));
|
|
|
|
return { app, server };
|
|
}
|
|
|
|
export { createApp, startWebServer };
|