Reimplemented outdated code, added encryption keys for each room, added support for profile images, added friend requests via url/qr-code

This commit is contained in:
pascalyazid committed 2026-05-11 21:35:28 +02:00
1 parent 508f17315e
commit 32e4bf8b32
58 files changed
+3270 -362

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
"use server";
import { revalidatePath } from "next/cache";
import { sendMessage, decryptIncomingMessage } from "@/utils/rooms/messages";
export type SendMessageState = { error: string } | { messageId: string } | null;
export async function sendMessageAction(
roomId: string,
_prevState: SendMessageState,
formData: FormData,
): Promise<SendMessageState> {
const value = formData.get("message");
if (typeof value !== "string" || !value.trim()) {
return { error: "Message cannot be empty." };
}
const result = await sendMessage(roomId, value.trim());
if (result.error) {
return { error: result.error };
}
revalidatePath(`/rooms/${roomId}`);
return { messageId: result.messageId };
}
export async function decryptMessageAction(
roomId: string,
encryptedValue: string,
iv: string,
authTag: string,
): Promise<{ plaintext: string } | { error: string }> {
return decryptIncomingMessage(roomId, encryptedValue, iv, authTag);
}
+326
View File
@@ -0,0 +1,326 @@
"use client";
import {
useActionState,
useRef,
useEffect,
useState,
useCallback,
useMemo,
} from "react";
import Image from "next/image";
import { createClient } from "@/utils/supabase/client";
import type { Message } from "@/types/chat";
import {
sendMessageAction,
decryptMessageAction,
type SendMessageState,
} from "./actions";
import type { MemberInfo } from "./member-map";
const initialState: SendMessageState = null;
// Prefix for temporary optimistic IDs
const OPTIMISTIC_PREFIX = "optimistic-";
export function Chat({
roomId,
initialMessages,
currentUserId,
memberMap,
}: {
roomId: string;
initialMessages: Message[];
currentUserId: string;
memberMap: Map<string, MemberInfo>;
}) {
const boundAction = sendMessageAction.bind(null, roomId);
const [state, action, pending] = useActionState(boundAction, initialState);
const formRef = useRef<HTMLFormElement>(null);
const bottomRef = useRef<HTMLDivElement>(null);
const optimisticCounter = useRef(0);
const [localMessages, setLocalMessages] = useState<Message[]>([]);
// Merge server messages (prop) with local messages (optimistic + realtime)
// Server messages that match local optimistic ones by user+value are replaced
// by the local version (which may have a real ID from realtime confirmation)
const messages = useMemo(() => {
const serverIds = new Set(initialMessages.map((m) => m.id));
const optimisticConfirmed = new Set<string>();
for (const local of localMessages) {
if (!local.id.startsWith(OPTIMISTIC_PREFIX) && !serverIds.has(local.id)) {
const match = initialMessages.find(
(s) => s.user_id === local.user_id && s.value === local.value,
);
if (match) optimisticConfirmed.add(match.id);
}
}
const serverFiltered = initialMessages.filter(
(m) => !optimisticConfirmed.has(m.id),
);
const localFiltered = localMessages.filter((m) => {
if (serverIds.has(m.id)) return false;
if (m.id.startsWith(OPTIMISTIC_PREFIX)) {
const serverValues = new Set(
initialMessages
.filter((s) => s.user_id === m.user_id)
.map((s) => s.value),
);
if (serverValues.has(m.value)) return false;
}
return true;
});
const merged = [...serverFiltered, ...localFiltered];
merged.sort(
(a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
);
return merged;
}, [initialMessages, localMessages]);
const scrollToBottom = useCallback(() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}, []);
const messageCount = messages.length;
useEffect(() => {
scrollToBottom();
}, [messageCount, scrollToBottom]);
// Clear input after successful send
useEffect(() => {
if (state !== null && !("error" in state) && !pending) {
formRef.current?.reset();
}
}, [state, pending]);
const handleAction = useCallback(
(formData: FormData) => {
const value = formData.get("message");
if (typeof value === "string" && value.trim()) {
const tempId = `${OPTIMISTIC_PREFIX}${++optimisticCounter.current}`;
const optimisticMsg: Message = {
id: tempId,
value: value.trim(),
created_at: new Date().toISOString(),
user_id: currentUserId,
room_id: roomId,
user: {
name: memberMap.get(currentUserId)?.name ?? "You",
avatar_url: memberMap.get(currentUserId)?.avatar_url ?? null,
},
};
setLocalMessages((prev) => [optimisticMsg, ...prev]);
}
action(formData);
},
[action, currentUserId, roomId, memberMap],
);
useEffect(() => {
const supabase = createClient();
const channel = supabase
.channel(`room-messages:${roomId}`)
.on(
"postgres_changes",
{
event: "INSERT",
schema: "public",
table: "messages",
filter: `room_id=eq.${roomId}`,
},
(payload: { new: Record<string, string> }) => {
const realId = payload.new.id;
const realUserId = payload.new.user_id;
if (realUserId === currentUserId) {
// Own message confirmed by server — swap optimistic ID → real ID
setLocalMessages((prev) => {
if (prev.some((m) => m.id === realId)) return prev;
const optimisticIdx = prev.findIndex(
(m) =>
m.id.startsWith(OPTIMISTIC_PREFIX) &&
m.user_id === currentUserId,
);
if (optimisticIdx !== -1) {
const updated = [...prev];
updated[optimisticIdx] = {
...updated[optimisticIdx],
id: realId,
created_at: payload.new.created_at,
};
return updated;
}
return prev;
});
} else {
// Other user's message — decrypt via server action
void decryptMessageAction(
roomId,
payload.new.value,
payload.new.iv ?? "",
payload.new.auth_tag ?? "",
).then((result) => {
if ("plaintext" in result) {
const msg: Message = {
id: realId,
value: result.plaintext,
created_at: payload.new.created_at,
user_id: realUserId,
room_id: payload.new.room_id,
user: {
name: memberMap.get(realUserId)?.name ?? "Unknown",
avatar_url: memberMap.get(realUserId)?.avatar_url ?? null,
},
};
setLocalMessages((prev) => {
if (prev.some((m) => m.id === realId)) return prev;
return [msg, ...prev];
});
}
});
}
},
)
.subscribe();
return () => {
void supabase.removeChannel(channel);
};
}, [roomId, memberMap, currentUserId]);
const displayMessages = [...messages].reverse();
return (
<div className=" rounded-xl border border-neutral-200 bg-white shadow-sm">
{/* Messages area */}
<div className="h-[calc(100vh-20rem)] overflow-y-auto p-4">
{displayMessages.length === 0 ? (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-neutral-400">
No messages yet. Start the conversation!
</p>
</div>
) : (
<div className="space-y-4">
{displayMessages.map((msg) => {
const isOwn = msg.user_id === currentUserId;
const isPending = msg.id.startsWith(OPTIMISTIC_PREFIX);
return (
<div
key={msg.id}
className={`flex ${isOwn ? "justify-end" : "justify-start"}`}
>
<div
className={`max-w-[75%] rounded-2xl px-4 py-2.5 transition-opacity ${
isOwn
? "bg-neutral-900 text-white"
: "bg-neutral-100 text-neutral-900"
} ${isPending ? "opacity-60" : "opacity-100"}`}
>
{!isOwn && (
<div className="mb-1 flex items-center gap-2">
<Avatar
name={msg.user?.name ?? "Unknown"}
avatarUrl={msg.user?.avatar_url ?? null}
size="md"
/>
<span className="text-xs font-semibold text-neutral-500">
{msg.user?.name ?? "Unknown"}
</span>
</div>
)}
<p className="text-sm whitespace-pre-wrap wrap-break-words">
{msg.value}
</p>
<p className="mt-1 text-right text-[10px] text-neutral-400">
{isPending ? "Sending..." : formatTime(msg.created_at)}
</p>
</div>
</div>
);
})}
<div ref={bottomRef} />
</div>
)}
</div>
{/* Send bar */}
<div className="border-t border-neutral-200 p-3">
<form ref={formRef} action={handleAction} className="flex gap-2">
<input
name="message"
type="text"
placeholder="Type a message..."
required
autoComplete="off"
className="flex-1 rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm placeholder:text-neutral-400 focus:border-neutral-900 focus:outline-none"
/>
<button
type="submit"
disabled={pending}
className="rounded-lg bg-neutral-900 px-4 py-2 text-sm font-medium text-white shadow-sm transition hover:bg-neutral-800 disabled:cursor-not-allowed disabled:bg-neutral-400"
>
{pending ? "Sending..." : "Send"}
</button>
</form>
{state && "error" in state && (
<p className="mt-2 text-xs text-red-600">{state.error}</p>
)}
</div>
</div>
);
}
function formatTime(isoString: string): string {
const date = new Date(isoString);
return date.toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
});
}
function Avatar({
name,
avatarUrl,
size = "md",
}: {
name: string;
avatarUrl: string | null;
size?: "sm" | "md";
}) {
const sizeClass = size === "sm" ? "size-5" : "size-8";
const textSize = size === "sm" ? "text-[10px]" : "text-xs";
if (avatarUrl) {
return (
<Image
src={avatarUrl}
alt=""
width={200}
height={200}
className={`${sizeClass} shrink-0 rounded-full object-cover`}
/>
);
}
return (
<div
className={`flex ${sizeClass} shrink-0 items-center justify-center rounded-full bg-neutral-200 font-medium text-neutral-600 ${textSize}`}
>
{name.charAt(0).toUpperCase()}
</div>
);
}
+21
View File
@@ -0,0 +1,21 @@
export default function RoomDetailLoading() {
return (
<div className="flex h-full flex-col">
{/* Header skeleton */}
<div className="flex items-center gap-3 border-b border-neutral-200 bg-white px-6 py-3">
<div className="size-8 animate-pulse rounded-lg bg-neutral-200" />
<div className="space-y-2">
<div className="h-4 w-32 animate-pulse rounded bg-neutral-200" />
<div className="h-3 w-20 animate-pulse rounded bg-neutral-200" />
</div>
</div>
{/* Chat area skeleton */}
<div className="flex flex-1 items-center justify-center">
<div className="flex flex-col items-center gap-3">
<div className="size-8 animate-spin rounded-full border-2 border-neutral-300 border-t-neutral-900" />
<p className="text-sm text-neutral-500">Loading room...</p>
</div>
</div>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import type { MemberEntry } from "./members-list";
export interface MemberInfo {
name: string;
avatar_url: string | null;
}
export function buildMemberMap(
members: MemberEntry[],
): Map<string, MemberInfo> {
const map = new Map<string, MemberInfo>();
for (const m of members) {
map.set(m.user_id, { name: m.name, avatar_url: m.avatar_url });
}
return map;
}
+84
View File
@@ -0,0 +1,84 @@
import Image from "next/image";
export interface MemberEntry {
user_id: string;
name: string;
avatar_url: string | null;
}
export function MembersList({
members,
currentUserId,
onRemoveMember,
disableActions,
}: {
members: MemberEntry[];
currentUserId?: string;
onRemoveMember?: (userId: string) => void;
disableActions?: boolean;
}) {
if (members.length === 0) return null;
return (
<div>
<h2 className="text-sm font-semibold text-neutral-900">
Members
<span className="ml-2 text-xs font-normal text-neutral-500">
{members.length}
</span>
</h2>
<ul className="mt-3 divide-y divide-neutral-100 rounded-xl border border-neutral-200 bg-white">
{members.map((member) => {
const isSelf = member.user_id === currentUserId;
return (
<li
key={member.user_id}
className="flex items-center gap-3 px-4 py-3"
>
{member.avatar_url ? (
<Image
src={member.avatar_url}
alt=""
width={200}
height={200}
className="size-8 rounded-full object-cover"
/>
) : (
<div className="flex size-8 items-center justify-center rounded-full bg-neutral-100 text-xs font-medium text-neutral-600">
{member.name.charAt(0).toUpperCase()}
</div>
)}
<span className="flex-1 text-sm font-medium text-neutral-900">
{member.name}
{isSelf && (
<span className="ml-1.5 text-xs font-normal text-neutral-400">
(you)
</span>
)}
</span>
{!isSelf && onRemoveMember && (
<button
type="button"
onClick={() => onRemoveMember(member.user_id)}
disabled={disableActions}
className="shrink-0 rounded-md px-2 py-1 text-xs text-neutral-400 transition hover:bg-red-50 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-50"
title={`Remove ${member.name}`}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
className="size-4"
>
<path d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z" />
</svg>
</button>
)}
</li>
);
})}
</ul>
</div>
);
}
+90
View File
@@ -0,0 +1,90 @@
import { createClient } from "@/utils/supabase/server";
import { listMembers } from "@/utils/rooms/rooms";
import { getMessages } from "@/utils/rooms/messages";
import { notFound } from "next/navigation";
import Link from "next/link";
import { Chat } from "./chat";
import { RoomSettings } from "./room-settings";
import { buildMemberMap } from "./member-map";
export default async function RoomDetailPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return notFound();
const { data: membership } = await supabase
.from("rooms_users")
.select("room_id")
.eq("room_id", id)
.eq("user_id", user.id)
.single();
if (!membership) return notFound();
const { data: room } = await supabase
.from("rooms")
.select("id, name, created_at")
.eq("id", id)
.single();
if (!room) return notFound();
const [members, { messages }] = await Promise.all([
listMembers(id),
getMessages(id),
]);
return (
<div className="flex h-full flex-col">
{/* Header */}
<div className="flex items-center justify-between border-b border-neutral-200 bg-white px-6 py-3">
<div className="flex items-center gap-3">
<Link
href="/rooms"
className="flex size-8 items-center justify-center rounded-lg text-neutral-500 transition hover:bg-neutral-100 hover:text-neutral-900"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
className="size-5"
>
<path
fillRule="evenodd"
d="M17 10a.75.75 0 0 1-.75.75H5.612l4.158 3.96a.75.75 0 0 1-1.04 1.08l-5.5-5.25a.75.75 0 0 1 0-1.08l5.5-5.25a.75.75 0 1 1 1.04 1.08L5.612 9.25H16.25A.75.75 0 0 1 17 10Z"
clipRule="evenodd"
/>
</svg>
</Link>
<div>
<h1 className="text-base font-semibold text-neutral-900">
{room.name}
</h1>
<p className="text-xs text-neutral-500">
{members.length} {members.length === 1 ? "member" : "members"}
</p>
</div>
</div>
<RoomSettings roomId={id} members={members} currentUserId={user.id} />
</div>
{/* Chat */}
<div className="flex-1 overflow-hidden">
<Chat
roomId={id}
initialMessages={messages}
currentUserId={user.id}
memberMap={buildMemberMap(members)}
/>
</div>
</div>
);
}
+107
View File
@@ -0,0 +1,107 @@
"use client";
import { useState, useTransition } from "react";
import type { MemberEntry } from "./members-list";
import { MembersList } from "./members-list";
import { AddMemberForm } from "../add-member-form";
import { deleteRoomAction, removeMemberAction } from "../actions";
export function RoomSettings({
roomId,
members,
currentUserId,
}: {
roomId: string;
members: MemberEntry[];
currentUserId: string;
}) {
const [open, setOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const [removeError, setRemoveError] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const handleDeleteRoom = () => {
if (
!confirm(
"Are you sure you want to delete this room? This cannot be undone.",
)
) {
return;
}
setDeleting(true);
startTransition(() => {
deleteRoomAction(roomId);
});
};
const handleRemoveMember = (userId: string) => {
setRemoveError(null);
startTransition(async () => {
const result = await removeMemberAction(roomId, userId);
if (result.error) {
setRemoveError(result.error);
}
});
};
return (
<div className="relative">
<button
onClick={() => setOpen(!open)}
aria-label="Room settings"
className="flex size-8 items-center justify-center rounded-lg text-neutral-500 transition hover:bg-neutral-100 hover:text-neutral-900"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
className="size-5"
>
<path
fillRule="evenodd"
d="M2 4.75A.75.75 0 0 1 2.75 4h14.5a.75.75 0 0 1 0 1.5H2.75A.75.75 0 0 1 2 4.75ZM2 10a.75.75 0 0 1 .75-.75h14.5a.75.75 0 0 1 0 1.5H2.75A.75.75 0 0 1 2 10Zm0 5.25a.75.75 0 0 1 .75-.75h14.5a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1-.75-.75Z"
clipRule="evenodd"
/>
</svg>
</button>
{open && (
<>
{/* Backdrop */}
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
{/* Panel */}
<div className="absolute right-0 top-full z-50 mt-2 w-80 rounded-xl border border-neutral-200 bg-white p-5 shadow-lg">
<h2 className="text-sm font-semibold text-neutral-900">
Room Settings
</h2>
{removeError && (
<p className="mt-2 text-xs text-red-600">{removeError}</p>
)}
<div className="mt-4 space-y-5">
<AddMemberForm roomId={roomId} />
<MembersList
members={members}
currentUserId={currentUserId}
onRemoveMember={handleRemoveMember}
disableActions={isPending}
/>
</div>
{/* Danger zone */}
<div className="mt-5 border-t border-neutral-100 pt-4">
<button
onClick={handleDeleteRoom}
disabled={deleting}
className="w-full rounded-lg border border-red-200 bg-white px-3 py-2 text-sm font-medium text-red-600 transition hover:bg-red-50 disabled:cursor-not-allowed disabled:opacity-50"
>
{deleting ? "Deleting..." : "Delete Room"}
</button>
</div>
</div>
</>
)}
</div>
);
}