Skip to content

Commit

Permalink
added players sync
Browse files Browse the repository at this point in the history
  • Loading branch information
MineFact committed Feb 29, 2024
1 parent 581565d commit 228763a
Show file tree
Hide file tree
Showing 5 changed files with 276 additions and 82 deletions.
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,11 @@ router.use(helmet());
Joi,
network
);
(await import("./routes/teams/POST_Playerlist.js")).initRoutes(
router,
Joi,
network
);

// Init PUT Routes for the API
(await import("./routes/teams/PUT_TeamHasBuildTeamToolsInstalled.js")).initRoutes(
Expand Down
53 changes: 53 additions & 0 deletions src/routes/teams/POST_Playerlist.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Router } from "express";
import Network, { BuildTeamIdentifier } from "../../struct/core/network.js";

export async function initRoutes(app: Router, joi: any, network: Network) {

app.post('/api/teams/:apikey/playerlist', async function (req, res) {

// Validate that the API key is a valid GUID
if(!await network.validateAPIKey(req, res))
return;

const buildTeam = await network.getBuildTeam(req.params.apikey, BuildTeamIdentifier.APIKey);

if(buildTeam == null) {
res.status(400).send({ error: 'Build Team not found' });
return;
}

// Validate the parameters with joi

// Schema for a single UUID and username pair
const uuidUsernameSchema = joi.array().ordered(
joi.string().guid({ version: 'uuidv4' }), // Validates a UUID (version 4)
joi.string() // Validates a simple string for the username
).length(2);

// Schema for the main array, containing multiple UUID-username pairs
const schema = joi.array().items(uuidUsernameSchema);

const validation = schema.validate(req.body);

// If the validation failed, return an error
if(validation.error != null){
res.status(400).send({success: false, error: validation.error.details[0].message});
return;
}


const result = await buildTeam.updatePlayerlist(req.body);



// If the playerlist was not updated, return an error
if(result == false){
res.status(400).send({success: false, error: 'An error occurred while updating the playerlist'});
return;
}else{
// Return the order id to the client
res.setHeader('Content-Type', 'application/json');
res.send({success: true})
}
})
}
51 changes: 51 additions & 0 deletions src/struct/core/buildteam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,15 @@ export default class BuildTeam {
private static readonly SERVER_UPDATE_INTERVAL: number = 60 * 24; // 24 hours
private static readonly FTP_CONFIGURATION_UPDATE_INTERVAL: number = 60 * 24; // 24 hours
private static readonly BUILD_TEAM_INFO_UPDATE_INTERVAL: number = 60 * 1; // 1 hour
private static readonly PLAYER_LIST_CLEAR_INTERVAL: number = 60 * 1; // 1 hours

private apiKey: string;
private buildTeamID: string | null = null;
private network: Network;
private psDatabase: DatabaseHandler
private nwDatabase: DatabaseHandler
private playerList: any[] = [];
private lastPlayerListUpdate: Date | null = null;

private psBuildTeamID: string | null = null;
private psCities: Map<number, any[]> = new Map() // Map<country_id, city>
Expand Down Expand Up @@ -78,6 +81,15 @@ export default class BuildTeam {

if(this.psFTPConfiguration != null && this.network.getUpdateCacheTicks() % BuildTeam.FTP_CONFIGURATION_UPDATE_INTERVAL == 0)
this.psFTPConfiguration.clear();

// If the last player list update is older than the player list clear interval, clear the player list
if(this.playerList != null && this.lastPlayerListUpdate != null && this.network.getUpdateCacheTicks() % BuildTeam.PLAYER_LIST_CLEAR_INTERVAL == 0){
const timeDifference = (new Date().getTime() - this.lastPlayerListUpdate.getTime()) / 1000;
if(timeDifference > BuildTeam.PLAYER_LIST_CLEAR_INTERVAL){
this.playerList = [];
this.lastPlayerListUpdate = null;
}
}
}

// Resets the cache for the build team
Expand All @@ -87,6 +99,8 @@ export default class BuildTeam {
this.psCountries.clear();
this.psServers.clear();
this.psFTPConfiguration.clear();
this.playerList = [];
this.lastPlayerListUpdate = null;
}

async loadBuildTeamData(){
Expand Down Expand Up @@ -594,6 +608,43 @@ export default class BuildTeam {



/* ======================================= */
/* Playerlist */
/* ======================================= */


/** Updates the playerlist of the build team.
*
* @param players The list of players
*
* @returns Returns true if the playerlist was updated successfully, otherwise false.
**/
async updatePlayerlist(players: any[]) {
// Validate that the build team id is loaded
if(this.buildTeamID == null)
await this.loadBuildTeamData();
if(this.buildTeamID == null)
return false;

// Take the data that is needed for the BuildTeamOnlinePlayers table
const tempArray: any[] = [];

players.forEach((subArray) => {
tempArray.push([subArray[0], subArray[1], this.buildTeamID]);
});

this.lastPlayerListUpdate = new Date();
this.playerList = tempArray;

return true;
}

getPlayerList() {
return this.playerList;
}




/* ======================================= */
/* PlotSystem */
Expand Down
38 changes: 38 additions & 0 deletions src/struct/core/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ export default class Network {
if (isStarting == true) bar?.tick();
}

this.syncPlayerList();

this.updateCacheTicks++;

if(this.updateCacheTicks >= Number.MAX_SAFE_INTEGER - 100)
Expand Down Expand Up @@ -437,7 +439,15 @@ export default class Network {
return json.display_name;
}

async syncPlayerList(): Promise<number | false>{
let globalPlayerList: any[] = [];

// Create a two dimensional array with one array for each player
for (const buildTeam of this.buildTeams.values())
globalPlayerList = globalPlayerList.concat(buildTeam.getPlayerList());

return this.syncPlayerListInDatabase(globalPlayerList);
}



Expand Down Expand Up @@ -579,4 +589,32 @@ export default class Network {
const SQL = "SELECT * FROM BuildTeamWarpGroups";
return await this.networkDatabase.query(SQL);
}


/* =================================================== */
/* DATABASE POST REQUESTS */
/* =================================================== */

private async syncPlayerListInDatabase(playerList: any[]): Promise<number | false> {
try {
// Truncate the table first
await this.networkDatabase.query("TRUNCATE TABLE BuildTeamOnlinePlayers");

// Insert new data if available
if (playerList && playerList.length > 0) {
const placeholders = playerList.map(() => "(?, ?, ?)").join(", ");
const flatValues = playerList.flat();
const insertSQL = `INSERT INTO BuildTeamOnlinePlayers (UUID, Name, BuildTeam) VALUES ${placeholders}`;
const insertResult = await this.networkDatabase.query(insertSQL, flatValues);

if (insertResult.affectedRows > 0)
return insertResult.affectedRows;
}
} catch (error) {
console.error(error);
return false;
}

return false;
}
}
Loading

0 comments on commit 228763a

Please sign in to comment.