Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Velocity Proxy and bridge that connects server to the API #20

Open
wants to merge 18 commits into
base: staging
Choose a base branch
from
Open
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Bump version and add ServerSync to bridge.
  • Loading branch information
benrobson committed Nov 16, 2024
commit 796133631c3e3851ca51a5f0198f6975415b2964
4 changes: 2 additions & 2 deletions zander-auth/pom.xml
Original file line number Diff line number Diff line change
@@ -10,7 +10,7 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>zander-auth</artifactId>
<version>1.0</version>
<version>1.3.0</version>

<repositories>
<!-- PaperMC/WaterFall -->
@@ -48,7 +48,7 @@
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.8.0</version>
<version>[2.9.0,)</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
2 changes: 1 addition & 1 deletion zander-bridge/pom.xml
Original file line number Diff line number Diff line change
@@ -10,7 +10,7 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>zander-bridge</artifactId>
<version>1.0</version>
<version>1.3.0</version>

<repositories>
<!-- PaperMC/WaterFall -->
2 changes: 1 addition & 1 deletion zander-hub/pom.xml
Original file line number Diff line number Diff line change
@@ -10,7 +10,7 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>zander-hub</artifactId>
<version>1.0</version>
<version>1.3.0</version>

<repositories>
<!-- PaperMC/WaterFall -->
2 changes: 1 addition & 1 deletion zander-velocity/dependency-reduced-pom.xml
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@
<groupId>org.modularsoft</groupId>
<artifactId>zander-velocity</artifactId>
<name>zander-velocity</name>
<version>1.2.0</version>
<version>1.3.0</version>
<build>
<resources>
<resource>
2 changes: 1 addition & 1 deletion zander-velocity/pom.xml
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@

<groupId>org.modularsoft</groupId>
<artifactId>zander-velocity</artifactId>
<version>1.2.0</version>
<version>1.3.0</version>
<packaging>jar</packaging>

<name>zander-velocity</name>
Original file line number Diff line number Diff line change
@@ -19,8 +19,9 @@
import org.modularsoft.zander.velocity.commands.*;
import org.modularsoft.zander.velocity.events.*;
import org.modularsoft.zander.velocity.util.announcement.TipChatter;
import org.modularsoft.zander.velocity.util.api.Bridge;
import org.modularsoft.zander.velocity.util.api.bridge.CommandProcessor;
import org.modularsoft.zander.velocity.util.api.Heartbeat;
import org.modularsoft.zander.velocity.util.api.bridge.ServerSync;
import org.slf4j.Logger;

import java.io.File;
@@ -70,14 +71,11 @@ public void onProxyInitialization(ProxyInitializeEvent event) {
commandManager.register(commandManager.metaBuilder("report").build(), new report());
commandManager.register(commandManager.metaBuilder("alert").build(), new alert());

// Start the Heartbeat task
// Start tasks
Heartbeat.startHeartbeatTask();

// Start the Announcement Tip task
TipChatter.startAnnouncementTipTask();

// Start the Bridge task
Bridge.startBridgeTask();
CommandProcessor.startBridgeTask();
ServerSync.startServerSyncTask();
}

@Inject
Original file line number Diff line number Diff line change
@@ -36,7 +36,7 @@ public void execute(final Invocation invocation) {
// Use the LegacyComponentSerializer to handle color codes and prefix
char translate = '&';
Component message = LegacyComponentSerializer.legacy(translate)
.deserialize(alertCommandPrefix + " " + alertMessage);
.deserialize(alertCommandPrefix + alertMessage);

// Broadcast the alert message
ZanderVelocityMain.getProxy().sendMessage(message);
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package org.modularsoft.zander.velocity.model;
package org.modularsoft.zander.velocity.model.bridge;

import com.google.gson.Gson;
import lombok.Builder;
import lombok.Getter;

@Builder
public class BridgeProcess {
public class BridgeCommandProcessor {

@Getter Integer bridgeId;

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package org.modularsoft.zander.velocity.model.bridge;

import com.google.gson.Gson;
import lombok.Builder;
import lombok.Getter;

import java.util.UUID;

@Builder
public class BridgeServerSync {

@Getter Object serverInfo;
@Getter String lastUpdated;

@Override
public String toString() {
return new Gson().toJson(this);
}

}
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package org.modularsoft.zander.velocity.util.api;
package org.modularsoft.zander.velocity.util.api.bridge;

import com.jayway.jsonpath.JsonPath;
import dev.dejvokep.boostedyaml.route.Route;
import io.github.ModularEnigma.Request;
import io.github.ModularEnigma.Response;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.modularsoft.zander.velocity.ZanderVelocityMain;
import org.modularsoft.zander.velocity.model.BridgeProcess;
import org.modularsoft.zander.velocity.model.bridge.BridgeCommandProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@@ -17,9 +15,9 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.CompletableFuture;

public class Bridge {
public class CommandProcessor {
// Initialize the logger
private static final Logger logger = LoggerFactory.getLogger(Bridge.class);
private static final Logger logger = LoggerFactory.getLogger(CommandProcessor.class);

public static void startBridgeTask() {
String BaseAPIURL = ZanderVelocityMain.getConfig().getString(Route.from("BaseAPIURL"));
@@ -53,8 +51,16 @@ public static void startBridgeTask() {
// Loop through each entry in the data list
for (Object dataEntry : dataList) {
int bridgeId = JsonPath.read(dataEntry, "$.bridgeId");
int processedInt = JsonPath.read(dataEntry, "$.processed"); // Read as int
boolean processed = (processedInt == 1); // Convert int to boolean
String command = JsonPath.read(dataEntry, "$.command");

// Skip processing if the command is already processed
if (processed) {
logger.info("Command with bridgeId {} has already been processed, skipping.", bridgeId);
continue; // Skip to the next iteration if already processed
}

// Execute the command asynchronously
CompletableFuture<Boolean> future = ZanderVelocityMain.getProxy()
.getCommandManager()
@@ -67,15 +73,15 @@ public static void startBridgeTask() {

// Mark the command as processed
try {
BridgeProcess bridgeProcess = BridgeProcess.builder()
BridgeCommandProcessor bridgeCommandProcessor = BridgeCommandProcessor.builder()
.bridgeId(bridgeId)
.build();

Request bridgeProcessReq = Request.builder()
.setURL(BaseAPIURL + "/bridge/command/process")
.setMethod(Request.Method.POST)
.addHeader("x-access-token", APIKey)
.setRequestBody(bridgeProcess.toString())
.setRequestBody(bridgeCommandProcessor.toString())
.build();

Response bridgeProcessRes = bridgeProcessReq.execute();
@@ -101,4 +107,4 @@ public static void startBridgeTask() {
}
}, 0, 60, TimeUnit.SECONDS);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package org.modularsoft.zander.velocity.util.api.bridge;

import dev.dejvokep.boostedyaml.route.Route;
import io.github.ModularEnigma.Request;
import io.github.ModularEnigma.Response;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import org.modularsoft.zander.velocity.ZanderVelocityMain;
import org.modularsoft.zander.velocity.model.bridge.BridgeServerSync;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class ServerSync {
private static final ProxyServer proxy = ZanderVelocityMain.getProxy();

public static void startServerSyncTask() {
String BaseAPIURL = ZanderVelocityMain.getConfig().getString(Route.from("BaseAPIURL"));
String APIKey = ZanderVelocityMain.getConfig().getString(Route.from("APIKey"));

// Create a ScheduledExecutorService with a single thread
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

// Schedule the task to run every 60 seconds
scheduler.scheduleAtFixedRate(() -> {
try {
// Collect server and player information
List<ServerInfo> serverInfoList = new ArrayList<>();
for (RegisteredServer server : proxy.getAllServers()) {
List<String> playerNames = server.getPlayersConnected().stream()
.map(Player::getUsername)
.collect(Collectors.toList());

ServerInfo info = new ServerInfo(
server.getServerInfo().getName(),
playerNames.size(),
playerNames
);
serverInfoList.add(info);
}

// Get the current time and format it as a DATETIME string
LocalDateTime now = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String lastUpdated = now.format(formatter);

// Build the BridgeServerSync object
BridgeServerSync serverInfo = BridgeServerSync.builder()
.serverInfo(serverInfoList)
.lastUpdated(lastUpdated)
.build();

// Prepare the request body
Request serverSyncReq = Request.builder()
.setURL(BaseAPIURL + "/bridge/server/update")
.setMethod(Request.Method.POST)
.addHeader("x-access-token", APIKey)
.setRequestBody(serverInfo.toString())
.build();

// Send the request and get the response
Response serverSyncRes = serverSyncReq.execute();
if (serverSyncRes.getStatusCode() != 200) {
ZanderVelocityMain.getLogger().error("Error syncing server info: " + serverSyncRes.getBody());
}

} catch (Exception e) {
// Handle any exceptions
ZanderVelocityMain.getLogger().error("Error occurred while syncing server info: " + e.getMessage());
}
}, 0, 60, TimeUnit.SECONDS);
}

// Helper class to hold server information
public static class ServerInfo {
private final String serverName;
private final int playerCount;
private final List<String> playerNames;

public ServerInfo(String serverName, int playerCount, List<String> playerNames) {
this.serverName = serverName;
this.playerCount = playerCount;
this.playerNames = playerNames;
}

// Getters
public String getServerName() {
return serverName;
}

public int getPlayerCount() {
return playerCount;
}

public List<String> getPlayerNames() {
return playerNames;
}
}
}
2 changes: 1 addition & 1 deletion zander-waterfall/dependency-reduced-pom.xml
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>zander-waterfall</artifactId>
<version>1.0</version>
<version>1.3.0</version>
<build>
<plugins>
<plugin>
2 changes: 1 addition & 1 deletion zander-waterfall/pom.xml
Original file line number Diff line number Diff line change
@@ -10,7 +10,7 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>zander-waterfall</artifactId>
<version>1.0</version>
<version>1.3.0</version>
<build>
<plugins>
<plugin>