live updates

This commit is contained in:
2026-01-29 02:16:24 -05:00
parent 864cbaece9
commit efa1ea3b45
12 changed files with 423 additions and 69 deletions

View File

@@ -15,6 +15,7 @@
"dotenv": "^16.4.5",
"cors": "^2.8.5",
"node-fetch": "^3.3.2",
"express-rate-limit": "^7.1.5"
"express-rate-limit": "^7.1.5",
"socket.io": "^4.6.1"
}
}

View File

@@ -4,10 +4,12 @@ import dotenv from 'dotenv';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import { createServer } from 'http';
import rateLimit from 'express-rate-limit';
import { initDB } from './db/index.js';
import { validateConfig, config } from './config.js';
import { errorHandler } from './middleware/errorHandler.js';
import { initializeSocket } from './sockets/index.js';
import authRoutes from './routes/auth.js';
import challengeRoutes from './routes/challenges.js';
import predictionRoutes from './routes/predictions.js';
@@ -24,6 +26,10 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const httpServer = createServer(app);
// Initialize Socket.io
initializeSocket(httpServer);
// Rate limiting
const authLimiter = rateLimit({
@@ -96,8 +102,9 @@ const PORT = config.server.port;
// Initialize database and start server
initDB()
.then(() => {
app.listen(PORT, '0.0.0.0', () => {
httpServer.listen(PORT, '0.0.0.0', () => {
console.log(`✅ Server running on port ${PORT}`);
console.log(`🔌 Socket.io ready for real-time updates`);
});
})
.catch(err => {

View File

@@ -2,6 +2,7 @@ import express from 'express';
import { query } from '../db/index.js';
import { authMiddleware } from '../middleware/auth.js';
import { asyncHandler, AppError } from '../middleware/errorHandler.js';
import { socketEvents } from '../sockets/index.js';
const router = express.Router();
@@ -147,46 +148,49 @@ router.post('/:id/invite', authMiddleware, asyncHandler(async (req, res) => {
[challengeId, userId]
);
invitedUsers.push(userId);
// Emit real-time notification to invited user
socketEvents.challengeInvitation(userId, {
challenge_id: challengeId,
challenge_title: challenge.title,
invited_by: req.user.username
});
} catch (err) {
// Ignore duplicate key errors
}
}
}
// Invite by emails
if (emails && Array.isArray(emails)) {
for (const email of emails) {
const users = await query('SELECT id FROM users WHERE email = ?', [email]);
if (users.length > 0) {
try {
await query(
'INSERT INTO challenge_participants (challenge_id, user_id, status) VALUES (?, ?, "pending")',
[challengeId, users[0].id]
);
invitedUsers.push(users[0].id);
// Emit real-time notification to invited user
socketEvents.challengeInvitation(users[0].id, {
challenge_id: challengeId,
challenge_title: challenge.title,
invited_by: req.user.username
});
} catch (err) {
// Ignore duplicate key errors
}
}
}
// Invite by emails
if (emails && Array.isArray(emails)) {
for (const email of emails) {
const users = await query('SELECT id FROM users WHERE email = ?', [email]);
if (users.length > 0) {
try {
await query(
'INSERT INTO challenge_participants (challenge_id, user_id, status) VALUES (?, ?, "pending")',
[challengeId, users[0].id]
);
invitedUsers.push(users[0].id);
} catch (err) {
// Ignore duplicate key errors
}
}
}
}
res.json({ invited: invitedUsers.length });
}));
// Accept/reject challenge invitation
router.post('/:id/respond', authMiddleware, asyncHandler(async (req, res) => {
const challengeId = req.params.id;
const { status } = req.body; // 'accepted' or 'rejected'
if (!['accepted', 'rejected'].includes(status)) {
throw new AppError('Invalid status', 400);
}
await query(
'UPDATE challenge_participants SET status = ?, responded_at = NOW() WHERE challenge_id = ? AND user_id = ?',
[status, challengeId, req.user.userId]
);
// Emit real-time event to challenge participants
socketEvents.challengeInvitationResponse(challengeId, {
user_id: req.user.userId,
username: req.user.username,
status
});
res.json({ status });
}));

View File

@@ -2,6 +2,7 @@ import express from 'express';
import { query } from '../db/index.js';
import { authMiddleware } from '../middleware/auth.js';
import { asyncHandler, AppError } from '../middleware/errorHandler.js';
import { socketEvents } from '../sockets/index.js';
const router = express.Router();
@@ -99,6 +100,12 @@ router.post('/request', authMiddleware, asyncHandler(async (req, res) => {
[req.user.userId, user_id]
);
// Emit real-time notification to the user receiving the friend request
socketEvents.friendRequest(user_id, {
from_user_id: req.user.userId,
from_username: req.user.username
});
res.json({ success: true });
}));
@@ -125,6 +132,16 @@ router.post('/respond', authMiddleware, asyncHandler(async (req, res) => {
[status, friendship_id]
);
// Get the friendship to notify the requester
const friendship = friendships[0];
// Emit real-time notification to the user who sent the request
socketEvents.friendRequestResponse(friendship.user_id, {
friend_id: req.user.userId,
friend_username: req.user.username,
status
});
res.json({ status });
}));

View File

@@ -2,6 +2,7 @@ import express from 'express';
import { query } from '../db/index.js';
import { authMiddleware } from '../middleware/auth.js';
import { asyncHandler, AppError } from '../middleware/errorHandler.js';
import { socketEvents } from '../sockets/index.js';
const router = express.Router();
@@ -73,6 +74,9 @@ router.post('/', authMiddleware, asyncHandler(async (req, res) => {
created_at: new Date()
};
// Emit real-time event to all users in the challenge
socketEvents.predictionCreated(challenge_id, prediction);
res.json({ prediction });
}));
@@ -120,6 +124,19 @@ router.post('/:id/validate', authMiddleware, asyncHandler(async (req, res) => {
[status, req.user.userId, predictionId]
);
// Get updated prediction with usernames
const updatedPrediction = await query(
`SELECT p.*, u.username, v.username as validated_by_username
FROM predictions p
INNER JOIN users u ON p.user_id = u.id
LEFT JOIN users v ON p.validated_by = v.id
WHERE p.id = ?`,
[predictionId]
);
// Emit real-time event to all users in the challenge
socketEvents.predictionValidated(prediction.challenge_id, updatedPrediction[0]);
res.json({ status });
}));

View File

@@ -0,0 +1,111 @@
/**
* Socket.io setup and event handlers
*/
import { Server } from 'socket.io';
import jwt from 'jsonwebtoken';
let io;
export function initializeSocket(server) {
io = new Server(server, {
cors: {
origin: process.env.CORS_ORIGIN || '*',
credentials: true
}
});
// Authentication middleware for socket connections
io.use((socket, next) => {
try {
const token = socket.handshake.auth.token;
if (!token) {
return next(new Error('Authentication error: No token provided'));
}
const decoded = jwt.verify(token, process.env.JWT_SECRET);
socket.userId = decoded.userId;
socket.username = decoded.username;
next();
} catch (err) {
next(new Error('Authentication error: Invalid token'));
}
});
io.on('connection', (socket) => {
console.log(`✅ Socket connected: ${socket.username} (${socket.userId})`);
// Join personal room for user-specific notifications
socket.join(`user:${socket.userId}`);
// Handle joining challenge rooms
socket.on('join:challenge', (challengeId) => {
socket.join(`challenge:${challengeId}`);
console.log(`👥 ${socket.username} joined challenge:${challengeId}`);
});
// Handle leaving challenge rooms
socket.on('leave:challenge', (challengeId) => {
socket.leave(`challenge:${challengeId}`);
console.log(`👋 ${socket.username} left challenge:${challengeId}`);
});
socket.on('disconnect', () => {
console.log(`❌ Socket disconnected: ${socket.username}`);
});
});
return io;
}
export function getIO() {
if (!io) {
throw new Error('Socket.io not initialized');
}
return io;
}
// Event emitters for different actions
export const socketEvents = {
// Emit to specific user
emitToUser(userId, event, data) {
io.to(`user:${userId}`).emit(event, data);
},
// Emit to all users in a challenge
emitToChallenge(challengeId, event, data) {
io.to(`challenge:${challengeId}`).emit(event, data);
},
// Prediction events
predictionCreated(challengeId, prediction) {
this.emitToChallenge(challengeId, 'prediction:created', prediction);
},
predictionValidated(challengeId, prediction) {
this.emitToChallenge(challengeId, 'prediction:validated', prediction);
},
// Challenge events
challengeInvitation(userId, challenge) {
this.emitToUser(userId, 'challenge:invitation', challenge);
},
challengeInvitationResponse(challengeId, response) {
this.emitToChallenge(challengeId, 'challenge:invitation_response', response);
},
// Friend events
friendRequest(userId, request) {
this.emitToUser(userId, 'friend:request', request);
},
friendRequestResponse(userId, response) {
this.emitToUser(userId, 'friend:response', response);
},
// Leaderboard updates
leaderboardUpdate(challengeId, leaderboard) {
this.emitToChallenge(challengeId, 'leaderboard:update', leaderboard);
}
};