Files
src
build.gradle
gradle.properties
settings.gradle
Code
10 544
src/main/java/com/extradev/extracline/ExtraCLine.java
package com.extradev.extracline;
import com.mojang.brigadier.arguments.StringArgumentType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.networking.v1.EntityTrackingEvents;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.command.permission.LeveledPermissionPredicate;
import net.minecraft.command.permission.Permission;
import net.minecraft.command.permission.PermissionPredicate;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.WorldSavePath;
import net.minecraft.entity.Entity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExtraCLine implements ModInitializer {
public static final String MOD_ID = "extracline";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
private static final Permission.Atom USE_PERMISSION = Permission.Atom.of(Identifier.of(MOD_ID, "use"));
private static final Map<UUID, String> LINES = new HashMap<>();
private static Path saveFile;
private static boolean dirty;
@Override
public void onInitialize() {
CLineConfig.load();
PayloadTypeRegistry.playS2C().register(CLinePayload.ID, CLinePayload.CODEC);
ServerLifecycleEvents.SERVER_STARTED.register(ExtraCLine::loadData);
ServerLifecycleEvents.SERVER_STOPPING.register(ExtraCLine::saveAndClearData);
ServerPlayConnectionEvents.JOIN.register(ExtraCLine::onJoin);
ServerPlayConnectionEvents.DISCONNECT.register(ExtraCLine::onDisconnect);
EntityTrackingEvents.START_TRACKING.register(ExtraCLine::onStartTracking);
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> dispatcher.register(
CommandManager.literal("cline")
.requires(ExtraCLine::hasUsePermission)
.executes(context -> showUsage(context.getSource()))
.then(CommandManager.literal("clear")
.executes(context -> clearLine(context.getSource())))
.then(CommandManager.literal("text")
.executes(context -> showUsage(context.getSource()))
.then(CommandManager.argument("text", StringArgumentType.greedyString())
.executes(context -> setLine(context.getSource(), StringArgumentType.getString(context, "text")))))
.then(CommandManager.argument("text", StringArgumentType.greedyString())
.executes(context -> setLine(context.getSource(), StringArgumentType.getString(context, "text"))))
));
}
private static boolean hasUsePermission(ServerCommandSource source) {
PermissionPredicate permissions = source.getPermissions();
return permissions.hasPermission(USE_PERMISSION) || permissions instanceof LeveledPermissionPredicate;
}
private static int showUsage(ServerCommandSource source) {
source.sendFeedback(() -> Text.literal("Usage cline text"), false);
return 1;
}
private static int setLine(ServerCommandSource source, String text) {
ServerPlayerEntity player = source.getPlayer();
if (player == null) {
source.sendError(Text.literal("Only players can set a CLine."));
return 0;
}
if (text.length() > CLineConfig.maxLength()) {
source.sendError(Text.literal("CLine is too long (maximum " + CLineConfig.maxLength() + " characters)."));
return 0;
}
UUID playerId = player.getUuid();
String previous = LINES.put(playerId, text);
if (!text.equals(previous)) {
dirty = true;
saveData();
}
broadcast(source.getServer(), new CLinePayload(playerId, text), null);
source.sendFeedback(() -> Text.literal("CLine updated."), false);
return 1;
}
private static int clearLine(ServerCommandSource source) {
ServerPlayerEntity player = source.getPlayer();
if (player == null) {
source.sendError(Text.literal("Only players can clear a CLine."));
return 0;
}
UUID playerId = player.getUuid();
if (LINES.remove(playerId) != null) {
dirty = true;
saveData();
}
broadcast(source.getServer(), new CLinePayload(playerId, ""), null);
source.sendFeedback(() -> Text.literal("CLine cleared."), false);
return 1;
}
private static void loadData(MinecraftServer server) {
LINES.clear();
dirty = false;
saveFile = server.getSavePath(WorldSavePath.ROOT).resolve("extracline-data.txt");
if (Files.notExists(saveFile)) {
return;
}
try {
for (String row : Files.readAllLines(saveFile, StandardCharsets.UTF_8)) {
int separator = row.indexOf('\t');
if (separator < 0) {
continue;
}
try {
UUID playerId = UUID.fromString(row.substring(0, separator));
String text = new String(Base64.getDecoder().decode(row.substring(separator + 1)), StandardCharsets.UTF_8);
if (!text.isEmpty()) {
LINES.put(playerId, text);
}
} catch (IllegalArgumentException ignored) {
}
}
} catch (IOException exception) {
LOGGER.error("Could not load saved CLines", exception);
}
}
private static void saveAndClearData(MinecraftServer server) {
saveData();
LINES.clear();
saveFile = null;
dirty = false;
}
private static void saveData() {
if (!dirty || saveFile == null) {
return;
}
List<String> rows = new ArrayList<>(LINES.size());
for (Map.Entry<UUID, String> entry : LINES.entrySet()) {
String encoded = Base64.getEncoder().encodeToString(entry.getValue().getBytes(StandardCharsets.UTF_8));
rows.add(entry.getKey() + "\t" + encoded);
}
try {
Files.createDirectories(saveFile.getParent());
Files.write(saveFile, rows, StandardCharsets.UTF_8);
dirty = false;
} catch (IOException exception) {
LOGGER.error("Could not save CLines", exception);
}
}
private static void onJoin(net.minecraft.server.network.ServerPlayNetworkHandler handler,
net.fabricmc.fabric.api.networking.v1.PacketSender sender,
MinecraftServer server) {
ServerPlayerEntity joiningPlayer = handler.getPlayer();
UUID joiningId = joiningPlayer.getUuid();
String joiningText = LINES.getOrDefault(joiningId, "");
for (ServerPlayerEntity onlinePlayer : server.getPlayerManager().getPlayerList()) {
ServerPlayNetworking.send(joiningPlayer,
new CLinePayload(onlinePlayer.getUuid(), LINES.getOrDefault(onlinePlayer.getUuid(), "")));
if (!onlinePlayer.getUuid().equals(joiningId)) {
ServerPlayNetworking.send(onlinePlayer, new CLinePayload(joiningId, joiningText));
}
}
}
private static void onDisconnect(net.minecraft.server.network.ServerPlayNetworkHandler handler, MinecraftServer server) {
UUID playerId = handler.getPlayer().getUuid();
broadcast(server, new CLinePayload(playerId, ""), playerId);
}
private static void onStartTracking(Entity trackedEntity, ServerPlayerEntity trackingPlayer) {
if (trackedEntity instanceof ServerPlayerEntity trackedPlayer) {
ServerPlayNetworking.send(trackingPlayer,
new CLinePayload(trackedPlayer.getUuid(), LINES.getOrDefault(trackedPlayer.getUuid(), "")));
}
}