ysn-rfd's picture
Upload 302 files
057576a verified
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);
// Security middleware
app.use(helmet());
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 1000,
message: 'Too many requests from this IP, please try again later.'
});
app.use('/api/', limiter);
// CORS configuration
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' }));
// Ensure uploads directory exists
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));
// Database connection
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);
}
};
// Import models
const User = require('./src/models/User');
const Conversation = require('./src/models/Conversation');
const Message = require('./src/models/Message');
// Import routes
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');
// Use routes
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);
// Socket.io configuration
const io = socketIo(server, {
cors: {
origin: process.env.CLIENT_URL || "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
}
});
// Socket.io authentication middleware
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'));
}
});
// Socket event handlers
io.on('connection', (socket) => {
console.log(`🔗 User ${socket.userId} connected via WebSocket: ${socket.id}`);
// Join user to their conversation rooms
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}`);
});
// Update user status to online
await User.findByIdAndUpdate(socket.userId, {
status: 'online',
lastSeen: new Date()
});
// Notify others that user is online
socket.broadcast.emit('user:status', {
userId: socket.userId,
status: 'online',
lastSeen: new Date()
});
} catch (error) {
console.error('❌ Error joining conversation rooms:', error);
}
};
// Handle new message
socket.on('message:send', async (data) => {
try {
const { conversationId, content, type, attachment, replyTo } = data;
// Validate conversation membership
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;
}
// Create message
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');
}
// Update conversation last activity
conversation.updatedAt = new Date();
conversation.lastMessage = message._id;
await conversation.save();
// Emit to all users in conversation
io.to(conversationId).emit('message:receive', message);
// Emit conversation update
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' });
}
});
// Handle typing indicators
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
});
});
// Handle message read receipts
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;
}
// Update user's last read in conversation
await Conversation.updateOne(
{
_id: conversationId,
'participants.user': socket.userId
},
{
$set: {
'participants.$.lastRead': new Date()
}
}
);
// Notify others in conversation
socket.to(conversationId).emit('message:read', {
messageId,
userId: socket.userId,
readAt: new Date()
});
} catch (error) {
console.error('❌ Error updating read receipt:', error);
}
});
// Handle disconnect
socket.on('disconnect', async () => {
try {
console.log(`🔌 User ${socket.userId} disconnected`);
// Update user status to offline
await User.findByIdAndUpdate(socket.userId, {
status: 'offline',
lastSeen: new Date()
});
// Notify others that user is offline
socket.broadcast.emit('user:status', {
userId: socket.userId,
status: 'offline',
lastSeen: new Date()
});
} catch (error) {
console.error('❌ Error handling disconnect:', error);
}
});
// Initialize socket connection
joinConversationRooms();
});
// Health check endpoint
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'
});
});
// Test CORS endpoint
app.get('/api/test-cors', (req, res) => {
res.json({
message: 'CORS is working correctly!',
timestamp: new Date().toISOString()
});
});
// Error handling middleware
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
});
});
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({ error: 'Route not found' });
});
// اضافه کردن کانفیگ CORS
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"]
}));
// پیش‌پردازش درخواست‌های OPTIONS
app.options('*', cors());
// Start server
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();