diff --git a/backend/dist/controllers/chatControllers.js b/backend/dist/controllers/chatControllers.js index efd57d6..c2d8ab1 100644 --- a/backend/dist/controllers/chatControllers.js +++ b/backend/dist/controllers/chatControllers.js @@ -15,6 +15,11 @@ const prisma = new client_1.PrismaClient(); const getChatHistory = (req, res) => __awaiter(void 0, void 0, void 0, function* () { const { roomId } = req.params; try { + // const cacheKey = `search:${roomId}`; + // const cachedResults = await getCachedData(cacheKey); + // if (cachedResults) { + // return res.status(200).json(JSON.parse(cachedResults)); + // } const messages = yield prisma.message.findMany({ where: { chatRoomId: roomId }, include: { @@ -29,7 +34,7 @@ const getChatHistory = (req, res) => __awaiter(void 0, void 0, void 0, function* message: message.content, at: message.timestamp, })); - // Send the formatted messages as a JSON response + // await setCachedData(cacheKey, JSON.stringify(messageFormat), 3600); res.json(messageFormat); } catch (error) { diff --git a/backend/dist/server.js b/backend/dist/server.js index 133768c..2af875c 100644 --- a/backend/dist/server.js +++ b/backend/dist/server.js @@ -31,23 +31,27 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", { value: true }); const ws_1 = __importStar(require("ws")); const client_1 = require("@prisma/client"); +const sendMail_1 = __importDefault(require("./mail/sendMail")); const prisma = new client_1.PrismaClient(); const wss = new ws_1.Server({ port: 8080 }); let clientCount = 0; -// Map to track which rooms each client is in const clientRoomMap = new Map(); // WebSocket -> Set of room IDs wss.on('connection', (ws) => { const clientId = ++clientCount; // Increment and get the client ID console.log(`Client${clientId} connected`); - // Initialize client-room mapping + const user = []; clientRoomMap.set(ws, new Set()); ws.on('message', (message) => __awaiter(void 0, void 0, void 0, function* () { var _a; const { type, data } = JSON.parse(message.toString()); // data will contain roomId, userId, targetUserId, and message // type will contain 'createRoom', 'joinRoom', 'sendMessage' + const roomId = data.roomId; switch (type) { case 'createRoom': try { @@ -98,6 +102,18 @@ wss.on('connection', (ws) => { break; case 'sendMessage': try { + const chatRoom = yield prisma.chatRoom.findUnique({ + where: { id: roomId }, + include: { + users: { + select: { user_id: true, username: true, email: true } // Ensure to fetch email + } + } + }); + if (!chatRoom) { + ws.send(JSON.stringify({ type: 'error', data: { message: 'Chat room not found' } })); + return; + } const newMessage = yield prisma.message.create({ data: { content: data.message, @@ -107,11 +123,67 @@ wss.on('connection', (ws) => { }); // Broadcast the message to all clients in the room wss.clients.forEach(client => { - if (client.readyState === ws_1.default.OPEN) { - const rooms = clientRoomMap.get(client); - if (rooms === null || rooms === void 0 ? void 0 : rooms.has(data.roomId)) { - client.send(JSON.stringify({ type: 'newMessage', data: { roomId: data.roomId, message: newMessage } })); - } + const rooms = clientRoomMap.get(client); + if (client.readyState === ws_1.default.OPEN && (rooms === null || rooms === void 0 ? void 0 : rooms.has(data.roomId))) { + client.send(JSON.stringify({ type: 'newMessage', data: { roomId: data.roomId, message: newMessage } })); + } + }); + // Send email to disconnected users + chatRoom.users.forEach(user => { + const isUserConnected = [...wss.clients].some(client => { var _a; return ((_a = clientRoomMap.get(client)) === null || _a === void 0 ? void 0 : _a.has(data.roomId)) && client.readyState === ws_1.default.OPEN && user.user_id === data.userId; }); + // Send email only to disconnected users and exclude the sender + if (!isUserConnected && user.user_id !== data.userId) { + const htmlContent = ` + + + + + +
+

New Message in Chat Room ${data.roomId}

+

You've received a new message in chat room ${data.roomId}.

+

Click the link below and enter the room id to view the message:

+

Join Room

+ +
+ + + `; + console.log('Sending email to', user.email); + (0, sendMail_1.default)(htmlContent, user.email, "Message notification"); } }); } diff --git a/backend/src/controllers/chatControllers.ts b/backend/src/controllers/chatControllers.ts index 35046e8..1d4d0cf 100644 --- a/backend/src/controllers/chatControllers.ts +++ b/backend/src/controllers/chatControllers.ts @@ -9,11 +9,11 @@ export const getChatHistory = async (req: Request, res: Response) => { const { roomId } = req.params; try { - const cacheKey = `search:${roomId}`; - const cachedResults = await getCachedData(cacheKey); - if (cachedResults) { - return res.status(200).json(JSON.parse(cachedResults)); - } + // const cacheKey = `search:${roomId}`; + // const cachedResults = await getCachedData(cacheKey); + // if (cachedResults) { + // return res.status(200).json(JSON.parse(cachedResults)); + // } const messages = await prisma.message.findMany({ where: { chatRoomId: roomId }, include: { @@ -28,7 +28,7 @@ export const getChatHistory = async (req: Request, res: Response) => { message: message.content, at: message.timestamp, })); - await setCachedData(cacheKey, JSON.stringify(messageFormat), 3600); + // await setCachedData(cacheKey, JSON.stringify(messageFormat), 3600); res.json(messageFormat); } catch (error) { diff --git a/backend/src/server.ts b/backend/src/server.ts index 19adcb6..ba1a751 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -72,102 +72,104 @@ wss.on('connection', (ws) => { } break; - case 'sendMessage': - try { - const chatRoom = await prisma.chatRoom.findUnique({ - where: { id: roomId }, - include: { - users: { - select: { user_id: true, username: true, email: true } // Ensure to fetch email + case 'sendMessage': + try { + const chatRoom = await prisma.chatRoom.findUnique({ + where: { id: roomId }, + include: { + users: { + select: { user_id: true, username: true, email: true } // Ensure to fetch email + } } + }); + + if (!chatRoom) { + ws.send(JSON.stringify({ type: 'error', data: { message: 'Chat room not found' } })); + return; } - }); - - if (!chatRoom) { - ws.send(JSON.stringify({ type: 'error', data: { message: 'Chat room not found' } })); - return; - } - - const newMessage = await prisma.message.create({ - data: { - content: data.message, - sender: { connect: { user_id: data.userId } }, - chatRoom: { connect: { id: data.roomId } }, - } - }); - - // Broadcast the message to all clients in the room - wss.clients.forEach(client => { - if (client.readyState === WebSocket.OPEN) { + + const newMessage = await prisma.message.create({ + data: { + content: data.message, + sender: { connect: { user_id: data.userId } }, + chatRoom: { connect: { id: data.roomId } }, + } + }); + + // Broadcast the message to all clients in the room + wss.clients.forEach(client => { const rooms = clientRoomMap.get(client); - if (rooms?.has(data.roomId)) { + if (client.readyState === WebSocket.OPEN && rooms?.has(data.roomId)) { client.send(JSON.stringify({ type: 'newMessage', data: { roomId: data.roomId, message: newMessage } })); } - } else { - // Handle sending email to disconnected users - chatRoom.users.forEach(user => { - // Check if user is disconnected - const isUserConnected = [...wss.clients].some(c => clientRoomMap.get(c)?.has(data.roomId) && c.readyState === WebSocket.OPEN); - - if (!isUserConnected && user.user_id !== data.userId) { - const htmlContent = ` - - - - - -
-

New Message in Chat Room ${data.roomId}

-

You've received a new message in chat room ${data.roomId}.

-

Click the link below and enter the room id to view the message:

-

Join Room

- -
- - - `; - sendMail(htmlContent, user.email, "Message notification"); - } - }); - } - }); - } catch (error) { - ws.send(JSON.stringify({ type: 'error', data: { message: 'Failed to send message' } })); - } - break; + }); + + chatRoom.users.forEach(user => { + const isUserConnected = [...wss.clients].some( + client => clientRoomMap.get(client)?.has(data.roomId) && client.readyState === WebSocket.OPEN && user.user_id === data.userId + ); + + console.log('User connected:', isUserConnected); + if (!isUserConnected && user.user_id !== data.userId) { + const htmlContent = ` + + + + + +
+

New Message in Chat Room ${data.roomId}

+

You've received a new message in chat room ${data.roomId}.

+

Click the link below and enter the room id to view the message:

+

Join Room

+ +
+ + + `; + + console.log('Sending email to', user.email); + sendMail(htmlContent, user.email, "Message notification"); + } + }); + } catch (error) { + ws.send(JSON.stringify({ type: 'error', data: { message: 'Failed to send message' } })); + } + break; + default: ws.send(JSON.stringify({ type: 'error', data: { message: 'Invalid message type' } })); diff --git a/backend/tsconfig.tsbuildinfo b/backend/tsconfig.tsbuildinfo index a640289..180b20e 100644 --- a/backend/tsconfig.tsbuildinfo +++ b/backend/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/index.ts","./src/seed.ts","./src/server.ts","./src/controllers/chatcontrollers.ts","./src/controllers/postcontroller.ts","./src/controllers/ratingcontroller.ts","./src/controllers/reviewcontrollers.ts","./src/controllers/routecontrollers.ts","./src/controllers/usercontrollers.ts","./src/lib/convertor.ts","./src/lib/prisma.ts","./src/mail/checkacademic.ts","./src/mail/sendmail.ts","./src/mail/sort.ts","./src/middleware/checkauth.ts","./src/middleware/moderation.ts","./src/routes/chatroutes.ts","./src/routes/mruote.ts","./src/routes/postsroutes.ts","./src/routes/ratingroute.ts","./src/routes/reviewroutes.ts","./src/routes/roomroutes.ts","./src/routes/userroutes.ts","./src/validation/registerschema.ts"],"version":"5.6.3"} \ No newline at end of file +{"root":["./src/index.ts","./src/seed.ts","./src/server.ts","./src/controllers/chatcontrollers.ts","./src/controllers/otpcontroller.ts","./src/controllers/postcontroller.ts","./src/controllers/ratingcontroller.ts","./src/controllers/reviewcontrollers.ts","./src/controllers/routecontrollers.ts","./src/controllers/usercontrollers.ts","./src/lib/convertor.ts","./src/lib/prisma.ts","./src/lib/redis.ts","./src/mail/checkacademic.ts","./src/mail/sendmail.ts","./src/mail/sort.ts","./src/middleware/checkauth.ts","./src/middleware/moderation.ts","./src/routes/chatroutes.ts","./src/routes/mruote.ts","./src/routes/otproute.ts","./src/routes/postsroutes.ts","./src/routes/ratingroute.ts","./src/routes/reviewroutes.ts","./src/routes/roomroutes.ts","./src/routes/userroutes.ts","./src/validation/registerschema.ts"],"version":"5.6.3"} \ No newline at end of file