-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
337 lines (287 loc) · 9.23 KB
/
Copy pathserver.js
File metadata and controls
337 lines (287 loc) · 9.23 KB
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
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const multer = require('multer');
const fs = require('fs');
const jwt = require('jsonwebtoken');
require('dotenv').config();
// Import models
const User = require('./models/User');
const Message = require('./models/Message');
// Import routes
const authRoutes = require('./routes/auth');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
app.use('/uploads', express.static('uploads'));
// Create uploads directory if it doesn't exist
if (!fs.existsSync('uploads')) {
fs.mkdirSync('uploads');
}
// Routes
app.use('/api/auth', authRoutes);
// MongoDB connection
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/chat-app';
mongoose.connect(MONGODB_URI)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('MongoDB connection error:', err));
// File upload configuration
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 10 * 1024 * 1024 // 10MB limit
}
});
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// API Routes
app.get('/api/messages', async (req, res) => {
try {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ error: 'Access denied. Please login.' });
}
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'fallback-secret-key');
const messages = await Message.find()
.populate('userId', 'username')
.sort({ timestamp: -1 })
.limit(50);
res.json(messages.reverse());
} catch (error) {
res.status(500).json({ error: 'Failed to fetch messages' });
}
});
app.post('/api/upload', upload.single('file'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ error: 'Access denied. Please login.' });
}
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'fallback-secret-key');
const user = await User.findById(decoded.userId);
if (!user) {
return res.status(401).json({ error: 'Invalid token. User not found.' });
}
const message = new Message({
username: user.username,
userId: user._id,
content: `Shared a file: ${req.file.originalname}`,
type: 'file',
fileName: req.file.originalname,
fileSize: req.file.size,
filePath: req.file.path
});
await message.save();
// Emit the file message to all connected clients
io.emit('message', {
_id: message._id,
username: message.username,
userId: message.userId,
content: message.content,
timestamp: message.timestamp,
type: message.type,
fileName: message.fileName,
fileSize: message.fileSize,
downloadUrl: `/uploads/${req.file.filename}`,
avatar: user.getAvatarColor()
});
res.json({
message: 'File uploaded successfully',
downloadUrl: `/uploads/${req.file.filename}`,
fileName: req.file.originalname,
fileSize: req.file.size
});
} catch (error) {
console.error('Upload error:', error);
res.status(500).json({ error: 'Failed to upload file' });
}
});
// File download route with streaming
app.get('/download/:filename', (req, res) => {
const filename = req.params.filename;
const filePath = path.join(__dirname, 'uploads', filename);
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'File not found' });
}
const stat = fs.statSync(filePath);
const fileSize = stat.size;
const range = req.headers.range;
if (range) {
// Support for range requests (streaming)
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunksize = (end - start) + 1;
const file = fs.createReadStream(filePath, { start, end });
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'application/octet-stream',
};
res.writeHead(206, head);
file.pipe(res);
} else {
// Normal download
const head = {
'Content-Length': fileSize,
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${filename}"`
};
res.writeHead(200, head);
fs.createReadStream(filePath).pipe(res);
}
});
// Socket.IO connection handling
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
// Handle user authentication and joining
socket.on('authenticate', async (token) => {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'fallback-secret-key');
const user = await User.findById(decoded.userId);
if (!user) {
socket.emit('authError', 'Invalid token');
return;
}
socket.userId = user._id;
socket.username = user.username;
// Update user online status and socket ID
user.isOnline = true;
user.lastSeen = new Date();
user.socketId = socket.id;
await user.save();
// Join user to their own room
socket.join(user._id.toString());
// Broadcast user joined
socket.broadcast.emit('userJoined', {
username: user.username,
avatar: user.getAvatarColor()
});
// Send recent messages to the authenticated user
const recentMessages = await Message.find()
.populate('userId', 'username')
.sort({ timestamp: -1 })
.limit(50);
const messagesWithAvatars = recentMessages.reverse().map(msg => ({
_id: msg._id,
username: msg.username,
userId: msg.userId,
content: msg.content,
timestamp: msg.timestamp,
type: msg.type,
fileName: msg.fileName,
fileSize: msg.fileSize,
downloadUrl: msg.type === 'file' ? `/uploads/${path.basename(msg.filePath)}` : null,
avatar: msg.userId ? User.findById(msg.userId).then(u => u?.getAvatarColor()) : '#999'
}));
socket.emit('messageHistory', messagesWithAvatars);
socket.emit('authenticated', {
username: user.username,
avatar: user.getAvatarColor()
});
} catch (error) {
console.error('Authentication error:', error);
socket.emit('authError', 'Authentication failed');
}
});
// Handle new messages
socket.on('message', async (data) => {
try {
if (!socket.userId) {
socket.emit('error', 'Please authenticate first');
return;
}
const user = await User.findById(socket.userId);
if (!user) {
socket.emit('error', 'User not found');
return;
}
const message = new Message({
username: user.username,
userId: user._id,
content: data.content,
type: 'text'
});
await message.save();
// Broadcast message to all connected clients
io.emit('message', {
_id: message._id,
username: message.username,
userId: message.userId,
content: message.content,
timestamp: message.timestamp,
type: message.type,
avatar: user.getAvatarColor()
});
} catch (error) {
console.error('Error saving message:', error);
socket.emit('error', 'Failed to send message');
}
});
// Handle typing indicators
socket.on('typing', (data) => {
if (socket.username) {
socket.broadcast.emit('typing', {
username: socket.username,
avatar: data.avatar
});
}
});
socket.on('stopTyping', (data) => {
if (socket.username) {
socket.broadcast.emit('stopTyping', {
username: socket.username
});
}
});
// Handle disconnection
socket.on('disconnect', async () => {
console.log('User disconnected:', socket.id);
if (socket.userId) {
try {
// Update user offline status
await User.findByIdAndUpdate(socket.userId, {
isOnline: false,
lastSeen: new Date(),
socketId: null
});
// Broadcast user left
socket.broadcast.emit('userLeft', socket.username);
} catch (error) {
console.error('Error updating user status on disconnect:', error);
}
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
console.log(`Visit http://localhost:${PORT} to access the chat application`);
});