aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/de/hysky/skyblocker/skyblock/item/PlayerHeadHashCache.java
blob: da83216410b3be2a6820382d00d258645dd0aac1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package de.hysky.skyblocker.skyblock.item;

import java.net.URI;
import java.util.Base64;
import java.util.concurrent.CompletableFuture;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.mojang.logging.LogUtils;

import de.hysky.skyblocker.utils.Http;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;

public class PlayerHeadHashCache {
	private static final Logger LOGGER = LogUtils.getLogger();
	private static final IntOpenHashSet CACHE = new IntOpenHashSet();

	public static void init() {
		CompletableFuture.runAsync(PlayerHeadHashCache::loadSkins);
	}

	private static void loadSkins() {
		try {
			String response = Http.sendGetRequest("https://api.hypixel.net/v2/resources/skyblock/items");
			JsonArray items = JsonParser.parseString(response).getAsJsonObject().getAsJsonArray("items");

			items.asList().stream()
			.map(JsonElement::getAsJsonObject)
			.filter(item -> item.get("material").getAsString().equals("SKULL_ITEM"))
			.filter(item -> item.has("skin"))
			.map(item -> Base64.getDecoder().decode(item.get("skin").getAsString()))
			.map(String::new)
			.map(profile -> JsonParser.parseString(profile).getAsJsonObject())
			.map(profile -> profile.getAsJsonObject("textures").getAsJsonObject("SKIN").get("url").getAsString())
			.map(PlayerHeadHashCache::getSkinHash)
			.mapToInt(String::hashCode)
			.forEach(CACHE::add);

			LOGGER.info("[Skyblocker Player Head Hash Cache] Successfully cached the hashes of all player head items!");
		} catch (Exception e) {
			LOGGER.error("[Skyblocker Player Head Hash Cache] Failed to cache skin hashes!", e);
		}
	}

	//From MinecraftProfileTexture#getHash
	public static String getSkinHash(String url) {
		try {
			return FilenameUtils.getBaseName(new URI(url).getPath());
		} catch (Exception e) {
			LOGGER.error("[Skyblocker Player Head Hash Cache] Malformed Skin URL! URL: {}", url, e);
		}

		return "";
	}

	public static boolean contains(int hash) {
		return CACHE.contains(hash);
	}
}