Volver al índice

src/main/java/ar/com/companeros/social/ChatRepeatGuard.java

package ar.com.companeros.social;

import java.text.Normalizer;
import java.util.*;

/** Historial breve de envíos reales; no depende del modelo ni de servicios externos. */
public final class ChatRepeatGuard {
    private static final long WINDOW_TICKS = 1800;
    private record Key(UUID sender, String channel, String recipient) { }
    private record Sent(long tick, String normalized, Set<String> words) { }
    private final Map<Key, ArrayDeque<Sent>> history = new LinkedHashMap<>();
    private static final Set<String> STOP = Set.of("el","la","los","las","de","en","un","una","para","por","con","y","a","que","si","me","te","se","mi","tu","sus","su");

    // Comparar texto y contenido: pequeños cambios de puntuación no convierten una repetición en novedad.
    public boolean duplicate(UUID sender, String channel, String recipient, String text, long tick) {
        var sent = history.get(new Key(sender, channel, recipient.toLowerCase(Locale.ROOT)));
        if (sent == null) return false;
        String normalized = normalize(text); Set<String> words = words(normalized);
        sent.removeIf(previous -> tick < previous.tick() || tick - previous.tick() >= WINDOW_TICKS);
        for (Sent previous : sent) {
            if (normalized.equals(previous.normalized())) return true;
            // Coordenadas, cantidades y niveles distintos sí cambian el mensaje.
            if (!numbers(normalized).equals(numbers(previous.normalized()))) continue;
            if (words.size() < 4 || previous.words().size() < 4) continue;
            Set<String> union = new HashSet<>(words); union.addAll(previous.words());
            Set<String> common = new HashSet<>(words); common.retainAll(previous.words());
            if ((double) common.size() / union.size() >= .8) return true;
        }
        return false;
    }

    // Sólo un envío confirmado entra al historial. Rechazos y cooldowns no simulan mensajes enviados.
    public void record(UUID sender, String channel, String recipient, String text, long tick) {
        Key key = new Key(sender, channel, recipient.toLowerCase(Locale.ROOT));
        if (!history.containsKey(key) && history.size() >= 1024) history.remove(history.keySet().iterator().next());
        var sent = history.computeIfAbsent(key, ignored -> new ArrayDeque<>());
        String normalized = normalize(text);
        sent.addLast(new Sent(tick, normalized, words(normalized)));
        while (sent.size() > 8) sent.removeFirst();
    }
    private static String normalize(String text) {
        return Normalizer.normalize(text, Normalizer.Form.NFKC).toLowerCase(Locale.ROOT)
            .replaceAll("[^\\p{L}\\p{N}+-]+", " ").strip();
    }
    private static Set<String> words(String text) {
        Set<String> words = new HashSet<>(Arrays.asList(text.split(" +")));
        words.removeAll(STOP); return Set.copyOf(words);
    }
    private static List<String> numbers(String text) {
        return java.util.regex.Pattern.compile("[+-]?\\d+").matcher(text).results().map(java.util.regex.MatchResult::group).toList();
    }
}