Skip to content

Commit

Permalink
Fix email
Browse files Browse the repository at this point in the history
  • Loading branch information
Somnath-Chattaraj committed Oct 23, 2024
1 parent 8c059ec commit 13f02c5
Show file tree
Hide file tree
Showing 5 changed files with 185 additions and 106 deletions.
7 changes: 6 additions & 1 deletion backend/dist/controllers/chatControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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) {
Expand Down
86 changes: 79 additions & 7 deletions backend/dist/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -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 = `
<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>
`;
console.log('Sending email to', user.email);
(0, sendMail_1.default)(htmlContent, user.email, "Message notification");
}
});
}
Expand Down
12 changes: 6 additions & 6 deletions backend/src/controllers/chatControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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) {
Expand Down
184 changes: 93 additions & 91 deletions backend/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `
<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) {
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 = `
<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>
`;

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' } }));
Expand Down
2 changes: 1 addition & 1 deletion backend/tsconfig.tsbuildinfo
Original file line number Diff line number Diff line change
@@ -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"}
{"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"}

0 comments on commit 13f02c5

Please sign in to comment.