112 lines
6.2 KiB
JavaScript
112 lines
6.2 KiB
JavaScript
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import crypto from "node:crypto";
|
|
|
|
const APPROVERS = ["tatiana", "pm"];
|
|
const DAY = 24 * 3600 * 1000;
|
|
const DEFAULT_LIMITS = [{ limit: 1, periodMs: DAY }];
|
|
|
|
export function createPublisher({ file, channels, gate, now = () => Date.now() }) {
|
|
let st;
|
|
try { st = JSON.parse(fs.readFileSync(file, "utf8")); } catch { st = { log: [] }; }
|
|
// состояние по каналам: stopped — { канал: true }, limits — { канал: [{limit, periodMs}] }
|
|
if (typeof st.stopped !== "object" || st.stopped === null) st.stopped = {};
|
|
st.limits ??= {};
|
|
st.log ??= [];
|
|
st.queue ??= []; // запланированные посты, не вышедшие из-за остановки: ждут ручного подтверждения
|
|
const limitsOf = (c) => st.limits[c] ?? channels[c]?.defaultLimits?.() ?? DEFAULT_LIMITS;
|
|
const save = () => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(st, null, 2)); };
|
|
const scrub = (s, ch) => ch.secrets().reduce((a, x) => a.split(x).join("***"), String(s));
|
|
|
|
function record(channel, text, result, reason, ch, url, extra) {
|
|
const e = { ...extra, time: new Date(now()).toISOString(), channel, text: ch ? scrub(text, ch) : String(text ?? ""), result, reason: ch ? scrub(reason, ch) : reason };
|
|
if (url) e.url = ch ? scrub(url, ch) : url;
|
|
st.log.push(e);
|
|
save();
|
|
return e;
|
|
}
|
|
|
|
// ключ публикации (или сам текст, если ключа нет) — одна и та же публикация второй раз не уходит
|
|
const hash = (channel, text, key) => crypto.createHash("sha256").update(channel + "\n" + (key ?? String(text).trim())).digest("hex").slice(0, 16);
|
|
|
|
async function publish({ channel, text, approvedBy, scheduled = false, key, internal = false, rubric, action }) {
|
|
const ch = channels[channel];
|
|
if (!ch) return record(channel, text, "rejected", "unknown-channel");
|
|
if (gate && !internal) {
|
|
const why = gate({ channel, text, rubric, action });
|
|
if (why) return record(channel, text, "rejected", why, ch);
|
|
}
|
|
if (st.stopped[channel]) {
|
|
if (scheduled && typeof text === "string" && text.trim()) {
|
|
const id = (st.queue.at(-1)?.id ?? 0) + 1;
|
|
st.queue.push({ id, channel, text, approvedBy, time: new Date(now()).toISOString() });
|
|
return record(channel, text, "rejected", "stopped", ch, undefined, { queued: id });
|
|
}
|
|
return record(channel, text, "rejected", "stopped", ch);
|
|
}
|
|
if (typeof text !== "string" || !text.trim()) return record(channel, text, "rejected", "rule:text-empty", ch);
|
|
if (text.length > 4096) return record(channel, text, "rejected", "rule:text-too-long", ch);
|
|
if (!APPROVERS.includes(approvedBy)) return record(channel, text, "rejected", "rule:approval", ch);
|
|
if (ch.secrets().some((s) => text.includes(s))) return record(channel, text, "rejected", "rule:secret-in-text", ch);
|
|
// одна и та же публикация второй раз не уходит
|
|
const h = hash(channel, text, key);
|
|
const dup = key == null ? null : st.log.find((e) => e.channel === channel && e.result === "published" && e.hash === h);
|
|
if (dup) return record(channel, text, "rejected", "duplicate", ch, dup.url, { ref: dup.ref, duplicateOf: dup.time });
|
|
for (const { limit, periodMs } of limitsOf(channel)) {
|
|
const recent = st.log.filter((e) => e.channel === channel && e.result === "published" && now() - Date.parse(e.time) < periodMs);
|
|
if (recent.length >= limit) {
|
|
const oldest = Math.min(...recent.map((e) => Date.parse(e.time)));
|
|
const retryAt = new Date(oldest + periodMs).toISOString();
|
|
return record(channel, text, "rejected", "limit", ch, undefined, { retryAt });
|
|
}
|
|
}
|
|
if (ch.approval && ch.approval() !== "received") return record(channel, text, "rejected", "waiting-approval", ch);
|
|
if (!ch.connected()) return record(channel, text, "error", "нет доступов", ch, undefined, { off: true }); // BRM-61: отправка выключена на этой версии
|
|
try {
|
|
const r = await ch.send(text);
|
|
const ref = r?.url ?? (r?.message_id != null ? `сообщение №${r.message_id}` : undefined);
|
|
return record(channel, text, "published", "ok", ch, r?.url, { ...(key != null ? { hash: h } : {}), ...(ref ? { ref } : {}) });
|
|
} catch (e) {
|
|
return record(channel, text, "error", e.message, ch); // без автоповтора
|
|
}
|
|
}
|
|
|
|
const names = (channel) => (channel ? [channel] : Object.keys(channels));
|
|
const mark = (channel, on, actor) => {
|
|
for (const c of names(channel)) {
|
|
if (!channels[c]) continue;
|
|
if (on) st.stopped[c] = true; else delete st.stopped[c];
|
|
st.log.push({ time: new Date(now()).toISOString(), channel: c, text: "", result: on ? "stopped" : "resumed", reason: on ? "stop" : "resume", actor: String(actor ?? "unknown") });
|
|
}
|
|
save();
|
|
};
|
|
|
|
return {
|
|
publish,
|
|
queue: () => st.queue.slice(),
|
|
// ручное подтверждение поста из очереди: проходит те же проверки, что и обычная публикация
|
|
async confirm(id, actor) {
|
|
const i = st.queue.findIndex((q) => q.id === id);
|
|
if (i < 0) return null;
|
|
const [q] = st.queue.splice(i, 1);
|
|
save();
|
|
return publish({ channel: q.channel, text: q.text, approvedBy: q.approvedBy, confirmedBy: actor });
|
|
},
|
|
discard(id) { st.queue = st.queue.filter((q) => q.id !== id); save(); },
|
|
stop(channel, actor) { mark(channel, true, actor); },
|
|
resume(channel, actor) { mark(channel, false, actor); },
|
|
setLimit(limit, periodMs, channel) {
|
|
for (const c of names(channel)) if (limit >= 0 && periodMs > 0) st.limits[c] = [{ limit, periodMs }];
|
|
save();
|
|
},
|
|
status: () => ({
|
|
stopped: Object.keys(channels).length > 0 && Object.keys(channels).every((c) => st.stopped[c]),
|
|
channels: Object.fromEntries(Object.entries(channels).map(([k, c]) => [k, {
|
|
connected: c.connected(), stopped: Boolean(st.stopped[k]), limits: limitsOf(k),
|
|
...(c.approval ? { approval: c.approval() } : {}),
|
|
}])),
|
|
}),
|
|
log: () => st.log.slice().reverse(),
|
|
};
|
|
}
|