peppa/packages/core/src/night-quiet.ts
2026-11-18 00:51:15 +05:00

49 lines
2.2 KiB
TypeScript

// PEP-208: the platform's night silence. From 23:00 to 08:00 (the platform's time zone,
// PEPPA_TZ) nobody — the superadmin included — gets a new Telegram message or browser push.
// It is applied where the queues are read (dueOutbox, pendingMonitorMessages,
// flushPushOutbox), so every place that sends goes through it: night messages wait in the
// queue and go out in the morning. Edits of messages already sent pass (they wake nobody);
// the bot's direct replies to what a person wrote at night are not queued and pass too.
// PEPPA_NIGHT_QUIET: "HH:MM-HH:MM" or "off". Standalone (no notifications.ts import):
// telegram.ts imports it.
export const NIGHT_QUIET_DEFAULT = "23:00-08:00";
const RANGE = /^([01]\d|2[0-3]):([0-5]\d)-([01]\d|2[0-3]):([0-5]\d)$/;
/** The window in minutes since local midnight, or null — no night silence. */
export function nightQuietWindow(env: NodeJS.ProcessEnv = process.env): { from: number; to: number } | null {
const raw = (env.PEPPA_NIGHT_QUIET ?? NIGHT_QUIET_DEFAULT).trim().toLowerCase();
if (raw === "off" || raw === "") return null;
const m = RANGE.exec(raw) ?? RANGE.exec(NIGHT_QUIET_DEFAULT)!;
const from = Number(m[1]) * 60 + Number(m[2]);
const to = Number(m[3]) * 60 + Number(m[4]);
return from === to ? null : { from, to };
}
const platformZone = () => process.env.PEPPA_TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
function localMinutes(now: Date, tz: string): number {
const parts = Object.fromEntries(
new Intl.DateTimeFormat("en-GB", { timeZone: tz, hour: "2-digit", minute: "2-digit", hourCycle: "h23" })
.formatToParts(now)
.map((p) => [p.type, p.value]),
);
return Number(parts.hour) * 60 + Number(parts.minute);
}
/** True inside the night silence: new messages to people wait for the morning. */
export function inNightQuiet(now: Date = new Date(), env: NodeJS.ProcessEnv = process.env): boolean {
const w = nightQuietWindow(env);
if (!w) return false;
let tz = platformZone();
let m: number;
try {
m = localMinutes(now, tz);
} catch {
tz = "UTC";
m = localMinutes(now, tz);
}
return w.from < w.to ? m >= w.from && m < w.to : m >= w.from || m < w.to;
}