feat: direct messages
1:1 conversations (userAId < userBId dedup pair), messages, per-participant read tracking (conversation_reads). Block relationship is enforced on every send. UI: /messages list + /messages/[id] thread (5s poll), MessageButton on profiles, unread-badged nav icon. This completes the social-feature backlog: notifications, rate limiting, blocking, reporting, search/discovery, mentions, DMs, plus fixes for the recipe-visibility 404, follow race, and 2-level comment thread cap found during the earlier audit. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, conversations, users, eq } from "@epicure/db";
|
||||
import { ConversationsList } from "@/components/social/conversations-list";
|
||||
import { MessageThread } from "@/components/social/message-thread";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { isParticipant, otherParticipantId } from "@/lib/messaging";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export default async function ConversationPage({ params }: Params) {
|
||||
const { id } = await params;
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
|
||||
const conversation = await db.query.conversations.findFirst({ where: eq(conversations.id, id) });
|
||||
if (!conversation || !isParticipant(conversation, session.user.id)) notFound();
|
||||
|
||||
const otherId = otherParticipantId(conversation, session.user.id);
|
||||
const other = await db.query.users.findFirst({ where: eq(users.id, otherId) });
|
||||
if (!other) notFound();
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto h-[calc(100vh-8rem)] border rounded-xl overflow-hidden flex">
|
||||
<div className="hidden sm:block w-80 border-r shrink-0 overflow-y-auto">
|
||||
<ConversationsList />
|
||||
</div>
|
||||
<div className="flex-1 flex flex-col min-w-0">
|
||||
<div className="border-b p-3 flex items-center gap-3">
|
||||
<Link href={`/u/${other.username}`} className="flex items-center gap-3">
|
||||
<Avatar className="h-8 w-8">
|
||||
{other.avatarUrl && <AvatarImage src={other.avatarUrl} />}
|
||||
<AvatarFallback className="text-xs">{other.name.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="font-medium text-sm hover:underline">{other.name}</span>
|
||||
</Link>
|
||||
</div>
|
||||
<MessageThread conversationId={id} currentUserId={session.user.id} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Metadata } from "next";
|
||||
import { MessageCircle } from "lucide-react";
|
||||
import { ConversationsList } from "@/components/social/conversations-list";
|
||||
|
||||
export const metadata: Metadata = { title: "Messages — Epicure" };
|
||||
|
||||
export default function MessagesPage() {
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto h-[calc(100vh-8rem)] border rounded-xl overflow-hidden flex">
|
||||
<div className="w-full sm:w-80 border-r shrink-0 overflow-y-auto">
|
||||
<ConversationsList />
|
||||
</div>
|
||||
<div className="hidden sm:flex flex-1 items-center justify-center text-muted-foreground">
|
||||
<div className="text-center space-y-2">
|
||||
<MessageCircle className="h-10 w-10 mx-auto opacity-50" />
|
||||
<p className="text-sm">Select a conversation</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { FollowButton } from "@/components/social/follow-button";
|
||||
import { BlockButton } from "@/components/social/block-button";
|
||||
import { MessageButton } from "@/components/social/message-button";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
|
||||
type Params = { params: Promise<{ username: string }> };
|
||||
@@ -113,6 +114,7 @@ export default async function UserProfilePage({ params }: Params) {
|
||||
targetUsername={user.username!}
|
||||
initialFollowing={isFollowing}
|
||||
/>
|
||||
{!isBlocked && <MessageButton targetUsername={user.username!} />}
|
||||
<BlockButton targetUsername={user.username!} initialBlocked={isBlocked} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, conversations, conversationReads, messages, eq, asc } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { isParticipant, otherParticipantId } from "@/lib/messaging";
|
||||
import { isBlockedEitherWay } from "@/lib/blocks";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
const Schema = z.object({ content: z.string().min(1).max(4000) });
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: RouteContext) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
const { id } = await params;
|
||||
|
||||
const conversation = await db.query.conversations.findFirst({ where: eq(conversations.id, id) });
|
||||
if (!conversation || !isParticipant(conversation, session!.user.id)) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(messages)
|
||||
.where(eq(messages.conversationId, id))
|
||||
.orderBy(asc(messages.createdAt))
|
||||
.limit(200);
|
||||
|
||||
await db
|
||||
.insert(conversationReads)
|
||||
.values({ conversationId: id, userId: session!.user.id, lastReadAt: new Date() })
|
||||
.onConflictDoUpdate({
|
||||
target: [conversationReads.conversationId, conversationReads.userId],
|
||||
set: { lastReadAt: new Date() },
|
||||
});
|
||||
|
||||
return NextResponse.json({ messages: rows });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest, { params }: RouteContext) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
const { id } = await params;
|
||||
|
||||
const limited = await applyRateLimit(`rl:message:${session!.user.id}`, 30, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
const conversation = await db.query.conversations.findFirst({ where: eq(conversations.id, id) });
|
||||
if (!conversation || !isParticipant(conversation, session!.user.id)) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const otherId = otherParticipantId(conversation, session!.user.id);
|
||||
if (await isBlockedEitherWay(session!.user.id, otherId)) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const body = await req.json() as unknown;
|
||||
const parsed = Schema.safeParse(body);
|
||||
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
||||
|
||||
const messageId = randomUUID();
|
||||
await db.insert(messages).values({
|
||||
id: messageId,
|
||||
conversationId: id,
|
||||
senderId: session!.user.id,
|
||||
content: parsed.data.content,
|
||||
});
|
||||
await db.update(conversations).set({ lastMessageAt: new Date() }).where(eq(conversations.id, id));
|
||||
|
||||
return NextResponse.json({ id: messageId }, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, conversations, conversationReads, messages, users, eq, or, desc, and, gt, sql } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { findOrCreateConversation, otherParticipantId } from "@/lib/messaging";
|
||||
import { isBlockedEitherWay } from "@/lib/blocks";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
const CreateSchema = z.object({
|
||||
username: z.string().min(1),
|
||||
content: z.string().min(1).max(4000).optional(),
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(conversations)
|
||||
.where(or(eq(conversations.userAId, session!.user.id), eq(conversations.userBId, session!.user.id)))
|
||||
.orderBy(desc(conversations.lastMessageAt))
|
||||
.limit(50);
|
||||
|
||||
const result = await Promise.all(
|
||||
rows.map(async (conv) => {
|
||||
const otherId = otherParticipantId(conv, session!.user.id);
|
||||
const [other, lastMessage, readRow] = await Promise.all([
|
||||
db.query.users.findFirst({
|
||||
where: eq(users.id, otherId),
|
||||
columns: { id: true, name: true, username: true, avatarUrl: true },
|
||||
}),
|
||||
db.query.messages.findFirst({
|
||||
where: eq(messages.conversationId, conv.id),
|
||||
orderBy: (m, { desc: d }) => [d(m.createdAt)],
|
||||
}),
|
||||
db.query.conversationReads.findFirst({
|
||||
where: and(eq(conversationReads.conversationId, conv.id), eq(conversationReads.userId, session!.user.id)),
|
||||
}),
|
||||
]);
|
||||
|
||||
const unreadRow = await db
|
||||
.select({ total: sql<string>`count(*)` })
|
||||
.from(messages)
|
||||
.where(
|
||||
and(
|
||||
eq(messages.conversationId, conv.id),
|
||||
readRow ? gt(messages.createdAt, readRow.lastReadAt) : sql`true`,
|
||||
sql`${messages.senderId} != ${session!.user.id}`
|
||||
)
|
||||
);
|
||||
|
||||
return {
|
||||
id: conv.id,
|
||||
otherUser: other,
|
||||
lastMessage: lastMessage?.content ?? null,
|
||||
lastMessageAt: conv.lastMessageAt,
|
||||
unreadCount: Number(unreadRow[0]?.total ?? 0),
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return NextResponse.json({ conversations: result });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const limited = await applyRateLimit(`rl:message:${session!.user.id}`, 30, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
const body = await req.json() as unknown;
|
||||
const parsed = CreateSchema.safeParse(body);
|
||||
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
||||
|
||||
const target = await db.query.users.findFirst({ where: eq(users.username, parsed.data.username) });
|
||||
if (!target) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
if (target.id === session!.user.id) return NextResponse.json({ error: "Cannot message yourself" }, { status: 400 });
|
||||
|
||||
if (await isBlockedEitherWay(session!.user.id, target.id)) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const conversation = await findOrCreateConversation(session!.user.id, target.id);
|
||||
|
||||
if (parsed.data.content) {
|
||||
await db.insert(messages).values({
|
||||
id: randomUUID(),
|
||||
conversationId: conversation.id,
|
||||
senderId: session!.user.id,
|
||||
content: parsed.data.content,
|
||||
});
|
||||
await db.update(conversations).set({ lastMessageAt: new Date() }).where(eq(conversations.id, conversation.id));
|
||||
}
|
||||
|
||||
return NextResponse.json({ conversationId: conversation.id }, { status: 201 });
|
||||
}
|
||||
Reference in New Issue
Block a user