Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add notification settings UI and email hooks

Richie McIlroy1336cdd43fc2
diff --git a/apps/web/actions/notifications/update-preferences.ts b/apps/web/actions/notifications/update-preferences.ts
index 47adad149..9fa59e7bb 100644
--- a/apps/web/actions/notifications/update-preferences.ts
+++ b/apps/web/actions/notifications/update-preferences.ts
@@ -27,6 +27,7 @@ export const updatePreferences = async ({
.update(users)
.set({
preferences: {
+ ...(currentUser.preferences ?? {}),
notifications,
},
})
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
index 714f00e4d..bfe549d8a 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
@@ -67,6 +67,7 @@ const Top = () => {
"/dashboard/settings/organization/billing": "Organization Settings",
"/dashboard/settings/organization/members": "Organization Settings",
"/dashboard/settings/account": "Account Settings",
+ "/dashboard/settings/notifications": "Notification Settings",
"/dashboard/spaces": "Spaces",
"/dashboard/spaces/browse": "Browse Spaces",
"/dashboard/analytics": "Analytics",
@@ -165,7 +166,12 @@ const Top = () => {
)}
<FontAwesomeIcon className="text-gray-12 size-3.5" icon={faBell} />
<AnimatePresence>
- {toggleNotifications && <Notifications ref={notificationsRef} />}
+ {toggleNotifications && (
+ <Notifications
+ ref={notificationsRef}
+ onClose={() => setToggleNotifications(false)}
+ />
+ )}
</AnimatePresence>
</div>
{!isDeveloperSection && (
diff --git a/apps/web/app/(org)/dashboard/_components/Notifications/NotificationFooter.tsx b/apps/web/app/(org)/dashboard/_components/Notifications/NotificationFooter.tsx
index 375a79fd0..6a270a176 100644
--- a/apps/web/app/(org)/dashboard/_components/Notifications/NotificationFooter.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Notifications/NotificationFooter.tsx
@@ -1,8 +1,12 @@
-import { faArrowDown, faArrowUp } from "@fortawesome/free-solid-svg-icons";
+import {
+ faArrowDown,
+ faArrowUp,
+ faCog,
+} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { SettingsDropdown } from "./SettingsDropdown";
+import Link from "next/link";
-export const NotificationFooter = () => {
+export const NotificationFooter = ({ onClose }: { onClose?: () => void }) => {
return (
<div className="flex justify-between items-center px-6 py-3 rounded-b-xl border bg-gray-4 border-gray-5">
<div className="flex gap-2 items-center">
@@ -17,7 +21,14 @@ export const NotificationFooter = () => {
<FontAwesomeIcon icon={faArrowUp} className="text-gray-2 size-2.5" />
</div>
</div>
- <SettingsDropdown />
+ <Link
+ href="/dashboard/settings/notifications"
+ onClick={onClose}
+ className="flex gap-1 items-center transition-opacity duration-200 cursor-pointer hover:opacity-70"
+ >
+ <FontAwesomeIcon icon={faCog} className="text-gray-10 size-3" />
+ <p className="text-[13px] text-gray-10">Settings</p>
+ </Link>
</div>
);
};
diff --git a/apps/web/app/(org)/dashboard/_components/Notifications/SettingsDropdown.tsx b/apps/web/app/(org)/dashboard/_components/Notifications/SettingsDropdown.tsx
deleted file mode 100644
index 7e894f537..000000000
--- a/apps/web/app/(org)/dashboard/_components/Notifications/SettingsDropdown.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-import {
- faArrowUp,
- faBellSlash,
- faCheck,
- faCog,
- faComment,
- faEye,
- faEyeSlash,
- faReply,
- faThumbsUp,
- type IconDefinition,
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { Menu, Transition } from "@headlessui/react";
-import clsx from "clsx";
-import { Fragment, useState } from "react";
-import { toast } from "sonner";
-import { updatePreferences } from "@/actions/notifications/update-preferences";
-import { useDashboardContext } from "../../Contexts";
-
-type NotificationOption = {
- icon: IconDefinition;
- label: string;
- value:
- | "pauseComments"
- | "pauseViews"
- | "pauseReactions"
- | "pauseReplies"
- | "pauseAnonViews";
-};
-
-const notificationOptions: NotificationOption[] = [
- { icon: faComment, label: "Comments", value: "pauseComments" },
- { icon: faReply, label: "Replies", value: "pauseReplies" },
- { icon: faEye, label: "Views", value: "pauseViews" },
- { icon: faEyeSlash, label: "Anonymous views", value: "pauseAnonViews" },
- { icon: faThumbsUp, label: "Reactions", value: "pauseReactions" },
-];
-
-export const SettingsDropdown = () => {
- const [showPauseSubmenu, setShowPauseSubmenu] = useState(false);
- const { userPreferences } = useDashboardContext();
-
- const updateNotificationPreferences = async (option: NotificationOption) => {
- try {
- const currentPrefs = userPreferences?.notifications ?? {
- pauseComments: false,
- pauseReplies: false,
- pauseViews: false,
- pauseReactions: false,
- pauseAnonViews: false,
- };
-
- await updatePreferences({
- notifications: {
- ...currentPrefs,
- [option.value]: !(currentPrefs[option.value] ?? false),
- },
- });
-
- toast.success(
- `Notifications from ${option.label} have been ${
- !(currentPrefs[option.value] ?? false) ? "paused" : "unpaused"
- }`,
- );
- } catch (error) {
- console.error("Failed to update preferences:", error);
- toast.error("Failed to update notification preferences");
- }
- };
-
- return (
- <Menu as="div" className="relative">
- <Menu.Button className="flex gap-1 items-center transition-opacity duration-200 cursor-pointer hover:opacity-70">
- <FontAwesomeIcon icon={faCog} className="text-gray-10 size-3" />
- <p className="text-[13px] text-gray-10">Settings</p>
- </Menu.Button>
-
- <Transition
- as={Fragment}
- enter="transition ease-out duration-200"
- enterFrom="opacity-0 scale-95"
- enterTo="opacity-100 scale-100"
- leave="transition ease-in duration-150"
- leaveFrom="opacity-100 scale-100"
- leaveTo="opacity-0 scale-95"
- >
- <Menu.Items className="absolute right-0 top-4 mb-2 min-w-[200px] bg-gray-2 rounded-lg shadow-lg border border-gray-3 p-1.5 z-50 focus:outline-none">
- <div className="relative">
- <Menu.Item>
- {({ active }) => (
- <div
- className={clsx(
- "flex flex-1 items-center group justify-between px-2 py-1 min-w-fit text-[13px] text-gray-11 rounded-lg cursor-pointer outline-none",
- active || showPauseSubmenu ? "bg-gray-3" : "",
- )}
- onMouseEnter={() => setShowPauseSubmenu(true)}
- onMouseLeave={() => setShowPauseSubmenu(false)}
- >
- <div className="flex gap-2 items-center">
- <FontAwesomeIcon
- icon={faBellSlash}
- className="text-gray-10 text-[13px] size-3.5 transition-colors group-hover:text-gray-12"
- />
- <p className="text-[13px] transition-colors group-hover:text-gray-12">
- Pause notifications
- </p>
- </div>
- <FontAwesomeIcon
- icon={faArrowUp}
- className="text-gray-10 size-2.5 rotate-90 transition-colors group-hover:text-gray-12"
- />
- </div>
- )}
- </Menu.Item>
-
- {/* Submenu */}
- {showPauseSubmenu && (
- <div
- className="absolute top-0 left-full z-50 p-2 -ml-1 rounded-lg border shadow-lg min-w-[150px] bg-gray-2 border-gray-3"
- onMouseEnter={() => setShowPauseSubmenu(true)}
- onMouseLeave={() => setShowPauseSubmenu(false)}
- >
- {notificationOptions.map((option, index) => (
- <div
- key={index}
- className="flex w-full items-center justify-between gap-2 px-2 py-1 text-[13px] text-gray-11 rounded-lg group hover:bg-gray-3 cursor-pointer outline-none"
- onClick={async () =>
- await updateNotificationPreferences(option)
- }
- >
- <div className="flex gap-1.5 items-center">
- <FontAwesomeIcon
- icon={option.icon}
- className="text-gray-10 size-3.5 transition-colors group-hover:text-gray-12"
- />
- <p className="text-[13px] transition-colors group-hover:text-gray-12">
- {option.label}
- </p>
- </div>
-
- {userPreferences?.notifications?.[option.value] && (
- <FontAwesomeIcon
- icon={faCheck}
- className="text-gray-10 size-2.5 transition-colors group-hover:text-gray-12"
- />
- )}
- </div>
- ))}
- </div>
- )}
- </div>
- </Menu.Items>
- </Transition>
- </Menu>
- );
-};
-
-export default SettingsDropdown;
diff --git a/apps/web/app/(org)/dashboard/_components/Notifications/index.tsx b/apps/web/app/(org)/dashboard/_components/Notifications/index.tsx
index 5a149ad5b..7257a9cfb 100644
--- a/apps/web/app/(org)/dashboard/_components/Notifications/index.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Notifications/index.tsx
@@ -20,11 +20,12 @@ import { NotificationHeader } from "./NotificationHeader";
import { NotificationItem } from "./NotificationItem";
import { NotificationsSkeleton } from "./Skeleton";
-type NotificationsProps = MotionProps & React.HTMLAttributes<HTMLDivElement>;
+type NotificationsProps = MotionProps &
+ React.HTMLAttributes<HTMLDivElement> & { onClose?: () => void };
const Notifications = forwardRef<HTMLDivElement, NotificationsProps>(
(props, ref) => {
- const { className } = props;
+ const { className, onClose, ...rest } = props;
const { activeOrganization } = useDashboardContext();
const [activeFilter, setActiveFilter] = useState<FilterType>("all");
const scrollRef = useRef<HTMLDivElement>(null);
@@ -90,7 +91,7 @@ const Notifications = forwardRef<HTMLDivElement, NotificationsProps>(
"flex absolute right-0 top-12 flex-col rounded-xl origin-top-right cursor-default w-[400px] h-[450px] bg-gray-1",
className,
)}
- {...props}
+ {...rest}
>
<NotificationHeader />
<FilterTabs
@@ -134,7 +135,7 @@ const Notifications = forwardRef<HTMLDivElement, NotificationsProps>(
<div className="flex-1 border-t border-gray-3" />
</div>
- <NotificationFooter />
+ <NotificationFooter onClose={onClose} />
</motion.div>
);
},
diff --git a/apps/web/app/(org)/dashboard/settings/notifications/NotificationsSettings.tsx b/apps/web/app/(org)/dashboard/settings/notifications/NotificationsSettings.tsx
new file mode 100644
index 000000000..0487d67ec
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/settings/notifications/NotificationsSettings.tsx
@@ -0,0 +1,104 @@
+"use client";
+
+import { Card, CardDescription, CardTitle, Switch } from "@cap/ui";
+import { useMutation } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { updatePreferences } from "@/actions/notifications/update-preferences";
+import { useDashboardContext } from "../../Contexts";
+
+type NotificationPreferences = {
+ pauseComments: boolean;
+ pauseReplies: boolean;
+ pauseViews: boolean;
+ pauseReactions: boolean;
+ pauseAnonViews: boolean;
+};
+
+const DEFAULT_PREFERENCES: NotificationPreferences = {
+ pauseComments: false,
+ pauseReplies: false,
+ pauseViews: false,
+ pauseReactions: false,
+ pauseAnonViews: false,
+};
+
+const NOTIFICATION_TYPES: {
+ key: keyof NotificationPreferences;
+ title: string;
+ description: string;
+}[] = [
+ {
+ key: "pauseComments",
+ title: "Comments",
+ description:
+ "Email and in-app alert when someone comments on one of your Caps.",
+ },
+ {
+ key: "pauseReplies",
+ title: "Replies",
+ description: "In-app alert when someone replies to a comment you left.",
+ },
+ {
+ key: "pauseViews",
+ title: "Views",
+ description: "Alert when a signed-in viewer watches one of your Caps.",
+ },
+ {
+ key: "pauseAnonViews",
+ title: "Anonymous views",
+ description: "Alert when an anonymous viewer watches one of your Caps.",
+ },
+ {
+ key: "pauseReactions",
+ title: "Reactions",
+ description: "In-app alert when someone reacts to one of your Caps.",
+ },
+];
+
+export const NotificationsSettings = () => {
+ const router = useRouter();
+ const { userPreferences } = useDashboardContext();
+ const [preferences, setPreferences] = useState<NotificationPreferences>(
+ () => ({
+ ...DEFAULT_PREFERENCES,
+ ...(userPreferences?.notifications ?? {}),
+ }),
+ );
+
+ const { mutate } = useMutation({
+ mutationFn: (next: NotificationPreferences) =>
+ updatePreferences({ notifications: next }),
+ onSuccess: () => router.refresh(),
+ onError: () => toast.error("Failed to update notification preferences"),
+ });
+
+ const toggle = (key: keyof NotificationPreferences) => {
+ const previous = preferences;
+ const next = { ...preferences, [key]: !preferences[key] };
+ setPreferences(next);
+ mutate(next, { onError: () => setPreferences(previous) });
+ };
+
+ return (
+ <Card className="divide-y divide-gray-4">
+ {NOTIFICATION_TYPES.map(({ key, title, description }) => (
+ <div
+ key={key}
+ className="flex gap-4 justify-between items-center py-4 first:pt-0 last:pb-0"
+ >
+ <div className="space-y-1">
+ <CardTitle className="text-base">{title}</CardTitle>
+ <CardDescription>{description}</CardDescription>
+ </div>
+ <Switch
+ checked={!preferences[key]}
+ onCheckedChange={() => toggle(key)}
+ aria-label={`${title} notifications`}
+ />
+ </div>
+ ))}
+ </Card>
+ );
+};
diff --git a/apps/web/app/(org)/dashboard/settings/notifications/loading.tsx b/apps/web/app/(org)/dashboard/settings/notifications/loading.tsx
new file mode 100644
index 000000000..fb2360af9
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/settings/notifications/loading.tsx
@@ -0,0 +1,40 @@
+"use client";
+
+import { SkeletonPage } from "@cap/ui";
+
+const ROWS = ["comments", "replies", "views", "anonViews", "reactions"];
+
+export default function Loading() {
+ return (
+ <SkeletonPage
+ customSkeleton={(Skeleton) => (
+ <div className="p-5 rounded-2xl border divide-y bg-gray-3 border-gray-4 divide-gray-4">
+ {ROWS.map((row) => (
+ <div
+ key={row}
+ className="flex gap-4 justify-between items-center py-4 first:pt-0 last:pb-0"
+ >
+ <div className="space-y-2">
+ <Skeleton
+ baseColor="var(--gray-4)"
+ highlightColor="var(--gray-5)"
+ className="w-32 h-5"
+ />
+ <Skeleton
+ baseColor="var(--gray-4)"
+ highlightColor="var(--gray-5)"
+ className="w-64 h-4 max-w-full"
+ />
+ </div>
+ <Skeleton
+ baseColor="var(--gray-4)"
+ highlightColor="var(--gray-5)"
+ className="w-11 h-6 rounded-full"
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ />
+ );
+}
diff --git a/apps/web/app/(org)/dashboard/settings/notifications/page.tsx b/apps/web/app/(org)/dashboard/settings/notifications/page.tsx
new file mode 100644
index 000000000..5e6626cb2
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/settings/notifications/page.tsx
@@ -0,0 +1,10 @@
+import type { Metadata } from "next";
+import { NotificationsSettings } from "./NotificationsSettings";
+
+export const metadata: Metadata = {
+ title: "Notification Settings — Cap",
+};
+
+export default function NotificationsSettingsPage() {
+ return <NotificationsSettings />;
+}
diff --git a/apps/web/app/api/email/new-comment/route.ts b/apps/web/app/api/email/new-comment/route.ts
deleted file mode 100644
index f2d57c9cf..000000000
--- a/apps/web/app/api/email/new-comment/route.ts
+++ /dev/null
@@ -1,241 +0,0 @@
-import { db } from "@cap/database";
-import { sendEmail } from "@cap/database/emails/config";
-import { NewComment } from "@cap/database/emails/new-comment";
-import { comments, users, videos } from "@cap/database/schema";
-import { buildEnv, serverEnv } from "@cap/env";
-import { and, eq, gt, ne } from "drizzle-orm";
-import type { NextRequest } from "next/server";
-
-const lastEmailSentCache = new Map<string, Date>();
-
-export async function POST(request: NextRequest) {
- console.log("Processing new comment email notification");
- const { commentId } = await request.json();
-
- if (!commentId) {
- console.error("Missing required field: commentId");
- return Response.json(
- { error: "Missing required fields: commentId" },
- { status: 400 },
- );
- }
-
- try {
- console.log(`Fetching comment details for commentId: ${commentId}`);
- // Get the comment details
- const commentDetails = await db()
- .select({
- id: comments.id,
- content: comments.content,
- type: comments.type,
- videoId: comments.videoId,
- authorId: comments.authorId,
- createdAt: comments.createdAt,
- })
- .from(comments)
- .where(eq(comments.id, commentId))
- .limit(1);
-
- if (!commentDetails || commentDetails.length === 0) {
- console.error(`Comment not found for commentId: ${commentId}`);
- return Response.json({ error: "Comment not found" }, { status: 404 });
- }
-
- const comment = commentDetails[0];
- if (comment) {
- console.log(
- `Found comment: ${comment.id}, type: ${comment.type}, videoId: ${comment.videoId}`,
- );
- }
-
- if (
- !comment ||
- comment.type !== "text" ||
- !comment.videoId ||
- !comment.content
- ) {
- console.log(
- "Skipping email notification - invalid comment data or non-text comment",
- );
- return Response.json(
- { success: false, reason: "Invalid comment data" },
- { status: 200 },
- );
- }
-
- console.log(`Fetching video details for videoId: ${comment.videoId}`);
- // Get the video details
- const videoDetails = await db()
- .select({
- id: videos.id,
- name: videos.name,
- ownerId: videos.ownerId,
- })
- .from(videos)
- .where(eq(videos.id, comment.videoId))
- .limit(1);
-
- if (!videoDetails || videoDetails.length === 0) {
- console.error(`Video not found for videoId: ${comment.videoId}`);
- return Response.json({ error: "Video not found" }, { status: 404 });
- }
-
- const video = videoDetails[0];
- if (video) {
- console.log(
- `Found video: ${video.id}, name: ${video.name}, ownerId: ${video.ownerId}`,
- );
- }
-
- if (!video || !video.ownerId || !video.id || !video.name) {
- console.error("Invalid video data");
- return Response.json({ error: "Invalid video data" }, { status: 500 });
- }
-
- console.log(`Fetching owner details for userId: ${video.ownerId}`);
- // Get the video owner's email
- const ownerDetails = await db()
- .select({
- id: users.id,
- email: users.email,
- })
- .from(users)
- .where(eq(users.id, video.ownerId))
- .limit(1);
-
- if (
- !ownerDetails ||
- !ownerDetails.length ||
- !ownerDetails[0] ||
- !ownerDetails[0].email
- ) {
- console.error(`Video owner not found for userId: ${video.ownerId}`);
- return Response.json({ error: "Video owner not found" }, { status: 404 });
- }
-
- const owner = ownerDetails[0];
- console.log(`Found owner: ${owner.id}, email: ${owner.email}`);
-
- if (!owner || !owner.email || !owner.id) {
- console.error("Invalid owner data");
- return Response.json({ error: "Invalid owner data" }, { status: 500 });
- }
-
- let commenterName = "Anonymous";
- if (comment.authorId) {
- console.log(`Fetching commenter details for userId: ${comment.authorId}`);
- const commenterDetails = await db()
- .select({
- id: users.id,
- name: users.name,
- })
- .from(users)
- .where(eq(users.id, comment.authorId))
- .limit(1);
-
- if (
- commenterDetails &&
- commenterDetails.length > 0 &&
- commenterDetails[0] &&
- commenterDetails[0].name
- ) {
- commenterName = commenterDetails[0].name;
- console.log(`Found commenter name: ${commenterName}`);
- } else {
- console.log("Commenter details not found, using 'Anonymous'");
- }
- } else {
- console.log("No authorId provided, using 'Anonymous'");
- }
-
- const now = new Date();
- const lastEmailSent = lastEmailSentCache.get(owner.id);
-
- if (lastEmailSent) {
- const fifteenMinutesAgo = new Date(now.getTime() - 15 * 60 * 1000);
-
- if (lastEmailSent > fifteenMinutesAgo) {
- console.log(
- `Rate limiting email to user ${
- owner.id
- } - last email sent at ${lastEmailSent.toISOString()}`,
- );
- return Response.json(
- { success: false, reason: "Email rate limited" },
- { status: 200 },
- );
- }
- }
-
- const fifteenMinutesAgo = new Date(now.getTime() - 15 * 60 * 1000);
- console.log(
- `Checking for recent comments since ${fifteenMinutesAgo.toISOString()}`,
- );
- const recentComments = await db()
- .select({
- id: comments.id,
- })
- .from(comments)
- .where(
- and(
- eq(comments.videoId, comment.videoId),
- eq(comments.type, "text"),
- gt(comments.createdAt, fifteenMinutesAgo),
- ne(comments.id, commentId),
- ),
- )
- .limit(1);
-
- if (recentComments && recentComments.length > 0 && recentComments[0]) {
- console.log(
- `Found recent comment ${recentComments[0].id}, skipping email notification`,
- );
- return Response.json(
- { success: false, reason: "Recent comment found" },
- { status: 200 },
- );
- }
-
- // Generate the video URL
- const videoUrl = buildEnv.NEXT_PUBLIC_IS_CAP
- ? `https://cap.link/${video.id}`
- : `${serverEnv().WEB_URL}/s/${video.id}`;
- console.log(`Generated video URL: ${videoUrl}`);
-
- console.log(
- `Sending email to ${owner.email} about comment on video "${video.name}"`,
- );
-
- try {
- const emailResult = await sendEmail({
- email: owner.email,
- subject: `New comment on your Cap: ${video.name}`,
- react: NewComment({
- email: owner.email,
- url: videoUrl,
- videoName: video.name,
- commenterName,
- commentContent: comment.content,
- }),
- marketing: true,
- });
-
- console.log("Email send result:", emailResult);
- console.log("Email sent successfully");
-
- lastEmailSentCache.set(owner.id, now);
- console.log(`Updated email cache for user ${owner.id}`);
-
- return Response.json({ success: true }, { status: 200 });
- } catch (emailError) {
- console.error("Error sending email via Resend:", emailError);
- return Response.json(
- { error: "Failed to send email", details: String(emailError) },
- { status: 500 },
- );
- }
- } catch (error) {
- console.error("Error sending new comment email:", error);
- return Response.json({ error: "Failed to send email" }, { status: 500 });
- }
-}
diff --git a/apps/web/app/api/video/comment/route.ts b/apps/web/app/api/video/comment/route.ts
deleted file mode 100644
index f150dc781..000000000
--- a/apps/web/app/api/video/comment/route.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { db } from "@cap/database";
-import { getCurrentUser } from "@cap/database/auth/session";
-import { nanoId } from "@cap/database/helpers";
-import { comments } from "@cap/database/schema";
-import { serverEnv } from "@cap/env";
-import { Comment, User, Video } from "@cap/web-domain";
-import { headers } from "next/headers";
-import type { NextRequest } from "next/server";
-import { rateLimitMiddleware } from "@/utils/helpers";
-
-async function handlePost(request: NextRequest) {
- const user = await getCurrentUser();
- const { type, content, videoId, timestamp, parentCommentId } =
- await request.json();
-
- const userId = user?.id || User.UserId.make("anonymous");
- const parentCommentIdSanitized = parentCommentId
- ? Comment.CommentId.make(parentCommentId.replace("temp-", ""))
- : null;
-
- if (!type || !content || !videoId) {
- console.error("Missing required data in /api/video/comment/route.ts");
-
- return Response.json(
- {
- error: true,
- message: "Missing required fields: type, content, or videoId",
- },
- { status: 400 },
- );
- }
-
- const id = Comment.CommentId.make(nanoId());
-
- try {
- const newComment = {
- id: id,
- authorId: userId,
- type: type,
- content: content,
- videoId: Video.VideoId.make(videoId),
- timestamp: timestamp || null,
- parentCommentId: parentCommentIdSanitized || null,
- createdAt: new Date(),
- updatedAt: new Date(),
- };
-
- await db().insert(comments).values(newComment);
-
- // Trigger email notification for new comment
- if (type === "text" && userId !== "anonymous") {
- try {
- // Don't await this to avoid blocking the response
- const absoluteUrl = new URL(
- "/api/email/new-comment",
- serverEnv().WEB_URL,
- ).toString();
- fetch(absoluteUrl, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- commentId: id,
- }),
- });
- } catch (error) {
- console.error("Error triggering comment notification:", error);
- // Don't fail the comment creation if notification fails
- }
- }
-
- return Response.json(
- {
- ...newComment,
- authorName: user?.name || "Anonymous",
- },
- { status: 200 },
- );
- } catch (error) {
- console.error("Error creating comment:", error);
- return Response.json(
- {
- error: true,
- message: "Failed to create comment",
- },
- { status: 500 },
- );
- }
-}
-
-export const POST = async (request: NextRequest) => {
- const headersList = await headers();
- return rateLimitMiddleware(10, handlePost(request), headersList) as any;
-};
-
-export async function GET() {
- return Response.json({ error: true }, { status: 405 });
-}
diff --git a/apps/web/lib/Notification.ts b/apps/web/lib/Notification.ts
index b5d6989bd..860b245d0 100644
--- a/apps/web/lib/Notification.ts
+++ b/apps/web/lib/Notification.ts
@@ -1,18 +1,24 @@
import { db } from "@cap/database";
import { sendEmail } from "@cap/database/emails/config";
import { FirstView } from "@cap/database/emails/first-view";
+import { NewComment } from "@cap/database/emails/new-comment";
import { nanoId } from "@cap/database/helpers";
import { comments, notifications, users, videos } from "@cap/database/schema";
import { buildEnv, serverEnv } from "@cap/env";
import type { Notification, NotificationBase } from "@cap/web-api-contract";
-import { type Comment, User, Video } from "@cap/web-domain";
-import { and, eq, gte, isNull, sql } from "drizzle-orm";
+import { Comment, User, Video } from "@cap/web-domain";
+import { and, eq, gte, isNull, ne, or, sql } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import type { UserPreferences } from "@/app/(org)/dashboard/dashboard-data";
import { getSessionHash } from "@/lib/anonymous-names";
export type NotificationType = Notification["type"];
+const COMMENT_EMAIL_THROTTLE_MS = 15 * 60 * 1000;
+
+const notificationSettingsUrl = () =>
+ `${serverEnv().WEB_URL}/dashboard/settings/notifications`;
+
type NotificationSpecificData = DistributiveOmit<
Notification,
keyof NotificationBase
@@ -229,6 +235,15 @@ export async function createNotification(
revalidatePath("/dashboard");
+ if (type === "comment") {
+ await sendNewCommentEmail({
+ videoId: notification.videoId,
+ recipientId: videoResult.ownerId,
+ authorId: notification.authorId,
+ comment: notification.comment,
+ });
+ }
+
return { success: true, notificationId };
} catch (error) {
console.error("Error creating notification:", error);
@@ -236,6 +251,87 @@ export async function createNotification(
}
}
+async function sendNewCommentEmail(params: {
+ videoId: string;
+ recipientId: string;
+ authorId: string;
+ comment: { id: string; content: string };
+}) {
+ try {
+ const database = db();
+
+ // Throttle to the same set of events that actually trigger an email: a
+ // top-level comment authored by someone other than the owner. Replies and
+ // the owner's own comments share comments.type === "text", so without these
+ // filters they'd poison the window and suppress legitimate comment emails.
+ // Top-level comments persist parentCommentId as "" (not NULL) — see
+ // Comment.CommentId.make("") in the share-page comment UI.
+ const throttleStart = new Date(Date.now() - COMMENT_EMAIL_THROTTLE_MS);
+ const [recentComment] = await database
+ .select({ id: comments.id })
+ .from(comments)
+ .where(
+ and(
+ eq(comments.videoId, Video.VideoId.make(params.videoId)),
+ eq(comments.type, "text"),
+ or(
+ isNull(comments.parentCommentId),
+ eq(comments.parentCommentId, Comment.CommentId.make("")),
+ ),
+ ne(comments.authorId, User.UserId.make(params.recipientId)),
+ gte(comments.createdAt, throttleStart),
+ ne(comments.id, Comment.CommentId.make(params.comment.id)),
+ ),
+ )
+ .limit(1);
+
+ if (recentComment) return;
+
+ const [recipient] = await database
+ .select({ email: users.email })
+ .from(users)
+ .where(eq(users.id, User.UserId.make(params.recipientId)))
+ .limit(1);
+
+ if (!recipient?.email) return;
+
+ const [video] = await database
+ .select({ name: videos.name })
+ .from(videos)
+ .where(eq(videos.id, Video.VideoId.make(params.videoId)))
+ .limit(1);
+
+ const videoName = video?.name || "Untitled Video";
+
+ const [commenter] = await database
+ .select({ name: users.name })
+ .from(users)
+ .where(eq(users.id, User.UserId.make(params.authorId)))
+ .limit(1);
+
+ const commenterName = commenter?.name || "Someone";
+
+ const videoUrl = buildEnv.NEXT_PUBLIC_IS_CAP
+ ? `https://cap.link/${params.videoId}`
+ : `${serverEnv().WEB_URL}/s/${params.videoId}`;
+
+ await sendEmail({
+ email: recipient.email,
+ subject: `New comment on your Cap: ${videoName}`,
+ react: NewComment({
+ email: recipient.email,
+ url: videoUrl,
+ videoName,
+ commenterName,
+ commentContent: params.comment.content,
+ manageNotificationsUrl: notificationSettingsUrl(),
+ }),
+ });
+ } catch (error) {
+ console.error("Failed to send new comment email:", error);
+ }
+}
+
export async function createAnonymousViewNotification({
videoId,
sessionId,
@@ -387,6 +483,7 @@ export async function sendFirstViewEmail(
url: videoUrl,
videoName: displayName,
viewerName,
+ manageNotificationsUrl: notificationSettingsUrl(),
}),
});
} catch (error) {
diff --git a/packages/database/emails/components/Footer.tsx b/packages/database/emails/components/Footer.tsx
index 500113b54..32fec015e 100644
--- a/packages/database/emails/components/Footer.tsx
+++ b/packages/database/emails/components/Footer.tsx
@@ -3,13 +3,24 @@ import { Hr, Tailwind, Text } from "@react-email/components";
export default function Footer({
email,
marketing,
+ manageNotificationsUrl,
}: {
email: string;
marketing?: boolean;
+ manageNotificationsUrl?: string;
}) {
return (
<Tailwind>
<Hr className="mx-0 my-6 w-full border border-gray-200" />
+ {manageNotificationsUrl && (
+ <Text className="text-[12px] leading-6 text-gray-500">
+ Don't want to receive these notifications?{" "}
+ <a href={manageNotificationsUrl} className="text-gray-600 underline">
+ Disable this notification
+ </a>
+ .
+ </Text>
+ )}
{marketing ? (
<Text className="text-[12px] leading-6 text-gray-500">
This email was intended for{" "}
diff --git a/packages/database/emails/first-view.tsx b/packages/database/emails/first-view.tsx
index 8a6e8fa32..f78a50127 100644
--- a/packages/database/emails/first-view.tsx
+++ b/packages/database/emails/first-view.tsx
@@ -19,11 +19,13 @@ export function FirstView({
url = "",
videoName = "",
viewerName = "",
+ manageNotificationsUrl,
}: {
email: string;
url: string;
videoName: string;
viewerName: string;
+ manageNotificationsUrl?: string;
}) {
return (
<Html>
@@ -65,7 +67,10 @@ export function FirstView({
<Text className="max-w-sm flex-wrap break-words font-medium text-purple-600 no-underline">
{url.replace(/^https?:\/\//, "")}
</Text>
- <Footer email={email} />
+ <Footer
+ email={email}
+ manageNotificationsUrl={manageNotificationsUrl}
+ />
</Container>
</Body>
</Tailwind>
diff --git a/packages/database/emails/new-comment.tsx b/packages/database/emails/new-comment.tsx
index 03e2d851a..477573a24 100644
--- a/packages/database/emails/new-comment.tsx
+++ b/packages/database/emails/new-comment.tsx
@@ -20,12 +20,14 @@ export function NewComment({
videoName = "",
commenterName = "",
commentContent = "",
+ manageNotificationsUrl,
}: {
email: string;
url: string;
videoName: string;
commenterName: string;
commentContent: string;
+ manageNotificationsUrl?: string;
}) {
return (
<Html>
@@ -71,7 +73,10 @@ export function NewComment({
<Text className="max-w-sm flex-wrap break-words font-medium text-purple-600 no-underline">
{url.replace(/^https?:\/\//, "")}
</Text>
- <Footer email={email} />
+ <Footer
+ email={email}
+ manageNotificationsUrl={manageNotificationsUrl}
+ />
</Container>
</Body>
</Tailwind>