Skip to content
This repository has been archived by the owner on Nov 22, 2024. It is now read-only.

Commit

Permalink
Changed config management, switched to pb4 placeholders in new custom…
Browse files Browse the repository at this point in the history
… chat formats
  • Loading branch information
Ale32bit committed Nov 4, 2024
1 parent 362132f commit df169f6
Show file tree
Hide file tree
Showing 24 changed files with 218 additions and 149 deletions.
4 changes: 0 additions & 4 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ repositories {
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.

maven { url 'https://maven.wispforest.io' }
maven { url 'https://maven.nucleoid.xyz' }
maven { url 'https://maven.reconnected.cc/releases' }
}
Expand All @@ -42,9 +41,6 @@ dependencies {
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"

annotationProcessor modImplementation("io.wispforest:owo-lib:${project.owo_version}")
include "io.wispforest:owo-sentinel:${project.owo_version}"

compileOnly "net.luckperms:api:${project.luckpermsapi_version}"
include modImplementation("me.lucko:fabric-permissions-api:${project.permissions_api_version}")

Expand Down
2 changes: 0 additions & 2 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ archives_base_name=rcc-server
# Dependencies
fabric_version=0.92.2+1.20.1

owo_version=0.11.2+1.20

luckpermsapi_version=5.4
permissions_api_version=0.2-SNAPSHOT

Expand Down
4 changes: 3 additions & 1 deletion src/main/java/cc/reconnected/server/RccServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import cc.reconnected.server.commands.teleport.*;
import cc.reconnected.server.commands.tell.*;
import cc.reconnected.server.commands.warp.*;
import cc.reconnected.server.config.Config;
import cc.reconnected.server.config.ConfigManager;
import cc.reconnected.server.core.*;
import cc.reconnected.server.data.StateManager;
import net.fabricmc.api.ModInitializer;
Expand Down Expand Up @@ -36,7 +38,7 @@ public class RccServer implements ModInitializer {
public static final String MOD_ID = "rcc-server";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);

public static final cc.reconnected.server.RccServerConfig CONFIG = cc.reconnected.server.RccServerConfig.createAndLoad();
public static Config CONFIG = ConfigManager.load();

public static final StateManager state = new StateManager();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import cc.reconnected.server.RccServer;
import cc.reconnected.server.api.events.RccEvents;
import cc.reconnected.server.config.ConfigManager;
import com.mojang.brigadier.CommandDispatcher;
import me.lucko.fabric.api.permissions.v0.Permissions;
import net.minecraft.command.CommandRegistryAccess;
Expand All @@ -21,7 +22,7 @@ public static void register(CommandDispatcher<ServerCommandSource> dispatcher, C
context.getSource().sendFeedback(() -> Text.of("Reloading RCC config..."), true);

try {
RccServer.CONFIG.load();
RccServer.CONFIG = ConfigManager.load();
} catch(Exception e) {
RccServer.LOGGER.error("Failed to load RCC config", e);
context.getSource().sendFeedback(() -> Text.of("Failed to load RCC config. Check console for more info."), true);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cc.reconnected.server.commands.admin;

import cc.reconnected.server.RccServer;
import cc.reconnected.server.api.events.RccEvents;
import cc.reconnected.server.core.AutoRestart;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
Expand Down Expand Up @@ -37,7 +36,7 @@ public static void register(CommandDispatcher<ServerCommandSource> dispatcher, C

private static int schedule(CommandContext<ServerCommandSource> context, int seconds, @Nullable String message) {
if (message == null) {
message = RccServer.CONFIG.autoRestart.restartBarLabel();
message = RccServer.CONFIG.autoRestart.restartBarLabel;
}
AutoRestart.schedule(seconds, message);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ private static int execute(CommandContext<ServerCommandSource> context, String n
return 1;
}

var maxHomes = RccServer.CONFIG.homes.maxHomes();
var maxHomes = RccServer.CONFIG.homes.maxHomes;
if(homes.size() >= maxHomes && !exists) {
context.getSource().sendFeedback(() -> Text.literal("You have reached the maximum amount of homes!").formatted(Formatting.RED), false);
return 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ public static void register(CommandDispatcher<ServerCommandSource> dispatcher, C
context.getSource().sendFeedback(() -> Text.of("This command can only be executed by players!"), false);
return 1;
}
return execute(context, RccServer.CONFIG.nearCommand.nearCommandDefaultRange(), context.getSource().getPlayer());
return execute(context, RccServer.CONFIG.nearCommand.nearCommandDefaultRange, context.getSource().getPlayer());
})
.then(argument("radius", IntegerArgumentType.integer(0, RccServer.CONFIG.nearCommand.nearCommandMaxRange()))
.then(argument("radius", IntegerArgumentType.integer(0, RccServer.CONFIG.nearCommand.nearCommandMaxRange))
.executes(context -> {
if (!context.getSource().isExecutedByPlayer()) {
context.getSource().sendFeedback(() -> Text.of("This command can only be executed by players!"), false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,17 +71,17 @@ public static void sendDirectMessage(String targetName, ServerCommandSource sour

var parsedMessage = MarkdownParser.defaultParser.parseNode(message);
var you = Component.text("You", NamedTextColor.GRAY, TextDecoration.ITALIC);
var sourceText = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.directMessages.tellMessage(),
var sourceText = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.directMessages.tellMessage,
Placeholder.component("source", you),
Placeholder.component("target", targetDisplayName),
Placeholder.component("message", parsedMessage.toText()));

var targetText = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.directMessages.tellMessage(),
var targetText = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.directMessages.tellMessage,
Placeholder.component("source", source.getDisplayName()),
Placeholder.component("target", you),
Placeholder.component("message", parsedMessage.toText()));

var text = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.directMessages.tellMessage(),
var text = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.directMessages.tellMessage,
Placeholder.component("source", source.getDisplayName()),
Placeholder.component("target", targetDisplayName),
Placeholder.component("message", parsedMessage.toText()));
Expand All @@ -104,7 +104,7 @@ public static void sendDirectMessage(String targetName, ServerCommandSource sour

var lp = RccServer.getInstance().luckPerms();
var playerAdapter = lp.getPlayerAdapter(ServerPlayerEntity.class);
var spyText = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.directMessages.tellMessageSpy(),
var spyText = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.directMessages.tellMessageSpy,
Placeholder.component("source", source.getDisplayName()),
Placeholder.component("target", targetDisplayName),
Placeholder.component("message", parsedMessage.toText()));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,21 @@
package cc.reconnected.server;
package cc.reconnected.server.config;

import io.wispforest.owo.config.annotation.Config;
import io.wispforest.owo.config.annotation.Nest;
import java.util.ArrayList;
import java.util.List;

import java.util.*;
public class Config {
Config() {
}

@Config(name = "rcc-server-config", wrapperName = "RccServerConfig")
public class RccServerConfigModel {
@Nest
public HttpApi httpApi = new HttpApi();

@Nest
public Afk afk = new Afk();

@Nest
public DirectMessages directMessages = new DirectMessages();

@Nest
public TeleportRequests teleportRequests = new TeleportRequests();

@Nest
public Homes homes = new Homes();

@Nest
public CustomTabList customTabList = new CustomTabList();

@Nest
public NearCommand nearCommand = new NearCommand();

@Nest
public AutoRestart autoRestart = new AutoRestart();

@Nest
public CustomNameConfig customName = new CustomNameConfig();

@Nest
public CustomChatFormat customChatFormat = new CustomChatFormat();
public TextFormats textFormats = new TextFormats();

public static class HttpApi {
public boolean enableHttpApi = true;
Expand Down Expand Up @@ -112,20 +92,24 @@ public static class AutoRestart {
));
}

public static class CustomNameConfig {
public LinkedHashMap<String, String> formats = new LinkedHashMap<>(Map.of(
"admin", "<red><username></red>",
"default", "<green><username></green>"
public static class TextFormats {
public record NameFormat(String group, String format) {
}

public boolean enableChatMarkdown = true;

public ArrayList<NameFormat> nameFormats = new ArrayList<>(List.of(
new NameFormat("admin", "<red>%player:name%</red>"),
new NameFormat("default", "<green>%player:name%</green>")
));
}

public static class CustomChatFormat {
public boolean enableMarkdown = true;
public String chatFormat = "<display_name><gray>:</gray> <message>";
public String emoteFormat = "<gray>\uD83D\uDC64 <display_name> <i><message></i></gray>";
public String joinFormat = "<green>+</green> <display_name> <yellow>joined!</yellow>";
public String joinRenamedFormat = "<green>+</green> <display_name> <yellow>joined! <i>(Previously known as <previous_name>)</i></yellow>";
public String leaveFormat = "<red>-</red> <display_name> <yellow>left!</yellow>";
public String deathFormat = "<gray>\u2620 <death_message></gray>";
public String chatFormat = "${player}<gray>:</gray> ${message}";
public String emoteFormat = "<gray>\uD83D\uDC64 ${player} <i>${message}</i></gray>";
public String joinFormat = "<green>+</green> ${player} <yellow>joined!</yellow>";
public String joinRenamedFormat = "<green>+</green> ${player} <yellow>joined! <i>(Previously known as ${previousName})</i></yellow>";
public String leaveFormat = "<red>-</red> ${player} <yellow>left!</yellow>";
public String deathFormat = "<gray>\u2620 ${message}</gray>";
}


}
47 changes: 47 additions & 0 deletions src/main/java/cc/reconnected/server/config/ConfigManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package cc.reconnected.server.config;

import cc.reconnected.server.RccServer;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.fabricmc.loader.api.FabricLoader;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;

public class ConfigManager {
private static final Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setPrettyPrinting()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
.create();
private static final Path configFilePath = FabricLoader.getInstance().getConfigDir().resolve(RccServer.MOD_ID + ".json");
private static Config config = null;

public static Config load() {
if (!configFilePath.toFile().exists()) {
config = new Config();
save();
return config;
}
try (var bf = new BufferedReader(new FileReader(configFilePath.toFile(), StandardCharsets.UTF_8))) {
config = gson.fromJson(bf, Config.class);
save();
} catch (Exception e) {
RccServer.LOGGER.error("Error loading the RccServer config file.", e);
}
return config;
}

public static void save() {
var json = gson.toJson(config);
try (var fw = new FileWriter(configFilePath.toFile(), StandardCharsets.UTF_8)) {
fw.write(json);
} catch (Exception e) {
RccServer.LOGGER.error("Error saving the RccServer config file.", e);
}
}
}
8 changes: 4 additions & 4 deletions src/main/java/cc/reconnected/server/core/AfkTracker.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

public class AfkTracker {
private static final int cycleDelay = 1;
private static final int absentTimeTrigger = RccServer.CONFIG.afk.afkTimeTrigger() * 20; // seconds * 20 ticks
private static final int absentTimeTrigger = RccServer.CONFIG.afk.afkTimeTrigger * 20; // seconds * 20 ticks

private final ConcurrentHashMap<UUID, PlayerActivityState> playerActivityStates = new ConcurrentHashMap<>();

Expand Down Expand Up @@ -57,7 +57,7 @@ public static void register() {
var displayNameJson = Text.Serializer.toJson(player.getDisplayName());
var displayName = JSONComponentSerializer.json().deserialize(displayNameJson);

var message = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.afk.afkMessage(),
var message = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.afk.afkMessage,
Placeholder.component("displayname", displayName),
Placeholder.unparsed("username", player.getGameProfile().getName()),
Placeholder.unparsed("uuid", player.getUuid().toString())
Expand All @@ -72,7 +72,7 @@ public static void register() {
var displayNameJson = Text.Serializer.toJson(player.getDisplayName());
var displayName = JSONComponentSerializer.json().deserialize(displayNameJson);

var message = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.afk.afkReturnMessage(),
var message = MiniMessage.miniMessage().deserialize(RccServer.CONFIG.afk.afkReturnMessage,
Placeholder.component("displayname", displayName),
Placeholder.unparsed("username", player.getGameProfile().getName()),
Placeholder.unparsed("uuid", player.getUuid().toString())
Expand All @@ -85,7 +85,7 @@ public static void register() {
}

private static void loadAfkTag() {
afkTag = Components.toText(MiniMessage.miniMessage().deserialize(RccServer.CONFIG.afk.afkTag()));
afkTag = Components.toText(MiniMessage.miniMessage().deserialize(RccServer.CONFIG.afk.afkTag));
}

private AfkTracker() {
Expand Down
16 changes: 8 additions & 8 deletions src/main/java/cc/reconnected/server/core/AutoRestart.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static void register() {
var miniMessage = MiniMessage.miniMessage();

RccEvents.READY.register((server, luckPerms) -> {
if (RccServer.CONFIG.autoRestart.enableAutoRestart()) {
if (RccServer.CONFIG.autoRestart.enableAutoRestart) {
scheduleNextRestart();
}
});
Expand All @@ -42,7 +42,7 @@ public static void register() {
if (restartBar == null || !timeBar.getUuid().equals(restartBar.getUuid()))
return;

var notificationTimes = RccServer.CONFIG.autoRestart.restartNotifications();
var notificationTimes = RccServer.CONFIG.autoRestart.restartNotifications;

var remainingSeconds = restartBar.getRemainingSeconds();
if (notificationTimes.contains(remainingSeconds)) {
Expand All @@ -57,7 +57,7 @@ public static void register() {
return;

final var text = Components.toText(
miniMessage.deserialize(RccServer.CONFIG.autoRestart.restartKickMessage())
miniMessage.deserialize(RccServer.CONFIG.autoRestart.restartKickMessage)
);
server.getPlayerManager().getPlayerList().forEach(player -> {
player.networkHandler.disconnect(text);
Expand All @@ -74,7 +74,7 @@ public static void register() {
}

private static void setup() {
var soundName = RccServer.CONFIG.autoRestart.restartSound();
var soundName = RccServer.CONFIG.autoRestart.restartSound;
try {
notificationKey = Key.key(soundName);
} catch (InvalidKeyException e) {
Expand Down Expand Up @@ -115,10 +115,10 @@ public static void cancel() {
private static void notifyRestart(MinecraftServer server, BossBarManager.TimeBar bar) {
var rcc = RccServer.getInstance();
var audience = rcc.adventure().players();
var sound = Sound.sound(notificationKey, Sound.Source.MASTER, 10f, RccServer.CONFIG.autoRestart.restartSoundPitch());
var sound = Sound.sound(notificationKey, Sound.Source.MASTER, 10f, RccServer.CONFIG.autoRestart.restartSoundPitch);
audience.playSound(sound, Sound.Emitter.self());

var comp = bar.parseLabel(RccServer.CONFIG.autoRestart.restartChatMessage());
var comp = bar.parseLabel(RccServer.CONFIG.autoRestart.restartChatMessage);
rcc.broadcastMessage(server, comp);
}

Expand All @@ -133,7 +133,7 @@ public static Long scheduleNextRestart() {
var barStartTime = delay - barTime;

currentSchedule = scheduler.schedule(() -> {
schedule(barTime, RccServer.CONFIG.autoRestart.restartBarLabel());
schedule(barTime, RccServer.CONFIG.autoRestart.restartBarLabel);
}, barStartTime, TimeUnit.SECONDS);

RccServer.LOGGER.info("Restart scheduled for in {} seconds", delay);
Expand All @@ -142,7 +142,7 @@ public static Long scheduleNextRestart() {

@Nullable
private static Long getNextDelay() {
var restartTimeStrings = RccServer.CONFIG.autoRestart.restartAt();
var restartTimeStrings = RccServer.CONFIG.autoRestart.restartAt;
LocalDateTime now = LocalDateTime.now();
LocalDateTime nextRunTime = null;
long shortestDelay = Long.MAX_VALUE;
Expand Down
Loading

0 comments on commit df169f6

Please sign in to comment.