brendmanager/src/delivery.js

81 lines
5.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// BRM-171: исходящая доставка в Telegram (сводки, отчёты агента, уведомления) — куда и дошло ли.
// Обёртка над адаптером Telegram с тем же контрактом. Чат: TELEGRAM_CHAT_ID или личный чат владелицы,
// если она нажала в боте «Да, сюда». Отправка считается работающей только после подтверждённой доставки.
// Ключ и номер чата наружу не выходят: подробности ответа Telegram проходят через scrub.
import fs from "node:fs";
import path from "node:path";
// Кто снимает причину: tatiana — владелица, pm — команда, agent — агент сам.
export const DELIVERY_WHO = { key: "pm", unbound: "tatiana", chat: "tatiana", other: "pm", elsewhere: "agent", unchecked: "agent", blocked: "tatiana", failed: "pm", paused: "tatiana" };
const BLOCKED = /blocked|deactivated|chat not found|kicked|not enough rights|have no rights/i;
export function createDelivery({ file, telegram, getChosenChat = () => null, getOwnerChat = () => null, summaryAsked = () => "none", receivesHere = () => true, isPaused = () => false, now = () => Date.now() }) {
let st = { ok: null, fail: null };
try { st = { ...st, ...JSON.parse(fs.readFileSync(file, "utf8")) }; } catch {}
const save = () => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(st)); };
const scrub = (s) => telegram.secrets().reduce((a, x) => a.split(x).join("***"), String(s ?? ""));
// У мока без понятия «чат» готовность — его connected(), как до BRM-171.
const chatAware = typeof telegram.chatId === "function";
const envChat = () => (chatAware ? telegram.chatId() || null : null);
// Личный чат, выбранный владелицей, — только у версии, которая принимает команды бота: иначе сводки пришли бы дважды.
const chat = () => (chatAware ? envChat() ?? (receivesHere() ? getChosenChat() : null) ?? null : "mock");
const where = () => String(chat());
const hasKey = () => telegram.secrets().length > 0;
function missing() {
if (!chatAware) return telegram.missing?.() ?? (telegram.connected() ? null : "key");
if (!hasKey()) return "key";
if (chat() == null) return "chat";
return null;
}
const connected = () => (chatAware ? hasKey() && chat() != null : telegram.connected());
function record(ok, detail = "") {
const at = new Date(now()).toISOString();
if (ok) { st.ok = { at, chat: where() }; st.fail = null; }
else st.fail = { at, chat: where(), detail: scrub(detail).slice(0, 300), code: BLOCKED.test(detail) ? "blocked" : "failed" };
save();
}
async function send(text) {
if (!connected()) throw new Error("нет доступов к Telegram");
if (!chatAware) {
try { const r = await telegram.send(text); record(true); return r; } catch (e) { record(false, e.message); throw e; }
}
const r = await telegram.api("sendMessage", { chat_id: chat(), text });
if (!r?.ok) { record(false, r?.description ?? "error"); throw new Error(scrub(r?.description ?? "ошибка Telegram")); }
record(true);
return r.result;
}
// Что мешает отправке сейчас: код причины (или null), кто снимает, подробность.
function state() {
const paused = isPaused();
const okHere = st.ok && st.ok.chat === where();
const failHere = st.fail && st.fail.chat === where() && (!st.ok || st.fail.at > st.ok.at);
let code = null;
if (!hasKey() && chatAware) code = "key";
else if (!chatAware && !telegram.connected()) code = telegram.missing?.() === "chat" ? "chat" : "key";
else if (chat() == null) code = !receivesHere() ? "elsewhere" : getOwnerChat() == null ? "unbound" : summaryAsked() === "other" ? "other" : "chat";
else if (failHere) code = st.fail.code;
else if (paused) code = "paused";
else if (!okHere) code = "unchecked";
return {
ready: connected() && !paused, confirmed: Boolean(okHere) && !failHere, paused,
chosen: chatAware && !envChat() && chat() != null,
problem: code ? { code, who: DELIVERY_WHO[code], detail: failHere && (code === "blocked" || code === "failed") ? st.fail.detail : "" } : null,
lastOk: okHere ? st.ok.at : null, lastFail: failHere ? st.fail.at : null,
};
}
return {
channel: telegram.channel ?? "telegram",
secrets: () => telegram.secrets(),
connected, missing, send, state,
call: (...a) => telegram.call(...a),
api: (...a) => telegram.api(...a),
// Проверочное сообщение в чат сводок: { ok } — итог уже записан в state().
async check(text) { try { await send(text); return { ok: true }; } catch { return { ok: false }; } },
};
}