feat: Introduce guest access for video viewing, implement user notification settings via email and Telegram, and add rate limiting infrastructure.

This commit is contained in:
Yusuf İpek
2026-02-07 13:56:26 +03:00
parent 296c5257a7
commit 88dcf9514c
17 changed files with 1566 additions and 39 deletions
@@ -101,7 +101,11 @@ export default function ProjectMembersPage() {
return; 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(''); setInviteEmail('');
fetchMembers(); fetchMembers();
} catch { } catch {
@@ -16,6 +16,7 @@ import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card'; import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { VideoCard } from '@/components/video-card'; import { VideoCard } from '@/components/video-card';
import { GuestGate } from '@/components/guest-gate';
import { auth } from '@/lib/auth'; import { auth } from '@/lib/auth';
import { db } from '@/lib/db'; 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 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 (
<GuestGate>
<ProjectContent
project={project}
projectId={projectId}
videos={videos}
canEdit={false}
isOwner={false}
isPublic={isPublic}
workspaceRole={null}
/>
</GuestGate>
);
}
return (
<ProjectContent
project={project}
projectId={projectId}
videos={videos}
canEdit={canEdit}
isOwner={isOwner}
isPublic={isPublic}
workspaceRole={workspaceRole}
/>
);
}
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 ( return (
<div className="px-6 lg:px-8 py-8 w-full"> <div className="px-6 lg:px-8 py-8 w-full">
{/* Back link */} {/* Back link */}
@@ -101,6 +101,7 @@ interface VideoData {
members: { role: string }[]; members: { role: string }[];
}; };
versions: (Version & { comments: Comment[] })[]; versions: (Version & { comments: Comment[] })[];
isAuthenticated: boolean;
} }
function formatTime(seconds: number): string { function formatTime(seconds: number): string {
@@ -167,6 +168,14 @@ export default function VideoPage() {
const [isSubmittingEdit, setIsSubmittingEdit] = useState(false); const [isSubmittingEdit, setIsSubmittingEdit] = useState(false);
const [deletingCommentId, setDeletingCommentId] = useState<string | null>(null); const [deletingCommentId, setDeletingCommentId] = useState<string | null>(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 // New version dialog
const [showVersionDialog, setShowVersionDialog] = useState(false); const [showVersionDialog, setShowVersionDialog] = useState(false);
const [newVersionUrl, setNewVersionUrl] = useState(''); const [newVersionUrl, setNewVersionUrl] = useState('');
@@ -371,6 +380,7 @@ export default function VideoPage() {
content: voiceData ? commentText.trim() || null : commentText, content: voiceData ? commentText.trim() || null : commentText,
timestamp: selectedTimestamp ?? currentTime, timestamp: selectedTimestamp ?? currentTime,
...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }), ...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }),
...(isGuest && guestName && { guestName }),
}), }),
}); });
@@ -395,7 +405,7 @@ export default function VideoPage() {
} finally { } finally {
setIsSubmittingComment(false); setIsSubmittingComment(false);
} }
}, [commentText, currentTime, selectedTimestamp, activeVersion, activeVersionId]); }, [commentText, currentTime, selectedTimestamp, activeVersion, activeVersionId, isGuest, guestName]);
// Voice recording handlers // Voice recording handlers
const startRecording = useCallback(async () => { const startRecording = useCallback(async () => {
@@ -631,6 +641,7 @@ export default function VideoPage() {
timestamp: comments.find((c) => c.id === parentId)?.timestamp ?? currentTime, timestamp: comments.find((c) => c.id === parentId)?.timestamp ?? currentTime,
parentId, parentId,
...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }), ...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }),
...(isGuest && guestName && { guestName }),
}), }),
}); });
if (res.ok) { if (res.ok) {
+498
View File
@@ -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 (
<button
type="button"
onClick={onToggle}
className={cn(
'flex items-center justify-between w-full p-3 rounded-lg border transition-colors text-left',
enabled
? 'border-primary/50 bg-primary/5'
: 'border-border hover:bg-accent/50'
)}
>
<div>
<span className="text-sm font-medium">{label}</span>
{description && (
<p className="text-xs text-muted-foreground mt-0.5">{description}</p>
)}
</div>
<div
className={cn(
'w-10 h-6 rounded-full relative transition-colors',
enabled ? 'bg-primary' : 'bg-muted'
)}
>
<div
className={cn(
'absolute top-1 w-4 h-4 rounded-full bg-white transition-transform',
enabled ? 'translate-x-5' : 'translate-x-1'
)}
/>
</div>
</button>
);
}
export default function SettingsPage() {
const [settings, setSettings] = useState<NotificationSettings>({
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<string | null>(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 (
<div className="flex items-center justify-center py-24">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="max-w-2xl mx-auto py-8 px-4">
<div className="mb-8">
<h1 className="text-2xl font-bold tracking-tight">Settings</h1>
<p className="text-muted-foreground mt-1">
Manage your notification preferences
</p>
</div>
{/* Status message */}
{message && (
<div
className={cn(
'flex items-center gap-2 p-3 rounded-lg mb-6 text-sm',
message.type === 'success'
? 'bg-green-500/10 text-green-700 dark:text-green-400'
: 'bg-destructive/10 text-destructive'
)}
>
{message.type === 'success' ? (
<CheckCircle2 className="h-4 w-4 shrink-0" />
) : (
<AlertCircle className="h-4 w-4 shrink-0" />
)}
{message.text}
</div>
)}
{/* Event Subscriptions */}
<Card className="mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Bell className="h-5 w-5" />
Notification Events
</CardTitle>
<CardDescription>
Choose which events trigger notifications
</CardDescription>
</CardHeader>
<CardContent className="space-y-2">
<ToggleButton
enabled={settings.onNewVideo}
onToggle={() =>
setSettings((s) => ({ ...s, onNewVideo: !s.onNewVideo }))
}
label="New Video Added"
description="When a new video is added to one of your projects"
/>
<ToggleButton
enabled={settings.onNewComment}
onToggle={() =>
setSettings((s) => ({ ...s, onNewComment: !s.onNewComment }))
}
label="New Comment"
description="When someone leaves a comment on your videos"
/>
<ToggleButton
enabled={settings.onNewReply}
onToggle={() =>
setSettings((s) => ({ ...s, onNewReply: !s.onNewReply }))
}
label="New Reply"
description="When someone replies to a comment thread"
/>
</CardContent>
</Card>
{/* Telegram */}
<Card className="mb-6">
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2">
<Send className="h-5 w-5" />
Telegram
</CardTitle>
<Badge variant={settings.telegramEnabled ? 'default' : 'secondary'}>
{settings.telegramEnabled ? 'Enabled' : 'Disabled'}
</Badge>
</div>
<CardDescription>
Get instant notifications via a Telegram bot
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="rounded-lg border bg-muted/50 p-3 text-sm text-muted-foreground space-y-1">
<p className="font-medium text-foreground">Setup instructions:</p>
<ol className="list-decimal list-inside space-y-1 text-xs">
<li>
Open Telegram and message{' '}
<a
href="https://t.me/BotFather"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline inline-flex items-center gap-0.5"
>
@BotFather <ExternalLink className="h-3 w-3" />
</a>
</li>
<li>Send <code className="px-1 py-0.5 bg-background rounded text-xs">/newbot</code> and follow the prompts to create a bot</li>
<li>Copy the <strong>Bot Token</strong> and paste it below</li>
<li>
Send a message to your new bot, then visit{' '}
<a
href="https://api.telegram.org"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline inline-flex items-center gap-0.5"
>
api.telegram.org <ExternalLink className="h-3 w-3" />
</a>{' '}
<code className="px-1 py-0.5 bg-background rounded text-xs">/bot&lt;token&gt;/getUpdates</code> to find your <strong>Chat ID</strong>
</li>
</ol>
</div>
<div className="space-y-3">
<div>
<Label htmlFor="telegram-token">Bot Token</Label>
<Input
id="telegram-token"
type="password"
placeholder="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
value={telegramToken}
onChange={(e) => setTelegramToken(e.target.value)}
className="mt-1 font-mono text-sm"
/>
</div>
<div>
<Label htmlFor="telegram-chat-id">Chat ID</Label>
<Input
id="telegram-chat-id"
placeholder="-1001234567890"
value={telegramChatId}
onChange={(e) => setTelegramChatId(e.target.value)}
className="mt-1 font-mono text-sm"
/>
</div>
</div>
<div className="flex items-center gap-2">
<ToggleButton
enabled={settings.telegramEnabled}
onToggle={() =>
setSettings((s) => ({ ...s, telegramEnabled: !s.telegramEnabled }))
}
label="Enable Telegram notifications"
/>
</div>
<Button
variant="outline"
size="sm"
onClick={() => handleTest('telegram')}
disabled={!telegramToken || !telegramChatId || testing === 'telegram'}
>
{testing === 'telegram' ? (
<Loader2 className="h-4 w-4 animate-spin mr-2" />
) : (
<Send className="h-4 w-4 mr-2" />
)}
Send Test Message
</Button>
</CardContent>
</Card>
{/* Email */}
<Card className="mb-6">
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2">
<Mail className="h-5 w-5" />
Email
</CardTitle>
<Badge variant={settings.emailEnabled ? 'default' : 'secondary'}>
{settings.emailEnabled ? 'Enabled' : 'Disabled'}
</Badge>
</div>
<CardDescription>
Receive notification emails to your account email address
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<ToggleButton
enabled={settings.emailEnabled}
onToggle={() =>
setSettings((s) => ({ ...s, emailEnabled: !s.emailEnabled }))
}
label="Enable email notifications"
/>
<Button
variant="outline"
size="sm"
onClick={() => handleTest('email')}
disabled={!settings.emailEnabled || testing === 'email'}
>
{testing === 'email' ? (
<Loader2 className="h-4 w-4 animate-spin mr-2" />
) : (
<Mail className="h-4 w-4 mr-2" />
)}
Send Test Email
</Button>
</CardContent>
</Card>
{/* Timezone */}
<Card className="mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Globe className="h-5 w-5" />
Timezone
</CardTitle>
<CardDescription>
Timestamps in notifications will use this timezone
</CardDescription>
</CardHeader>
<CardContent>
<Select
value={settings.timezone}
onValueChange={(value) =>
setSettings((s) => ({ ...s, timezone: value }))
}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select timezone" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel>Americas</SelectLabel>
<SelectItem value="America/New_York">Eastern Time (New York)</SelectItem>
<SelectItem value="America/Chicago">Central Time (Chicago)</SelectItem>
<SelectItem value="America/Denver">Mountain Time (Denver)</SelectItem>
<SelectItem value="America/Los_Angeles">Pacific Time (Los Angeles)</SelectItem>
<SelectItem value="America/Anchorage">Alaska (Anchorage)</SelectItem>
<SelectItem value="Pacific/Honolulu">Hawaii (Honolulu)</SelectItem>
<SelectItem value="America/Toronto">Toronto</SelectItem>
<SelectItem value="America/Vancouver">Vancouver</SelectItem>
<SelectItem value="America/Mexico_City">Mexico City</SelectItem>
<SelectItem value="America/Sao_Paulo">São Paulo</SelectItem>
<SelectItem value="America/Argentina/Buenos_Aires">Buenos Aires</SelectItem>
<SelectItem value="America/Bogota">Bogotá</SelectItem>
</SelectGroup>
<SelectGroup>
<SelectLabel>Europe</SelectLabel>
<SelectItem value="Europe/London">London (GMT/BST)</SelectItem>
<SelectItem value="Europe/Paris">Paris (CET)</SelectItem>
<SelectItem value="Europe/Berlin">Berlin (CET)</SelectItem>
<SelectItem value="Europe/Amsterdam">Amsterdam (CET)</SelectItem>
<SelectItem value="Europe/Madrid">Madrid (CET)</SelectItem>
<SelectItem value="Europe/Rome">Rome (CET)</SelectItem>
<SelectItem value="Europe/Zurich">Zurich (CET)</SelectItem>
<SelectItem value="Europe/Stockholm">Stockholm (CET)</SelectItem>
<SelectItem value="Europe/Helsinki">Helsinki (EET)</SelectItem>
<SelectItem value="Europe/Athens">Athens (EET)</SelectItem>
<SelectItem value="Europe/Istanbul">Istanbul (TRT)</SelectItem>
<SelectItem value="Europe/Moscow">Moscow (MSK)</SelectItem>
<SelectItem value="Europe/Kiev">Kyiv (EET)</SelectItem>
<SelectItem value="Europe/Warsaw">Warsaw (CET)</SelectItem>
</SelectGroup>
<SelectGroup>
<SelectLabel>Asia & Pacific</SelectLabel>
<SelectItem value="Asia/Dubai">Dubai (GST)</SelectItem>
<SelectItem value="Asia/Kolkata">India (IST)</SelectItem>
<SelectItem value="Asia/Bangkok">Bangkok (ICT)</SelectItem>
<SelectItem value="Asia/Singapore">Singapore (SGT)</SelectItem>
<SelectItem value="Asia/Hong_Kong">Hong Kong (HKT)</SelectItem>
<SelectItem value="Asia/Shanghai">Shanghai (CST)</SelectItem>
<SelectItem value="Asia/Tokyo">Tokyo (JST)</SelectItem>
<SelectItem value="Asia/Seoul">Seoul (KST)</SelectItem>
<SelectItem value="Asia/Taipei">Taipei (CST)</SelectItem>
<SelectItem value="Asia/Jakarta">Jakarta (WIB)</SelectItem>
<SelectItem value="Australia/Sydney">Sydney (AEST)</SelectItem>
<SelectItem value="Australia/Melbourne">Melbourne (AEST)</SelectItem>
<SelectItem value="Australia/Perth">Perth (AWST)</SelectItem>
<SelectItem value="Pacific/Auckland">Auckland (NZST)</SelectItem>
</SelectGroup>
<SelectGroup>
<SelectLabel>Africa & Middle East</SelectLabel>
<SelectItem value="Africa/Cairo">Cairo (EET)</SelectItem>
<SelectItem value="Africa/Lagos">Lagos (WAT)</SelectItem>
<SelectItem value="Africa/Johannesburg">Johannesburg (SAST)</SelectItem>
<SelectItem value="Africa/Nairobi">Nairobi (EAT)</SelectItem>
<SelectItem value="Asia/Riyadh">Riyadh (AST)</SelectItem>
<SelectItem value="Asia/Tehran">Tehran (IRST)</SelectItem>
</SelectGroup>
<SelectGroup>
<SelectLabel>Other</SelectLabel>
<SelectItem value="UTC">UTC</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</CardContent>
</Card>
<Separator className="my-6" />
{/* Save button */}
<div className="flex justify-end">
<Button onClick={handleSave} disabled={saving}>
{saving ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Saving...
</>
) : (
'Save Settings'
)}
</Button>
</div>
</div>
);
}
@@ -101,7 +101,11 @@ export default function WorkspaceMembersPage() {
return; 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(''); setInviteEmail('');
fetchMembers(); fetchMembers();
} catch { } catch {
@@ -54,7 +54,10 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
return NextResponse.json({ error: 'Access denied' }, { status: 403 }); return NextResponse.json({ error: 'Access denied' }, { status: 403 });
} }
return NextResponse.json(video); return NextResponse.json({
...video,
isAuthenticated: !!session?.user?.id,
});
} catch (error) { } catch (error) {
console.error('Error fetching video:', error); console.error('Error fetching video:', error);
return NextResponse.json( return NextResponse.json(
@@ -4,6 +4,7 @@ import { auth } from '@/lib/auth';
import { ProjectMemberRole } from '@prisma/client'; import { ProjectMemberRole } from '@prisma/client';
import { validateUrl, validateOptionalUrl } from '@/lib/validation'; import { validateUrl, validateOptionalUrl } from '@/lib/validation';
import { rateLimit } from '@/lib/rate-limit'; import { rateLimit } from '@/lib/rate-limit';
import { notifyProjectOwner } from '@/lib/notifications';
type RouteParams = { params: Promise<{ projectId: string }> }; 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 }); return NextResponse.json(video, { status: 201 });
} catch (error) { } catch (error) {
console.error('Error creating video:', error); console.error('Error creating video:', error);
+220
View File
@@ -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<string, unknown> = {
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 <[email protected]>';
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 }
);
}
}
@@ -3,6 +3,7 @@ import { db } from '@/lib/db';
import { auth } from '@/lib/auth'; import { auth } from '@/lib/auth';
import { validateOptionalUrl } from '@/lib/validation'; import { validateOptionalUrl } from '@/lib/validation';
import { rateLimit } from '@/lib/rate-limit'; import { rateLimit } from '@/lib/rate-limit';
import { notifyProjectOwner } from '@/lib/notifications';
type RouteParams = { params: Promise<{ versionId: string }> }; 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 }); return NextResponse.json(comment, { status: 201 });
} catch (error) { } catch (error) {
console.error('Error creating comment:', error); console.error('Error creating comment:', error);
+13 -1
View File
@@ -53,7 +53,19 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
return NextResponse.json({ error: 'Access denied' }, { status: 403 }); 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) { } catch (error) {
console.error('Error fetching video:', error); console.error('Error fetching video:', error);
return NextResponse.json( return NextResponse.json(
+100 -33
View File
@@ -25,6 +25,7 @@ import {
Trash2, Trash2,
X, X,
ArrowUpRight, ArrowUpRight,
User,
} from 'lucide-react'; } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
@@ -83,9 +84,11 @@ interface VideoData {
project: { project: {
name: string; name: string;
ownerId: string; ownerId: string;
members: { role: string }[]; visibility: string;
}; };
versions: (Version & { comments: Comment[] })[]; versions: (Version & { comments: Comment[] })[];
isAuthenticated: boolean;
canComment: boolean;
} }
function formatTime(seconds: number): string { function formatTime(seconds: number): string {
@@ -148,6 +151,18 @@ export default function WatchPage() {
const [isSubmittingEdit, setIsSubmittingEdit] = useState(false); const [isSubmittingEdit, setIsSubmittingEdit] = useState(false);
const [deletingCommentId, setDeletingCommentId] = useState<string | null>(null); const [deletingCommentId, setDeletingCommentId] = useState<string | null>(null);
const [guestName, setGuestName] = useState(''); 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 // Fetch video data
useEffect(() => { useEffect(() => {
@@ -310,6 +325,7 @@ export default function WatchPage() {
content: voiceData ? commentText.trim() || null : commentText, content: voiceData ? commentText.trim() || null : commentText,
timestamp: selectedTimestamp ?? currentTime, timestamp: selectedTimestamp ?? currentTime,
...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }), ...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }),
...(isGuest && guestName && { guestName }),
}), }),
}); });
@@ -334,7 +350,7 @@ export default function WatchPage() {
} finally { } finally {
setIsSubmittingComment(false); setIsSubmittingComment(false);
} }
}, [commentText, currentTime, selectedTimestamp, activeVersion, activeVersionId]); }, [commentText, currentTime, selectedTimestamp, activeVersion, activeVersionId, isGuest, guestName]);
// Voice recording handlers // Voice recording handlers
const startRecording = useCallback(async () => { const startRecording = useCallback(async () => {
@@ -536,11 +552,11 @@ export default function WatchPage() {
versions: prev.versions.map((v) => versions: prev.versions.map((v) =>
v.id === activeVersionId v.id === activeVersionId
? { ? {
...v, ...v,
comments: v.comments.map((c) => comments: v.comments.map((c) =>
c.id === commentId ? { ...c, isResolved: !c.isResolved } : c c.id === commentId ? { ...c, isResolved: !c.isResolved } : c
), ),
} }
: v : v
), ),
}; };
@@ -567,6 +583,7 @@ export default function WatchPage() {
timestamp: comments.find((c) => c.id === parentId)?.timestamp ?? currentTime, timestamp: comments.find((c) => c.id === parentId)?.timestamp ?? currentTime,
parentId, parentId,
...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }), ...(voiceData && { voiceUrl: voiceData.url, voiceDuration: voiceData.duration }),
...(isGuest && guestName && { guestName }),
}), }),
}); });
if (res.ok) { if (res.ok) {
@@ -578,13 +595,13 @@ export default function WatchPage() {
versions: prev.versions.map((v) => versions: prev.versions.map((v) =>
v.id === activeVersionId v.id === activeVersionId
? { ? {
...v, ...v,
comments: v.comments.map((c) => comments: v.comments.map((c) =>
c.id === parentId c.id === parentId
? { ...c, replies: [...c.replies, newReply] } ? { ...c, replies: [...c.replies, newReply] }
: c : c
), ),
} }
: v : v
), ),
}; };
@@ -686,17 +703,17 @@ export default function WatchPage() {
versions: prev.versions.map((v) => versions: prev.versions.map((v) =>
v.id === activeVersionId v.id === activeVersionId
? { ? {
...v, ...v,
comments: v.comments.map((c) => { comments: v.comments.map((c) => {
if (c.id === commentId) return { ...c, content: editText.trim() }; if (c.id === commentId) return { ...c, content: editText.trim() };
return { return {
...c, ...c,
replies: c.replies.map((r) => replies: c.replies.map((r) =>
r.id === commentId ? { ...r, content: editText.trim() } : r r.id === commentId ? { ...r, content: editText.trim() } : r
), ),
}; };
}), }),
} }
: v : v
), ),
}; };
@@ -724,14 +741,14 @@ export default function WatchPage() {
versions: prev.versions.map((v) => versions: prev.versions.map((v) =>
v.id === activeVersionId v.id === activeVersionId
? { ? {
...v, ...v,
comments: v.comments comments: v.comments
.filter((c) => c.id !== commentId) .filter((c) => c.id !== commentId)
.map((c) => ({ .map((c) => ({
...c, ...c,
replies: c.replies.filter((r) => r.id !== commentId), replies: c.replies.filter((r) => r.id !== commentId),
})), })),
} }
: v : v
), ),
}; };
@@ -790,6 +807,56 @@ export default function WatchPage() {
); );
} }
// Guest name gate — prompt guests to enter their name before viewing
if (isGuest && !guestNameConfirmed) {
return (
<div className="h-screen flex items-center justify-center bg-background">
<div className="w-full max-w-sm mx-auto p-6">
<div className="text-center mb-6">
<div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-primary/10 mb-4">
<User className="h-6 w-6 text-primary" />
</div>
<h1 className="text-xl font-semibold mb-1">Welcome to OpenFrame</h1>
<p className="text-sm text-muted-foreground">
Enter your name to view and comment on this video
</p>
</div>
<div className="space-y-3">
<Input
placeholder="Your name"
value={guestName}
onChange={(e) => setGuestName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && guestName.trim()) {
localStorage.setItem('openframe_guest_name', guestName.trim());
setGuestNameConfirmed(true);
}
}}
autoFocus
/>
<Button
className="w-full"
disabled={!guestName.trim()}
onClick={() => {
localStorage.setItem('openframe_guest_name', guestName.trim());
setGuestNameConfirmed(true);
}}
>
Continue
</Button>
</div>
<p className="text-xs text-muted-foreground text-center mt-4">
Or{' '}
<Link href="/login" className="text-primary hover:underline">
sign in
</Link>{' '}
for a full account
</p>
</div>
</div>
);
}
const embedUrl = getEmbedUrl(activeVersion); const embedUrl = getEmbedUrl(activeVersion);
return ( return (
+6
View File
@@ -19,6 +19,7 @@
"next": "16.1.6", "next": "16.1.6",
"next-auth": "^5.0.0-beta.30", "next-auth": "^5.0.0-beta.30",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"nodemailer": "^8.0.1",
"pg": "^8.18.0", "pg": "^8.18.0",
"prisma": "^7.3.0", "prisma": "^7.3.0",
"radix-ui": "^1.4.3", "radix-ui": "^1.4.3",
@@ -33,6 +34,7 @@
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@types/bcryptjs": "^3.0.0", "@types/bcryptjs": "^3.0.0",
"@types/node": "^20", "@types/node": "^20",
"@types/nodemailer": "^7.0.9",
"@types/pg": "^8.16.0", "@types/pg": "^8.16.0",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
@@ -686,6 +688,8 @@
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-Ez8QE4DMfhjjTsES9K2dwfV258qBui7qxUsoaixZDiTzbde4U12e1pXGNu/ECsUIOi5/zoCxAQxIhQnaUQ2VvA=="], "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-Ez8QE4DMfhjjTsES9K2dwfV258qBui7qxUsoaixZDiTzbde4U12e1pXGNu/ECsUIOi5/zoCxAQxIhQnaUQ2VvA=="],
"@types/nodemailer": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-vI8oF1M+8JvQhsId0Pc38BdUP2evenIIys7c7p+9OZXSPOH5c1dyINP1jT8xQ2xPuBUXmIC87s+91IZMDjH8Ow=="],
"@types/pg": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-RmhMd/wD+CF8Dfo+cVIy3RR5cl8CyfXQ0tGgW6XBL8L4LM/UTEbNXYRbLwU6w+CgrKBNbrQWt4FUtTfaU5jSYQ=="], "@types/pg": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-RmhMd/wD+CF8Dfo+cVIy3RR5cl8CyfXQ0tGgW6XBL8L4LM/UTEbNXYRbLwU6w+CgrKBNbrQWt4FUtTfaU5jSYQ=="],
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-KkiJeU6VbYbUOp5ITMIc7kBfqlYkKA5KhEHVrGMmUUMt7NeaZg65ojdPk+FtNrBAOXNVM5QM72jnADjM+XVRAQ=="], "@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-KkiJeU6VbYbUOp5ITMIc7kBfqlYkKA5KhEHVrGMmUUMt7NeaZg65ojdPk+FtNrBAOXNVM5QM72jnADjM+XVRAQ=="],
@@ -1412,6 +1416,8 @@
"node-releases": ["[email protected]", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="], "node-releases": ["[email protected]", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="],
"nodemailer": ["[email protected]", "", {}, "sha512-5kcldIXmaEjZcHR6F28IKGSgpmZHaF1IXLWFTG+Xh3S+Cce4MiakLtWY+PlBU69fLbRa8HlaGIrC/QolUpHkhg=="],
"npm-run-path": ["[email protected]", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="], "npm-run-path": ["[email protected]", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="],
"nypm": ["[email protected]", "", { "dependencies": { "citty": "^0.2.0", "pathe": "^2.0.3", "tinyexec": "^1.0.2" }, "bin": { "nypm": "dist/cli.mjs" } }, "sha512-K6AJy1GMVyfyMXRVB88700BJqNUkByijGJM8kEHpLdcAt+vSQAVfkWWHYzuRXHSY6xA2sNc5RjTj0p9rE2izVQ=="], "nypm": ["[email protected]", "", { "dependencies": { "citty": "^0.2.0", "pathe": "^2.0.3", "tinyexec": "^1.0.2" }, "bin": { "nypm": "dist/cli.mjs" } }, "sha512-K6AJy1GMVyfyMXRVB88700BJqNUkByijGJM8kEHpLdcAt+vSQAVfkWWHYzuRXHSY6xA2sNc5RjTj0p9rE2izVQ=="],
+72
View File
@@ -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 (
<div className="h-screen flex items-center justify-center bg-background">
<div className="w-full max-w-sm mx-auto p-6">
<div className="text-center mb-6">
<div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-primary/10 mb-4">
<User className="h-6 w-6 text-primary" />
</div>
<h1 className="text-xl font-semibold mb-1">Welcome to OpenFrame</h1>
<p className="text-sm text-muted-foreground">
Enter your name to view and comment on this project
</p>
</div>
<div className="space-y-3">
<Input
placeholder="Your name"
value={guestName}
onChange={(e) => setGuestName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') confirm();
}}
autoFocus
/>
<Button className="w-full" disabled={!guestName.trim()} onClick={confirm}>
Continue
</Button>
</div>
<p className="text-xs text-muted-foreground text-center mt-4">
Or{' '}
<Link href="/login" className="underline hover:text-foreground">
sign in
</Link>{' '}
with your account
</p>
</div>
</div>
);
}
+415
View File
@@ -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<boolean> {
try {
const payload: Record<string, unknown> = {
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<boolean> {
const transporter = createSmtpTransport();
const fromAddress = process.env.SMTP_FROM || process.env.EMAIL_FROM || 'OpenFrame <[email protected]>';
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 `<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><meta name="color-scheme" content="dark"></head>
<body style="margin:0;padding:0;background-color:${COLORS.bg};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:${COLORS.text};">
<table width="100%" cellpadding="0" cellspacing="0" style="background-color:${COLORS.bg};padding:40px 16px;">
<tr><td align="center">
<table width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;">
<!-- Header -->
<tr><td style="padding:0 0 24px;">
<table cellpadding="0" cellspacing="0"><tr>
<td style="padding-right:10px;vertical-align:middle;color:${COLORS.accent};font-size:20px;">&#9654;</td>
<td style="vertical-align:middle;font-size:18px;font-weight:700;color:${COLORS.text};letter-spacing:-0.3px;">OpenFrame</td>
</tr></table>
</td></tr>
<!-- Main Card -->
<tr><td style="background-color:${COLORS.card};border:1px solid ${COLORS.border};padding:0;">
${body}
</td></tr>
<!-- Footer -->
<tr><td style="padding:20px 0 0;text-align:center;">
<p style="margin:0 0 6px;font-size:11px;color:${COLORS.textDim};">You received this because email notifications are enabled.</p>
<a href="${escapeAttr(settingsUrl)}" style="font-size:11px;color:${COLORS.accent};text-decoration:underline;">Unsubscribe &middot; Manage notification settings</a>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}
/** 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 `<tr>
<td style="padding:6px 16px 6px 0;color:${COLORS.textDim};font-size:13px;white-space:nowrap;vertical-align:top;">${label}</td>
<td style="padding:6px 0;font-size:13px;${valStyle}">${value}</td>
</tr>`;
}
/** Generates the accent-colored event type heading bar */
function emailHeading(icon: string, title: string): string {
return `<td style="padding:16px 20px;border-bottom:1px solid ${COLORS.border};background-color:${COLORS.accentDark};">
<span style="font-size:14px;font-weight:600;color:${COLORS.accent};">${icon} &nbsp;${title}</span>
</td>`;
}
/** Generates a CTA button */
function emailButton(text: string, url: string): string {
return `<a href="${escapeAttr(url)}" style="display:inline-block;padding:9px 22px;background-color:${COLORS.accent};color:#0f1114;font-size:13px;font-weight:600;text-decoration:none;letter-spacing:0.2px;">${text}</a>`;
}
/**
* 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(`
<tr>${emailHeading('&#9654;', 'New Video Added')}</tr>
<tr><td style="padding:20px;">
<table cellpadding="0" cellspacing="0" style="width:100%;margin-bottom:20px;">
${emailRow('Project', escapeHtml(event.projectName), true)}
${emailRow('Video', escapeHtml(event.videoTitle), true)}
${emailRow('Added by', escapeHtml(event.addedBy))}
${emailRow('When', now)}
</table>
${emailButton('View Video &#8594;', event.url)}
</td></tr>
`),
};
case 'new_comment':
return {
subject: `[OpenFrame] New comment on ${event.videoTitle}`,
html: emailTemplate(`
<tr>${emailHeading('&#9679;', 'New Comment')}</tr>
<tr><td style="padding:20px;">
<table cellpadding="0" cellspacing="0" style="width:100%;margin-bottom:16px;">
${emailRow('Project', escapeHtml(event.projectName), true)}
${emailRow('Video', escapeHtml(event.videoTitle), true)}
${emailRow('From', escapeHtml(event.commentAuthor))}
${emailRow('At', event.timestamp)}
${emailRow('When', now)}
</table>
<div style="border-left:2px solid ${COLORS.accent};padding:10px 14px;margin:0 0 20px;background-color:${COLORS.cardInner};color:${COLORS.textSecondary};font-size:13px;line-height:1.6;">
${escapeHtml(truncate(event.commentText, 300))}
</div>
${emailButton('View Comment &#8594;', event.url)}
</td></tr>
`),
};
case 'new_reply':
return {
subject: `[OpenFrame] ${event.replyAuthor} replied on ${event.videoTitle}`,
html: emailTemplate(`
<tr>${emailHeading('&#8617;', 'New Reply')}</tr>
<tr><td style="padding:20px;">
<table cellpadding="0" cellspacing="0" style="width:100%;margin-bottom:16px;">
${emailRow('Project', escapeHtml(event.projectName), true)}
${emailRow('Video', escapeHtml(event.videoTitle), true)}
${emailRow('From', `<span style="color:${COLORS.text};font-weight:500;">${escapeHtml(event.replyAuthor)}</span> <span style="color:${COLORS.textDim};">&#8594;</span> ${escapeHtml(event.parentAuthor)}`)}
${emailRow('When', now)}
</table>
<div style="border-left:2px solid ${COLORS.accent};padding:10px 14px;margin:0 0 20px;background-color:${COLORS.cardInner};color:${COLORS.textSecondary};font-size:13px;line-height:1.6;">
${escapeHtml(truncate(event.replyText, 300))}
</div>
${emailButton('View Reply &#8594;', event.url)}
</td></tr>
`),
};
}
}
/**
* Generate branded HTML for test emails sent from settings page.
*/
export function testEmailHtml(): string {
return emailTemplate(`
<tr>${emailHeading('&#10003;', 'Test Notification')}</tr>
<tr><td style="padding:20px;">
<p style="margin:0 0 8px;font-size:14px;color:${COLORS.text};">Email notifications are working.</p>
<p style="margin:0;font-size:13px;color:${COLORS.textSecondary};">You&rsquo;ll receive emails when there&rsquo;s activity on your projects.</p>
</td></tr>
`);
}
// ============================================
// 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<void> {
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<boolean>[] = [];
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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
/** Escape a URL for use inside an HTML href="..." attribute */
function escapeAttr(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
function truncate(str: string, maxLen: number): string {
return str.length > maxLen ? str.slice(0, maxLen) + '...' : str;
}
+9 -1
View File
@@ -6,7 +6,13 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "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": { "dependencies": {
"@auth/prisma-adapter": "^2.11.1", "@auth/prisma-adapter": "^2.11.1",
@@ -23,6 +29,7 @@
"next": "16.1.6", "next": "16.1.6",
"next-auth": "^5.0.0-beta.30", "next-auth": "^5.0.0-beta.30",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"nodemailer": "^8.0.1",
"pg": "^8.18.0", "pg": "^8.18.0",
"prisma": "^7.3.0", "prisma": "^7.3.0",
"radix-ui": "^1.4.3", "radix-ui": "^1.4.3",
@@ -37,6 +44,7 @@
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@types/bcryptjs": "^3.0.0", "@types/bcryptjs": "^3.0.0",
"@types/node": "^20", "@types/node": "^20",
"@types/nodemailer": "^7.0.9",
"@types/pg": "^8.16.0", "@types/pg": "^8.16.0",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
+49
View File
@@ -30,6 +30,7 @@ model User {
projects Project[] projects Project[]
comments Comment[] comments Comment[]
projectMemberships ProjectMember[] projectMemberships ProjectMember[]
notificationSetting NotificationSetting?
@@map("users") @@map("users")
} }
@@ -321,3 +322,51 @@ enum SharePermission {
VIEW // Can only view VIEW // Can only view
COMMENT // Can view and comment 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")
}
+56
View File
@@ -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();