import { all, chunks, first, placeholders, run } from "../db"; import { randomId } from "../crypto"; import { publicUrl } from "../events/emit"; import { CATEGORY_INFO, NOTIFICATION_CATEGORIES } from "~/lib/notification-categories"; import type { DigestMode, NotificationCategory } from "~/lib/notification-categories"; import type { EmailFooter } from "../email"; export type CategoryPref = { web: boolean; email: boolean; digest: DigestMode }; /** Unsubscribe targets: a category, or the legacy participating/watching email switches. */ export type UnsubscribeTarget = NotificationCategory | "participating" | "watching"; const HOUR_MS = 60 * 60 * 1000; /** Per-recipient email budget per hour; overflow is folded into the next digest instead of being dropped. */ export const EMAILS_PER_HOUR = 20; function defaults(category: NotificationCategory): CategoryPref { const info = CATEGORY_INFO[category]; return { web: info.web, email: info.email, digest: "off" }; } type PrefRow = { user_id: string; category: string; web: number; email: number; digest: string }; function fromRow(category: NotificationCategory, row: PrefRow | undefined): CategoryPref { if (!row) return defaults(category); const digest = row.digest === "daily" && CATEGORY_INFO[category].digestable ? "daily" : "off"; return { web: row.web === 1, email: row.email === 1, digest }; } export async function loadCategoryPrefs(userId: string): Promise> { const rows = await all("SELECT * FROM notification_category_prefs WHERE user_id = ?", userId); const byCategory = new Map(rows.map((row) => [row.category, row])); const out = {} as Record; for (const category of NOTIFICATION_CATEGORIES) out[category] = fromRow(category, byCategory.get(category)); return out; } export async function categoryPrefsFor( userIds: string[], category: NotificationCategory, ): Promise> { const out = new Map(); for (const part of chunks(userIds)) { const rows = await all( `SELECT * FROM notification_category_prefs WHERE category = ? AND user_id IN (${placeholders(part.length)})`, category, ...part, ); const byUser = new Map(rows.map((row) => [row.user_id, row])); for (const userId of part) out.set(userId, fromRow(category, byUser.get(userId))); } return out; } export async function saveCategoryPref( userId: string, category: NotificationCategory, pref: CategoryPref, ): Promise { const digest = CATEGORY_INFO[category].digestable ? pref.digest : "off"; await run( `INSERT INTO notification_category_prefs (user_id, category, web, email, digest, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (user_id, category) DO UPDATE SET web = excluded.web, email = excluded.email, digest = excluded.digest, updated_at = excluded.updated_at`, userId, category, pref.web ? 1 : 0, pref.email ? 1 : 0, digest, Date.now(), ); } async function unsubscribeToken(userId: string): Promise { const existing = await first<{ token: string }>( "SELECT token FROM notification_unsubscribe_tokens WHERE user_id = ?", userId, ); if (existing) return existing.token; await run( "INSERT OR IGNORE INTO notification_unsubscribe_tokens (user_id, token, created_at) VALUES (?, ?, ?)", userId, randomId(32), Date.now(), ); const row = await first<{ token: string }>( "SELECT token FROM notification_unsubscribe_tokens WHERE user_id = ?", userId, ); return row?.token ?? ""; } export async function userForUnsubscribeToken(token: string): Promise { const row = await first<{ user_id: string }>( "SELECT user_id FROM notification_unsubscribe_tokens WHERE token = ?", token, ); return row?.user_id ?? null; } const REASON_COPY: Record = { participating: "You are receiving this because you are participating in this thread.", watching: "You are receiving this because you are watching this repository.", ...(Object.fromEntries( NOTIFICATION_CATEGORIES.map((category) => [ category, `You are receiving this because ${CATEGORY_INFO[category].label.toLowerCase()} emails are on.`, ]), ) as Record), }; export async function emailFooter(userId: string, target: UnsubscribeTarget): Promise { const token = await unsubscribeToken(userId); const query = new URLSearchParams({ token, category: target }); return { reason: REASON_COPY[target], manageUrl: publicUrl("/settings/notifications"), unsubscribeUrl: token ? publicUrl(`/email/unsubscribe?${query}`) : null, }; } /** Turns off email for one unsubscribe target; web notifications are left alone. */ export async function unsubscribe(userId: string, target: UnsubscribeTarget): Promise { if (target === "participating" || target === "watching") { const column = target === "participating" ? "email_participating" : "email_watching"; await run( `INSERT INTO notification_settings (user_id, ${column}, updated_at) VALUES (?, 0, ?) ON CONFLICT (user_id) DO UPDATE SET ${column} = 0, updated_at = excluded.updated_at`, userId, Date.now(), ); return; } const current = (await categoryPrefsFor([userId], target)).get(userId) ?? defaults(target); await saveCategoryPref(userId, target, { ...current, email: false }); } /** Counts one email against the recipient's hourly budget; false means the budget is spent. */ export async function takeEmailBudget(userId: string): Promise { const window = Math.floor(Date.now() / HOUR_MS) * HOUR_MS; const row = await first<{ sent: number }>( `INSERT INTO notification_email_counters (user_id, window_start, sent) VALUES (?, ?, 1) ON CONFLICT (user_id, window_start) DO UPDATE SET sent = sent + 1 RETURNING sent`, userId, window, ); return (row?.sent ?? 1) <= EMAILS_PER_HOUR; } export async function pruneEmailCounters(): Promise { await run("DELETE FROM notification_email_counters WHERE window_start < ?", Date.now() - 2 * HOUR_MS); }