diff --git a/AdvancedCore/src/main/java/com/bencodez/advancedcore/AdvancedCoreConfigOptions.java b/AdvancedCore/src/main/java/com/bencodez/advancedcore/AdvancedCoreConfigOptions.java index 1d111df9ce..5fdd22e544 100644 --- a/AdvancedCore/src/main/java/com/bencodez/advancedcore/AdvancedCoreConfigOptions.java +++ b/AdvancedCore/src/main/java/com/bencodez/advancedcore/AdvancedCoreConfigOptions.java @@ -3,11 +3,10 @@ import java.util.ArrayList; import java.util.concurrent.TimeUnit; -import org.bukkit.NamespacedKey; -import org.bukkit.Registry; import org.bukkit.Sound; import org.bukkit.configuration.ConfigurationSection; +import com.bencodez.advancedcore.api.misc.SoundResolver; import com.bencodez.advancedcore.api.user.UserStorage; import com.bencodez.simpleapi.debug.DebugLevel; import com.bencodez.simpleapi.file.YMLConfig; @@ -664,19 +663,9 @@ public AdvancedCoreConfigOptions() { * * @return The Sound object for click sound, or null if set to "none" */ - public Sound getClickSoundSound() { - - if (getClickSoundSoundStr().equalsIgnoreCase("none")) { - return null; - } - try { - return Registry.SOUNDS - .get(NamespacedKey.minecraft(getClickSoundSoundStr().replaceAll("_", ".").toLowerCase())); - } catch (Exception e) { - e.printStackTrace(); - return Registry.SOUNDS.get(NamespacedKey.minecraft("ui.button.click")); - } - } + public Sound getClickSoundSound() { + return SoundResolver.resolveClickSound(getClickSoundSoundStr()); + } /** * Loads configuration options from the YML configuration file. diff --git a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/misc/SoundResolver.java b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/misc/SoundResolver.java new file mode 100644 index 0000000000..4eff9d912e --- /dev/null +++ b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/misc/SoundResolver.java @@ -0,0 +1,85 @@ +package com.bencodez.advancedcore.api.misc; + +import java.util.Locale; + +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.Sound; + +/** Resolves configured sound keys without relying on registry objects' debug text. */ +public final class SoundResolver { + private SoundResolver() { + } + + /** Accepts canonical keys, namespaced keys and legacy Minecraft enum-style names. */ + public static Sound resolve(String input) { + return resolve(input, Registry.SOUNDS); + } + + static Sound resolve(String input, Registry registry) { + if (input == null || input.isBlank()) { + return null; + } + String name = input.trim(); + NamespacedKey key = parseKey(name); + if (key == null) { + return null; + } + Sound exact = registry.get(key); + if (exact != null) { + return exact; + } + // Legacy names flatten dots, but underscores inside a key remain significant. + // Never reinterpret an explicitly namespaced key as an enum constant. + if (name.indexOf(':') < 0 && name.matches("[A-Za-z0-9_]+")) { + for (Sound sound : registry) { + NamespacedKey candidate = sound.getKey(); + if (NamespacedKey.MINECRAFT.equals(candidate.getNamespace()) + && candidate.getKey().replace('.', '_').equalsIgnoreCase(name)) { + return sound; + } + } + } + return null; + } + + /** Parses configuration input without propagating Bukkit's validation exceptions. */ + public static NamespacedKey parseKey(String input) { + if (input == null || input.isBlank()) { + return null; + } + try { + return NamespacedKey.fromString(input.trim().toLowerCase(Locale.ROOT)); + } catch (IllegalArgumentException ex) { + return null; + } + } + + /** Retains the GUI click option's historical mixed underscore/dot aliases. */ + public static Sound resolveClickSound(String input) { + if ("none".equalsIgnoreCase(input)) { + return null; + } + Sound sound = resolve(input); + if (sound != null) { + return sound; + } + if (parseKey(input) == null) { + return resolve("ui.button.click"); + } + // Explicit namespaced keys are exact, even if the registry has no match. + if (input.indexOf(':') >= 0) { + return null; + } + // This legacy transformation is click-only and bare-name-only; shared + // resolution above keeps underscores in keys such as block.note_block.chime. + NamespacedKey legacy = parseKey(input.replace('_', '.')); + return legacy == null ? resolve("ui.button.click") : Registry.SOUNDS.get(legacy); + } + + /** A stable value suitable for configuration and the reward editor. */ + public static String configurationKey(Sound sound) { + NamespacedKey key = sound.getKey(); + return NamespacedKey.MINECRAFT.equals(key.getNamespace()) ? key.getKey() : key.toString(); + } +} diff --git a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/rewards/editbuttons/RewardEditSound.java b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/rewards/editbuttons/RewardEditSound.java index b7d02d2d9f..d34f27b9c0 100644 --- a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/rewards/editbuttons/RewardEditSound.java +++ b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/rewards/editbuttons/RewardEditSound.java @@ -6,6 +6,7 @@ import org.bukkit.entity.Player; import com.bencodez.advancedcore.api.inventory.editgui.EditGUI; +import com.bencodez.advancedcore.api.misc.SoundResolver; import com.bencodez.advancedcore.api.rewards.RewardEditData; import com.bencodez.simpleapi.array.ArrayUtils; @@ -21,7 +22,7 @@ public void open(Player player, RewardEditData reward) { inv.addButton(getBooleanButton("Sound.Enabled", reward)); ArrayList sounds = new ArrayList<>(); - Registry.SOUNDS.forEach(sound -> sounds.add(sound.toString())); + Registry.SOUNDS.forEach(sound -> sounds.add(SoundResolver.configurationKey(sound))); inv.addButton(getStringButton("Sound.Sound", reward, ArrayUtils.convert(sounds))); inv.addButton(getDoubleButton("Sound.Volume", reward)); diff --git a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/user/AdvancedCoreUser.java b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/user/AdvancedCoreUser.java index d404b71fd5..8702d2e57b 100644 --- a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/user/AdvancedCoreUser.java +++ b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/user/AdvancedCoreUser.java @@ -27,10 +27,8 @@ import org.bukkit.Bukkit; import org.bukkit.Effect; -import org.bukkit.NamespacedKey; import org.bukkit.OfflinePlayer; import org.bukkit.Particle; -import org.bukkit.Registry; import org.bukkit.Sound; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.serialization.ConfigurationSerializable; @@ -41,6 +39,7 @@ import org.bukkit.potion.PotionEffectType; import com.bencodez.advancedcore.AdvancedCorePlugin; +import com.bencodez.advancedcore.api.misc.SoundResolver; import com.bencodez.advancedcore.api.item.ItemBuilder; import com.bencodez.advancedcore.api.messages.PlaceholderUtils; import com.bencodez.advancedcore.api.misc.PlayerManager; @@ -593,6 +592,7 @@ public static CompletionStage persistedReplayCompletion(AdvancedCorePlugin */ @Getter private AdvancedCorePlugin plugin = null; + private long lastInvalidSoundWarningAt; /** The uuid. */ private String uuid; @@ -2824,16 +2824,21 @@ public void playParticleEffect(String effectName, int data, int particles, int r public void playSound(String soundName, float volume, float pitch) { Player player = getPlayer(); if (player != null) { - Sound sound = null; - try { - sound = Registry.SOUNDS.get(NamespacedKey.minecraft(soundName)); - } catch (Exception e) { - plugin.debug(e); - } + Sound sound = SoundResolver.resolve(soundName); if (sound != null) { player.playSound(player.getLocation(), sound, volume, pitch); } else { - plugin.debug("Invalid sound: " + soundName); + // Bound both diagnostic size and repeated warnings for this user. + synchronized (this) { + long now = System.currentTimeMillis(); + if (now - lastInvalidSoundWarningAt >= 30_000L) { + lastInvalidSoundWarningAt = now; + String value = String.valueOf(soundName); + value = value.substring(0, Math.min(value.length(), 128)).replaceAll("[\\p{Cntrl}]", "?"); + plugin.getLogger().warning("Invalid reward sound: " + value + + ". Use a registry key such as entity.player.levelup (warnings limited to one per 30s per user)."); + } + } } } } diff --git a/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/sound/SoundResolutionFixture.java b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/sound/SoundResolutionFixture.java new file mode 100644 index 0000000000..aaeb363600 --- /dev/null +++ b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/sound/SoundResolutionFixture.java @@ -0,0 +1,233 @@ +package com.bencodez.advancedcore.tests.sound; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.lang.reflect.Method; +import java.util.List; +import java.util.logging.Logger; + +import org.bukkit.Bukkit; +import org.bukkit.Keyed; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import com.bencodez.advancedcore.AdvancedCoreConfigOptions; +import com.bencodez.advancedcore.AdvancedCorePlugin; +import com.bencodez.advancedcore.api.misc.SoundResolver; +import com.bencodez.advancedcore.api.user.AdvancedCoreUser; + +public class SoundResolutionFixture { + private Registry registry; + private Sound levelup; + private Sound chime; + private Sound custom; + private Method resolve; + + // The real API initializes all registry constants through Bukkit. Supply a + // synthetic server registry only during that initialization; no server is run. + @BeforeAll + static void initializeRegistry() throws Exception { + try (MockedStatic bukkit = mockStatic(Bukkit.class)) { + bukkit.when(() -> Bukkit.getRegistry(any())).thenAnswer(call -> new EmptyRegistry<>()); + Class.forName("org.bukkit.Registry"); + } + } + + private static final class EmptyRegistry implements Registry { + public T get(NamespacedKey key) { return entries.stream().filter(e -> e.getKey().equals(key)).findFirst().orElse(null); } + public T getOrThrow(NamespacedKey key) { return null; } + public java.util.stream.Stream stream() { return java.util.stream.Stream.empty(); } + private List entries = List.of(); + public java.util.Iterator iterator() { return entries.iterator(); } + } + + @SuppressWarnings("unchecked") + @BeforeEach + void setup() throws Exception { + registry = mock(Registry.class); + levelup = sound("minecraft:entity.player.levelup"); + chime = sound("minecraft:block.note_block.chime"); + custom = sound("example:custom.note_block"); + when(registry.iterator()).thenAnswer(ignored -> List.of(levelup, chime, custom).iterator()); + when(registry.get(any())).thenAnswer(call -> { + NamespacedKey key = call.getArgument(0); + return List.of(levelup, chime, custom).stream().filter(s -> s.getKey().equals(key)).findFirst().orElse(null); + }); + resolve = SoundResolver.class.getDeclaredMethod("resolve", String.class, Registry.class); + resolve.setAccessible(true); + } + + private Sound sound(String key) { + Sound sound = mock(Sound.class); + when(sound.getKey()).thenReturn(NamespacedKey.fromString(key)); + when(sound.toString()).thenReturn("CraftSound{holder=synthetic-debug-text}"); + return sound; + } + + private Sound resolve(String name) throws Exception { + return (Sound) resolve.invoke(null, name, registry); + } + + @Test void editorKeysIgnoreRegistryDebugTextAndRoundTrip() throws Exception { + assertEquals("block.note_block.chime", SoundResolver.configurationKey(chime)); + assertEquals("example:custom.note_block", SoundResolver.configurationKey(custom)); + for (Sound sound : List.of(levelup, chime, custom)) { + assertSame(sound, resolve(SoundResolver.configurationKey(sound))); + } + } + + @Test void actualEditorOffersStableKeysInsteadOfDebugStrings() { + var reward = mock(com.bencodez.advancedcore.api.rewards.RewardEditData.class); + var editor = mock(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditSound.class, CALLS_REAL_METHODS); + doReturn(null).when(editor).getBooleanButton(anyString(), any()); + doReturn(null).when(editor).getDoubleButton(anyString(), any()); + doReturn(null).when(editor).getBackButton(any()); + doReturn(null).when(editor).getStringButton(anyString(), any(), any(String[].class)); + @SuppressWarnings("unchecked") + var sounds = (EmptyRegistry) Registry.SOUNDS; + sounds.entries = List.of(chime, custom); + try (var gui = mockConstruction(com.bencodez.advancedcore.api.inventory.editgui.EditGUI.class)) { + editor.open(mock(Player.class), reward); + verify(editor).getStringButton("Sound.Sound", reward, + new String[] {"block.note_block.chime", "example:custom.note_block"}); + } finally { + sounds.entries = List.of(); + } + } + + @Test void canonicalNamespacedAndLegacyInputsResolve() throws Exception { + for (String name : List.of("entity.player.levelup", "minecraft:entity.player.levelup", "ENTITY_PLAYER_LEVELUP")) { + assertSame(levelup, resolve(name)); + } + for (String name : List.of("block.note_block.chime", "minecraft:block.note_block.chime", "BLOCK_NOTE_BLOCK_CHIME")) { + assertSame(chime, resolve(name)); + } + assertSame(custom, resolve("example:custom.note_block")); + } + + @Test void invalidAndUnrelatedNamesDoNotInventRegistryEntries() throws Exception { + for (String name : new String[] {null, "", " ", "unknown", "bad:key:extra", "bad sound", "CraftSound{holder=debug}", + "minecraft:BLOCK_NOTE_BLOCK_CHIME", "example:BLOCK_NOTE_BLOCK_CHIME", "CUSTOM_NOTE_BLOCK", "block.note.block.chime", "a".repeat(300), "minecraft:" + "a".repeat(300)}) { + assertNull(assertDoesNotThrow(() -> resolve(name)), String.valueOf(name)); + } + } + + @Test void playbackPreservesLocationVolumePitchAndOfflineNoop() throws Exception { + AdvancedCoreUser user = mock(AdvancedCoreUser.class, CALLS_REAL_METHODS); + var pluginField = AdvancedCoreUser.class.getDeclaredField("plugin"); + pluginField.setAccessible(true); + pluginField.set(user, mock(AdvancedCorePlugin.class)); + Player player = mock(Player.class); + Location location = mock(Location.class); + doReturn(player).when(user).getPlayer(); + when(player.getLocation()).thenReturn(location); + try (MockedStatic resolver = mockStatic(SoundResolver.class)) { + resolver.when(() -> SoundResolver.resolve("BLOCK_NOTE_BLOCK_CHIME")).thenReturn(chime); + user.playSound("BLOCK_NOTE_BLOCK_CHIME", 0.4f, 1.6f); + verify(player).playSound(location, chime, 0.4f, 1.6f); + doReturn(null).when(user).getPlayer(); + user.playSound("offline", 1f, 1f); + resolver.verify(() -> SoundResolver.resolve("offline"), never()); + } + } + + @Test void invalidRewardWarnsNormallyWithBoundedTextAndRepetition() throws Exception { + AdvancedCoreUser user = mock(AdvancedCoreUser.class, CALLS_REAL_METHODS); + doReturn(mock(Player.class)).when(user).getPlayer(); + AdvancedCorePlugin plugin = mock(AdvancedCorePlugin.class); + Logger logger = mock(Logger.class); + when(plugin.getLogger()).thenReturn(logger); + var field = AdvancedCoreUser.class.getDeclaredField("plugin"); + field.setAccessible(true); + field.set(user, plugin); + assertDoesNotThrow(() -> user.playSound("x".repeat(500), 1f, 1f)); + user.playSound(null, 1f, 1f); + var lastWarning = AdvancedCoreUser.class.getDeclaredField("lastInvalidSoundWarningAt"); + lastWarning.setAccessible(true); + lastWarning.setLong(user, 0L); + user.playSound("bad\nsound", 1f, 1f); + var warning = org.mockito.ArgumentCaptor.forClass(String.class); + verify(logger, times(2)).warning(warning.capture()); + for (String message : warning.getAllValues()) { + assertTrue(message.contains("Invalid reward sound:")); + assertFalse(message.contains("\n")); + assertTrue(message.length() < 300); + } + } + + @Test void namespacedClickKeysNeverUseLegacyRewrite() { + @SuppressWarnings("unchecked") + var sounds = (EmptyRegistry) Registry.SOUNDS; + Sound click = sound("minecraft:ui.button.click"); + Sound dottedNamespace = sound("example.sounds:ui.button.click"); + Sound exactUnderscore = sound("example_sounds:custom_note"); + sounds.entries = List.of(click, dottedNamespace, exactUnderscore); + try { + AdvancedCoreConfigOptions options = mock(AdvancedCoreConfigOptions.class, CALLS_REAL_METHODS); + assertAll( + () -> { + when(options.getClickSoundSoundStr()).thenReturn("minecraft:ui_button.click"); + assertNull(options.getClickSoundSound()); + }, + () -> { + when(options.getClickSoundSoundStr()).thenReturn("example_sounds:ui_button.click"); + assertNull(options.getClickSoundSound()); + }, + () -> { + when(options.getClickSoundSoundStr()).thenReturn("example.sounds:ui.button.click"); + assertSame(dottedNamespace, options.getClickSoundSound()); + }, + () -> { + when(options.getClickSoundSoundStr()).thenReturn("example_sounds:custom_note"); + assertSame(exactUnderscore, options.getClickSoundSound()); + }); + } finally { sounds.entries = List.of(); } + } + + @Test void mixedLegacyClickAliasRemainsSupported() { + @SuppressWarnings("unchecked") + var sounds = (EmptyRegistry) Registry.SOUNDS; + Sound click = sound("minecraft:ui.button.click"); + sounds.entries = List.of(click); + try { + AdvancedCoreConfigOptions options = mock(AdvancedCoreConfigOptions.class, CALLS_REAL_METHODS); + when(options.getClickSoundSoundStr()).thenReturn("UI_BUTTON.CLICK"); + assertSame(click, options.getClickSoundSound()); + } finally { sounds.entries = List.of(); } + } + + @Test void clickSoundUsesSameResolverAndRetainsNoneAndFallback() { + @SuppressWarnings("unchecked") + var sounds = (EmptyRegistry) Registry.SOUNDS; + Sound click = sound("minecraft:ui.button.click"); + sounds.entries = List.of(chime, levelup, click); + try { + // Use the actual Spigot parser and shared resolver, not static stubs. + AdvancedCoreConfigOptions options = mock(AdvancedCoreConfigOptions.class, CALLS_REAL_METHODS); + for (String invalid : new String[] {null, "", " ", "a".repeat(300), "bad:key:extra"}) { + when(options.getClickSoundSoundStr()).thenReturn(invalid); + assertSame(click, assertDoesNotThrow(options::getClickSoundSound), String.valueOf(invalid)); + } + for (String valid : List.of("BLOCK_NOTE_BLOCK_CHIME", "block.note_block.chime", "minecraft:block.note_block.chime")) { + when(options.getClickSoundSoundStr()).thenReturn(valid); + assertSame(chime, options.getClickSoundSound()); + } + when(options.getClickSoundSoundStr()).thenReturn("none"); + assertNull(options.getClickSoundSound()); + when(options.getClickSoundSoundStr()).thenReturn("unknown.valid"); + assertNull(options.getClickSoundSound()); + when(options.getClickSoundSoundStr()).thenReturn("UI_BUTTON.CLICK"); + assertSame(click, options.getClickSoundSound()); + } finally { + sounds.entries = List.of(); + } + } +} diff --git a/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/sound/SoundResolutionTest.java b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/sound/SoundResolutionTest.java new file mode 100644 index 0000000000..bebf212345 --- /dev/null +++ b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/sound/SoundResolutionTest.java @@ -0,0 +1,63 @@ +package com.bencodez.advancedcore.tests.sound; + +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Arrays; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** Keep the synthetic Bukkit/Registry/Sound bootstrap out of the shared test loader. */ +class SoundResolutionTest { + private static URLClassLoader isolated; + private static Class fixture; + + @BeforeAll + static void isolateRegistryBootstrap() throws Throwable { + URL[] urls = Arrays.stream(System.getProperty("surefire.test.class.path").split(File.pathSeparator)) + .map(path -> { + try { return new File(path).toURI().toURL(); } + catch (java.net.MalformedURLException ex) { throw new IllegalArgumentException(ex); } + }).toArray(URL[]::new); + isolated = new URLClassLoader(urls, ClassLoader.getPlatformClassLoader()); + fixture = Class.forName("com.bencodez.advancedcore.tests.sound.SoundResolutionFixture", true, isolated); + assertNotSame(SoundResolutionTest.class.getClassLoader(), fixture.getClassLoader()); + invoke(null, "initializeRegistry"); + assertSame(isolated, Class.forName("org.bukkit.Registry", false, isolated).getClassLoader()); + assertSame(isolated, Class.forName("org.bukkit.Sound", false, isolated).getClassLoader()); + } + + @AfterAll + static void closeIsolatedLoader() throws Exception { + if (isolated != null) { isolated.close(); } + } + + private static void invoke(Object target, String method) throws Throwable { + var call = fixture.getDeclaredMethod(method); + call.setAccessible(true); + try { call.invoke(target); } + catch (InvocationTargetException ex) { throw ex.getCause(); } + } + + private void check(String method) throws Throwable { + Object instance = fixture.getDeclaredConstructor().newInstance(); + invoke(instance, "setup"); + invoke(instance, method); + } + + @Test void editorKeysIgnoreRegistryDebugTextAndRoundTrip() throws Throwable { check("editorKeysIgnoreRegistryDebugTextAndRoundTrip"); } + @Test void actualEditorOffersStableKeysInsteadOfDebugStrings() throws Throwable { check("actualEditorOffersStableKeysInsteadOfDebugStrings"); } + @Test void canonicalNamespacedAndLegacyInputsResolve() throws Throwable { check("canonicalNamespacedAndLegacyInputsResolve"); } + @Test void invalidAndUnrelatedNamesDoNotInventRegistryEntries() throws Throwable { check("invalidAndUnrelatedNamesDoNotInventRegistryEntries"); } + @Test void playbackPreservesLocationVolumePitchAndOfflineNoop() throws Throwable { check("playbackPreservesLocationVolumePitchAndOfflineNoop"); } + @Test void invalidRewardWarnsNormallyWithBoundedTextAndRepetition() throws Throwable { check("invalidRewardWarnsNormallyWithBoundedTextAndRepetition"); } + @Test void namespacedClickKeysNeverUseLegacyRewrite() throws Throwable { check("namespacedClickKeysNeverUseLegacyRewrite"); } + @Test void mixedLegacyClickAliasRemainsSupported() throws Throwable { check("mixedLegacyClickAliasRemainsSupported"); } + @Test void clickSoundUsesSameResolverAndRetainsNoneAndFallback() throws Throwable { check("clickSoundUsesSameResolverAndRetainsNoneAndFallback"); } +}