v4: weekly digests and monthly recaps go out by email, every email is written once as Markdown in the app's one catalog, and a review of the last two commits removes what they stated twice — users get a weekly digest (what happened to them, what the people and playlists they follow posted, the week's top dumps, the community) and a monthly recap (the month's top dumps and the community), both on by default, in their own style and scheme. digest-service sends what is due every quarter of an hour from digest_schedule (migration 0020), which holds each user's rolling 7- or 30-day period; existing users' first periods are spread over the coming week or month, a digest more than a period late covers the last full one, an empty one isn't sent, and an address like admin@localhost is skipped. Each digest carries a one-click unsubscribe (List-Unsubscribe and List-Unsubscribe-Post, POST /api/users/unsubscribe) and a link to the new /unsubscribe page, which asks before turning that cadence off, since mail scanners open every link; the token (lib/jwt) names the user and the cadence and never expires. The welcome email now says the digests are on. The emails' words moved out of a hand-written api/mail/strings.ts into the Lingui catalogs the interface uses: lingui extracts api/mail/ too, the catalogs moved to a top-level locales/ that both halves read, compile emits ES modules the server imports (api/mail/i18n.ts), messages take ICU plurals, and the labels the settings tab, the unsubscribe page and the emails share are one message each (their French had already drifted apart). Each template writes its email once as Markdown, which is the plain-text part, and EmailKit.render draws its blocks in the style (a lone link is a button, a list item starting with an image a thumbnail row, a numbered list a ranking, --- the footer), so no string is declared for an HTML and a text version; user text is escaped for Markdown, which the welcome body didn't do for usernames, whose _ read as emphasis. paint() set colors before a border-top shorthand that reset them, so every divider was black. The review also gave one home to what was written twice: the locale list (shared/locale.ts, read by lingui.config, the client, the server and its catalog loader), the base style and default scheme (shared/theme.ts), an email's look (lookOf, which digest-service, welcome and reset share), whether email is on (EMAIL_ENABLED, read by email-service and index.html), a setting's column and its default in the digests' SQL (SETTINGS_COLUMNS, DEFAULT_SETTINGS), the unsubscribe token (made once, not parsed back from a URL), AuthProvider's compare-and-store, ThemeProvider's twin style and scheme code (useThemeChoice), the test JWT encoder, and duplicate digest messages. The email palettes stay a flattened copy of the themes' tokens, now under a test that caught Times' secondary and link colors drifting. The Dockerfile copies api/mail and locales so the build extracts the emails' messages and the server finds its catalogs, and deno.json maps @lingui/core for the runtime image. 236 backend tests (new: digest building, sending, catch-up, scheduling and unsubscribing; the Markdown renderer; French from the catalog; palettes against themes; the stagger migration; unsubscribe tokens) and 661 frontend tests (new: the unsubscribe page) pass, and tsc, eslint, doc:lint, deno check, deno lint and deno fmt are clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-04 22:14:46 +00:00
parent 89014639cb
commit 7960d74c55
60 changed files with 3778 additions and 534 deletions

View File

@@ -28,14 +28,14 @@ Deno.test("runMigrations: a fresh database is left as schema.sql made it", () =>
.get() as {
n: number;
};
assertEquals(applied.n, 19);
assertEquals(applied.n, 20);
// Running again applies nothing.
runMigrations(db);
assertEquals(
(db.prepare(`SELECT COUNT(*) as n FROM schema_migrations;`).get() as {
n: number;
}).n,
19,
20,
);
db.close();
});

View File

@@ -0,0 +1,35 @@
import "../../setup.ts";
import { assert, assertEquals } from "@std/assert";
import { DatabaseSync } from "node:sqlite";
import { up as up0020 } from "../../../db/migrations/0020_digest_schedule.ts";
Deno.test("migration 0020 spreads existing users' first digests over the coming period", () => {
const db = new DatabaseSync(":memory:");
db.exec(`CREATE TABLE users (id TEXT PRIMARY KEY);`);
const ids = Array.from({ length: 40 }, () => crypto.randomUUID());
for (const id of ids) {
db.prepare(`INSERT INTO users (id) VALUES (?);`).run(id);
}
const before = Date.now();
up0020(db);
up0020(db); // idempotent
const rows = db.prepare(
`SELECT user_id, cadence, window_start FROM digest_schedule;`,
).all() as { user_id: string; cadence: string; window_start: string }[];
assertEquals(rows.length, 80);
const due = (cadence: string, days: number) =>
rows.filter((r) => r.cadence === cadence).map((r) =>
new Date(r.window_start).getTime() + days * 86_400_000
);
for (const [cadence, days] of [["weekly", 7], ["monthly", 30]] as const) {
const dues = due(cadence, days);
// Each first digest falls due within the coming period, not all at once.
assert(
dues.every((t) =>
t >= before - 1000 && t <= Date.now() + days * 86_400_000
),
);
assert(new Set(dues.map((t) => Math.floor(t / 3_600_000))).size > 10);
}
db.close();
});

View File

@@ -35,6 +35,7 @@ const TABLES = [
"attachments",
"chat_messages",
"user_settings",
"digest_schedule",
"categories",
"playlists",
"dumps",

View File

@@ -5,9 +5,11 @@ import {
createJWT,
createMediaToken,
createPasswordResetToken,
createUnsubscribeToken,
verifyJWT,
verifyMediaToken,
verifyPasswordResetToken,
verifyUnsubscribeToken,
} from "../../lib/jwt.ts";
const KEY = new TextEncoder().encode("test-secret-test-secret-test-secret");
@@ -60,3 +62,24 @@ Deno.test("verifyJWT: refuses a bad signature, an expired token, garbage", async
assertEquals(await verifyJWT("not.a.jwt"), null);
});
Deno.test("an unsubscribe token names its user and cadence, and is nothing else", async () => {
const userId = crypto.randomUUID();
const token = await createUnsubscribeToken(userId, "monthly");
assertEquals(await verifyUnsubscribeToken(token), {
userId,
cadence: "monthly",
});
assertEquals(await verifyJWT(token), null);
assertEquals(await verifyMediaToken(token), null);
assertEquals(
await verifyUnsubscribeToken(await createMediaToken(userId)),
null,
);
const yearly = await new SignJWT({
purpose: "unsubscribe",
userId,
cadence: "yearly",
}).setProtectedHeader({ alg: "HS256" }).sign(KEY);
assertEquals(await verifyUnsubscribeToken(yearly), null);
});

View File

@@ -0,0 +1,104 @@
import "../setup.ts";
import { assert, assertFalse, assertStringIncludes } from "@std/assert";
import { type DigestContent, renderDigestEmail } from "../../mail/digest.ts";
const links = {
notifications: "https://g.test/notifications",
followed: "https://g.test/~/followed",
chat: "https://g.test/?chat=open",
settings: "https://g.test/users/ann/~/settings",
unsubscribe: "https://g.test/unsubscribe?token=t",
};
const dump = (title: string, over = {}) => ({
title,
url: "https://g.test/dumps/x",
poster: "bob",
domain: "example.com",
thumbnail: "https://g.test/api/thumbnails/x?v=1",
votes: 1,
comments: 0,
mine: false,
...over,
});
Deno.test("renderDigestEmail: the weekly digest escapes what users wrote and links to unsubscribe", () => {
const content: DigestContent = {
cadence: "weekly",
from: new Date("2026-09-27T08:00:00Z"),
to: new Date("2026-10-04T08:00:00Z"),
reader: "ann",
activity: {
counts: { upvotes: 12, followers: 1 },
highlights: [{
kind: "comment",
who: "bob",
target: { title: "<script>x</script>", url: "https://g.test/dumps/y" },
quote: "a <b>bold</b> claim",
at: new Date("2026-09-30T10:00:00Z"),
}],
total: 13,
},
network: { dumps: [dump("Net & work")], more: 2 },
top: [dump("Mine", { mine: true, votes: 4 })],
community: null,
links,
};
const email = renderDigestEmail(content, { style: "smooth", scheme: "auto" });
assertStringIncludes(email.subject, "Your week on gerbeur, Sep 27");
assertFalse(email.html.includes("<script>x"));
assertStringIncludes(email.html, "&lt;script&gt;x&lt;/script&gt;");
assertStringIncludes(email.html, "a &lt;b&gt;bold&lt;/b&gt; claim");
assertStringIncludes(email.html, "Net &amp; work");
assertStringIncludes(email.html, "2 more on your Followed feed");
assertStringIncludes(email.html, ">yours</span>");
assertStringIncludes(email.html, `href="${links.unsubscribe}"`);
assertStringIncludes(
email.html,
"12 upvotes, 1 new follower, and 3 new dumps",
);
// The plain-text part is Markdown, with what users wrote escaped.
assertStringIncludes(email.text, "# Your week, ann");
assertStringIncludes(email.text, "## From people you follow");
assertStringIncludes(
email.text,
"[Turn off weekly digests](https://g.test/unsubscribe?token=t)",
);
assertStringIncludes(
email.text,
"[\\<script\\>x\\</script\\>](https://g.test/dumps/y)",
);
assertStringIncludes(email.text, " > a \\<b\\>bold\\</b\\> claim");
assertFalse(email.html.includes("Community"));
});
Deno.test("renderDigestEmail: the monthly recap leads with a wide image and the month's totals", () => {
const content: DigestContent = {
cadence: "monthly",
from: new Date("2026-09-04T08:00:00Z"),
to: new Date("2026-10-04T08:00:00Z"),
reader: "ann",
activity: null,
network: null,
top: [dump("First"), dump("Second"), dump("Third"), dump("Fourth")],
community: {
members: [{ username: "cy", invitedBy: "ann" }],
membersMore: 0,
playlists: [],
playlistsMore: 0,
chatMessages: 1284,
totals: { dumps: 203, upvotes: 911, comments: 402 },
},
links,
};
const email = renderDigestEmail(content, {
style: "melange",
scheme: "light",
});
assertStringIncludes(email.subject, "The month on gerbeur");
assertStringIncludes(email.html, `width="528"`);
assertStringIncludes(email.html, "1,284");
assertStringIncludes(email.html, "invited by you");
assertStringIncludes(email.html, "Turn off monthly recaps");
// Only #2 and #3 get a thumbnail beside the hero.
assert(email.html.match(/<img[^>]*width="64"/g)?.length === 2);
});

View File

@@ -10,13 +10,12 @@ import { EMAIL_STYLES } from "../../mail/styles.ts";
import { STYLE_NAMES } from "../../../shared/theme.ts";
const doc = (kit: EmailKit) =>
kit.document({
kit.render({
subject: "S <1>",
preheader: "P & Q",
title: "T",
body: kit.para("body"),
footer: kit.footer("why", [["Settings", "https://x.test/?a=1&b=2"]]),
});
markdown:
"# T\n\nbody\n\n## One\n\nfirst\n\n## Two\n\nsecond\n\n---\n\nwhy\n\n[Settings](https://x.test/?a=1&b=2)",
}).html;
Deno.test("esc: user text never becomes markup", () => {
assertEquals(
@@ -26,7 +25,7 @@ Deno.test("esc: user text never becomes markup", () => {
});
Deno.test("EmailKit: auto inlines light and recolors in a dark media block", () => {
const html = doc(new EmailKit({ style: "smooth", scheme: "auto" }, "en"));
const html = doc(new EmailKit({ style: "smooth", scheme: "auto" }));
const { light, dark } = EMAIL_STYLES.smooth;
assertStringIncludes(html, `background-color:${light.card}`);
assertStringIncludes(html, "@media (prefers-color-scheme:dark)");
@@ -44,36 +43,70 @@ Deno.test("EmailKit: auto inlines light and recolors in a dark media block", ()
Deno.test("EmailKit: a chosen scheme is the only one sent", () => {
const { light, dark } = EMAIL_STYLES.kanagawa;
const darkHtml = doc(
new EmailKit({ style: "kanagawa", scheme: "dark" }, "en"),
new EmailKit({ style: "kanagawa", scheme: "dark" }),
);
assertStringIncludes(darkHtml, `background-color:${dark.card}`);
assertFalse(darkHtml.includes(light.card));
assertFalse(darkHtml.includes("prefers-color-scheme"));
assertStringIncludes(darkHtml, `content="dark"`);
const lightHtml = doc(
new EmailKit({ style: "kanagawa", scheme: "light" }, "fr"),
new EmailKit({ style: "kanagawa", scheme: "light" }),
);
assertStringIncludes(lightHtml, `background-color:${light.card}`);
assertStringIncludes(lightHtml, `<html lang="fr">`);
assertFalse(lightHtml.includes("prefers-color-scheme"));
});
Deno.test("EmailKit: every style draws its own card and font", () => {
for (const name of STYLE_NAMES) {
const style = EMAIL_STYLES[name];
const html = doc(new EmailKit({ style: name, scheme: "light" }, "en"));
const html = doc(new EmailKit({ style: name, scheme: "light" }));
assertStringIncludes(html, `background-color:${style.light.card}`);
assertStringIncludes(html, `font-family:${style.font}`);
assertEquals(html.includes("fonts.googleapis.com"), !!style.webFont, name);
}
// The rainbow and the hard shadow are what GeoCities and Brutalist look like.
const geo = new EmailKit({ style: "geocities", scheme: "light" }, "en");
const geo = new EmailKit({ style: "geocities", scheme: "light" });
assertStringIncludes(
geo.section("A", "", false),
"linear-gradient(90deg,#ff004d",
);
const brutal = doc(
new EmailKit({ style: "brutalist", scheme: "light" }, "en"),
new EmailKit({ style: "brutalist", scheme: "light" }),
);
assert(brutal.includes("box-shadow:5px 5px 0"));
});
Deno.test("EmailKit.render: the Markdown is the text part, and its blocks take the style", () => {
const kit = new EmailKit({ style: "smooth", scheme: "light" });
const markdown = [
"*Eyebrow*",
"# Title",
"## Section",
"**12** upvotes",
"- **@lou** said hi *Fri*\n > a quote",
"1. ![](https://x.test/t.png) [A dump](https://x.test/d) *yours* · by @lou",
"[Do it](https://x.test/go)",
"```\nhttps://x.test/raw\n```",
"*A note.*",
"---",
"Why you get this.",
].join("\n\n");
const { html, text } = kit.render({ subject: "S", preheader: "P", markdown });
assertEquals(text, markdown);
const { light } = EMAIL_STYLES.smooth;
assertStringIncludes(html, "text-transform:uppercase;margin:0 0 8px;");
assertStringIncludes(html, ">Title</h1>");
assertStringIncludes(html, `font-size:22px;`);
assertStringIncludes(html, "“a quote”");
assertStringIncludes(html, `>1</td>`);
assertStringIncludes(html, `width="64" height="48"`);
assertStringIncludes(html, `>A dump</a>`);
assertStringIncludes(html, `>yours</span>`);
assertStringIncludes(html, `>by @lou</div>`);
assertStringIncludes(html, `background-color:${light.accent};`);
assertStringIncludes(html, ">Do it</a></td></tr></table>");
assertStringIncludes(html, "word-break:break-all;");
assertStringIncludes(html, "Why you get this.</td>");
// A divider takes its color after the shorthand that would reset it.
assertFalse(html.includes(`border-color:${light.rule};border-top`));
});

View File

@@ -0,0 +1,40 @@
import "../setup.ts";
import { assertEquals } from "@std/assert";
import { EMAIL_STYLES, type EmailPalette } from "../../mail/styles.ts";
import { STYLE_NAMES } from "../../../shared/theme.ts";
// The email palettes are copies of the themes' tokens, flattened for mail
// clients. The roles that map one to one must stay equal to the theme's.
const TOKENS: [keyof EmailPalette, string][] = [
["outer", "--color-bg"],
["card", "--color-surface"],
["text", "--color-text"],
["sec", "--color-text-secondary"],
["muted", "--color-text-muted"],
["accent", "--color-accent"],
["link", "--color-link"],
["onAccent", "--color-on-accent"],
];
Deno.test("email palettes keep their theme's colors", () => {
for (const name of STYLE_NAMES) {
const css = Deno.readTextFileSync(
new URL(`../../../src/themes/${name}.css`, import.meta.url),
);
for (const [role, token] of TOKENS) {
const match = css.match(
new RegExp(
`${token}:\\s*light-dark\\(\\s*(#[0-9a-f]+),\\s*(#[0-9a-f]+)\\s*\\)`,
"i",
),
);
if (!match) throw new Error(`${name} has no ${token}`);
const { light, dark } = EMAIL_STYLES[name];
assertEquals(
[light[role], dark[role]],
[match[1].toLowerCase(), match[2].toLowerCase()],
`${name} ${role} (${token})`,
);
}
}
});

View File

@@ -2,20 +2,22 @@ import "../setup.ts";
import { assertFalse, assertStringIncludes } from "@std/assert";
import { renderWelcomeEmail } from "../../mail/welcome.ts";
import { renderPasswordResetEmail } from "../../mail/password-reset.ts";
import { i18n } from "../../mail/i18n.ts";
Deno.test("renderWelcomeEmail: fills the built-in body, in both parts", () => {
const email = renderWelcomeEmail("newbie");
assertStringIncludes(email.subject, "Welcome to gerbeur");
assertStringIncludes(email.text, "Hi **newbie**");
assertFalse(email.text.includes("{{"));
assertStringIncludes(email.html, "newbie</strong>");
assertStringIncludes(email.html, "newbie</b>");
assertStringIncludes(email.html, "Welcome to gerbeur!</h1>");
});
Deno.test("renderPasswordResetEmail: the button and the raw link carry the URL", () => {
const url = "http://gerbeur.test/reset-password?token=a.b&x=<y>";
const email = renderPasswordResetEmail("bob", url, 1);
assertStringIncludes(email.text, url);
assertStringIncludes(email.text, "# Reset your password");
assertStringIncludes(email.text, `[Reset password](${url})`);
assertStringIncludes(email.text, "for 1 hour");
assertStringIncludes(
email.html,
@@ -23,3 +25,15 @@ Deno.test("renderPasswordResetEmail: the button and the raw link carry the URL",
);
assertFalse(email.html.includes("<y>"));
});
Deno.test("the emails speak the catalog's language", () => {
i18n.activate("fr");
try {
const email = renderPasswordResetEmail("bob", "http://g.test/r", 2);
assertStringIncludes(email.subject, "Réinitialisez votre mot de passe");
assertStringIncludes(email.text, "pendant 2 heures");
assertStringIncludes(renderWelcomeEmail("bob").text, "Bonjour **bob**");
} finally {
i18n.activate("en");
}
});

View File

@@ -479,7 +479,7 @@ test("request-password-reset: emails a link that resets the password", async ()
assertEquals(mail.sent.length, 1);
assertEquals(mail.sent[0].to, user.email);
const token = decodeURIComponent(
mail.sent[0].text.match(/token=([^\s]+)/)![1],
mail.sent[0].text.match(/token=([^\s)]+)/)![1],
);
const res = await post("/api/users/reset-password", {
json: { token, newPassword: "from-the-email" },

View File

@@ -0,0 +1,270 @@
import {
captureEmails,
createUser,
db,
insertComment,
insertDump,
insertPlaylist,
post,
test,
} from "../helpers.ts";
import { assert, assertEquals, assertFalse } from "@std/assert";
import {
buildDigest,
PERIOD_MS,
sendDueDigests,
syncDigestSchedules,
} from "../../services/digest-service.ts";
import {
getSettings,
updateSettings,
} from "../../services/settings-service.ts";
const DAY = 86_400_000;
const ago = (ms: number) => new Date(Date.now() - ms).toISOString();
const week = () =>
[new Date(Date.now() - 7 * DAY), new Date(Date.now() + 60_000)] as const;
function notify(
userId: string,
type: string,
data: object,
createdAt = ago(DAY),
) {
db.prepare(
`INSERT INTO notifications (id, user_id, type, data, read, created_at) VALUES (?, ?, ?, ?, 0, ?);`,
).run(crypto.randomUUID(), userId, type, JSON.stringify(data), createdAt);
}
function follow(
followerId: string,
target: { user?: string; playlist?: string },
) {
db.prepare(
`INSERT INTO follows (id, follower_id, followed_user_id, followed_playlist_id, created_at) VALUES (?, ?, ?, ?, ?);`,
).run(
crypto.randomUUID(),
followerId,
target.user ?? null,
target.playlist ?? null,
ago(DAY),
);
}
function vote(dumpId: string, n: number) {
db.prepare(`UPDATE dumps SET vote_count = ? WHERE id = ?;`).run(n, dumpId);
}
function schedule(userId: string, cadence: string, windowStart: string) {
db.prepare(
`INSERT OR REPLACE INTO digest_schedule (user_id, cadence, window_start) VALUES (?, ?, ?);`,
).run(userId, cadence, windowStart);
}
const windowOf = (userId: string, cadence: string) =>
(db.prepare(
`SELECT window_start FROM digest_schedule WHERE user_id = ? AND cadence = ?;`,
).get(userId, cadence) as { window_start: string } | undefined)?.window_start;
test("buildDigest: the weekly digest gathers activity, network, top and community", async () => {
const reader = await createUser();
const friend = await createUser({ invitedBy: reader.id });
const stranger = await createUser();
const mine = insertDump({ userId: reader.id, title: "My dump" });
vote(mine.id, 3);
const commentId = insertComment({
dumpId: mine.id,
userId: friend.id,
body: "Loved **this** [link](https://x.test)",
});
notify(reader.id, "dump_commented", {
commenterId: friend.id,
commenterUsername: friend.username,
commentId,
dumpId: mine.id,
dumpTitle: "My dump",
});
notify(reader.id, "user_followed", {
followerId: friend.id,
followerUsername: friend.username,
});
for (let i = 0; i < 3; i++) {
notify(reader.id, "dump_upvoted", {
voterId: friend.id,
voterUsername: friend.username,
dumpId: mine.id,
dumpTitle: "My dump",
});
}
// Before the period: not counted.
notify(reader.id, "user_followed", { followerUsername: "old" }, ago(9 * DAY));
follow(reader.id, { user: friend.id });
const posted = insertDump({ userId: friend.id, title: "Friend's post" });
vote(posted.id, 5);
insertDump({ userId: friend.id, title: "Private", isPrivate: true });
insertDump({ userId: friend.id, title: "Too old", createdAt: ago(10 * DAY) });
const mix = insertPlaylist({ userId: stranger.id, title: "Mix" });
follow(reader.id, { playlist: mix.id });
const added = insertDump({ userId: stranger.id, title: "Added <b>" });
db.prepare(
`INSERT INTO playlist_dumps (playlist_id, dump_id, position, added_at) VALUES (?, ?, 0, ?);`,
).run(mix.id, added.id, ago(DAY));
// Posted by someone followed and added to a followed playlist: listed once.
db.prepare(
`INSERT INTO playlist_dumps (playlist_id, dump_id, position, added_at) VALUES (?, ?, 1, ?);`,
).run(mix.id, posted.id, ago(DAY));
const [from, to] = week();
const digest =
(buildDigest(reader.id, reader.username, "weekly", from, to, "tok"))!;
assertEquals(digest.activity?.counts, {
comments: 1,
followers: 1,
upvotes: 3,
});
assertEquals(digest.activity?.total, 5);
assertEquals(digest.activity?.highlights.map((h) => h.kind), [
"comment",
"userFollow",
]);
assertEquals(digest.activity?.highlights[0].quote, "Loved this link");
assertEquals(digest.network?.dumps.map((d) => [d.title, d.addedTo]), [
["Friend's post", undefined],
["Added <b>", "Mix"],
]);
assertEquals(digest.top.map((d) => [d.title, d.mine]), [
["Friend's post", false],
["My dump", true],
]);
assertEquals(
digest.community?.members.map((m) => [m.username, m.invitedBy]),
[
[friend.username, reader.username],
[stranger.username, null],
],
);
assertEquals(digest.community?.totals.dumps, 3);
assert(digest.links.unsubscribe.includes("/unsubscribe?token="));
});
test("buildDigest: the monthly recap has no personal sections, and nothing makes no digest", async () => {
const reader = await createUser({ createdAt: ago(40 * DAY) });
const [from, to] = [
new Date(Date.now() - 30 * DAY),
new Date(Date.now() + 60_000),
];
assertEquals(
buildDigest(reader.id, reader.username, "monthly", from, to, "tok"),
null,
);
const other = await createUser({ createdAt: ago(40 * DAY) });
notify(reader.id, "user_followed", { followerUsername: other.username });
const d = insertDump({ userId: other.id, title: "Hit" });
vote(d.id, 2);
insertDump({ userId: other.id, title: "No votes" });
const recap =
(buildDigest(reader.id, reader.username, "monthly", from, to, "tok"))!;
assertEquals(recap.activity, null);
assertEquals(recap.network, null);
assertEquals(recap.top.map((t) => t.title), ["Hit"]);
});
test("sendDueDigests: sends what's due in the reader's style, once, and moves the period on", async () => {
using mail = captureEmails();
const reader = await createUser({ createdAt: ago(20 * DAY) });
const other = await createUser({ createdAt: ago(20 * DAY) });
updateSettings(reader.id, { style: "geocities", colorScheme: "dark" });
const d = insertDump({
userId: other.id,
title: "Worth a look",
createdAt: ago(3 * DAY),
});
vote(d.id, 1);
const start = ago(PERIOD_MS.weekly + DAY);
schedule(reader.id, "weekly", start);
schedule(reader.id, "monthly", ago(DAY));
schedule(other.id, "weekly", ago(DAY));
schedule(other.id, "monthly", ago(DAY));
assertEquals(await sendDueDigests(), 1);
assertEquals(mail.sent.length, 1);
const email = mail.sent[0];
assertEquals(email.to, reader.email);
assert(email.subject.startsWith("Your week on gerbeur"));
assert(email.html.includes("Worth a look"));
assert(email.html.includes("#1b1b46"), "GeoCities' dark card");
assertFalse(email.html.includes("prefers-color-scheme"));
assertEquals(
email.headers?.["List-Unsubscribe-Post"],
"List-Unsubscribe=One-Click",
);
assertEquals(
windowOf(reader.id, "weekly"),
new Date(new Date(start).getTime() + PERIOD_MS.weekly).toISOString(),
);
// Nothing is due any more.
assertEquals(await sendDueDigests(), 0);
// The header's link turns the weekly digest off, in one click.
const link = email.headers!["List-Unsubscribe"].slice(1, -1);
const res = await post(new URL(link).pathname + new URL(link).search, {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
});
assertEquals(res.status, 200);
assertEquals(getSettings(reader.id).digestWeekly, false);
assertEquals(getSettings(reader.id).digestMonthly, true);
syncDigestSchedules(new Date());
assertEquals(windowOf(reader.id, "weekly"), undefined);
});
test("sendDueDigests: an empty digest isn't sent, a late one covers the last period, and admin@localhost is skipped", async () => {
using mail = captureEmails();
const quiet = await createUser({ createdAt: ago(60 * DAY) });
schedule(quiet.id, "weekly", ago(PERIOD_MS.weekly + DAY));
assertEquals(await sendDueDigests(), 0);
assert(windowOf(quiet.id, "weekly")! > ago(2 * DAY));
const late = await createUser({ createdAt: ago(60 * DAY) });
const d = insertDump({ userId: quiet.id, title: "Recent" });
vote(d.id, 1);
schedule(late.id, "weekly", ago(5 * PERIOD_MS.weekly));
const local = await createUser({
email: "admin@localhost",
createdAt: ago(60 * DAY),
});
schedule(local.id, "weekly", ago(PERIOD_MS.weekly + DAY));
const before = Date.now();
// Quiet's next period has only begun.
assertEquals(await sendDueDigests(), 1);
assertEquals(mail.sent.map((m) => m.to), [late.email]);
// The late one's period is the last week, so the next starts now.
assert(new Date(windowOf(late.id, "weekly")!).getTime() >= before);
assert(windowOf(local.id, "weekly")! > ago(2 * DAY));
});
test("syncDigestSchedules: new users start now, a turned-off cadence loses its row", async () => {
const user = await createUser();
const now = new Date();
syncDigestSchedules(now);
assertEquals(windowOf(user.id, "weekly"), now.toISOString());
assertEquals(windowOf(user.id, "monthly"), now.toISOString());
updateSettings(user.id, { digestMonthly: false });
syncDigestSchedules(new Date(now.getTime() + 1000));
assertEquals(windowOf(user.id, "weekly"), now.toISOString());
assertEquals(windowOf(user.id, "monthly"), undefined);
});
test("unsubscribe: a bad or other kind of token is refused", async () => {
const user = await createUser();
assertEquals((await post("/api/users/unsubscribe?token=nope")).status, 400);
assertEquals(
(await post(`/api/users/unsubscribe?token=${user.token}`)).status,
400,
);
assertEquals((await post("/api/users/unsubscribe")).status, 400);
});