diff --git a/.gitignore b/.gitignore index f8c302b6..df1b3ed4 100644 --- a/.gitignore +++ b/.gitignore @@ -122,3 +122,4 @@ run/ /api/target/ /backend-api/target/ /.fastRequest/ +/deploy/ diff --git a/build.gradle b/build.gradle index d7eca954..e528365f 100644 --- a/build.gradle +++ b/build.gradle @@ -5,22 +5,46 @@ buildscript { } } dependencies { - classpath("gradle.plugin.com.github.johnrengelman:shadow:7.1.2") + classpath("com.gradleup.shadow:shadow-gradle-plugin:8.3.6") // for shadowing classpath("io.freefair.gradle:lombok-plugin:8.6") } } allprojects { + apply plugin: "java" + apply plugin: "com.gradleup.shadow" + apply plugin: "io.freefair.lombok" + apply plugin: "maven-publish" + version = rootProject.properties["version"] group = rootProject.properties["group"] + + java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + artifacts { + archives shadowJar + } + + repositories { + // Maven Defaults + mavenCentral() + mavenLocal() + maven { url "https://mvnrepository.com/artifact" } + + // JitPack + maven { url "https://jitpack.io" } + + // Local libs folder as a flat directory repository + flatDir { + dirs "${rootDir}/libs" + } + } } subprojects { - apply plugin: "java" - apply plugin: "com.github.johnrengelman.shadow" - apply plugin: "io.freefair.lombok" - apply plugin: "maven-publish" - apply from: rootDir.toString() + "/dependencies.gradle" ext { @@ -33,9 +57,6 @@ subprojects { targetCompatibility = JavaVersion.VERSION_11 repositories { - mavenCentral() - mavenLocal() - // Spigot / Bukkit maven { url "https://hub.spigotmc.org/nexus/content/repositories/snapshots" @@ -55,9 +76,6 @@ subprojects { maven { url "https://maven.fabricmc.net" } maven { url "https://libraries.minecraft.net" } - // JitPack - maven { url "https://jitpack.io" } - maven { url "https://mvnrepository.com/artifact" } // OpenCollab maven { name "opencollabRepositoryMavenSnapshots" @@ -72,11 +90,6 @@ subprojects { maven { url "https://repo.extendedclip.com/content/repositories/placeholderapi" } } - java { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 - } - processResources { // Debugging: Print values doFirst { @@ -92,7 +105,12 @@ subprojects { expand ( "name": rootProject.name.toString(), "version": rootProject.version.toString(), - "main": project.ext.pluginMain.toString(), + ) + } + filesMatching("**/velocity-plugin.json") { + expand ( + "name": rootProject.name.toString(), + "version": rootProject.version.toString(), ) } filesMatching("**/streamline.properties") { @@ -124,10 +142,6 @@ subprojects { // minimize() } - artifacts { - archives shadowJar - } - tasks.register('deploy', Copy) { // Define the deployment directory def deployDir = file(System.getenv("DEPLOY_DIR") ?: "$rootDir/deploy") @@ -168,6 +182,35 @@ subprojects { } } +//tasks.register("clearDeploys", Delete) { +// // Define the deployment directory +// def deployDir = file(System.getenv("DEPLOY_DIR") ?: "$rootDir/deploy") +// +// deployDir.mkdirs() +// File[] files = deployDir.listFiles() +// if (files != null) { +// files.each { file -> +// if (file.isFile()) { +// file.delete() +// } +// } +// } +//} + +//clean.finalizedBy(clearDeploys) +//tasks.named('clearDeploys').configure { +// dependsOn 'clean' +//} + +//clearDeploys.finalizedBy(build) +//tasks.named("build") { +// doFirst { +// tasks.named('clean') { +// it. +// } +// } +//} + wrapper { gradleVersion = "8.9" distributionType = Wrapper.DistributionType.ALL diff --git a/bungee/build.gradle b/bungee/build.gradle index da298260..744fbbc9 100644 --- a/bungee/build.gradle +++ b/bungee/build.gradle @@ -1,7 +1,6 @@ dependencies { - // Platform. - compileOnly 'net.md-5:bungeecord-api:1.20-R0.3-SNAPSHOT' - compileOnly 'net.md-5:bungeecord-parent:1.20-R0.3-SNAPSHOT' + // Platform + annotationProcessor(compileOnly('net.md-5:bungeecord-api:1.21-R0.1-SNAPSHOT')) // Defaults. compileOnly(files(FILES)) diff --git a/bungee/src/main/java/net/streamline/platform/BasePlugin.java b/bungee/src/main/java/net/streamline/platform/BasePlugin.java index 619dd3da..fdb86fe6 100644 --- a/bungee/src/main/java/net/streamline/platform/BasePlugin.java +++ b/bungee/src/main/java/net/streamline/platform/BasePlugin.java @@ -41,6 +41,7 @@ import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; +import java.util.logging.Logger; public abstract class BasePlugin extends Plugin implements ISingularityExtension { @Getter @@ -120,8 +121,6 @@ public void setupProperties() { @Override public void onEnable() { - getLogger().addHandler(new CosmicLogHandler()); - userManager = new UserManager(); messenger = new Messenger(); consoleHolder = new ConsoleHolder(); @@ -156,6 +155,8 @@ public void onDisable() { UserUtils.syncAllUsers(); UuidManager.getUuids().forEach(UuidInfo::save); + getProxy().unregisterChannel(SLAPI.getApiChannel()); + this.disable(); fireStopEvent(); @@ -349,4 +350,14 @@ public static ConcurrentSkipListMap getPlayersByUUID() { } return map; } + + @Override + public Logger getLoggerLogger() { + return getLogger(); + } + + @Override + public org.slf4j.Logger getSLFLogger() { + return null; + } } diff --git a/bungee/src/main/resources/plugin.yml b/bungee/src/main/resources/plugin.yml index 4ebbbb89..3b9a1313 100644 --- a/bungee/src/main/resources/plugin.yml +++ b/bungee/src/main/resources/plugin.yml @@ -2,7 +2,7 @@ name: '${name}' version: '${version}' main: 'net.streamline.base.StreamlineBungee' authors: - - MrDrakify + - Drak website: https://github.com/Streamline-Essentials description: True potential is here. A Proxy and Spigot plugin that opens up endless cross-platform possibilities. depend: diff --git a/dependencies.gradle b/dependencies.gradle index 4eb9e16f..a9fe0c8f 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -4,12 +4,14 @@ ext { "com.github.Server-Utilities:TheBase:master-SNAPSHOT", "org.pf4j:pf4j:3.10.0", "commons-codec:commons-codec:1.5", + "ch.qos.logback:logback-classic:1.5.6", ] SHADOW = [ "com.github.ben-manes.caffeine:caffeine:3.1.8", "com.github.Server-Utilities:TheBase:master-SNAPSHOT", "org.pf4j:pf4j:3.10.0", "commons-codec:commons-codec:1.5", + "ch.qos.logback:logback-classic:1.5.6", ] ANNO = [ "com.github.ben-manes.caffeine:caffeine:3.1.8", diff --git a/folia/build.gradle b/folia/build.gradle deleted file mode 100644 index 5fcc5d65..00000000 --- a/folia/build.gradle +++ /dev/null @@ -1,44 +0,0 @@ -repositories { - mavenLocal() - mavenCentral() - maven { - name = "papermc" - url = uri("https://repo.papermc.io/repository/maven-public/") - } - maven { - name = "papermc" - url = uri("https://repo.papermc.io/repository/maven-public/") - } -} - -dependencies { - // Platform. -// compileOnly "dev.folia:folia-api:1.20-SNAPSHOT" // currently does not work... - compileOnly(files("impl/folia-api.jar")) - compileOnly("io.papermc.paper:paper-api:1.20.2-R0.1-SNAPSHOT") - -// implementation "net.kyori:adventure-api:4.15.0" -// implementation "net.kyori:adventure-text-serializer-legacy:4.15.0" -// implementation "net.kyori:adventure-text-serializer-plain:4.15.0" -// implementation "net.kyori:adventure-text-serializer-gson:4.15.0" - - // Defaults. - compileOnly(files(FILES)) - annotationProcessor(ANNO) - compileOnly(COMP_ONLY) - - // Other Plugins - compileOnly(OTHER_PLUGINS) - implementation "com.github.hamza-cskn.obliviate-invs:core:4.1.11" - - // Streamline API. -// shadow(implementation project(":api")) - implementation project(path: ":StreamlineCore-API") - implementation project(path: ":StreamlineCore-BAPI", configuration: "shadow") -} - -java { - toolchain { - languageVersion = JavaLanguageVersion.of(17) - } -} diff --git a/folia/src/main/java/net/streamline/base/Streamline.java b/folia/src/main/java/net/streamline/base/Streamline.java deleted file mode 100644 index 908f7f3e..00000000 --- a/folia/src/main/java/net/streamline/base/Streamline.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.streamline.base; - -import lombok.Getter; -import lombok.Setter; -import net.streamline.metrics.Metrics; -import net.streamline.platform.BasePlugin; -import net.streamline.api.modules.ModuleManager; -import net.streamline.platform.commands.StreamlineSpigotCommand; - -public class Streamline extends BasePlugin { - @Getter @Setter - private static StreamlineSpigotCommand streamlineSpigotCommand; - - @Override - public void enable() { - try { - ModuleManager.registerExternalModules(); - ModuleManager.startModules(); - } catch (Exception e) { - e.printStackTrace(); - } - - Metrics metrics = new Metrics(this, 16972); - metrics.addCustomChart(new Metrics.SimplePie("plugin_version", () -> getDescription().getVersion())); - metrics.addCustomChart(new Metrics.SimplePie("modules_loaded_count", () -> String.valueOf(ModuleManager.getLoadedModules().size()))); - metrics.addCustomChart(new Metrics.SimplePie("modules_enabled_count", () -> String.valueOf(ModuleManager.getEnabledModules().size()))); - - streamlineSpigotCommand = new StreamlineSpigotCommand(); - } - - @Override - public void disable() { - ModuleManager.stopModules(); - } - - @Override - public void load() { - - } - - @Override - public void reload() { - - } -} diff --git a/folia/src/main/java/net/streamline/base/TenSecondTimer.java b/folia/src/main/java/net/streamline/base/TenSecondTimer.java deleted file mode 100644 index fbdce6c4..00000000 --- a/folia/src/main/java/net/streamline/base/TenSecondTimer.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.streamline.base; - -import lombok.Getter; -import net.streamline.api.messages.builders.PlayerLocationMessageBuilder; -import net.streamline.api.savables.users.StreamlineLocation; -import net.streamline.api.savables.users.StreamPlayer; -import net.streamline.platform.savables.UserManager; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; - -@Getter -public class TenSecondTimer implements Runnable { - final Player player; - final int taskId; - - public TenSecondTimer(Player player) { - this.player = player; - this.taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(Streamline.getInstance(), this, 20 * 2, 20 * 10); - } - - @Override - public void run() { - if (! checkPlayer()) return; - - StreamPlayer StreamPlayer = UserManager.getInstance().getOrGetPlayer(player); - - Location location = player.getLocation(); - World world = location.getWorld(); - if (world == null) world = Bukkit.getWorlds().get(0); - StreamlineLocation streamlineLocation = new StreamlineLocation(world.getName(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); - - PlayerLocationMessageBuilder.build(StreamPlayer, streamlineLocation, StreamPlayer).send(); - } - - public boolean checkPlayer() { - if (player == null) { - Bukkit.getScheduler().cancelTask(taskId); - return false; - } - if (! player.isOnline()) { - Bukkit.getScheduler().cancelTask(taskId); - return false; - } - return true; - } -} diff --git a/folia/src/main/java/net/streamline/metrics/Metrics.java b/folia/src/main/java/net/streamline/metrics/Metrics.java deleted file mode 100644 index 4d52eca3..00000000 --- a/folia/src/main/java/net/streamline/metrics/Metrics.java +++ /dev/null @@ -1,849 +0,0 @@ -package net.streamline.metrics; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.Method; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.logging.Level; -import java.util.stream.Collectors; -import java.util.zip.GZIPOutputStream; -import javax.net.ssl.HttpsURLConnection; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; - -public class Metrics { - - private final Plugin plugin; - - private final MetricsBase metricsBase; - - /** - * Creates a new Metrics instance. - * - * @param plugin Your plugin instance. - * @param serviceId The id of the service. It can be found at What is my plugin id? - */ - public Metrics(JavaPlugin plugin, int serviceId) { - this.plugin = plugin; - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - if (!config.isSet("serverUuid")) { - config.addDefault("enabled", true); - config.addDefault("serverUuid", UUID.randomUUID().toString()); - config.addDefault("logFailedRequests", false); - config.addDefault("logSentData", false); - config.addDefault("logResponseStatusText", false); - // Inform the server owners about bStats - config - .options() - .header( - "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" - + "many people use their plugin and their total player count. It's recommended to keep bStats\n" - + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" - + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" - + "anonymous.") - .copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { - } - } - // Load the data - boolean enabled = config.getBoolean("enabled", true); - String serverUUID = config.getString("serverUuid"); - boolean logErrors = config.getBoolean("logFailedRequests", false); - boolean logSentData = config.getBoolean("logSentData", false); - boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); - metricsBase = - new MetricsBase( - "bukkit", - serverUUID, - serviceId, - enabled, - this::appendPlatformData, - this::appendServiceData, - submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), - plugin::isEnabled, - (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), - (message) -> this.plugin.getLogger().log(Level.INFO, message), - logErrors, - logSentData, - logResponseStatusText); - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - metricsBase.addCustomChart(chart); - } - - private void appendPlatformData(JsonObjectBuilder builder) { - builder.appendField("playerAmount", getPlayerAmount()); - builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); - builder.appendField("bukkitVersion", Bukkit.getVersion()); - builder.appendField("bukkitName", Bukkit.getName()); - builder.appendField("javaVersion", System.getProperty("java.version")); - builder.appendField("osName", System.getProperty("os.name")); - builder.appendField("osArch", System.getProperty("os.arch")); - builder.appendField("osVersion", System.getProperty("os.version")); - builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); - } - - private void appendServiceData(JsonObjectBuilder builder) { - builder.appendField("pluginVersion", plugin.getDescription().getVersion()); - } - - private int getPlayerAmount() { - try { - // Around MC 1.8 the return type was changed from an array to a collection, - // This fixes java.lang.NoSuchMethodError: - // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - return onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - // Just use the new method if the reflection failed - return Bukkit.getOnlinePlayers().size(); - } - } - - public static class MetricsBase { - - /** The version of the Metrics class. */ - public static final String METRICS_VERSION = "3.0.0"; - - private static final ScheduledExecutorService scheduler = - Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics")); - - private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; - - private final String platform; - - private final String serverUuid; - - private final int serviceId; - - private final Consumer appendPlatformDataConsumer; - - private final Consumer appendServiceDataConsumer; - - private final Consumer submitTaskConsumer; - - private final Supplier checkServiceEnabledSupplier; - - private final BiConsumer errorLogger; - - private final Consumer infoLogger; - - private final boolean logErrors; - - private final boolean logSentData; - - private final boolean logResponseStatusText; - - private final Set customCharts = new HashSet<>(); - - private final boolean enabled; - - /** - * Creates a new MetricsBase class instance. - * - * @param platform The platform of the service. - * @param serviceId The id of the service. - * @param serverUuid The server uuid. - * @param enabled Whether or not data sending is enabled. - * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and - * appends all platform-specific data. - * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and - * appends all service-specific data. - * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be - * used to delegate the data collection to a another thread to prevent errors caused by - * concurrency. Can be {@code null}. - * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. - * @param errorLogger A consumer that accepts log message and an error. - * @param infoLogger A consumer that accepts info log messages. - * @param logErrors Whether or not errors should be logged. - * @param logSentData Whether or not the sent data should be logged. - * @param logResponseStatusText Whether or not the response status text should be logged. - */ - public MetricsBase( - String platform, - String serverUuid, - int serviceId, - boolean enabled, - Consumer appendPlatformDataConsumer, - Consumer appendServiceDataConsumer, - Consumer submitTaskConsumer, - Supplier checkServiceEnabledSupplier, - BiConsumer errorLogger, - Consumer infoLogger, - boolean logErrors, - boolean logSentData, - boolean logResponseStatusText) { - this.platform = platform; - this.serverUuid = serverUuid; - this.serviceId = serviceId; - this.enabled = enabled; - this.appendPlatformDataConsumer = appendPlatformDataConsumer; - this.appendServiceDataConsumer = appendServiceDataConsumer; - this.submitTaskConsumer = submitTaskConsumer; - this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; - this.errorLogger = errorLogger; - this.infoLogger = infoLogger; - this.logErrors = logErrors; - this.logSentData = logSentData; - this.logResponseStatusText = logResponseStatusText; - checkRelocation(); - if (enabled) { - // WARNING: Removing the option to opt-out will get your plugin banned from bStats - startSubmitting(); - } - } - - public void addCustomChart(CustomChart chart) { - this.customCharts.add(chart); - } - - private void startSubmitting() { - final Runnable submitTask = - () -> { - if (!enabled || !checkServiceEnabledSupplier.get()) { - // Submitting data or service is disabled - scheduler.shutdown(); - return; - } - if (submitTaskConsumer != null) { - submitTaskConsumer.accept(this::submitData); - } else { - this.submitData(); - } - }; - // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution - // of requests on the - // bStats backend. To circumvent this problem, we introduce some randomness into the initial - // and second delay. - // WARNING: You must not modify and part of this Metrics class, including the submit delay or - // frequency! - // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it! - long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); - long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); - scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); - scheduler.scheduleAtFixedRate( - submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); - } - - private void submitData() { - final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); - appendPlatformDataConsumer.accept(baseJsonBuilder); - final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); - appendServiceDataConsumer.accept(serviceJsonBuilder); - JsonObjectBuilder.JsonObject[] chartData = - customCharts.stream() - .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) - .filter(Objects::nonNull) - .toArray(JsonObjectBuilder.JsonObject[]::new); - serviceJsonBuilder.appendField("id", serviceId); - serviceJsonBuilder.appendField("customCharts", chartData); - baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); - baseJsonBuilder.appendField("serverUUID", serverUuid); - baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); - JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); - scheduler.execute( - () -> { - try { - // Send the data - sendData(data); - } catch (Exception e) { - // Something went wrong! :( - if (logErrors) { - errorLogger.accept("Could not submit bStats metrics data", e); - } - } - }); - } - - private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { - if (logSentData) { - infoLogger.accept("Sent bStats metrics data: " + data.toString()); - } - String url = String.format(REPORT_URL, platform); - HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setRequestProperty("User-Agent", "Metrics-Service/1"); - connection.setDoOutput(true); - try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(compressedData); - } - StringBuilder builder = new StringBuilder(); - try (BufferedReader bufferedReader = - new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - } - if (logResponseStatusText) { - infoLogger.accept("Sent data to bStats and received response: " + builder); - } - } - - /** Checks that the class was properly relocated. */ - private void checkRelocation() { - // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null - || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this little - // "trick" ... :D - final String defaultPackage = - new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); - final String examplePackage = - new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure no one just copy & pastes the example and uses the wrong package - // names - if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) - || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - - /** - * Gzips the given string. - * - * @param str The string to gzip. - * @return The gzipped string. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } - } - - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public abstract static class CustomChart { - - private final String chartId; - - protected CustomChart(String chartId) { - if (chartId == null) { - throw new IllegalArgumentException("chartId must not be null"); - } - this.chartId = chartId; - } - - public JsonObjectBuilder.JsonObject getRequestJsonObject( - BiConsumer errorLogger, boolean logErrors) { - JsonObjectBuilder builder = new JsonObjectBuilder(); - builder.appendField("chartId", chartId); - try { - JsonObjectBuilder.JsonObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - builder.appendField("data", data); - } catch (Throwable t) { - if (logErrors) { - errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return builder.build(); - } - - protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; - } - - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("value", value).build(); - } - } - - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("value", value).build(); - } - } - - /** - * An extremely simple JSON builder. - * - *

While this class is neither feature-rich nor the most performant one, it's sufficient enough - * for its use-case. - */ - public static class JsonObjectBuilder { - - private StringBuilder builder = new StringBuilder(); - - private boolean hasAtLeastOneField = false; - - public JsonObjectBuilder() { - builder.append("{"); - } - - /** - * Appends a null field to the JSON. - * - * @param key The key of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendNull(String key) { - appendFieldUnescaped(key, "null"); - return this; - } - - /** - * Appends a string field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String value) { - if (value == null) { - throw new IllegalArgumentException("JSON value must not be null"); - } - appendFieldUnescaped(key, "\"" + escape(value) + "\""); - return this; - } - - /** - * Appends an integer field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int value) { - appendFieldUnescaped(key, String.valueOf(value)); - return this; - } - - /** - * Appends an object to the JSON. - * - * @param key The key of the field. - * @param object The object. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject object) { - if (object == null) { - throw new IllegalArgumentException("JSON object must not be null"); - } - appendFieldUnescaped(key, object.toString()); - return this; - } - - /** - * Appends a string array to the JSON. - * - * @param key The key of the field. - * @param values The string array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values) - .map(value -> "\"" + escape(value) + "\"") - .collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an integer array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an object array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends a field to the object. - * - * @param key The key of the field. - * @param escapedValue The escaped value of the field. - */ - private void appendFieldUnescaped(String key, String escapedValue) { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - if (key == null) { - throw new IllegalArgumentException("JSON key must not be null"); - } - if (hasAtLeastOneField) { - builder.append(","); - } - builder.append("\"").append(escape(key)).append("\":").append(escapedValue); - hasAtLeastOneField = true; - } - - /** - * Builds the JSON string and invalidates this builder. - * - * @return The built JSON string. - */ - public JsonObject build() { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - JsonObject object = new JsonObject(builder.append("}").toString()); - builder = null; - return object; - } - - /** - * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. - * - *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. - * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). - * - * @param value The value to escape. - * @return The escaped value. - */ - private static String escape(String value) { - final StringBuilder builder = new StringBuilder(); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (c == '"') { - builder.append("\\\""); - } else if (c == '\\') { - builder.append("\\\\"); - } else if (c <= '\u000F') { - builder.append("\\u000").append(Integer.toHexString(c)); - } else if (c <= '\u001F') { - builder.append("\\u00").append(Integer.toHexString(c)); - } else { - builder.append(c); - } - } - return builder.toString(); - } - - /** - * A super simple representation of a JSON object. - * - *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not - * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, - * JsonObject)}. - */ - public static class JsonObject { - - private final String value; - - private JsonObject(String value) { - this.value = value; - } - - @Override - public String toString() { - return value; - } - } - } -} \ No newline at end of file diff --git a/folia/src/main/java/net/streamline/platform/BasePlugin.java b/folia/src/main/java/net/streamline/platform/BasePlugin.java deleted file mode 100644 index 85957b71..00000000 --- a/folia/src/main/java/net/streamline/platform/BasePlugin.java +++ /dev/null @@ -1,458 +0,0 @@ -package net.streamline.platform; - -import lombok.Getter; -import lombok.Setter; -import net.streamline.api.SLAPI; -import net.streamline.api.configs.given.GivenConfigs; -import net.streamline.api.events.StreamlineEvent; -import net.streamline.api.events.server.ServerStopEvent; -import net.streamline.api.interfaces.IProperEvent; -import net.streamline.api.interfaces.IStreamline; -import net.streamline.api.logging.StreamlineLogHandler; -import net.streamline.api.modules.ModuleUtils; -import net.streamline.api.objects.StreamlineResourcePack; -import net.streamline.api.savables.users.StreamlineConsole; -import net.streamline.api.savables.users.StreamPlayer; -import net.streamline.api.permissions.MessageUtils; -import net.streamline.api.permissions.UserUtils; -import net.streamline.apib.SLAPIB; -import net.streamline.platform.commands.ProperCommand; -import net.streamline.api.command.StreamlineCommand; -import net.streamline.platform.handlers.BackendHandler; -import net.streamline.platform.messaging.ProxyPluginMessenger; -import net.streamline.platform.profile.SpigotProfiler; -import net.streamline.platform.savables.UserManager; -import net.streamline.platform.listeners.PlatformListener; -import org.bukkit.Bukkit; -import org.bukkit.Server; -import org.bukkit.command.Command; -import org.bukkit.command.CommandMap; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.Listener; -import org.bukkit.plugin.java.JavaPlugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import tv.quaint.events.BaseEventHandler; - -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentSkipListSet; - -public abstract class BasePlugin extends JavaPlugin implements IStreamline { - public static class Runner implements Runnable { - public Runner() { - MessageUtils.logInfo("Task Runner registered!"); - } - - @Override - public void run() { - SLAPI.getMainScheduler().tick(); - } - } - - @Getter - private final PlatformType platformType = PlatformType.SPIGOT; - @Getter - private final ServerType serverType = ServerType.BACKEND; - - @Getter @Setter - private StreamlineResourcePack resourcePack; - - @Getter - private final String version = "${{project.version}}"; - @Getter - private static BasePlugin instance; - @Getter - private SLAPI slapi; - @Getter - private SLAPIB slapiB; - - public Server getProxy() { - return getServer(); - } - - @Getter - private UserManager userManager; - @Getter - private Messenger messenger; - - @Override - public void onLoad() { - instance = this; - - String parentPath = getDataFolder().getParent(); - if (parentPath != null) { - File parentFile = new File(parentPath); - File[] files = parentFile.listFiles((f) -> { - if (! f.isDirectory()) return false; - if (f.getName().equals("StreamlineAPI")) return true; - return false; - }); - - if (files != null) { - Arrays.stream(files).forEach(file -> { - file.renameTo(new File(parentPath, "StreamlineCore")); - }); - } - } - - setupCommandMap(); - - this.load(); - } - - @Override - public void onEnable() { - getLogger().addHandler(new StreamlineLogHandler()); - - userManager = new UserManager(); - messenger = new Messenger(); - slapi = new SLAPI<>(getName(), this, getUserManager(), getMessenger()); - SLAPI.setBackendHandler(new BackendHandler()); - slapiB = new SLAPIB(getSlapi(), this); - - getSlapi().setProxyMessenger(new ProxyPluginMessenger()); - getSlapi().setProfiler(new SpigotProfiler()); - - getProxy().getScheduler().scheduleSyncRepeatingTask(this, new Runner(), 0, 1); - - getProxy().getMessenger().registerOutgoingPluginChannel(this, SLAPI.getApiChannel()); - getProxy().getMessenger().registerIncomingPluginChannel(this, SLAPI.getApiChannel(), new PlatformListener.ProxyMessagingListener()); - - this.enable(); - registerListener(new PlatformListener()); - } - - @Override - public void onDisable() { - for (StreamPlayer user : UserUtils.getLoadedUsersSet()) { - user.saveAll(); - } - - this.disable(); - fireStopEvent(); - } - - public void fireStopEvent() { - ServerStopEvent e = new ServerStopEvent().fire(); - if (e.isCancelled()) return; - if (! e.isSendable()) return; - ModuleUtils.sendMessage(ModuleUtils.getConsole(), e.getMessage()); - } - - abstract public void enable(); - - abstract public void disable(); - - abstract public void load(); - - abstract public void reload(); - - public static void registerListener(Listener listener) { - getInstance().getProxy().getPluginManager().registerEvents(listener, getInstance()); - } - - @Override - public @NotNull ConcurrentSkipListSet getOnlinePlayers() { - ConcurrentSkipListSet players = new ConcurrentSkipListSet<>(); - - for (Player player : onlinePlayers()) { - players.add(getUserManager().getOrGetPlayer(player)); - } - - return players; - } - - @Override - public ProperCommand createCommand(StreamlineCommand command) { - return new ProperCommand(command); - } - - @Override - public int getMaxPlayers() { - return getInstance().getProxy().getMaxPlayers(); - } - - @Override - public ConcurrentSkipListSet getOnlinePlayerNames() { - ConcurrentSkipListSet r = new ConcurrentSkipListSet<>(); - - getOnlinePlayers().forEach(a -> { - r.add(a.getName()); - }); - -// r.add(getUserManager().getConsole().latestName); - - return r; - } - - @Override - public long getConnectionThrottle() { - return getInstance().getProxy().getConnectionThrottle(); - } - - public static List onlinePlayers() { - return new ArrayList<>(getInstance().getProxy().getOnlinePlayers()); - } - - public static List playersOnServer(String serverName) { - return new ArrayList<>(/*getInstance().getProxy().gets(serverName).getPlayers()*/); - } - - public static Player getPlayer(String uuid) { - for (Player player : onlinePlayers()) { - if (player.getUniqueId().toString().equals(uuid)) return player; - } - - return null; - } - - public static Optional getPlayerByName(String name) { - return Optional.ofNullable(getInstance().getProxy().getPlayer(name)); - } - - public static @Nullable Player getPlayerExact(@NotNull String name) { - if (getPlayerByName(name).isEmpty()) return null; - return getPlayerByName(name).get(); - } - - public static @NotNull List matchPlayer(@NotNull String name) { - Player player = getPlayerExact(name); - if (player == null) return new ArrayList<>(); - return List.of(player); - } - - public static @Nullable Player getPlayer(@NotNull UUID id) { - return getPlayer(id.toString()); - } - - public static Player getPlayer(CommandSender sender) { - return getInstance().getProxy().getPlayer(sender.getName()); - } - - @Override - public boolean getOnlineMode() { - return getInstance().getProxy().getOnlineMode(); - } - - @Override - public void shutdown() { - getInstance().getProxy().shutdown(); - } - - @Override - public int broadcast(@NotNull String message, @NotNull String permission) { - int people = 0; - - for (Player player : onlinePlayers()) { - if (! player.hasPermission(permission)) continue; - getMessenger().sendMessage(player, message); - people ++; - } - - return people; - } - - @Override - public boolean hasPermission(StreamPlayer user, String permission) { - Player player = getPlayer(user.getUuid()); - if (player == null) return false; - return player.hasPermission(permission); - } - - @Override - public void chatAs(StreamPlayer as, String message) { - if (as instanceof StreamlineConsole) { - runAsStrictly(as, message); - } - if (as instanceof StreamPlayer) { - if (MessageUtils.isCommand(message)) runAsStrictly(as, message.substring("/".length())); - Player player = getPlayer(as.getUuid()); - if (player == null) return; - player.chat(message); - } - } - - @Override - public void runAsStrictly(StreamPlayer as, String command) { - if (as instanceof StreamlineConsole) { - getInstance().getProxy().dispatchCommand(getInstance().getProxy().getConsoleSender(), command); - } - if (as instanceof StreamPlayer) { - if (MessageUtils.isCommand(command)) runAsStrictly(as, command.substring("/".length())); - Player player = getPlayer(as.getUuid()); - if (player == null) return; - getInstance().getProxy().dispatchCommand(player, command); - } - } - - @Override - public boolean serverHasPlugin(String plugin) { - return getInstance().getProxy().getPluginManager().getPlugin(plugin) != null; - } - - @Override - public boolean equalsAnyServer(String servername) { - return getServerNames().contains(servername); - } - - @Override - public void fireEvent(IProperEvent event) { - if (! (event.getEvent() instanceof Event)) return; - Event e = (Event) event.getEvent(); - getInstance().getProxy().getPluginManager().callEvent(e); - } - - @Override - public void fireEvent(StreamlineEvent event) { - fireEvent(event, true); - } - - @Override - public void fireEvent(StreamlineEvent event, boolean async) { - try { - BaseEventHandler.fireEvent(event); - } catch (Exception e) { - handleMisSync(event, async); - } - } - - @Override - public void handleMisSync(StreamlineEvent event, boolean async) { - BaseEventHandler.fireEvent(event); - } - - @Override - public ConcurrentSkipListSet getServerNames() { - return new ConcurrentSkipListSet<>(GivenConfigs.getProfileConfig().getCachedProfile().getServers().keySet()); - } - - @Override - public void sendResourcePack(StreamlineResourcePack resourcePack, StreamPlayer player) { - Player p = getPlayer(player.getUuid()); - sendResourcePack(resourcePack, p); - } - - @Override - public void sendResourcePack(StreamlineResourcePack resourcePack, String uuid) { - Player p = getPlayer(uuid); - -// getMessenger().logInfo("Attempting to send a resource pack to a uuid of '" + whitelistedUuid + "'..."); - - sendResourcePack(resourcePack, p); - } - - public void sendResourcePack(StreamlineResourcePack resourcePack, Player player) { - if (player == null) { - MessageUtils.logWarning("Tried to send a player a resource pack, but could not find their player!"); - return; - } - -// getMessenger().logInfo("Sending resource pack to '" + player.getName() + "'."); - - try { - if (resourcePack.getHash().length > 0) { - if (! resourcePack.getPrompt().isEmpty()) { - player.setResourcePack(resourcePack.getUrl(), resourcePack.getHash(), resourcePack.getPrompt(), resourcePack.isForce()); - return; - } - player.setResourcePack(resourcePack.getUrl(), resourcePack.getHash(), resourcePack.isForce()); - return; - } - player.setResourcePack(resourcePack.getUrl()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public ClassLoader getMainClassLoader() { - return getProxy().getClass().getClassLoader(); - } - - @Getter @Setter - private static boolean commandsNeedToBeSynced = false; - - @Getter @Setter - private static CommandMap commandMap; - - private static void setupCommandMap() { - try { - final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap"); - bukkitCommandMap.setAccessible(true); - commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Register command(s) into the server command map. - * @param commands The command(s) to register - */ - public static void registerCommands(ProperCommand... commands) { - // Get the commandMap - try { - // Register all the commands into the map - for (final ProperCommand command : commands) { - commandMap.register(command.getLabel(), command.getParent().getBase(), command); - } - - CompletableFuture.runAsync(BasePlugin::syncCommands); - } catch (final Exception exception) { - exception.printStackTrace(); - } - } - - /** - * Unregister command(s) from the server command map. - * @param commands The command(s) to unregister - */ - public static void unregisterCommands(String... commands) { - // Get the commandMap - try { - // Register all the commands into the map - for (final String command : commands) { - Command com = commandMap.getCommand(command); - if (com == null) { - MessageUtils.logDebug("Tried to unregister a command that does not exist: " + command); - continue; - } - - com.unregister(commandMap); - } - - CompletableFuture.runAsync(BasePlugin::syncCommands); - } catch (final Exception e) { - MessageUtils.logWarningWithInfo("Failed to unregister commands: ", e); - } - } - - public static void syncCommands() { - try { - // Get the CraftServer class - Class craftServerClass = Bukkit.getServer().getClass(); - - // Attempt to find the syncCommands method - try { - Method syncCommandsMethod = craftServerClass.getDeclaredMethod("syncCommands"); - syncCommandsMethod.setAccessible(true); - - // Invoke the syncCommands method - syncCommandsMethod.invoke(Bukkit.getServer()); - } catch (NoSuchMethodException e) { - MessageUtils.logDebugWithInfo("syncCommands method not found: ", e); - } catch (IllegalAccessException | InvocationTargetException e) { - MessageUtils.logDebugWithInfo("Failed to invoke syncCommands method: ", e); - } - } catch (Exception e) { - MessageUtils.logDebugWithInfo("An unknown error occurred while syncing commands: ", e); - } - } -} diff --git a/folia/src/main/java/net/streamline/platform/Messenger.java b/folia/src/main/java/net/streamline/platform/Messenger.java deleted file mode 100644 index aa7b6765..00000000 --- a/folia/src/main/java/net/streamline/platform/Messenger.java +++ /dev/null @@ -1,238 +0,0 @@ -package net.streamline.platform; - -import lombok.Getter; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.TextColor; -import net.kyori.adventure.text.serializer.json.JSONComponentSerializer; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.streamline.api.SLAPI; -import net.streamline.api.interfaces.IMessenger; -import net.streamline.api.modules.ModuleUtils; -import net.streamline.api.objects.StreamlineTitle; -import net.streamline.api.savables.users.StreamlineConsole; -import net.streamline.api.savables.users.StreamPlayer; -import net.streamline.api.text.HexPolicy; -import net.streamline.api.text.TextManager; -import net.streamline.api.permissions.MessageUtils; -import net.streamline.base.Streamline; -import net.streamline.platform.savables.UserManager; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class Messenger implements IMessenger { - @Getter - private static Messenger instance; - - public Messenger() { - instance = this; - } - - public void sendMessage(@Nullable CommandSender to, String message) { - if (to == null) return; - if (! SLAPI.isReady()) { - try { - to.sendMessage(codedText(message)); - } catch (NoSuchMethodError e) { - to.sendMessage(codedString(message)); - } - } else { - try { - to.sendMessage(codedText(replaceAllPlayerBungee(to, message))); - } catch (NoSuchMethodError e) { - to.sendMessage(codedString(replaceAllPlayerBungee(to, message))); - } - } - } - - public void sendMessage(@Nullable CommandSender to, String otherUUID, String message) { - if (to == null) return; - if (! SLAPI.isReady()) { - try { - to.sendMessage(codedText(message)); - } catch (NoSuchMethodError e) { - to.sendMessage(codedString(message)); - } - } else { - try { - to.sendMessage(codedText(MessageUtils.replaceAllPlayerBungee(otherUUID, message))); - } catch (NoSuchMethodError e) { - to.sendMessage(codedString(MessageUtils.replaceAllPlayerBungee(otherUUID, message))); - } - } - } - public void sendMessage(@Nullable CommandSender to, StreamPlayer other, String message) { - if (to == null) return; - if (! SLAPI.isReady()) { - try { - to.sendMessage(codedText(message)); - } catch (NoSuchMethodError e) { - to.sendMessage(codedString(message)); - } - } else { - try { - to.sendMessage(codedText(MessageUtils.replaceAllPlayerBungee(other, message))); - } catch (NoSuchMethodError e) { - to.sendMessage(codedString(MessageUtils.replaceAllPlayerBungee(other, message))); - } - } - } - - public void sendMessage(@Nullable StreamPlayer to, String message) { - if (to instanceof StreamlineConsole) sendMessage(Streamline.getInstance().getProxy().getConsoleSender(), message); - if (to == null) return; - sendMessage(Streamline.getPlayer(to.getUuid()), message); - } - - public void sendMessage(@Nullable StreamPlayer to, String otherUUID, String message) { - if (to instanceof StreamlineConsole) sendMessage(Streamline.getInstance().getProxy().getConsoleSender(), otherUUID, message); - if (to == null) return; - sendMessage(Streamline.getPlayer(to.getUuid()), otherUUID, message); - } - - public void sendMessage(@Nullable StreamPlayer to, StreamPlayer other, String message) { - if (to instanceof StreamlineConsole) sendMessage(Streamline.getInstance().getProxy().getConsoleSender(), other, message); - if (to == null) return; - sendMessage(Streamline.getPlayer(to.getUuid()), other, message); - } - - public void sendMessageRaw(CommandSender to, String message) { - if (to == null) return; - - String r = message; - if (SLAPI.isReady()) { - r = replaceAllPlayerBungee(to, message); - } - - to.sendMessage(r); - } - - public void sendMessageRaw(CommandSender to, String otherUUID, String message) { - if (to == null) return; - - String r = message; - if (SLAPI.isReady()) { - r = MessageUtils.replaceAllPlayerBungee(otherUUID, message); - } - - to.sendMessage(r); - } - - public void sendMessageRaw(CommandSender to, StreamPlayer other, String message) { - if (to == null) return; - - String r = message; - if (SLAPI.isReady()) { - r = MessageUtils.replaceAllPlayerBungee(other, message); - } - - to.sendMessage(r); - } - - public void sendMessageRaw(@Nullable StreamPlayer to, String message) { - if (to instanceof StreamlineConsole) sendMessage(Bukkit.getConsoleSender(), message); - if (to == null) return; - sendMessageRaw(Streamline.getPlayer(to.getUuid()), message); - } - - public void sendMessageRaw(@Nullable StreamPlayer to, String otherUUID, String message) { - if (to instanceof StreamlineConsole) sendMessageRaw(Bukkit.getConsoleSender(), otherUUID, message); - if (to == null) return; - sendMessageRaw(Streamline.getPlayer(to.getUuid()), otherUUID, message); - } - - public void sendMessageRaw(@Nullable StreamPlayer to, StreamPlayer other, String message) { - if (to instanceof StreamlineConsole) sendMessageRaw(Bukkit.getConsoleSender(), other, message); - if (to == null) return; - sendMessageRaw(Streamline.getPlayer(to.getUuid()), other, message); - } - - public void sendTitle(StreamPlayer player, StreamlineTitle title) { - Player p = Streamline.getPlayer(player.getUuid()); - if (p == null) { - MessageUtils.logInfo("Could not send a title to a player because player is null!"); - return; - } - - - p.sendTitle(title.getMain(), - title.getSub(), - (int) title.getFadeIn(), - (int) title.getStay(), - (int) title.getFadeOut() - ); - } - - @Override - public String codedString(String from) { - return ChatColor.translateAlternateColorCodes('&', ModuleUtils.newLined(from)); - } - - public String stripColor(String string){ - return ChatColor.stripColor(string).replaceAll("([<][#][1-9a-f][1-9a-f][1-9a-f][1-9a-f][1-9a-f][1-9a-f][>])+", ""); - } - public String asString(Component textComponent){ - return LegacyComponentSerializer.legacySection().serialize(textComponent); - } - - public static Component legacyCode(String from) { - return LegacyComponentSerializer.builder().extractUrls().character('&').hexColors().build().deserialize(from); - } - - public Component codedText(String from) { - String raw = codedString(from); // Assuming codedString is another method you've implemented - - String legacy = MessageUtils.codedString(raw); // Replace this with your actual legacy converter - - List componentsList = new ArrayList<>(); - - // Handle hex codes - for (HexPolicy policy : TextManager.getHexPolicies()) { - for (String hexCode : TextManager.extractHexCodes(legacy, policy)) { - String original = hexCode; - if (! hexCode.startsWith("#")) hexCode = "#" + hexCode; - legacy = legacy.replace(policy.getResult(original), - LegacyComponentSerializer.legacyAmpersand().serialize(Component.text("", TextColor.fromCSSHexString(hexCode)))); - } - } - - List jsonStrings = TextManager.extractJsonStrings(legacy, "!!json:"); - - int lastEnd = 0; - - for (String jsonStr : jsonStrings) { - int index = legacy.indexOf("!!json:" + jsonStr); - String before = legacy.substring(lastEnd, index); - Component beforeComponent = LegacyComponentSerializer.legacyAmpersand().deserialize(before); - componentsList.add(beforeComponent); - - try { - Component jsonComponent = JSONComponentSerializer.json().deserialize(jsonStr); - componentsList.add(jsonComponent); - } catch (Exception e) { - // Handle exception - e.printStackTrace(); - } - - lastEnd = index + jsonStr.length() + 7; // 7 is the length of "!!json:" - } - - // Append any remaining text after the last JSON block - if (lastEnd < legacy.length()) { - Component remainingComponent = LegacyComponentSerializer.legacyAmpersand().deserialize(legacy.substring(lastEnd)); - componentsList.add(remainingComponent); - } - - return Component.empty().children(componentsList); - } - - public String replaceAllPlayerBungee(CommandSender sender, String of) { - return MessageUtils.replaceAllPlayerBungee(UserManager.getInstance().getOrGetUser(sender), of); - } -} diff --git a/folia/src/main/java/net/streamline/platform/commands/ProperCommand.java b/folia/src/main/java/net/streamline/platform/commands/ProperCommand.java deleted file mode 100644 index 2aee0722..00000000 --- a/folia/src/main/java/net/streamline/platform/commands/ProperCommand.java +++ /dev/null @@ -1,72 +0,0 @@ -package net.streamline.platform.commands; - -import lombok.Getter; -import net.streamline.api.command.StreamlineCommand; -import net.streamline.api.command.result.CommandResult; -import net.streamline.api.interfaces.IProperCommand; -import net.streamline.api.permissions.MessageUtils; -import net.streamline.api.permissions.UserUtils; -import net.streamline.base.Streamline; -import net.streamline.platform.savables.UserManager; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabExecutor; -import org.bukkit.command.defaults.BukkitCommand; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentSkipListSet; - -@Getter -public class ProperCommand extends BukkitCommand implements TabExecutor, IProperCommand { - private final StreamlineCommand parent; - - public ProperCommand(StreamlineCommand parent) { - super(parent.getBase(), "Not defined.", "Not defined.", List.of(parent.getAliases())); - this.parent = parent; - } - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - return execute(sender, label, args); - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if (args == null) args = new String[] { "" }; - if (args.length < 1) args = new String[] { "" }; - ConcurrentSkipListSet r = parent.baseTabComplete(UserUtils.getOrGetUserByName(sender.getName()), args); - - return r == null ? new ArrayList<>() : new ArrayList<>(MessageUtils.getCompletion(r, args[args.length - 1])); - } - - public void register() { - try { - Streamline.registerCommands(this); - } catch(Exception e) { - e.printStackTrace(); - } - } - - public void unregister() { - try { - Streamline.unregisterCommands(getParent().getBase()); - } catch(Exception e) { - e.printStackTrace(); - } - } - - @Override - public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { - CommandResult result = parent.baseRun(UserManager.getInstance().getOrGetUser(sender), args); - - if (result == null) return false; - if (result == StreamlineCommand.notSet()) return true; - if (result == StreamlineCommand.error()) return false; - if (result == StreamlineCommand.failure()) return false; - return result == StreamlineCommand.success(); - } -} diff --git a/folia/src/main/java/net/streamline/platform/commands/StreamlineSpigotCommand.java b/folia/src/main/java/net/streamline/platform/commands/StreamlineSpigotCommand.java deleted file mode 100644 index fb469313..00000000 --- a/folia/src/main/java/net/streamline/platform/commands/StreamlineSpigotCommand.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.streamline.platform.commands; - -import net.streamline.api.command.CommandHandler; -import net.streamline.api.command.StreamlineCommand; -import net.streamline.api.modules.ModuleUtils; -import net.streamline.api.savables.users.StreamPlayer; -import net.streamline.base.Streamline; -import net.streamline.platform.Messenger; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabExecutor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import tv.quaint.utils.StringUtils; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -public class StreamlineSpigotCommand implements TabExecutor { - public StreamlineSpigotCommand() { - try { - Objects.requireNonNull(Streamline.getInstance().getCommand("streamlinespigot")).setExecutor(this); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if (args == null) args = new String[] { "" }; - String commandName = context.getStringArg(0); - - StreamlineCommand streamlineCommand = CommandHandler.getStreamlineCommand(commandName); - if (streamlineCommand == null) { - sender.sendMessage(Messenger.getInstance().codedText("&cCommand not found!")); - return true; - } - - String[] newArgs = StringUtils.argsMinus(args, 0); - - StreamPlayer senderUser = ModuleUtils.getOrGetUserByName(sender.getName()); - if (senderUser == null) { - sender.sendMessage(Messenger.getInstance().codedText("&cCould not find your user...")); - return true; - } - - streamlineCommand.baseRun(senderUser, newArgs); - return true; - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if (args.length == 0) { - return StringUtils.getAsCompletionList("", - CommandHandler.getLoadedStreamlineCommands().values().stream().map(StreamlineCommand::getBase).collect(Collectors.toList())); - } - if (args.length == 1) { - return StringUtils.getAsCompletionList(context.getStringArg(0), - CommandHandler.getLoadedStreamlineCommands().values().stream().map(StreamlineCommand::getBase).collect(Collectors.toList())); - } - - String commandName = context.getStringArg(0); - - StreamlineCommand streamlineCommand = CommandHandler.getStreamlineCommand(commandName); - if (streamlineCommand == null) return null; - - String[] newArgs = StringUtils.argsMinus(args, 0); - - StreamPlayer senderUser = ModuleUtils.getOrGetUserByName(sender.getName()); - if (senderUser == null) return null; - - return new ArrayList<>(streamlineCommand.baseTabComplete(senderUser, newArgs)); - } -} diff --git a/folia/src/main/java/net/streamline/platform/events/ProperEvent.java b/folia/src/main/java/net/streamline/platform/events/ProperEvent.java deleted file mode 100644 index 18b123eb..00000000 --- a/folia/src/main/java/net/streamline/platform/events/ProperEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.streamline.platform.events; - -import lombok.Getter; -import lombok.Setter; -import net.streamline.api.events.StreamlineEvent; -import net.streamline.api.interfaces.IProperEvent; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -import java.util.concurrent.ConcurrentHashMap; - -public class ProperEvent extends Event implements IProperEvent { - @Getter @Setter - private Event event; - @Getter @Setter - StreamlineEvent streamlineEvent; - - @Getter @Setter - private static ConcurrentHashMap handlerMap = new ConcurrentHashMap<>(); - - public static HandlerList getHandlerList() { - return new HandlerList(); - } - - public static void addHandler(StreamlineEvent event, HandlerList list) { - handlerMap.put(event, list); - } - - public ProperEvent(StreamlineEvent streamlineEvent) { - this(streamlineEvent, false); - } - - public ProperEvent(StreamlineEvent streamlineEvent, boolean async) { - super(async); - setEvent(this); - setStreamlineEvent(streamlineEvent); - } - - @NotNull - @Override - public HandlerList getHandlers() { - HandlerList list = ProperEvent.getHandlerMap().get(this.getStreamlineEvent()); - if (list == null) { - list = new HandlerList(); - ProperEvent.getHandlerMap().put(this.getStreamlineEvent(), list); - } - return list; - } -} diff --git a/folia/src/main/java/net/streamline/platform/handlers/BackendHandler.java b/folia/src/main/java/net/streamline/platform/handlers/BackendHandler.java deleted file mode 100644 index 4542c459..00000000 --- a/folia/src/main/java/net/streamline/platform/handlers/BackendHandler.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.streamline.platform.handlers; - -import net.streamline.api.interfaces.IBackendHandler; -import net.streamline.api.savables.users.StreamlineLocation; -import net.streamline.api.savables.users.StreamPlayer; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.util.UUID; - -public class BackendHandler implements IBackendHandler { - @Override - public void teleport(StreamPlayer player, StreamlineLocation location) { - Player p = Bukkit.getPlayer(UUID.fromString(player.getUuid())); - if (p == null) return; - - Location l = new Location(Bukkit.getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); - - p.teleport(l); - } -} diff --git a/folia/src/main/java/net/streamline/platform/listeners/PlatformListener.java b/folia/src/main/java/net/streamline/platform/listeners/PlatformListener.java deleted file mode 100644 index 4e81e43e..00000000 --- a/folia/src/main/java/net/streamline/platform/listeners/PlatformListener.java +++ /dev/null @@ -1,210 +0,0 @@ -package net.streamline.platform.listeners; - -import lombok.Getter; -import lombok.Setter; -import net.streamline.api.SLAPI; -import net.streamline.api.configs.given.CachedUUIDsHandler; -import net.streamline.api.configs.given.GivenConfigs; -import net.streamline.api.configs.given.MainMessagesHandler; -import net.streamline.api.configs.given.whitelist.WhitelistConfig; -import net.streamline.api.configs.given.whitelist.WhitelistEntry; -import net.streamline.api.events.server.*; -import net.streamline.api.events.server.ping.PingReceivedEvent; -import net.streamline.api.messages.events.ProxyMessageInEvent; -import net.streamline.api.messages.proxied.ProxiedMessage; -import net.streamline.api.modules.ModuleManager; -import net.streamline.api.modules.ModuleUtils; -import net.streamline.api.objects.PingedResponse; -import net.streamline.api.savables.users.StreamPlayer; -import net.streamline.api.permissions.MessageUtils; -import net.streamline.api.permissions.UserUtils; -import net.streamline.base.Streamline; -import net.streamline.base.TenSecondTimer; -import net.streamline.platform.events.ProperEvent; -import net.streamline.platform.savables.UserManager; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.AsyncPlayerPreLoginEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.server.ServerListPingEvent; -import org.bukkit.event.server.ServerLoadEvent; -import org.bukkit.plugin.messaging.PluginMessageListener; -import org.bukkit.util.CachedServerIcon; -import org.jetbrains.annotations.NotNull; -import tv.quaint.events.BaseEventHandler; -import tv.quaint.events.BaseEventListener; -import tv.quaint.events.processing.BaseProcessor; - -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; - -public class PlatformListener implements Listener { - @Getter @Setter - private static boolean messaged = false; - @Getter @Setter - private static boolean joined = false; - @Getter @Setter - private static BaseProcessorListener processorListener; - - public static boolean isTested() { - return isMessaged() && isJoined(); - } - - public PlatformListener() { - MessageUtils.logInfo("BaseListener registered!"); - setProcessorListener(new BaseProcessorListener()); - ModuleUtils.listen(getProcessorListener(), SLAPI.getBaseModule()); - } - - @EventHandler - public void onPreJoin(AsyncPlayerPreLoginEvent event) { - StreamPlayer user = UserUtils.getOrGetUserByName(event.getName()); - if (! (user instanceof StreamPlayer)) return; - StreamPlayer player = (StreamPlayer) user; - - WhitelistConfig whitelistConfig = GivenConfigs.getWhitelistConfig(); - if (whitelistConfig.isEnabled()) { - WhitelistEntry entry = whitelistConfig.getEntry(player.getUuid()); - if (entry == null) { - event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST, MessageUtils.codedString(MainMessagesHandler.MESSAGES.INVALID.WHITELIST_NOT.get())); - return; - } - } - - LoginReceivedEvent loginReceivedEvent = new LoginReceivedEvent(player); - BaseEventHandler.fireEvent(loginReceivedEvent); - - if (loginReceivedEvent.getResult().isCancelled()) { - if (! loginReceivedEvent.getResult().validate()) return; - - event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, MessageUtils.codedString(loginReceivedEvent.getResult().getDisconnectMessage())); - } - } - - @EventHandler - public void onJoin(PlayerJoinEvent event) { - Player player = event.getPlayer(); - - CachedUUIDsHandler.cachePlayer(player.getUniqueId().toString(), player.getName()); - - StreamPlayer StreamPlayer = UserManager.getInstance().getOrGetPlayer(player); - StreamPlayer.setLatestIP(UserManager.getInstance().parsePlayerIP(player)); - StreamPlayer.setLatestName(player.getName()); - - LoginCompletedEvent loginCompletedEvent = new LoginCompletedEvent(StreamPlayer); - ModuleUtils.fireEvent(loginCompletedEvent); - - setJoined(true); - - new TenSecondTimer(player); - } - - @EventHandler - public void onLeave(PlayerQuitEvent event) { - String uuid = event.getPlayer().getUniqueId().toString(); - StreamPlayer StreamPlayer = UserUtils.getOrGetPlayer(uuid); - if (StreamPlayer == null) return; - - LogoutEvent logoutEvent = new LogoutEvent(StreamPlayer); - ModuleUtils.fireEvent(logoutEvent); - - StreamPlayer.getStorageResource().sync(); - UserUtils.unloadUser(StreamPlayer); - } - - @EventHandler - public void onChat(AsyncPlayerChatEvent event) { - Player player = event.getPlayer(); - - StreamPlayer StreamPlayer = UserManager.getInstance().getOrGetPlayer(player); - StreamlineChatEvent chatEvent = new StreamlineChatEvent(StreamPlayer, event.getMessage()); - Streamline.getInstance().fireEvent(chatEvent, true); - if (chatEvent.isCanceled()) { - event.setCancelled(true); - return; - } - event.setMessage(chatEvent.getMessage()); - } - - @EventHandler - public void onProperEvent(ProperEvent event) { - ModuleManager.fireEvent(event.getStreamlineEvent()); - } - - public static class ProxyMessagingListener implements PluginMessageListener { - public ProxyMessagingListener() { - MessageUtils.logInfo("Registered " + getClass().getSimpleName() + "!"); - } - - @Override - public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte @NotNull [] message) { - StreamPlayer StreamPlayer = UserManager.getInstance().getOrGetPlayer(player); - - try { - ProxiedMessage messageIn = new ProxiedMessage(StreamPlayer, true, message, channel); - ProxyMessageInEvent e = new ProxyMessageInEvent(messageIn); - ModuleUtils.fireEvent(e); - if (e.isCancelled()) return; - SLAPI.getInstance().getProxyMessenger().receiveMessage(e); - } catch (Exception e) { - // do nothing. - } - } - } - - @EventHandler - public void onStart(ServerLoadEvent event) { - ServerStartEvent e = new ServerStartEvent().fire(); - if (e.isCancelled()) return; - if (! e.isSendable()) return; - ModuleUtils.sendMessage(ModuleUtils.getConsole(), e.getMessage()); - } - - public static class BaseProcessorListener implements BaseEventListener { - public BaseProcessorListener() { - MessageUtils.logInfo("Registered " + getClass().getSimpleName() + "!"); - } - - @BaseProcessor - public void onProxiedMessageReceived(ProxyMessageInEvent event) { - setMessaged(true); - } - } - - @EventHandler - public void onPing(ServerListPingEvent event) { - PingedResponse.Protocol protocol = new PingedResponse.Protocol("latest", 1); - - List playerInfos = new ArrayList<>(); - for (Player player : Bukkit.getOnlinePlayers()) { - playerInfos.add(new PingedResponse.PlayerInfo(player.getName(), player.getUniqueId().toString())); - } - - PingedResponse.Players players = new PingedResponse.Players(event.getMaxPlayers(), event.getNumPlayers(), - playerInfos.toArray(new PingedResponse.PlayerInfo[0])); - - PingedResponse response = new PingedResponse(protocol, players, event.getMotd()); - - PingReceivedEvent pingReceivedEvent = new PingReceivedEvent(response).fire(); - - if (pingReceivedEvent.isCancelled()) { - return; - } - - event.setMotd(pingReceivedEvent.getResponse().getDescription()); - event.setMaxPlayers(pingReceivedEvent.getResponse().getPlayers().getMax()); -// event.setNumPlayers(pingReceivedEvent.getResponse().getPlayers().getOnline()); - - try { - CachedServerIcon icon = Bukkit.loadServerIcon(Paths.get(pingReceivedEvent.getResponse().getFaviconString()).toFile()); - event.setServerIcon(icon); - } catch (Exception e) { - // do nothing. - } - } -} diff --git a/folia/src/main/java/net/streamline/platform/messaging/ProxyPluginMessenger.java b/folia/src/main/java/net/streamline/platform/messaging/ProxyPluginMessenger.java deleted file mode 100644 index 8a022491..00000000 --- a/folia/src/main/java/net/streamline/platform/messaging/ProxyPluginMessenger.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.streamline.platform.messaging; - -import net.streamline.api.SLAPI; -import net.streamline.api.messages.ProxiedStreamPlayer; -import net.streamline.api.messages.ProxyMessenger; -import net.streamline.api.messages.builders.*; -import net.streamline.api.messages.events.ProxyMessageInEvent; -import net.streamline.api.messages.proxied.ProxiedMessage; -import net.streamline.api.messages.proxied.ProxiedMessageManager; -import net.streamline.api.objects.SingleSet; -import net.streamline.api.objects.StreamlineResourcePack; -import net.streamline.api.savables.users.StreamPlayer; -import net.streamline.api.permissions.UserUtils; -import net.streamline.base.Streamline; - -import java.util.ArrayList; - -public class ProxyPluginMessenger implements ProxyMessenger { - @Override - public void sendMessage(ProxiedMessage message) { - if (Streamline.getInstance().getProxy().getOnlinePlayers().isEmpty()) { - ProxiedMessageManager.pendMessage(message); - return; - } - - new ArrayList<>(Streamline.getInstance().getProxy().getOnlinePlayers()).get(0) - .sendPluginMessage(Streamline.getInstance(), message.getMainChannel(), message.read()); - } - - @Override - public void receiveMessage(ProxyMessageInEvent event) { - ProxiedMessageManager.onProxiedMessageReceived(event.getMessage()); - if (event.getMessage().getMainChannel().equals(SLAPI.getApiChannel())) { - if (event.getMessage().getSubChannel().equals(ResourcePackMessageBuilder.getSubChannel())) { - SingleSet set = ResourcePackMessageBuilder.unbuild(event.getMessage()); - StreamlineResourcePack resourcePack = set.getValue(); - - Streamline.getInstance().sendResourcePack(resourcePack, set.getKey()); - } - if (event.getMessage().getSubChannel().equals(ServerInfoMessageBuilder.getSubChannel())) { - ServerInfoMessageBuilder.handle(event.getMessage()); - } - if (event.getMessage().getSubChannel().equals(SavablePlayerMessageBuilder.getSubChannel())) { - ProxiedStreamPlayer proxiedPlayer = SavablePlayerMessageBuilder.unbuild(event.getMessage()); - - UserUtils.unloadUser(proxiedPlayer.getUuid()); - StreamPlayer player = new StreamPlayer(proxiedPlayer); - UserUtils.loadUser(player); - } - if (event.getMessage().getSubChannel().equals(UserNameMessageBuilder.getSubChannel())) { - UserNameMessageBuilder.handle(event.getMessage()); - } - if (event.getMessage().getSubChannel().equals(TeleportMessageBuilder.getSubChannel())) { - TeleportMessageBuilder.handle(event.getMessage()); - } - } - } -} diff --git a/folia/src/main/java/net/streamline/platform/profile/SpigotProfiler.java b/folia/src/main/java/net/streamline/platform/profile/SpigotProfiler.java deleted file mode 100644 index d6b7adef..00000000 --- a/folia/src/main/java/net/streamline/platform/profile/SpigotProfiler.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.streamline.platform.profile; - -import net.streamline.api.profile.StreamlineProfiler; - -public class SpigotProfiler implements StreamlineProfiler { - -} diff --git a/folia/src/main/java/net/streamline/platform/savables/UserManager.java b/folia/src/main/java/net/streamline/platform/savables/UserManager.java deleted file mode 100644 index d064cc7a..00000000 --- a/folia/src/main/java/net/streamline/platform/savables/UserManager.java +++ /dev/null @@ -1,213 +0,0 @@ -package net.streamline.platform.savables; - -import lombok.Getter; -import net.luckperms.api.model.user.User; -import net.streamline.api.SLAPI; -import net.streamline.api.configs.given.GivenConfigs; -import net.streamline.api.configs.given.MainMessagesHandler; -import net.streamline.api.interfaces.IUserManager; -import net.streamline.api.messages.builders.ServerConnectMessageBuilder; -import net.streamline.api.objects.StreamlineResourcePack; -import net.streamline.api.objects.StreamlineServerInfo; -import net.streamline.api.savables.users.StreamlineConsole; -import net.streamline.api.savables.users.StreamPlayer; -import net.streamline.api.permissions.UserUtils; -import net.streamline.base.Streamline; -import net.streamline.platform.BasePlugin; -import net.streamline.platform.Messenger; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.net.InetSocketAddress; -import java.util.concurrent.ConcurrentSkipListMap; -import java.util.concurrent.ConcurrentSkipListSet; - -public class UserManager implements IUserManager { - @Getter - private static UserManager instance; - - public UserManager() { - instance = this; - } - - public StreamPlayer getOrGetPlayer(Player player) { - StreamPlayer p = UserUtils.getOrGetPlayer(player.getUniqueId().toString()); - if (p == null) { - p = new StreamPlayer(player.getUniqueId().toString()); - UserUtils.loadUser(p); - } - - return p; - } - - public StreamPlayer getOrGetUser(CommandSender sender) { - if (isConsole(sender)) { - return UserUtils.getOrGetUser(GivenConfigs.getMainConfig().userConsoleDiscriminator()); - } else { - return UserUtils.getOrGetUser(Streamline.getPlayer(sender).getUniqueId().toString()); - } - } - - public String getUsername(CommandSender sender) { - if (isConsole(sender)) return GivenConfigs.getMainConfig().userConsoleNameRegular(); - else return sender.getName(); - } - - public String getUsername(String uuid) { - if (uuid.equals(GivenConfigs.getMainConfig().userConsoleDiscriminator())) return GivenConfigs.getMainConfig().userConsoleNameRegular(); - else { - Player player = Streamline.getPlayer(uuid); - if (player == null) return null; - return getUsername(player); - } - } - - public boolean isConsole(CommandSender sender) { - return sender.equals(Streamline.getInstance().getProxy().getConsoleSender()); - } - - public boolean isOnline(String uuid) { - if (UserUtils.isConsole(uuid)) return true; - for (Player player : BasePlugin.onlinePlayers()) { - if (player.getUniqueId().toString().equals(uuid)) return true; - } - - return false; - } - - public String parsePlayerIP(Player player) { - if (player == null) return MainMessagesHandler.MESSAGES.DEFAULTS.IS_NULL.get(); - - InetSocketAddress address = player.getAddress(); - if (address == null) return MainMessagesHandler.MESSAGES.DEFAULTS.PLACEHOLDERS.IS_NULL.get(); - String ipSt = address.toString().replace("/", ""); - String[] ipSplit = ipSt.split(":"); - ipSt = ipSplit[0]; - - return ipSt; - } - - public boolean runAs(StreamPlayer user, boolean bypass, String command) { - CommandSender source; - if (user instanceof StreamPlayer) { - StreamPlayer player = (StreamPlayer) user; - source = Streamline.getPlayer(player.getUuid()); - } - else { - source = Streamline.getInstance().getProxy().getConsoleSender(); - Streamline.getInstance().getProxy().dispatchCommand(source, command); - return true; - } - StreamPlayer player = (StreamPlayer) user; - if (source == null) return false; - boolean already = source.hasPermission("*"); - if (bypass && !already) { - User u = SLAPI.getLuckPerms().getUserManager().getUser(player.getUuid()); - if (u == null) return false; - UserUtils.addPermission(u, "*"); - } - Streamline.getInstance().getProxy().dispatchCommand(source, command); - if (bypass && !already) { - User u = SLAPI.getLuckPerms().getUserManager().getUser(player.getUuid()); - if (u == null) return false; - UserUtils.removePermission(u, "*"); - } - return true; - } - - public ConcurrentSkipListSet getUsersOn(String server) { - ConcurrentSkipListSet r = new ConcurrentSkipListSet<>(); - - UserUtils.getLoadedUsersSet().forEach(a -> { - if (! a.isOnline()) return; - if (a.getLatestServer().equals(server)) r.add(a); - }); - - return r; - } - - public void connect(StreamPlayer user, String server) { - if (! user.isOnline()) return; - if (user instanceof StreamlineConsole) return; - - Player player = Streamline.getPlayer(user.getUuid()); - if (player == null) return; - StreamPlayer pl = getOrGetPlayer(player); - StreamlineServerInfo s = GivenConfigs.getProfileConfig().getServerInfo(server); - SLAPI.getInstance().getProxyMessenger().sendMessage(ServerConnectMessageBuilder.build(pl, s, pl.getUuid())); - } - - public void sendUserResourcePack(StreamPlayer user, StreamlineResourcePack pack) { - if (! (user instanceof StreamPlayer)) return; - StreamPlayer player = (StreamPlayer) user; - if (! player.updateOnline()) return; - Player p = Streamline.getPlayer(user.getUuid()); - if (p == null) return; - - Streamline.getInstance().sendResourcePack(pack, user); - } - - @Override - public String parsePlayerIP(String uuid) { - Player player = Streamline.getPlayer(uuid); - if (player == null) return MainMessagesHandler.MESSAGES.DEFAULTS.IS_NULL.get(); - - InetSocketAddress address = player.getAddress(); - if (address == null) return MainMessagesHandler.MESSAGES.DEFAULTS.PLACEHOLDERS.IS_NULL.get(); - String ipSt = address.toString().replace("/", ""); - String[] ipSplit = ipSt.split(":"); - ipSt = ipSplit[0]; - - return ipSt; - } - - @Override - public double getPlayerPing(String uuid) { - Player player = Streamline.getPlayer(uuid); - if (player == null) return 0d; - return player.getPing(); - } - - @Override - public void kick(StreamPlayer user, String message) { - Player player = Streamline.getInstance().getProxy().getPlayer(user.getUuid()); - if (player == null) return; - player.kickPlayer(Messenger.getInstance().codedString(message)); - } - - @Override - public Player getPlayer(String uuid) { - return Streamline.getPlayer(uuid); - } - - @Override - public ConcurrentSkipListMap ensurePlayers() { - ConcurrentSkipListMap r = new ConcurrentSkipListMap<>(); - - for (Player player : BasePlugin.onlinePlayers()) { - if (UserUtils.isLoaded(player.getUniqueId().toString())) { - StreamPlayer p = getOrGetPlayer(player); - r.put(player.getUniqueId().toString(), p); - continue; - } - - StreamPlayer p = new StreamPlayer(player.getUniqueId().toString()); - r.put(player.getUniqueId().toString(), p); - } - - return r; - } - - @Override - public String getServerPlayerIsOn(String uuid) { - return "null"; - } - - @Override - public String getDisplayName(String uuid) { - Player player = getPlayer(uuid); - if (player == null) return null; - - return player.getDisplayName(); - } -} diff --git a/folia/src/main/resources/plugin.yml b/folia/src/main/resources/plugin.yml deleted file mode 100644 index 2a65f842..00000000 --- a/folia/src/main/resources/plugin.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: '${name}' -version: '${version}' -main: 'net.streamline.base.Streamline' -authors: - - MrDrakify -website: https://github.com/Streamline-Essentials -description: True potential is here. A Proxy and Spigot plugin that opens up endless cross-platform possibilities. -depend: - - LuckPerms -soft-depend: - - Geyser-Spigot - - Geyser-Folia - - PlaceholderAPI -folia-supported: true - -commands: - streamlinespigot: - description: Main command for Streamline - permission: streamline.command.base.default - aliases: - - sls - - streamline - - sl \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 61e520ae..95f50d50 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,6 +9,6 @@ org.gradle.vfs.watch = false # Other properties name = StreamlineCore group = com.github.Streamline-Essentials.StreamlineCore -version = 2.5.4.0 +version = 2.5.4.3 plugin.main = default \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index d64cd491..00000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index dedd5d1e..00000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-all.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1aa94a42..faf93008 100644 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -84,7 +86,7 @@ done # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -203,7 +205,7 @@ fi DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. diff --git a/gradlew.bat b/gradlew.bat index 93e3f59f..9d21a218 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @@ -43,11 +45,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -57,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail diff --git a/singularity-api/src/main/java/singularity/Singularity.java b/singularity-api/src/main/java/singularity/Singularity.java index 2f1a87b7..f08f8b32 100644 --- a/singularity-api/src/main/java/singularity/Singularity.java +++ b/singularity-api/src/main/java/singularity/Singularity.java @@ -1,9 +1,13 @@ package singularity; +import ch.qos.logback.classic.LoggerContext; +import gg.drak.thebase.async.AsyncUtils; import gg.drak.thebase.objects.SingleSet; import gg.drak.thebase.objects.handling.derived.PluginEventable; import lombok.Getter; import lombok.Setter; +import org.slf4j.LoggerFactory; +import org.slf4j.event.Level; import singularity.configs.given.GivenConfigs; import singularity.data.console.CosmicSender; import singularity.data.runners.PlayerSaver; @@ -11,11 +15,16 @@ import singularity.data.uuid.UuidInfo; import singularity.data.uuid.UuidManager; import singularity.database.CoreDBOperator; +import singularity.database.servers.SavedServer; +import singularity.events.server.ServerLogTextEvent; import singularity.interfaces.*; import singularity.interfaces.audiences.IPlayerInterface; import singularity.interfaces.audiences.IConsoleHolder; import singularity.interfaces.audiences.real.RealSender; import singularity.interfaces.audiences.real.RealPlayer; +import singularity.logging.CosmicLogHandler; +import singularity.logging.CosmicLogbackAppender; +import singularity.logging.LogCollector; import singularity.messages.ProxyMessenger; import singularity.messages.proxied.ProxiedMessageManager; import singularity.modules.CosmicModule; @@ -25,9 +34,7 @@ import singularity.utils.MessageUtils; import singularity.utils.UserUtils; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; @@ -36,6 +43,7 @@ import java.util.concurrent.ConcurrentSkipListSet; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.logging.Logger; public class Singularity, M extends IMessenger> extends PluginEventable { public static class CommandRunner extends BaseRunnable { @@ -121,8 +129,6 @@ public static void removeCachedCommand(int id) { cachedCommands.remove(id); } - @Getter - private static File userFolder; @Getter private static File moduleFolder; @Getter @@ -183,22 +189,25 @@ public Singularity(String identifier, S platform, U userManager, M messenger, IC super(identifier); instance = this; + // Field Stuff this.platform = platform; this.userManager = userManager; this.messenger = messenger; this.consoleHolder = consoleHolder; this.playerInterface = playerInterface; + // Console Stuff + setupLogger(); + + // Set up the api channel. setApiChannel(apiChannel); // setProxiedServer(platform.getServerType().equals(IStreamline.ServerType.BACKEND)); setProxy(platform.getServerType().equals(ISingularityExtension.ServerType.PROXY)); - userFolder = new File(getDataFolder(), "users" + File.separator); moduleFolder = new File(getDataFolder(), "modules" + File.separator); moduleSaveFolder = new File(getDataFolder(), "module-resources" + File.separator); mainCommandsFolder = new File(getDataFolder(), getCommandsFolderChild()); - userFolder.mkdirs(); moduleFolder.mkdirs(); moduleSaveFolder.mkdirs(); mainCommandsFolder.mkdirs(); @@ -253,6 +262,8 @@ public Singularity(String identifier, S platform, U userManager, M messenger, IC playerSaver = new PlayerSaver(); + LogCollector.init(); + setReady(true); } @@ -260,12 +271,46 @@ public Singularity(String identifier, S platform, U userManager, M messenger, IC this(identifier, platform, userManager, messenger, consoleHolder, playerInterface, null, apiChannel); } + public void setupLogger() { + if (getPlatform().hasLoggerLogger()) { + java.util.logging.Logger rootLogger = getPlatform().getLoggerLogger(); + while (rootLogger.getParent() != null) { + rootLogger = rootLogger.getParent(); + } + // Remove existing handlers to avoid duplicates (optional) +// for (java.util.logging.Handler handler : rootLogger.getHandlers()) { +// rootLogger.removeHandler(handler); +// } + // Add the custom handler + CosmicLogHandler handler = new CosmicLogHandler(); + rootLogger.addHandler(handler); + } + if (getPlatform().hasSLFLogger()) { + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + ch.qos.logback.classic.Logger rootLogger = loggerContext.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + + // Remove existing appenders + rootLogger.detachAndStopAllAppenders(); + + // Add custom appender + CosmicLogbackAppender appender = new CosmicLogbackAppender(); + appender.setContext(loggerContext); + appender.setName("CosmicLogbackAppender"); + appender.start(); + rootLogger.addAppender(appender); + } + } + public static String getServerUuid() { - return GivenConfigs.getMainConfig().getOrCreateUuid(); + return GivenConfigs.getServerConfig().getServerUuid(); } public static String getServerName() { - return GivenConfigs.getMainConfig().getServerName(); + return GivenConfigs.getServerConfig().getServerName(); + } + + public static SavedServer getServer() { + return GivenConfigs.getServerConfig().getServer(); } public ConcurrentSkipListMap getFiles(File folder, Predicate filePredicate) { diff --git a/singularity-api/src/main/java/singularity/configs/given/GivenConfigs.java b/singularity-api/src/main/java/singularity/configs/given/GivenConfigs.java index 96d7dfab..ad714122 100644 --- a/singularity-api/src/main/java/singularity/configs/given/GivenConfigs.java +++ b/singularity-api/src/main/java/singularity/configs/given/GivenConfigs.java @@ -78,7 +78,7 @@ public static SavedServer getServer() { } public static String getServerName() { - return getServerConfig().getName(); + return getServerConfig().getServerName(); } public static void setServer(SavedServer server) { diff --git a/singularity-api/src/main/java/singularity/configs/given/MainConfigHandler.java b/singularity-api/src/main/java/singularity/configs/given/MainConfigHandler.java index e24e0e40..af8c4152 100644 --- a/singularity-api/src/main/java/singularity/configs/given/MainConfigHandler.java +++ b/singularity-api/src/main/java/singularity/configs/given/MainConfigHandler.java @@ -42,9 +42,6 @@ public void init() { debugConsoleDebugPrefix(); // getHexPolicies(); - - getOrCreateUuid(); - getServerName(); } // CONSOLE @@ -220,16 +217,4 @@ public String debugConsoleDebugPrefix() { return getResource().getOrSetDefault("debug.console.debug.prefix", "&f[&3StreamlineCore&f] &f[&cDEBUG&f] &r"); } - - public String getOrCreateUuid() { - reloadResource(); - - return getResource().getOrSetDefault("server.uuid", UUID.randomUUID().toString()); - } - - public String getServerName() { - reloadResource(); - - return getResource().getOrSetDefault("server.name", getOrCreateUuid()); - } } diff --git a/singularity-api/src/main/java/singularity/configs/given/ServerConfigHandler.java b/singularity-api/src/main/java/singularity/configs/given/ServerConfigHandler.java index d691a51e..ffbb1454 100644 --- a/singularity-api/src/main/java/singularity/configs/given/ServerConfigHandler.java +++ b/singularity-api/src/main/java/singularity/configs/given/ServerConfigHandler.java @@ -17,41 +17,48 @@ public ServerConfigHandler() { @Override public void init() { + getServerUuid(); + getServerName(); } public static String getRandomUUID() { return UUID.randomUUID().toString(); } - public String getName() { + public String getServerName() { reloadResource(); - return getOrSetDefault("server.name", "Proxy"); + return getOrSetDefault("server.name", getServerUuid()); } - private String getUUIDFromConfig() { + public String getServerUuidFromConfig() { reloadResource(); return getOrSetDefault("server.uuid", getRandomUUID()); } - public String getUUID() { - String uuid = getUUIDFromConfig(); + public String getServerUuid() { + String uuid = getServerUuidFromConfig(); uuid = ensureProperUUID(uuid); return uuid; } public String ensureProperUUID(String uuid) { + return ensureProperUUID(uuid, true); + } + + public String ensureProperUUID(String uuid, boolean set) { if (uuid.equals("00000000-0000-0000-0000-000000000000") || uuid.isBlank() || ! UuidUtils.isUuid(uuid)) { uuid = getRandomUUID(); - write("server.uuid", uuid); } + if (set) setServerUuid(uuid); + return uuid; } public SavedServer getServer() { - return new SavedServer(getUUID(), getName(), Singularity.getInstance().getPlatform().getServerType()); + return new SavedServer(getServerUuid(), getServerName(), Singularity.getInstance().getPlatform().getServerType()); } public void setServer(SavedServer server) { @@ -62,4 +69,15 @@ public void setServer(SavedServer server) { public void setServerName(String name) { write("server.name", name); } + + public void setServerUuid(String uuid) { + setServerUuid(uuid, false); + } + + public void setServerUuid(String uuid, boolean isEnsureProper) { + if (! isEnsureProper) { + uuid = ensureProperUUID(uuid, false); + } + write("server.uuid", uuid); + } } diff --git a/singularity-api/src/main/java/singularity/data/console/CosmicSender.java b/singularity-api/src/main/java/singularity/data/console/CosmicSender.java index be709e7a..ffa17251 100644 --- a/singularity-api/src/main/java/singularity/data/console/CosmicSender.java +++ b/singularity-api/src/main/java/singularity/data/console/CosmicSender.java @@ -23,7 +23,7 @@ import java.util.concurrent.CompletableFuture; @Getter -public class CosmicSender implements Loadable { +public class CosmicSender implements Loadable { public String getIdentifier() { return getUuid(); } @@ -91,6 +91,9 @@ public CosmicSender() { this( GivenConfigs.getMainConfig().getConsoleDiscriminator() ); + + this.setCurrentName(GivenConfigs.getMainConfig().getConsoleName()); + this.augment(Singularity.getMainDatabase().loadPlayer(getIdentifier()), false); } public CosmicSender setCurrentName(String currentName) { @@ -143,7 +146,7 @@ public void ensureLoaded() { } @Override - public CosmicPlayer augment(CompletableFuture> future, boolean isGet) { + public CosmicSender augment(CompletableFuture> future, boolean isGet) { fullyLoaded = false; future.whenComplete((optional, error) -> { @@ -154,7 +157,7 @@ public CosmicPlayer augment(CompletableFuture> future, bo } if (optional.isPresent()) { - CosmicPlayer sender = optional.get(); + CosmicSender sender = optional.get(); setUuid(sender.getUuid()); setFirstJoinMillis(sender.getFirstJoinMillis()); @@ -166,7 +169,7 @@ public CosmicPlayer augment(CompletableFuture> future, bo setMeta(sender.getMeta()); setPermissions(sender.getPermissions()); - augmentMore(sender); + if (this instanceof CosmicPlayer && sender instanceof CosmicPlayer) augmentMore((CosmicPlayer) sender); setCurrentNameAsProper(); // might need to be forced... need to check this... } else { @@ -188,7 +191,7 @@ public CosmicPlayer augment(CompletableFuture> future, bo fullyLoaded = true; }); - return (CosmicPlayer) this; + return this; } public void augmentMore(CosmicPlayer sender) { diff --git a/singularity-api/src/main/java/singularity/data/players/CosmicPlayer.java b/singularity-api/src/main/java/singularity/data/players/CosmicPlayer.java index ab985be5..4aa02aeb 100644 --- a/singularity-api/src/main/java/singularity/data/players/CosmicPlayer.java +++ b/singularity-api/src/main/java/singularity/data/players/CosmicPlayer.java @@ -21,8 +21,8 @@ public class CosmicPlayer extends CosmicSender { @Setter private CosmicLocation location; - public CosmicPlayer(String uuid) { - super(uuid); + public CosmicPlayer(String uuid, boolean temporary) { + super(uuid, temporary); setServerName(""); @@ -31,6 +31,10 @@ public CosmicPlayer(String uuid) { this.location = new CosmicLocation(this); } + public CosmicPlayer(String uuid) { + this(uuid, false); + } + public CosmicLocation getLocation() { if (location == null) { location = new CosmicLocation(this); @@ -159,9 +163,11 @@ public void setPitch(float pitch) { @Override public void reload() { CompletableFuture.runAsync(() -> { - Optional optional = Singularity.getMainDatabase().loadPlayer(getUuid()).join(); + Optional optional = Singularity.getMainDatabase().loadPlayer(getUuid()).join(); if (optional.isEmpty()) return; - CosmicPlayer streamPlayer = optional.get(); + CosmicSender sender = optional.get(); + if (! (sender instanceof CosmicPlayer)) return; + CosmicPlayer streamPlayer = (CosmicPlayer) sender; setFirstJoinMillis(streamPlayer.getFirstJoinDate().getTime()); setLastJoinMillis(streamPlayer.getLastJoinDate().getTime()); diff --git a/singularity-api/src/main/java/singularity/data/update/defaults/CosmicPlayerUpdater.java b/singularity-api/src/main/java/singularity/data/update/defaults/CosmicPlayerUpdater.java index 3b393460..7ef9052c 100644 --- a/singularity-api/src/main/java/singularity/data/update/defaults/CosmicPlayerUpdater.java +++ b/singularity-api/src/main/java/singularity/data/update/defaults/CosmicPlayerUpdater.java @@ -2,6 +2,7 @@ import singularity.Singularity; import singularity.configs.given.GivenConfigs; +import singularity.data.console.CosmicSender; import singularity.data.players.CosmicPlayer; import singularity.data.update.UpdateType; @@ -10,8 +11,8 @@ public class CosmicPlayerUpdater extends UpdateType { public CosmicPlayerUpdater() { super("cosmic_players", CosmicPlayer.class, (identifier) -> { - Optional optional = Singularity.getMainDatabase().loadPlayer(identifier).join(); - return optional.orElse(null); + Optional optional = Singularity.getMainDatabase().loadPlayer(identifier).join(); + return (CosmicPlayer) optional.filter(s -> s instanceof CosmicPlayer).orElse(null); }, (player) -> { Singularity.getMainDatabase().savePlayer(player); }, GivenConfigs.getMainConfig().getPlayerDataSaveInterval() * 20L); diff --git a/singularity-api/src/main/java/singularity/database/CoreDBOperator.java b/singularity-api/src/main/java/singularity/database/CoreDBOperator.java index f7da6c71..d7950878 100644 --- a/singularity-api/src/main/java/singularity/database/CoreDBOperator.java +++ b/singularity-api/src/main/java/singularity/database/CoreDBOperator.java @@ -34,7 +34,7 @@ public class CoreDBOperator extends DBOperator { @Getter @Setter - private static AsyncCache> loadingPlayers = Caffeine.newBuilder() + private static AsyncCache> loadingPlayers = Caffeine.newBuilder() .expireAfterWrite(Duration.ofSeconds(10)) .buildAsync(); ; @@ -362,10 +362,10 @@ private CompletableFuture saveSenderAsync(CosmicSender sender) { }); } - public CompletableFuture> loadPlayer(String uuid) { - CompletableFuture> future = getLoadingPlayers().getIfPresent(uuid); + public CompletableFuture> loadPlayer(String uuid) { + CompletableFuture> future = getLoadingPlayers().getIfPresent(uuid); if (future == null || future.isDone()) { - CompletableFuture> loading = CompletableFuture.supplyAsync(() -> { + CompletableFuture> loading = CompletableFuture.supplyAsync(() -> { ensureUsable(); if (! exists(uuid).join()) { diff --git a/singularity-api/src/main/java/singularity/events/server/CosmicLogPopEvent.java b/singularity-api/src/main/java/singularity/events/server/CosmicLogPopEvent.java new file mode 100644 index 00000000..c43569bb --- /dev/null +++ b/singularity-api/src/main/java/singularity/events/server/CosmicLogPopEvent.java @@ -0,0 +1,21 @@ +package singularity.events.server; + +import lombok.Getter; +import lombok.Setter; +import singularity.events.CosmicEvent; + +import java.util.concurrent.ConcurrentSkipListMap; +import java.util.function.BiConsumer; + +@Getter @Setter +public class CosmicLogPopEvent extends CosmicEvent { + private final ConcurrentSkipListMap poppedLogs; + + public CosmicLogPopEvent(ConcurrentSkipListMap poppedLogs) { + this.poppedLogs = poppedLogs; + } + + public void forEachLog(BiConsumer consumer) { + poppedLogs.forEach(consumer); + } +} diff --git a/singularity-api/src/main/java/singularity/events/server/ServerLogTextEvent.java b/singularity-api/src/main/java/singularity/events/server/ServerLogTextEvent.java index c133a966..e8c969e7 100644 --- a/singularity-api/src/main/java/singularity/events/server/ServerLogTextEvent.java +++ b/singularity-api/src/main/java/singularity/events/server/ServerLogTextEvent.java @@ -2,18 +2,15 @@ import lombok.Getter; import singularity.events.CosmicEvent; - -import java.util.logging.LogRecord; +import singularity.logging.LogIntent; @Getter public class ServerLogTextEvent extends CosmicEvent { - final LogRecord record; - - public ServerLogTextEvent(LogRecord record) { - this.record = record; - } + private final String message; + private final LogIntent intent; - public String getMessage() { - return getRecord().getMessage(); + public ServerLogTextEvent(String message, LogIntent intent) { + this.message = message; + this.intent = intent; } } diff --git a/singularity-api/src/main/java/singularity/interfaces/ISingularityExtension.java b/singularity-api/src/main/java/singularity/interfaces/ISingularityExtension.java index 5171454f..193a16d3 100644 --- a/singularity-api/src/main/java/singularity/interfaces/ISingularityExtension.java +++ b/singularity-api/src/main/java/singularity/interfaces/ISingularityExtension.java @@ -7,6 +7,7 @@ import org.jetbrains.annotations.NotNull; import java.util.concurrent.ConcurrentSkipListSet; +import java.util.logging.Logger; public interface ISingularityExtension { enum PlatformType { @@ -66,4 +67,16 @@ enum ServerType { String getName(); boolean isOfflineMode(); + + Logger getLoggerLogger(); + + default boolean hasLoggerLogger() { + return getLoggerLogger() != null; + } + + org.slf4j.Logger getSLFLogger(); + + default boolean hasSLFLogger() { + return getSLFLogger() != null; + } } diff --git a/singularity-api/src/main/java/singularity/listeners/CosmicListener.java b/singularity-api/src/main/java/singularity/listeners/CosmicListener.java new file mode 100644 index 00000000..7561b6e8 --- /dev/null +++ b/singularity-api/src/main/java/singularity/listeners/CosmicListener.java @@ -0,0 +1,11 @@ +package singularity.listeners; + +import gg.drak.thebase.events.BaseEventHandler; +import gg.drak.thebase.events.BaseEventListener; +import singularity.Singularity; + +public class CosmicListener implements BaseEventListener { + public CosmicListener() { + BaseEventHandler.bake(this, Singularity.getBaseModule()); + } +} diff --git a/singularity-api/src/main/java/singularity/loading/Loadable.java b/singularity-api/src/main/java/singularity/loading/Loadable.java index 20b437b3..ed3e5a1f 100644 --- a/singularity-api/src/main/java/singularity/loading/Loadable.java +++ b/singularity-api/src/main/java/singularity/loading/Loadable.java @@ -1,6 +1,9 @@ package singularity.loading; import gg.drak.thebase.objects.Identifiable; +import singularity.data.console.CosmicSender; +import singularity.data.players.CosmicPlayer; +import singularity.utils.UserUtils; import java.util.Optional; import java.util.concurrent.CompletableFuture; @@ -29,7 +32,10 @@ default L augment(CompletableFuture> loader) { boolean isLoaded(); - void saveAndUnload(boolean async); + default void saveAndUnload(boolean async) { + save(async); + unload(); + } default void saveAndUnload() { saveAndUnload(true); @@ -60,4 +66,20 @@ default void onceFullyLoaded(Consumer> consumer) { default > void onceFullyLoadedTyped(Consumer consumer) { consumer.accept(waitUntilFullyLoadedTyped()); } + + default Optional asSender() { + return UserUtils.getOrGetSender(getIdentifier()); + } + + default Optional asSenderOrCreate() { + return UserUtils.getOrCreateSender(getIdentifier()); + } + + default Optional asPlayer() { + return UserUtils.getOrGetPlayer(getIdentifier()); + } + + default Optional asPlayerOrCreate() { + return UserUtils.getOrCreatePlayer(getIdentifier()); + } } diff --git a/singularity-api/src/main/java/singularity/loading/Loader.java b/singularity-api/src/main/java/singularity/loading/Loader.java index 7495d532..46d56ff3 100644 --- a/singularity-api/src/main/java/singularity/loading/Loader.java +++ b/singularity-api/src/main/java/singularity/loading/Loader.java @@ -126,4 +126,8 @@ public void unload(String identifier) { public void unload(L loadable) { unload(loadable.getIdentifier()); } + + public boolean isLoaded(L loadable) { + return isLoaded(loadable.getIdentifier()); + } } diff --git a/singularity-api/src/main/java/singularity/logging/CosmicLogHandler.java b/singularity-api/src/main/java/singularity/logging/CosmicLogHandler.java index 192e7ccf..543c9db6 100644 --- a/singularity-api/src/main/java/singularity/logging/CosmicLogHandler.java +++ b/singularity-api/src/main/java/singularity/logging/CosmicLogHandler.java @@ -2,16 +2,60 @@ import singularity.events.server.ServerLogTextEvent; +import java.io.ByteArrayOutputStream; import java.util.logging.LogRecord; import java.util.logging.StreamHandler; +import java.util.logging.Level; public class CosmicLogHandler extends StreamHandler { + private final ByteArrayOutputStream baos; + + public CosmicLogHandler() { + // Set output to System.out by default + super.setOutputStream(System.out); + + this.baos = new ByteArrayOutputStream(); + } + @Override public synchronized void publish(LogRecord record) { - ServerLogTextEvent event = new ServerLogTextEvent(record).fire(); + Level level = record.getLevel(); + LogIntent intent = null; + switch (level.getName()) { + case "FINE": + intent = LogIntent.DEBUG; + break; + case "INFO": + intent = LogIntent.INFO; + break; + case "WARNING": + intent = LogIntent.WARNING; + break; + case "SEVERE": + intent = LogIntent.SEVERE; + break; + default: + intent = LogIntent.OTHER; + break; + } + + // Create and fire the event + ServerLogTextEvent event = new ServerLogTextEvent(record.getMessage(), intent).fire(); if (event.isCancelled()) { return; } - super.publish(event.getRecord()); + + // Capture the log message + String formattedMessage = getFormatter().format(record); + baos.write(formattedMessage.getBytes(), 0, formattedMessage.length()); + + // Pass to parent handler for actual logging + super.publish(record); + super.flush(); // Ensure immediate output + } + + // Method to get captured logs + public String getCapturedLogs() { + return baos.toString(); } } diff --git a/singularity-api/src/main/java/singularity/logging/CosmicLogbackAppender.java b/singularity-api/src/main/java/singularity/logging/CosmicLogbackAppender.java new file mode 100644 index 00000000..32c22c34 --- /dev/null +++ b/singularity-api/src/main/java/singularity/logging/CosmicLogbackAppender.java @@ -0,0 +1,52 @@ +package singularity.logging; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import singularity.events.server.ServerLogTextEvent; + +import java.io.ByteArrayOutputStream; + +public class CosmicLogbackAppender extends AppenderBase { + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + @Override + protected void append(ILoggingEvent eventObject) { + Level level = eventObject.getLevel(); + LogIntent intent = null; + switch (level.levelStr) { + case "DEBUG": + intent = LogIntent.DEBUG; + break; + case "INFO": + intent = LogIntent.INFO; + break; + case "WARN": + intent = LogIntent.WARNING; + break; + case "ERROR": + intent = LogIntent.SEVERE; + break; + default: + intent = LogIntent.OTHER; + break; + } + + // Create and fire the event + ServerLogTextEvent event = new ServerLogTextEvent(eventObject.getFormattedMessage(), intent).fire(); + if (event.isCancelled()) { + return; + } + + // Capture the log message + String message = eventObject.getFormattedMessage() + System.lineSeparator(); + baos.write(message.getBytes(), 0, message.length()); + + // Optionally forward to console + System.out.print(message); + } + + public String getCapturedLogs() { + return baos.toString(); + } +} \ No newline at end of file diff --git a/singularity-api/src/main/java/singularity/logging/LogCollector.java b/singularity-api/src/main/java/singularity/logging/LogCollector.java new file mode 100644 index 00000000..74bf17da --- /dev/null +++ b/singularity-api/src/main/java/singularity/logging/LogCollector.java @@ -0,0 +1,69 @@ +package singularity.logging; + +import gg.drak.thebase.events.processing.BaseProcessor; +import lombok.Getter; +import lombok.Setter; +import singularity.events.server.CosmicLogPopEvent; +import singularity.events.server.ServerLogTextEvent; +import singularity.listeners.CosmicListener; +import singularity.logging.timers.LogPopTimer; +import singularity.utils.MessageUtils; + +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentSkipListMap; + +public class LogCollector extends CosmicListener { + @Getter @Setter + private static ConcurrentLinkedQueue logQueue = new ConcurrentLinkedQueue<>(); + + public static void addLog(ServerLogTextEvent event) { + logQueue.add(event); + } + + /** + * Pops all logs from the queue and returns them as a map. + * @return A map of log entries where the key is the log ID and the value is the log message. + */ + public static ConcurrentSkipListMap getLogs() { + ConcurrentSkipListMap logs = new ConcurrentSkipListMap<>(); + int id = 0; + + while (! logQueue.isEmpty()) { + ServerLogTextEvent event = logQueue.poll(); + if (event != null) { + logs.put(id++, event); + } + } + + return logs; + } + + public static void clearLogs() { + logQueue.clear(); + } + + public static void init() { + setInstance(new LogCollector()); + + setLogPopTimer(new LogPopTimer()); + + MessageUtils.logInfo("LogCollector initialized. Listening for log events."); + } + + public static void popAndEvent() { + ConcurrentSkipListMap logs = getLogs(); + if (! logs.isEmpty()) { + CosmicLogPopEvent event = new CosmicLogPopEvent(logs).fire(); + } + } + + @Getter @Setter + private static LogCollector instance; + @Getter @Setter + private static LogPopTimer logPopTimer; + + @BaseProcessor + public void onServerLogTextEvent(ServerLogTextEvent event) { + addLog(event); + } +} diff --git a/singularity-api/src/main/java/singularity/logging/LogIntent.java b/singularity-api/src/main/java/singularity/logging/LogIntent.java new file mode 100644 index 00000000..39b16cd1 --- /dev/null +++ b/singularity-api/src/main/java/singularity/logging/LogIntent.java @@ -0,0 +1,11 @@ +package singularity.logging; + +public enum LogIntent { + INFO, + WARNING, + SEVERE, + DEBUG, + + OTHER, + ; +} \ No newline at end of file diff --git a/singularity-api/src/main/java/singularity/logging/timers/LogPopTimer.java b/singularity-api/src/main/java/singularity/logging/timers/LogPopTimer.java new file mode 100644 index 00000000..bc03f427 --- /dev/null +++ b/singularity-api/src/main/java/singularity/logging/timers/LogPopTimer.java @@ -0,0 +1,14 @@ +package singularity.logging.timers; + +import gg.drak.thebase.async.AsyncTask; +import singularity.logging.LogCollector; + +public class LogPopTimer extends AsyncTask { + public LogPopTimer() { + super(LogPopTimer::runTask, 0, 20 * 5); // Runs every 5 seconds + } + + public static void runTask(AsyncTask task) { + LogCollector.popAndEvent(); + } +} diff --git a/singularity-api/src/main/java/singularity/objects/PingedResponse.java b/singularity-api/src/main/java/singularity/objects/PingedResponse.java index fd4c73c4..a1e5ccaf 100644 --- a/singularity-api/src/main/java/singularity/objects/PingedResponse.java +++ b/singularity-api/src/main/java/singularity/objects/PingedResponse.java @@ -102,7 +102,7 @@ public PingedResponse(Protocol version, Players players, String description) thr } public PingedResponse(Protocol version, Players players, String description, String favicon) throws IOException { - this( version, players, description, favicon == null ? null : CosmicFavicon.createFromURL(favicon)); + this(version, players, description, favicon == null ? null : CosmicFavicon.createFromURL(favicon)); } public PingedResponse(Protocol version, Players players, String description, CosmicFavicon favicon) diff --git a/singularity-api/src/main/java/singularity/utils/UserUtils.java b/singularity-api/src/main/java/singularity/utils/UserUtils.java index f08d5424..f9f42db1 100644 --- a/singularity-api/src/main/java/singularity/utils/UserUtils.java +++ b/singularity-api/src/main/java/singularity/utils/UserUtils.java @@ -165,6 +165,15 @@ public static Optional getSender(String uuid) { return Optional.of(sender); } + public static Optional getPlayer(String uuid) { + Optional optional = getSender(uuid); + if (optional.isPresent()) { + if (optional.get() instanceof CosmicPlayer) return optional.map(s -> (CosmicPlayer) s); + } + + return Optional.empty(); + } + public static CosmicPlayer loadPlayer(CosmicPlayer player) { return (CosmicPlayer) loadSender(player); } @@ -174,21 +183,15 @@ public static Optional getOrCreatePlayer(CosmicSender sender) { } public static CosmicSender createSender() { - CosmicSender console = new CosmicSender(); - ModuleUtils.fireEvent(new CreateSenderEvent(console)); - return console; + return new CosmicSender(); } public static CosmicSender createSender(String uuid) { - CosmicSender sender = new CosmicSender(uuid); - ModuleUtils.fireEvent(new CreateSenderEvent(sender)); - return sender; + return new CosmicSender(uuid); } public static CosmicPlayer createPlayer(String uuid) { - CosmicPlayer player = new CosmicPlayer(uuid); - ModuleUtils.fireEvent(new CreateSenderEvent(player)); - return player; + return new CosmicPlayer(uuid); } public static Optional getOrCreateSender(String uuid) { @@ -198,12 +201,12 @@ public static Optional getOrCreateSender(String uuid) { if (isConsole(uuid)) return Optional.ofNullable(getConsole()); if (! UuidUtils.isValidPlayerUUID(uuid)) return Optional.empty(); - CosmicSender sender = createSender(uuid); - sender.load(); + CosmicPlayer player = createPlayer(uuid); + player.load(); - sender.augment(Singularity.getMainDatabase().loadPlayer(uuid), false); + player.augment(Singularity.getMainDatabase().loadPlayer(uuid), false); - return Optional.of(sender); + return Optional.of(player); } public static Optional getOrCreatePlayer(String uuid) { @@ -229,6 +232,10 @@ public static CosmicSender createTemporarySender(String uuid) { return new CosmicSender(uuid, true); } + public static CosmicPlayer createTemporaryPlayer(String uuid) { + return new CosmicPlayer(uuid, true); + } + public static Optional getOrGetSender(String uuid) { if (uuid == null || uuid.isEmpty()) return Optional.empty(); @@ -239,21 +246,18 @@ public static Optional getOrGetSender(String uuid) { if (! UuidUtils.isValidPlayerUUID(uuid)) return Optional.empty(); - CosmicSender sender = createTemporarySender(uuid); - sender.load(); + CosmicPlayer player = createTemporaryPlayer(uuid); + player.load(); - sender.augment(Singularity.getMainDatabase().loadPlayer(uuid), true); + player.augment(Singularity.getMainDatabase().loadPlayer(uuid), true); - return Optional.of(sender); + return Optional.of(player); } public static Optional getOrGetPlayer(String uuid) { Optional optional = getOrGetSender(uuid); - if (optional.isEmpty()) return Optional.empty(); - - CosmicSender sender = optional.get(); - if (sender instanceof CosmicPlayer) { - return Optional.of((CosmicPlayer) sender); + if (optional.isPresent()) { + if (optional.get() instanceof CosmicPlayer) return optional.map(s -> (CosmicPlayer) s); } return Optional.empty(); diff --git a/singularity-api/src/main/resources/main-config.yml b/singularity-api/src/main/resources/main-config.yml index e1d124c8..2d09c0e0 100644 --- a/singularity-api/src/main/resources/main-config.yml +++ b/singularity-api/src/main/resources/main-config.yml @@ -55,10 +55,10 @@ players: equation: "2500 + (2500 * (%streamline_user_level% - 1))" # Settings for tags. # Tags are a list of Strings ("this" and "this also" are Strings) that can be - # used when running scripts, events, or other features; as a way to distinguish + # used when running scripts, events, or other features, as a way to distinguish # between certain players. (Like that of actual Minecraft tags that Mojang # introduced in 1.13.) --> (Link below for the Minecraft version -- NOT Streamline!) - # https://www.digminecraft.com/game_commands/tag_command.php#:~:text=You%20can%20add%2C%20list%20and,and%20manage%20tags%20for%20players. + # https://www.digminecraft.com/game_commands/tag_command.php tags: # The default tags a user will receive when their profile is first created. default: [] diff --git a/spigot/build.gradle b/spigot/build.gradle index 558fc6a8..555831d2 100644 --- a/spigot/build.gradle +++ b/spigot/build.gradle @@ -1,13 +1,13 @@ dependencies { // Platform dependencies. // Spigot (commented out: uncomment if needed) -// compileOnly "org.spigotmc:spigot-api:1.21.4-R0.1-SNAPSHOT" +// annotationProcessor(compileOnly("org.spigotmc:spigot-api:1.21.4-R0.1-SNAPSHOT")) // Paper (commented out: uncomment if needed) - compileOnly "io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT" + annotationProcessor(compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")) // Use Spigot API for version 1.16.5 -// compileOnly "org.spigotmc:spigot-api:1.16.5-R0.1-SNAPSHOT" +// annotationProcessor(compileOnly("org.spigotmc:spigot-api:1.16.5-R0.1-SNAPSHOT")) // Defaults. compileOnly(files(FILES)) @@ -16,8 +16,10 @@ dependencies { // Other Plugins compileOnly(OTHER_PLUGINS) - implementation shadow("com.github.hamza-cskn.obliviate-invs:core:4.1.12") - compileOnly("com.github.Streamline-Essentials:BukkitOfUtils:master-SNAPSHOT") + + // BOU + implementation(shadow("com.github.hamza-cskn.obliviate-invs:core:4.1.12")) + annotationProcessor(compileOnly("com.github.Streamline-Essentials:BukkitOfUtils:master-SNAPSHOT")) // Streamline API. compileOnly project(path: ":StreamlineCore-API") @@ -26,6 +28,7 @@ dependencies { implementation(project(path: ':StreamlineCore-BAPI', configuration: 'shadow')) { // Correct way to exclude dependency exclude group: "com.github.server-utilities", module: "TheBase" + exclude group: "gg.drak.thebase" } compileOnly project(path: ":StreamlineCore-Singularity") diff --git a/spigot/src/main/java/net/streamline/platform/BasePlugin.java b/spigot/src/main/java/net/streamline/platform/BasePlugin.java index e5cb3ca4..54182c79 100644 --- a/spigot/src/main/java/net/streamline/platform/BasePlugin.java +++ b/spigot/src/main/java/net/streamline/platform/BasePlugin.java @@ -50,6 +50,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; +import java.util.logging.Logger; public abstract class BasePlugin extends BetterPlugin implements ISingularityExtension { @Getter @@ -90,6 +91,9 @@ public Server getProxy() { @Getter @Setter private static TaskScheduler scheduler; + @Getter @Setter + private static PlatformListener.ProxyMessagingListener proxyMessagingListener; + @Override public void onBaseConstruct() { instance = this; @@ -156,8 +160,10 @@ public void onBaseEnabled() { TaskManager.init(); + proxyMessagingListener = new PlatformListener.ProxyMessagingListener(); + getProxy().getMessenger().registerOutgoingPluginChannel(this, SLAPI.getApiChannel()); - getProxy().getMessenger().registerIncomingPluginChannel(this, SLAPI.getApiChannel(), new PlatformListener.ProxyMessagingListener()); + getProxy().getMessenger().registerIncomingPluginChannel(this, SLAPI.getApiChannel(), proxyMessagingListener); playerChecker = new PlayerChecker(); PlayerTeleporter.init(); @@ -173,6 +179,10 @@ public void onBaseDisable() { UserUtils.syncAllUsers(); UuidManager.getUuids().forEach(UuidInfo::save); + getProxy().getMessenger().unregisterOutgoingPluginChannel(this, SLAPI.getApiChannel()); + getProxy().getMessenger().unregisterIncomingPluginChannel(this, SLAPI.getApiChannel()); +// getProxy().getMessenger().unregisterIncomingPluginChannel(this, SLAPI.getApiChannel(), proxyMessagingListener); + this.disable(); fireStopEvent(); @@ -515,4 +525,14 @@ public static ConcurrentSkipListMap getPlayersByUUID() { public static Command getBukkitCommand(String name) { return commandMap.getCommand(name); } + + @Override + public Logger getLoggerLogger() { + return getLogger(); + } + + @Override + public org.slf4j.Logger getSLFLogger() { + return null; + } } \ No newline at end of file diff --git a/velocity/build.gradle b/velocity/build.gradle index b8de120a..cc0de13f 100644 --- a/velocity/build.gradle +++ b/velocity/build.gradle @@ -1,6 +1,6 @@ dependencies { - compileOnly 'com.velocitypowered:velocity-api:3.4.0-SNAPSHOT' - annotationProcessor 'com.velocitypowered:velocity-api:3.4.0-SNAPSHOT' + // Platform + annotationProcessor(compileOnly('com.velocitypowered:velocity-api:3.4.0-SNAPSHOT')) // implementation 'net.kyori:adventure-text-serializer-gson:4.15.0' diff --git a/velocity/src/main/java/net/streamline/base/StreamlineVelocity.java b/velocity/src/main/java/net/streamline/base/StreamlineVelocity.java index e28d7295..a629f8fc 100644 --- a/velocity/src/main/java/net/streamline/base/StreamlineVelocity.java +++ b/velocity/src/main/java/net/streamline/base/StreamlineVelocity.java @@ -12,24 +12,23 @@ import java.io.File; import java.nio.file.Path; -@Plugin( - id = "streamlinecore", - name = "${name}", - version = "${version}", - dependencies = { - @Dependency(id = "luckperms"), - @Dependency(id = "geyser-velocity", optional = true) - } -) +//@Plugin( +// id = "streamlinecore", +// name = "StreamlineCore", +// dependencies = { +// @Dependency(id = "luckperms"), +// @Dependency(id = "geyser-velocity", optional = true) +// } +//) public class StreamlineVelocity extends BasePlugin { @Inject public StreamlineVelocity(ProxyServer server, Logger logger, Metrics.Factory metricsFactory) { - super(server, logger, getStreamlineFolder(), metricsFactory); + super(server, logger, getOwnFolder(), metricsFactory); } - public static File getStreamlineFolder() { + public static File getOwnFolder() { return new File(getPluginsDirectory(), "StreamlineCore"); } diff --git a/velocity/src/main/java/net/streamline/platform/BasePlugin.java b/velocity/src/main/java/net/streamline/platform/BasePlugin.java index af853528..40bd6745 100644 --- a/velocity/src/main/java/net/streamline/platform/BasePlugin.java +++ b/velocity/src/main/java/net/streamline/platform/BasePlugin.java @@ -411,4 +411,14 @@ public static ConcurrentSkipListMap getPlayersByUUID() { } return map; } + + @Override + public java.util.logging.Logger getLoggerLogger() { + return null; + } + + @Override + public org.slf4j.Logger getSLFLogger() { + return getLogger(); + } } diff --git a/velocity/src/main/java/net/streamline/platform/listeners/PlatformListener.java b/velocity/src/main/java/net/streamline/platform/listeners/PlatformListener.java index d9ab643c..51b0a8e9 100644 --- a/velocity/src/main/java/net/streamline/platform/listeners/PlatformListener.java +++ b/velocity/src/main/java/net/streamline/platform/listeners/PlatformListener.java @@ -220,7 +220,7 @@ public void onPing(ProxyPingEvent event) { if (ping.getFavicon().isEmpty()) { response = new PingedResponse(protocol, players, Messenger.getInstance().asString(ping.getDescriptionComponent())); } else { - response = new PingedResponse(protocol, players, Messenger.getInstance().asString(ping.getDescriptionComponent()), ping.getFavicon().toString()); + response = new PingedResponse(protocol, players, Messenger.getInstance().asString(ping.getDescriptionComponent()), ping.getFavicon().get().getBase64Url()); } } catch (Throwable e) { MessageUtils.logWarning("Failed to get favicon from ping: " + e.getMessage()); diff --git a/velocity/src/main/resources/plugin.yml b/velocity/src/main/resources/plugin.yml deleted file mode 100644 index e69de29b..00000000 diff --git a/velocity/src/main/resources/velocity-plugin.json b/velocity/src/main/resources/velocity-plugin.json new file mode 100644 index 00000000..7c690596 --- /dev/null +++ b/velocity/src/main/resources/velocity-plugin.json @@ -0,0 +1,24 @@ +{ + "id": "streamlinecore", + "name": "${name}", + "version": "${version}", + "authors": [ + "Drak" + ], + "author": "Drak", + "dependencies": [ + { + "id": "luckperms", + "optional": false + }, + { + "id": "geyser-velocity", + "optional": true + }, + { + "id": "floodgate", + "optional": true + } + ], + "main": "net.streamline.base.StreamlineVelocity" +} \ No newline at end of file