-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
497 lines (420 loc) · 13.8 KB
/
server.js
File metadata and controls
497 lines (420 loc) · 13.8 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const fs = require('fs');
const path = require('path');
const multer = require('multer');
const crypto = require('crypto');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Create necessary directories
const mediaDir = path.join(__dirname, 'public', 'media');
const thumbnailDir = path.join(__dirname, 'public', 'thumbnails');
if (!fs.existsSync(mediaDir)) {
fs.mkdirSync(mediaDir, { recursive: true });
}
if (!fs.existsSync(thumbnailDir)) {
fs.mkdirSync(thumbnailDir, { recursive: true });
}
// Configure multer for file uploads
const storage = multer.diskStorage({
destination: function (req, file, cb) {
// Select the appropriate directory based on mimetype
if (file.fieldname === 'thumbnail') {
cb(null, 'public/thumbnails');
} else {
cb(null, 'public/media');
}
},
filename: function (req, file, cb) {
// Use original filename but ensure it's safe
const safeFilename = file.originalname.replace(/[^a-zA-Z0-9-_.]/g, '_');
cb(null, safeFilename);
}
});
// File filter for uploads
const fileFilter = (req, file, cb) => {
// Accept video files and jpeg images (for thumbnails)
if (file.mimetype.startsWith('video/') ||
(file.fieldname === 'thumbnail' && file.mimetype === 'image/jpeg')) {
cb(null, true);
} else {
cb(new Error('Only video files and JPEG thumbnails are allowed!'), false);
}
};
const upload = multer({
storage: storage,
fileFilter: fileFilter,
limits: { fileSize: 500 * 1024 * 1024 } // 500MB limit
});
// Serve static files
app.use(express.static('public'));
app.use(express.json());
// Room management
const rooms = {
'main': {
users: {},
leader: null, // Track who controls the video
videoState: {
playing: false,
currentTime: 0,
lastUpdate: Date.now(),
currentVideo: ''
}
}
};
// User tracking
let users = {};
let userCount = 0;
// Update video time when playing
setInterval(() => {
for (const roomName in rooms) {
const room = rooms[roomName];
if (room.videoState.playing) {
const now = Date.now();
const elapsed = (now - room.videoState.lastUpdate) / 1000;
room.videoState.currentTime += elapsed;
room.videoState.lastUpdate = now;
}
}
}, 1000);
// Get list of available videos
app.get('/api/videos', (req, res) => {
fs.readdir(mediaDir, (err, files) => {
if (err) {
return res.status(500).json({ error: 'Failed to retrieve videos' });
}
// Filter only video files
const videoExtensions = ['.mp4', '.webm', '.ogg', '.mov', '.mkv'];
const videoPromises = files
.filter(file => {
const ext = path.extname(file).toLowerCase();
return videoExtensions.includes(ext);
})
.map(async (file) => {
// Check if thumbnail exists
const thumbnailName = path.basename(file, path.extname(file)) + '.jpg';
const thumbnailPath = path.join(thumbnailDir, thumbnailName);
const hasThumbnail = fs.existsSync(thumbnailPath);
return {
name: file,
url: `/media/${file}`,
thumbnail: hasThumbnail ? `/thumbnails/${thumbnailName}` : null
};
});
Promise.all(videoPromises)
.then(videos => res.json(videos))
.catch(error => {
console.error('Error processing videos:', error);
res.status(500).json({ error: 'Failed to process videos' });
});
});
});
// Get list of rooms
app.get('/api/rooms', (req, res) => {
const roomList = Object.keys(rooms).map(roomName => ({
name: roomName,
userCount: Object.keys(rooms[roomName].users).length
}));
res.json(roomList);
});
// Handle video file uploads
app.post('/api/upload', upload.fields([
{ name: 'video', maxCount: 1 },
{ name: 'thumbnail', maxCount: 1 }
]), async (req, res) => {
if (!req.files || !req.files.video) {
return res.status(400).json({ error: 'No video file uploaded' });
}
try {
const videoFile = req.files.video[0];
let thumbnailUrl = null;
// Check if client provided a thumbnail
if (req.files.thumbnail && req.files.thumbnail[0]) {
const thumbnailFile = req.files.thumbnail[0];
thumbnailUrl = `/thumbnails/${thumbnailFile.filename}`;
}
const videoInfo = {
name: videoFile.filename,
url: `/media/${videoFile.filename}`,
thumbnail: thumbnailUrl
};
// Notify all clients about the new video
io.emit('new-video', videoInfo);
res.json(videoInfo);
} catch (error) {
console.error('Error during upload process:', error);
res.status(500).json({ error: 'Failed to process video upload' });
}
});
io.on('connection', (socket) => {
let currentRoom = 'main';
// Send current room list to new connection
socket.emit('room-list', Object.keys(rooms).map(roomName => ({
name: roomName,
userCount: Object.keys(rooms[roomName].users).length
})));
// Join the main room by default
socket.join('main');
socket.emit('sync-video', rooms['main'].videoState);
socket.on('user-joined', (username) => {
users[socket.id] = username;
userCount++;
// Add user to main room by default
rooms['main'].users[socket.id] = username;
// If no leader is assigned for the room, make this user the leader
if (!rooms['main'].leader) {
rooms['main'].leader = socket.id;
}
// Let the user know if they are the leader
socket.emit('leader-status', {
isLeader: rooms['main'].leader === socket.id
});
// Notify all clients about updated user count
io.emit('user-count', {
total: userCount,
room: Object.keys(rooms[currentRoom].users).length
});
// Notify room members about new user
io.to(currentRoom).emit('user-joined-notification', username);
console.log(`${username} joined room "${currentRoom}". Total users: ${userCount}`);
});
// Handle room creation
socket.on('create-room', (roomName) => {
if (!rooms[roomName]) {
rooms[roomName] = {
users: {},
videoState: {
playing: false,
currentTime: 0,
lastUpdate: Date.now(),
currentVideo: ''
}
};
// Notify all clients about the new room
io.emit('room-created', {
name: roomName,
userCount: 0
});
console.log(`Room "${roomName}" created`);
}
});
// Handle room joining
socket.on('join-room', (roomName) => {
// Check if room exists, if not create it
if (!rooms[roomName]) {
rooms[roomName] = {
users: {},
leader: null,
videoState: {
playing: false,
currentTime: 0,
lastUpdate: Date.now(),
currentVideo: ''
}
};
}
// Leave current room
socket.leave(currentRoom);
// If this user was the leader of the current room, assign a new leader
if (rooms[currentRoom].leader === socket.id) {
const remainingUsers = Object.keys(rooms[currentRoom].users).filter(id => id !== socket.id);
if (remainingUsers.length > 0) {
// Assign first remaining user as leader
rooms[currentRoom].leader = remainingUsers[0];
// Notify new leader
io.to(remainingUsers[0]).emit('leader-status', { isLeader: true });
} else {
rooms[currentRoom].leader = null;
}
}
delete rooms[currentRoom].users[socket.id];
// Join new room
currentRoom = roomName;
socket.join(currentRoom);
rooms[currentRoom].users[socket.id] = users[socket.id];
// If no leader in the new room, make this user the leader
if (!rooms[currentRoom].leader) {
rooms[currentRoom].leader = socket.id;
}
// Let the user know if they are the leader
socket.emit('leader-status', {
isLeader: rooms[currentRoom].leader === socket.id
});
// Send room's current video state
socket.emit('sync-video', rooms[currentRoom].videoState);
// Notify room members about new user
io.to(currentRoom).emit('user-joined-notification', users[socket.id]);
// Update room user counts
io.emit('room-user-counts', Object.keys(rooms).map(room => ({
name: room,
userCount: Object.keys(rooms[room].users).length
})));
console.log(`${users[socket.id]} joined room "${currentRoom}"`);
});
// Handle video selection
socket.on('select-video', (videoUrl) => {
rooms[currentRoom].videoState.currentVideo = videoUrl;
rooms[currentRoom].videoState.currentTime = 0;
rooms[currentRoom].videoState.playing = false;
// Broadcast video selection to room members
io.to(currentRoom).emit('video-selected', videoUrl);
io.to(currentRoom).emit('sync-video', rooms[currentRoom].videoState);
console.log(`Video selected in room "${currentRoom}": ${videoUrl}`);
});
// Handle video events (play, pause, seek)
socket.on('video-event', (data) => {
if (data.type === 'play') {
rooms[currentRoom].videoState.playing = true;
rooms[currentRoom].videoState.currentTime = data.currentTime;
rooms[currentRoom].videoState.lastUpdate = Date.now();
} else if (data.type === 'pause') {
rooms[currentRoom].videoState.playing = false;
rooms[currentRoom].videoState.currentTime = data.currentTime;
} else if (data.type === 'seek') {
rooms[currentRoom].videoState.currentTime = data.currentTime;
rooms[currentRoom].videoState.lastUpdate = Date.now();
}
// Broadcast updated state to all room members except sender
socket.to(currentRoom).emit('sync-video', rooms[currentRoom].videoState);
});
// Handle chat messages
socket.on('chat-message', (data) => {
// Broadcast message to all room members except sender
socket.to(currentRoom).emit('chat-message', data);
});
// Handle typing indicators
socket.on('user-typing', () => {
socket.to(currentRoom).emit('user-typing', users[socket.id]);
});
socket.on('user-stopped-typing', () => {
socket.to(currentRoom).emit('user-stopped-typing', users[socket.id]);
});
// Handle reactions
socket.on('reaction', (reaction) => {
socket.to(currentRoom).emit('reaction', {
reaction: reaction,
username: users[socket.id]
});
});
// Handle disconnections
socket.on('disconnect', () => {
if (users[socket.id]) {
// Check if user was a room leader
if (rooms[currentRoom] && rooms[currentRoom].leader === socket.id) {
// Find a new leader
const remainingUsers = Object.keys(rooms[currentRoom].users).filter(id => id !== socket.id);
if (remainingUsers.length > 0) {
// Assign first remaining user as leader
rooms[currentRoom].leader = remainingUsers[0];
// Notify new leader
io.to(remainingUsers[0]).emit('leader-status', { isLeader: true });
} else {
rooms[currentRoom].leader = null;
}
}
// Remove user from their current room
if (rooms[currentRoom]) {
delete rooms[currentRoom].users[socket.id];
// Clean up empty rooms (except main)
if (currentRoom !== 'main' && Object.keys(rooms[currentRoom].users).length === 0) {
delete rooms[currentRoom];
io.emit('room-deleted', currentRoom);
}
}
userCount--;
delete users[socket.id];
// Update room user counts
io.emit('room-user-counts', Object.keys(rooms).map(room => ({
name: room,
userCount: Object.keys(rooms[room].users).length
})));
io.emit('user-count', {
total: userCount
});
}
});
});
// Add this to your server.js to help debug video issues
// Debug endpoint to check video files
app.get('/api/debug/videos', (req, res) => {
const debugInfo = {
mediaDir: mediaDir,
exists: fs.existsSync(mediaDir),
files: [],
errors: []
};
try {
if (debugInfo.exists) {
// List all files
const files = fs.readdirSync(mediaDir);
// Get details about each file
debugInfo.files = files.map(filename => {
try {
const filePath = path.join(mediaDir, filename);
const stats = fs.statSync(filePath);
return {
name: filename,
path: filePath,
size: stats.size,
isFile: stats.isFile(),
created: stats.birthtime,
modified: stats.mtime,
url: `/media/${filename}`,
accessible: true
};
} catch (err) {
debugInfo.errors.push(`Error processing file ${filename}: ${err.message}`);
return {
name: filename,
error: err.message,
accessible: false
};
}
});
}
} catch (err) {
debugInfo.errors.push(`Error reading directory: ${err.message}`);
}
res.json(debugInfo);
});
// Debug endpoint to check a specific video
app.get('/api/debug/video/:filename', (req, res) => {
const filename = req.params.filename;
const filePath = path.join(mediaDir, filename);
const debugInfo = {
filename: filename,
requestedPath: filePath,
exists: false,
error: null,
stats: null
};
try {
if (fs.existsSync(filePath)) {
debugInfo.exists = true;
const stats = fs.statSync(filePath);
debugInfo.stats = {
size: stats.size,
isFile: stats.isFile(),
created: stats.birthtime,
modified: stats.mtime
};
// Read the first few bytes to check file signature
const buffer = Buffer.alloc(16);
const fd = fs.openSync(filePath, 'r');
fs.readSync(fd, buffer, 0, 16, 0);
fs.closeSync(fd);
// Convert to hex for debugging
debugInfo.fileSignature = buffer.toString('hex');
}
} catch (err) {
debugInfo.error = err.message;
}
res.json(debugInfo);
});
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});