stremio/apps/master-api/src/app.ts
Jos Vooges | STH 1f180476d1 Restore series meta via seasons path; keep TMDB enrich off the critical path.
Series listing broke after switching to series.episodes and selecting stillUrl — revert to the pre-TMDB catalog-aligned query.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 04:50:46 +02:00

122 lines
3.5 KiB
TypeScript

import Fastify from "fastify";
import cookie from "@fastify/cookie";
import cors from "@fastify/cors";
import rateLimit from "@fastify/rate-limit";
import websocket from "@fastify/websocket";
import { loadConfig } from "./config";
import { disconnectDatabase, prisma } from "./database/client";
import { registerAuthRoutes, ensureAdminUser } from "./auth/routes";
import { registerNodeRoutes } from "./nodes/routes";
import { registerStremioRoutes } from "./stremio/routes";
import { registerAdminRoutes } from "./admin/routes";
import { registerInstallRoutes } from "./install/routes";
import { nodeConnectionManager } from "./websocket/manager";
import { toErrorResponse } from "./security/errors";
async function main() {
const config = loadConfig();
const app = Fastify({
logger: {
level: config.NODE_ENV === "production" ? "info" : "debug",
redact: ["req.headers.cookie", "req.headers.authorization"],
},
trustProxy: true,
});
await app.register(cors, {
origin: true,
credentials: true,
});
await app.register(cookie, {
secret: config.SESSION_SECRET,
});
await app.register(rateLimit, {
max: 300,
timeWindow: "1 minute",
});
await app.register(websocket, {
options: {
// Large library sync batches (still chunked on the node side)
maxPayload: 16 * 1024 * 1024,
},
});
app.addHook("onSend", async (request, reply, payload) => {
if (!request.url.startsWith("/stremio/")) {
reply.header("X-Content-Type-Options", "nosniff");
reply.header("Referrer-Policy", "no-referrer");
reply.header("X-Frame-Options", "DENY");
}
return payload;
});
app.setErrorHandler((error, _request, reply) => {
const { statusCode, body } = toErrorResponse(error);
reply.status(statusCode).send(body);
});
app.get("/health", async () => ({
status: "ok",
service: "master-api",
version: "1.0.0",
}));
await registerAuthRoutes(app, config);
await registerNodeRoutes(app);
await registerStremioRoutes(app, config);
await registerAdminRoutes(app, config);
await registerInstallRoutes(app, config);
app.get("/api/v1/node/connect", { websocket: true }, (socket) => {
void nodeConnectionManager.handleConnection(socket);
});
nodeConnectionManager.init(config);
await ensureAdminUser(config);
// Safety net if migrate history drifted — series meta must not 500.
try {
await prisma.$executeRawUnsafe(
`ALTER TABLE "episodes" ADD COLUMN IF NOT EXISTS "still_url" TEXT`
);
} catch (err) {
console.warn("Could not ensure episodes.still_url:", err);
}
// Repair drifted episode.series_id so series.episodes and seasons.episodes stay aligned.
try {
await prisma.$executeRawUnsafe(`
UPDATE episodes e
SET series_id = s.series_id
FROM seasons s
WHERE e.season_id = s.id
AND e.series_id IS DISTINCT FROM s.series_id
`);
} catch (err) {
console.warn("Could not repair episode series_id drift:", err);
}
const shutdown = async () => {
console.log("Shutting down...");
nodeConnectionManager.shutdown();
await app.close();
await disconnectDatabase();
process.exit(0);
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
await app.listen({ port: config.PORT, host: config.HOST });
console.log(`Master API listening on ${config.HOST}:${config.PORT}`);
}
main().catch((err) => {
console.error("Failed to start:", err);
void prisma.$disconnect();
process.exit(1);
});