Adds methods for getting head skins from id

This commit is contained in:
Kristian Knarvik 2023-01-19 15:54:30 +01:00
parent e93a7cbe5b
commit 035d894e88

View File

@ -7,7 +7,12 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.profile.PlayerProfile; import org.bukkit.profile.PlayerProfile;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.UUID; import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* An item factory for generating player head-based icons * An item factory for generating player head-based icons
@ -15,6 +20,9 @@ import java.util.UUID;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class PlayerHeadGUIItemFactory extends AbstractGUIItemFactory<PlayerHeadGUIItemFactory> { public class PlayerHeadGUIItemFactory extends AbstractGUIItemFactory<PlayerHeadGUIItemFactory> {
private static final String textureBaseURL = "https://textures.minecraft.net/texture/";
private static final Pattern texturePattern = Pattern.compile("/texture/([0-9a-z]+)");
/** /**
* Instantiates a player head gui item factory * Instantiates a player head gui item factory
*/ */
@ -53,4 +61,43 @@ public class PlayerHeadGUIItemFactory extends AbstractGUIItemFactory<PlayerHeadG
return useSkin(Bukkit.getOfflinePlayer(uuid)); return useSkin(Bukkit.getOfflinePlayer(uuid));
} }
/**
* Uses the skin from the given texture id
*
* <p>This methods takes the id after "<a href="https://textures.minecraft.net/texture/">
* https://textures.minecraft.net/texture/</a>" as input. A base64 JSON value can also be used, though it's not
* recommended.</p>
*
* @param textureId <p>The id of the texture to use</p>
* @return <p>The factory. Used for chaining commands</p>
*/
public PlayerHeadGUIItemFactory useSkin(String textureId) {
//Get the texture id from a Base64 encoded JSON string
if (!textureId.isBlank() && textureId.length() % 4 == 0) {
String decoded = new String(Base64.getDecoder().decode(textureId));
Matcher matcher = texturePattern.matcher(decoded);
if (matcher.find()) {
textureId = matcher.group(1);
}
}
try {
return useSkin(new URL(textureBaseURL + textureId));
} catch (MalformedURLException exception) {
throw new IllegalArgumentException("Texture id resulted in invalid URL");
}
}
/**
* Uses the head skin from the given URL
*
* @param url <p>The URL to use</p>
* @return <p>The factory. Used for chaining commands</p>
*/
public PlayerHeadGUIItemFactory useSkin(URL url) {
PlayerProfile profile = Bukkit.createPlayerProfile(UUID.randomUUID());
profile.getTextures().setSkin(url);
return changeItemMeta(SkullMeta.class, (meta) -> meta.setOwnerProfile(profile));
}
} }