Merge branch 'ycshin-node' of https://g.wace.me/jskim/vexplor_dev into jskim-node
This commit is contained in:
@@ -0,0 +1,257 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { apiClient, API_BASE_URL } from "@/lib/api/client";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
|
||||
// ============================================
|
||||
// Types
|
||||
// ============================================
|
||||
export interface Room {
|
||||
id: string;
|
||||
name: string;
|
||||
type: "dm" | "group" | "channel";
|
||||
lastMessage?: string;
|
||||
lastMessageAt?: string;
|
||||
unreadCount: number;
|
||||
participants: Participant[];
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface Participant {
|
||||
userId: string;
|
||||
userName: string;
|
||||
photo?: string | null;
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: string;
|
||||
roomId: string;
|
||||
senderId: string;
|
||||
senderName: string;
|
||||
senderPhoto?: string | null;
|
||||
content: string;
|
||||
type: "text" | "file" | "system";
|
||||
fileUrl?: string;
|
||||
fileName?: string;
|
||||
fileMimeType?: string | null;
|
||||
reactions: Reaction[];
|
||||
threadCount?: number;
|
||||
parentId?: string | null;
|
||||
isDeleted: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface Reaction {
|
||||
emoji: string;
|
||||
users: { userId: string; userName: string }[];
|
||||
}
|
||||
|
||||
export interface CompanyUser {
|
||||
userId: string;
|
||||
userName: string;
|
||||
deptName?: string;
|
||||
positionName?: string;
|
||||
photo?: string | null;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// API helpers
|
||||
// ============================================
|
||||
async function fetchApi<T>(url: string): Promise<T> {
|
||||
const res = await apiClient.get(url);
|
||||
return res.data?.data ?? res.data;
|
||||
}
|
||||
|
||||
async function postApi<T>(url: string, data?: unknown): Promise<T> {
|
||||
const res = await apiClient.post(url, data);
|
||||
return res.data?.data ?? res.data;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Hooks
|
||||
// ============================================
|
||||
export function useRooms() {
|
||||
const { user } = useAuth();
|
||||
const companyCode = user?.companyCode || user?.company_code;
|
||||
return useQuery<Room[]>({
|
||||
queryKey: ["messenger", "rooms", companyCode],
|
||||
queryFn: async () => {
|
||||
const data = await fetchApi<any[]>("/messenger/rooms");
|
||||
return data.map((r) => ({
|
||||
id: String(r.id),
|
||||
name: r.room_name ?? r.name ?? "",
|
||||
type: r.room_type ?? r.type,
|
||||
lastMessage: r.last_message ?? r.lastMessage,
|
||||
lastMessageAt: r.last_message_at ?? r.lastMessageAt,
|
||||
unreadCount: r.unread_count ?? r.unreadCount ?? 0,
|
||||
description: r.description,
|
||||
participants: (r.participants ?? []).map((p: any) => ({
|
||||
userId: p.user_id ?? p.userId,
|
||||
userName: p.user_name ?? p.userName,
|
||||
photo: p.photo ? `data:image/jpeg;base64,${p.photo}` : null,
|
||||
})),
|
||||
}));
|
||||
},
|
||||
refetchInterval: 30000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useMessages(roomId: string | null) {
|
||||
return useQuery<Message[]>({
|
||||
queryKey: ["messenger", "messages", roomId],
|
||||
queryFn: async () => {
|
||||
const data = await fetchApi<any[]>(`/messenger/rooms/${roomId}/messages`);
|
||||
return data.map((m) => ({
|
||||
id: String(m.id),
|
||||
roomId: String(m.room_id ?? m.roomId),
|
||||
senderId: m.sender_id ?? m.senderId,
|
||||
senderName: m.sender_name ?? m.senderName ?? m.sender_id,
|
||||
senderPhoto: m.sender_photo
|
||||
? `data:image/jpeg;base64,${m.sender_photo}`
|
||||
: (m.senderPhoto ?? null),
|
||||
content: m.content ?? "",
|
||||
type: m.message_type ?? m.type ?? "text",
|
||||
fileUrl: m.files?.[0]?.id
|
||||
? `${API_BASE_URL}/messenger/files/${m.files[0].id}`
|
||||
: (m.file_url ?? m.fileUrl),
|
||||
fileName: m.files?.[0]?.original_name ?? m.file_name ?? m.fileName,
|
||||
fileMimeType: m.files?.[0]?.mime_type ?? null,
|
||||
reactions: m.reactions ?? [],
|
||||
threadCount: m.thread_count ?? m.threadCount ?? 0,
|
||||
parentId: m.parent_message_id ?? m.parentId ?? null,
|
||||
isDeleted: m.is_deleted ?? m.isDeleted ?? false,
|
||||
createdAt: m.created_at ?? m.createdAt,
|
||||
}));
|
||||
},
|
||||
enabled: !!roomId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCompanyUsers() {
|
||||
const { user } = useAuth();
|
||||
const companyCode = user?.companyCode || user?.company_code;
|
||||
return useQuery<CompanyUser[]>({
|
||||
queryKey: ["messenger", "users", companyCode],
|
||||
queryFn: async () => {
|
||||
const data = await fetchApi<any[]>("/messenger/users");
|
||||
return data.map((u) => ({
|
||||
userId: u.user_id ?? u.userId,
|
||||
userName: u.user_name ?? u.userName,
|
||||
deptName: u.dept_name ?? u.deptName,
|
||||
photo: u.photo ? `data:image/jpeg;base64,${u.photo}` : null,
|
||||
}));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUnreadCount() {
|
||||
return useQuery<number>({
|
||||
queryKey: ["messenger", "unread"],
|
||||
queryFn: () => fetchApi("/messenger/unread"),
|
||||
refetchInterval: 15000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSendMessage() {
|
||||
const qc = useQueryClient();
|
||||
const { user } = useAuth();
|
||||
return useMutation({
|
||||
mutationFn: (payload: { roomId: string; content: string; type?: string; parentId?: string | null; fileUrl?: string; fileName?: string }) =>
|
||||
postApi(`/messenger/rooms/${payload.roomId}/messages`, {
|
||||
content: payload.content,
|
||||
type: payload.type,
|
||||
parentId: payload.parentId,
|
||||
file_url: payload.fileUrl,
|
||||
file_name: payload.fileName,
|
||||
}),
|
||||
onMutate: async (variables) => {
|
||||
const queryKey = ["messenger", "messages", variables.roomId];
|
||||
await qc.cancelQueries({ queryKey });
|
||||
const previous = qc.getQueryData<Message[]>(queryKey);
|
||||
const optimistic: Message = {
|
||||
id: `optimistic-${Date.now()}`,
|
||||
roomId: variables.roomId,
|
||||
senderId: user?.userId ?? "me",
|
||||
senderName: "",
|
||||
content: variables.content,
|
||||
type: (variables.type as Message["type"]) ?? "text",
|
||||
reactions: [],
|
||||
isDeleted: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
qc.setQueryData<Message[]>(queryKey, (old) => [...(old ?? []), optimistic]);
|
||||
return { previous, queryKey };
|
||||
},
|
||||
onError: (_err, _vars, context) => {
|
||||
if (context) qc.setQueryData(context.queryKey, context.previous);
|
||||
},
|
||||
onSuccess: (_data, variables) => {
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "messages", variables.roomId] });
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "rooms"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateRoom() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (payload: { type: "dm" | "group" | "channel"; name?: string; description?: string; participantIds: string[] }) =>
|
||||
postApi<Room>("/messenger/rooms", payload),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "rooms"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useMarkAsRead() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (roomId: string) => postApi(`/messenger/rooms/${roomId}/read`),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "unread"] });
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "rooms"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useAddReaction() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (payload: { messageId: string; roomId: string; emoji: string }) =>
|
||||
postApi(`/messenger/messages/${payload.messageId}/reactions`, { emoji: payload.emoji }),
|
||||
onSuccess: (_data, variables) => {
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "messages", variables.roomId] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateRoom() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ roomId, name }: { roomId: string; name: string }) =>
|
||||
apiClient.put(`/messenger/rooms/${roomId}`, { room_name: name }).then((res) => res.data?.data ?? res.data),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "rooms"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUploadFile() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({ file, roomId }: { file: File; roomId: string }) => {
|
||||
const formData = new FormData();
|
||||
formData.append("files", file);
|
||||
formData.append("room_id", roomId);
|
||||
const res = await apiClient.post("/messenger/files/upload", formData, {
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
});
|
||||
return res.data?.data ?? res.data;
|
||||
},
|
||||
onSuccess: (_data, variables) => {
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "messages", variables.roomId] });
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "rooms"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useCallback, useState } from "react";
|
||||
import { io, Socket } from "socket.io-client";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useMessengerContext } from "@/contexts/MessengerContext";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL || "http://localhost:8080";
|
||||
|
||||
export type UserStatus = "online" | "away" | "offline";
|
||||
|
||||
interface NewMessageEvent {
|
||||
room_id: number;
|
||||
sender_name: string;
|
||||
sender_id: string;
|
||||
sender_photo?: string | null;
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface TypingEvent {
|
||||
room_id: number;
|
||||
user_id: string;
|
||||
user_name: string;
|
||||
}
|
||||
|
||||
export function useMessengerSocket() {
|
||||
const socketRef = useRef<Socket | null>(null);
|
||||
const { selectedRoomId, notificationEnabled, isOpen, openMessenger, mutedRooms } = useMessengerContext();
|
||||
const currentUserIdRef = useRef<string | null>(null);
|
||||
const selectedRoomIdRef = useRef(selectedRoomId);
|
||||
const notificationEnabledRef = useRef(notificationEnabled);
|
||||
const isOpenRef = useRef(isOpen);
|
||||
const mutedRoomsRef = useRef(mutedRooms);
|
||||
|
||||
const qc = useQueryClient();
|
||||
const [userStatuses, setUserStatuses] = useState<Map<string, UserStatus>>(new Map());
|
||||
const [typingUsers, setTypingUsers] = useState<Map<string, string[]>>(new Map());
|
||||
|
||||
// Keep refs in sync so socket handlers use latest values
|
||||
useEffect(() => {
|
||||
selectedRoomIdRef.current = selectedRoomId;
|
||||
}, [selectedRoomId]);
|
||||
|
||||
useEffect(() => {
|
||||
notificationEnabledRef.current = notificationEnabled;
|
||||
}, [notificationEnabled]);
|
||||
|
||||
useEffect(() => {
|
||||
isOpenRef.current = isOpen;
|
||||
}, [isOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
mutedRoomsRef.current = mutedRooms;
|
||||
}, [mutedRooms]);
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem("authToken");
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split(".")[1]));
|
||||
currentUserIdRef.current = payload.userId ?? payload.user_id ?? null;
|
||||
} catch {}
|
||||
|
||||
const socket = io(BACKEND_URL, {
|
||||
path: "/socket.io",
|
||||
auth: { token },
|
||||
transports: ["websocket", "polling"],
|
||||
});
|
||||
|
||||
socketRef.current = socket;
|
||||
|
||||
socket.on("connect", () => {
|
||||
socket.emit("join_rooms");
|
||||
});
|
||||
|
||||
// Receive full presence list on connect
|
||||
socket.on("presence_list", (data: Record<string, string>) => {
|
||||
setUserStatuses((prev) => {
|
||||
const next = new Map(prev);
|
||||
for (const [uid, status] of Object.entries(data)) {
|
||||
next.set(uid, status as UserStatus);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
});
|
||||
|
||||
// Receive individual status updates
|
||||
socket.on("user_status", (data: { userId: string; status: UserStatus }) => {
|
||||
setUserStatuses((prev) => {
|
||||
const next = new Map(prev);
|
||||
if (data.status === "offline") {
|
||||
next.delete(data.userId);
|
||||
} else {
|
||||
next.set(data.userId, data.status);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
});
|
||||
|
||||
// Tab visibility → away/online
|
||||
const handleVisibilityChange = () => {
|
||||
const status = document.hidden ? "away" : "online";
|
||||
socket.emit("set_status", { status });
|
||||
};
|
||||
document.addEventListener("visibilitychange", handleVisibilityChange);
|
||||
|
||||
// BUG-5 & BUG-8: Handle new_message with cache invalidation and toast
|
||||
socket.on("new_message", (data: NewMessageEvent) => {
|
||||
const roomIdStr = String(data.room_id);
|
||||
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "messages", roomIdStr] });
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "rooms"] });
|
||||
qc.invalidateQueries({ queryKey: ["messenger", "unread"] });
|
||||
|
||||
const isOwnMessage = data.sender_id === currentUserIdRef.current;
|
||||
const isRoomMuted = mutedRoomsRef.current.has(roomIdStr);
|
||||
if (notificationEnabledRef.current && !isOwnMessage && !isRoomMuted && (!isOpenRef.current || roomIdStr !== selectedRoomIdRef.current)) {
|
||||
const photoSrc = data.sender_photo
|
||||
? `data:image/jpeg;base64,${data.sender_photo}`
|
||||
: null;
|
||||
toast(
|
||||
<div className="flex items-center gap-2 cursor-pointer" onClick={() => openMessenger(roomIdStr)}>
|
||||
{photoSrc ? (
|
||||
<img src={photoSrc} alt="" className="w-6 h-6 rounded-full object-cover shrink-0" />
|
||||
) : (
|
||||
<div className="w-6 h-6 rounded-full bg-muted flex items-center justify-center text-xs font-medium shrink-0">
|
||||
{(data.sender_name || "?").charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium text-sm">{data.sender_name || "새 메시지"}</div>
|
||||
<div className="text-xs text-muted-foreground truncate">{data.content?.slice(0, 60) || ""}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// BUG-7: Backend emits "user_typing" / "user_stop_typing"
|
||||
socket.on("user_typing", (data: TypingEvent) => {
|
||||
const roomIdStr = String(data.room_id);
|
||||
setTypingUsers((prev) => {
|
||||
const next = new Map(prev);
|
||||
const users = next.get(roomIdStr) || [];
|
||||
if (!users.includes(data.user_name)) {
|
||||
next.set(roomIdStr, [...users, data.user_name]);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
});
|
||||
|
||||
socket.on("user_stop_typing", (data: TypingEvent) => {
|
||||
const roomIdStr = String(data.room_id);
|
||||
setTypingUsers((prev) => {
|
||||
const next = new Map(prev);
|
||||
const users = next.get(roomIdStr) || [];
|
||||
next.set(roomIdStr, users.filter((u) => u !== data.user_name));
|
||||
return next;
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
||||
socket.disconnect();
|
||||
socketRef.current = null;
|
||||
};
|
||||
}, [toast, qc]);
|
||||
|
||||
const emitTypingStart = useCallback(
|
||||
(roomId: string) => {
|
||||
socketRef.current?.emit("typing_start", { room_id: Number(roomId) });
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const emitTypingStop = useCallback(
|
||||
(roomId: string) => {
|
||||
socketRef.current?.emit("typing_stop", { room_id: Number(roomId) });
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return { socket: socketRef, userStatuses, typingUsers, emitTypingStart, emitTypingStop };
|
||||
}
|
||||
Reference in New Issue
Block a user