48 lines
2.5 KiB
JavaScript
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(),
|
|
};
|
|
}
|