brendmanager/src/publisher.js
Peppa 997a862f74
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 0с
ci / checks (pull_request) Successful in 3s
deploy / deploy (pull_request) Successful in 2s
BRM-14: публикация в Telegram по режиму B: лимит, журнал, остановка
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 14:53:17 +05:00

48 lines
2.5 KiB
JavaScript

import fs from "node:fs";
import path from "node:path";
const APPROVERS = ["tatiana", "pm"];
const DAY = 24 * 3600 * 1000;
export function createPublisher({ file, channels, now = () => Date.now() }) {
let st;
try { st = JSON.parse(fs.readFileSync(file, "utf8")); } catch { st = { stopped: false, limit: 1, periodMs: DAY, log: [] }; }
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) {
const e = { time: new Date(now()).toISOString(), channel, text: ch ? scrub(text, ch) : String(text ?? ""), result, reason: ch ? scrub(reason, ch) : reason };
st.log.push(e);
save();
return e;
}
async function publish({ channel, text, approvedBy }) {
const ch = channels[channel];
if (!ch) return record(channel, text, "rejected", "unknown-channel");
if (st.stopped) 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 recent = st.log.filter((e) => e.channel === channel && e.result === "published" && now() - Date.parse(e.time) < st.periodMs);
if (recent.length >= st.limit) return record(channel, text, "rejected", "limit", ch);
if (!ch.connected()) return record(channel, text, "error", "нет доступов", ch);
try {
await ch.send(text);
return record(channel, text, "published", "ok", ch);
} catch (e) {
return record(channel, text, "error", e.message, ch); // без автоповтора
}
}
return {
publish,
stop() { st.stopped = true; save(); },
resume() { st.stopped = false; save(); },
setLimit(limit, periodMs) { if (limit >= 0) st.limit = limit; if (periodMs > 0) st.periodMs = periodMs; save(); },
status: () => ({ stopped: st.stopped, limit: st.limit, periodMs: st.periodMs, channels: Object.fromEntries(Object.entries(channels).map(([k, c]) => [k, { connected: c.connected() }])) }),
log: () => st.log.slice().reverse(),
};
}