Skip to content

Commit 8dd9abd

Browse files
committed
fixing(websocket): empty token parameter in WebSocket URL; WS connection issues
1 parent ac5076b commit 8dd9abd

File tree

11 files changed

+93
-217
lines changed

11 files changed

+93
-217
lines changed

apps/collabydraw/app/api/auth/signup.ts

Lines changed: 0 additions & 32 deletions
This file was deleted.

apps/collabydraw/app/api/createRoom/route.ts

Lines changed: 0 additions & 50 deletions
This file was deleted.

apps/collabydraw/app/api/room/create/route.ts

Lines changed: 0 additions & 50 deletions
This file was deleted.

apps/collabydraw/app/api/room/join/route.ts

Lines changed: 0 additions & 50 deletions
This file was deleted.

apps/collabydraw/app/api/user/route.ts

Lines changed: 0 additions & 11 deletions
This file was deleted.

apps/collabydraw/components/CollaborationStartBtn.tsx

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@ import { RoomSharingDialog } from "./RoomSharingDialog";
88
import { usePathname } from "next/navigation";
99
import { CollaborationAdDialog } from "./CollaborationAdDialog";
1010
import { cn } from "@/lib/utils";
11+
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip";
12+
import { RoomParticipants } from "@repo/common/types";
1113

12-
export default function CollaborationStartBtn({ slug, participantsCount }: { slug?: string, participantsCount?: number }) {
14+
export default function CollaborationStartBtn({ slug, participants }: { slug?: string, participants?: RoomParticipants[] }) {
1315
const pathname = usePathname();
1416
const [isOpen, setIsOpen] = useState(false);
1517
const { data: session } = useSession();
@@ -18,10 +20,32 @@ export default function CollaborationStartBtn({ slug, participantsCount }: { slu
1820

1921
return (
2022
<div className="Start_Room_Session transition-transform duration-500 ease-in-out flex items-center justify-end">
23+
<div className="UserList__wrapper flex w-full justify-end items-center">
24+
<div className="UserList p-1 flex flex-wrap justify-end items-center gap-[.625rem]">
25+
<TooltipProvider delayDuration={0}>
26+
<div className="flex space-x-2">
27+
{participants?.map((participant) => (
28+
<Tooltip key={participant.userId}>
29+
<TooltipTrigger asChild>
30+
<div style={{ backgroundColor: getClientColor(participant) }} className={`w-7 h-7 rounded-full flex items-center justify-center cursor-pointer`}>
31+
<span className="text-sm font-bold text-gray-900 dark:text-gray-100">
32+
{participant.userName.charAt(0)}
33+
</span>
34+
</div>
35+
</TooltipTrigger>
36+
<TooltipContent>
37+
{participant.userName}
38+
</TooltipContent>
39+
</Tooltip>
40+
))}
41+
</div>
42+
</TooltipProvider>
43+
</div>
44+
</div>
2145
<Button type="button" onClick={() => setIsOpen(true)}
2246
className={cn("excalidraw-button collab-button relative w-auto py-3 px-4 rounded-md text-[.875rem] font-semibold shadow-none active:scale-[.98]", roomSlug ? "bg-[#0fb884] dark:bg-[#0fb884] hover:bg-[#0fb884]" : "bg-color-primary hover:bg-brand-hover active:bg-brand-active")}
23-
title="Live collaboration...">Share {roomSlug && participantsCount && participantsCount > 0 && (
24-
<div className="CollabButton-collaborators text-[.6rem] text-[#2b8a3e] bg-[#b2f2bb] font-bold font-assistant rounded-[50%] p-1 min-w-4 min-h-4 w-4 h-4 flex items-center justify-center absolute bottom-[-5px] right-[-5px]">{participantsCount}</div>
47+
title="Live collaboration...">Share {roomSlug && participants && participants.length > 0 && (
48+
<div className="CollabButton-collaborators text-[.6rem] text-[#2b8a3e] bg-[#b2f2bb] font-bold font-assistant rounded-[50%] p-1 min-w-4 min-h-4 w-4 h-4 flex items-center justify-center absolute bottom-[-5px] right-[-5px]">{participants.length}</div>
2549
)}</Button>
2650

2751
{session?.user && session?.user.id ? (
@@ -35,4 +59,26 @@ export default function CollaborationStartBtn({ slug, participantsCount }: { slu
3559
)}
3660
</div>
3761
)
38-
}
62+
}
63+
64+
function hashToInteger(id: string) {
65+
let hash = 0;
66+
if (!id) return hash;
67+
68+
for (let i = 0; i < id.length; i++) {
69+
const char = id.charCodeAt(i);
70+
hash = (hash << 5) - hash + char;
71+
}
72+
return hash;
73+
}
74+
75+
export const getClientColor = (collaborator: { userId: string; userName: string; }) => {
76+
if (!collaborator?.userId) return "hsl(0, 0%, 83%)";
77+
78+
const hash = Math.abs(hashToInteger(collaborator?.userId));
79+
const hue = (hash % 36) * 10;
80+
const saturation = 90;
81+
const lightness = 75;
82+
83+
return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
84+
};

apps/collabydraw/components/auth/signup-form.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ export function SignUpForm() {
3838
return
3939
}
4040

41+
console.log('signUp Result = ', signUpResult);
42+
4143
const signInResult = await signIn("credentials", {
4244
email: values.email,
4345
password: values.password,
@@ -48,7 +50,7 @@ export function SignUpForm() {
4850
toast.error(signInResult.error);
4951
return;
5052
}
51-
53+
console.log('signIn Result = ', signInResult);
5254
toast.success("Account created successfully")
5355
router.push("/");
5456
} catch (error) {

apps/collabydraw/components/canvas/CanvasSheet.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,7 @@ export function CanvasSheet({ roomName, roomId, userId, userName }: { roomName:
307307
onToolSelect={setActiveTool}
308308
/>
309309
{matches && (
310-
<CollaborationStart participantsCount={participants.length} slug={roomName} />
310+
<CollaborationStart participants={participants} slug={roomName} />
311311
)}
312312
</div>
313313

apps/collabydraw/hooks/useWebSocket.tsx

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
import { useCallback, useEffect, useRef, useState } from 'react';
44
import { RoomParticipants, WS_DATA_TYPE, WebSocketChatMessage, WebSocketMessage } from '@repo/common/types';
5+
import { useSession } from 'next-auth/react';
6+
7+
const WS_URL = process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:8080';
8+
const MAX_RECONNECT_ATTEMPTS = 5;
59

610
export function useWebSocket(roomId: string, roomName: string, userId: string, userName: string) {
711
const [isConnected, setIsConnected] = useState(false);
@@ -10,23 +14,31 @@ export function useWebSocket(roomId: string, roomName: string, userId: string, u
1014
const socketRef = useRef<WebSocket | null>(null);
1115
const reconnectTimeoutRef = useRef<NodeJS.Timeout>();
1216
const reconnectAttemptsRef = useRef(0);
13-
const MAX_RECONNECT_ATTEMPTS = 5;
1417
const paramsRef = useRef({ roomId, roomName, userId, userName });
18+
const { data: session, status } = useSession();
1519

1620
useEffect(() => {
1721
paramsRef.current = { roomId, roomName, userId, userName };
1822
}, [roomId, roomName, userId, userName]);
1923

2024
const connectWebSocket = useCallback(() => {
21-
if (socketRef.current?.readyState === WebSocket.OPEN) {
25+
if (status === "loading") {
2226
return;
2327
}
2428
if (socketRef.current?.readyState === WebSocket.OPEN) {
29+
return;
30+
}
31+
if (socketRef.current?.readyState === WebSocket.CONNECTING) {
2532
socketRef.current.close();
2633
}
2734

2835
try {
29-
const ws = new WebSocket(`ws://localhost:8080`);
36+
let wsUrl = WS_URL;
37+
if (status === "authenticated" && session?.accessToken) {
38+
wsUrl = `${WS_URL}?token=${encodeURIComponent(session.accessToken)}`;
39+
}
40+
41+
const ws = new WebSocket(wsUrl);
3042

3143
const handleOpen = () => {
3244
setIsConnected(true);
@@ -120,9 +132,12 @@ export function useWebSocket(roomId: string, roomName: string, userId: string, u
120132
} catch (error) {
121133
console.error('Failed to create WebSocket connection:', error);
122134
}
123-
}, []);
135+
}, [session, status]);
124136

125137
useEffect(() => {
138+
if (status !== "loading") {
139+
connectWebSocket();
140+
}
126141
connectWebSocket();
127142

128143
return () => {
@@ -138,7 +153,7 @@ export function useWebSocket(roomId: string, roomName: string, userId: string, u
138153
socketRef.current.close(1000, 'Component unmounted');
139154
}
140155
};
141-
}, [connectWebSocket]);
156+
}, [connectWebSocket, status]);
142157

143158
const sendMessage = useCallback((content: string) => {
144159
if (!content?.trim()) {

apps/collabydraw/utils/auth.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ export const authOptions: NextAuthOptions = {
6262
token.accessToken = jwt.sign(
6363
{ id: token.id, email: token.email },
6464
process.env.NEXTAUTH_SECRET || "",
65-
{ expiresIn: "3d" }
65+
{ expiresIn: "7d" }
6666
);
6767
return token;
6868
},

0 commit comments

Comments
 (0)