From f20dc859a8221781e79c90572cf71a982437f946 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 14 Nov 2026 12:15:32 -0800 Subject: [PATCH 1/2] Make Web Library import replace existing challenges The Library asks the admin to confirm that the current challenges will be replaced, but the import was then refused with "Challenges already exist in your world" whenever the game mode had any. Importing a database file or a template already wipes and replaces. Wipe the game mode's challenges and levels before loading the download, once the download has parsed, so a broken download cannot leave the world empty. Player data is kept. Remove the now unused exist-challenges-or-levels locale key. Co-Authored-By: Claude Fable 5.2 --- .../managers/ChallengesImportManager.java | 31 +++++++++---------- src/main/resources/locales/cs.yml | 1 - src/main/resources/locales/de.yml | 1 - src/main/resources/locales/en-US.yml | 1 - src/main/resources/locales/es.yml | 1 - src/main/resources/locales/fr.yml | 1 - src/main/resources/locales/hu.yml | 1 - src/main/resources/locales/ja.yml | 1 - src/main/resources/locales/lv.yml | 1 - src/main/resources/locales/pl.yml | 1 - src/main/resources/locales/pt.yml | 1 - src/main/resources/locales/ru.yml | 1 - src/main/resources/locales/uk.yml | 1 - src/main/resources/locales/zh-CN.yml | 1 - src/main/resources/locales/zh-HK.yml | 1 - src/main/resources/locales/zh-TW.yml | 1 - .../managers/ChallengesImportManagerTest.java | 24 +++++++++----- 17 files changed, 31 insertions(+), 39 deletions(-) diff --git a/src/main/java/world/bentobox/challenges/managers/ChallengesImportManager.java b/src/main/java/world/bentobox/challenges/managers/ChallengesImportManager.java index 39de7c3f..b12d5568 100644 --- a/src/main/java/world/bentobox/challenges/managers/ChallengesImportManager.java +++ b/src/main/java/world/bentobox/challenges/managers/ChallengesImportManager.java @@ -761,7 +761,8 @@ private void reportImportFailure(User user, World world, Exception e) /** - * This method loads downloaded challenges into memory. + * This method loads downloaded challenges into memory. Any challenges and levels that the + * game mode already has are replaced, the same as for file imports. Player data is kept. * @param user User who calls downloaded challenge loading * @param world Target world. * @param downloadString String that need to be loaded via DefaultDataHolder. @@ -778,21 +779,6 @@ public void loadDownloadedChallenges(User user, World world, String downloadStri ChallengesManager manager = this.addon.getChallengesManager(); - // If exist any challenge or level that is bound to current world, then do not load default challenges. - if (manager.hasAnyChallengeData(world.getName())) - { - if (user.isPlayer()) - { - Utils.sendMessage(user, world, Constants.ERRORS + "exist-challenges-or-levels"); - } - else - { - this.addon.logWarning("challenges.errors.exist-challenges-or-levels"); - } - - return; - } - try { // This prefix will be used to all challenges. That is a unique way how to separate challenged for @@ -800,6 +786,19 @@ public void loadDownloadedChallenges(User user, World world, String downloadStri String uniqueIDPrefix = Utils.getGameMode(world).toLowerCase() + "_"; DefaultDataHolder downloadedChallenges = new DefaultJSONHandler(this.addon).loadWebObject(downloadString); + if (downloadedChallenges == null) + { + return; + } + + // The admin has confirmed that the current challenges should be replaced. Wipe them only + // now that the download has parsed, so a broken download cannot leave the world empty. + if (manager.hasAnyChallengeData(world.getName())) + { + this.addon.getPlugin().getIWM().getAddon(world).ifPresent(gameModeAddon -> + manager.wipeDatabase(gameModeAddon.getDescription().getName().toLowerCase())); + } + // All new challenges should get correct ID. So we need to map it to loaded challenges. downloadedChallenges.getChallengeList().forEach(challenge -> { // Set correct challenge ID diff --git a/src/main/resources/locales/cs.yml b/src/main/resources/locales/cs.yml index 66b25c80..33f7e73e 100644 --- a/src/main/resources/locales/cs.yml +++ b/src/main/resources/locales/cs.yml @@ -1233,7 +1233,6 @@ challenges: load-error: "Chyba: Nelze načíst [value]." no-rank: "Na toto nemáš hodnost." cannot-remove-items: "Některé předměty nelze odebrat z tvého inventáře!" - exist-challenges-or-levels: "Ve tvém světě již existují výzvy. Nelze pokračovat!" no-challenges: "Výzvy nejsou v aktuálním světě implementovány!" no-challenges-admin: "Výzvy nejsou v aktuálním světě implementovány! Měl bys použít /[command] k jejich přidání!" missing-arguments: "Příkaz postrádá argumenty." diff --git a/src/main/resources/locales/de.yml b/src/main/resources/locales/de.yml index ea0e7f47..078813b1 100644 --- a/src/main/resources/locales/de.yml +++ b/src/main/resources/locales/de.yml @@ -1224,7 +1224,6 @@ challenges: load-error: "Fehler: [value] kann nicht geladen werden." no-rank: "Du hast keinen Rang, der hoch genug ist, um das zu tun." cannot-remove-items: "Einige Items können nicht aus deinem Inventar entfernt werden!" - exist-challenges-or-levels: "Die Herausforderung existiert bereits in deiner Welt. Kann nicht fortfahren!" no-challenges: "Die Herausforderungen sind in dieser Welt noch nicht implementiert!" no-challenges-admin: "Die Herausforderungen sind in dieser Welt noch nicht implementiert! Verwende /[command] um sie hinzuzufügen!" missing-arguments: "Dem Befehl fehlen Argumente." diff --git a/src/main/resources/locales/en-US.yml b/src/main/resources/locales/en-US.yml index 5d9613b5..d1682767 100755 --- a/src/main/resources/locales/en-US.yml +++ b/src/main/resources/locales/en-US.yml @@ -1343,7 +1343,6 @@ challenges: import-failed: "Could not import challenges: [message]. Check the server console for details." no-rank: "You do not have a high enough rank to do that." cannot-remove-items: "Some items cannot be removed from your inventory!" - exist-challenges-or-levels: "Challenges already exist in your world. Cannot proceed!" no-challenges: "Challenges are not implemented in this world yet!" no-challenges-admin: "Challenges are not implemented in this world yet! Use /[command] to add them!" missing-arguments: "The command is missing arguments." diff --git a/src/main/resources/locales/es.yml b/src/main/resources/locales/es.yml index ec7f8c99..ba16bb5d 100755 --- a/src/main/resources/locales/es.yml +++ b/src/main/resources/locales/es.yml @@ -1242,7 +1242,6 @@ challenges: load-error: "Error: No se pudo cargar [value]." no-rank: "No tienes un rango lo suficientemente alto como para hacer eso." cannot-remove-items: "¡Algunos items no se pueden eliminar de tu inventario!" - exist-challenges-or-levels: "Los desafíos ya existen en tu mundo. ¡No se puede proceder!" no-challenges: "¡Los desafíos aún no se han implementado en este mundo!" no-challenges-admin: "¡Los desafíos aún no se han implementado en este mundo! ¡Usa /[command] para agregarlos!" missing-arguments: "Faltan argumentos de comando." diff --git a/src/main/resources/locales/fr.yml b/src/main/resources/locales/fr.yml index 8ddb7594..fe92bc97 100644 --- a/src/main/resources/locales/fr.yml +++ b/src/main/resources/locales/fr.yml @@ -1234,7 +1234,6 @@ challenges: load-error: "Erreur: Impossible de charger [value]." no-rank: "Vous n'avez pas un rang assez élevé pour faire cela." cannot-remove-items: "Certains objets ne peuvent pas être supprimés de votre inventaire !" - exist-challenges-or-levels: "Dans votre monde il existe déjà des challenges. Impossible de continuer !" no-challenges: "Les challenges ne sont pas actifs dans le monde actuel !" no-challenges-admin: "Les Challenges ne sont pas actifs dans le monde actuel ! Vous devez utiliser /[command] pour ajouter cela !" missing-arguments: "La commande n'a pas d'arguments." diff --git a/src/main/resources/locales/hu.yml b/src/main/resources/locales/hu.yml index d9701a5e..c90e3533 100644 --- a/src/main/resources/locales/hu.yml +++ b/src/main/resources/locales/hu.yml @@ -1235,7 +1235,6 @@ challenges: load-error: "Hiba: Nem lehet betölteni az [value] értéket." no-rank: "Nincs elég magas rangod ahhoz." cannot-remove-items: "Néhány elem nem távolítható el a készletből!" - exist-challenges-or-levels: "A világban már léteznek kihívások. Nem lehet folytatni!" no-challenges: "A kihívások még nem valósultak meg ezen a világon!" no-challenges-admin: "A kihívások még nem valósultak meg ezen a világon! Használja a /[command] billentyűket a hozzáadásukhoz!" missing-arguments: "A parancsból hiányoznak az argumentumok." diff --git a/src/main/resources/locales/ja.yml b/src/main/resources/locales/ja.yml index 3950496f..a9842764 100644 --- a/src/main/resources/locales/ja.yml +++ b/src/main/resources/locales/ja.yml @@ -1220,7 +1220,6 @@ challenges: load-error: &cエラー:[value]をロードできません。 no-rank: &cあなたにはそれをするランクがありません。 cannot-remove-items: &c一部のアイテムはインベントリから削除できません! - exist-challenges-or-levels: &c世界にはすでに課題が存在します。続行できません! no-challenges: &cチャレンジは現在の世界では実装されていません! no-challenges-admin: &cチャレンジは現在の世界では実装されていません!それらを追加するには&5 / [command]&cを使用する必要があります。 missing-arguments: &cコマンドに引数がありません。 diff --git a/src/main/resources/locales/lv.yml b/src/main/resources/locales/lv.yml index 2b7930be..871cbeab 100644 --- a/src/main/resources/locales/lv.yml +++ b/src/main/resources/locales/lv.yml @@ -1410,7 +1410,6 @@ challenges: load-error: 'Kļūda: Nevar ielādēt [value].' no-rank: "Tavs ranks nav pietiekoši augsts, lai veiktu šo darbību." cannot-remove-items: 'Dažus priekšmetus neizdevās izņemt no tava inventāra!' - exist-challenges-or-levels: 'Šajā pasaulē jau existē uzdevumi, nevar turpināt!' no-challenges: 'Uzdevumi nav izveidoti šajā pasaulē!' no-challenges-admin: 'Uzdevumi nav izveidoti šajā pasaulē! Izmanto /[command], lai tos pievienotu!' missing-arguments: 'Pietrūkst komandas parametri.' diff --git a/src/main/resources/locales/pl.yml b/src/main/resources/locales/pl.yml index 1eaf25ef..cd521d23 100644 --- a/src/main/resources/locales/pl.yml +++ b/src/main/resources/locales/pl.yml @@ -1165,7 +1165,6 @@ challenges: load-error: "Error: Nie można załadować [value]." no-rank: " Nie masz wystarczająco wysokiej rangi, aby to zrobić." cannot-remove-items: " Niektórych przedmiotów nie można usunąć z ekwipunku!" - exist-challenges-or-levels: "Zadania już istnieją w twoim świecie. Nie można kontynuować!" no-challenges: "Zadania nie są jeszcze zaimplementowane na tym świecie!" no-challenges-admin: "Zadania nie są jeszcze zaimplementowane na tym świecie! Użyj /[command] i , aby je dodać!" missing-arguments: "Poleceniu brakuje argumentów." diff --git a/src/main/resources/locales/pt.yml b/src/main/resources/locales/pt.yml index 660dbe6e..1630a3e8 100644 --- a/src/main/resources/locales/pt.yml +++ b/src/main/resources/locales/pt.yml @@ -1239,7 +1239,6 @@ challenges: load-error: "Erro: Não é possível carregar [value]." no-rank: "Você não tem uma classificação alta o suficiente para fazer isso." cannot-remove-items: "Alguns itens não podem ser removidos do seu inventário!" - exist-challenges-or-levels: "Desafios já existem em seu mundo. Não é possível prosseguir!" no-challenges: "Os desafios ainda não foram implementados neste mundo!" no-challenges-admin: "Os desafios ainda não foram implementados neste mundo! Use /[command] para adicioná-los!" missing-arguments: "O comando não tem argumentos." diff --git a/src/main/resources/locales/ru.yml b/src/main/resources/locales/ru.yml index 12d6ca03..e65bde07 100644 --- a/src/main/resources/locales/ru.yml +++ b/src/main/resources/locales/ru.yml @@ -1304,7 +1304,6 @@ challenges: missing-arguments: "В команде отсутствуют аргументы." wrong-environment: "Вы находитесь в неправильном окружении!" missing-addon: "Невозможно выполнить задание: отсутствует обязательный аддон или плагин." - exist-challenges-or-levels: "Челленджи уже существуют в вашем мире. Не могу продолжить!" no-challenges: "Челленджи еще не реализованы в этом мире!" no-challenges-admin: "Челленджи еще не реализованы в этом мире! Используйте /[command] чтобы добавить их!" missing-level: "Уровень челленджа [level] не определен в базе данных. Это может привести к ошибкам!" diff --git a/src/main/resources/locales/uk.yml b/src/main/resources/locales/uk.yml index 7f9ce936..513f2658 100644 --- a/src/main/resources/locales/uk.yml +++ b/src/main/resources/locales/uk.yml @@ -1239,7 +1239,6 @@ challenges: load-error: "Помилка: неможливо завантажити [value]." no-rank: "Ви не маєте достатньо високого рангу, щоб це зробити." cannot-remove-items: "Деякі предмети не можна видалити з вашого інвентарю!" - exist-challenges-or-levels: "Проблеми вже існують у вашому світі. Неможливо продовжити!" no-challenges: "Виклики ще не реалізовані в цьому світі!" no-challenges-admin: "Виклики ще не реалізовані в цьому світі! Використовуйте /[command] , щоб додати їх!" missing-arguments: У команді відсутні аргументи. diff --git a/src/main/resources/locales/zh-CN.yml b/src/main/resources/locales/zh-CN.yml index 1b46255d..5e908e17 100644 --- a/src/main/resources/locales/zh-CN.yml +++ b/src/main/resources/locales/zh-CN.yml @@ -1029,7 +1029,6 @@ challenges: load-error: "错误: 无法载入 [value]。" no-rank: "你没有等级可以做到这一点." cannot-remove-items: "有些物品无法从你的物品栏中删除!" - exist-challenges-or-levels: "&c挑战已经存在于您的世界中。无法继续!" no-challenges: "这个游戏模式没有可进行的挑战!" no-challenges-admin: "这个游戏模式还没有可进行的挑战!请使用 /[command] 来添加挑战。" missing-arguments: "命令缺少参数。" diff --git a/src/main/resources/locales/zh-HK.yml b/src/main/resources/locales/zh-HK.yml index 92900094..61fe7acb 100644 --- a/src/main/resources/locales/zh-HK.yml +++ b/src/main/resources/locales/zh-HK.yml @@ -1112,7 +1112,6 @@ challenges: load-error: '錯誤: 無法載入 [value].' no-rank: '你還未達到足夠的頭銜等級以完成挑戰。' cannot-remove-items: '部分物品無法從你的背包內移除!' - exist-challenges-or-levels: '你的世界內已經有了這挑戰。 無法進行!' no-challenges: '這個世界尚未開放挑戰功能!' no-challenges-admin: '這個世界尚未開放挑戰功能! 使用/[command] 添加挑戰!' missing-arguments: '指令不完整。' diff --git a/src/main/resources/locales/zh-TW.yml b/src/main/resources/locales/zh-TW.yml index 16c2d1ed..c4662937 100644 --- a/src/main/resources/locales/zh-TW.yml +++ b/src/main/resources/locales/zh-TW.yml @@ -1281,7 +1281,6 @@ challenges: no-rank: 你的權限等級不足,無法執行此操作。 wrong-biome: 你必須站在 [biome] 生態域內才能完成此挑戰! cannot-remove-items: 部分物品無法從你的背包中移除! - exist-challenges-or-levels: 此世界已存在挑戰或等級,無法繼續! no-challenges: 此世界尚未設定挑戰! no-challenges-admin: 此世界尚未設定挑戰!請使用 /[command] 新增挑戰! missing-arguments: 指令缺少必要參數。 diff --git a/src/test/java/world/bentobox/challenges/managers/ChallengesImportManagerTest.java b/src/test/java/world/bentobox/challenges/managers/ChallengesImportManagerTest.java index e7c640ce..36939aea 100644 --- a/src/test/java/world/bentobox/challenges/managers/ChallengesImportManagerTest.java +++ b/src/test/java/world/bentobox/challenges/managers/ChallengesImportManagerTest.java @@ -291,20 +291,28 @@ void testLoadDownloadedChallengesNullWorld() { } @Test - void testLoadDownloadedChallengesExistingData() { + void testLoadDownloadedChallengesExistingDataIsReplaced() { when(cm.hasAnyChallengeData(anyString())).thenReturn(true); - when(user.isPlayer()).thenReturn(true); cim.loadDownloadedChallenges(user, world, "{}"); - verify(user).getTranslation(any(World.class), eq("challenges.errors.exist-challenges-or-levels")); - verify(cm, never()).loadChallenge(any(), any(), anyBoolean(), any(), anyBoolean()); + verify(cm).wipeDatabase("bskyblock"); + verify(user, never()).getTranslation(any(World.class), eq("challenges.errors.exist-challenges-or-levels")); + verify(cm).saveChallenges(); + verify(cm).saveLevels(); } @Test - void testLoadDownloadedChallengesExistingDataConsoleUser() { - when(cm.hasAnyChallengeData(anyString())).thenReturn(true); - when(user.isPlayer()).thenReturn(false); + void testLoadDownloadedChallengesNoExistingDataDoesNotWipe() { + when(cm.hasAnyChallengeData(anyString())).thenReturn(false); cim.loadDownloadedChallenges(user, world, "{}"); - verify(addon).logWarning("challenges.errors.exist-challenges-or-levels"); + verify(cm, never()).wipeDatabase(anyString()); + } + + @Test + void testLoadDownloadedChallengesBrokenDownloadKeepsExistingData() { + when(cm.hasAnyChallengeData(anyString())).thenReturn(true); + cim.loadDownloadedChallenges(user, world, "{ this is not json"); + verify(cm, never()).wipeDatabase(anyString()); + verify(cm, never()).saveChallenges(); } @Test From a3a7a6248bf4ceb3c673376c84b73995eb703f1f Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 14 Nov 2026 12:24:56 -0800 Subject: [PATCH 2/2] Guard web import against a non-gamemode world Sonar S2259: Utils.getGameMode returns null when the world does not belong to a game mode, so building the ID prefix could throw. Resolve the game mode addon once up front, report not-a-gamemode-world as the template import does, and reuse the name for the prefix and the wipe. Co-Authored-By: Claude Fable 5.2 --- .../managers/ChallengesImportManager.java | 25 ++++++++++++++++--- .../managers/ChallengesImportManagerTest.java | 10 ++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/main/java/world/bentobox/challenges/managers/ChallengesImportManager.java b/src/main/java/world/bentobox/challenges/managers/ChallengesImportManager.java index b12d5568..934642d9 100644 --- a/src/main/java/world/bentobox/challenges/managers/ChallengesImportManager.java +++ b/src/main/java/world/bentobox/challenges/managers/ChallengesImportManager.java @@ -777,13 +777,33 @@ public void loadDownloadedChallenges(User user, World world, String downloadStri return; } + Optional optional = this.addon.getPlugin().getIWM().getAddon(world); + + if (optional.isEmpty()) + { + if (user != null && user.isPlayer()) + { + Utils.sendMessage(user, + world, + Constants.ERRORS + "not-a-gamemode-world", + Constants.PARAMETER_WORLD, world.getName()); + } + + this.addon.logWarning("Given world is not a gamemode world."); + + return; + } + + // Challenges and levels are stored under the lowercase game mode name. + final String gameMode = optional.get().getDescription().getName().toLowerCase(); + ChallengesManager manager = this.addon.getChallengesManager(); try { // This prefix will be used to all challenges. That is a unique way how to separate challenged for // each game mode. - String uniqueIDPrefix = Utils.getGameMode(world).toLowerCase() + "_"; + String uniqueIDPrefix = gameMode + "_"; DefaultDataHolder downloadedChallenges = new DefaultJSONHandler(this.addon).loadWebObject(downloadString); if (downloadedChallenges == null) @@ -795,8 +815,7 @@ public void loadDownloadedChallenges(User user, World world, String downloadStri // now that the download has parsed, so a broken download cannot leave the world empty. if (manager.hasAnyChallengeData(world.getName())) { - this.addon.getPlugin().getIWM().getAddon(world).ifPresent(gameModeAddon -> - manager.wipeDatabase(gameModeAddon.getDescription().getName().toLowerCase())); + manager.wipeDatabase(gameMode); } // All new challenges should get correct ID. So we need to map it to loaded challenges. diff --git a/src/test/java/world/bentobox/challenges/managers/ChallengesImportManagerTest.java b/src/test/java/world/bentobox/challenges/managers/ChallengesImportManagerTest.java index 36939aea..f06c8b38 100644 --- a/src/test/java/world/bentobox/challenges/managers/ChallengesImportManagerTest.java +++ b/src/test/java/world/bentobox/challenges/managers/ChallengesImportManagerTest.java @@ -290,6 +290,16 @@ void testLoadDownloadedChallengesNullWorld() { verify(addon).logError("Given world is not part of BentoBox"); } + @Test + void testLoadDownloadedChallengesNotAGameModeWorld() { + when(iwm.getAddon(any())).thenReturn(java.util.Optional.empty()); + when(cm.hasAnyChallengeData(anyString())).thenReturn(true); + cim.loadDownloadedChallenges(user, world, "{}"); + verify(addon).logWarning("Given world is not a gamemode world."); + verify(cm, never()).wipeDatabase(anyString()); + verify(cm, never()).saveChallenges(); + } + @Test void testLoadDownloadedChallengesExistingDataIsReplaced() { when(cm.hasAnyChallengeData(anyString())).thenReturn(true);