From e049ed1d7ebfc265283d8ef0205d0826a1bec5de Mon Sep 17 00:00:00 2001 From: Kevinthegreat <92656833+kevinthegreat1@users.noreply.github.com> Date: Wed, 17 Apr 2024 15:55:18 -0400 Subject: Add ProfileUtils and clean up code --- .../java/de/hysky/skyblocker/SkyblockerMod.java | 2 + .../skyblocker/skyblock/dungeon/DungeonScore.java | 58 ++++--------- .../skyblocker/skyblock/item/ItemCooldowns.java | 97 +++++++--------------- .../de/hysky/skyblocker/utils/ProfileUtils.java | 58 +++++++++++++ 4 files changed, 106 insertions(+), 109 deletions(-) create mode 100644 src/main/java/de/hysky/skyblocker/utils/ProfileUtils.java (limited to 'src/main') diff --git a/src/main/java/de/hysky/skyblocker/SkyblockerMod.java b/src/main/java/de/hysky/skyblocker/SkyblockerMod.java index 494b16e2..947c3fd3 100644 --- a/src/main/java/de/hysky/skyblocker/SkyblockerMod.java +++ b/src/main/java/de/hysky/skyblocker/SkyblockerMod.java @@ -46,6 +46,7 @@ import de.hysky.skyblocker.skyblock.waypoint.OrderedWaypoints; import de.hysky.skyblocker.skyblock.waypoint.Relics; import de.hysky.skyblocker.utils.ApiUtils; import de.hysky.skyblocker.utils.NEURepoManager; +import de.hysky.skyblocker.utils.ProfileUtils; import de.hysky.skyblocker.utils.Utils; import de.hysky.skyblocker.utils.chat.ChatMessageListener; import de.hysky.skyblocker.utils.discord.DiscordRPCManager; @@ -166,6 +167,7 @@ public class SkyblockerMod implements ClientModInitializer { MuseumItemCache.init(); SecretsTracker.init(); ApiUtils.init(); + ProfileUtils.init(); Debug.init(); Kuudra.init(); RenderHelper.init(); diff --git a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/DungeonScore.java b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/DungeonScore.java index 9d610ccd..f9e33410 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/DungeonScore.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/DungeonScore.java @@ -3,15 +3,12 @@ package de.hysky.skyblocker.skyblock.dungeon; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import de.hysky.skyblocker.config.SkyblockerConfig; import de.hysky.skyblocker.config.SkyblockerConfigManager; -import de.hysky.skyblocker.events.SkyblockEvents; import de.hysky.skyblocker.skyblock.dungeon.secrets.DungeonManager; import de.hysky.skyblocker.skyblock.tabhud.util.PlayerListMgr; -import de.hysky.skyblocker.utils.ApiUtils; import de.hysky.skyblocker.utils.Constants; -import de.hysky.skyblocker.utils.Http; +import de.hysky.skyblocker.utils.ProfileUtils; import de.hysky.skyblocker.utils.Utils; import de.hysky.skyblocker.utils.scheduler.MessageScheduler; import de.hysky.skyblocker.utils.scheduler.Scheduler; @@ -26,12 +23,8 @@ import net.minecraft.util.collection.DefaultedList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.CompletableFuture; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.util.stream.StreamSupport; public class DungeonScore { private static final SkyblockerConfig.DungeonScore SCORE_CONFIG = SkyblockerConfigManager.get().locations.dungeons.dungeonScore; @@ -68,11 +61,9 @@ public class DungeonScore { private static int puzzleCount; private static int deathCount; private static int score; - private static final Map SpiritPetCache = new HashMap<>(); - public static void init() { + public static void init() { Scheduler.INSTANCE.scheduleCyclic(DungeonScore::tick, 20); - SkyblockEvents.LEAVE.register(SpiritPetCache::clear); ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> reset()); ClientReceiveMessageEvents.GAME.register((message, overlay) -> { if (overlay || !Utils.isInDungeons()) return; @@ -288,36 +279,18 @@ public class DungeonScore { return matcher != null ? Integer.parseInt(matcher.group("crypts")) : 0; } - public static boolean hasSpiritPet(String name) { - return SpiritPetCache.computeIfAbsent(name, k -> { - String playeruuid = ApiUtils.name2Uuid(name); - try (Http.ApiResponse response = Http.sendHypixelRequest("skyblock/profiles", "?uuid=" + playeruuid)) { - if (!response.ok()) throw new IllegalStateException("Failed to get profile uuid for player " + name + "! Response: " + response.content()); - JsonObject responseJson = JsonParser.parseString(response.content()).getAsJsonObject(); - - JsonObject player = StreamSupport.stream(responseJson.getAsJsonArray("profiles").spliterator(), false) - .map(JsonElement::getAsJsonObject) - .filter(profile -> profile.getAsJsonPrimitive("selected").getAsBoolean()) - .findFirst() - .orElseThrow(() -> new IllegalStateException("No selected profile found!?")) - .getAsJsonObject("members").entrySet().stream() - .filter(entry -> entry.getKey().equals(playeruuid)) - .map(Map.Entry::getValue) - .map(JsonElement::getAsJsonObject) - .findFirst() - .orElseThrow(() -> new IllegalStateException("Player somehow not found inside their own profile!")); - - for (JsonElement element : player.getAsJsonObject("pets_data").getAsJsonArray("pets")) { - if (!element.getAsJsonObject().get("type").getAsString().equals("SPIRIT")) continue; - if (!element.getAsJsonObject().get("tier").getAsString().equals("LEGENDARY")) continue; - - return true; - } - } catch (Exception e) { - LOGGER.error("[Skyblocker] Spirit pet lookup by name failed! Name: {}", name, e); + public static boolean hasSpiritPet(JsonObject player, String name) { + try { + for (JsonElement pet : player.getAsJsonObject("pets_data").getAsJsonArray("pets")) { + if (!pet.getAsJsonObject().get("type").getAsString().equals("SPIRIT")) continue; + if (!pet.getAsJsonObject().get("tier").getAsString().equals("LEGENDARY")) continue; + + return true; } - return false; - }); + } catch (Exception e) { + LOGGER.error("[Skyblocker] Spirit pet lookup by name failed! Name: {}", name, e); + } + return false; } private static void checkMessageForDeaths(String message) { @@ -327,11 +300,10 @@ public class DungeonScore { deathCount++; if (deathCount > 1) return; final String whoDied = matcher.group("whodied").transform(s -> { - if (s.equals("You")) return MinecraftClient.getInstance().player.getName().getString(); //This will be wrong if the dead player is called 'You' but that's unlikely + if (s.equals("You")) return MinecraftClient.getInstance().getSession().getUsername(); //This will be wrong if the dead player is called 'You' but that's unlikely else return s; }); - CompletableFuture.supplyAsync(() -> hasSpiritPet(whoDied)) - .thenAccept(hasSpiritPet -> firstDeathHasSpiritPet = hasSpiritPet); + ProfileUtils.updateProfile(whoDied).thenAccept(player -> firstDeathHasSpiritPet = hasSpiritPet(player, whoDied)); } private static void checkMessageForWatcher(String message) { diff --git a/src/main/java/de/hysky/skyblocker/skyblock/item/ItemCooldowns.java b/src/main/java/de/hysky/skyblocker/skyblock/item/ItemCooldowns.java index 86765499..be934810 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/item/ItemCooldowns.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/item/ItemCooldowns.java @@ -1,15 +1,9 @@ package de.hysky.skyblocker.skyblock.item; -import com.google.gson.JsonParser; import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.common.collect.ImmutableList; import de.hysky.skyblocker.config.SkyblockerConfigManager; -import de.hysky.skyblocker.events.SkyblockEvents; -import de.hysky.skyblocker.utils.ApiUtils; -import de.hysky.skyblocker.utils.Http; import de.hysky.skyblocker.utils.ItemUtils; -import de.hysky.skyblocker.utils.Utils; +import de.hysky.skyblocker.utils.ProfileUtils; import net.fabricmc.fabric.api.event.client.player.ClientPlayerBlockBreakEvents; import net.fabricmc.fabric.api.event.player.UseItemCallback; import net.minecraft.block.BlockState; @@ -22,21 +16,14 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import java.util.HashMap; +import java.util.List; import java.util.Map; -import com.mojang.util.UndashedUuid; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.session.Session; - -import java.util.stream.StreamSupport; -import java.util.concurrent.CompletableFuture; - public class ItemCooldowns { private static final String JUNGLE_AXE_ID = "JUNGLE_AXE"; private static final String TREECAPITATOR_ID = "TREECAPITATOR_AXE"; private static final String GRAPPLING_HOOK_ID = "GRAPPLING_HOOK"; - private static final ImmutableList BAT_ARMOR_IDS = ImmutableList.of("BAT_PERSON_HELMET", "BAT_PERSON_CHESTPLATE", "BAT_PERSON_LEGGINGS", "BAT_PERSON_BOOTS"); - public static final long HypixelApiCooldown = 180000; //3min 180000 + private static final List BAT_ARMOR_IDS = List.of("BAT_PERSON_HELMET", "BAT_PERSON_CHESTPLATE", "BAT_PERSON_LEGGINGS", "BAT_PERSON_BOOTS"); private static final Map ITEM_COOLDOWNS = new HashMap<>(); private static final int[] EXPERIENCE_LEVELS = { 0, 660, 730, 800, 880, 960, 1050, 1150, 1260, 1380, 1510, 1650, 1800, 1960, 2130, @@ -49,75 +36,53 @@ public class ItemCooldowns { 561700, 611700, 666700, 726700, 791700, 861700, 936700, 1016700, 1101700, 1191700, 1286700, 1386700, 1496700, 1616700, 1746700, 1886700 }; - public static int MonkeyLevel = 1; - public static double CalcMonkeyExp = 0; - public static double currentCooldown = 0; - public static long unixTimeStamp = 0; + public static int monkeyLevel = 1; + public static double monkeyExp = 0; + public static void init() { ClientPlayerBlockBreakEvents.AFTER.register(ItemCooldowns::afterBlockBreak); UseItemCallback.EVENT.register(ItemCooldowns::onItemInteract); - unixTimeStamp = System.currentTimeMillis() - HypixelApiCooldown; } - public static void currentCooldown() { - long DeltaTime = System.currentTimeMillis() - unixTimeStamp; - if (DeltaTime < HypixelApiCooldown) { - return; - } - unixTimeStamp = System.currentTimeMillis(); - CompletableFuture.runAsync(() -> { - String name = MinecraftClient.getInstance().getSession().getUsername(); - String playeruuid = ApiUtils.name2Uuid(name); - try (Http.ApiResponse response = Http.sendHypixelRequest("skyblock/profiles", "?uuid=" + playeruuid)) { - if (!response.ok()) - throw new IllegalStateException("Failed to get profile uuid for player " + name + "! Response: " + response.content()); - JsonObject responseJson = JsonParser.parseString(response.content()).getAsJsonObject(); - JsonObject players = StreamSupport.stream(responseJson.getAsJsonArray("profiles").spliterator(), false) - .map(JsonElement::getAsJsonObject) - .filter(profile -> profile.getAsJsonPrimitive("selected").getAsBoolean()) - .findFirst() - .orElseThrow(() -> new IllegalStateException("No selected profile found!?")) - .getAsJsonObject("members").entrySet().stream() - .filter(entry -> entry.getKey().equals(playeruuid)) - .map(Map.Entry::getValue) - .map(JsonElement::getAsJsonObject) - .findFirst() - .orElseThrow(() -> new IllegalStateException("Player somehow not found inside their own profile!")); - for (JsonElement element : players.getAsJsonObject("pets_data").getAsJsonArray("pets")) { - if (!element.getAsJsonObject().get("type").getAsString().equals("MONKEY")) continue; - if (!element.getAsJsonObject().get("active").getAsString().equals("true")) continue; - if (element.getAsJsonObject().get("tier").getAsString().equals("LEGENDARY")) { - CalcMonkeyExp = Double.parseDouble(element.getAsJsonObject().get("exp").getAsString()); - MonkeyLevel = 0; - for (int xpLevel : EXPERIENCE_LEVELS) { - if (CalcMonkeyExp < xpLevel) { - break; - } else { - CalcMonkeyExp -= xpLevel; - MonkeyLevel++; - } + public static void updateCooldown() { + ProfileUtils.updateProfile().thenAccept(player -> { + for (JsonElement pet : player.getAsJsonObject("pets_data").getAsJsonArray("pets")) { + if (!pet.getAsJsonObject().get("type").getAsString().equals("MONKEY")) continue; + if (!pet.getAsJsonObject().get("active").getAsString().equals("true")) continue; + if (pet.getAsJsonObject().get("tier").getAsString().equals("LEGENDARY")) { + monkeyExp = Double.parseDouble(pet.getAsJsonObject().get("exp").getAsString()); + monkeyLevel = 0; + for (int xpLevel : EXPERIENCE_LEVELS) { + if (monkeyExp < xpLevel) { + break; + } else { + monkeyExp -= xpLevel; + monkeyLevel++; } } } - } catch (Exception e) { - System.out.println("[Skyblocker] Failed to get Player Pet Data, is the API Down/Limited?"); } - double BaseCooldown = 2000; - double EvolvedAxesCooldownReductionPercentage = MonkeyLevel * 0.5; - double MonkeyPetCDRReduction = (BaseCooldown * EvolvedAxesCooldownReductionPercentage) / 100; - currentCooldown = BaseCooldown - MonkeyPetCDRReduction; + }).exceptionally(e -> { + ProfileUtils.LOGGER.error("[Skyblocker Item Cooldown] Failed to get Player Pet Data, is the API Down/Limited?", e); + return null; }); } + private static int getCooldown() { + int baseCooldown = 2000; + int monkeyPetCooldownReduction = baseCooldown * monkeyLevel / 200; + return baseCooldown - monkeyPetCooldownReduction; + } + public static void afterBlockBreak(World world, PlayerEntity player, BlockPos pos, BlockState state) { if (!SkyblockerConfigManager.get().general.itemCooldown.enableItemCooldowns) return; String usedItemId = ItemUtils.getItemId(player.getMainHandStack()); if (usedItemId.isEmpty()) return; if (state.isIn(BlockTags.LOGS)) { if (usedItemId.equals(JUNGLE_AXE_ID) || usedItemId.equals(TREECAPITATOR_ID)) { - currentCooldown(); + updateCooldown(); if (!isOnCooldown(JUNGLE_AXE_ID) || !isOnCooldown(TREECAPITATOR_ID)) { - ITEM_COOLDOWNS.put(usedItemId, new CooldownEntry((int) currentCooldown)); + ITEM_COOLDOWNS.put(usedItemId, new CooldownEntry(getCooldown())); } } } diff --git a/src/main/java/de/hysky/skyblocker/utils/ProfileUtils.java b/src/main/java/de/hysky/skyblocker/utils/ProfileUtils.java new file mode 100644 index 00000000..0a1f238a --- /dev/null +++ b/src/main/java/de/hysky/skyblocker/utils/ProfileUtils.java @@ -0,0 +1,58 @@ +package de.hysky.skyblocker.utils; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import de.hysky.skyblocker.SkyblockerMod; +import it.unimi.dsi.fastutil.objects.ObjectLongPair; +import net.minecraft.client.MinecraftClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +public class ProfileUtils { + public static final Logger LOGGER = LoggerFactory.getLogger(ProfileUtils.class); + private static final long HYPIXEL_API_COOLDOWN = 300000; // 5min = 300000 + + public static Map> players = new HashMap<>(); + + public static void init() { + updateProfile(); + } + + public static CompletableFuture updateProfile() { + return updateProfile(MinecraftClient.getInstance().getSession().getUsername()); + } + + public static CompletableFuture updateProfile(String name) { + ObjectLongPair playerCache = players.get(name); + if (playerCache != null && playerCache.rightLong() + HYPIXEL_API_COOLDOWN > System.currentTimeMillis()) { + return CompletableFuture.completedFuture(playerCache.left()); + } + + return CompletableFuture.supplyAsync(() -> { + String uuid = ApiUtils.name2Uuid(name); + try (Http.ApiResponse response = Http.sendHypixelRequest("skyblock/profiles", "?uuid=" + uuid)) { + if (!response.ok()) { + throw new IllegalStateException("Failed to get profile uuid for players " + name + "! Response: " + response.content()); + } + JsonObject responseJson = SkyblockerMod.GSON.fromJson(response.content(), JsonObject.class); + + JsonObject player = responseJson.getAsJsonArray("profiles").asList().stream() + .map(JsonElement::getAsJsonObject) + .filter(profile -> profile.getAsJsonPrimitive("selected").getAsBoolean()) + .findFirst() + .orElseThrow(() -> new IllegalStateException("No selected profile found!?")) + .getAsJsonObject("members").get(uuid).getAsJsonObject(); + + players.put(name, ObjectLongPair.of(player, System.currentTimeMillis())); + return player; + } catch (Exception e) { + LOGGER.error("[Skyblocker Profile Utils] Failed to get Player Profile Data for players {}, is the API Down/Limited?", name, e); + } + return null; + }); + } +} -- cgit