brendmanager/src/publish-server.js
2026-11-15 15:03:18 +05:00

46 lines
2.4 KiB
JavaScript

import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createPublisher } from "./publisher.js";
import { createTelegram } from "./telegram.js";
import { createLinkedIn } from "./linkedin.js";
const ROOT = path.dirname(fileURLToPath(import.meta.url));
export function createApp({ file, channels }) {
const pub = createPublisher({ file, channels });
return http.createServer(async (req, res) => {
const send = (code, data, type = "application/json") => {
res.writeHead(code, { "content-type": type + "; charset=utf-8" });
res.end(type === "application/json" ? JSON.stringify(data) : data);
};
try {
const url = req.url.split("?")[0];
if (url === "/healthz") return send(200, { ok: true });
if (req.method === "GET" && url === "/publish.html") return send(200, fs.readFileSync(path.join(ROOT, "../public/publish.html"), "utf8"), "text/html");
if (req.method === "GET" && url === "/api/publish/status") return send(200, pub.status());
if (req.method === "GET" && url === "/api/publish/log") return send(200, pub.log());
if (req.method === "GET" && url === "/api/publish/queue") return send(200, pub.queue());
if (req.method === "POST") {
let raw = "";
for await (const c of req) raw += c;
let body;
try { body = raw ? JSON.parse(raw) : {}; } catch { return send(400, { error: "Некорректный JSON" }); }
if (url === "/api/publish") return send(200, await pub.publish(body));
if (url === "/api/publish/confirm") return send(200, (await pub.confirm(Number(body.id), body.actor ?? "pm")) ?? { error: "not found" });
if (url === "/api/publish/discard") { pub.discard(Number(body.id)); return send(200, pub.queue()); }
if (url === "/api/publish/stop") { pub.stop(body.channel, body.actor ?? "pm"); return send(200, pub.status()); }
if (url === "/api/publish/resume") { pub.resume(body.channel, body.actor ?? "pm"); return send(200, pub.status()); }
}
send(404, { error: "not found" });
} catch { send(500, { error: "internal" }); }
});
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const port = Number(process.env.PORT ?? 3000);
createApp({ file: process.env.PUBLISH_FILE ?? "data/publish-state.json", channels: { telegram: createTelegram(), linkedin: createLinkedIn() } })
.listen(port, () => console.log(`listening on ${port}`));
}