package com.gastinelclaims; import com.gastinelclaims.core.ChunkKey; import com.gastinelclaims.core.ClaimRegistry; import com.gastinelclaims.core.PseudoMatcher; import com.gastinelclaims.core.PseudoMatcher.Profil; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.mojang.authlib.GameProfile; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.commands.SharedSuggestionProvider; import net.minecraft.network.chat.Component; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.neoforge.event.RegisterCommandsEvent; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; /** /claim, /claim info, /unclaim, /friend [add|unadd ] */ public final class ClaimCommands { @SubscribeEvent public static void onRegister(RegisterCommandsEvent event) { CommandDispatcher d = event.getDispatcher(); d.register(Commands.literal("claim") .executes(ClaimCommands::claim) .then(Commands.literal("info").executes(ClaimCommands::info))); d.register(Commands.literal("unclaim").executes(ClaimCommands::unclaim)); d.register(Commands.literal("friend") .executes(ClaimCommands::listFriends) .then(Commands.literal("add") .then(Commands.argument("pseudo", StringArgumentType.word()) .suggests((ctx, b) -> SharedSuggestionProvider.suggest( PseudoMatcher.suggestions(List.of(ctx.getSource().getServer().getPlayerNames())), b)) .executes(ctx -> addFriend(ctx, StringArgumentType.getString(ctx, "pseudo"))))) .then(Commands.literal("unadd") .then(Commands.argument("pseudo", StringArgumentType.word()) .suggests((ctx, b) -> SharedSuggestionProvider.suggest(PseudoMatcher.suggestions(friendNames(ctx)), b)) .executes(ctx -> removeFriend(ctx, StringArgumentType.getString(ctx, "pseudo")))))); } // --- Claims --- private static int claim(CommandContext ctx) throws CommandSyntaxException { ServerPlayer p = ctx.getSource().getPlayerOrException(); ClaimsData data = ClaimsData.get(p.server); ChunkKey key = ClaimsData.key(p.level(), p.blockPosition()); int max = ClaimsConfig.maxClaims(); ClaimRegistry r = data.registry(); switch (r.claim(p.getUUID(), key, max)) { case OK -> { data.setDirty(); ok(ctx, "Chunk [" + key.x() + ", " + key.z() + "] protégé. Claims : " + r.countOf(p.getUUID()) + "/" + max + "."); return 1; } case ALREADY_YOURS -> fail(ctx, "Ce chunk est déjà à toi."); case CLAIMED_BY_OTHER -> fail(ctx, "Ce chunk est déjà claim par " + nameOf(p.server, r.ownerOf(key)) + "."); case LIMIT_REACHED -> fail(ctx, "Limite atteinte (" + max + " chunks). Fais /unclaim ailleurs d'abord."); } return 0; } private static int unclaim(CommandContext ctx) throws CommandSyntaxException { ServerPlayer p = ctx.getSource().getPlayerOrException(); ClaimsData data = ClaimsData.get(p.server); ChunkKey key = ClaimsData.key(p.level(), p.blockPosition()); switch (data.registry().unclaim(p.getUUID(), key)) { case OK -> { data.setDirty(); ok(ctx, "Chunk [" + key.x() + ", " + key.z() + "] libéré."); return 1; } case NOT_CLAIMED -> fail(ctx, "Ce chunk n'est pas claim."); case NOT_OWNER -> fail(ctx, "Ce chunk appartient à " + nameOf(p.server, data.registry().ownerOf(key)) + "."); } return 0; } private static int info(CommandContext ctx) throws CommandSyntaxException { ServerPlayer p = ctx.getSource().getPlayerOrException(); ClaimRegistry r = ClaimsData.get(p.server).registry(); ChunkKey key = ClaimsData.key(p.level(), p.blockPosition()); UUID owner = r.ownerOf(key); int max = ClaimsConfig.maxClaims(); int left = Math.max(0, max - r.countOf(p.getUUID())); String who = owner == null ? "libre" : "à " + nameOf(p.server, owner); ok(ctx, "Chunk [" + key.x() + ", " + key.z() + "] : " + who + ". Il te reste " + left + "/" + max + " claims."); return 1; } // --- Amis --- private static int listFriends(CommandContext ctx) throws CommandSyntaxException { ServerPlayer p = ctx.getSource().getPlayerOrException(); var friends = ClaimsData.get(p.server).registry().friendsOf(p.getUUID()); if (friends.isEmpty()) { ok(ctx, "Aucun ami. Ajoute-en avec /friend add ."); } else { List names = new ArrayList<>(); for (UUID u : friends) names.add(nameOf(p.server, u)); ok(ctx, "Amis (" + names.size() + ") : " + String.join(", ", names)); } return 1; } private static int addFriend(CommandContext ctx, String name) throws CommandSyntaxException { ServerPlayer p = ctx.getSource().getPlayerOrException(); PseudoMatcher.Resultat res = chercher(p.server, name); if (res.statut() == PseudoMatcher.Statut.AMBIGU) { fail(ctx, PseudoMatcher.messageAmbigu(name, res.candidats())); return 0; } Profil target = res.profil(); if (target == null) { // Aucun profil connu : comportement d'origine (profil hors-ligne créé par le cache du serveur). Optional g = p.server.getProfileCache() == null ? Optional.empty() : p.server.getProfileCache().get(name); if (g.isEmpty()) { fail(ctx, "Joueur inconnu du serveur : " + name + "."); return 0; } target = new Profil(g.get().getId(), g.get().getName()); } ClaimsData data = ClaimsData.get(p.server); switch (data.registry().addFriend(p.getUUID(), target.id())) { case OK -> { data.setDirty(); ok(ctx, target.nom() + " a maintenant accès à tous tes claims."); return 1; } case SELF -> fail(ctx, "Tu ne peux pas t'ajouter toi-même."); case ALREADY -> fail(ctx, target.nom() + " est déjà ton ami."); default -> { } } return 0; } private static int removeFriend(CommandContext ctx, String name) throws CommandSyntaxException { ServerPlayer p = ctx.getSource().getPlayerOrException(); ClaimsData data = ClaimsData.get(p.server); // On cherche d'abord dans la liste d'amis (marche même si le cache de profils a oublié le pseudo) List amis = new ArrayList<>(); for (UUID u : data.registry().friendsOf(p.getUUID())) amis.add(new Profil(u, nameOf(p.server, u))); PseudoMatcher.Resultat res = PseudoMatcher.resoudreParmi(name, amis); if (res.statut() == PseudoMatcher.Statut.AMBIGU) { fail(ctx, PseudoMatcher.messageAmbigu(name, res.candidats())); return 0; } UUID friend = null; String affiche = name; if (res.trouve()) { friend = res.profil().id(); affiche = res.profil().nom(); } else { PseudoMatcher.Resultat glob = chercher(p.server, name); if (glob.statut() == PseudoMatcher.Statut.AMBIGU) { fail(ctx, PseudoMatcher.messageAmbigu(name, glob.candidats())); return 0; } if (glob.trouve()) { friend = glob.profil().id(); affiche = glob.profil().nom(); } else if (p.server.getProfileCache() != null) { friend = p.server.getProfileCache().get(name).map(GameProfile::getId).orElse(null); } } if (friend == null || data.registry().removeFriend(p.getUUID(), friend) != ClaimRegistry.FriendResult.OK) { fail(ctx, affiche + " n'est pas dans ta liste d'amis."); return 0; } data.setDirty(); ok(ctx, affiche + " n'a plus accès à tes claims."); return 1; } // --- Utilitaires --- /** * Pseudo tapé -> profil : joueurs en ligne d'abord, sinon cache de profils (usercache.json, joueurs déjà venus). * Tolérant aux caractères non tapables (guillemet...) ; ambigu si plusieurs comptes ressemblent à la saisie. */ private static PseudoMatcher.Resultat chercher(MinecraftServer server, String saisie) { List enLigne = new ArrayList<>(); for (ServerPlayer sp : server.getPlayerList().getPlayers()) { enLigne.add(new Profil(sp.getUUID(), sp.getGameProfile().getName())); } return PseudoMatcher.resoudre(saisie, enLigne, profilsDuCache(server)); } /** Lit usercache.json (écrit par le serveur à chaque ajout) ; liste vide en cas de problème. */ private static List profilsDuCache(MinecraftServer server) { List out = new ArrayList<>(); try { java.nio.file.Path f = server.getFile("usercache.json"); if (!Files.isRegularFile(f)) return out; try (Reader r = Files.newBufferedReader(f, StandardCharsets.UTF_8)) { JsonElement root = JsonParser.parseReader(r); if (!root.isJsonArray()) return out; JsonArray arr = root.getAsJsonArray(); for (JsonElement e : arr) { if (!e.isJsonObject() || !e.getAsJsonObject().has("name") || !e.getAsJsonObject().has("uuid")) continue; try { out.add(new Profil(UUID.fromString(e.getAsJsonObject().get("uuid").getAsString()), e.getAsJsonObject().get("name").getAsString())); } catch (RuntimeException ignored) { } } } } catch (Exception ex) { GastinelClaims.LOGGER.warn("[GastinelClaims] usercache.json illisible : {}", ex.toString()); } return out; } public static String nameOf(MinecraftServer server, UUID uuid) { if (uuid == null) return "?"; ServerPlayer online = server.getPlayerList().getPlayer(uuid); if (online != null) return online.getGameProfile().getName(); if (server.getProfileCache() != null) { Optional prof = server.getProfileCache().get(uuid); if (prof.isPresent()) return prof.get().getName(); } return uuid.toString().substring(0, 8); } private static List friendNames(CommandContext ctx) { ServerPlayer p = ctx.getSource().getPlayer(); if (p == null) return List.of(); List names = new ArrayList<>(); for (UUID u : ClaimsData.get(p.server).registry().friendsOf(p.getUUID())) names.add(nameOf(p.server, u)); return names; } private static void ok(CommandContext ctx, String msg) { ctx.getSource().sendSuccess(() -> Component.literal(msg), false); } private static void fail(CommandContext ctx, String msg) { ctx.getSource().sendFailure(Component.literal(msg)); } private ClaimCommands() {} }