-
Notifications
You must be signed in to change notification settings - Fork 5
/
roomMetadata.js
60 lines (53 loc) · 2.9 KB
/
roomMetadata.js
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
const Room = require('./models/roomModel'); // Import the Room model to interact with the database
const Message = require('./models/messageModel'); // Importing Message model to delete messages.
const roomOccupancy = {};
const roomSessions = {};
const roomDeletionTimeouts = {};
function increaseRoomOccupancy(room, sessionId) {
if (!roomSessions[room]) {
roomSessions[room] = new Set();
}
roomSessions[room].add(sessionId);
roomOccupancy[room] = roomSessions[room].size;
clearTimeout(roomDeletionTimeouts[room]);
console.log(`IncreaseRoomOccupancy: Room ${room} occupancy increased to ${roomOccupancy[room]}.`); // gpt_pilot_debugging_log
}
function decreaseRoomOccupancy(io, room, sessionId) {
if (roomSessions[room]) {
roomSessions[room].delete(sessionId);
roomOccupancy[room] = roomSessions[room].size;
console.log(`DecreaseRoomOccupancy: Room ${room} occupancy decreased to ${roomOccupancy[room]}.`); // gpt_pilot_debugging_log
if (roomOccupancy[room] <= 0) {
clearTimeout(roomDeletionTimeouts[room]);
roomDeletionTimeouts[room] = setTimeout(async () => {
try {
// NEW: Delete the room messages from the database.
await Message.deleteMany({room: room})
.then(() => console.log(`All messages for room ${room} deleted due to inactivity.`)) // gpt_pilot_debugging_log
.catch((error) => console.error(`Error deleting messages for room ${room}: ${error.message}`, error.stack)); // gpt_pilot_debugging_log
io.to(room).emit('room deleted', { room: room });
delete roomOccupancy[room];
delete roomSessions[room];
Room.deleteOne({ name: room }) // Delete the room from the database
.then(() => console.log(`Room ${room} deleted from database due to inactivity.`)) // gpt_pilot_debugging_log
.catch((error) => console.error(`Error deleting room ${room} from database: ${error.message}`, error.stack)); // gpt_pilot_debugging_log
delete roomDeletionTimeouts[room];
console.log(`Room ${room} deleted due to inactivity.`); // gpt_pilot_debugging_log
} catch (error) {
console.error(`Error in timeout deleting room ${room}: ${error.message}`, error.stack); // gpt_pilot_debugging_log
}
}, 60000);
}
}
}
function doesRoomExist(room) {
const exists = roomOccupancy.hasOwnProperty(room);
console.log(`doesRoomExist: Room ${room} exists check returned ${exists}.`); // gpt_pilot_debugging_log
return exists;
}
module.exports = {
increaseRoomOccupancy,
decreaseRoomOccupancy,
doesRoomExist,
roomOccupancy // Exporting roomOccupancy for access in chat.js
};