veltrixcode commited on
Commit
2883b44
·
verified ·
1 Parent(s): 2a53671

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +37 -753
server.js CHANGED
@@ -1,770 +1,54 @@
1
- const express = require('express');
2
- const cors = require('cors');
3
- const path = require('path');
4
- const bcrypt = require('bcrypt');
5
- const multer = require('multer');
6
- const { getDb } = require('./db');
7
- const { getSecondaryDb } = require('./dbSecondary');
8
- const otpService = require('./otpService');
9
- const axios = require('axios');
10
- const http = require('http');
11
- const socketIo = require('socket.io');
12
- const fs = require('fs');
13
- const { ObjectId } = require('mongodb');
14
 
15
  const app = express();
16
- const server = http.createServer(app);
17
- const io = socketIo(server, {
18
- cors: {
19
- origin: "*",
20
- methods: ["GET", "POST"]
21
- }
22
- });
23
- const port = 7860;
24
-
25
- // Middleware
26
- app.use(cors());
27
  app.use(express.json());
28
 
29
- // Serve static files from React build directory
30
- app.use(express.static(path.join(__dirname, 'public')));
31
-
32
- // Store logs in memory (in production, use a database)
33
- let serverLogs = [];
34
-
35
- // Logging middleware
36
- function logRequest(req, res, next) {
37
- const start = Date.now();
38
-
39
- // Log incoming request
40
- const requestLog = {
41
- type: 'request',
42
- message: `${req.method} ${req.path}`,
43
- details: {
44
- method: req.method,
45
- path: req.path,
46
- headers: req.headers,
47
- body: req.body,
48
- timestamp: new Date().toISOString(),
49
- ip: req.ip || req.connection.remoteAddress
50
- },
51
- source: 'middleware'
52
- };
53
-
54
- emitLog(requestLog);
55
-
56
- // Override res.end to log response
57
- const originalEnd = res.end;
58
- res.end = function(chunk, encoding) {
59
- const duration = Date.now() - start;
60
-
61
- const responseLog = {
62
- type: 'response',
63
- message: `${req.method} ${req.path} - ${res.statusCode} (${duration}ms)`,
64
- details: {
65
- statusCode: res.statusCode,
66
- duration: duration,
67
- headers: res.getHeaders(),
68
- timestamp: new Date().toISOString()
69
- },
70
- source: 'middleware'
71
- };
72
-
73
- emitLog(responseLog);
74
- originalEnd.call(this, chunk, encoding);
75
- };
76
-
77
- next();
78
- }
79
-
80
- // Apply logging middleware
81
- app.use(logRequest);
82
-
83
- // Emit log to all connected clients
84
- function emitLog(logData) {
85
- serverLogs.unshift(logData);
86
-
87
- // Keep only last 1000 logs
88
- if (serverLogs.length > 1000) {
89
- serverLogs = serverLogs.slice(0, 1000);
90
- }
91
-
92
- io.emit('server-log', logData);
93
- }
94
-
95
- // Manual logging function
96
- function log(level, message, details = {}) {
97
- const logData = {
98
- type: level,
99
- message: message,
100
- details: {
101
- ...details,
102
- timestamp: new Date().toISOString()
103
- },
104
- source: 'server'
105
- };
106
-
107
- emitLog(logData);
108
-
109
- // Also log to console
110
- console.log(`[${level.toUpperCase()}] ${message}`, details);
111
- }
112
-
113
- // OTP Authentication middleware (MongoDB version)
114
- const requireOtpAuth = async (req, res, next) => {
115
- const otp = req.headers['x-otp-token'];
116
- const email = req.headers['x-user-email'];
117
-
118
- if (!otp || !email) {
119
- return res.status(401).json({ error: 'Missing OTP or email headers' });
120
- }
121
-
122
- try {
123
- const db = await getDb();
124
- const result = await db.collection('otps').findOne({
125
- email,
126
- otp,
127
- verified: true,
128
- expires_at: { $gt: new Date() }
129
- });
130
- if (!result) {
131
- return res.status(401).json({ error: 'Invalid or expired OTP' });
132
- }
133
- req.user = { email };
134
- next();
135
- } catch (err) {
136
- console.error('OTP verification error:', err);
137
- res.status(500).json({ error: 'Internal server error' });
138
- }
139
- };
140
-
141
- // Admin OTP Authentication middleware (MongoDB version)
142
- const requireAdminOtpAuth = async (req, res, next) => {
143
- try {
144
- const otp = req.headers['x-otp-token'];
145
- const email = req.headers['x-user-email'];
146
- if (!otp || !email) {
147
- return res.status(401).json({ success: false, error: 'Missing authentication headers' });
148
- }
149
- const db = await getDb();
150
- const result = await db.collection('otps').findOne({
151
- email,
152
- otp,
153
- is_used: false,
154
- expires_at: { $gt: new Date() }
155
- });
156
- if (!result) {
157
- return res.status(401).json({ success: false, error: 'Invalid or expired OTP' });
158
- }
159
- await db.collection('otps').updateOne({ email, otp }, { $set: { is_used: true } });
160
- next();
161
- } catch (error) {
162
- console.error('Admin auth error:', error);
163
- res.status(500).json({ success: false, error: 'Authentication error' });
164
- }
165
- };
166
-
167
- // Middleware to check OTP authentication
168
- async function checkOtpAuth(req, res, next) {
169
- const otp = req.headers['x-otp-token'];
170
- const email = req.headers['x-user-email'];
171
-
172
- if (!otp || !email) {
173
- return res.status(401).json({ success: false, error: 'OTP token and email are required' });
174
- }
175
-
176
- try {
177
- const result = await otpService.verifyUserOtp(email, otp);
178
- if (!result.success) {
179
- return res.status(401).json({ success: false, error: 'Invalid OTP' });
180
- }
181
- next();
182
- } catch (error) {
183
- res.status(401).json({ success: false, error: error.message });
184
- }
185
- }
186
-
187
- // Middleware to check admin OTP authentication
188
- async function checkAdminOtpAuth(req, res, next) {
189
- const otp = req.headers['x-otp-token'];
190
-
191
- if (!otp) {
192
- return res.status(401).json({ success: false, error: 'OTP token required' });
193
- }
194
-
195
- try {
196
- const response = await fetch('https://mail-steel.vercel.app/admin/verify-otp', {
197
- method: 'POST',
198
- headers: {
199
- 'Content-Type': 'application/json'
200
- },
201
- body: JSON.stringify({ otp })
202
- });
203
-
204
- const data = await response.json();
205
- if (!data.success) {
206
- return res.status(401).json({ success: false, error: 'Invalid OTP' });
207
- }
208
-
209
- next();
210
- } catch (error) {
211
- console.error('Admin OTP verification failed:', error);
212
- res.status(500).json({ success: false, error: 'Failed to verify admin OTP' });
213
- }
214
- }
215
-
216
- // Routes
217
- app.get('/', (req, res) => {
218
- log('info', 'Homepage accessed', {
219
- path: req.path,
220
- userAgent: req.get('User-Agent'),
221
- ip: req.ip
222
- });
223
- res.sendFile(path.join(__dirname, 'public', 'index.html'));
224
- });
225
-
226
- // API Routes
227
-
228
- // Send OTP
229
- app.post('/api/send-otp', async (req, res) => {
230
- const { email, type } = req.body;
231
-
232
- if (!email && type !== 'admin') {
233
- return res.status(400).json({ success: false, error: 'Email is required for user OTP' });
234
- }
235
-
236
- try {
237
- let result;
238
- if (type === 'admin') {
239
- result = await otpService.sendAdminOtp();
240
- } else {
241
- result = await otpService.sendUserOtp(email);
242
- }
243
- res.json(result);
244
- } catch (error) {
245
- res.status(500).json({ success: false, error: error.message });
246
- }
247
- });
248
-
249
- // Verify OTP
250
- app.post('/api/verify-otp', async (req, res) => {
251
- const { email, otp, type } = req.body;
252
-
253
- if (!otp || (type !== 'admin' && !email)) {
254
- return res.status(400).json({ success: false, error: 'OTP and email (for user) are required' });
255
- }
256
-
257
- try {
258
- let result;
259
- if (type === 'admin') {
260
- result = await otpService.verifyAdminOtp(otp);
261
- } else {
262
- result = await otpService.verifyUserOtp(email, otp);
263
- }
264
- res.json(result);
265
- } catch (error) {
266
- res.status(500).json({ success: false, error: error.message });
267
- }
268
- });
269
-
270
- // Register new user (MongoDB version)
271
- app.post('/api/register', async (req, res) => {
272
- const { name, email, password } = req.body;
273
- if (!name || !email || !password) {
274
- return res.status(400).json({ success: false, error: 'Name, email and password are required' });
275
- }
276
- try {
277
- const db = await getDb();
278
- const existingUser = await db.collection('users').findOne({ email });
279
- if (existingUser) {
280
- return res.status(400).json({ success: false, error: 'Email already registered' });
281
- }
282
- const hashedPassword = await bcrypt.hash(password, 10);
283
- const result = await db.collection('users').insertOne({ name, email, password: hashedPassword, created_at: new Date() });
284
- res.json({ success: true, user: { id: result.insertedId, name, email }, message: 'Registration successful' });
285
- } catch (error) {
286
- console.error('Error registering user:', error);
287
- res.status(500).json({ success: false, error: 'Failed to register user' });
288
- }
289
  });
290
 
291
- // Login (MongoDB version)
292
- app.post('/api/login', async (req, res) => {
293
- const { email, password } = req.body;
294
- if (!email || !password) {
295
- return res.status(400).json({ success: false, error: 'Email and password are required' });
296
- }
297
- try {
298
- const db = await getDb();
299
- const user = await db.collection('users').findOne({ email });
300
- if (!user) {
301
- return res.status(401).json({ success: false, error: 'Invalid email or password' });
302
- }
303
- const validPassword = await bcrypt.compare(password, user.password);
304
- if (!validPassword) {
305
- return res.status(401).json({ success: false, error: 'Invalid email or password' });
306
- }
307
- res.json({ success: true, user: { id: user._id, name: user.name, email: user.email } });
308
- } catch (error) {
309
- console.error('Error logging in:', error);
310
- res.status(500).json({ success: false, error: 'Login failed' });
311
- }
312
- });
313
 
314
- // Get user submissions (MongoDB version)
315
- app.get('/api/user-submissions/:userId', checkOtpAuth, async (req, res) => {
316
- const { userId } = req.params;
317
- try {
318
- const db = await getDb();
319
- const userIdObj = ObjectId.isValid(userId) ? new ObjectId(userId) : userId;
320
- const submissions = await db.collection('submissions').find({ user_id: userIdObj }).sort({ created_at: -1 }).toArray();
321
- const mappedSubs = submissions.map(sub => {
322
- const payment_address = sub.payment_address || sub.upi_id || 'oldsub';
323
- const mapped = {
324
- ...sub,
325
- payment_address,
326
- card_type: sub.card_type || 'oldsub',
327
- payment_method: sub.payment_method || 'oldsub'
328
- };
329
- delete mapped.upi_id;
330
- return mapped;
331
- });
332
- res.json({ success: true, submissions: mappedSubs });
333
- } catch (error) {
334
- res.status(500).json({ success: false, error: 'Failed to fetch submissions' });
335
- }
336
- });
337
-
338
- // Gift Card Submission (MongoDB version)
339
- app.post('/api/gift-cards', checkOtpAuth, async (req, res) => {
340
- const { ticket_user_name, gc_code, gc_phone, ticket_number, payment_address, amount, proof_video_url, card_type, payment_method } = req.body;
341
- const userId = req.headers['x-user-id'];
342
- const finalTicketNumber = ticket_number || `TKT-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
343
- if (!ticket_user_name || !gc_code || !gc_phone || !payment_address || !amount || !proof_video_url || !card_type || !payment_method) {
344
- return res.status(400).json({ success: false, error: 'All fields are required including the video URL, card type, payment address, and payment method' });
345
- }
346
- try {
347
- const db = await getDb();
348
- const userIdObj = ObjectId.isValid(userId) ? new ObjectId(userId) : userId;
349
- const result = await db.collection('submissions').insertOne({
350
- user_id: userIdObj,
351
- ticket_user_name,
352
- gc_code,
353
- gc_phone,
354
- ticket_number: finalTicketNumber,
355
- payment_address,
356
- amount,
357
- proof_video_url,
358
- card_type,
359
- payment_method,
360
- status: 'pending',
361
- created_at: new Date(),
362
- updated_at: new Date()
363
- });
364
- res.json({ success: true, submissionId: result.insertedId, message: 'Gift card submission successful' });
365
- } catch (error) {
366
- console.error('Gift card submission error:', error);
367
- res.status(500).json({ success: false, error: 'Failed to submit gift card. Please try again.' });
368
- }
369
- });
370
 
371
- // File2Link Upload Route
372
- app.post('/api/upload', async (req, res) => {
373
- try {
374
- const formData = new FormData();
375
- formData.append('file', req.files.file);
376
 
377
- const response = await axios.post('https://file2link-ol4p.onrender.com/.com/upload', formData, {
378
- headers: {
379
- ...formData.getHeaders()
380
- }
381
- });
382
 
383
- if (response.data.success) {
384
- res.json({
385
- success: true,
386
- videoUrl: response.data.access_url
387
- });
388
- } else {
389
- throw new Error('Upload failed');
390
- }
391
- } catch (error) {
392
- console.error('File upload error:', error);
393
- res.status(500).json({
394
- success: false,
395
- error: 'Failed to upload file. Please try again.'
396
- });
397
- }
398
  });
399
 
400
- // Get chat messages (MongoDB version)
401
- app.get('/api/messages/:userId', checkOtpAuth, async (req, res) => {
402
- const { userId } = req.params;
403
- const userEmail = req.headers['x-user-email'];
404
- try {
405
- const mainDb = await getDb();
406
- const db = await getSecondaryDb();
407
- const user = await mainDb.collection('users').findOne({ email: userEmail });
408
- // Allow legacy numeric id or ObjectId string
409
- const userIdStr = userId.toString();
410
- const userIdObj = ObjectId.isValid(userIdStr) ? new ObjectId(userIdStr) : userIdStr;
411
- if (!user || (user._id.toString() !== userIdStr && user.id?.toString() !== userIdStr)) {
412
- return res.status(403).json({ success: false, error: 'Unauthorized access' });
413
- }
414
- const messages = await db.collection('messages').find({ $or: [ { user_id: userIdObj }, { user_id: user.id } ] }).sort({ created_at: 1 }).toArray();
415
- res.json({ success: true, messages });
416
- } catch (error) {
417
- console.error('Error fetching messages:', error);
418
- res.status(500).json({ success: false, error: 'Failed to fetch messages', details: error.message });
419
- }
420
- });
421
-
422
- // Send message (MongoDB version)
423
- app.post('/api/messages', checkOtpAuth, async (req, res) => {
424
- const { userId, content, sender } = req.body;
425
- const userEmail = req.headers['x-user-email'];
426
- if (!content || !sender) {
427
- return res.status(400).json({ success: false, error: 'Content and sender are required' });
428
- }
429
- try {
430
- const mainDb = await getDb();
431
- const db = await getSecondaryDb();
432
- const user = await mainDb.collection('users').findOne({ email: userEmail });
433
- const userIdStr = userId.toString();
434
- const userIdObj = ObjectId.isValid(userIdStr) ? new ObjectId(userIdStr) : userIdStr;
435
- if (!user || (user._id.toString() !== userIdStr && user.id?.toString() !== userIdStr)) {
436
- return res.status(403).json({ success: false, error: 'Unauthorized access' });
437
- }
438
- const result = await db.collection('messages').insertOne({ user_id: userIdObj, content, sender, created_at: new Date() });
439
- res.json({ success: true, message: { ...result.ops?.[0], user_id: userId, id: userId, _id: result.insertedId } });
440
- } catch (error) {
441
- console.error('Error sending message:', error);
442
- res.status(500).json({ success: false, error: 'Failed to send message', details: error.message });
443
- }
444
- });
445
 
446
- // Admin routes (MongoDB version)
447
- app.get('/api/admin/users', async (req, res) => {
448
- try {
449
- const db = await getDb();
450
- const users = await db.collection('users').find({}, { projection: { password: 0 } }).sort({ created_at: -1 }).toArray();
451
- res.json({ success: true, users });
452
- } catch (error) {
453
- console.error('Error fetching users:', error);
454
- res.status(500).json({ success: false, error: 'Failed to fetch users' });
455
- }
456
- });
457
-
458
- app.get('/api/admin/messages/all', async (req, res) => {
459
- try {
460
- const db = await getSecondaryDb();
461
- const messages = await db.collection('messages').find({}).sort({ created_at: -1 }).toArray();
462
- res.json({ success: true, messages });
463
- } catch (error) {
464
- console.error('Error fetching messages:', error);
465
- res.status(500).json({ success: false, error: 'Failed to fetch messages', details: error.message });
466
- }
467
- });
468
-
469
- app.get('/api/admin/messages/:userId', async (req, res) => {
470
- const { userId } = req.params;
471
- try {
472
- const db = await getSecondaryDb();
473
- const userIdObj = ObjectId.isValid(userId) ? new ObjectId(userId) : userId;
474
- const messages = await db.collection('messages').find({ user_id: userIdObj }).sort({ created_at: 1 }).toArray();
475
- res.json({ success: true, messages });
476
- } catch (error) {
477
- console.error('Error fetching messages:', error);
478
- res.status(500).json({ success: false, error: 'Failed to fetch messages', details: error.message });
479
- }
480
- });
481
-
482
- app.post('/api/admin/messages', async (req, res) => {
483
- try {
484
- const { userId, content } = req.body;
485
- const db = await getSecondaryDb();
486
- // Convert userId to ObjectId
487
- const userIdObj = ObjectId.isValid(userId) ? new ObjectId(userId) : userId;
488
- const result = await db.collection('messages').insertOne({ user_id: userIdObj, content, sender: 'admin', created_at: new Date() });
489
- res.json({ success: true });
490
- } catch (error) {
491
- console.error('Error sending message:', error);
492
- res.status(500).json({ success: false, error: 'Failed to send message', details: error.message });
493
- }
494
- });
495
-
496
- app.delete('/api/admin/messages/:messageId', async (req, res) => {
497
- const { messageId } = req.params;
498
- try {
499
- const db = await getSecondaryDb();
500
- // Convert messageId to ObjectId
501
- const messageIdObj = ObjectId.isValid(messageId) ? new ObjectId(messageId) : messageId;
502
- await db.collection('messages').deleteOne({ _id: messageIdObj });
503
- res.json({ success: true });
504
- } catch (error) {
505
- console.error('Error deleting message:', error);
506
- res.status(500).json({ success: false, error: 'Failed to delete message', details: error.message });
507
- }
508
- });
509
-
510
- app.delete('/api/admin/users/:userId', async (req, res) => {
511
- const { userId } = req.params;
512
- try {
513
- const db = await getDb();
514
- const secondaryDb = await getSecondaryDb();
515
- const userIdObj = ObjectId.isValid(userId) ? new ObjectId(userId) : userId;
516
- // First delete all messages for the user from secondary DB
517
- await secondaryDb.collection('messages').deleteMany({ user_id: userIdObj });
518
- // Then delete the user from main DB
519
- await db.collection('users').deleteOne({ _id: userIdObj });
520
- res.json({ success: true });
521
- } catch (error) {
522
- console.error('Error deleting user:', error);
523
- res.status(500).json({ success: false, error: 'Failed to delete user', details: error.message });
524
- }
525
- });
526
-
527
- app.get('/api/admin/submissions', async (req, res) => {
528
- try {
529
- const db = await getDb();
530
- const submissions = await db.collection('submissions').find({}).sort({ created_at: -1 }).toArray();
531
- const mappedSubs = submissions.map(sub => {
532
- const payment_address = sub.payment_address || sub.upi_id || 'oldsub';
533
- const mapped = {
534
- ...sub,
535
- payment_address,
536
- card_type: sub.card_type || 'oldsub',
537
- payment_method: sub.payment_method || 'oldsub'
538
- };
539
- delete mapped.upi_id;
540
- return mapped;
541
- });
542
- res.json({ success: true, submissions: mappedSubs });
543
- } catch (error) {
544
- console.error('Error fetching submissions:', error);
545
- res.status(500).json({ success: false, error: 'Failed to fetch submissions' });
546
- }
547
- });
548
-
549
- // Update submission status
550
- app.post('/api/admin/submissions/:submissionId/status', async (req, res) => {
551
- const { submissionId } = req.params;
552
- const { status } = req.body;
553
-
554
- // Validate status
555
- const validStatuses = ['pending', 'approved', 'rejected', 'paid', 'closed'];
556
- if (!validStatuses.includes(status)) {
557
- return res.status(400).json({
558
- success: false,
559
- error: `Invalid status. Must be one of: ${validStatuses.join(', ')}`
560
- });
561
- }
562
-
563
- try {
564
- const db = await getDb();
565
- // Convert submissionId to ObjectId
566
- const submissionIdObj = ObjectId.isValid(submissionId) ? new ObjectId(submissionId) : submissionId;
567
- // First check if submission exists
568
- const checkResult = await db.collection('submissions').findOne({ _id: submissionIdObj });
569
-
570
- if (!checkResult) {
571
- return res.status(404).json({ success: false, error: 'Submission not found' });
572
- }
573
-
574
- // If status is 'closed', mask the gc_code
575
- let updateFields = { status: status, updated_at: new Date() };
576
- if (status === 'closed' && checkResult.gc_code) {
577
- updateFields.gc_code = 'x'.repeat(checkResult.gc_code.length);
578
- }
579
-
580
- // Update submission status (and gc_code if closed)
581
- const updateResult = await db.collection('submissions').updateOne(
582
- { _id: submissionIdObj },
583
- { $set: updateFields }
584
- );
585
-
586
- if (updateResult.matchedCount === 0) {
587
- return res.status(500).json({
588
- success: false,
589
- error: 'Failed to update submission status'
590
- });
591
- }
592
-
593
- res.json({
594
- success: true,
595
- submission: updateResult.value,
596
- message: `Status updated to ${status}`
597
- });
598
- } catch (error) {
599
- console.error('Error updating submission status:', error);
600
- res.status(500).json({
601
- success: false,
602
- error: 'Failed to update submission status',
603
- details: error.message
604
- });
605
- }
606
- });
607
-
608
- // Get submission details including video proof
609
- app.get('/api/admin/submissions/:submissionId', async (req, res) => {
610
- const { submissionId } = req.params;
611
- try {
612
- const db = await getDb();
613
- // Convert submissionId to ObjectId
614
- const submissionIdObj = ObjectId.isValid(submissionId) ? new ObjectId(submissionId) : submissionId;
615
- const submission = await db.collection('submissions').findOne({ _id: submissionIdObj });
616
-
617
- if (!submission) {
618
- return res.status(404).json({ success: false, error: 'Submission not found' });
619
- }
620
- // Ensure card_type, payment_method, and payment_address are always present, and remove upi_id
621
- const payment_address = submission.payment_address || submission.upi_id || 'oldsub';
622
- const submissionDetails = {
623
- ...submission,
624
- payment_address,
625
- card_type: submission.card_type || 'oldsub',
626
- payment_method: submission.payment_method || 'oldsub'
627
- };
628
- delete submissionDetails.upi_id;
629
- res.json({ success: true, submission: submissionDetails });
630
- } catch (error) {
631
- console.error('Error fetching submission details:', error);
632
- res.status(500).json({ success: false, error: 'Failed to fetch submission details' });
633
- }
634
- });
635
-
636
- // Utility endpoint to update old submissions: set card_type and payment_method to 'oldsub' where missing
637
- app.post('/api/admin/fix-old-submissions', async (req, res) => {
638
- try {
639
- const db = await getDb();
640
- const result = await db.collection('submissions').updateMany(
641
- {
642
- $or: [
643
- { card_type: { $in: [null, ''] } },
644
- { payment_method: { $in: [null, ''] } }
645
- ]
646
- },
647
- { $set: { card_type: 'oldsub', payment_method: 'oldsub' } }
648
- );
649
- res.json({
650
- success: true,
651
- updatedCount: result.modifiedCount
652
- });
653
- } catch (error) {
654
- console.error('Error updating old submissions:', error);
655
- res.status(500).json({ success: false, error: 'Failed to update old submissions' });
656
- }
657
- });
658
-
659
- // Check if submission is open (Sunday 9am-9pm)
660
- app.get('/isubmissionopen', (req, res) => {
661
- const now = new Date();
662
- const dayOfWeek = now.getDay(); // 0 = Sunday, 1 = Monday, ..., 6 = Saturday
663
- const hour = now.getHours();
664
-
665
- // Check if it's Sunday (day 0) and between 9am (9) and 9pm (21)
666
- const isSubmissionOpen = dayOfWeek === 0 && hour >= 9 && hour < 21;
667
-
668
- log('info', 'Submission status checked', {
669
- dayOfWeek: dayOfWeek,
670
- hour: hour,
671
- isOpen: isSubmissionOpen,
672
- ip: req.ip
673
- });
674
-
675
- res.json({
676
- success: true,
677
- isSubmissionOpen: true,
678
- currentTime: now.toISOString(),
679
- dayOfWeek: dayOfWeek,
680
- hour: hour
681
- });
682
- });
683
-
684
- // Catch-all route for React Router - serve index.html for all non-API routes
685
- app.get('*', (req, res) => {
686
- // Skip API routes
687
- if (req.path.startsWith('/api/')) {
688
- return res.status(404).json({ error: 'API endpoint not found' });
689
- }
690
-
691
- // Skip the /isubmissionopen endpoint
692
- if (req.path === '/isubmissionopen') {
693
- return res.status(404).json({ error: 'Endpoint not found' });
694
- }
695
-
696
- log('info', 'React route accessed', {
697
- path: req.path,
698
- userAgent: req.get('User-Agent'),
699
- ip: req.ip
700
- });
701
-
702
- res.sendFile(path.join(__dirname, 'public', 'index.html'));
703
- });
704
-
705
- // Socket.IO connection handling
706
- io.on('connection', (socket) => {
707
- log('info', 'Client connected to server logs', {
708
- socketId: socket.id,
709
- totalConnections: io.engine.clientsCount
710
- });
711
-
712
- // Send existing logs to new client
713
- socket.emit('server-log', {
714
- type: 'info',
715
- message: 'Connected to server logs',
716
- details: {
717
- socketId: socket.id,
718
- totalLogs: serverLogs.length
719
- }
720
- });
721
-
722
- socket.on('disconnect', () => {
723
- log('info', 'Client disconnected from server logs', {
724
- socketId: socket.id,
725
- totalConnections: io.engine.clientsCount
726
- });
727
- });
728
-
729
- socket.on('request-logs', () => {
730
- log('info', 'Client requested historical logs', { socketId: socket.id });
731
- // Send last 100 logs
732
- const recentLogs = serverLogs.slice(0, 100);
733
- socket.emit('historical-logs', recentLogs);
734
- });
735
- });
736
-
737
- // Error handling
738
- process.on('uncaughtException', (error) => {
739
- log('error', 'Uncaught Exception', {
740
- error: error.message,
741
- stack: error.stack
742
- });
743
- });
744
-
745
- process.on('unhandledRejection', (reason, promise) => {
746
- log('error', 'Unhandled Rejection', {
747
- reason: reason,
748
- promise: promise
749
- });
750
- });
751
 
752
- // Periodic system logs
753
- setInterval(() => {
754
- const memoryUsage = process.memoryUsage();
755
- log('info', 'System status', {
756
- memory: {
757
- rss: Math.round(memoryUsage.rss / 1024 / 1024) + 'MB',
758
- heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024) + 'MB',
759
- heapTotal: Math.round(memoryUsage.heapTotal / 1024 / 1024) + 'MB'
760
- },
761
- uptime: Math.round(process.uptime()) + 's',
762
- connections: io.engine.clientsCount
763
- });
764
- }, 30000); // Every 30 seconds
765
 
766
- server.listen(port, () => {
767
- console.log(`Server running on port ${port}`);
768
  });
769
 
770
- module.exports = app;
 
1
+ import express from "express";
2
+ import http from "http";
3
+ import mediasoup from "mediasoup";
 
 
 
 
 
 
 
 
 
 
4
 
5
  const app = express();
 
 
 
 
 
 
 
 
 
 
 
6
  app.use(express.json());
7
 
8
+ const worker = await mediasoup.createWorker();
9
+ const router = await worker.createRouter({
10
+ mediaCodecs: [{
11
+ kind: "video",
12
+ mimeType: "video/H264",
13
+ clockRate: 90000,
14
+ parameters: { "packetization-mode": 1, "profile-level-id": "42e01f" }
15
+ }]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  });
17
 
18
+ let producer;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ app.post("/whip", async (req, res) => {
21
+ const transport = await router.createWebRtcTransport({
22
+ listenIps: [{ ip: "0.0.0.0", announcedIp: null }],
23
+ enableUdp: true, enableTcp: true, preferUdp: true
24
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ const sdp = req.body.sdp;
 
 
 
 
27
 
28
+ await transport.connect({ dtlsParameters: sdp.dtlsParameters });
29
+ producer = await transport.produce({
30
+ kind: "video",
31
+ rtpParameters: sdp.rtpParameters
32
+ });
33
 
34
+ res.json({ ok: true });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  });
36
 
37
+ app.get("/whep", async (req, res) => {
38
+ if (!producer) return res.status(404).send("No stream");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ const transport = await router.createWebRtcTransport({
41
+ listenIps: [{ ip: "0.0.0.0", announcedIp: null }],
42
+ enableUdp: true, enableTcp: true, preferUdp: true
43
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ const consumer = await transport.consume({
46
+ producerId: producer.id,
47
+ rtpCapabilities: router.rtpCapabilities,
48
+ paused: false
49
+ });
 
 
 
 
 
 
 
 
50
 
51
+ res.json({ consumer });
 
52
  });
53
 
54
+ http.createServer(app).listen(3000);