Skip to content
62 linesCodeBlameRaw
1import { env } from "cloudflare:workers";
2import { data } from "react-router";
3
4import { notifyClient, type NotifyPreferencesChange, type PresenceChange, type PushSubscriptionJson } from "@g1t/contracts";
5
6import type { Route } from "./+types/api";
7import { assertSameOrigin, requireUser } from "../../lib/session.server";
8
9function client() {
10 if (!env.NOTIFY) throw data({ error: "Notifications are not set up here." }, { status: 503 });
11 return notifyClient(env.NOTIFY);
12}
13
14/**
15 * The signed-in person's notification settings, as JSON: `GET` their
16 * status (with `?endpoint=` for whether this browser gets pushes), `POST`
17 * a change: `subscribe`, `unsubscribe`, `preferences`, `test`, or
18 * `presence` (your status, being away, Do Not Disturb).
19 */
20export async function loader({ context, request }: Route.LoaderArgs) {
21 const user = requireUser(context, request);
22 const endpoint = new URL(request.url).searchParams.get("endpoint");
23 const status = await client().status(user, endpoint);
24 return Response.json(status, { headers: { "cache-control": "no-store" } });
25}
26
27type Sent = {
28 intent?: string;
29 subscription?: PushSubscriptionJson & { expirationTime?: number | null };
30 endpoint?: string;
31 preferences?: NotifyPreferencesChange;
32 change?: PresenceChange;
33};
34
35export async function action({ context, request }: Route.ActionArgs) {
36 assertSameOrigin(request);
37 const user = requireUser(context, request);
38 const sent = (await request.json().catch(() => ({}))) as Sent;
39 const notify = client();
40 switch (sent.intent) {
41 case "subscribe": {
42 const s = sent.subscription;
43 if (!s?.endpoint || !s.keys?.p256dh || !s.keys?.auth) return Response.json({ ok: false }, { status: 400 });
44 const subscription: PushSubscriptionJson = { endpoint: s.endpoint, keys: { p256dh: s.keys.p256dh, auth: s.keys.auth } };
45 return Response.json(await notify.subscribe(user, subscription, request.headers.get("user-agent")));
46 }
47 case "unsubscribe":
48 return Response.json(await notify.unsubscribe(user, String(sent.endpoint ?? "")));
49 case "preferences":
50 return Response.json(await notify.setPreferences(user, sent.preferences ?? {}));
51 case "test":
52 return Response.json(await notify.test(user));
53 case "presence": {
54 // Set by hand here: a calendar's or an integration's comes through their own door.
55 const change = sent.change ?? {};
56 const status = change.status ? { ...change.status, source: "manual" as const } : change.status;
57 return Response.json(await notify.setPresence(user, { ...change, ...("status" in change ? { status } : {}) }));
58 }
59 default:
60 return Response.json({ ok: false }, { status: 400 });
61 }
62}