Skip to content

Commit

Permalink
Api v1 refactor (#239)
Browse files Browse the repository at this point in the history
  • Loading branch information
DeathTrooperr authored Aug 15, 2023
1 parent 07cac9b commit 9acd34f
Show file tree
Hide file tree
Showing 30 changed files with 470 additions and 384 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ $ curl http://localhost:4567/v1/players
```
# ServerTap Command

ServerTap currently supports only one management command in game. The supported subcommands are `reload` & 'info'
which as their names imply let you reload the plugin and display information basic info about it (version, author, etc).
ServerTap currently supports only one management command in game. The supported subcommands are `reload` & `info`
which as their names imply let you reload and display basic information about the plugin (version, author, etc).

**Note**: The Permission for the `/servertap` Command is `servertap.admin`.

Expand Down
1 change: 0 additions & 1 deletion src/main/java/io/servertap/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ public class Constants {

public static final String API_V1 = "v1";


// Economy Related Messages
public static final String VAULT_MISSING = "Vault not found or you are missing an economy plugin. Related functionality disabled";
public static final String VAULT_MISSING_PAY_PARAMS = "Missing uuid and/or amount";
Expand Down
47 changes: 30 additions & 17 deletions src/main/java/io/servertap/ServerTapMain.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
package io.servertap;

import io.servertap.api.v1.models.ConsoleLine;
import io.servertap.api.v1.websockets.ConsoleListener;
import io.servertap.commands.ServerTapCommand;
import io.servertap.metrics.Metrics;
import io.servertap.plugin.api.ServerTapWebserverService;
import io.servertap.plugin.api.ServerTapWebserverServiceImpl;
import io.servertap.utils.EconomyWrapper;
import io.servertap.utils.Lag;
import io.servertap.utils.ConsoleListener;
import io.servertap.utils.LagDetector;
import io.servertap.utils.pluginwrappers.ExternalPluginWrapperRepo;
import io.servertap.webhooks.WebhookEventListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.ServicePriority;
Expand All @@ -25,58 +26,65 @@

public class ServerTapMain extends JavaPlugin {

public static ServerTapMain instance;
private static final java.util.logging.Logger log = Bukkit.getLogger();
private WebServer app;

Logger rootLogger = (Logger) LogManager.getRootLogger();

private final Logger rootLogger = (Logger) LogManager.getRootLogger();
private final List<ConsoleLine> consoleBuffer = new ArrayList<>();
private int maxConsoleBufferSize = 1000;
private ExternalPluginWrapperRepo externalPluginWrapperRepo;
private WebhookEventListener webhookEventListener;
private int maxConsoleBufferSize = 1000;
private ConsoleListener consoleListener;
public static ServerTapMain instance;
private final LagDetector lagDetector;
private final Server server;
private WebServer app;

public ServerTapMain() {
super();
instance = this;
server = getServer();
lagDetector = new LagDetector();
}

public ServerTapMain(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file) {
super(loader, description, dataFolder, file);
instance = this;
server = getServer();
lagDetector = new LagDetector();
}

@Override
public void onEnable() {
// Tell bStats what plugin this is
new Metrics(this, 9492);

// Initialize any economy integration (if one is installed)
new EconomyWrapper(log).setupEconomy();
// Initialize any external plugin integrations
externalPluginWrapperRepo = new ExternalPluginWrapperRepo(this, log);

// Start the TPS Counter with a 100 tick Delay every 1 tick
Bukkit.getScheduler().runTaskTimer(this, new Lag(), 100, 1);
Bukkit.getScheduler().runTaskTimer(this, lagDetector, 100, 1);

// Initialize config file + set defaults
saveDefaultConfig();

FileConfiguration bukkitConfig = getConfig();
maxConsoleBufferSize = bukkitConfig.getInt("websocketConsoleBuffer");
rootLogger.addFilter(new ConsoleListener(this));
consoleListener = new ConsoleListener(this);
rootLogger.addFilter(consoleListener);

setupWebServer(bukkitConfig);

new ServerTapCommand(this);

webhookEventListener = new WebhookEventListener(this, bukkitConfig, log);
getServer().getPluginManager().registerEvents(webhookEventListener, this);
webhookEventListener = new WebhookEventListener(this, bukkitConfig, log, externalPluginWrapperRepo.getEconomyWrapper());
server.getPluginManager().registerEvents(webhookEventListener, this);

getServer().getServicesManager().register(ServerTapWebserverService.class, new ServerTapWebserverServiceImpl(this), this, ServicePriority.Normal);
server.getServicesManager().register(ServerTapWebserverService.class, new ServerTapWebserverServiceImpl(this), this, ServicePriority.Normal);
}

private void setupWebServer(FileConfiguration bukkitConfig) {
app = new WebServer(this, bukkitConfig, log);
app.start(bukkitConfig.getInt("port", 4567));
WebServerRoutes.addV1Routes(app);
WebServerRoutes.addV1Routes(this, log, lagDetector, app, consoleListener, externalPluginWrapperRepo);
}

public void reload() {
Expand All @@ -87,7 +95,12 @@ public void reload() {
reloadConfig();
FileConfiguration bukkitConfig = getConfig();
maxConsoleBufferSize = bukkitConfig.getInt("websocketConsoleBuffer");

externalPluginWrapperRepo = new ExternalPluginWrapperRepo(this, log);
consoleListener.resetListeners();

setupWebServer(bukkitConfig);

webhookEventListener.loadWebhooksFromConfig(bukkitConfig);
log.info("[ServerTap] ServerTap reloaded successfully!");
}
Expand Down
80 changes: 43 additions & 37 deletions src/main/java/io/servertap/WebServerRoutes.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,68 +3,74 @@
import io.javalin.http.Handler;
import io.javalin.websocket.WsConfig;
import io.servertap.api.v1.*;
import io.servertap.api.v1.websockets.WebsocketHandler;

import java.util.function.Consumer;
import io.servertap.utils.ConsoleListener;
import io.servertap.utils.LagDetector;
import io.servertap.utils.pluginwrappers.ExternalPluginWrapperRepo;

import static io.servertap.Constants.*;

import java.util.function.Consumer;
import java.util.logging.Logger;

public final class WebServerRoutes {

private WebServerRoutes() {}

public static void addV1Routes(WebServer webServer) {
public static void addV1Routes(ServerTapMain main, Logger log, LagDetector lagDetector, WebServer webServer,
ConsoleListener consoleListener, ExternalPluginWrapperRepo externalPluginWrapperRepo) {
PrefixedRouteBuilder pr = new PrefixedRouteBuilder(API_V1, webServer);

pr.get("ping", ServerApi::ping);
ApiV1Initializer api = new ApiV1Initializer(main, log, lagDetector, consoleListener, externalPluginWrapperRepo);

pr.get("ping", api.getServerApi()::ping);

// Server routes
pr.get("server", ServerApi::serverGet);
pr.post("server/exec", ServerApi::postCommand);
pr.get("server/ops", ServerApi::getOps);
pr.post("server/ops", ServerApi::opPlayer);
pr.delete("server/ops", ServerApi::deopPlayer);
pr.get("server/whitelist", ServerApi::whitelistGet);
pr.post("server/whitelist", ServerApi::whitelistPost);
pr.delete("server/whitelist", ServerApi::whitelistDelete);

pr.get("worlds", WorldApi::worldsGet);
pr.post("worlds/save", WorldApi::saveAllWorlds);
pr.get("worlds/download", WorldApi::downloadWorlds);
pr.get("worlds/{uuid}", WorldApi::worldGet);
pr.post("worlds/{uuid}/save", WorldApi::saveWorld);
pr.get("worlds/{uuid}/download", WorldApi::downloadWorld);

pr.get("scoreboard", ServerApi::scoreboardGet);
pr.get("scoreboard/{name}", ServerApi::objectiveGet);
pr.get("server", api.getServerApi()::serverGet);
pr.post("server/exec", api.getServerApi()::postCommand);
pr.get("server/ops", api.getServerApi()::getOps);
pr.post("server/ops", api.getServerApi()::opPlayer);
pr.delete("server/ops", api.getServerApi()::deopPlayer);
pr.get("server/whitelist", api.getServerApi()::whitelistGet);
pr.post("server/whitelist", api.getServerApi()::whitelistPost);
pr.delete("server/whitelist", api.getServerApi()::whitelistDelete);

pr.get("worlds", api.getWorldApi()::worldsGet);
pr.post("worlds/save", api.getWorldApi()::saveAllWorlds);
pr.get("worlds/download", api.getWorldApi()::downloadWorlds);
pr.get("worlds/{uuid}", api.getWorldApi()::worldGet);
pr.post("worlds/{uuid}/save", api.getWorldApi()::saveWorld);
pr.get("worlds/{uuid}/download", api.getWorldApi()::downloadWorld);

pr.get("scoreboard", api.getServerApi()::scoreboardGet);
pr.get("scoreboard/{name}", api.getServerApi()::objectiveGet);

// Chat
pr.post("chat/broadcast", ServerApi::broadcastPost);
pr.post("chat/tell", ServerApi::tellPost);
pr.post("chat/broadcast", api.getServerApi()::broadcastPost);
pr.post("chat/tell", api.getServerApi()::tellPost);

// Player routes
pr.get("players", PlayerApi::playersGet);
pr.get("players/all", PlayerApi::offlinePlayersGet);
pr.get("players/{uuid}", PlayerApi::playerGet);
pr.get("players/{playerUuid}/{worldUuid}/inventory", PlayerApi::getPlayerInv);
pr.get("players", api.getPlayerApi()::playersGet);
pr.get("players/all", api.getPlayerApi()::offlinePlayersGet);
pr.get("players/{uuid}", api.getPlayerApi()::playerGet);
pr.get("players/{playerUuid}/{worldUuid}/inventory", api.getPlayerApi()::getPlayerInv);

// Economy routes
pr.post("economy/pay", EconomyApi::playerPay);
pr.post("economy/debit", EconomyApi::playerDebit);
pr.get("economy", EconomyApi::getEconomyPluginInformation);
pr.post("economy/pay", api.getEconomyApi()::playerPay);
pr.post("economy/debit", api.getEconomyApi()::playerDebit);
pr.get("economy", api.getEconomyApi()::getEconomyPluginInformation);

// Plugin routes
pr.get("plugins", PluginApi::listPlugins);
pr.post("plugins", PluginApi::installPlugin);
pr.get("plugins", api.getPluginApi()::listPlugins);
pr.post("plugins", api.getPluginApi()::installPlugin);

// PAPI Routes
pr.post("placeholders/replace", PAPIApi::replacePlaceholders);
pr.post("placeholders/replace", api.getPapiApi()::replacePlaceholders);

// Websocket handler
pr.ws("ws/console", WebsocketHandler::events);
pr.ws("ws/console", api.getWebsocketHandler()::events);

// Advancement routes
pr.get("advancements", AdvancementsApi::getAdvancements);
pr.get("advancements", api.getAdvancementsApi()::getAdvancements);
}

private static class PrefixedRouteBuilder {
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/io/servertap/api/v1/AdvancementsApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@
import io.javalin.openapi.OpenApiParam;
import io.javalin.openapi.OpenApiResponse;
import io.servertap.api.v1.models.Advancement;
import io.servertap.api.v1.models.Player;
import org.bukkit.Bukkit;

import java.util.ArrayList;

public class AdvancementsApi {

@OpenApi(
path = "/v1/advancements",
summary = "Gets all server advancements",
Expand All @@ -24,7 +22,7 @@ public class AdvancementsApi {
@OpenApiResponse(status = "200", content = @OpenApiContent(from = Advancement.class))
}
)
public static void getAdvancements(Context ctx) {
public void getAdvancements(Context ctx) {
final ArrayList<Advancement> advancements = new ArrayList<>();

Bukkit.advancementIterator().forEachRemaining(advancement -> {
Expand All @@ -37,4 +35,4 @@ public static void getAdvancements(Context ctx) {
ctx.json(advancements);
}

}
}
64 changes: 64 additions & 0 deletions src/main/java/io/servertap/api/v1/ApiV1Initializer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package io.servertap.api.v1;

import io.servertap.ServerTapMain;
import io.servertap.utils.ConsoleListener;
import io.servertap.api.v1.websockets.WebsocketHandler;
import io.servertap.utils.LagDetector;
import io.servertap.utils.pluginwrappers.ExternalPluginWrapperRepo;

import java.util.logging.Logger;

public class ApiV1Initializer {
private final WebsocketHandler websocketHandler;
private final AdvancementsApi advancementsApi;
private final EconomyApi economyApi;
private final PluginApi pluginApi;
private final ServerApi serverApi;
private final PlayerApi playerApi;
private final WorldApi worldApi;
private final PAPIApi papiApi;

public ApiV1Initializer(ServerTapMain main, Logger log, LagDetector lagDetector, ConsoleListener consoleListener,
ExternalPluginWrapperRepo externalPluginWrapperRepo) {
this.websocketHandler = new WebsocketHandler(main, log, consoleListener);
this.advancementsApi = new AdvancementsApi();
this.economyApi = new EconomyApi(externalPluginWrapperRepo.getEconomyWrapper());
this.pluginApi = new PluginApi(main, log);
this.serverApi = new ServerApi(main, log, lagDetector, externalPluginWrapperRepo.getEconomyWrapper());
this.playerApi = new PlayerApi(log, externalPluginWrapperRepo.getEconomyWrapper());
this.worldApi = new WorldApi(main, log);
this.papiApi = new PAPIApi();
}

public WebsocketHandler getWebsocketHandler() {
return websocketHandler;
}

public AdvancementsApi getAdvancementsApi() {
return advancementsApi;
}

public EconomyApi getEconomyApi() {
return economyApi;
}

public PluginApi getPluginApi() {
return pluginApi;
}

public ServerApi getServerApi() {
return serverApi;
}

public PlayerApi getPlayerApi() {
return playerApi;
}

public WorldApi getWorldApi() {
return worldApi;
}

public PAPIApi getPapiApi() {
return papiApi;
}
}
Loading

0 comments on commit 9acd34f

Please sign in to comment.