|
|
const express = require('express');
|
|
|
const http = require('http');
|
|
|
const socketIo = require('socket.io');
|
|
|
const mongoose = require('mongoose');
|
|
|
const cors = require('cors');
|
|
|
const bcrypt = require('bcryptjs');
|
|
|
const jwt = require('jsonwebtoken');
|
|
|
const path = require('path');
|
|
|
const fs = require('fs');
|
|
|
const helmet = require('helmet');
|
|
|
const rateLimit = require('express-rate-limit');
|
|
|
require('dotenv').config();
|
|
|
|
|
|
const app = express();
|
|
|
const server = http.createServer(app);
|
|
|
|
|
|
|
|
|
app.use(helmet());
|
|
|
|
|
|
|
|
|
const limiter = rateLimit({
|
|
|
windowMs: 15 * 60 * 1000,
|
|
|
max: 1000,
|
|
|
message: 'Too many requests from this IP, please try again later.'
|
|
|
});
|
|
|
app.use('/api/', limiter);
|
|
|
|
|
|
|
|
|
app.use(cors({
|
|
|
origin: process.env.CLIENT_URL || "http://localhost:3000",
|
|
|
credentials: true,
|
|
|
methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
|
|
|
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"]
|
|
|
}));
|
|
|
|
|
|
app.use(express.json({ limit: '50mb' }));
|
|
|
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
|
|
|
|
|
|
|
|
|
const uploadsDir = path.join(__dirname, 'uploads');
|
|
|
if (!fs.existsSync(uploadsDir)) {
|
|
|
fs.mkdirSync(uploadsDir, { recursive: true });
|
|
|
console.log('📁 Created uploads directory');
|
|
|
}
|
|
|
app.use('/uploads', express.static(uploadsDir));
|
|
|
|
|
|
|
|
|
const connectDB = async () => {
|
|
|
try {
|
|
|
const conn = await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/ysnrfd-messenger', {
|
|
|
useNewUrlParser: true,
|
|
|
useUnifiedTopology: true,
|
|
|
});
|
|
|
console.log(`✅ MongoDB Connected: ${conn.connection.host}`);
|
|
|
} catch (error) {
|
|
|
console.error('❌ Database connection error:', error);
|
|
|
process.exit(1);
|
|
|
}
|
|
|
};
|
|
|
|
|
|
|
|
|
const User = require('./src/models/User');
|
|
|
const Conversation = require('./src/models/Conversation');
|
|
|
const Message = require('./src/models/Message');
|
|
|
|
|
|
|
|
|
const authRoutes = require('./src/routes/auth');
|
|
|
const userRoutes = require('./src/routes/users');
|
|
|
const conversationRoutes = require('./src/routes/conversations');
|
|
|
const messageRoutes = require('./src/routes/messages');
|
|
|
const uploadRoutes = require('./src/routes/upload');
|
|
|
|
|
|
|
|
|
app.use('/api/auth', authRoutes);
|
|
|
app.use('/api/users', userRoutes);
|
|
|
app.use('/api/conversations', conversationRoutes);
|
|
|
app.use('/api/messages', messageRoutes);
|
|
|
app.use('/api/upload', uploadRoutes);
|
|
|
|
|
|
|
|
|
const io = socketIo(server, {
|
|
|
cors: {
|
|
|
origin: process.env.CLIENT_URL || "http://localhost:3000",
|
|
|
methods: ["GET", "POST"],
|
|
|
credentials: true
|
|
|
}
|
|
|
});
|
|
|
|
|
|
|
|
|
io.use(async (socket, next) => {
|
|
|
try {
|
|
|
const token = socket.handshake.auth.token || socket.handshake.headers.token;
|
|
|
if (!token) {
|
|
|
return next(new Error('Authentication error: No token provided'));
|
|
|
}
|
|
|
|
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'fallback-secret');
|
|
|
const user = await User.findById(decoded.userId);
|
|
|
|
|
|
if (!user) {
|
|
|
return next(new Error('Authentication error: User not found'));
|
|
|
}
|
|
|
|
|
|
socket.userId = user._id;
|
|
|
socket.user = user;
|
|
|
next();
|
|
|
} catch (error) {
|
|
|
console.error('Socket authentication error:', error);
|
|
|
next(new Error('Authentication error: Invalid token'));
|
|
|
}
|
|
|
});
|
|
|
|
|
|
|
|
|
io.on('connection', (socket) => {
|
|
|
console.log(`🔗 User ${socket.userId} connected via WebSocket: ${socket.id}`);
|
|
|
|
|
|
|
|
|
const joinConversationRooms = async () => {
|
|
|
try {
|
|
|
const conversations = await Conversation.find({
|
|
|
'participants.user': socket.userId
|
|
|
});
|
|
|
|
|
|
conversations.forEach(conversation => {
|
|
|
socket.join(conversation._id.toString());
|
|
|
console.log(`👥 User ${socket.userId} joined room ${conversation._id}`);
|
|
|
});
|
|
|
|
|
|
|
|
|
await User.findByIdAndUpdate(socket.userId, {
|
|
|
status: 'online',
|
|
|
lastSeen: new Date()
|
|
|
});
|
|
|
|
|
|
|
|
|
socket.broadcast.emit('user:status', {
|
|
|
userId: socket.userId,
|
|
|
status: 'online',
|
|
|
lastSeen: new Date()
|
|
|
});
|
|
|
} catch (error) {
|
|
|
console.error('❌ Error joining conversation rooms:', error);
|
|
|
}
|
|
|
};
|
|
|
|
|
|
|
|
|
socket.on('message:send', async (data) => {
|
|
|
try {
|
|
|
const { conversationId, content, type, attachment, replyTo } = data;
|
|
|
|
|
|
|
|
|
const conversation = await Conversation.findOne({
|
|
|
_id: conversationId,
|
|
|
'participants.user': socket.userId
|
|
|
});
|
|
|
|
|
|
if (!conversation) {
|
|
|
socket.emit('message:error', { error: 'Not a member of this conversation' });
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
|
|
|
const message = new Message({
|
|
|
conversation: conversationId,
|
|
|
sender: socket.userId,
|
|
|
content,
|
|
|
type: type || 'text',
|
|
|
attachment,
|
|
|
replyTo,
|
|
|
status: 'sent'
|
|
|
});
|
|
|
|
|
|
await message.save();
|
|
|
await message.populate('sender', 'username displayName avatar status');
|
|
|
if (message.replyTo) {
|
|
|
await message.populate('replyTo');
|
|
|
}
|
|
|
|
|
|
|
|
|
conversation.updatedAt = new Date();
|
|
|
conversation.lastMessage = message._id;
|
|
|
await conversation.save();
|
|
|
|
|
|
|
|
|
io.to(conversationId).emit('message:receive', message);
|
|
|
|
|
|
|
|
|
io.to(conversationId).emit('conversation:updated', {
|
|
|
conversationId,
|
|
|
lastMessage: message,
|
|
|
updatedAt: conversation.updatedAt
|
|
|
});
|
|
|
|
|
|
console.log(`💬 Message sent in conversation ${conversationId} by user ${socket.userId}`);
|
|
|
|
|
|
} catch (error) {
|
|
|
console.error('❌ Error sending message:', error);
|
|
|
socket.emit('message:error', { error: 'Failed to send message' });
|
|
|
}
|
|
|
});
|
|
|
|
|
|
|
|
|
socket.on('typing:start', (data) => {
|
|
|
const { conversationId } = data;
|
|
|
socket.to(conversationId).emit('typing:start', {
|
|
|
userId: socket.userId,
|
|
|
conversationId
|
|
|
});
|
|
|
});
|
|
|
|
|
|
socket.on('typing:stop', (data) => {
|
|
|
const { conversationId } = data;
|
|
|
socket.to(conversationId).emit('typing:stop', {
|
|
|
userId: socket.userId,
|
|
|
conversationId
|
|
|
});
|
|
|
});
|
|
|
|
|
|
|
|
|
socket.on('message:read', async (data) => {
|
|
|
try {
|
|
|
const { messageId, conversationId } = data;
|
|
|
|
|
|
const message = await Message.findByIdAndUpdate(
|
|
|
messageId,
|
|
|
{
|
|
|
$addToSet: {
|
|
|
readBy: {
|
|
|
user: socket.userId,
|
|
|
readAt: new Date()
|
|
|
}
|
|
|
}
|
|
|
},
|
|
|
{ new: true }
|
|
|
);
|
|
|
|
|
|
if (!message) {
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
|
|
|
await Conversation.updateOne(
|
|
|
{
|
|
|
_id: conversationId,
|
|
|
'participants.user': socket.userId
|
|
|
},
|
|
|
{
|
|
|
$set: {
|
|
|
'participants.$.lastRead': new Date()
|
|
|
}
|
|
|
}
|
|
|
);
|
|
|
|
|
|
|
|
|
socket.to(conversationId).emit('message:read', {
|
|
|
messageId,
|
|
|
userId: socket.userId,
|
|
|
readAt: new Date()
|
|
|
});
|
|
|
|
|
|
} catch (error) {
|
|
|
console.error('❌ Error updating read receipt:', error);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
|
|
|
socket.on('disconnect', async () => {
|
|
|
try {
|
|
|
console.log(`🔌 User ${socket.userId} disconnected`);
|
|
|
|
|
|
|
|
|
await User.findByIdAndUpdate(socket.userId, {
|
|
|
status: 'offline',
|
|
|
lastSeen: new Date()
|
|
|
});
|
|
|
|
|
|
|
|
|
socket.broadcast.emit('user:status', {
|
|
|
userId: socket.userId,
|
|
|
status: 'offline',
|
|
|
lastSeen: new Date()
|
|
|
});
|
|
|
} catch (error) {
|
|
|
console.error('❌ Error handling disconnect:', error);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
|
|
|
joinConversationRooms();
|
|
|
});
|
|
|
|
|
|
|
|
|
app.get('/api/health', (req, res) => {
|
|
|
res.json({
|
|
|
status: 'OK',
|
|
|
message: 'YSNRFD Messenger Backend is running!',
|
|
|
timestamp: new Date().toISOString(),
|
|
|
environment: process.env.NODE_ENV || 'development'
|
|
|
});
|
|
|
});
|
|
|
|
|
|
|
|
|
app.get('/api/test-cors', (req, res) => {
|
|
|
res.json({
|
|
|
message: 'CORS is working correctly!',
|
|
|
timestamp: new Date().toISOString()
|
|
|
});
|
|
|
});
|
|
|
|
|
|
|
|
|
app.use((err, req, res, next) => {
|
|
|
console.error('❌ Error:', err.stack);
|
|
|
res.status(500).json({
|
|
|
error: process.env.NODE_ENV === 'production'
|
|
|
? 'Internal server error'
|
|
|
: err.message
|
|
|
});
|
|
|
});
|
|
|
|
|
|
|
|
|
app.use('*', (req, res) => {
|
|
|
res.status(404).json({ error: 'Route not found' });
|
|
|
});
|
|
|
|
|
|
|
|
|
app.use(cors({
|
|
|
origin: process.env.CLIENT_URL || "http://localhost:3000",
|
|
|
credentials: true,
|
|
|
methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
|
|
|
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"]
|
|
|
}));
|
|
|
|
|
|
|
|
|
app.options('*', cors());
|
|
|
|
|
|
|
|
|
const PORT = process.env.PORT || 5000;
|
|
|
|
|
|
const startServer = async () => {
|
|
|
try {
|
|
|
await connectDB();
|
|
|
|
|
|
server.listen(PORT, () => {
|
|
|
console.log(`\n🚀 YSNRFD Messenger backend running on port ${PORT}`);
|
|
|
console.log(`🔧 Environment: ${process.env.NODE_ENV || 'development'}`);
|
|
|
console.log(`🌍 Frontend URL: ${process.env.CLIENT_URL || 'http://localhost:3000'}`);
|
|
|
console.log(`📊 MongoDB: ${process.env.MONGODB_URI || 'mongodb://localhost:27017/ysnrfd-messenger'}`);
|
|
|
console.log(`🔍 Health check: http://localhost:${PORT}/api/health`);
|
|
|
console.log(`🔍 CORS test: http://localhost:${PORT}/api/test-cors\n`);
|
|
|
});
|
|
|
} catch (error) {
|
|
|
console.error('❌ Failed to start server:', error);
|
|
|
process.exit(1);
|
|
|
}
|
|
|
};
|
|
|
|
|
|
startServer(); |