From 88dcf9514cb0e0144c69322d43bf55d2e1c81a33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yusuf=20=C4=B0pek?= Date: Sat, 7 Feb 2026 13:56:26 +0300 Subject: [PATCH] feat: Introduce guest access for video viewing, implement user notification settings via email and Telegram, and add rate limiting infrastructure. --- .../projects/[projectId]/members/page.tsx | 6 +- app/(dashboard)/projects/[projectId]/page.tsx | 49 ++ .../[projectId]/videos/[videoId]/page.tsx | 13 +- app/(dashboard)/settings/page.tsx | 498 ++++++++++++++++++ .../workspaces/[workspaceId]/members/page.tsx | 6 +- .../[projectId]/videos/[videoId]/route.ts | 5 +- app/api/projects/[projectId]/videos/route.ts | 13 + app/api/settings/notifications/route.ts | 220 ++++++++ .../versions/[versionId]/comments/route.ts | 40 ++ app/api/watch/[videoId]/route.ts | 14 +- app/watch/[videoId]/page.tsx | 133 +++-- bun.lock | 6 + components/guest-gate.tsx | 72 +++ lib/notifications.ts | 415 +++++++++++++++ package.json | 10 +- prisma/schema.prisma | 49 ++ scripts/db-extras.ts | 56 ++ 17 files changed, 1566 insertions(+), 39 deletions(-) create mode 100644 app/(dashboard)/settings/page.tsx create mode 100644 app/api/settings/notifications/route.ts create mode 100644 components/guest-gate.tsx create mode 100644 lib/notifications.ts create mode 100644 scripts/db-extras.ts diff --git a/app/(dashboard)/projects/[projectId]/members/page.tsx b/app/(dashboard)/projects/[projectId]/members/page.tsx index 0164da8..557b6f6 100644 --- a/app/(dashboard)/projects/[projectId]/members/page.tsx +++ b/app/(dashboard)/projects/[projectId]/members/page.tsx @@ -101,7 +101,11 @@ export default function ProjectMembersPage() { return; } - setSuccess(`Invited ${data.user.name || data.user.email} as ${inviteRole.toLowerCase()}`); + if (data.user) { + setSuccess(`Invited ${data.user.name || data.user.email || inviteEmail} as ${inviteRole.toLowerCase()}`); + } else { + setSuccess(data.message || `Invitation sent to ${inviteEmail}`); + } setInviteEmail(''); fetchMembers(); } catch { diff --git a/app/(dashboard)/projects/[projectId]/page.tsx b/app/(dashboard)/projects/[projectId]/page.tsx index dcfde3d..3cf4a74 100644 --- a/app/(dashboard)/projects/[projectId]/page.tsx +++ b/app/(dashboard)/projects/[projectId]/page.tsx @@ -16,6 +16,7 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { VideoCard } from '@/components/video-card'; +import { GuestGate } from '@/components/guest-gate'; import { auth } from '@/lib/auth'; import { db } from '@/lib/db'; @@ -135,7 +136,55 @@ export default async function ProjectPage({ params }: ProjectPageProps) { }); const canEdit = isOwner || project.members[0]?.role === 'ADMIN' || workspaceRole === 'OWNER' || workspaceRole === 'ADMIN'; + const isAuthenticated = !!session?.user?.id; + // Guest name gate for unauthenticated users on public projects + if (!isAuthenticated && isPublic) { + return ( + + + + ); + } + + return ( + + ); +} + +function ProjectContent({ + project, + projectId, + videos, + canEdit, + isOwner, + isPublic, + workspaceRole, +}: { + project: { name: string; description: string | null; visibility: string; workspace: { id: string; name: string } | null; members: { role: string }[] }; + projectId: string; + videos: { id: string; title: string; thumbnailUrl: string; currentVersion: number; commentCount: number; duration: string; lastUpdated: string }[]; + canEdit: boolean; + isOwner: boolean; + isPublic: boolean; + workspaceRole: string | null; +}) { return (
{/* Back link */} diff --git a/app/(dashboard)/projects/[projectId]/videos/[videoId]/page.tsx b/app/(dashboard)/projects/[projectId]/videos/[videoId]/page.tsx index 26aace5..561d466 100644 --- a/app/(dashboard)/projects/[projectId]/videos/[videoId]/page.tsx +++ b/app/(dashboard)/projects/[projectId]/videos/[videoId]/page.tsx @@ -101,6 +101,7 @@ interface VideoData { members: { role: string }[]; }; versions: (Version & { comments: Comment[] })[]; + isAuthenticated: boolean; } function formatTime(seconds: number): string { @@ -167,6 +168,14 @@ export default function VideoPage() { const [isSubmittingEdit, setIsSubmittingEdit] = useState(false); const [deletingCommentId, setDeletingCommentId] = useState(null); + // Guest name (for unauthenticated users on public projects) + const [guestName, setGuestName] = useState(''); + useEffect(() => { + const saved = localStorage.getItem('openframe_guest_name'); + if (saved) setGuestName(saved); + }, []); + const isGuest = video ? !video.isAuthenticated : false; + // New version dialog const [showVersionDialog, setShowVersionDialog] = useState(false); const [newVersionUrl, setNewVersionUrl] = useState(''); @@ -371,6 +380,7 @@ export default function VideoPage() { content: voiceData ? commentText.trim() || null : commentText, timestamp: selectedTimestamp ?? currentTime, ...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }), + ...(isGuest && guestName && { guestName }), }), }); @@ -395,7 +405,7 @@ export default function VideoPage() { } finally { setIsSubmittingComment(false); } - }, [commentText, currentTime, selectedTimestamp, activeVersion, activeVersionId]); + }, [commentText, currentTime, selectedTimestamp, activeVersion, activeVersionId, isGuest, guestName]); // Voice recording handlers const startRecording = useCallback(async () => { @@ -631,6 +641,7 @@ export default function VideoPage() { timestamp: comments.find((c) => c.id === parentId)?.timestamp ?? currentTime, parentId, ...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }), + ...(isGuest && guestName && { guestName }), }), }); if (res.ok) { diff --git a/app/(dashboard)/settings/page.tsx b/app/(dashboard)/settings/page.tsx new file mode 100644 index 0000000..c01d987 --- /dev/null +++ b/app/(dashboard)/settings/page.tsx @@ -0,0 +1,498 @@ +'use client'; + +import { useState, useEffect, useCallback } from 'react'; +import { Bell, Send, Mail, CheckCircle2, AlertCircle, Loader2, ExternalLink, Globe } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Separator } from '@/components/ui/separator'; +import { Badge } from '@/components/ui/badge'; +import { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectLabel, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { cn } from '@/lib/utils'; + +interface NotificationSettings { + telegramBotToken: string | null; + telegramChatId: string | null; + telegramEnabled: boolean; + emailEnabled: boolean; + onNewVideo: boolean; + onNewComment: boolean; + onNewReply: boolean; + timezone: string; +} + +function ToggleButton({ + enabled, + onToggle, + label, + description, +}: { + enabled: boolean; + onToggle: () => void; + label: string; + description?: string; +}) { + return ( + + ); +} + +export default function SettingsPage() { + const [settings, setSettings] = useState({ + telegramBotToken: null, + telegramChatId: null, + telegramEnabled: false, + emailEnabled: false, + onNewVideo: true, + onNewComment: true, + onNewReply: true, + timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC', + }); + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [testing, setTesting] = useState(null); + const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null); + + // Form state for Telegram fields (separate from saved settings for editing) + const [telegramToken, setTelegramToken] = useState(''); + const [telegramChatId, setTelegramChatId] = useState(''); + + useEffect(() => { + async function fetchSettings() { + try { + const res = await fetch('/api/settings/notifications'); + if (res.ok) { + const data = await res.json(); + setSettings(data); + setTelegramToken(data.telegramBotToken || ''); + setTelegramChatId(data.telegramChatId || ''); + } + } catch { + console.error('Failed to fetch notification settings'); + } finally { + setLoading(false); + } + } + fetchSettings(); + }, []); + + const showMessage = useCallback((type: 'success' | 'error', text: string) => { + setMessage({ type, text }); + setTimeout(() => setMessage(null), 4000); + }, []); + + const handleSave = useCallback(async () => { + setSaving(true); + try { + const res = await fetch('/api/settings/notifications', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ...settings, + telegramBotToken: telegramToken || null, + telegramChatId: telegramChatId || null, + }), + }); + + if (res.ok) { + const data = await res.json(); + setSettings(data); + showMessage('success', 'Settings saved'); + } else { + const data = await res.json(); + showMessage('error', data.error || 'Failed to save'); + } + } catch { + showMessage('error', 'Failed to save settings'); + } finally { + setSaving(false); + } + }, [settings, telegramToken, telegramChatId, showMessage]); + + const handleTest = useCallback( + async (channel: 'telegram' | 'email') => { + setTesting(channel); + try { + const res = await fetch('/api/settings/notifications', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + channel, + telegramBotToken: telegramToken, + telegramChatId, + }), + }); + const data = await res.json(); + if (res.ok) { + showMessage('success', data.message); + } else { + showMessage('error', data.error || 'Test failed'); + } + } catch { + showMessage('error', 'Test failed'); + } finally { + setTesting(null); + } + }, + [telegramToken, telegramChatId, showMessage] + ); + + if (loading) { + return ( +
+ +
+ ); + } + + return ( +
+
+

Settings

+

+ Manage your notification preferences +

+
+ + {/* Status message */} + {message && ( +
+ {message.type === 'success' ? ( + + ) : ( + + )} + {message.text} +
+ )} + + {/* Event Subscriptions */} + + + + + Notification Events + + + Choose which events trigger notifications + + + + + setSettings((s) => ({ ...s, onNewVideo: !s.onNewVideo })) + } + label="New Video Added" + description="When a new video is added to one of your projects" + /> + + setSettings((s) => ({ ...s, onNewComment: !s.onNewComment })) + } + label="New Comment" + description="When someone leaves a comment on your videos" + /> + + setSettings((s) => ({ ...s, onNewReply: !s.onNewReply })) + } + label="New Reply" + description="When someone replies to a comment thread" + /> + + + + {/* Telegram */} + + +
+ + + Telegram + + + {settings.telegramEnabled ? 'Enabled' : 'Disabled'} + +
+ + Get instant notifications via a Telegram bot + +
+ +
+

Setup instructions:

+
    +
  1. + Open Telegram and message{' '} + + @BotFather + +
  2. +
  3. Send /newbot and follow the prompts to create a bot
  4. +
  5. Copy the Bot Token and paste it below
  6. +
  7. + Send a message to your new bot, then visit{' '} + + api.telegram.org + {' '} + /bot<token>/getUpdates to find your Chat ID +
  8. +
+
+ +
+
+ + setTelegramToken(e.target.value)} + className="mt-1 font-mono text-sm" + /> +
+
+ + setTelegramChatId(e.target.value)} + className="mt-1 font-mono text-sm" + /> +
+
+ +
+ + setSettings((s) => ({ ...s, telegramEnabled: !s.telegramEnabled })) + } + label="Enable Telegram notifications" + /> +
+ + +
+
+ + {/* Email */} + + +
+ + + Email + + + {settings.emailEnabled ? 'Enabled' : 'Disabled'} + +
+ + Receive notification emails to your account email address + +
+ + + setSettings((s) => ({ ...s, emailEnabled: !s.emailEnabled })) + } + label="Enable email notifications" + /> + + + +
+ + {/* Timezone */} + + + + + Timezone + + + Timestamps in notifications will use this timezone + + + + + + + + + + {/* Save button */} +
+ +
+
+ ); +} diff --git a/app/(dashboard)/workspaces/[workspaceId]/members/page.tsx b/app/(dashboard)/workspaces/[workspaceId]/members/page.tsx index cc9fabe..c534c4a 100644 --- a/app/(dashboard)/workspaces/[workspaceId]/members/page.tsx +++ b/app/(dashboard)/workspaces/[workspaceId]/members/page.tsx @@ -101,7 +101,11 @@ export default function WorkspaceMembersPage() { return; } - setSuccess(`Invited ${data.user.name || data.user.email} as ${inviteRole.toLowerCase()}`); + if (data.user) { + setSuccess(`Invited ${data.user.name || data.user.email || inviteEmail} as ${inviteRole.toLowerCase()}`); + } else { + setSuccess(data.message || `Invitation sent to ${inviteEmail}`); + } setInviteEmail(''); fetchMembers(); } catch { diff --git a/app/api/projects/[projectId]/videos/[videoId]/route.ts b/app/api/projects/[projectId]/videos/[videoId]/route.ts index 64ffedc..6b06661 100644 --- a/app/api/projects/[projectId]/videos/[videoId]/route.ts +++ b/app/api/projects/[projectId]/videos/[videoId]/route.ts @@ -54,7 +54,10 @@ export async function GET(request: NextRequest, { params }: RouteParams) { return NextResponse.json({ error: 'Access denied' }, { status: 403 }); } - return NextResponse.json(video); + return NextResponse.json({ + ...video, + isAuthenticated: !!session?.user?.id, + }); } catch (error) { console.error('Error fetching video:', error); return NextResponse.json( diff --git a/app/api/projects/[projectId]/videos/route.ts b/app/api/projects/[projectId]/videos/route.ts index 861375f..afecb96 100644 --- a/app/api/projects/[projectId]/videos/route.ts +++ b/app/api/projects/[projectId]/videos/route.ts @@ -4,6 +4,7 @@ import { auth } from '@/lib/auth'; import { ProjectMemberRole } from '@prisma/client'; import { validateUrl, validateOptionalUrl } from '@/lib/validation'; import { rateLimit } from '@/lib/rate-limit'; +import { notifyProjectOwner } from '@/lib/notifications'; type RouteParams = { params: Promise<{ projectId: string }> }; @@ -141,6 +142,18 @@ export async function POST(request: NextRequest, { params }: RouteParams) { }, }); + // Notify project owner (fire-and-forget, skip if they added it themselves) + if (project.ownerId !== session.user.id) { + const baseUrl = process.env.NEXTAUTH_URL || ''; + notifyProjectOwner(project.ownerId, { + type: 'new_video', + projectName: project.name, + videoTitle: title.trim(), + addedBy: session.user.name || 'A team member', + url: `${baseUrl}/watch/${video.id}`, + }).catch((err) => console.error('Notification failed:', err)); + } + return NextResponse.json(video, { status: 201 }); } catch (error) { console.error('Error creating video:', error); diff --git a/app/api/settings/notifications/route.ts b/app/api/settings/notifications/route.ts new file mode 100644 index 0000000..71fdacf --- /dev/null +++ b/app/api/settings/notifications/route.ts @@ -0,0 +1,220 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { db } from '@/lib/db'; +import { auth } from '@/lib/auth'; +import { rateLimit } from '@/lib/rate-limit'; +import nodemailer from 'nodemailer'; +import { testEmailHtml } from '@/lib/notifications'; + +// GET /api/settings/notifications — Fetch current notification preferences +export async function GET() { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const settings = await db.notificationSetting.findUnique({ + where: { userId: session.user.id }, + }); + + // Return defaults if no settings exist yet + return NextResponse.json( + settings ?? { + telegramBotToken: null, + telegramChatId: null, + telegramEnabled: false, + emailEnabled: false, + onNewVideo: true, + onNewComment: true, + onNewReply: true, + timezone: 'UTC', + } + ); + } catch (error) { + console.error('Error fetching notification settings:', error); + return NextResponse.json( + { error: 'Failed to fetch settings' }, + { status: 500 } + ); + } +} + +// PUT /api/settings/notifications — Update notification preferences +export async function PUT(request: NextRequest) { + try { + const limited = await rateLimit(request, 'mutate'); + if (limited) return limited; + + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const body = await request.json(); + const { + telegramBotToken, + telegramChatId, + telegramEnabled, + emailEnabled, + onNewVideo, + onNewComment, + onNewReply, + timezone, + } = body; + + // Validate: if enabling Telegram, both token and chatId are required + if (telegramEnabled && (!telegramBotToken || !telegramChatId)) { + return NextResponse.json( + { error: 'Telegram Bot Token and Chat ID are required to enable Telegram notifications' }, + { status: 400 } + ); + } + + const settings = await db.notificationSetting.upsert({ + where: { userId: session.user.id }, + create: { + userId: session.user.id, + telegramBotToken: telegramBotToken || null, + telegramChatId: telegramChatId || null, + telegramEnabled: !!telegramEnabled, + emailEnabled: !!emailEnabled, + onNewVideo: onNewVideo ?? true, + onNewComment: onNewComment ?? true, + onNewReply: onNewReply ?? true, + timezone: timezone || 'UTC', + }, + update: { + telegramBotToken: telegramBotToken || null, + telegramChatId: telegramChatId || null, + telegramEnabled: !!telegramEnabled, + emailEnabled: !!emailEnabled, + onNewVideo: onNewVideo ?? true, + onNewComment: onNewComment ?? true, + onNewReply: onNewReply ?? true, + timezone: timezone || 'UTC', + }, + }); + + return NextResponse.json(settings); + } catch (error) { + console.error('Error updating notification settings:', error); + return NextResponse.json( + { error: 'Failed to update settings' }, + { status: 500 } + ); + } +} + +// POST /api/settings/notifications — Test a notification channel +export async function POST(request: NextRequest) { + try { + const limited = await rateLimit(request, 'mutate'); + if (limited) return limited; + + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const body = await request.json(); + const { channel, telegramBotToken, telegramChatId } = body; + + if (channel === 'telegram') { + if (!telegramBotToken || !telegramChatId) { + return NextResponse.json( + { error: 'Bot Token and Chat ID are required' }, + { status: 400 } + ); + } + + const settingsUrl = `${process.env.NEXTAUTH_URL || ''}/settings`; + const telegramPayload: Record = { + chat_id: telegramChatId, + text: '✅ OpenFrame notifications connected successfully!\n\nYou will receive notifications here when activity happens on your projects.', + link_preview_options: { is_disabled: true }, + }; + // Telegram inline keyboard buttons require HTTPS URLs + if (settingsUrl.startsWith('https://')) { + telegramPayload.reply_markup = { + inline_keyboard: [[{ text: 'Open Settings', url: settingsUrl }]], + }; + } + const res = await fetch(`https://api.telegram.org/bot${telegramBotToken}/sendMessage`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(telegramPayload), + }); + + if (!res.ok) { + const data = await res.json().catch(() => ({})); + const desc = (data as { description?: string }).description || 'Unknown error'; + return NextResponse.json( + { error: `Telegram test failed: ${desc}` }, + { status: 400 } + ); + } + + return NextResponse.json({ success: true, message: 'Test message sent to Telegram' }); + } + + if (channel === 'email') { + const user = await db.user.findUnique({ + where: { id: session.user.id }, + select: { email: true }, + }); + + if (!user?.email) { + return NextResponse.json( + { error: 'No email address on your account' }, + { status: 400 } + ); + } + + const smtpHost = process.env.SMTP_HOST; + const smtpPort = Number(process.env.SMTP_PORT || '587'); + const smtpUser = process.env.SMTP_USER; + const smtpPass = process.env.SMTP_PASSWORD; + + if (!smtpHost || !smtpUser || !smtpPass) { + return NextResponse.json( + { error: 'Email service not configured (SMTP settings missing)' }, + { status: 500 } + ); + } + + const transporter = nodemailer.createTransport({ + host: smtpHost, + port: smtpPort, + secure: smtpPort === 465, + auth: { user: smtpUser, pass: smtpPass }, + }); + + const fromAddress = process.env.SMTP_FROM || process.env.EMAIL_FROM || 'OpenFrame '; + + try { + await transporter.sendMail({ + from: fromAddress, + to: user.email, + subject: '[OpenFrame] Test notification', + html: testEmailHtml(), + }); + } catch (emailErr) { + console.error('SMTP test email failed:', emailErr); + return NextResponse.json( + { error: 'Failed to send test email — check SMTP settings' }, + { status: 500 } + ); + } + + return NextResponse.json({ success: true, message: `Test email sent to ${user.email}` }); + } + + return NextResponse.json({ error: 'Unknown channel' }, { status: 400 }); + } catch (error) { + console.error('Error testing notification:', error); + return NextResponse.json( + { error: 'Failed to test notification' }, + { status: 500 } + ); + } +} diff --git a/app/api/versions/[versionId]/comments/route.ts b/app/api/versions/[versionId]/comments/route.ts index 474c92b..9282902 100644 --- a/app/api/versions/[versionId]/comments/route.ts +++ b/app/api/versions/[versionId]/comments/route.ts @@ -3,6 +3,7 @@ import { db } from '@/lib/db'; import { auth } from '@/lib/auth'; import { validateOptionalUrl } from '@/lib/validation'; import { rateLimit } from '@/lib/rate-limit'; +import { notifyProjectOwner } from '@/lib/notifications'; type RouteParams = { params: Promise<{ versionId: string }> }; @@ -184,6 +185,45 @@ export async function POST(request: NextRequest, { params }: RouteParams) { }, }); + // Notify project owner (fire-and-forget, skip self-notifications) + const commentAuthorName = session?.user?.name || guestName || 'Someone'; + const isOwnProject = session?.user?.id === project.ownerId; + if (!isOwnProject) { + const baseUrl = process.env.NEXTAUTH_URL || ''; + const videoTitle = version.video.title || 'Untitled Video'; + const mins = Math.floor(parseFloat(timestamp) / 60); + const secs = Math.floor(parseFloat(timestamp) % 60); + const ts = `${mins}:${secs.toString().padStart(2, '0')}`; + + if (parentId) { + // It's a reply — look up parent author + const parentComment = await db.comment.findUnique({ + where: { id: parentId }, + include: { author: { select: { name: true } } }, + }); + notifyProjectOwner(project.ownerId, { + type: 'new_reply', + projectName: project.name, + videoTitle, + replyAuthor: commentAuthorName, + replyText: content?.trim() || '(voice note)', + parentAuthor: parentComment?.author?.name || parentComment?.guestName || 'Someone', + timestamp: ts, + url: `${baseUrl}/watch/${version.video.id}`, + }).catch((err) => console.error('Notification failed:', err)); + } else { + notifyProjectOwner(project.ownerId, { + type: 'new_comment', + projectName: project.name, + videoTitle, + commentAuthor: commentAuthorName, + commentText: content?.trim() || '(voice note)', + timestamp: ts, + url: `${baseUrl}/watch/${version.video.id}`, + }).catch((err) => console.error('Notification failed:', err)); + } + } + return NextResponse.json(comment, { status: 201 }); } catch (error) { console.error('Error creating comment:', error); diff --git a/app/api/watch/[videoId]/route.ts b/app/api/watch/[videoId]/route.ts index 2735c34..e53cc73 100644 --- a/app/api/watch/[videoId]/route.ts +++ b/app/api/watch/[videoId]/route.ts @@ -53,7 +53,19 @@ export async function GET(request: NextRequest, { params }: RouteParams) { return NextResponse.json({ error: 'Access denied' }, { status: 403 }); } - return NextResponse.json(video); + // Include auth context so the client knows if the viewer is a guest + const { project, ...videoData } = video; + return NextResponse.json({ + ...videoData, + projectId: video.projectId, + project: { + name: project.name, + ownerId: project.ownerId, + visibility: project.visibility, + }, + isAuthenticated: !!session?.user?.id, + canComment: isOwner || isMember || isPublic, + }); } catch (error) { console.error('Error fetching video:', error); return NextResponse.json( diff --git a/app/watch/[videoId]/page.tsx b/app/watch/[videoId]/page.tsx index 5f228b5..9ee07c9 100644 --- a/app/watch/[videoId]/page.tsx +++ b/app/watch/[videoId]/page.tsx @@ -25,6 +25,7 @@ import { Trash2, X, ArrowUpRight, + User, } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; @@ -83,9 +84,11 @@ interface VideoData { project: { name: string; ownerId: string; - members: { role: string }[]; + visibility: string; }; versions: (Version & { comments: Comment[] })[]; + isAuthenticated: boolean; + canComment: boolean; } function formatTime(seconds: number): string { @@ -148,6 +151,18 @@ export default function WatchPage() { const [isSubmittingEdit, setIsSubmittingEdit] = useState(false); const [deletingCommentId, setDeletingCommentId] = useState(null); const [guestName, setGuestName] = useState(''); + const [guestNameConfirmed, setGuestNameConfirmed] = useState(false); + + // Restore guest name from localStorage + useEffect(() => { + const saved = localStorage.getItem('openframe_guest_name'); + if (saved) { + setGuestName(saved); + setGuestNameConfirmed(true); + } + }, []); + + const isGuest = video ? !video.isAuthenticated : false; // Fetch video data useEffect(() => { @@ -310,6 +325,7 @@ export default function WatchPage() { content: voiceData ? commentText.trim() || null : commentText, timestamp: selectedTimestamp ?? currentTime, ...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }), + ...(isGuest && guestName && { guestName }), }), }); @@ -334,7 +350,7 @@ export default function WatchPage() { } finally { setIsSubmittingComment(false); } - }, [commentText, currentTime, selectedTimestamp, activeVersion, activeVersionId]); + }, [commentText, currentTime, selectedTimestamp, activeVersion, activeVersionId, isGuest, guestName]); // Voice recording handlers const startRecording = useCallback(async () => { @@ -536,11 +552,11 @@ export default function WatchPage() { versions: prev.versions.map((v) => v.id === activeVersionId ? { - ...v, - comments: v.comments.map((c) => - c.id === commentId ? { ...c, isResolved: !c.isResolved } : c - ), - } + ...v, + comments: v.comments.map((c) => + c.id === commentId ? { ...c, isResolved: !c.isResolved } : c + ), + } : v ), }; @@ -567,6 +583,7 @@ export default function WatchPage() { timestamp: comments.find((c) => c.id === parentId)?.timestamp ?? currentTime, parentId, ...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }), + ...(isGuest && guestName && { guestName }), }), }); if (res.ok) { @@ -578,13 +595,13 @@ export default function WatchPage() { versions: prev.versions.map((v) => v.id === activeVersionId ? { - ...v, - comments: v.comments.map((c) => - c.id === parentId - ? { ...c, replies: [...c.replies, newReply] } - : c - ), - } + ...v, + comments: v.comments.map((c) => + c.id === parentId + ? { ...c, replies: [...c.replies, newReply] } + : c + ), + } : v ), }; @@ -686,17 +703,17 @@ export default function WatchPage() { versions: prev.versions.map((v) => v.id === activeVersionId ? { - ...v, - comments: v.comments.map((c) => { - if (c.id === commentId) return { ...c, content: editText.trim() }; - return { - ...c, - replies: c.replies.map((r) => - r.id === commentId ? { ...r, content: editText.trim() } : r - ), - }; - }), - } + ...v, + comments: v.comments.map((c) => { + if (c.id === commentId) return { ...c, content: editText.trim() }; + return { + ...c, + replies: c.replies.map((r) => + r.id === commentId ? { ...r, content: editText.trim() } : r + ), + }; + }), + } : v ), }; @@ -724,14 +741,14 @@ export default function WatchPage() { versions: prev.versions.map((v) => v.id === activeVersionId ? { - ...v, - comments: v.comments - .filter((c) => c.id !== commentId) - .map((c) => ({ - ...c, - replies: c.replies.filter((r) => r.id !== commentId), - })), - } + ...v, + comments: v.comments + .filter((c) => c.id !== commentId) + .map((c) => ({ + ...c, + replies: c.replies.filter((r) => r.id !== commentId), + })), + } : v ), }; @@ -790,6 +807,56 @@ export default function WatchPage() { ); } + // Guest name gate — prompt guests to enter their name before viewing + if (isGuest && !guestNameConfirmed) { + return ( +
+
+
+
+ +
+

Welcome to OpenFrame

+

+ Enter your name to view and comment on this video +

+
+
+ setGuestName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && guestName.trim()) { + localStorage.setItem('openframe_guest_name', guestName.trim()); + setGuestNameConfirmed(true); + } + }} + autoFocus + /> + +
+

+ Or{' '} + + sign in + {' '} + for a full account +

+
+
+ ); + } + const embedUrl = getEmbedUrl(activeVersion); return ( diff --git a/bun.lock b/bun.lock index 63a8609..79c4290 100644 --- a/bun.lock +++ b/bun.lock @@ -19,6 +19,7 @@ "next": "16.1.6", "next-auth": "^5.0.0-beta.30", "next-themes": "^0.4.6", + "nodemailer": "^8.0.1", "pg": "^8.18.0", "prisma": "^7.3.0", "radix-ui": "^1.4.3", @@ -33,6 +34,7 @@ "@tailwindcss/postcss": "^4", "@types/bcryptjs": "^3.0.0", "@types/node": "^20", + "@types/nodemailer": "^7.0.9", "@types/pg": "^8.16.0", "@types/react": "^19", "@types/react-dom": "^19", @@ -686,6 +688,8 @@ "@types/node": ["@types/node@20.19.32", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-Ez8QE4DMfhjjTsES9K2dwfV258qBui7qxUsoaixZDiTzbde4U12e1pXGNu/ECsUIOi5/zoCxAQxIhQnaUQ2VvA=="], + "@types/nodemailer": ["@types/nodemailer@7.0.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-vI8oF1M+8JvQhsId0Pc38BdUP2evenIIys7c7p+9OZXSPOH5c1dyINP1jT8xQ2xPuBUXmIC87s+91IZMDjH8Ow=="], + "@types/pg": ["@types/pg@8.16.0", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-RmhMd/wD+CF8Dfo+cVIy3RR5cl8CyfXQ0tGgW6XBL8L4LM/UTEbNXYRbLwU6w+CgrKBNbrQWt4FUtTfaU5jSYQ=="], "@types/react": ["@types/react@19.2.13", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-KkiJeU6VbYbUOp5ITMIc7kBfqlYkKA5KhEHVrGMmUUMt7NeaZg65ojdPk+FtNrBAOXNVM5QM72jnADjM+XVRAQ=="], @@ -1412,6 +1416,8 @@ "node-releases": ["node-releases@2.0.27", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="], + "nodemailer": ["nodemailer@8.0.1", "", {}, "sha512-5kcldIXmaEjZcHR6F28IKGSgpmZHaF1IXLWFTG+Xh3S+Cce4MiakLtWY+PlBU69fLbRa8HlaGIrC/QolUpHkhg=="], + "npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="], "nypm": ["nypm@0.6.5", "", { "dependencies": { "citty": "^0.2.0", "pathe": "^2.0.3", "tinyexec": "^1.0.2" }, "bin": { "nypm": "dist/cli.mjs" } }, "sha512-K6AJy1GMVyfyMXRVB88700BJqNUkByijGJM8kEHpLdcAt+vSQAVfkWWHYzuRXHSY6xA2sNc5RjTj0p9rE2izVQ=="], diff --git a/components/guest-gate.tsx b/components/guest-gate.tsx new file mode 100644 index 0000000..1112bcc --- /dev/null +++ b/components/guest-gate.tsx @@ -0,0 +1,72 @@ +'use client'; + +import { useState, useEffect, type ReactNode } from 'react'; +import Link from 'next/link'; +import { User } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; + +/** + * Client component that gates content behind a guest name prompt. + * If the user already has a name in localStorage, it skips the gate. + * Only renders children after the guest confirms their name. + */ +export function GuestGate({ children }: { children: ReactNode }) { + const [guestName, setGuestName] = useState(''); + const [confirmed, setConfirmed] = useState(false); + + useEffect(() => { + const saved = localStorage.getItem('openframe_guest_name'); + if (saved) { + setGuestName(saved); + setConfirmed(true); + } + }, []); + + if (confirmed) { + return <>{children}; + } + + const confirm = () => { + if (!guestName.trim()) return; + localStorage.setItem('openframe_guest_name', guestName.trim()); + setConfirmed(true); + }; + + return ( +
+
+
+
+ +
+

Welcome to OpenFrame

+

+ Enter your name to view and comment on this project +

+
+
+ setGuestName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') confirm(); + }} + autoFocus + /> + +
+

+ Or{' '} + + sign in + {' '} + with your account +

+
+
+ ); +} diff --git a/lib/notifications.ts b/lib/notifications.ts new file mode 100644 index 0000000..3f87a0d --- /dev/null +++ b/lib/notifications.ts @@ -0,0 +1,415 @@ +import { db } from '@/lib/db'; +import nodemailer from 'nodemailer'; + +// ============================================ +// NOTIFICATION CHANNELS +// ============================================ + +/** + * Send a message via Telegram Bot API with optional inline keyboard button. + */ +async function sendTelegram( + botToken: string, + chatId: string, + text: string, + buttonLabel?: string, + buttonUrl?: string, +): Promise { + try { + const payload: Record = { + chat_id: chatId, + text, + link_preview_options: { is_disabled: true }, + }; + + // Add inline keyboard button for clickable URL (Telegram requires HTTPS) + if (buttonLabel && buttonUrl && buttonUrl.startsWith('https://')) { + payload.reply_markup = { + inline_keyboard: [[{ text: buttonLabel, url: buttonUrl }]], + }; + } + + const res = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const body = await res.text(); + console.error('Telegram API error:', res.status, body); + return false; + } + return true; + } catch (err) { + console.error('Telegram send failed:', err); + return false; + } +} + +/** + * Create a nodemailer SMTP transporter from environment variables. + * Required env vars: SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD + */ +function createSmtpTransport() { + const host = process.env.SMTP_HOST; + const port = Number(process.env.SMTP_PORT || '587'); + const user = process.env.SMTP_USER; + const pass = process.env.SMTP_PASSWORD; + + if (!host || !user || !pass) return null; + + return nodemailer.createTransport({ + host, + port, + secure: port === 465, + auth: { user, pass }, + }); +} + +/** + * Send an email notification via SMTP. + * Requires SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD environment variables. + * Falls back to logging if not configured. + */ +async function sendEmail(to: string, subject: string, html: string): Promise { + const transporter = createSmtpTransport(); + const fromAddress = process.env.SMTP_FROM || process.env.EMAIL_FROM || 'OpenFrame '; + + if (!transporter) { + console.warn('SMTP not configured — skipping email notification'); + return false; + } + + try { + await transporter.sendMail({ from: fromAddress, to, subject, html }); + return true; + } catch (err) { + console.error('Email send failed:', err); + return false; + } +} + +// ============================================ +// NOTIFICATION EVENT TYPES +// ============================================ + +export type NotificationEvent = + | { type: 'new_video'; projectName: string; videoTitle: string; addedBy: string; url: string } + | { type: 'new_comment'; projectName: string; videoTitle: string; commentAuthor: string; commentText: string; timestamp: string; url: string } + | { type: 'new_reply'; projectName: string; videoTitle: string; replyAuthor: string; replyText: string; parentAuthor: string; timestamp: string; url: string }; + +/** Structured Telegram message with text body + button label/URL */ +interface TelegramMessage { + text: string; + buttonLabel: string; + buttonUrl: string; +} + +/** + * Format a notification event into a Telegram message with an inline keyboard button. + * The URL is no longer in the text body — it's attached as a clickable button instead. + */ +function formatTelegramMessage(event: NotificationEvent, timezone: string): TelegramMessage { + const now = formatNow(timezone); + switch (event.type) { + case 'new_video': + return { + text: + `🎬 New Video Added\n\n` + + `▸ Project: ${event.projectName}\n` + + `▸ Video: ${event.videoTitle}\n` + + `▸ Added by: ${event.addedBy}\n` + + `▸ ${now}`, + buttonLabel: 'View Video', + buttonUrl: event.url, + }; + case 'new_comment': + return { + text: + `💬 New Comment\n\n` + + `▸ Project: ${event.projectName}\n` + + `▸ Video: ${event.videoTitle}\n` + + `▸ By: ${event.commentAuthor} at ${event.timestamp}\n` + + `▸ ${now}\n\n` + + `"${truncate(event.commentText, 200)}"`, + buttonLabel: 'View Comment', + buttonUrl: event.url, + }; + case 'new_reply': + return { + text: + `↩️ New Reply\n\n` + + `▸ Project: ${event.projectName}\n` + + `▸ Video: ${event.videoTitle}\n` + + `▸ ${event.replyAuthor} replied to ${event.parentAuthor}\n` + + `▸ ${now}\n\n` + + `"${truncate(event.replyText, 200)}"`, + buttonLabel: 'View Reply', + buttonUrl: event.url, + }; + } +} + +// ============================================ +// EMAIL TEMPLATE +// ============================================ + +const BASE_URL = () => process.env.NEXTAUTH_URL || ''; + +// Theme colors (hex equivalents of oklch dark theme) +const COLORS = { + bg: '#111114', // page background (very dark) + card: '#1a1a20', // card background + cardInner: '#212128', // inner card / section bg + border: '#2a2a32', // subtle border + accent: '#2ec8d8', // primary/accent teal-cyan + accentDark: '#1a3a40',// accent background for headings + text: '#ebebeb', // primary text + textSecondary: '#9a9a9f', // muted text + textDim: '#6a6a72', // dimmer labels +} as const; + +/** + * Wrap email body content in a branded template matching OpenFrame's dark theme. + * Square corners (radius:0), card-based layout, teal accent, unsubscribe footer. + */ +function emailTemplate(body: string): string { + const settingsUrl = `${BASE_URL()}/settings`; + return ` + + + + + +
+ + + + + + + + + + + +
+ + + +
OpenFrame
+
+ ${body} +
+

You received this because email notifications are enabled.

+ Unsubscribe · Manage notification settings +
+
+ +`; +} + +/** Generates an info row for email detail tables */ +function emailRow(label: string, value: string, isHighlight = false): string { + const valStyle = isHighlight + ? `color:${COLORS.text};font-weight:600;` + : `color:${COLORS.textSecondary};`; + return ` + ${label} + ${value} + `; +} + +/** Generates the accent-colored event type heading bar */ +function emailHeading(icon: string, title: string): string { + return ` + ${icon}  ${title} + `; +} + +/** Generates a CTA button */ +function emailButton(text: string, url: string): string { + return `${text}`; +} + +/** + * Format a notification event into an email subject + full branded HTML email. + */ +function formatEmail(event: NotificationEvent, timezone: string): { subject: string; html: string } { + const now = formatNow(timezone); + switch (event.type) { + case 'new_video': + return { + subject: `[OpenFrame] New video in ${event.projectName}: ${event.videoTitle}`, + html: emailTemplate(` + ${emailHeading('▶', 'New Video Added')} + + + ${emailRow('Project', escapeHtml(event.projectName), true)} + ${emailRow('Video', escapeHtml(event.videoTitle), true)} + ${emailRow('Added by', escapeHtml(event.addedBy))} + ${emailRow('When', now)} +
+ ${emailButton('View Video →', event.url)} + + `), + }; + case 'new_comment': + return { + subject: `[OpenFrame] New comment on ${event.videoTitle}`, + html: emailTemplate(` + ${emailHeading('●', 'New Comment')} + + + ${emailRow('Project', escapeHtml(event.projectName), true)} + ${emailRow('Video', escapeHtml(event.videoTitle), true)} + ${emailRow('From', escapeHtml(event.commentAuthor))} + ${emailRow('At', event.timestamp)} + ${emailRow('When', now)} +
+
+ ${escapeHtml(truncate(event.commentText, 300))} +
+ ${emailButton('View Comment →', event.url)} + + `), + }; + case 'new_reply': + return { + subject: `[OpenFrame] ${event.replyAuthor} replied on ${event.videoTitle}`, + html: emailTemplate(` + ${emailHeading('↩', 'New Reply')} + + + ${emailRow('Project', escapeHtml(event.projectName), true)} + ${emailRow('Video', escapeHtml(event.videoTitle), true)} + ${emailRow('From', `${escapeHtml(event.replyAuthor)} ${escapeHtml(event.parentAuthor)}`)} + ${emailRow('When', now)} +
+
+ ${escapeHtml(truncate(event.replyText, 300))} +
+ ${emailButton('View Reply →', event.url)} + + `), + }; + } +} + +/** + * Generate branded HTML for test emails sent from settings page. + */ +export function testEmailHtml(): string { + return emailTemplate(` + ${emailHeading('✓', 'Test Notification')} + +

Email notifications are working.

+

You’ll receive emails when there’s activity on your projects.

+ + `); +} + +// ============================================ +// MAIN DISPATCH +// ============================================ + +/** + * Notify the project owner about an event. + * Looks up the owner's notification settings and dispatches to enabled channels. + * Best-effort — never throws, logs errors. + */ +export async function notifyProjectOwner(ownerId: string, event: NotificationEvent): Promise { + try { + const settings = await db.notificationSetting.findUnique({ + where: { userId: ownerId }, + include: { user: { select: { email: true } } }, + }); + + if (!settings) return; // No notification preferences configured + + const shouldNotify = + (event.type === 'new_video' && settings.onNewVideo) || + (event.type === 'new_comment' && settings.onNewComment) || + (event.type === 'new_reply' && settings.onNewReply); + + if (!shouldNotify) return; + + const promises: Promise[] = []; + const tz = settings.timezone || 'UTC'; + // Telegram + if (settings.telegramEnabled && settings.telegramBotToken && settings.telegramChatId) { + const msg = formatTelegramMessage(event, tz); + promises.push(sendTelegram( + settings.telegramBotToken, + settings.telegramChatId, + msg.text, + msg.buttonLabel, + msg.buttonUrl, + )); + } + + // Email + if (settings.emailEnabled && settings.user.email) { + const { subject, html } = formatEmail(event, tz); + promises.push(sendEmail(settings.user.email, subject, html)); + } + + await Promise.allSettled(promises); + } catch (err) { + console.error('Notification dispatch failed:', err); + } +} + +// ============================================ +// HELPERS +// ============================================ + +/** + * Format current date/time in the user's timezone. + * Returns e.g. "Jan 15, 2025 at 3:45 PM" + */ +function formatNow(timezone: string): string { + try { + return new Date().toLocaleString('en-US', { + timeZone: timezone, + month: 'short', + day: 'numeric', + year: 'numeric', + hour: 'numeric', + minute: '2-digit', + hour12: true, + }); + } catch { + // Invalid timezone — fall back to UTC + return new Date().toLocaleString('en-US', { + timeZone: 'UTC', + month: 'short', + day: 'numeric', + year: 'numeric', + hour: 'numeric', + minute: '2-digit', + hour12: true, + }); + } +} + +function escapeHtml(str: string): string { + return str + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +} + +/** Escape a URL for use inside an HTML href="..." attribute */ +function escapeAttr(str: string): string { + return str + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(//g, '>'); +} + +function truncate(str: string, maxLen: number): string { + return str.length > maxLen ? str.slice(0, maxLen) + '...' : str; +} diff --git a/package.json b/package.json index 5cf38b0..1ab362c 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,13 @@ "dev": "next dev", "build": "next build", "start": "next start", - "lint": "eslint" + "lint": "eslint", + "db:generate": "prisma generate", + "db:push": "prisma db push", + "db:migrate": "prisma migrate deploy", + "db:seed": "prisma db seed", + "db:setup": "bun run db:generate && bun run db:push && bun run db:extras", + "db:extras": "bun run scripts/db-extras.ts" }, "dependencies": { "@auth/prisma-adapter": "^2.11.1", @@ -23,6 +29,7 @@ "next": "16.1.6", "next-auth": "^5.0.0-beta.30", "next-themes": "^0.4.6", + "nodemailer": "^8.0.1", "pg": "^8.18.0", "prisma": "^7.3.0", "radix-ui": "^1.4.3", @@ -37,6 +44,7 @@ "@tailwindcss/postcss": "^4", "@types/bcryptjs": "^3.0.0", "@types/node": "^20", + "@types/nodemailer": "^7.0.9", "@types/pg": "^8.16.0", "@types/react": "^19", "@types/react-dom": "^19", diff --git a/prisma/schema.prisma b/prisma/schema.prisma index a505b8a..367447e 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -30,6 +30,7 @@ model User { projects Project[] comments Comment[] projectMemberships ProjectMember[] + notificationSetting NotificationSetting? @@map("users") } @@ -321,3 +322,51 @@ enum SharePermission { VIEW // Can only view COMMENT // Can view and comment } + +// ============================================ +// NOTIFICATION SETTINGS +// ============================================ + +model NotificationSetting { + id String @id @default(cuid()) + + userId String @unique + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + // Telegram webhook + telegramBotToken String? // Bot token from @BotFather + telegramChatId String? // Chat/group ID to send messages to + telegramEnabled Boolean @default(false) + + // Email notifications (uses account email by default) + emailEnabled Boolean @default(false) + + // Event subscriptions + onNewVideo Boolean @default(true) + onNewComment Boolean @default(true) + onNewReply Boolean @default(true) + + // User timezone for notification timestamps (IANA timezone identifier) + timezone String @default("UTC") + + // Timestamps + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@map("notification_settings") +} + +// Rate limiting table (created as UNLOGGED via raw SQL migration) +// Defined here so `prisma db push` doesn't drop it +model RateLimit { + id Int @id @default(autoincrement()) + key String @db.VarChar(255) + action String @db.VarChar(50) + count Int @default(1) + windowStart DateTime @default(now()) @map("window_start") + + @@unique([key, action]) + @@index([key, action]) + @@index([windowStart]) + @@map("rate_limits") +} diff --git a/scripts/db-extras.ts b/scripts/db-extras.ts new file mode 100644 index 0000000..9716c1f --- /dev/null +++ b/scripts/db-extras.ts @@ -0,0 +1,56 @@ +/** + * db-extras.ts — Run all custom SQL migrations that Prisma doesn't manage. + * + * This script runs after `prisma db push` / `prisma migrate deploy` to set up + * tables and functions that need raw SQL (UNLOGGED tables, custom functions, etc.). + * + * Usage: bun run db:extras + * + * To add new custom migrations: + * 1. Create a .sql file in prisma/migrations/ + * 2. Add the filename to the EXTRAS array below + */ + +import { readFileSync } from 'fs'; +import { join } from 'path'; +import pg from 'pg'; + +const EXTRAS = [ + 'rate_limit.sql', + // Add future custom SQL files here +]; + +async function main() { + const url = process.env.DATABASE_URL; + if (!url) { + console.error('❌ DATABASE_URL is not set'); + process.exit(1); + } + + // Strip Prisma-specific query params (e.g. ?schema=public) that pg doesn't understand + const cleanUrl = url.split('?')[0]; + const client = new pg.Client({ connectionString: cleanUrl }); + + try { + await client.connect(); + console.log('✅ Connected to database\n'); + + for (const file of EXTRAS) { + const filePath = join(import.meta.dirname, '..', 'prisma', 'migrations', file); + const sql = readFileSync(filePath, 'utf-8'); + + console.log(`▸ Running ${file}...`); + await client.query(sql); + console.log(` ✓ ${file} applied\n`); + } + + console.log('✅ All database extras applied successfully'); + } catch (err) { + console.error('❌ Database extras failed:', err); + process.exit(1); + } finally { + await client.end(); + } +} + +main();