Spaces:
Paused
Paused
Update server.js
Browse files
server.js
CHANGED
|
@@ -9,10 +9,17 @@ const { getPool, initializeDatabase, closePool } = require('./db');
|
|
| 9 |
const otpService = require('./otpService');
|
| 10 |
const axios = require('axios');
|
| 11 |
const http = require('http');
|
|
|
|
| 12 |
const fs = require('fs');
|
| 13 |
|
| 14 |
const app = express();
|
| 15 |
const server = http.createServer(app);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
const port = process.env.PORT || 3000;
|
| 17 |
|
| 18 |
// Initialize database and start server
|
|
@@ -37,133 +44,13 @@ const port = process.env.PORT || 3000;
|
|
| 37 |
})();
|
| 38 |
|
| 39 |
// Middleware
|
| 40 |
-
app.use(cors(
|
| 41 |
-
origin: "*",
|
| 42 |
-
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
|
| 43 |
-
allowedHeaders: [
|
| 44 |
-
"Content-Type",
|
| 45 |
-
"Authorization",
|
| 46 |
-
"X-Requested-With",
|
| 47 |
-
"Accept",
|
| 48 |
-
"Origin",
|
| 49 |
-
"x-otp-token",
|
| 50 |
-
"x-user-email",
|
| 51 |
-
"x-user-id"
|
| 52 |
-
],
|
| 53 |
-
credentials: true,
|
| 54 |
-
preflightContinue: false,
|
| 55 |
-
optionsSuccessStatus: 204
|
| 56 |
-
}));
|
| 57 |
app.use(express.json());
|
| 58 |
app.use(express.static('public'));
|
| 59 |
|
| 60 |
-
// Global CORS preflight handler
|
| 61 |
-
app.options('*', cors());
|
| 62 |
-
|
| 63 |
// Store logs in memory (in production, use a database)
|
| 64 |
let serverLogs = [];
|
| 65 |
|
| 66 |
-
// Message cache for better performance
|
| 67 |
-
let messageCache = new Map(); // userId -> { messages: [], lastUpdated: timestamp }
|
| 68 |
-
const CACHE_TTL = 30000; // 30 seconds
|
| 69 |
-
|
| 70 |
-
// Event Stream clients management
|
| 71 |
-
let eventStreamClients = new Map(); // userId -> Set of response objects
|
| 72 |
-
let adminClients = new Set(); // Set of admin response objects
|
| 73 |
-
|
| 74 |
-
// Cache management functions
|
| 75 |
-
function getCachedMessages(userId) {
|
| 76 |
-
const cached = messageCache.get(userId);
|
| 77 |
-
if (cached && (Date.now() - cached.lastUpdated) < CACHE_TTL) {
|
| 78 |
-
return cached.messages;
|
| 79 |
-
}
|
| 80 |
-
return null;
|
| 81 |
-
}
|
| 82 |
-
|
| 83 |
-
function setCachedMessages(userId, messages) {
|
| 84 |
-
messageCache.set(userId, {
|
| 85 |
-
messages: messages,
|
| 86 |
-
lastUpdated: Date.now()
|
| 87 |
-
});
|
| 88 |
-
}
|
| 89 |
-
|
| 90 |
-
function invalidateUserCache(userId) {
|
| 91 |
-
messageCache.delete(userId);
|
| 92 |
-
}
|
| 93 |
-
|
| 94 |
-
// Event Stream management functions
|
| 95 |
-
function addEventStreamClient(userId, res) {
|
| 96 |
-
if (!eventStreamClients.has(userId)) {
|
| 97 |
-
eventStreamClients.set(userId, new Set());
|
| 98 |
-
}
|
| 99 |
-
eventStreamClients.get(userId).add(res);
|
| 100 |
-
|
| 101 |
-
// Set up connection cleanup
|
| 102 |
-
res.on('close', () => {
|
| 103 |
-
removeEventStreamClient(userId, res);
|
| 104 |
-
});
|
| 105 |
-
}
|
| 106 |
-
|
| 107 |
-
function removeEventStreamClient(userId, res) {
|
| 108 |
-
const clients = eventStreamClients.get(userId);
|
| 109 |
-
if (clients) {
|
| 110 |
-
clients.delete(res);
|
| 111 |
-
if (clients.size === 0) {
|
| 112 |
-
eventStreamClients.delete(userId);
|
| 113 |
-
}
|
| 114 |
-
}
|
| 115 |
-
}
|
| 116 |
-
|
| 117 |
-
function addAdminClient(res) {
|
| 118 |
-
adminClients.add(res);
|
| 119 |
-
|
| 120 |
-
// Set up connection cleanup
|
| 121 |
-
res.on('close', () => {
|
| 122 |
-
adminClients.delete(res);
|
| 123 |
-
});
|
| 124 |
-
}
|
| 125 |
-
|
| 126 |
-
function broadcastToUser(userId, event, data) {
|
| 127 |
-
const clients = eventStreamClients.get(userId);
|
| 128 |
-
if (clients) {
|
| 129 |
-
const message = `data: ${JSON.stringify({ event, data, timestamp: new Date().toISOString() })}\n\n`;
|
| 130 |
-
clients.forEach(client => {
|
| 131 |
-
if (!client.destroyed) {
|
| 132 |
-
client.write(message);
|
| 133 |
-
}
|
| 134 |
-
});
|
| 135 |
-
}
|
| 136 |
-
}
|
| 137 |
-
|
| 138 |
-
function broadcastToAdmins(event, data) {
|
| 139 |
-
const message = `data: ${JSON.stringify({ event, data, timestamp: new Date().toISOString() })}\n\n`;
|
| 140 |
-
adminClients.forEach(client => {
|
| 141 |
-
if (!client.destroyed) {
|
| 142 |
-
client.write(message);
|
| 143 |
-
}
|
| 144 |
-
});
|
| 145 |
-
}
|
| 146 |
-
|
| 147 |
-
function broadcastToAll(event, data) {
|
| 148 |
-
const message = `data: ${JSON.stringify({ event, data, timestamp: new Date().toISOString() })}\n\n`;
|
| 149 |
-
|
| 150 |
-
// Broadcast to all user clients
|
| 151 |
-
eventStreamClients.forEach((clients, userId) => {
|
| 152 |
-
clients.forEach(client => {
|
| 153 |
-
if (!client.destroyed) {
|
| 154 |
-
client.write(message);
|
| 155 |
-
}
|
| 156 |
-
});
|
| 157 |
-
});
|
| 158 |
-
|
| 159 |
-
// Broadcast to admin clients
|
| 160 |
-
adminClients.forEach(client => {
|
| 161 |
-
if (!client.destroyed) {
|
| 162 |
-
client.write(message);
|
| 163 |
-
}
|
| 164 |
-
});
|
| 165 |
-
}
|
| 166 |
-
|
| 167 |
// Logging middleware
|
| 168 |
function logRequest(req, res, next) {
|
| 169 |
const start = Date.now();
|
|
@@ -212,22 +99,6 @@ function logRequest(req, res, next) {
|
|
| 212 |
// Apply logging middleware
|
| 213 |
app.use(logRequest);
|
| 214 |
|
| 215 |
-
// CORS headers middleware for all responses
|
| 216 |
-
app.use((req, res, next) => {
|
| 217 |
-
res.header('Access-Control-Allow-Origin', '*');
|
| 218 |
-
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH');
|
| 219 |
-
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin, x-otp-token, x-user-email, x-user-id');
|
| 220 |
-
res.header('Access-Control-Allow-Credentials', 'true');
|
| 221 |
-
|
| 222 |
-
// Handle preflight requests
|
| 223 |
-
if (req.method === 'OPTIONS') {
|
| 224 |
-
res.status(204).end();
|
| 225 |
-
return;
|
| 226 |
-
}
|
| 227 |
-
|
| 228 |
-
next();
|
| 229 |
-
});
|
| 230 |
-
|
| 231 |
// Emit log to all connected clients
|
| 232 |
function emitLog(logData) {
|
| 233 |
serverLogs.unshift(logData);
|
|
@@ -237,8 +108,7 @@ function emitLog(logData) {
|
|
| 237 |
serverLogs = serverLogs.slice(0, 1000);
|
| 238 |
}
|
| 239 |
|
| 240 |
-
|
| 241 |
-
broadcastToAdmins('server-log', logData);
|
| 242 |
}
|
| 243 |
|
| 244 |
// Manual logging function
|
|
@@ -649,13 +519,10 @@ app.post('/api/upload', async (req, res) => {
|
|
| 649 |
}
|
| 650 |
});
|
| 651 |
|
| 652 |
-
// Get chat messages
|
| 653 |
app.get('/api/messages/:userId', checkOtpAuth, async (req, res) => {
|
| 654 |
const { userId } = req.params;
|
| 655 |
const userEmail = req.headers['x-user-email'];
|
| 656 |
-
const page = parseInt(req.query.page) || 1;
|
| 657 |
-
const limit = parseInt(req.query.limit) || 50;
|
| 658 |
-
const offset = (page - 1) * limit;
|
| 659 |
|
| 660 |
try {
|
| 661 |
// Verify that the user is requesting their own messages
|
|
@@ -664,60 +531,18 @@ app.get('/api/messages/:userId', checkOtpAuth, async (req, res) => {
|
|
| 664 |
return res.status(403).json({ success: false, error: 'Unauthorized access' });
|
| 665 |
}
|
| 666 |
|
| 667 |
-
// Check cache first for first page
|
| 668 |
-
const cachedMessages = getCachedMessages(userId);
|
| 669 |
-
if (cachedMessages && page === 1 && limit <= 50) {
|
| 670 |
-
const paginatedMessages = cachedMessages.slice(0, limit);
|
| 671 |
-
return res.json({
|
| 672 |
-
success: true,
|
| 673 |
-
messages: paginatedMessages,
|
| 674 |
-
pagination: {
|
| 675 |
-
page: 1,
|
| 676 |
-
limit: limit,
|
| 677 |
-
total: cachedMessages.length,
|
| 678 |
-
totalPages: Math.ceil(cachedMessages.length / limit)
|
| 679 |
-
},
|
| 680 |
-
cached: true
|
| 681 |
-
});
|
| 682 |
-
}
|
| 683 |
-
|
| 684 |
-
// Get total count for pagination
|
| 685 |
-
const countResult = await getPool().query(
|
| 686 |
-
'SELECT COUNT(*) FROM messages WHERE user_id = $1',
|
| 687 |
-
[userId]
|
| 688 |
-
);
|
| 689 |
-
const totalMessages = parseInt(countResult.rows[0].count);
|
| 690 |
-
|
| 691 |
-
// Get paginated messages
|
| 692 |
const result = await getPool().query(
|
| 693 |
-
'SELECT * FROM messages WHERE user_id = $1 ORDER BY created_at
|
| 694 |
-
[userId
|
| 695 |
);
|
| 696 |
-
|
| 697 |
-
const messages = result.rows.reverse(); // Reverse to maintain chronological order
|
| 698 |
-
|
| 699 |
-
// Cache the results for first page
|
| 700 |
-
if (page === 1 && limit <= 50) {
|
| 701 |
-
setCachedMessages(userId, messages);
|
| 702 |
-
}
|
| 703 |
-
|
| 704 |
-
res.json({
|
| 705 |
-
success: true,
|
| 706 |
-
messages: messages,
|
| 707 |
-
pagination: {
|
| 708 |
-
page,
|
| 709 |
-
limit,
|
| 710 |
-
total: totalMessages,
|
| 711 |
-
totalPages: Math.ceil(totalMessages / limit)
|
| 712 |
-
}
|
| 713 |
-
});
|
| 714 |
} catch (error) {
|
| 715 |
console.error('Error fetching messages:', error);
|
| 716 |
res.status(500).json({ success: false, error: 'Failed to fetch messages' });
|
| 717 |
}
|
| 718 |
});
|
| 719 |
|
| 720 |
-
// Send message
|
| 721 |
app.post('/api/messages', checkOtpAuth, async (req, res) => {
|
| 722 |
const { userId, content, sender } = req.body;
|
| 723 |
const userEmail = req.headers['x-user-email'];
|
|
@@ -737,200 +562,13 @@ app.post('/api/messages', checkOtpAuth, async (req, res) => {
|
|
| 737 |
'INSERT INTO messages (user_id, content, sender) VALUES ($1, $2, $3) RETURNING *',
|
| 738 |
[userId, content, sender]
|
| 739 |
);
|
| 740 |
-
|
| 741 |
-
const newMessage = result.rows[0];
|
| 742 |
-
|
| 743 |
-
// Invalidate cache for this user
|
| 744 |
-
invalidateUserCache(userId);
|
| 745 |
-
|
| 746 |
-
// Emit real-time update to chat room
|
| 747 |
-
broadcastToUser(userId, 'new-message', {
|
| 748 |
-
message: newMessage,
|
| 749 |
-
userEmail: userEmail
|
| 750 |
-
});
|
| 751 |
-
|
| 752 |
-
// Emit message sent confirmation
|
| 753 |
-
broadcastToUser(userId, 'message-sent', {
|
| 754 |
-
messageId: newMessage.id,
|
| 755 |
-
userId: userId,
|
| 756 |
-
timestamp: new Date().toISOString()
|
| 757 |
-
});
|
| 758 |
-
|
| 759 |
-
log('info', 'Message sent and saved to database', {
|
| 760 |
-
messageId: newMessage.id,
|
| 761 |
-
userId: userId,
|
| 762 |
-
sender: sender,
|
| 763 |
-
contentLength: content.length
|
| 764 |
-
});
|
| 765 |
-
|
| 766 |
-
res.json({ success: true, message: newMessage });
|
| 767 |
} catch (error) {
|
| 768 |
console.error('Error sending message:', error);
|
| 769 |
-
|
| 770 |
-
// Emit error to client
|
| 771 |
-
broadcastToUser(userId, 'message-error', {
|
| 772 |
-
error: 'Failed to send message',
|
| 773 |
-
userId: userId
|
| 774 |
-
});
|
| 775 |
-
|
| 776 |
res.status(500).json({ success: false, error: 'Failed to send message' });
|
| 777 |
}
|
| 778 |
});
|
| 779 |
|
| 780 |
-
// Check if submission is open (Sunday 9am-9pm)
|
| 781 |
-
app.get('/isubmissionopen', (req, res) => {
|
| 782 |
-
const now = new Date();
|
| 783 |
-
const dayOfWeek = now.getDay(); // 0 = Sunday, 1 = Monday, ..., 6 = Saturday
|
| 784 |
-
const hour = now.getHours();
|
| 785 |
-
|
| 786 |
-
// Check if it's Sunday (dayOfWeek === 0) and between 9am (9) and 9pm (21)
|
| 787 |
-
const isSubmissionOpen = dayOfWeek === 0 && hour >= 9 && hour < 21;
|
| 788 |
-
|
| 789 |
-
log('info', 'Submission status checked', {
|
| 790 |
-
dayOfWeek: dayOfWeek,
|
| 791 |
-
hour: hour,
|
| 792 |
-
isOpen: isSubmissionOpen,
|
| 793 |
-
ip: req.ip
|
| 794 |
-
});
|
| 795 |
-
|
| 796 |
-
res.json({
|
| 797 |
-
success: true,
|
| 798 |
-
isSubmissionOpen: isSubmissionOpen
|
| 799 |
-
});
|
| 800 |
-
});
|
| 801 |
-
|
| 802 |
-
// Event Stream endpoints
|
| 803 |
-
app.get('/events/user/:userId', checkOtpAuth, (req, res) => {
|
| 804 |
-
const { userId } = req.params;
|
| 805 |
-
const userEmail = req.headers['x-user-email'];
|
| 806 |
-
|
| 807 |
-
// Verify that the user is requesting their own events
|
| 808 |
-
if (parseInt(userId) !== parseInt(req.headers['x-user-id'])) {
|
| 809 |
-
return res.status(403).json({ success: false, error: 'Unauthorized access' });
|
| 810 |
-
}
|
| 811 |
-
|
| 812 |
-
// Set up Event Stream headers
|
| 813 |
-
res.writeHead(200, {
|
| 814 |
-
'Content-Type': 'text/event-stream',
|
| 815 |
-
'Cache-Control': 'no-cache',
|
| 816 |
-
'Connection': 'keep-alive',
|
| 817 |
-
'Access-Control-Allow-Origin': '*',
|
| 818 |
-
'Access-Control-Allow-Headers': 'Cache-Control'
|
| 819 |
-
});
|
| 820 |
-
|
| 821 |
-
// Send initial connection message
|
| 822 |
-
res.write(`data: ${JSON.stringify({
|
| 823 |
-
event: 'connected',
|
| 824 |
-
data: { userId, userEmail, timestamp: new Date().toISOString() }
|
| 825 |
-
})}\n\n`);
|
| 826 |
-
|
| 827 |
-
// Add client to event stream
|
| 828 |
-
addEventStreamClient(userId, res);
|
| 829 |
-
|
| 830 |
-
log('info', 'User connected to event stream', { userId, userEmail });
|
| 831 |
-
});
|
| 832 |
-
|
| 833 |
-
app.get('/events/admin', (req, res) => {
|
| 834 |
-
// Set up Event Stream headers
|
| 835 |
-
res.writeHead(200, {
|
| 836 |
-
'Content-Type': 'text/event-stream',
|
| 837 |
-
'Cache-Control': 'no-cache',
|
| 838 |
-
'Connection': 'keep-alive',
|
| 839 |
-
'Access-Control-Allow-Origin': '*',
|
| 840 |
-
'Access-Control-Allow-Headers': 'Cache-Control'
|
| 841 |
-
});
|
| 842 |
-
|
| 843 |
-
// Send initial connection message
|
| 844 |
-
res.write(`data: ${JSON.stringify({
|
| 845 |
-
event: 'connected',
|
| 846 |
-
data: { type: 'admin', timestamp: new Date().toISOString() }
|
| 847 |
-
})}\n\n`);
|
| 848 |
-
|
| 849 |
-
// Send existing logs
|
| 850 |
-
const recentLogs = serverLogs.slice(0, 100);
|
| 851 |
-
res.write(`data: ${JSON.stringify({
|
| 852 |
-
event: 'historical-logs',
|
| 853 |
-
data: recentLogs
|
| 854 |
-
})}\n\n`);
|
| 855 |
-
|
| 856 |
-
// Add client to admin event stream
|
| 857 |
-
addAdminClient(res);
|
| 858 |
-
|
| 859 |
-
log('info', 'Admin connected to event stream');
|
| 860 |
-
});
|
| 861 |
-
|
| 862 |
-
// Typing indicator endpoints
|
| 863 |
-
app.post('/api/typing', checkOtpAuth, (req, res) => {
|
| 864 |
-
const { userId } = req.body;
|
| 865 |
-
const userEmail = req.headers['x-user-email'];
|
| 866 |
-
|
| 867 |
-
if (!userId) {
|
| 868 |
-
return res.status(400).json({ success: false, error: 'User ID required' });
|
| 869 |
-
}
|
| 870 |
-
|
| 871 |
-
// Broadcast typing indicator to other users in the chat
|
| 872 |
-
broadcastToUser(userId, 'user-typing', {
|
| 873 |
-
userId: userId,
|
| 874 |
-
userEmail: userEmail,
|
| 875 |
-
timestamp: new Date().toISOString()
|
| 876 |
-
});
|
| 877 |
-
|
| 878 |
-
res.json({ success: true });
|
| 879 |
-
});
|
| 880 |
-
|
| 881 |
-
app.post('/api/stop-typing', checkOtpAuth, (req, res) => {
|
| 882 |
-
const { userId } = req.body;
|
| 883 |
-
const userEmail = req.headers['x-user-email'];
|
| 884 |
-
|
| 885 |
-
if (!userId) {
|
| 886 |
-
return res.status(400).json({ success: false, error: 'User ID required' });
|
| 887 |
-
}
|
| 888 |
-
|
| 889 |
-
// Broadcast stop typing indicator
|
| 890 |
-
broadcastToUser(userId, 'user-stopped-typing', {
|
| 891 |
-
userId: userId,
|
| 892 |
-
userEmail: userEmail,
|
| 893 |
-
timestamp: new Date().toISOString()
|
| 894 |
-
});
|
| 895 |
-
|
| 896 |
-
res.json({ success: true });
|
| 897 |
-
});
|
| 898 |
-
|
| 899 |
-
// Admin typing indicator endpoints
|
| 900 |
-
app.post('/api/admin/typing', (req, res) => {
|
| 901 |
-
const { userId } = req.body;
|
| 902 |
-
|
| 903 |
-
if (!userId) {
|
| 904 |
-
return res.status(400).json({ success: false, error: 'User ID required' });
|
| 905 |
-
}
|
| 906 |
-
|
| 907 |
-
// Broadcast typing indicator to user
|
| 908 |
-
broadcastToUser(userId, 'user-typing', {
|
| 909 |
-
userId: userId,
|
| 910 |
-
userEmail: 'admin',
|
| 911 |
-
timestamp: new Date().toISOString()
|
| 912 |
-
});
|
| 913 |
-
|
| 914 |
-
res.json({ success: true });
|
| 915 |
-
});
|
| 916 |
-
|
| 917 |
-
app.post('/api/admin/stop-typing', (req, res) => {
|
| 918 |
-
const { userId } = req.body;
|
| 919 |
-
|
| 920 |
-
if (!userId) {
|
| 921 |
-
return res.status(400).json({ success: false, error: 'User ID required' });
|
| 922 |
-
}
|
| 923 |
-
|
| 924 |
-
// Broadcast stop typing indicator
|
| 925 |
-
broadcastToUser(userId, 'user-stopped-typing', {
|
| 926 |
-
userId: userId,
|
| 927 |
-
userEmail: 'admin',
|
| 928 |
-
timestamp: new Date().toISOString()
|
| 929 |
-
});
|
| 930 |
-
|
| 931 |
-
res.json({ success: true });
|
| 932 |
-
});
|
| 933 |
-
|
| 934 |
// Admin routes
|
| 935 |
app.get('/api/admin/users', async (req, res) => {
|
| 936 |
try {
|
|
@@ -974,45 +612,13 @@ app.get('/api/admin/messages/:userId', async (req, res) => {
|
|
| 974 |
app.post('/api/admin/messages', async (req, res) => {
|
| 975 |
try {
|
| 976 |
const { userId, content } = req.body;
|
| 977 |
-
|
| 978 |
-
'INSERT INTO messages (user_id, content, sender) VALUES ($1, $2, $3)
|
| 979 |
[userId, content, 'admin']
|
| 980 |
);
|
| 981 |
-
|
| 982 |
-
const newMessage = result.rows[0];
|
| 983 |
-
|
| 984 |
-
// Invalidate cache for this user
|
| 985 |
-
invalidateUserCache(userId);
|
| 986 |
-
|
| 987 |
-
// Emit real-time update to chat room
|
| 988 |
-
broadcastToUser(userId, 'new-message', {
|
| 989 |
-
message: newMessage,
|
| 990 |
-
userEmail: 'admin'
|
| 991 |
-
});
|
| 992 |
-
|
| 993 |
-
// Emit message sent confirmation
|
| 994 |
-
broadcastToUser(userId, 'message-sent', {
|
| 995 |
-
messageId: newMessage.id,
|
| 996 |
-
userId: userId,
|
| 997 |
-
timestamp: new Date().toISOString()
|
| 998 |
-
});
|
| 999 |
-
|
| 1000 |
-
log('info', 'Admin message sent and saved to database', {
|
| 1001 |
-
messageId: newMessage.id,
|
| 1002 |
-
userId: userId,
|
| 1003 |
-
contentLength: content.length
|
| 1004 |
-
});
|
| 1005 |
-
|
| 1006 |
-
res.json({ success: true, message: newMessage });
|
| 1007 |
} catch (error) {
|
| 1008 |
-
console.error('Error sending
|
| 1009 |
-
|
| 1010 |
-
// Emit error to client
|
| 1011 |
-
broadcastToUser(userId, 'message-error', {
|
| 1012 |
-
error: 'Failed to send message',
|
| 1013 |
-
userId: userId
|
| 1014 |
-
});
|
| 1015 |
-
|
| 1016 |
res.status(500).json({ success: false, error: 'Failed to send message' });
|
| 1017 |
}
|
| 1018 |
});
|
|
@@ -1139,6 +745,63 @@ app.get('/api/admin/submissions/:submissionId', async (req, res) => {
|
|
| 1139 |
}
|
| 1140 |
});
|
| 1141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1142 |
// Error handling
|
| 1143 |
process.on('uncaughtException', (error) => {
|
| 1144 |
log('error', 'Uncaught Exception', {
|
|
@@ -1157,41 +820,15 @@ process.on('unhandledRejection', (reason, promise) => {
|
|
| 1157 |
// Periodic system logs
|
| 1158 |
setInterval(() => {
|
| 1159 |
const memoryUsage = process.memoryUsage();
|
| 1160 |
-
|
| 1161 |
memory: {
|
| 1162 |
rss: Math.round(memoryUsage.rss / 1024 / 1024) + 'MB',
|
| 1163 |
heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024) + 'MB',
|
| 1164 |
heapTotal: Math.round(memoryUsage.heapTotal / 1024 / 1024) + 'MB'
|
| 1165 |
},
|
| 1166 |
uptime: Math.round(process.uptime()) + 's',
|
| 1167 |
-
connections:
|
| 1168 |
-
|
| 1169 |
-
};
|
| 1170 |
-
|
| 1171 |
-
log('info', 'System status', systemStatus);
|
| 1172 |
-
|
| 1173 |
-
// Broadcast system status to admin clients
|
| 1174 |
-
broadcastToAdmins('system-status', systemStatus);
|
| 1175 |
}, 30000); // Every 30 seconds
|
| 1176 |
|
| 1177 |
-
// Periodic cache cleanup
|
| 1178 |
-
setInterval(() => {
|
| 1179 |
-
const now = Date.now();
|
| 1180 |
-
let cleanedCount = 0;
|
| 1181 |
-
|
| 1182 |
-
for (const [userId, cacheData] of messageCache.entries()) {
|
| 1183 |
-
if (now - cacheData.lastUpdated > CACHE_TTL) {
|
| 1184 |
-
messageCache.delete(userId);
|
| 1185 |
-
cleanedCount++;
|
| 1186 |
-
}
|
| 1187 |
-
}
|
| 1188 |
-
|
| 1189 |
-
if (cleanedCount > 0) {
|
| 1190 |
-
log('info', 'Cache cleanup completed', {
|
| 1191 |
-
cleanedCount: cleanedCount,
|
| 1192 |
-
remainingCacheSize: messageCache.size
|
| 1193 |
-
});
|
| 1194 |
-
}
|
| 1195 |
-
}, 60000); // Every minute
|
| 1196 |
-
|
| 1197 |
module.exports = app;
|
|
|
|
| 9 |
const otpService = require('./otpService');
|
| 10 |
const axios = require('axios');
|
| 11 |
const http = require('http');
|
| 12 |
+
const socketIo = require('socket.io');
|
| 13 |
const fs = require('fs');
|
| 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 = process.env.PORT || 3000;
|
| 24 |
|
| 25 |
// Initialize database and start server
|
|
|
|
| 44 |
})();
|
| 45 |
|
| 46 |
// Middleware
|
| 47 |
+
app.use(cors());
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
app.use(express.json());
|
| 49 |
app.use(express.static('public'));
|
| 50 |
|
|
|
|
|
|
|
|
|
|
| 51 |
// Store logs in memory (in production, use a database)
|
| 52 |
let serverLogs = [];
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
// Logging middleware
|
| 55 |
function logRequest(req, res, next) {
|
| 56 |
const start = Date.now();
|
|
|
|
| 99 |
// Apply logging middleware
|
| 100 |
app.use(logRequest);
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
// Emit log to all connected clients
|
| 103 |
function emitLog(logData) {
|
| 104 |
serverLogs.unshift(logData);
|
|
|
|
| 108 |
serverLogs = serverLogs.slice(0, 1000);
|
| 109 |
}
|
| 110 |
|
| 111 |
+
io.emit('server-log', logData);
|
|
|
|
| 112 |
}
|
| 113 |
|
| 114 |
// Manual logging function
|
|
|
|
| 519 |
}
|
| 520 |
});
|
| 521 |
|
| 522 |
+
// Get chat messages
|
| 523 |
app.get('/api/messages/:userId', checkOtpAuth, async (req, res) => {
|
| 524 |
const { userId } = req.params;
|
| 525 |
const userEmail = req.headers['x-user-email'];
|
|
|
|
|
|
|
|
|
|
| 526 |
|
| 527 |
try {
|
| 528 |
// Verify that the user is requesting their own messages
|
|
|
|
| 531 |
return res.status(403).json({ success: false, error: 'Unauthorized access' });
|
| 532 |
}
|
| 533 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 534 |
const result = await getPool().query(
|
| 535 |
+
'SELECT * FROM messages WHERE user_id = $1 ORDER BY created_at ASC',
|
| 536 |
+
[userId]
|
| 537 |
);
|
| 538 |
+
res.json({ success: true, messages: result.rows });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 539 |
} catch (error) {
|
| 540 |
console.error('Error fetching messages:', error);
|
| 541 |
res.status(500).json({ success: false, error: 'Failed to fetch messages' });
|
| 542 |
}
|
| 543 |
});
|
| 544 |
|
| 545 |
+
// Send message
|
| 546 |
app.post('/api/messages', checkOtpAuth, async (req, res) => {
|
| 547 |
const { userId, content, sender } = req.body;
|
| 548 |
const userEmail = req.headers['x-user-email'];
|
|
|
|
| 562 |
'INSERT INTO messages (user_id, content, sender) VALUES ($1, $2, $3) RETURNING *',
|
| 563 |
[userId, content, sender]
|
| 564 |
);
|
| 565 |
+
res.json({ success: true, message: result.rows[0] });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
} catch (error) {
|
| 567 |
console.error('Error sending message:', error);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
res.status(500).json({ success: false, error: 'Failed to send message' });
|
| 569 |
}
|
| 570 |
});
|
| 571 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 572 |
// Admin routes
|
| 573 |
app.get('/api/admin/users', async (req, res) => {
|
| 574 |
try {
|
|
|
|
| 612 |
app.post('/api/admin/messages', async (req, res) => {
|
| 613 |
try {
|
| 614 |
const { userId, content } = req.body;
|
| 615 |
+
await getPool().query(
|
| 616 |
+
'INSERT INTO messages (user_id, content, sender) VALUES ($1, $2, $3)',
|
| 617 |
[userId, content, 'admin']
|
| 618 |
);
|
| 619 |
+
res.json({ success: true });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 620 |
} catch (error) {
|
| 621 |
+
console.error('Error sending message:', error);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
res.status(500).json({ success: false, error: 'Failed to send message' });
|
| 623 |
}
|
| 624 |
});
|
|
|
|
| 745 |
}
|
| 746 |
});
|
| 747 |
|
| 748 |
+
// Check if submission is open (Sunday 9am-9pm)
|
| 749 |
+
app.get('/isubmissionopen', (req, res) => {
|
| 750 |
+
const now = new Date();
|
| 751 |
+
const dayOfWeek = now.getDay(); // 0 = Sunday, 1 = Monday, ..., 6 = Saturday
|
| 752 |
+
const hour = now.getHours();
|
| 753 |
+
|
| 754 |
+
// Check if it's Sunday (day 0) and between 9am (9) and 9pm (21)
|
| 755 |
+
const isSubmissionOpen = dayOfWeek === 0 && hour >= 9 && hour < 21;
|
| 756 |
+
|
| 757 |
+
log('info', 'Submission status checked', {
|
| 758 |
+
dayOfWeek: dayOfWeek,
|
| 759 |
+
hour: hour,
|
| 760 |
+
isOpen: isSubmissionOpen,
|
| 761 |
+
ip: req.ip
|
| 762 |
+
});
|
| 763 |
+
|
| 764 |
+
res.json({
|
| 765 |
+
success: true,
|
| 766 |
+
isSubmissionOpen: isSubmissionOpen,
|
| 767 |
+
currentTime: now.toISOString(),
|
| 768 |
+
dayOfWeek: dayOfWeek,
|
| 769 |
+
hour: hour
|
| 770 |
+
});
|
| 771 |
+
});
|
| 772 |
+
|
| 773 |
+
// Socket.IO connection handling
|
| 774 |
+
io.on('connection', (socket) => {
|
| 775 |
+
log('info', 'Client connected to server logs', {
|
| 776 |
+
socketId: socket.id,
|
| 777 |
+
totalConnections: io.engine.clientsCount
|
| 778 |
+
});
|
| 779 |
+
|
| 780 |
+
// Send existing logs to new client
|
| 781 |
+
socket.emit('server-log', {
|
| 782 |
+
type: 'info',
|
| 783 |
+
message: 'Connected to server logs',
|
| 784 |
+
details: {
|
| 785 |
+
socketId: socket.id,
|
| 786 |
+
totalLogs: serverLogs.length
|
| 787 |
+
}
|
| 788 |
+
});
|
| 789 |
+
|
| 790 |
+
socket.on('disconnect', () => {
|
| 791 |
+
log('info', 'Client disconnected from server logs', {
|
| 792 |
+
socketId: socket.id,
|
| 793 |
+
totalConnections: io.engine.clientsCount
|
| 794 |
+
});
|
| 795 |
+
});
|
| 796 |
+
|
| 797 |
+
socket.on('request-logs', () => {
|
| 798 |
+
log('info', 'Client requested historical logs', { socketId: socket.id });
|
| 799 |
+
// Send last 100 logs
|
| 800 |
+
const recentLogs = serverLogs.slice(0, 100);
|
| 801 |
+
socket.emit('historical-logs', recentLogs);
|
| 802 |
+
});
|
| 803 |
+
});
|
| 804 |
+
|
| 805 |
// Error handling
|
| 806 |
process.on('uncaughtException', (error) => {
|
| 807 |
log('error', 'Uncaught Exception', {
|
|
|
|
| 820 |
// Periodic system logs
|
| 821 |
setInterval(() => {
|
| 822 |
const memoryUsage = process.memoryUsage();
|
| 823 |
+
log('info', 'System status', {
|
| 824 |
memory: {
|
| 825 |
rss: Math.round(memoryUsage.rss / 1024 / 1024) + 'MB',
|
| 826 |
heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024) + 'MB',
|
| 827 |
heapTotal: Math.round(memoryUsage.heapTotal / 1024 / 1024) + 'MB'
|
| 828 |
},
|
| 829 |
uptime: Math.round(process.uptime()) + 's',
|
| 830 |
+
connections: io.engine.clientsCount
|
| 831 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 832 |
}, 30000); // Every 30 seconds
|
| 833 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 834 |
module.exports = app;
|