Skip to content

Commit

Permalink
Fix update repository (#663)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinthegreat1 authored Apr 22, 2024
1 parent 9e1fb6e commit abf64d3
Show file tree
Hide file tree
Showing 10 changed files with 64 additions and 39 deletions.
34 changes: 20 additions & 14 deletions src/main/java/de/hysky/skyblocker/utils/FileUtils.java
Original file line number Diff line number Diff line change
@@ -1,37 +1,43 @@
package de.hysky.skyblocker.utils;

import com.mojang.logging.LogUtils;
import org.slf4j.Logger;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.slf4j.Logger;

import com.mojang.logging.LogUtils;
import java.util.stream.Stream;

public class FileUtils {
private static final Logger LOGGER = LogUtils.getLogger();

public static void recursiveDelete(Path dir) throws IOException {
if (!Files.exists(dir)) {
return;
}

if (Files.isDirectory(dir) && !Files.isSymbolicLink(dir)) {
Files.list(dir).forEach(child -> {
try {
recursiveDelete(child);
} catch (Exception e) {
LOGGER.error("[Skyblocker] Encountered an exception while deleting a file! Path: {}", child.toAbsolutePath(), e);
}
});
try (Stream<Path> stream = Files.list(dir)) {
stream.forEach(child -> {
try {
recursiveDelete(child);
} catch (Exception e) {
LOGGER.error("[Skyblocker] Encountered an exception while deleting a file. Path: {}", child.toAbsolutePath(), e);
}
});
}
}

if (!Files.isWritable(dir)) {
dir.toFile().setWritable(true);
if (!Files.isWritable(dir) && !dir.toFile().setWritable(true)) {
LOGGER.error("[Skyblocker] Failed to make file writable. Path: {}", dir.toAbsolutePath());
}

Files.delete(dir);
}

/**
* Replaces any characters that do not match the regex: [^a-z0-9_.-]
*
*
* @implNote Designed to convert a file path to an {@link net.minecraft.util.Identifier}
*/
public static String normalizePath(Path path) {
Expand Down
48 changes: 31 additions & 17 deletions src/main/java/de/hysky/skyblocker/utils/NEURepoManager.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package de.hysky.skyblocker.utils;

import com.mojang.brigadier.Command;
import de.hysky.skyblocker.SkyblockerMod;
import de.hysky.skyblocker.skyblock.itemlist.ItemRepository;
import de.hysky.skyblocker.utils.scheduler.Scheduler;
import io.github.moulberry.repo.NEURepository;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text;
import org.apache.commons.lang3.function.Consumers;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
Expand All @@ -28,7 +32,7 @@ public class NEURepoManager {
* Use {@link #NEU_REPO}.
*/
private static final Path LOCAL_REPO_DIR = SkyblockerMod.CONFIG_DIR.resolve("item-repo"); // TODO rename to NotEnoughUpdates-REPO
private static final CompletableFuture<Void> REPO_INITIALIZED = loadRepository();
private static CompletableFuture<Void> REPO_LOADING = loadRepository().thenAccept(Consumers.nop());
public static final NEURepository NEU_REPO = NEURepository.of(LOCAL_REPO_DIR);

/**
Expand All @@ -39,14 +43,16 @@ public class NEURepoManager {
public static void init() {
ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) ->
dispatcher.register(ClientCommandManager.literal(SkyblockerMod.NAMESPACE)
.then(ClientCommandManager.literal("updaterepository").executes(context -> {
deleteAndDownloadRepository();
return 1;
}))));
.then(ClientCommandManager.literal("updateRepository").executes(context -> {
deleteAndDownloadRepository(context.getSource().getPlayer());
return Command.SINGLE_SUCCESS;
}))
)
);
}

private static CompletableFuture<Void> loadRepository() {
return CompletableFuture.runAsync(() -> {
private static CompletableFuture<Boolean> loadRepository() {
return CompletableFuture.supplyAsync(() -> {
try {
if (Files.isDirectory(NEURepoManager.LOCAL_REPO_DIR)) {
try (Git localRepo = Git.open(NEURepoManager.LOCAL_REPO_DIR.toFile())) {
Expand All @@ -58,28 +64,36 @@ private static CompletableFuture<Void> loadRepository() {
LOGGER.info("[Skyblocker] NEU Repository Downloaded");
}
NEU_REPO.reload();
} catch (TransportException e){
return true;
} catch (TransportException e) {
LOGGER.error("[Skyblocker] Transport operation failed. Most likely unable to connect to the remote NEU repo on github", e);
} catch (RepositoryNotFoundException e) {
LOGGER.warn("[Skyblocker] Local NEU Repository not found or corrupted, downloading new one", e);
deleteAndDownloadRepository();
Scheduler.INSTANCE.schedule(() -> deleteAndDownloadRepository(MinecraftClient.getInstance().player), 1);
} catch (Exception e) {
LOGGER.error("[Skyblocker] Encountered unknown exception while initializing NEU Repository", e);
}
return false;
});
}

private static void deleteAndDownloadRepository() {
CompletableFuture.runAsync(() -> {
private static void deleteAndDownloadRepository(PlayerEntity player) {
if (REPO_LOADING != null && !REPO_LOADING.isDone()) {
player.sendMessage(Constants.PREFIX.get().append(Text.translatable("skyblocker.updateRepository.loading")), false);
return;
}
player.sendMessage(Constants.PREFIX.get().append(Text.translatable("skyblocker.updateRepository.start")), false);

REPO_LOADING = CompletableFuture.runAsync(() -> {
try {
ItemRepository.setFilesImported(false);
FileUtils.recursiveDelete(NEURepoManager.LOCAL_REPO_DIR);
} catch (Exception ex) {
if (MinecraftClient.getInstance().player != null)
MinecraftClient.getInstance().player.sendMessage(Constants.PREFIX.get().append(Text.translatable("skyblocker.updaterepository.failed")), false);
return;
player.sendMessage(Constants.PREFIX.get().append(Text.translatable("skyblocker.updateRepository.deleted")), false);
player.sendMessage(Constants.PREFIX.get().append(Text.translatable(loadRepository().join() ? "skyblocker.updateRepository.success" : "skyblocker.updateRepository.failed")), false);
} catch (Exception e) {
LOGGER.error("[Skyblocker] Encountered unknown exception while deleting the NEU repo", e);
player.sendMessage(Constants.PREFIX.get().append(Text.translatable("skyblocker.updateRepository.error")), false);
}
loadRepository();
});
}

Expand All @@ -89,6 +103,6 @@ private static void deleteAndDownloadRepository() {
* @return a completable future of the given runnable
*/
public static CompletableFuture<Void> runAsyncAfterLoad(Runnable runnable) {
return REPO_INITIALIZED.thenRunAsync(runnable);
return REPO_LOADING.thenRunAsync(runnable);
}
}
7 changes: 6 additions & 1 deletion src/main/resources/assets/skyblocker/lang/en_us.json
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,12 @@
"skyblocker.bars.config.explanationTitle": "What is this?",
"skyblocker.bars.config.explanation": "Welcome to the status bars config screen!\n\nDrag and drop the bars to snap them to an anchor (white squares) or existing bars.\nYou can right click them to edit a bunch of properties.\nBy hovering your mouse between 2 bars (your cursor should change), you can resize them.\n\nEverything is saved when you leave",

"skyblocker.updaterepository.failed": "§cUpdating local repository failed. Remove files manually and restart game.",
"skyblocker.updateRepository.start": "§bUpdating the local repository...",
"skyblocker.updateRepository.loading": "§cThe local repository is currently being updated by another process, please try again in a moment.",
"skyblocker.updateRepository.deleted": "§bDeleted the local repository successfully, downloading new files... This will take a minute!",
"skyblocker.updateRepository.success": "§aUpdated the local repository successfully.",
"skyblocker.updateRepository.failed": "§cUpdating the local repository failed. See logs for details.",
"skyblocker.updateRepository.error": "§cEncountered an error while deleting and updating the local repository. Try again in a moment or remove the files manually and restart the game. See logs for details.",

"skyblocker.dungeons.secrets.physicalEntranceNotFound": "§cDungeon Entrance Room coordinates not found. Please go back to the green Entrance Room.",
"skyblocker.dungeons.secrets.markSecretFound": "§rMarked secret #%d as found.",
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/assets/skyblocker/lang/es_es.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
"text.autoconfig.skyblocker.option.messages.hideAOTE": "Ocultar Mensajes de la AOTE",
"text.autoconfig.skyblocker.option.messages.hideMana": "Ocultar los Mensajes del Consumo de Maná de la Barra de Acción",
"text.autoconfig.skyblocker.option.messages.hideMana.@Tooltip": "Da una mejor experiencia con FancyBar",
"skyblocker.updaterepository.failed": "§cLa actualización del repositorio local fallo. Elimina los archivos manualmente y reinicia el juego.",
"skyblocker.updateRepository.error": "§cLa actualización del repositorio local fallo. Elimina los archivos manualmente y reinicia el juego.",
"text.autoconfig.skyblocker.option.general.shortcuts.enableShortcuts": "Habilitar atajos",
"text.autoconfig.skyblocker.option.general.shortcuts.enableShortcuts.@Tooltip": "Solo funciona en Hypixel. Edita atajos ejecutando \"/skyblocker shortcuts\". Al menos una de las siguientes opciones debe ser activada para surgir efecto.",
"text.autoconfig.skyblocker.option.general.shortcuts": "Atajos",
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/assets/skyblocker/lang/fr_fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@
"text.autoconfig.skyblocker.option.richPresence.info.LOCATION": "LIEU",
"text.autoconfig.skyblocker.category.quickNav": "Navigation rapide",
"text.autoconfig.skyblocker.option.quickNav.enableQuickNav": "Activer la navigation rapide",
"skyblocker.updaterepository.failed": "§cLa mise à jour de la repository a échoué. Supprimez les fichiers manuellement et relancez le jeu.",
"skyblocker.updateRepository.error": "§cLa mise à jour de la repository a échoué. Supprimez les fichiers manuellement et relancez le jeu.",
"skyblocker.fishing.reelNow": "Enroulez la ligne !",
"text.autoconfig.skyblocker.option.general.fishing.enableFishingHelper": "Activer l'assistant de pêche",
"text.autoconfig.skyblocker.option.general.fishing": "Assistant de pêche",
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/assets/skyblocker/lang/pt_br.json
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@
"text.autoconfig.skyblocker.option.general.itemTooltip.enableMotesPrice.@Tooltip": "Mostrar os preços de venda dos Motes de um item enquanto está no The Rift.",
"text.autoconfig.skyblocker.option.general.itemInfoDisplay.attributeShardInfo.@Tooltip": "Mostra o nível do atributo como uma contagem de stack e os iniciais do nome do atributo.",
"text.autoconfig.skyblocker.category.slayer": "Slayers",
"skyblocker.updaterepository.failed": "§cAtualização do repositório local falhou. Remova os arquivos manualmente e reinicie o jogo.",
"skyblocker.updateRepository.error": "§cAtualização do repositório local falhou. Remova os arquivos manualmente e reinicie o jogo.",
"text.autoconfig.skyblocker.option.general.hideStatusEffectOverlay": "Esconder Overlay de Status de Efeitos",
"text.autoconfig.skyblocker.option.general.itemList.enableItemList": "Ativar Lista de Itens",
"text.autoconfig.skyblocker.option.general.itemList": "Lista de Itens",
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/assets/skyblocker/lang/ru_ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@
"text.autoconfig.skyblocker.option.locations.barn.solveTreasureHunter": "Показывать Решение Treasure Hunter",
"text.autoconfig.skyblocker.option.messages.chatFilterResult.FILTER": "Скрыть",
"text.autoconfig.skyblocker.option.messages.chatFilterResult.PASS": "Не скрывать",
"skyblocker.updaterepository.failed": "§cОшибка в обновлении местного репозитория. Перезапустите игру, удалив файлы вручную.",
"skyblocker.updateRepository.error": "§cОшибка в обновлении местного репозитория. Перезапустите игру, удалив файлы вручную.",
"text.autoconfig.skyblocker.option.richPresence.info.BITS": "BITS",
"text.autoconfig.skyblocker.option.locations.dungeons.croesusHelper": "Помощь в меню Croesus",
"text.autoconfig.skyblocker.option.general.experiments": "Помощь в Экспериментах",
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/assets/skyblocker/lang/tr_tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"text.autoconfig.skyblocker.option.general.bars.barpositions.defenceBarPosition": "Defans barı konumu",
"text.autoconfig.skyblocker.option.general.bars.barpositions.experienceBarPosition": "Tecrübe barı konumu",
"key.categories.skyblocker": "Skyblocker",
"skyblocker.updaterepository.failed": "§cYerel depo güncellenemedi. Dosyaları manuel olarak silip oyunu tekrar başlatın.",
"skyblocker.updateRepository.error": "§cYerel depo güncellenemedi. Dosyaları manuel olarak silip oyunu tekrar başlatın.",
"text.autoconfig.skyblocker.option.general.fishing": "Balık Tutma Yardımcısı",
"text.autoconfig.skyblocker.option.general.fishing.enableFishingHelper": "Balık tutma yardımcısını aktifleştir",
"text.autoconfig.skyblocker.category.messages": "Mesajlar",
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/assets/skyblocker/lang/zh_cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"text.autoconfig.skyblocker.option.messages.hideMana.@Tooltip": "已被更好的属性条代替",
"text.autoconfig.skyblocker.option.general.hideEmptyTooltips": "隐藏菜单中分隔符的物品信息",
"text.autoconfig.skyblocker.option.locations.dungeons.mapScaling": "地图界面大小",
"skyblocker.updaterepository.failed": "§c更新本地数据存储库失败,请手动删除文件并重启游戏。",
"skyblocker.updateRepository.error": "§c更新本地数据存储库失败,请手动删除文件并重启游戏。",
"text.autoconfig.skyblocker.option.general.fishing": "钓鱼助手",
"text.autoconfig.skyblocker.option.general.fishing.enableFishingHelper": "启用钓鱼助手",
"skyblocker.fishing.reelNow": "收竿!",
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/assets/skyblocker/lang/zh_tw.json
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@
"text.autoconfig.skyblocker.option.general.teleportOverlay": "傳送類型技能目標位置顯示",
"text.autoconfig.skyblocker.option.richPresence.info": "Skyblock訊息",
"text.autoconfig.skyblocker.option.richPresence.cycleMode": "循環Skyblock訊息",
"skyblocker.updaterepository.failed": "§c更新本機資料儲存庫失敗,請手動刪除檔案並重新啟動遊戲。",
"skyblocker.updateRepository.error": "§c更新本機資料儲存庫失敗,請手動刪除檔案並重新啟動遊戲。",
"skyblocker.dungeons.secrets.markSecretFoundUnable": "§c無法將秘密 #%d 標記為已找到。",
"skyblocker.dungeons.secrets.markSecretMissingUnable": "§c無法將秘密 #%d 標記為已忽略。",
"skyblocker.dungeons.dungeonScore.scoreText": "分數:%s",
Expand Down

0 comments on commit abf64d3

Please sign in to comment.