forked from xxmichaellong/ptcg-sim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
282 lines (264 loc) · 10 KB
/
server.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
const express = require('express');
const cors = require('cors');
const http = require('http');
const { Server } = require('socket.io');
const { instrument } = require("@socket.io/admin-ui");
const bcrypt = require('bcryptjs');
const path = require('path');
const dotenv = require('dotenv');
const envFilePath = path.join(__dirname, 'socket-admin-password.env');
const sqlite3 = require('sqlite3').verbose();
const fs = require('fs');
dotenv.config({ path: envFilePath });
function generateRandomKey(length) {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let key = '';
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
key += characters.charAt(randomIndex);
}
return key;
}
async function main() {
const app = express();
// HTTP Server Setup
const server = http.createServer(app);
// Socket.IO Server Setup
const io = new Server(server, {
connectionStateRecovery: {},
cors: {
origin: ["https://admin.socket.io", "https://ptcgsim.online/"],
credentials: true
}
});
// Create a new SQLite database
const dbFilePath = 'data/db.sqlite';
const maxSizeGB = 15;
const db = new sqlite3.Database(dbFilePath);
let isDatabaseCapacityReached = false;
// Check database size
const checkDatabaseSizeGB = () => {
const stats = fs.statSync(dbFilePath);
const fileSizeInBytes = stats.size;
const fileSizeInGB = fileSizeInBytes / (1024 * 1024 * 1024); // Convert bytes to gigabytes
return fileSizeInGB;
};
// Perform size check periodically
setInterval(() => {
const currentSize = checkDatabaseSizeGB();
if (currentSize > maxSizeGB) {
isDatabaseCapacityReached = true;
};
}, 1000 * 60 * 60);
// Create a table to store key-value pairs
db.serialize(() => {
db.run('CREATE TABLE IF NOT EXISTS KeyValuePairs (key TEXT PRIMARY KEY, value TEXT)');
});
// Bcrypt Configuration
const saltRounds = 10;
const plainPassword = process.env.ADMIN_PASSWORD || "defaultPassword";
const hashedPassword = bcrypt.hashSync(plainPassword, saltRounds);
// Socket.IO Admin Instrumentation
instrument(io, {
auth: {
type: "basic",
username: "admin",
password: hashedPassword,
},
mode: "development",
});
app.set('view engine', 'ejs'); // Set EJS as the view engine
app.set('views', path.join(__dirname, 'views')); // Set the views directory
// Express App Configuration
app.use(cors());
app.use(express.static(__dirname));
app.get('/', (_, res) => {
res.render('index', { importDataJSON: null });
});
app.get('/import', (req, res) => {
const key = req.query.key;
if (!key) {
return res.status(400).json({ error: 'Key parameter is missing' });
}
db.get('SELECT value FROM KeyValuePairs WHERE key = ?', [key], (err, row) => {
if (err) {
console.error('Error fetching value from database:', err);
return res.status(500).json({ error: 'Internal server error' });
}
if (row) {
res.render('index', { importDataJSON: row.value });
} else {
res.status(404).json({ error: 'Key not found' });
}
});
});
const roomInfo = new Map();
// Function to periodically clean up empty rooms
const cleanUpEmptyRooms = () => {
roomInfo.forEach((room, roomId) => {
if (room.players.size === 0 && room.spectators.size === 0) {
roomInfo.delete(roomId);
};
});
}
// Set up a timer to clean up empty rooms every 5 minutes (adjust as needed)
setInterval(cleanUpEmptyRooms, 5 * 60 * 1000);
//Socket.IO Connection Handling
io.on('connection', async (socket) => {
// Function to handle disconnections (unintended)
const disconnectHandler = (roomId, username) => {
if (!socket.data.leaveRoom){
socket.to(roomId).emit('userDisconnected', username);
};
// Remove the disconnected user from the roomInfo map
if (roomInfo.has(roomId)) {
const room = roomInfo.get(roomId);
if (room.players.has(username)) {
room.players.delete(username);
} else if (room.spectators.has(username)) {
room.spectators.delete(username);
};
// If both players and spectators are empty, remove the roomInfo entry
if (room.players.size === 0 && room.spectators.size === 0) {
roomInfo.delete(roomId);
};
};
};
// Function to handle event emission
const emitToRoom = (eventName, data) => {
socket.broadcast.to(data.roomId).emit(eventName, data);
if (eventName === 'leaveRoom'){
socket.leave(data.roomId);
if (socket.data.disconnectListener){
socket.data.leaveRoom = true;
socket.data.disconnectListener();
socket.removeListener('disconnect', socket.data.disconnectListener);
socket.data.leaveRoom = false;
};
};
};
socket.on('storeGameState', (exportData) => {
if (isDatabaseCapacityReached) {
socket.emit('exportGameStateFailed', 'No more storage for game states! You should probably tell Michael/Xiao Xiao.');
} else {
const key = generateRandomKey(4);
db.run('INSERT OR REPLACE INTO KeyValuePairs (key, value) VALUES (?, ?)', [key, exportData], (err) => {
if (err) {
console.error('Error storing key-value pair in database:', err);
socket.emit('exportGameStateFailed', 'Error exporting game! Please try again or save as a file.');
} else {
socket.emit('exportGameStateSuccessful', key);
};
});
}
});
socket.on('joinGame', (roomId, username, isSpectator) => {
if (!roomInfo.has(roomId)) {
roomInfo.set(roomId, { players: new Set(), spectators: new Set() });
};
const room = roomInfo.get(roomId);
if (room.players.size < 2 || isSpectator) {
socket.join(roomId);
// Check if the user is a spectator or there are fewer than 2 players
if (isSpectator) {
room.spectators.add(username);
socket.emit('spectatorJoin');
} else {
room.players.add(username);
socket.emit('joinGame');
socket.data.disconnectListener = () => disconnectHandler(roomId, username);
socket.on('disconnect', socket.data.disconnectListener);
};
} else {
socket.emit('roomReject');
};
});
socket.on('userReconnected', (data) => {
if (!roomInfo.has(data.roomId)) {
roomInfo.set(data.roomId, { players: new Set(), spectators: new Set() });
};
const room = roomInfo.get(data.roomId);
socket.join(data.roomId);
if (!data.notSpectator) {
room.spectators.add(data.username);
} else {
room.players.add(data.username);
socket.data.disconnectListener = () => disconnectHandler(data.roomId, data.username);
socket.on('disconnect', socket.data.disconnectListener);
io.to(data.roomId).emit('userReconnected', data);
};
});
// List of socket events
const events = [
'leaveRoom',
'requestAction',
'pushAction',
'resyncActions',
'catchUpActions',
'syncCheck',
'appendMessage',
'spectatorActionData',
'initiateImport',
'endImport',
// 'exchangeData',
// 'loadDeckData',
// 'reset',
// 'setup',
// 'takeTurn',
// 'draw',
// 'moveCardBundle',
// 'shuffleIntoDeck',
// 'moveToDeckTop',
// 'switchWithDeckTop',
// 'viewDeck',
// 'shuffleAll',
// 'discardAll',
// 'lostZoneAll',
// 'handAll',
// 'leaveAll',
// 'discardAndDraw',
// 'shuffleAndDraw',
// 'shuffleBottomAndDraw',
// 'shuffleZone',
// 'useAbility',
// 'removeAbilityCounter',
// 'addDamageCounter',
// 'updateDamageCounter',
// 'removeDamageCounter',
// 'addSpecialCondition',
// 'updateSpecialCondition',
// 'removeSpecialCondition',
// 'discardBoard',
// 'handBoard',
// 'shuffleBoard',
// 'lostZoneBoard',
'lookAtCards',
'stopLookingAtCards',
'revealCards',
'hideCards',
'revealShortcut',
'hideShortcut',
'lookShortcut',
'stopLookingShortcut',
// 'playRandomCardFaceDown',
// 'rotateCard',
// 'changeType',
// 'attack',
// 'pass',
// 'VSTARGXFunction',
];
// Register event listeners using the common function
for (const event of events) {
socket.on(event, (data) => {
emitToRoom(event, data);
});
};
});
// Server Port Configuration
const port = 4000;
// Start the server
server.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
}
main();