Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

13.2 KB
Raw Blame
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 { serverEnv } from "@cap/env";
import type { Notification, NotificationBase } from "@cap/web-api-contract";
import { Comment, User, Video } from "@cap/web-domain";
import { and, eq, gte, inArray, isNull, ne, or, sql } from "drizzle-orm";
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
>;

type AuthoredNotificationData = Exclude<
	NotificationSpecificData,
	{ type: "anon_view" }
>;

type CreateNotificationInput<D = AuthoredNotificationData> =
	D extends AuthoredNotificationData
		? Omit<D, "author"> & { authorId: string } & {
				parentCommentId?: Comment.CommentId;
			}
		: never;

const ANON_NOTIF_WINDOW_MS = 5 * 60 * 1000;
const ANON_NOTIF_MAX_PER_VIDEO = 50;

const isDuplicateEntryError = (error: unknown) => {
	if (!error || typeof error !== "object") return false;
	const duplicateEntryError = error as {
		code?: string;
		errno?: number;
		message?: string;
		sqlMessage?: string;
	};
	if (
		duplicateEntryError.code !== "ER_DUP_ENTRY" &&
		duplicateEntryError.errno !== 1062
	)
		return false;
	const message =
		`${duplicateEntryError.sqlMessage ?? ""} ${duplicateEntryError.message ?? ""}`.trim();
	return message.includes("dedup_key_idx");
};

export async function createNotification(
	notification: CreateNotificationInput,
) {
	try {
		const [videoExists] = await db()
			.select({ id: videos.id, ownerId: videos.ownerId })
			.from(videos)
			.where(eq(videos.id, Video.VideoId.make(notification.videoId)))
			.limit(1);

		if (!videoExists) {
			console.error("Video not found for videoId:", notification.videoId);
			throw new Error(`Video not found for videoId: ${notification.videoId}`);
		}

		const [ownerResult] = await db()
			.select({
				id: users.id,
				activeOrganizationId: users.activeOrganizationId,
				preferences: users.preferences,
			})
			.from(users)
			.where(eq(users.id, videoExists.ownerId))
			.limit(1);

		if (!ownerResult) {
			console.warn(
				"Owner not found for videoId:",
				notification.videoId,
				"ownerId:",
				videoExists.ownerId,
				"- skipping notification creation",
			);
			return;
		}

		const videoResult = {
			videoId: videoExists.id,
			ownerId: ownerResult.id,
			activeOrganizationId: ownerResult.activeOrganizationId,
			preferences: ownerResult.preferences,
		};

		const { type, ...data } = notification;

		if (type === "reply" && notification.parentCommentId) {
			const [parentComment] = await db()
				.select({ authorId: comments.authorId })
				.from(comments)
				.where(eq(comments.id, notification.parentCommentId))
				.limit(1);

			const recipientId = parentComment?.authorId;
			if (!recipientId) return;
			if (
				recipientId === videoResult.ownerId ||
				recipientId === notification.authorId
			)
				return;

			const [recipientUser] = await db()
				.select({
					preferences: users.preferences,
					activeOrganizationId: users.activeOrganizationId,
				})
				.from(users)
				.where(eq(users.id, recipientId))
				.limit(1);

			if (!recipientUser) {
				console.warn(`Reply recipient user ${recipientId} not found`);
				return;
			}

			const recipientPrefs = recipientUser.preferences as
				| UserPreferences
				| undefined;
			if (recipientPrefs?.notifications?.pauseReplies) return;

			const [existingReply] = await db()
				.select({ id: notifications.id })
				.from(notifications)
				.where(
					and(
						eq(notifications.type, "reply"),
						eq(notifications.recipientId, recipientId),
						sql`JSON_EXTRACT(${notifications.data}, '$.comment.id') = ${notification.comment.id}`,
					),
				)
				.limit(1);

			if (existingReply) return;

			const notificationId = nanoId();

			await db().insert(notifications).values({
				id: notificationId,
				orgId: recipientUser.activeOrganizationId,
				recipientId,
				type,
				data,
				videoId: notification.videoId,
			});

			return { success: true, notificationId };
		}

		if (videoResult.ownerId === notification.authorId) {
			return;
		}

		const preferences = videoResult.preferences as UserPreferences;
		if (preferences?.notifications) {
			const notificationPrefs = preferences.notifications;

			const shouldSkipNotification =
				(type === "comment" && notificationPrefs.pauseComments) ||
				(type === "view" && notificationPrefs.pauseViews) ||
				(type === "reaction" && notificationPrefs.pauseReactions);

			if (shouldSkipNotification) {
				return;
			}
		}

		let hasExistingNotification = false;
		if (type === "view") {
			const [existingNotification] = await db()
				.select({ id: notifications.id })
				.from(notifications)
				.where(
					and(
						eq(notifications.type, "view"),
						eq(notifications.recipientId, videoResult.ownerId),
						eq(notifications.videoId, notification.videoId),
						sql`JSON_EXTRACT(${notifications.data}, '$.authorId') = ${notification.authorId}`,
					),
				)
				.limit(1);

			hasExistingNotification = !!existingNotification;
		} else if (type === "comment" || type === "reaction") {
			const [existingNotification] = await db()
				.select({ id: notifications.id })
				.from(notifications)
				.where(
					and(
						eq(notifications.type, type),
						eq(notifications.recipientId, videoResult.ownerId),
						sql`JSON_EXTRACT(${notifications.data}, '$.comment.id') = ${notification.comment.id}`,
					),
				)
				.limit(1);

			hasExistingNotification = !!existingNotification;
		}

		if (hasExistingNotification) {
			return;
		}

		const notificationId = nanoId();

		if (!videoResult.activeOrganizationId) {
			console.warn(
				`User ${videoResult.ownerId} has no active organization, skipping notification`,
			);
			return;
		}

		await db().insert(notifications).values({
			id: notificationId,
			orgId: videoResult.activeOrganizationId,
			recipientId: videoResult.ownerId,
			type,
			data,
			videoId: notification.videoId,
		});

		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);
		throw error;
	}
}

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)),
					// Media comments email through the same path as text comments, so
					// they must share the throttle window with them.
					inArray(comments.type, ["text", "video", "audio"]),
					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 = `${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,
	anonName,
	location,
}: {
	videoId: string;
	sessionId: string;
	anonName: string;
	location: string | null;
}) {
	const sessionHash = getSessionHash(sessionId);
	const dedupKey = `anon_view:${videoId}:${sessionHash}`;
	const rateWindowStart = new Date(Date.now() - ANON_NOTIF_WINDOW_MS);

	try {
		const database = db();

		const [existingNotification] = await database
			.select({ id: notifications.id })
			.from(notifications)
			.where(eq(notifications.dedupKey, dedupKey))
			.limit(1);

		if (existingNotification) return;

		const [videoWithOwner] = await database
			.select({
				videoId: videos.id,
				ownerId: users.id,
				activeOrganizationId: users.activeOrganizationId,
				preferences: users.preferences,
			})
			.from(videos)
			.innerJoin(users, eq(users.id, videos.ownerId))
			.where(eq(videos.id, Video.VideoId.make(videoId)))
			.limit(1);

		if (!videoWithOwner?.activeOrganizationId) return;

		const preferences = videoWithOwner.preferences as UserPreferences;
		if (preferences?.notifications?.pauseAnonViews) return;

		const [recentNotificationCount] = await database
			.select({ count: sql<number>`COUNT(*)` })
			.from(notifications)
			.where(
				and(
					eq(notifications.type, "anon_view"),
					eq(notifications.recipientId, videoWithOwner.ownerId),
					gte(notifications.createdAt, rateWindowStart),
					eq(notifications.videoId, videoId),
				),
			)
			.limit(1);

		if (Number(recentNotificationCount?.count ?? 0) >= ANON_NOTIF_MAX_PER_VIDEO)
			return;

		await database.insert(notifications).values({
			id: nanoId(),
			orgId: videoWithOwner.activeOrganizationId,
			recipientId: videoWithOwner.ownerId,
			type: "anon_view",
			data: { videoId, anonName, location },
			videoId,
			dedupKey,
		});
	} catch (error) {
		if (isDuplicateEntryError(error)) return;
		throw error;
	}
}

export async function sendFirstViewEmail(
	params:
		| { videoId: string; viewerName: string; isAnonymous: true }
		| { videoId: string; viewerUserId: string; isAnonymous: false },
) {
	try {
		const database = db();

		const videoWithOwner = await database
			.select({
				firstViewEmailSentAt: videos.firstViewEmailSentAt,
				videoName: videos.name,
				ownerId: videos.ownerId,
				ownerEmail: users.email,
				preferences: users.preferences,
			})
			.from(videos)
			.innerJoin(users, eq(users.id, videos.ownerId))
			.where(eq(videos.id, Video.VideoId.make(params.videoId)))
			.limit(1)
			.then((rows) => {
				const row = rows[0];
				if (!row || row.firstViewEmailSentAt) return null;
				return row;
			});

		if (!videoWithOwner?.ownerEmail) return;

		if (!params.isAnonymous && params.viewerUserId === videoWithOwner.ownerId)
			return;

		const preferences = videoWithOwner.preferences as UserPreferences;
		if (params.isAnonymous) {
			if (preferences?.notifications?.pauseAnonViews) return;
		} else {
			if (preferences?.notifications?.pauseViews) return;
		}

		const [result] = await database
			.update(videos)
			.set({ firstViewEmailSentAt: new Date() })
			.where(
				and(
					eq(videos.id, Video.VideoId.make(params.videoId)),
					isNull(videos.firstViewEmailSentAt),
				),
			);

		if (result.affectedRows === 0) return;

		let viewerName: string;
		if (params.isAnonymous) {
			viewerName = params.viewerName;
		} else {
			const [viewer] = await database
				.select({ name: users.name, email: users.email })
				.from(users)
				.where(eq(users.id, User.UserId.make(params.viewerUserId)))
				.limit(1);
			viewerName = viewer?.name || viewer?.email || "Someone";
		}

		const videoUrl = `${serverEnv().WEB_URL}/s/${params.videoId}`;

		const displayName = videoWithOwner.videoName || "Untitled Video";

		await sendEmail({
			email: videoWithOwner.ownerEmail,
			subject: `Your Cap "${displayName}" just got its first view!`,
			react: FirstView({
				email: videoWithOwner.ownerEmail,
				url: videoUrl,
				videoName: displayName,
				viewerName,
				manageNotificationsUrl: notificationSettingsUrl(),
			}),
		});
	} catch (error) {
		console.error("Failed to send first view email:", error);
	}
}