"use server"; import { and, eq } from "drizzle-orm"; import { db } from "@/lib/db"; import { pushSubscriptions } from "@/modules/_core/schema"; import { getCurrentSession } from "@/lib/session"; import { sendPush } from "@/modules/_core/push"; type PushSubscriptionJSON = { endpoint: string; keys: { p256dh: string; auth: string }; }; export async function subscribeToPush(sub: PushSubscriptionJSON, userAgent: string): Promise { const { user } = await getCurrentSession(); await db .insert(pushSubscriptions) .values({ userId: user.id, endpoint: sub.endpoint, p256dh: sub.keys.p256dh, auth: sub.keys.auth, userAgent: userAgent.slice(0, 512), }) .onConflictDoUpdate({ target: pushSubscriptions.endpoint, set: { p256dh: sub.keys.p256dh, auth: sub.keys.auth }, }); } export async function unsubscribeFromPush(endpoint: string): Promise { const { user } = await getCurrentSession(); await db .delete(pushSubscriptions) .where(and(eq(pushSubscriptions.userId, user.id), eq(pushSubscriptions.endpoint, endpoint))); } export async function sendTestNotification(): Promise { const { user } = await getCurrentSession(); await sendPush(user.id, { title: "famapp test", body: "Push notifications are working!", url: "/settings", }); }