GastinelClaims 1.1.1 : pseudos avec caractere non tapable (guillemet) vises sans ce caractere, ambiguite annoncee

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Cette révision appartient à :
Theo GastineletClaude Sonnet 5.5 a révisé 2026-10-11 00:23:22 +02:00
1 Parent 4fff64919e
révision 1e2f116b6f
6 fichiers modifiés
+336 -24

Aucun fichier ne correspond à votre recherche

+86 -21
Voir le fichier
@@ -2,6 +2,11 @@ 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;
@@ -16,6 +21,9 @@ 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;
@@ -39,11 +47,11 @@ public final class ClaimCommands {
.then(Commands.literal("add")
.then(Commands.argument("pseudo", StringArgumentType.word())
.suggests((ctx, b) -> SharedSuggestionProvider.suggest(
ctx.getSource().getServer().getPlayerNames(), b))
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(friendNames(ctx), b))
.suggests((ctx, b) -> SharedSuggestionProvider.suggest(PseudoMatcher.suggestions(friendNames(ctx)), b))
.executes(ctx -> removeFriend(ctx, StringArgumentType.getString(ctx, "pseudo"))))));
}
@@ -117,20 +125,31 @@ public final class ClaimCommands {
private static int addFriend(CommandContext<CommandSourceStack> ctx, String name) throws CommandSyntaxException {
ServerPlayer p = ctx.getSource().getPlayerOrException();
Optional<GameProfile> target = resolve(p.server, name);
if (target.isEmpty()) {
fail(ctx, "Joueur inconnu du serveur : " + name + ".");
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<GameProfile> 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.get().getId())) {
switch (data.registry().addFriend(p.getUUID(), target.id())) {
case OK -> {
data.setDirty();
ok(ctx, target.get().getName() + " a maintenant accès à tous tes claims.");
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.get().getName() + " est déjà ton ami.");
case ALREADY -> fail(ctx, target.nom() + " est déjà ton ami.");
default -> { }
}
return 0;
@@ -140,30 +159,76 @@ public final class ClaimCommands {
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)
UUID friend = null;
for (UUID u : data.registry().friendsOf(p.getUUID())) {
if (nameOf(p.server, u).equalsIgnoreCase(name)) { friend = u; break; }
List<Profil> 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;
}
if (friend == null) {
friend = resolve(p.server, name).map(GameProfile::getId).orElse(null);
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, name + " n'est pas dans ta liste d'amis.");
fail(ctx, affiche + " n'est pas dans ta liste d'amis.");
return 0;
}
data.setDirty();
ok(ctx, name + " n'a plus accès à tes claims.");
ok(ctx, affiche + " n'a plus accès à tes claims.");
return 1;
}
// --- Utilitaires ---
/** Pseudo -> profil : joueur en ligne, sinon cache de profils du serveur (joueurs déjà venus). */
private static Optional<GameProfile> resolve(MinecraftServer server, String name) {
ServerPlayer online = server.getPlayerList().getPlayerByName(name);
if (online != null) return Optional.of(online.getGameProfile());
if (server.getProfileCache() == null) return Optional.empty();
return server.getProfileCache().get(name);
/**
* 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<Profil> 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<Profil> profilsDuCache(MinecraftServer server) {
List<Profil> 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) {
+123
Voir le fichier
@@ -0,0 +1,123 @@
package com.gastinelclaims.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Résolution tolérante d'un pseudo tapé en commande (logique pure, sans Minecraft).
*
* Problème : un pseudo hors-ligne peut contenir des caractères qu'un argument {@code word()} ne sait pas
* taper (ex. {@code gabybou201"}). Règle : on compare d'abord le pseudo exact (sans tenir compte de la casse),
* puis les formes normalisées (minuscules, tout ce qui n'est pas [A-Za-z0-9_] retiré).
* Sécurité : si la forme normalisée correspond à PLUSIEURS comptes différents (UUID différents), on ne choisit
* jamais : le résultat est AMBIGU et la liste des candidats est annoncée. L'UUID retenu est toujours celui du
* vrai profil trouvé, jamais un UUID recalculé à partir du texte tapé.
*
* Ordre : joueurs en ligne d'abord ; le cache de profils (usercache) n'est consulté que si aucun joueur en ligne
* ne correspond.
*/
public final class PseudoMatcher {
public record Profil(UUID id, String nom) { }
public enum Statut { TROUVE, AMBIGU, INCONNU }
/** approximatif : vrai si le pseudo tapé diffère du vrai pseudo (match par forme normalisée). */
public record Resultat(Statut statut, Profil profil, List<Profil> candidats, boolean approximatif) {
public boolean trouve() { return statut == Statut.TROUVE; }
}
private static final Resultat INCONNU = new Resultat(Statut.INCONNU, null, List.of(), false);
/** Minuscules, caractères hors [A-Za-z0-9_] retirés. */
public static String normaliser(String s) {
if (s == null) return "";
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_') sb.append(c);
else if (c >= 'A' && c <= 'Z') sb.append((char) (c + 32));
}
return sb.toString();
}
/** Forme tapable dans un argument word() de Brigadier : [0-9A-Za-z_.+-] seulement. */
public static String tapable(String nom) {
if (nom == null) return "";
StringBuilder sb = new StringBuilder(nom.length());
for (int i = 0; i < nom.length(); i++) {
char c = nom.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
|| c == '_' || c == '.' || c == '+' || c == '-') sb.append(c);
}
return sb.toString();
}
/** Suggestions (tab) : formes tapables, sans doublon, ordre conservé, sans entrée vide. */
public static List<String> suggestions(Collection<String> noms) {
LinkedHashSet<String> out = new LinkedHashSet<>();
for (String n : noms) {
String t = tapable(n);
if (!t.isEmpty()) out.add(t);
}
return new ArrayList<>(out);
}
/** Un seul groupe de profils (ex. les joueurs en ligne, ou les amis). */
public static Resultat resoudreParmi(String saisie, Collection<Profil> profils) {
return resoudre(saisie, profils, List.of());
}
public static Resultat resoudre(String saisie, Collection<Profil> enLigne, Collection<Profil> cache) {
if (saisie == null || saisie.isEmpty()) return INCONNU;
Resultat r = etape(saisie, dedoublonner(enLigne), false);
if (r.statut() != Statut.INCONNU) return r;
return etape(saisie, dedoublonner(cache), true);
}
/**
* strict (cache) : un pseudo exact qui partage sa forme normalisée avec un AUTRE compte reste AMBIGU
* (profils fantômes d'anciens essais) : on ne désigne pas un compte au hasard.
*/
private static Resultat etape(String saisie, List<Profil> profils, boolean strict) {
List<Profil> exacts = new ArrayList<>();
for (Profil p : profils) if (p.nom().equalsIgnoreCase(saisie)) exacts.add(p);
String norm = normaliser(saisie);
List<Profil> proches = new ArrayList<>();
if (!norm.isEmpty()) for (Profil p : profils) if (normaliser(p.nom()).equals(norm)) proches.add(p);
if (exacts.size() == 1 && (!strict || proches.size() <= 1)) {
return new Resultat(Statut.TROUVE, exacts.get(0), List.of(exacts.get(0)), false);
}
if (!exacts.isEmpty()) {
// plusieurs exacts (casse différente) ou exact + comptes proches dans le cache : jamais au hasard
return new Resultat(Statut.AMBIGU, null, List.copyOf(strict ? proches : exacts), false);
}
if (proches.size() == 1) return new Resultat(Statut.TROUVE, proches.get(0), proches, true);
if (proches.size() > 1) return new Resultat(Statut.AMBIGU, null, List.copyOf(proches), true);
return INCONNU;
}
private static List<Profil> dedoublonner(Collection<Profil> profils) {
Map<UUID, Profil> m = new LinkedHashMap<>();
for (Profil p : profils) if (p != null && p.id() != null && p.nom() != null) m.putIfAbsent(p.id(), p);
return new ArrayList<>(m.values());
}
/** Message clair listant les candidats (vrais pseudos). */
public static String messageAmbigu(String saisie, List<Profil> candidats) {
StringBuilder sb = new StringBuilder("Plusieurs joueurs ressemblent à « ").append(saisie).append(" » : ");
for (int i = 0; i < candidats.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(candidats.get(i).nom());
}
return sb.append(". Je ne choisis pas à ta place : fais-le te rejoindre en ligne, ou tape le pseudo exact.").toString();
}
private PseudoMatcher() { }
}
+1 -1
Voir le fichier
@@ -4,7 +4,7 @@ license="MIT"
[[mods]]
modId="gastinelclaims"
version="1.1.0"
version="1.1.1"
displayName="GastinelClaims"
authors="Théo Gastinel"
description='''Protection de terrains par chunk (/claim, /unclaim, /friend) et zones protégées (spawn incassable, /zoneprotegee). Mod côté serveur uniquement.'''