123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235 |
- const express = require('express');
- const app = express();
- const port = 4000;
- const fs = require('fs');
- const { join } = require('path');
- app.use(express.json()); // Middleware to parse JSON bodies
- // constants -------------------------------
- const CLEANUP_INTERVAL = 1000 * 7;
- const JOINCODE_TIMEOUT_THRESHOLD = 1000 * 10; // 10 seconds
- const MIGRATION_TIMEOUT_THRESHOLD = 1000 * 20; // = 60s
- // clean up ---------------------------------
- setInterval(cleanup, CLEANUP_INTERVAL);
- function cleanup() {
- const now = Date.now();
-
- joinCodes = joinCodes.filter(code => code.isActive && (now - code.lastActive < JOINCODE_TIMEOUT_THRESHOLD));
- // // -- Debug Log --
- // for( var i = 0 ; i < migrationCodes.length; ++i ) {
- // var code = migrationCodes [ i ] ;
- // var delta = now - code.lastActive;
- // console.log( `scan [${i}] delta=${delta} / ${MIGRATION_TIMEOUT_THRESHOLD}`);
- // if( delta > MIGRATION_TIMEOUT_THRESHOLD ) console.log(`pop ${i}`);
- // }
- migrationCodes = migrationCodes.filter(code => ( (now - code.lastActive) < MIGRATION_TIMEOUT_THRESHOLD ) );
- writeActiveCodesToLog();
- }
- // app configuration -----------------------
- app.listen(port, () => {
- console.log(`Server listening at http://localhost:${port}`);
- });
- process.on('exit', () => {
- writeActiveCodesToLog();
- });
- process.on('SIGINT', () => {
- writeActiveCodesToLog();
- process.exit();
- });
- // app log -----------------------------------
- function writeActiveCodesToLog()
- {
- let out_text = `${Date.now()}\n`;
- const activeJoinCodes = joinCodes.filter(code => code.isActive);
- out_text += `* JOIN CODES:\n${JSON.stringify(activeJoinCodes,null,2)}\n`;
- out_text += `* MIGRATION CODES:\n${JSON.stringify(migrationCodes,null,2)}\n`;
- fs.writeFileSync('applog.log', out_text );
- }
- app.get('/viewLog', (req, res) => {
- fs.readFile('applog.log', 'utf8', (err, data) => {
- if (err) {
- console.error("Error reading applog.log:", err);
- res.status(500).send('Error reading log file');
- return;
- }
- res.type('text/plain');
- res.send(data);
- });
- });
- // join codes ----------------------------------
- let joinCodes = [];
- app.post('/addJoinCode', (req, res) => {
- const { joinCode, isPublic, isActive, isFull } = req.body; // Updated to include isFull
- if (joinCode && typeof isPublic !== 'undefined' && typeof isActive !== 'undefined' && typeof isFull !== 'undefined') { // Check for isFull
- joinCodes.push({ joinCode, isPublic, isActive, isFull, lastActive: Date.now() }); // Updated to include isFull
- res.send({ message: 'Join code added' });
- } else {
- res.status(400).send({ error: 'Invalid request body' });
- }
- writeActiveCodesToLog();
- });
- app.post('/updateActiveStatus', (req, res) => {
- const { joinCode, isPublic, isActive, isFull } = req.body;
- const joinCodeIndex = joinCodes.findIndex(code => code.joinCode === joinCode);
- if (joinCodeIndex >= 0) {
- joinCodes[joinCodeIndex].isActive = isActive;
- joinCodes[joinCodeIndex].isPublic = isPublic;
- joinCodes[joinCodeIndex].isFull = isFull;
- joinCodes[joinCodeIndex].lastActive = Date.now();
- if (!isActive) {
- res.send('Join code will be deactivated');
- } else {
- res.send('Active status updated');
- }
- } else {
- res.status(404).send('Join code not found');
- }
- writeActiveCodesToLog();
- });
- app.get('/getRandomJoinCode', (req, res) => {
- const now = Date.now();
- const activeJoinCodes = joinCodes.filter(code => code.isPublic && code.isActive && !code.isFull && (now - code.lastActive < JOINCODE_TIMEOUT_THRESHOLD));
- if (activeJoinCodes.length === 0) {
- res.status(404).send({ error: 'No active public join codes available' });
- return;
- }
- const randomIndex = Math.floor(Math.random() * activeJoinCodes.length);
- res.send({ joinCode: activeJoinCodes[randomIndex].joinCode });
- });
- app.get('/getAllActiveJoinCodes', (req, res) => {
- const now = Date.now();
- const activeJoinCodes = joinCodes.filter(code => code.isPublic && code.isActive && !code.isFull && (now - code.lastActive < JOINCODE_TIMEOUT_THRESHOLD));
- if (activeJoinCodes.length === 0) {
- res.status(404).send({ error: 'No active public join codes available' });
- return;
- }
- res.send({ joinCodes: activeJoinCodes.map(code => code.joinCode) });
- });
- // migration codes ----------------------------------------
- let migrationCodes = [];
- app.post('/test', ( req, res ) => {
- const { lobbyKey , joinCode , hostMigrating , count } = req.body;
- const data = { lobbyKey, joinCode, hostMigrating, count };
- res.send( req.body );
- } );
- app.post('/startHostMigration', ( req, res ) =>
- {
- const { lobbyKey } = req.body;
-
- const idx = migrationCodes.findIndex( x => x.lobbyKey === lobbyKey );
- if( idx !== -1 )
- {
- res.status(403).send( 'migration for this lobbyKey has already started' );
- return;
- }
- if ( lobbyKey )
- {
- let data = {
- lobbyKey,
- hostMigrating : false,
- count : 0,
- joinCode : "null" ,
- lastActive: Date.now()
- };
- migrationCodes.push( data );
- res.send({ message: 'migration code added' });
- }
- else
- {
- res.status( 400 ).send({ error: 'Invalid request body' });
- }
- writeActiveCodesToLog();
- });
- app.post('/updateHostMigration', (req, res) => {
- const { lobbyKey , joinCode , hostMigrating , count } = req.body;
- const idx = migrationCodes.findIndex( x => x.lobbyKey === lobbyKey );
- if (idx >= 0)
- {
- if( migrationCodes[idx].hostMigrating && hostMigrating )
- {
- res.status(403).send( 'migration already progress' );
- }
- else
- {
- migrationCodes[idx].lastActive = Date.now();
- migrationCodes[idx].hostMigrating = hostMigrating;
- migrationCodes[idx].joinCode = joinCode;
- migrationCodes[idx].count = count;
- res.send("migration code updated");
- }
- }
- else
- {
- res.status(404).send('Lobby key not found');
- }
- writeActiveCodesToLog();
- });
- app.get('/getHostMigration', (req, res) => {
- const { lobbyKey } = req.body;
- const idx = migrationCodes.findIndex( x => x.lobbyKey === lobbyKey );
- if( idx < 0 )
- {
- res.status(404).send({ error: 'lobby key not found' });
- return;
- }
- migrationCodes[ idx ].lastActive = Date.now();
- let d_ = migrationCodes[ idx ];
- let output =
- {
- hostMigrating : d_.hostMigrating ,
- joinCode : d_.joinCode ,
- count : d_.count
- }
- res.send( output );
- });
|