Team Ai
Apppublic

anas044/attendance-nodejs

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
websocket.js95 linesDownload Raw Back to root
1// socket.js
2const { Server } = require('socket.io');
3const pool = require('./pg/pg');
4
5const setupSocketIO = (server) => {
6    const io = new Server(server, {
7        cors: {
8            origin: "*",
9            credentials: true
10        }
11    });
12
13    // Store active users: { userId: { sessionId, joinedAt, socket } }
14    const activeUsers = new Map();
15
16    io.on('connection', (socket) => {
17        console.log('User connected:', socket.id);
18
19        const userId = socket.handshake.query.userId;
20        const sessionId = socket.handshake.query.sessionId;
21
22        // Handle join event
23        socket.on('join', (data) => {
24            console.log('Join event:', data);
25            
26            // Store user info
27            activeUsers.set(userId, {
28                sessionId: data.sessionId,
29                joinedAt: data.joinedAt,
30                socket: socket
31            });
32            
33            console.log(`User ${userId} joined session ${data.sessionId} at ${data.joinedAt}`);
34        });
35
36        // Handle disconnect
37        socket.on('disconnect', async () => {
38            console.log('User disconnected:', socket.id);
39            
40            const userInfo = activeUsers.get(userId);
41            if (userInfo) {
42                // Save attendance
43                await saveAttendance(
44                    userInfo.sessionId,
45                    userId,
46                    userInfo.joinedAt,
47                    new Date().toISOString()
48                );
49                
50                // Remove from active users
51                activeUsers.delete(userId);
52                
53                console.log(`Attendance saved for user ${userId}`);
54            }
55        });
56    });
57
58    console.log('Socket.io server ready');
59    return io;
60};
61
62const saveAttendance = async (sessionId, userId, joinedAt, leftAt) => {
63    try {
64        const tokenCheck = await pool.query(
65            'SELECT * FROM session_tokens WHERE user_id = $1 AND session_id = $2',
66            [userId, sessionId]
67        );
68        
69        if (tokenCheck.rowCount === 0) {
70            return;
71        }
72        
73        // const existingAttendance = await pool.query(
74        //     'SELECT * FROM attendance WHERE session_id = $1 AND student_id = $2',
75        //     [sessionId, userId]
76        // );
77        
78        // if (existingAttendance.rowCount > 0) {
79        //     console.log(`Attendance already exists for user ${userId}`);
80        //     return;
81        // }
82        
83        await pool.query(
84            'INSERT INTO attendance (session_id, student_id, joined_at, left_at) VALUES ($1, $2, $3, $4)',
85            [sessionId, userId, joinedAt, leftAt]
86        );
87        
88
89        
90    } catch (error) {
91        console.error('Error saving attendance:', error);
92    }
93};
94
95module.exports = { setupSocketIO };