141 lines
4.2 KiB
JavaScript
141 lines
4.2 KiB
JavaScript
|
const express = require('express');
|
||
|
const router = express.Router();
|
||
|
const DirectMessage = require('../models/DirectMessage');
|
||
|
const jwt = require('jsonwebtoken');
|
||
|
const User = require('../models/User');
|
||
|
|
||
|
function authenticate(req, res, next) {
|
||
|
const token = req.header('Authorization');
|
||
|
if (!token) return res.sendStatus(401);
|
||
|
jwt.verify(token, 'SECRET_KEY', (err, decoded) => {
|
||
|
if (err) return res.sendStatus(401);
|
||
|
req.userId = decoded.userId;
|
||
|
next();
|
||
|
});
|
||
|
}
|
||
|
|
||
|
router.get('/', authenticate, async (req, res) => {
|
||
|
try {
|
||
|
const dms = await DirectMessage.find({
|
||
|
$or: [
|
||
|
{ sender: req.userId },
|
||
|
{ recipient: req.userId },
|
||
|
],
|
||
|
}).populate('sender recipient', 'username');
|
||
|
|
||
|
// Group the messages by conversation
|
||
|
let conversations = {};
|
||
|
dms.forEach(dm => {
|
||
|
const otherUserId = dm.sender._id.toString() === req.userId ? dm.recipient._id.toString() : dm.sender._id.toString();
|
||
|
if (!conversations[otherUserId]) {
|
||
|
conversations[otherUserId] = {
|
||
|
userId: otherUserId,
|
||
|
username: dm.sender._id.toString() === req.userId ? dm.recipient.username : dm.sender.username,
|
||
|
messages: [],
|
||
|
};
|
||
|
}
|
||
|
conversations[otherUserId].messages.push(dm);
|
||
|
});
|
||
|
|
||
|
// Convert the conversations object to an array
|
||
|
const conversationsArray = Object.values(conversations);
|
||
|
|
||
|
res.json(conversationsArray);
|
||
|
} catch (error) {
|
||
|
console.error(error);
|
||
|
res.status(500).json({ error: "Could not get Direct Messages." });
|
||
|
}
|
||
|
});
|
||
|
|
||
|
|
||
|
router.get('/:otherUserId', authenticate, async (req, res) => {
|
||
|
const { otherUserId } = req.params;
|
||
|
|
||
|
try {
|
||
|
const dms = await DirectMessage.find({
|
||
|
$or: [
|
||
|
{ sender: req.userId, recipient: otherUserId },
|
||
|
{ sender: otherUserId, recipient: req.userId },
|
||
|
],
|
||
|
}).populate('sender recipient', 'username');
|
||
|
|
||
|
res.json(dms);
|
||
|
} catch (error) {
|
||
|
console.error(error);
|
||
|
res.status(500).json({ error: "Could not get Direct Messages." });
|
||
|
}
|
||
|
});
|
||
|
|
||
|
router.delete('/:dmId', authenticate, async (req, res) => {
|
||
|
const { dmId } = req.params;
|
||
|
|
||
|
try {
|
||
|
const dm = await DirectMessage.findById(dmId);
|
||
|
|
||
|
if (!dm) {
|
||
|
return res.status(404).json({ error: "Direct Message not found." });
|
||
|
}
|
||
|
|
||
|
// Check if the authenticated user is the sender of the DM
|
||
|
if (dm.sender.toString() !== req.userId) {
|
||
|
return res.status(403).json({ error: "You can only delete your own Direct Messages." });
|
||
|
}
|
||
|
|
||
|
await dm.remove();
|
||
|
|
||
|
res.json({ message: "Direct Message deleted." });
|
||
|
} catch (error) {
|
||
|
console.error(error);
|
||
|
res.status(500).json({ error: "Could not delete Direct Message." });
|
||
|
}
|
||
|
});
|
||
|
|
||
|
router.post('/send', authenticate, async (req, res) => {
|
||
|
const { recipientId, text, senderId } = req.body;
|
||
|
console.log(req.user)
|
||
|
|
||
|
if (!recipientId || !text) {
|
||
|
return res.status(400).json({ error: "Recipient ID and text are required." });
|
||
|
}
|
||
|
|
||
|
try {
|
||
|
// Check if the recipient exists
|
||
|
const recipient = await User.findById(recipientId);
|
||
|
if (!recipient) {
|
||
|
return res.status(404).json({ error: "Recipient not found." });
|
||
|
}
|
||
|
// Create the Direct Message
|
||
|
const dm = new DirectMessage({
|
||
|
sender: senderId,
|
||
|
recipient: recipientId,
|
||
|
content: text,
|
||
|
});
|
||
|
|
||
|
// Save the Direct Message
|
||
|
const savedDm = await dm.save();
|
||
|
|
||
|
// Populate the sender and recipient fields with full user objects
|
||
|
await savedDm.populate('sender recipient', 'username').exec;
|
||
|
|
||
|
// Now emit the `new_dm` event with the populated Direct Message
|
||
|
const io = req.app.io;
|
||
|
const senderSocketId = req.app.onlineUsers[senderId];
|
||
|
const recipientSocketId = req.app.onlineUsers[recipientId];
|
||
|
if (senderSocketId) {
|
||
|
io.to(senderSocketId).emit('new_dm', savedDm);
|
||
|
}
|
||
|
if (recipientSocketId) {
|
||
|
io.to(recipientSocketId).emit('new_dm', savedDm);
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
res.json(savedDm);
|
||
|
} catch (error) {
|
||
|
console.error(error);
|
||
|
res.status(500).json({ error: "Could not send Direct Message." });
|
||
|
}
|
||
|
});
|
||
|
|
||
|
module.exports = router;
|