// Platform channel and Peppa's own digest (PEP-60): a Telegram channel set by a superadmin // gets platform events (releases, service outages, restarts) and the daily platform digest; // paired users get the platform digest too (notification event «platform»). No migrations: // everything lives in `settings`; messages go through the Telegram outbox with retries. import { m as tr } from "@peppa/shared/i18n"; import { projects, questions, sessions, tasks, users, type Db } from "@peppa/db"; import { formatTaskKey, loadEnv } from "@peppa/shared"; import { and, asc, eq, gte, isNotNull, isNull, notInArray } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { deliverToUser, hhmmToMinutes, isValidTimezone, localClock, serverTimezone } from "./notifications.ts"; import { FINISHED_SESSION_STATUSES } from "./sessions.ts"; import { getSetting, setSetting } from "./settings.ts"; import { enqueueTelegram } from "./telegram.ts"; import { describeAccount, listAccountUsage } from "./usage.ts"; export const PLATFORM_CHANNEL_EVENTS = ["releases", "services", "digest"] as const; export type PlatformChannelEvent = (typeof PLATFORM_CHANNEL_EVENTS)[number]; export const PLATFORM_CHANNEL_EVENT_NAMES: Record = { releases: tr("Новые версии Peppa FACTORY"), services: tr("Падение, восстановление и перезапуск сервисов"), digest: tr("Ежедневный дайджест"), }; export interface ChannelCheck { ok: boolean; /** Human-readable reason when not ok. */ error: string | null; at: string; } export interface PlatformChannel { /** Telegram Chat ID of the channel («-100…» or «@name»); null = no channel. */ chatId: number | string | null; /** Channel title from the last good check. */ title: string | null; check: ChannelCheck | null; events: Record; digest: { time: string; timezone: string; users: boolean }; setAt?: string; } const KEY = "platform.telegram_channel"; const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/; export function defaultPlatformChannel(): PlatformChannel { return { chatId: null, title: null, check: null, events: { releases: true, services: true, digest: true }, digest: { time: "09:00", timezone: serverTimezone(), users: false }, }; } /** Saved channel settings merged over the defaults. */ export async function getPlatformChannel(db: Db): Promise { const d = defaultPlatformChannel(); const s = (await getSetting>(db, KEY)) ?? {}; const events = { ...d.events }; for (const e of PLATFORM_CHANNEL_EVENTS) if (typeof s.events?.[e] === "boolean") events[e] = s.events[e]; return { chatId: s.chatId ?? null, title: s.title ?? null, check: s.check ?? null, events, digest: { time: s.digest?.time && HHMM.test(s.digest.time) ? s.digest.time : d.digest.time, timezone: s.digest?.timezone && isValidTimezone(s.digest.timezone) ? s.digest.timezone : d.digest.timezone, users: s.digest?.users ?? d.digest.users, }, ...(s.setAt ? { setAt: s.setAt } : {}), }; } /** «-1004371018094» → number, «@name» stays a string; anything else is refused. */ export function parseChatId(raw: string): number | string { const s = raw.trim(); if (/^-?\d{5,20}$/.test(s)) return Number(s); if (/^@[A-Za-z][A-Za-z0-9_]{3,}$/.test(s)) return s; throw new PeppaError(tr("Chat ID канала — число вида -100… или @имя_канала")); } export interface PlatformChannelPatch { chatId?: number | string | null; events?: Partial>; digest?: Partial; } /** Changes the settings; a new Chat ID drops the previous check result. */ export async function setPlatformChannel(db: Db, patch: PlatformChannelPatch): Promise { const cur = await getPlatformChannel(db); const next: PlatformChannel = { ...cur, events: { ...cur.events, ...patch.events }, digest: { ...cur.digest, ...patch.digest } }; if (!HHMM.test(next.digest.time)) throw new PeppaError(tr("Время дайджеста: формат ЧЧ:ММ")); if (!isValidTimezone(next.digest.timezone)) throw new PeppaError(tr("Неизвестная таймзона: {tz}", { tz: next.digest.timezone })); if (patch.chatId !== undefined && String(patch.chatId) !== String(cur.chatId)) { Object.assign(next, { chatId: patch.chatId, title: null, check: null, setAt: new Date().toISOString() }); } await setSetting(db, KEY, next); return next; } // ── check ────────────────────────────────────────────────────────────────────────── export interface BotApiAccess { token?: string; apiUrl?: string; } export const CHANNEL_NOT_VISIBLE = tr("бот не видит канал — добавьте его администратором"); export const CHANNEL_NO_POST = tr("бот не может публиковать — дайте ему право «Публикация сообщений»"); type ApiResult = { ok: true; result: T } | { ok: false; error_code?: number; description?: string }; async function botApi(tg: BotApiAccess, method: string, params: Record): Promise> { const token = tg.token ?? process.env.TELEGRAM_BOT_TOKEN; if (!token) return { ok: false, description: tr("TELEGRAM_BOT_TOKEN не задан") }; const base = tg.apiUrl ?? process.env.TELEGRAM_API_URL ?? "https://api.telegram.org"; try { const res = await fetch(`${base}/bot${token}/${method}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(params), signal: AbortSignal.timeout(15_000), }); return (await res.json()) as ApiResult; } catch (e) { return { ok: false, description: (e as Error).message }; } } /** * Whether the bot can post to the channel: getMe → getChat → getChatMember. Saves the result * (and the channel title) into the settings and returns them. */ export async function checkPlatformChannel(db: Db, tg: BotApiAccess = {}, o: { now?: Date } = {}): Promise { const cur = await getPlatformChannel(db); if (cur.chatId == null) throw new PeppaError(tr("Канал платформы не задан")); const at = (o.now ?? new Date()).toISOString(); const verdict = async (): Promise<{ ok: boolean; error: string | null; title: string | null }> => { const me = await botApi<{ id: number }>(tg, "getMe", {}); if (!me.ok) return { ok: false, error: `Telegram: ${me.description ?? tr("нет ответа")}`, title: null }; const chat = await botApi<{ title?: string; type: string }>(tg, "getChat", { chat_id: cur.chatId }); if (!chat.ok) { const gone = chat.error_code === 400 || chat.error_code === 403 || /chat not found|not a member|kicked/i.test(chat.description ?? ""); return { ok: false, error: gone ? CHANNEL_NOT_VISIBLE : `Telegram: ${chat.description ?? tr("нет ответа")}`, title: null }; } const title = chat.result.title ?? null; const member = await botApi<{ status: string; can_post_messages?: boolean }>(tg, "getChatMember", { chat_id: cur.chatId, user_id: me.result.id }); if (!member.ok) return { ok: false, error: `Telegram: ${member.description ?? tr("нет ответа")}`, title }; const m = member.result; const canPost = chat.result.type === "channel" ? m.status === "creator" || (m.status === "administrator" && m.can_post_messages !== false) : m.status !== "left" && m.status !== "kicked"; return canPost ? { ok: true, error: null, title } : { ok: false, error: m.status === "left" || m.status === "kicked" ? CHANNEL_NOT_VISIBLE : CHANNEL_NO_POST, title }; }; const v = await verdict(); const next: PlatformChannel = { ...cur, title: v.title ?? cur.title, check: { ok: v.ok, error: v.error, at } }; await setSetting(db, KEY, next); return next; } /** «канал подключён — Peppa News» / the reason / «не проверен». */ export function describeChannel(c: PlatformChannel): string { if (c.chatId == null) return tr("канал не задан"); if (!c.check) return `${c.chatId}: ${tr("не проверен")}`; return c.check.ok ? (c.title ? tr("канал подключён — {title}", { title: c.title }) : tr("канал подключён")) : `${c.chatId}: ${c.check.error}`; } /** Watchdog: re-checks a channel that isn't working yet at most once an hour. */ export async function recheckPlatformChannel(db: Db, o: { now?: Date; tg?: BotApiAccess; log?: (m: string) => void } = {}): Promise { const c = await getPlatformChannel(db); const now = o.now ?? new Date(); if (c.chatId == null || c.check?.ok) return false; if (c.check && now.getTime() - Date.parse(c.check.at) < 3600_000) return false; const r = await checkPlatformChannel(db, o.tg, { now }); if (r.check?.ok) o.log?.(`platform channel: ${describeChannel(r)}`); return true; } // ── posting ──────────────────────────────────────────────────────────────────────── const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">"); /** * Queues a message to the platform channel if it is connected and the event is on. Service * events use `mon:` keys so the watchdog delivers them itself when the bot is down. */ export async function postToChannel(db: Db, event: PlatformChannelEvent, dedupeKey: string, html: string, channel?: PlatformChannel): Promise { const c = channel ?? (await getPlatformChannel(db)); if (c.chatId == null || !c.check?.ok || !c.events[event]) return false; return enqueueTelegram(db, { dedupeKey, method: "sendMessage", params: { chat_id: c.chatId, text: html, parse_mode: "HTML", link_preview_options: { is_disabled: true } }, }); } // ── builds and releases ──────────────────────────────────────────────────────────── /** Key of the project that is Peppa itself. */ export const platformProjectKey = () => process.env.PEPPA_PLATFORM_KEY || "PEP"; export interface PlatformBuild { version: string; commit: string; at: string; /** Platform stories found in the commits since the previous build. */ tasks: string[]; } const BUILD = "platform.build"; const BUILDS = "platform.builds"; export const getPlatformBuild = (db: Db) => getSetting(db, BUILD); /** Announced builds, newest last (the digest lists the ones since its previous run). */ export async function recentPlatformBuilds(db: Db): Promise { return (await getSetting(db, BUILDS)) ?? []; } const short = (sha: string) => sha.slice(0, 7); /** Titles of the platform's stories by key (missing ones are left out). */ async function storyTitles(db: Db, keys: string[]): Promise> { const pk = platformProjectKey(); const [p] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, pk)); const out = new Map(); if (!p || !keys.length) return out; const rows = await db.select({ number: tasks.number, title: tasks.title }).from(tasks).where(eq(tasks.projectId, p.id)); for (const r of rows) out.set(formatTaskKey(pk, r.number), r.title); return out; } function storyLine(webUrl: string, key: string, title: string | undefined): string { return ` • ${esc(key)}${title ? ` ${esc(title.length > 70 ? `${title.slice(0, 70)}…` : title)}` : ""}`; } /** * A new build of Peppa is live (watchdog, runner/platform-build.ts). The first one is only * remembered; later ones are posted to the channel: «🚀 Peppa v0.16.0 · b1c2d3e» + stories. */ export async function announcePlatformBuild(db: Db, b: Omit, o: { now?: Date } = {}): Promise { const prev = await getPlatformBuild(db); if (prev?.commit === b.commit) return false; const build: PlatformBuild = { ...b, at: (o.now ?? new Date()).toISOString() }; await setSetting(db, BUILD, build); if (!prev) return false; await setSetting(db, BUILDS, [...(await recentPlatformBuilds(db)), build].slice(-20)); return postToChannel(db, "releases", `pch:release:${b.commit}`, renderBuild(build, await storyTitles(db, build.tasks))); } export function renderBuild(b: PlatformBuild, titles: Map = new Map()): string { const webUrl = loadEnv().PEPPA_WEB_URL; const lines = [`🚀 Peppa v${esc(b.version)} · ${esc(short(b.commit))}`]; if (b.tasks.length) lines.push(`${tr("Задачи")}: ${b.tasks.map(esc).join(", ")}`, ...b.tasks.slice(0, 15).map((k) => storyLine(webUrl, k, titles.get(k)))); return lines.join("\n"); } // ── platform digest ──────────────────────────────────────────────────────────────── export interface PlatformDigest { since: Date; build: PlatformBuild | null; /** Builds announced since the previous digest. */ builds: PlatformBuild[]; /** Platform stories finished since the previous digest. */ done: { key: string; title: string }[]; services: { name: string; ok: boolean; state: string }[]; runners: number; questions: number; rateLimited: number; limits: string[]; } /** Changes of Peppa since `since` and the current state of the platform. */ export async function buildPlatformDigest(db: Db, o: { since: Date; now?: Date }): Promise { const now = o.now ?? new Date(); const { serviceStatus, describeState, SERVICE_NAMES } = await import("./monitor.ts"); const pk = platformProjectKey(); const [p] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, pk)); const done = p ? ( await db .select({ number: tasks.number, title: tasks.title }) .from(tasks) .where(and(eq(tasks.projectId, p.id), eq(tasks.status, "done"), gte(tasks.updatedAt, o.since))) .orderBy(asc(tasks.number)) ).map((t) => ({ key: formatTaskKey(pk, t.number), title: t.title })) : []; const live = await db.select({ status: sessions.status }).from(sessions).where(notInArray(sessions.status, FINISHED_SESSION_STATUSES)); const open = await db.select({ id: questions.id }).from(questions).where(isNull(questions.answeredAt)); const services = (await serviceStatus(db, { now })).filter((s) => s.heartbeat).map((s) => ({ name: SERVICE_NAMES[s.service], ok: s.ok, state: describeState(s) })); const limits = (await listAccountUsage(db, { now: now.getTime() })) .filter((a) => a.limitedUntil || (a.fiveHour?.pct ?? 0) >= 50 || (a.sevenDay?.pct ?? 0) >= 50) .map(describeAccount); return { since: o.since, build: await getPlatformBuild(db), builds: (await recentPlatformBuilds(db)).filter((b) => Date.parse(b.at) >= o.since.getTime()), done, services, runners: live.length, questions: open.length, rateLimited: live.filter((s) => s.status === "rate_limited").length, limits, }; } /** Nothing new and nothing going on: the digest isn't sent. */ export const platformDigestEmpty = (d: PlatformDigest) => !d.done.length && !d.builds.length && !d.runners && !d.questions && d.services.every((s) => s.ok); export function renderPlatformDigest(d: PlatformDigest): string { const webUrl = loadEnv().PEPPA_WEB_URL; const lines = [`🐷 ${tr("Дайджест Peppa FACTORY")}`]; if (d.done.length || d.builds.length) { lines.push("", `${tr("Что нового")}`); for (const b of d.builds) lines.push(`🚀 v${esc(b.version)} · ${esc(short(b.commit))}`); if (d.done.length) lines.push(`✅ ${tr("Сделано")}: ${d.done.map((t) => esc(t.key)).join(", ")}`, ...d.done.slice(0, 12).map((t) => storyLine(webUrl, t.key, t.title))); if (d.done.length > 12) lines.push(` …${tr("и ещё {n}", { n: d.done.length - 12 })}`); } lines.push("", `${tr("Сейчас")}`); if (d.build) lines.push(`${tr("Версия")}: v${esc(d.build.version)} · ${esc(short(d.build.commit))}`); if (d.services.length) lines.push(`${tr("Сервисы")}: ${d.services.map((s) => `${s.ok ? "✅" : "⚠️"} ${esc(s.name)}${s.ok ? "" : ` (${esc(s.state)})`}`).join(", ")}`); lines.push( d.rateLimited ? tr("Агентов за работой: {n} (ждут сброса лимита: {limited})", { n: d.runners, limited: d.rateLimited }) : tr("Агентов за работой: {n}", { n: d.runners }), tr("Вопросов: {n}", { n: d.questions }), ); if (d.limits.length) lines.push(`${tr("Лимиты")}: ${d.limits.map(esc).join("; ")}`); return lines.join("\n"); } const LAST = "platform.digest.last"; const WINDOW_MIN = 180; /** * Watchdog tick: at the platform's digest time (once a local day) builds the digest over the * time since the previous one and sends it to the channel and, when enabled, to every paired * user who keeps the «platform» notification on. Returns where it went. */ export async function platformDigestTick(db: Db, o: { now?: Date; force?: boolean; log?: (m: string) => void } = {}): Promise<{ channel: boolean; users: number } | null> { const now = o.now ?? new Date(); const c = await getPlatformChannel(db); const clock = localClock(now, c.digest.timezone); const target = hhmmToMinutes(c.digest.time); const last = await getSetting<{ date: string; at: string }>(db, LAST); if (!o.force) { if (clock.minutes < target || clock.minutes >= target + WINDOW_MIN) return null; if (last?.date === clock.date) return null; } const toChannel = c.chatId != null && !!c.check?.ok && c.events.digest; if (!toChannel && !c.digest.users) return null; await setSetting(db, LAST, { date: clock.date, at: now.toISOString() }); const since = last ? new Date(last.at) : new Date(now.getTime() - 24 * 3600_000); const d = await buildPlatformDigest(db, { since, now }); if (platformDigestEmpty(d)) { o.log?.("platform digest: nothing to report"); return { channel: false, users: 0 }; } const text = renderPlatformDigest(d); const channel = toChannel && (await postToChannel(db, "digest", `pch:digest:${clock.date}`, text, c)); let sent = 0; if (c.digest.users) { const paired = (await db.select().from(users).where(isNotNull(users.telegramChatId))).filter((u) => !u.disabledAt); for (const u of paired) { const r = await deliverToUser(db, u, { event: "platform", dedupeKey: `pdigest:${clock.date}:${u.telegramChatId}`, telegram: { params: { text, parse_mode: "HTML", link_preview_options: { is_disabled: true } } }, now, }); if (r.telegram) sent++; } } o.log?.(`platform digest: channel ${channel ? "yes" : "no"}, users ${sent}`); return { channel, users: sent }; }