feat: add opt-in daily Discord reminders with quiet hours
This commit is contained in:
10
src/reminders/contracts.ts
Normal file
10
src/reminders/contracts.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { z } from "zod";
|
||||
const clock = z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/, "Use HH:MM time");
|
||||
export const reminderInput = z.object({ enabled: z.boolean(), time: clock, quietStart: clock, quietEnd: clock }).strict();
|
||||
export const defaultReminder = { enabled: false, time: "20:00", quietStart: "22:00", quietEnd: "08:00" };
|
||||
export type ReminderPreferences = z.infer<typeof reminderInput>;
|
||||
export type ReminderResponse = ReminderPreferences & { available: boolean; lastDelivery: { date: string; status: string } | null };
|
||||
export function inQuietHours(time: string, start: string, end: string) {
|
||||
if (start === end) return false;
|
||||
return start < end ? time >= start && time < end : time >= start || time < end;
|
||||
}
|
||||
28
src/reminders/routes.ts
Normal file
28
src/reminders/routes.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { Hono } from "hono";
|
||||
import { bodyLimit } from "hono/body-limit";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import type { AppDatabase, AuthEnv, createAuth } from "../auth";
|
||||
import { reminderDeliveries, reminderSettings } from "../db/schema";
|
||||
import { defaultReminder, reminderInput } from "./contracts";
|
||||
|
||||
export function createReminderRoutes(db: AppDatabase, auth: ReturnType<typeof createAuth>, available: boolean, now: () => number) {
|
||||
const app = new Hono<AuthEnv>();
|
||||
app.use("*", auth.requireAuth);
|
||||
app.get("/", c => {
|
||||
const userId = c.get("user").id;
|
||||
const prefs = db.select().from(reminderSettings).where(eq(reminderSettings.userId, userId)).get() ?? defaultReminder;
|
||||
const last = db.select().from(reminderDeliveries).where(eq(reminderDeliveries.userId, userId)).orderBy(desc(reminderDeliveries.updatedAt)).get();
|
||||
return c.json({ enabled: prefs.enabled, time: prefs.time, quietStart: prefs.quietStart, quietEnd: prefs.quietEnd, available,
|
||||
lastDelivery: last ? { date: last.date, status: last.status === "pending" ? "uncertain" : last.status } : null });
|
||||
});
|
||||
app.put("/", auth.requireSameOrigin, bodyLimit({ maxSize: 2048 }), async c => {
|
||||
const parsed = reminderInput.safeParse(await c.req.json().catch(() => null));
|
||||
if (!parsed.success) return c.json({ error: "Choose valid reminder and quiet-hour times." }, 422);
|
||||
if (parsed.data.enabled && !available) return c.json({ error: "Discord reminders are not configured on this server." }, 422);
|
||||
const row = { ...parsed.data, updatedAt: now() };
|
||||
db.insert(reminderSettings).values({ userId: c.get("user").id, ...row })
|
||||
.onConflictDoUpdate({ target: reminderSettings.userId, set: row }).run();
|
||||
return c.json(parsed.data);
|
||||
});
|
||||
return app;
|
||||
}
|
||||
100
src/reminders/worker.test.ts
Normal file
100
src/reminders/worker.test.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { fixture } from "../habits/test-fixture";
|
||||
import { reminderDeliveries, reminderSettings } from "../db/schema";
|
||||
import { sendDueReminders } from "./worker";
|
||||
import { createApi } from "../api";
|
||||
import { defaultReminder, inQuietHours } from "./contracts";
|
||||
import type { DiscordFetch } from "../sharing/routes";
|
||||
const config = { token: "test-only-bot", origin: "https://minabot.example" };
|
||||
async function setup() {
|
||||
const f = fixture();
|
||||
const habit = await f.json("/habits", "POST", { name: "Private habit name", method: "manual" }, 201);
|
||||
f.db.insert(reminderSettings).values({ userId: "alice", ...defaultReminder, enabled: true, updatedAt: 0 }).run();
|
||||
return { f, habit };
|
||||
}
|
||||
function transport(sent: string[]): DiscordFetch {
|
||||
return async (url, init) => {
|
||||
if (url.endsWith("/users/@me/channels")) return Response.json({ id: "223456789012345678" });
|
||||
sent.push(String(init?.body)); return Response.json({ id: "323456789012345678" });
|
||||
};
|
||||
}
|
||||
|
||||
test("reminders follow local time, send only unfinished habits, and deduplicate concurrent workers", async () => {
|
||||
const { f, habit } = await setup(); const sent: string[] = [];
|
||||
try {
|
||||
await sendDueReminders(f.db, config, transport(sent), () => Date.parse("2026-09-04T17:59:00Z")); expect(sent).toHaveLength(0);
|
||||
const now = () => Date.parse("2026-09-04T18:00:00Z");
|
||||
await Promise.all([sendDueReminders(f.db, config, transport(sent), now), sendDueReminders(f.db, config, transport(sent), now)]);
|
||||
expect(sent).toHaveLength(1); expect(sent[0]).not.toContain("Private habit name");
|
||||
expect(JSON.parse(sent[0]!).allowed_mentions.parse).toEqual([]);
|
||||
await sendDueReminders(f.db, config, transport(sent), now); expect(sent).toHaveLength(1);
|
||||
f.setTime("2026-09-05T18:00:00Z");
|
||||
await f.json(`/habits/${habit.id}/days/2026-09-05/progress`, "PUT", { done: true });
|
||||
await sendDueReminders(f.db, config, transport(sent), () => Date.parse("2026-09-05T18:00:00Z")); expect(sent).toHaveLength(1);
|
||||
} finally { f.close(); }
|
||||
});
|
||||
|
||||
test("quiet hours defer until their end and DST overlap sends once", async () => {
|
||||
const { f } = await setup(); const sent: string[] = [];
|
||||
try {
|
||||
expect(inQuietHours("23:00", "22:00", "08:00")).toBe(true);
|
||||
expect(inQuietHours("07:59", "22:00", "08:00")).toBe(true);
|
||||
expect(inQuietHours("08:00", "22:00", "08:00")).toBe(false);
|
||||
f.db.update(reminderSettings).set({ quietStart: "19:00", quietEnd: "21:00" }).run();
|
||||
await sendDueReminders(f.db, config, transport(sent), () => Date.parse("2026-09-04T18:00:00Z")); expect(sent).toHaveLength(0);
|
||||
await sendDueReminders(f.db, config, transport(sent), () => Date.parse("2026-09-04T19:00:00Z")); expect(sent).toHaveLength(1);
|
||||
f.db.update(reminderSettings).set({ time: "02:30", quietStart: "00:00", quietEnd: "00:00" }).run();
|
||||
await sendDueReminders(f.db, config, transport(sent), () => Date.parse("2026-10-25T00:30:00Z"));
|
||||
await sendDueReminders(f.db, config, transport(sent), () => Date.parse("2026-10-25T01:30:00Z")); expect(sent).toHaveLength(2);
|
||||
} finally { f.close(); }
|
||||
});
|
||||
|
||||
test("opt-out during channel creation cancels the message", async () => {
|
||||
const { f } = await setup(); let posts = 0;
|
||||
try {
|
||||
await sendDueReminders(f.db, config, async url => {
|
||||
if (!url.endsWith("/users/@me/channels")) posts++;
|
||||
f.db.update(reminderSettings).set({ enabled: false }).run();
|
||||
return Response.json({ id: "223456789012345678" });
|
||||
}, () => Date.parse("2026-09-04T18:00:00Z"));
|
||||
expect(posts).toBe(0);
|
||||
expect(f.db.select().from(reminderDeliveries).get()?.status).toBe("skipped");
|
||||
} finally { f.close(); }
|
||||
});
|
||||
|
||||
test("rate limits persist their retry deadline; ambiguous sends are not retried", async () => {
|
||||
const { f } = await setup(); let attempts = 0;
|
||||
let timestamp = Date.parse("2026-09-04T18:00:00Z");
|
||||
try {
|
||||
const request: DiscordFetch = async url => {
|
||||
if (url.endsWith("/users/@me/channels")) return Response.json({ id: "223456789012345678" });
|
||||
attempts++;
|
||||
if (attempts === 1) return Response.json({ retry_after: 600 }, { status: 429 });
|
||||
throw new Error("Ambiguous connection failure");
|
||||
};
|
||||
await sendDueReminders(f.db, config, request, () => timestamp);
|
||||
timestamp += 60000; await sendDueReminders(f.db, config, request, () => timestamp); expect(attempts).toBe(1);
|
||||
timestamp += 540000; await sendDueReminders(f.db, config, request, () => timestamp); expect(attempts).toBe(2);
|
||||
expect(f.db.select().from(reminderDeliveries).get()?.status).toBe("uncertain");
|
||||
timestamp += 60000; await sendDueReminders(f.db, config, request, () => timestamp); expect(attempts).toBe(2);
|
||||
} finally { f.close(); }
|
||||
});
|
||||
|
||||
test("reminder preferences require authentication, origin, valid clocks, and configured delivery", async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
expect((await f.request("/reminders", "PUT", { ...defaultReminder, enabled: true })).status).toBe(422);
|
||||
expect((await f.request("/reminders", "PUT", defaultReminder, "a", { Origin: "https://evil.test" })).status).toBe(403);
|
||||
expect((await f.request("/reminders", "GET", undefined, "x")).status).toBe(401);
|
||||
const app = createApi(f.db, { origin: f.origin, clientId: "", clientSecret: "", cookieSecret: "test-secret-at-least-32-characters" }, undefined, undefined, undefined, { token: "test", channelId: "" });
|
||||
const call = (body: unknown) => app.request(`${f.origin}/api/reminders`, { method: "PUT", headers: { Cookie: `minabot_session=${"a".repeat(43)}`, Origin: f.origin, "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
expect((await call({ ...defaultReminder, time: "25:00" })).status).toBe(422);
|
||||
expect((await call({ ...defaultReminder, enabled: true })).status).toBe(200);
|
||||
expect(f.db.select().from(reminderSettings).where(eq(reminderSettings.userId, "alice")).get()?.enabled).toBe(true);
|
||||
expect((await f.json("/reminders", "GET", undefined, 200, "b")).enabled).toBe(false);
|
||||
const exported = await f.json("/account/export"); expect(exported.reminderSettings[0].enabled).toBe(true);
|
||||
await f.request("/account", "DELETE", { confirmation: "DELETE" });
|
||||
expect(f.db.select().from(reminderSettings).all()).toEqual([]);
|
||||
} finally { f.close(); }
|
||||
});
|
||||
86
src/reminders/worker.ts
Normal file
86
src/reminders/worker.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { and, eq, lt } from "drizzle-orm";
|
||||
import type { AppDatabase } from "../auth";
|
||||
import { reminderDeliveries, reminderSettings, reminderWorkerState, users } from "../db/schema";
|
||||
import { HabitService } from "../habits/service";
|
||||
import { localDate } from "../habits/calendar";
|
||||
import { inQuietHours } from "./contracts";
|
||||
import type { DiscordFetch } from "../sharing/routes";
|
||||
|
||||
export type ReminderConfig = { token: string; origin: string };
|
||||
function localClock(timestamp: number, timezone: string) {
|
||||
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: timezone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(timestamp);
|
||||
return `${parts.find(part => part.type === "hour")!.value}:${parts.find(part => part.type === "minute")!.value}`;
|
||||
}
|
||||
export async function sendDueReminders(db: AppDatabase, config: ReminderConfig, request: DiscordFetch = fetch, now: () => number = Date.now) {
|
||||
if (!config.token) return;
|
||||
const cooldown = db.select().from(reminderWorkerState).where(eq(reminderWorkerState.id, "discord")).get();
|
||||
if (cooldown && cooldown.blockedUntil > now()) return;
|
||||
const headers = { Authorization: `Bot ${config.token}`, "Content-Type": "application/json" };
|
||||
const rows = db.select({ prefs: reminderSettings, user: users }).from(reminderSettings).innerJoin(users, eq(users.id, reminderSettings.userId)).where(eq(reminderSettings.enabled, true)).all();
|
||||
// Retain recent delivery history and deduplication records without unbounded growth.
|
||||
db.delete(reminderDeliveries).where(lt(reminderDeliveries.updatedAt, now() - 90 * 86400000)).run();
|
||||
for (const { user } of rows) {
|
||||
function due() {
|
||||
const currentUser = db.select().from(users).where(eq(users.id, user.id)).get();
|
||||
const prefs = db.select().from(reminderSettings).where(eq(reminderSettings.userId, user.id)).get();
|
||||
if (!currentUser || !prefs?.enabled) return null;
|
||||
const timestamp = now(); const clock = localClock(timestamp, currentUser.timezone);
|
||||
if (clock < prefs.time || inQuietHours(clock, prefs.quietStart, prefs.quietEnd)) return null;
|
||||
const service = new HabitService(db, { id: currentUser.id, discordId: currentUser.discordId, username: currentUser.username, displayName: currentUser.globalName ?? currentUser.username, avatarUrl: null, timezone: currentUser.timezone }, timestamp);
|
||||
service.sync();
|
||||
// Avoid sending an artificial "today" after a backwards timezone change.
|
||||
if (service.today !== localDate(timestamp, currentUser.timezone)) return null;
|
||||
const remaining = service.list().filter(habit => { const day = service.day(habit.id, service.today); return day.due && !day.complete; }).length;
|
||||
return remaining ? { date: service.today, remaining } : null;
|
||||
}
|
||||
const initial = due(); if (!initial) continue;
|
||||
const id = db.transaction(tx => {
|
||||
const previous = tx.select().from(reminderDeliveries).where(and(eq(reminderDeliveries.userId, user.id), eq(reminderDeliveries.date, initial.date))).get();
|
||||
if (previous && (previous.status !== "deferred" || (previous.retryAt ?? 0) > now())) return null;
|
||||
const id = previous?.id ?? crypto.randomUUID();
|
||||
if (previous) tx.update(reminderDeliveries).set({ status: "pending", retryAt: null, updatedAt: now() }).where(eq(reminderDeliveries.id, id)).run();
|
||||
else tx.insert(reminderDeliveries).values({ id, userId: user.id, date: initial.date, status: "pending", updatedAt: now() }).run();
|
||||
return id;
|
||||
}, { behavior: "immediate" });
|
||||
if (!id) continue;
|
||||
const update = (status: string, retryAt: number | null = null) => db.update(reminderDeliveries).set({ status, retryAt, updatedAt: now() }).where(eq(reminderDeliveries.id, id)).run();
|
||||
const defer = async (response?: Response) => {
|
||||
const body = response ? await response.json().catch(() => null) as { retry_after?: number } | null : null;
|
||||
const seconds = Math.min(86400, Math.max(60, Number(body?.retry_after) || 60));
|
||||
update("deferred", now() + seconds * 1000);
|
||||
if (response?.status === 429) db.insert(reminderWorkerState).values({ id: "discord", blockedUntil: now() + seconds * 1000 })
|
||||
.onConflictDoUpdate({ target: reminderWorkerState.id, set: { blockedUntil: now() + seconds * 1000 } }).run();
|
||||
};
|
||||
let channel: Response;
|
||||
try { channel = await request("https://discord.com/api/v10/users/@me/channels", {
|
||||
method: "POST", headers, body: JSON.stringify({ recipient_id: user.discordId }), redirect: "error", signal: AbortSignal.timeout(10000),
|
||||
}); } catch { await defer(); continue; }
|
||||
if (channel.status === 429) { await defer(channel); return; }
|
||||
if (channel.status >= 500) { await defer(channel); continue; }
|
||||
const destination = channel.ok ? await channel.json().catch(() => null) as { id?: string } | null : null;
|
||||
if (!destination?.id || !/^\d{17,20}$/.test(destination.id)) { update("failed"); continue; }
|
||||
// A user may opt out or finish a habit while Discord opens the DM channel.
|
||||
const latest = due();
|
||||
if (!latest || latest.date !== initial.date) { update("skipped"); continue; }
|
||||
let response: Response;
|
||||
try { response = await request(`https://discord.com/api/v10/channels/${destination.id}/messages`, {
|
||||
method: "POST", headers, redirect: "error", signal: AbortSignal.timeout(15000),
|
||||
body: JSON.stringify({ content: `A little time for yourself: ${latest.remaining} ${latest.remaining === 1 ? "habit remains" : "habits remain"} today. Check in: ${config.origin}/`,
|
||||
allowed_mentions: { parse: [] }, nonce: createHash("sha256").update(id).digest("hex").slice(0, 24), enforce_nonce: true }),
|
||||
}); } catch { update("uncertain"); continue; }
|
||||
if (response.status === 429) { await defer(response); return; }
|
||||
update(response.ok ? "sent" : response.status >= 500 ? "uncertain" : "failed");
|
||||
}
|
||||
}
|
||||
export function startReminders(db: AppDatabase, config: ReminderConfig) {
|
||||
let running = false;
|
||||
const tick = async () => {
|
||||
if (running) return; running = true;
|
||||
try { await sendDueReminders(db, config); }
|
||||
catch { console.error(JSON.stringify({ event: "reminder_worker_failed", timestamp: new Date().toISOString() })); }
|
||||
finally { running = false; }
|
||||
};
|
||||
const timer = setInterval(() => void tick(), 60000); timer.unref();
|
||||
return { stop: () => clearInterval(timer) };
|
||||
}
|
||||
Reference in New Issue
Block a user