Update environment configurations for client and server, refactor ChatPopup to accept sessionId as a prop, enhance chat message handling with senderName and guestId, and improve error logging in chat message processing. Adjust useChatHistory and useWebRTC hooks for better state management and message retrieval.
This commit is contained in:
+2
-2
@@ -1,4 +1,4 @@
|
||||
DATABASE_URL=postgres://postgres:v1sq3vD5faXL@194.26.138.94:5432/stream
|
||||
JWT_SECRET=b5cf2bd3894fb24191f13dc9dddaeecccc92d0ee298e7ee41c2d0aab51c28fa1
|
||||
PORT=6000
|
||||
SOCKET_PORT=6001
|
||||
PORT=3000
|
||||
SOCKET_PORT=3001
|
||||
@@ -1,4 +1,4 @@
|
||||
import { pgTable, uuid, text, timestamp, pgEnum } from "drizzle-orm/pg-core";
|
||||
import { pgTable, uuid, text, timestamp, pgEnum, varchar } from "drizzle-orm/pg-core";
|
||||
import { relations } from "drizzle-orm";
|
||||
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
|
||||
import { serverSessions } from "./serverSessions";
|
||||
@@ -13,6 +13,8 @@ export const chatMessages = pgTable("chat_messages", {
|
||||
.notNull()
|
||||
.references(() => serverSessions.id, { onDelete: "cascade" }),
|
||||
userId: uuid("user_id").references(() => users.id), // Nullable для системных сообщений или анонимных пользователей
|
||||
guestId: uuid("guest_id"), // ID гостя (для неавторизованных пользователей)
|
||||
senderName: varchar("sender_name", { length: 255 }).notNull(), // Имя отправителя (из БД для авторизованных, "Guest" для неавторизованных)
|
||||
content: text("content").notNull(),
|
||||
type: messageTypeEnum("type").notNull().default("text"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
|
||||
+179
-94
@@ -83,72 +83,79 @@ io.on("connection", (socket) => {
|
||||
console.log(`[WebRTC] User connected: ${socket.id}`);
|
||||
|
||||
// Присоединение к комнате
|
||||
socket.on("join-room", async ({ roomId, userId, isAudioEnabled, isVideoEnabled }) => {
|
||||
console.log(
|
||||
`[WebRTC] User ${userId} (socket: ${socket.id}) joining room ${roomId}, audio: ${isAudioEnabled}, video: ${isVideoEnabled}`
|
||||
);
|
||||
|
||||
// Покинуть предыдущую комнату если была
|
||||
const existingUser = users.get(userId);
|
||||
if (existingUser?.roomId) {
|
||||
socket.on(
|
||||
"join-room",
|
||||
async ({ roomId, userId, isAudioEnabled, isVideoEnabled }) => {
|
||||
console.log(
|
||||
`[WebRTC] User ${userId} leaving previous room ${existingUser.roomId}`
|
||||
`[WebRTC] User ${userId} (socket: ${socket.id}) joining room ${roomId}, audio: ${isAudioEnabled}, video: ${isVideoEnabled}`
|
||||
);
|
||||
socket.leave(existingUser.roomId);
|
||||
const prevRoom = rooms.get(existingUser.roomId);
|
||||
if (prevRoom) {
|
||||
prevRoom.participants.delete(userId);
|
||||
socket.to(existingUser.roomId).emit("user-left", userId);
|
||||
|
||||
// Покинуть предыдущую комнату если была
|
||||
const existingUser = users.get(userId);
|
||||
if (existingUser?.roomId) {
|
||||
console.log(
|
||||
`[WebRTC] User ${userId} leaving previous room ${existingUser.roomId}`
|
||||
);
|
||||
socket.leave(existingUser.roomId);
|
||||
const prevRoom = rooms.get(existingUser.roomId);
|
||||
if (prevRoom) {
|
||||
prevRoom.participants.delete(userId);
|
||||
socket.to(existingUser.roomId).emit("user-left", userId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Присоединиться к новой комнате
|
||||
socket.join(roomId);
|
||||
// Присоединиться к новой комнате
|
||||
socket.join(roomId);
|
||||
|
||||
// Создать комнату если не существует
|
||||
if (!rooms.has(roomId)) {
|
||||
console.log(`[WebRTC] Creating new room: ${roomId}`);
|
||||
rooms.set(roomId, {
|
||||
id: roomId,
|
||||
participants: new Set(),
|
||||
// Создать комнату если не существует
|
||||
if (!rooms.has(roomId)) {
|
||||
console.log(`[WebRTC] Creating new room: ${roomId}`);
|
||||
rooms.set(roomId, {
|
||||
id: roomId,
|
||||
participants: new Set(),
|
||||
});
|
||||
}
|
||||
|
||||
const room = rooms.get(roomId)!;
|
||||
room.participants.add(userId);
|
||||
|
||||
// Сохранить пользователя
|
||||
users.set(userId, {
|
||||
id: userId,
|
||||
roomId,
|
||||
socketId: socket.id,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`[WebRTC] Room ${roomId} now has participants:`,
|
||||
Array.from(room.participants)
|
||||
);
|
||||
|
||||
// Уведомить других участников
|
||||
socket.to(roomId).emit("user-joined", userId);
|
||||
console.log(
|
||||
`[WebRTC] Notified room ${roomId} about user ${userId} joining`
|
||||
);
|
||||
|
||||
// Отправить состояние аудио/видео нового пользователя всем в комнате
|
||||
socket
|
||||
.to(roomId)
|
||||
.emit("audio-toggle", { userId, isEnabled: isAudioEnabled !== false });
|
||||
socket
|
||||
.to(roomId)
|
||||
.emit("video-toggle", { userId, isEnabled: isVideoEnabled !== false });
|
||||
|
||||
// Отправить список участников новому пользователю
|
||||
const participants = Array.from(room.participants).filter(
|
||||
(id) => id !== userId
|
||||
);
|
||||
console.log(
|
||||
`[WebRTC] Sending participant list to ${userId}:`,
|
||||
participants
|
||||
);
|
||||
socket.emit("room-participants", participants);
|
||||
}
|
||||
|
||||
const room = rooms.get(roomId)!;
|
||||
room.participants.add(userId);
|
||||
|
||||
// Сохранить пользователя
|
||||
users.set(userId, {
|
||||
id: userId,
|
||||
roomId,
|
||||
socketId: socket.id,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`[WebRTC] Room ${roomId} now has participants:`,
|
||||
Array.from(room.participants)
|
||||
);
|
||||
|
||||
// Уведомить других участников
|
||||
socket.to(roomId).emit("user-joined", userId);
|
||||
console.log(
|
||||
`[WebRTC] Notified room ${roomId} about user ${userId} joining`
|
||||
);
|
||||
|
||||
// Отправить состояние аудио/видео нового пользователя всем в комнате
|
||||
socket.to(roomId).emit("audio-toggle", { userId, isEnabled: isAudioEnabled !== false });
|
||||
socket.to(roomId).emit("video-toggle", { userId, isEnabled: isVideoEnabled !== false });
|
||||
|
||||
// Отправить список участников новому пользователю
|
||||
const participants = Array.from(room.participants).filter(
|
||||
(id) => id !== userId
|
||||
);
|
||||
console.log(
|
||||
`[WebRTC] Sending participant list to ${userId}:`,
|
||||
participants
|
||||
);
|
||||
socket.emit("room-participants", participants);
|
||||
});
|
||||
);
|
||||
|
||||
// Покидание комнаты
|
||||
socket.on("leave-room", ({ roomId, userId }) => {
|
||||
@@ -215,13 +222,17 @@ io.on("connection", (socket) => {
|
||||
|
||||
// Обработка audio/video toggle
|
||||
socket.on("audio-toggle", ({ roomId, userId, isEnabled }) => {
|
||||
console.log(`[WebRTC] Audio toggle from ${userId} in room ${roomId}: ${isEnabled}`);
|
||||
console.log(
|
||||
`[WebRTC] Audio toggle from ${userId} in room ${roomId}: ${isEnabled}`
|
||||
);
|
||||
// Отправляем всем в комнате (кроме отправителя)
|
||||
socket.to(roomId).emit("audio-toggle", { userId, isEnabled });
|
||||
});
|
||||
|
||||
socket.on("video-toggle", ({ roomId, userId, isEnabled }) => {
|
||||
console.log(`[WebRTC] Video toggle from ${userId} in room ${roomId}: ${isEnabled}`);
|
||||
console.log(
|
||||
`[WebRTC] Video toggle from ${userId} in room ${roomId}: ${isEnabled}`
|
||||
);
|
||||
// Отправляем всем в комнате (кроме отправителя)
|
||||
socket.to(roomId).emit("video-toggle", { userId, isEnabled });
|
||||
});
|
||||
@@ -233,44 +244,118 @@ io.on("connection", (socket) => {
|
||||
});
|
||||
|
||||
// Обработка сообщений чата
|
||||
socket.on("chat-message", async ({ roomId, userId, content, userName }) => {
|
||||
console.log(`[Chat] Message from ${userId} in room ${roomId}: ${content}`);
|
||||
|
||||
const user = findUserBySocketId(socket.id);
|
||||
if (!user || user.roomId !== roomId) {
|
||||
console.warn(`[Chat] User ${socket.id} is not in room ${roomId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Сохраняем сообщение в БД
|
||||
const savedMessage = await saveChatMessage({
|
||||
sessionId: roomId,
|
||||
userId: userId || null, // null для анонимных пользователей
|
||||
socket.on(
|
||||
"chat-message",
|
||||
async ({ roomId, userId, content, senderName, guestId }) => {
|
||||
console.log(`[Chat] Received message:`, {
|
||||
roomId,
|
||||
userId,
|
||||
guestId,
|
||||
senderName,
|
||||
content,
|
||||
type: "text",
|
||||
});
|
||||
|
||||
// Формируем сообщение для отправки клиентам
|
||||
const messageToSend = {
|
||||
id: savedMessage.id,
|
||||
senderId: userId,
|
||||
senderName: userName,
|
||||
content: savedMessage.content,
|
||||
timestamp: savedMessage.createdAt,
|
||||
type: savedMessage.type,
|
||||
};
|
||||
const user = findUserBySocketId(socket.id);
|
||||
if (!user || user.roomId !== roomId) {
|
||||
console.warn(`[Chat] User ${socket.id} is not in room ${roomId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Отправляем всем в комнате (включая отправителя)
|
||||
io.to(roomId).emit("chat-message", messageToSend);
|
||||
console.log(`[Chat] Message broadcasted to room ${roomId}`);
|
||||
} catch (error) {
|
||||
console.error(`[Chat] Error saving message:`, error);
|
||||
socket.emit("chat-error", {
|
||||
message: "Failed to save message",
|
||||
});
|
||||
try {
|
||||
// Определяем имя отправителя
|
||||
const finalSenderName = senderName || "Guest";
|
||||
|
||||
console.log(
|
||||
`[Chat] Preparing to save message with senderName: "${finalSenderName}"`
|
||||
);
|
||||
|
||||
// Валидация UUID
|
||||
const uuidRegex =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
if (!uuidRegex.test(roomId)) {
|
||||
console.error(`[Chat] Invalid roomId/sessionId format: ${roomId}`);
|
||||
throw new Error("Invalid sessionId format");
|
||||
}
|
||||
|
||||
if (userId && !uuidRegex.test(userId)) {
|
||||
console.error(`[Chat] Invalid userId format: ${userId}`);
|
||||
throw new Error("Invalid userId format");
|
||||
}
|
||||
|
||||
if (guestId && !uuidRegex.test(guestId)) {
|
||||
console.error(`[Chat] Invalid guestId format: ${guestId}`);
|
||||
throw new Error("Invalid guestId format");
|
||||
}
|
||||
|
||||
// Проверяем существование сессии
|
||||
console.log(`[Chat] Checking if session exists: ${roomId}`);
|
||||
try {
|
||||
const sessionExists = await serverSessionService.findById(roomId);
|
||||
if (!sessionExists) {
|
||||
console.error(`[Chat] Session not found in database: ${roomId}`);
|
||||
console.error(
|
||||
`[Chat] This might cause foreign key constraint error`
|
||||
);
|
||||
// Не возвращаемся - попробуем сохранить и увидим точную ошибку БД
|
||||
} else {
|
||||
console.log(`[Chat] Session found:`, sessionExists.id);
|
||||
}
|
||||
} catch (sessionCheckError) {
|
||||
console.error(`[Chat] Error checking session:`, sessionCheckError);
|
||||
// Продолжаем - увидим точную ошибку при сохранении
|
||||
}
|
||||
|
||||
// Сохраняем сообщение в БД
|
||||
const messageData = {
|
||||
sessionId: roomId,
|
||||
userId: userId || null, // null для анонимных пользователей
|
||||
guestId: guestId || null, // ID гостя для неавторизованных
|
||||
senderName: finalSenderName, // Имя отправителя
|
||||
content,
|
||||
type: "text" as const,
|
||||
};
|
||||
|
||||
console.log(
|
||||
`[Chat] Saving message to DB:`,
|
||||
JSON.stringify(messageData, null, 2)
|
||||
);
|
||||
const savedMessage = await saveChatMessage(messageData);
|
||||
console.log(`[Chat] Message saved successfully:`, savedMessage);
|
||||
|
||||
// Формируем сообщение для отправки клиентам
|
||||
const messageToSend = {
|
||||
id: savedMessage.id,
|
||||
senderId: userId || guestId,
|
||||
senderName: savedMessage.senderName,
|
||||
content: savedMessage.content,
|
||||
timestamp: savedMessage.createdAt,
|
||||
type: savedMessage.type,
|
||||
};
|
||||
|
||||
// Отправляем всем в комнате (включая отправителя)
|
||||
io.to(roomId).emit("chat-message", messageToSend);
|
||||
console.log(`[Chat] Message broadcasted to room ${roomId}`);
|
||||
} catch (error) {
|
||||
console.error(`[Chat] Error saving message:`, error);
|
||||
console.error(`[Chat] Error details:`, JSON.stringify(error, null, 2));
|
||||
|
||||
// Отправляем детальную ошибку на клиент
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Failed to save message";
|
||||
const errorDetails =
|
||||
error && typeof error === "object"
|
||||
? (error as any).detail || (error as any).message || errorMessage
|
||||
: errorMessage;
|
||||
|
||||
console.error(`[Chat] Sending error to client:`, errorDetails);
|
||||
|
||||
socket.emit("chat-error", {
|
||||
message: errorDetails,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
// Отключение
|
||||
socket.on("disconnect", () => {
|
||||
|
||||
@@ -3,17 +3,24 @@ import {
|
||||
chatMessages,
|
||||
type NewChatMessage,
|
||||
} from "../../db/schema/chatMessages";
|
||||
import { eq, desc } from "drizzle-orm";
|
||||
import { eq, desc, sql } from "drizzle-orm";
|
||||
|
||||
/**
|
||||
* Сохранить новое сообщение в чате
|
||||
*/
|
||||
export async function saveChatMessage(message: NewChatMessage) {
|
||||
const [newMessage] = await db
|
||||
.insert(chatMessages)
|
||||
.values(message)
|
||||
.returning();
|
||||
return newMessage;
|
||||
try {
|
||||
console.log("[saveChatMessage] Attempting to insert message:", message);
|
||||
const [newMessage] = await db
|
||||
.insert(chatMessages)
|
||||
.values(message)
|
||||
.returning();
|
||||
console.log("[saveChatMessage] Message inserted successfully:", newMessage);
|
||||
return newMessage;
|
||||
} catch (error) {
|
||||
console.error("[saveChatMessage] Database error:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,7 +30,15 @@ export async function saveChatMessage(message: NewChatMessage) {
|
||||
*/
|
||||
export async function getChatHistory(sessionId: string, limit = 100) {
|
||||
const messages = await db
|
||||
.select()
|
||||
.select({
|
||||
id: chatMessages.id,
|
||||
// senderId - это либо userId (для авторизованных), либо guestId (для гостей)
|
||||
senderId: sql<string>`COALESCE(${chatMessages.userId}, ${chatMessages.guestId})`.as('senderId'),
|
||||
senderName: chatMessages.senderName,
|
||||
content: chatMessages.content,
|
||||
timestamp: chatMessages.createdAt,
|
||||
type: chatMessages.type,
|
||||
})
|
||||
.from(chatMessages)
|
||||
.where(eq(chatMessages.sessionId, sessionId))
|
||||
.orderBy(desc(chatMessages.createdAt))
|
||||
|
||||
Reference in New Issue
Block a user