File size: 10,370 Bytes
057576a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
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();