Skip to content

Commit

Permalink
Merge pull request #130 from Somnath-Chattaraj/message
Browse files Browse the repository at this point in the history
Message
  • Loading branch information
Somnath-Chattaraj authored Oct 23, 2024
2 parents ee9205b + b9977f6 commit add1f48
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 4 deletions.
4 changes: 2 additions & 2 deletions backend/src/controllers/chatControllers.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';


const prisma = new PrismaClient();


export const getChatHistory = async (req: Request, res: Response) => {
const { roomId } = req.params;

try {

const messages = await prisma.message.findMany({
where: { chatRoomId: roomId },
include: {
Expand All @@ -22,8 +24,6 @@ export const getChatHistory = async (req: Request, res: Response) => {
message: message.content,
at: message.timestamp,
}));

// Send the formatted messages as a JSON response
res.json(messageFormat);

} catch (error) {
Expand Down
79 changes: 77 additions & 2 deletions backend/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import WebSocket, { Server } from 'ws';
import { PrismaClient } from '@prisma/client';
import sendMail from './mail/sendMail';

const prisma = new PrismaClient();
const wss = new Server({ port: 8080 });
let clientCount = 0;

// Map to track which rooms each client is in
const clientRoomMap = new Map<WebSocket, Set<number>>(); // WebSocket -> Set of room IDs

wss.on('connection', (ws) => {
const clientId = ++clientCount; // Increment and get the client ID
console.log(`Client${clientId} connected`);
const user = [];

// Initialize client-room mapping
clientRoomMap.set(ws, new Set());

ws.on('message', async (message) => {
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':
Expand Down Expand Up @@ -72,6 +74,20 @@ wss.on('connection', (ws) => {

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;
}

const newMessage = await prisma.message.create({
data: {
content: data.message,
Expand All @@ -87,6 +103,65 @@ wss.on('connection', (ws) => {
if (rooms?.has(data.roomId)) {
client.send(JSON.stringify({ type: 'newMessage', data: { roomId: data.roomId, message: newMessage } }));
}
} else {

chatRoom.users.forEach(user => {

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 = `
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
.container {
max-width: 600px;
margin: auto;
background: #ffffff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
}
h1 {
color: #333;
}
p {
font-size: 16px;
line-height: 1.5;
color: #555;
}
a {
color: #007BFF;
text-decoration: none;
font-weight: bold;
}
.footer {
margin-top: 20px;
font-size: 12px;
color: #888;
}
</style>
</head>
<body>
<div class="container">
<h1>New Message in Chat Room ${data.roomId}</h1>
<p>You've received a new message in chat room <strong>${data.roomId}</strong>.</p>
<p>Click the link below and enter the room id to view the message:</p>
<p><a href="https://www.campusify.site/room/joinroom">Join Room</a></p>
<p class="footer">Thank you for using our service!</p>
</div>
</body>
</html>
`;
sendMail(htmlContent, user.email, "Message notification");
}
});
}
});
} catch (error) {
Expand Down

0 comments on commit add1f48

Please sign in to comment.