Skip to content

Commit

Permalink
Implement a config system for Gradle...
Browse files Browse the repository at this point in the history
, add many more platforms (Bungee, Minestom and Velocity), use a better logger and just general improvements
  • Loading branch information
Novampr committed Mar 13, 2024
1 parent 40b4044 commit 12b3c4d
Show file tree
Hide file tree
Showing 29 changed files with 1,068 additions and 57 deletions.
11 changes: 9 additions & 2 deletions API/build.gradle
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import groovy.json.JsonSlurper

plugins {
id 'java'
id "maven-publish"
id 'com.github.johnrengelman.shadow' version '8.1.1'
}

group = 'net.kore'
version = '0.1.0'
def jsonSlurper = new JsonSlurper()
def config = jsonSlurper.parse(new File(rootDir, 'config.json'))

group = config.group as String
version = config.version as String

repositories {
mavenCentral()
Expand All @@ -15,6 +20,8 @@ dependencies {
implementation 'com.google.code.gson:gson:2.10.1'
implementation "org.spongepowered:configurate-hocon:4.1.2"
implementation "org.apache.logging.log4j:log4j-api:2.17.0"
implementation 'org.slf4j:slf4j-api:2.0.12'
implementation "net.kyori:adventure-api:4.16.0"
}

shadowJar {
Expand Down
1 change: 1 addition & 0 deletions API/src/main/java/net/kore/pronouns/api/PronounsAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public static void setInstance(PronounsAPI i) {
abstract public String getReflexive(UUID uuid);

public String formatPlayer(String input, String name) {
if (name == null) name = "null";
return input.replace("${player}", name);
}
}
74 changes: 37 additions & 37 deletions API/src/main/java/net/kore/pronouns/api/PronounsLogger.java
Original file line number Diff line number Diff line change
@@ -1,60 +1,60 @@
package net.kore.pronouns.api;

import net.kyori.adventure.text.Component;

import java.util.logging.Logger;

public class PronounsLogger {
private static boolean isL4J = false;
private static Logger javaLogger = null;
private static org.apache.logging.log4j.Logger l4JLogger = null;

public static void setLogger(Logger logger) {
javaLogger = logger;
}

public static void setLogger(org.apache.logging.log4j.Logger logger) {
l4JLogger = logger;
isL4J = true;
}
private static Object LOGGER;
public static void setLogger(Object l) { LOGGER = l; }

public static void info(String info) {
if (isL4J) {
l4JLogger.info(info);
} else if (javaLogger != null) {
javaLogger.info(info);
} else {
throw new IllegalStateException("Logger not ready.");
try {
LOGGER.getClass().getMethod("info", String.class).invoke(LOGGER, info);
} catch (Throwable ee) {
try {
LOGGER.getClass().getMethod("info", Component.class).invoke(LOGGER, Component.text(info));
} catch (Throwable e) {
throw new IllegalStateException("Logger couldn't be executed.", e);
}
}
}

public static void warn(String info) {
if (isL4J) {
l4JLogger.warn(info);
} else if (javaLogger != null) {
javaLogger.warning(info);
} else {
throw new IllegalStateException("Logger not ready.");
try {
LOGGER.getClass().getMethod("warning", String.class).invoke(LOGGER, info);
} catch (Throwable eee) {
try {
LOGGER.getClass().getMethod("warn", String.class).invoke(LOGGER, info);
} catch (Throwable ee) {
try {
LOGGER.getClass().getMethod("warn", Component.class).invoke(LOGGER, Component.text(info));
} catch (Throwable e) {
throw new IllegalStateException("Logger couldn't be executed.", e);
}
}
}
}

public static void error(String info) {
if (isL4J) {
l4JLogger.error(info);
} else if (javaLogger != null) {
javaLogger.severe(info);
} else {
throw new IllegalStateException("Logger not ready.");
try {
LOGGER.getClass().getMethod("severe", String.class).invoke(LOGGER, info);
} catch (Throwable eee) {
try {
LOGGER.getClass().getMethod("error", String.class).invoke(LOGGER, info);
} catch (Throwable ee) {
try {
LOGGER.getClass().getMethod("error", Component.class).invoke(LOGGER, Component.text(info));
} catch (Throwable e) {
throw new IllegalStateException("Logger couldn't be executed.", e);
}
}
}
}

public static void debug(String info) {
if (PronounsConfig.get().node("debug-logging").getBoolean(false)) {
if (isL4J) {
l4JLogger.info(info);
} else if (javaLogger != null) {
javaLogger.info(info);
} else {
throw new IllegalStateException("Logger not ready.");
}
info(info);
}
}
}
35 changes: 35 additions & 0 deletions Bungee/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import groovy.json.JsonSlurper

plugins {
id 'java'
id 'com.github.johnrengelman.shadow' version '8.1.1'
}

def jsonSlurper = new JsonSlurper()
def config = jsonSlurper.parse(new File(rootDir, 'config.json'))

group = config.group as String
version = config.version as String

shadowJar {
archiveBaseName.set('Pronouns-Bungee')
archiveClassifier.set('')
archiveVersion.set(version)
destinationDirectory.set(new File(rootDir, "output"))
}

repositories {
mavenCentral()
maven {
url = "https://oss.sonatype.org/content/groups/public/"
}
maven {
url = "https://libraries.minecraft.net"
}
}

dependencies {
implementation project(path: ':API')
compileOnly 'net.md-5:bungeecord-api:1.20-R0.3-SNAPSHOT'
implementation "org.spongepowered:configurate-hocon:4.1.2"
}
47 changes: 47 additions & 0 deletions Bungee/src/main/java/net/kore/pronouns/bungee/BungeePronouns.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package net.kore.pronouns.bungee;

import com.google.common.io.Resources;
import net.kore.pronouns.api.PronounsConfig;
import net.kore.pronouns.api.PronounsLogger;
import net.md_5.bungee.api.plugin.Plugin;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.hocon.HoconConfigurationLoader;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

public class BungeePronouns extends Plugin {
private static BungeePronouns INSTANCE;
public static BungeePronouns getInstance() {
return INSTANCE;
}

@Override
public void onEnable() {
PronounsLogger.setLogger(getLogger());

File configFile = new File(getDataFolder(), "config.conf");
if (!configFile.exists() || !configFile.isDirectory()) {
try {
Files.copy(Paths.get(Resources.getResource("config.conf").toURI()), configFile.toPath());
} catch (Exception e) {
throw new RuntimeException(e);
}
}

HoconConfigurationLoader loader = HoconConfigurationLoader.builder()
.file(configFile)
.build();

try {
PronounsConfig.set(loader.load());
} catch (ConfigurateException e) {
throw new RuntimeException(e);
}

INSTANCE = this;

BungeePronounsAPI.get();
}
}
177 changes: 177 additions & 0 deletions Bungee/src/main/java/net/kore/pronouns/bungee/BungeePronounsAPI.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
package net.kore.pronouns.bungee;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.kore.pronouns.api.CachedPronouns;
import net.kore.pronouns.api.PronounsAPI;
import net.kore.pronouns.api.PronounsConfig;
import net.kore.pronouns.api.PronounsLogger;
import net.md_5.bungee.api.connection.ProxiedPlayer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class BungeePronounsAPI extends PronounsAPI {
private BungeePronounsAPI() {
BungeePronouns.getInstance().getProxy().getScheduler().schedule(BungeePronouns.getInstance(), () -> {
PronounsLogger.debug("Refreshing cache...");
cache.clear();
for (ProxiedPlayer player : BungeePronouns.getInstance().getProxy().getPlayers()) {
getPronouns(player.getUniqueId());
}
}, 0L, PronounsConfig.get().node("refresh").getLong(5), TimeUnit.MINUTES);
}
private static BungeePronounsAPI INSTANCE;
private static final List<CachedPronouns> cache = new ArrayList<>();

public static BungeePronounsAPI get() {
if (INSTANCE == null) {
INSTANCE = new BungeePronounsAPI();
PronounsAPI.setInstance(INSTANCE);
}
return INSTANCE;
}

private String getPronounsFromJA(JsonArray ja, int limit) {
List<String> ls = new ArrayList<>();

for (JsonElement je : ja) {
if (ls.size() == limit) break;
String pronoun = je.getAsString();
String p1 = PronounsConfig.get().node(pronoun, "overridep1").getString(PronounsConfig.get().node(pronoun, "personal-1").getString("No pronoun for "+pronoun+" defined in config.conf"));
ls.add(p1);
}

return String.join("/", ls);
}

public String getPronounFromShort(String pronoun) {
String p1 = PronounsConfig.get().node(pronoun, "overridep1").getString(PronounsConfig.get().node(pronoun, "personal-1").getString("No pronoun for "+pronoun+" defined in config.conf"));
String p2 = PronounsConfig.get().node(pronoun, "overridep2").getString(PronounsConfig.get().node(pronoun, "personal-2").getString("No pronoun for "+pronoun+" defined in config.conf"));
return p1+"/"+p2;
}

private JsonObject getObj(UUID uuid) {
try {
URL url = new URL("https://pronoundb.org/api/v2/lookup?platform=minecraft&ids="+uuid.toString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();

String response = content.toString();

return JsonParser.parseString(response).getAsJsonObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

private void check() {
cache.removeIf(cp -> Instant.now().toEpochMilli() - cp.timeCached() > 300000L);
}

private JsonArray getCached(UUID uuid) {
Optional<CachedPronouns> ocp = cache.stream().filter(cp -> cp.uuid().equals(uuid)).findFirst();
return ocp.map(CachedPronouns::pronouns).orElse(null);
}

private JsonArray getJsonArray(UUID uuid) {
check();
JsonArray cached = getCached(uuid);
if (cached != null) {
return cached;
}
JsonObject jo = getObj(uuid);
if (jo == null) {
return null;
}
if (!jo.has(uuid.toString())) {
return null;
}
JsonArray ja = new JsonArray();
for (JsonElement je : jo.get(uuid.toString()).getAsJsonObject().get("sets").getAsJsonObject().get("en").getAsJsonArray()) {
ja.add(formatPlayer(je.getAsString(), BungeePronouns.getInstance().getProxy().getPlayer(uuid).getName()));
}

if (cache.size() == PronounsConfig.get().node("max-cache").getLong()) {
PronounsLogger.debug("Cache has hit max, now flooding cache to prevent max cache hit.");
cache.clear();
}
cache.add(new CachedPronouns(uuid, ja, Instant.now().toEpochMilli()));
return ja;
}

public String getPronounsLimit(UUID uuid, int limit) {
JsonArray ja = getJsonArray(uuid);
if (ja == null) {
return PronounsConfig.get().node("no-pronouns").getString("\"no-pronouns\" is not defined in config.conf");
}
if (ja.size() == 1 || limit == 1) return getPronounFromShort(ja.get(0).getAsString());

return getPronounsFromJA(ja, limit);
}

public String getPronouns(UUID uuid) {
return getPronounsLimit(uuid, 3);
}

public String getShortPronouns(UUID uuid) {
return getPronounsLimit(uuid, 2);
}

public String getPersonal1(UUID uuid) {
JsonArray ja = getJsonArray(uuid);
if (ja == null) {
return PronounsConfig.get().node("no-pronouns").getString("\"no-pronouns\" is not defined in config.conf");
}

return PronounsConfig.get().node(ja.get(0).getAsString(), "personal-1").getString("No pronoun defined for " + ja.get(0).getAsString() + "in config.conf");
}

public String getPersonal2(UUID uuid) {
JsonArray ja = getJsonArray(uuid);
if (ja == null) {
return PronounsConfig.get().node("no-pronouns").getString("\"no-pronouns\" is not defined in config.conf");
}

return PronounsConfig.get().node(ja.get(0).getAsString(), "personal-2").getString("No pronoun defined for " + ja.get(0).getAsString() + "in config.conf");
}

public String getPossessive(UUID uuid) {
JsonArray ja = getJsonArray(uuid);
if (ja == null) {
return PronounsConfig.get().node("no-pronouns").getString("\"no-pronouns\" is not defined in config.conf");
}

return PronounsConfig.get().node(ja.get(0).getAsString(), "possessive").getString("No pronoun defined for " + ja.get(0).getAsString() + "in config.conf");
}

public String getReflexive(UUID uuid) {
JsonArray ja = getJsonArray(uuid);
if (ja == null) {
return PronounsConfig.get().node("no-pronouns").getString("\"no-pronouns\" is not defined in config.conf");
}

return PronounsConfig.get().node(ja.get(0).getAsString(), "reflexive").getString("No pronoun defined for " + ja.get(0).getAsString() + "in config.conf");
}
}
Loading

0 comments on commit 12b3c4d

Please sign in to comment.