Make SkinServer json serializable and add a button go skins menu to show current gateway server.

This commit is contained in:
Matthew Messinger 2018-07-13 23:05:21 -04:00
parent a34cfed3bf
commit 540ed43178
11 changed files with 178 additions and 102 deletions

View file

@ -1,8 +1,11 @@
package com.voxelmodpack.hdskins;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@ -21,7 +24,10 @@ import com.mumfrey.liteloader.util.log.LiteLoaderLogger;
import com.voxelmodpack.hdskins.gui.GuiSkins;
import com.voxelmodpack.hdskins.resource.SkinResourceManager;
import com.voxelmodpack.hdskins.skins.AsyncCacheLoader;
import com.voxelmodpack.hdskins.skins.LegacySkinServer;
import com.voxelmodpack.hdskins.skins.ServerType;
import com.voxelmodpack.hdskins.skins.SkinServer;
import com.voxelmodpack.hdskins.skins.ValhallaSkinServer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.texture.ITextureObject;
@ -31,13 +37,15 @@ import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.resources.IResourceManagerReloadListener;
import net.minecraft.client.resources.SkinManager.SkinAvailableCallback;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@ -50,7 +58,6 @@ import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public final class HDSkinManager implements IResourceManagerReloadListener {
@ -68,6 +75,7 @@ public final class HDSkinManager implements IResourceManagerReloadListener {
private List<ISkinCacheClearListener> clearListeners = Lists.newArrayList();
private BiMap<String, Class<? extends SkinServer>> skinServerTypes = HashBiMap.create(2);
private List<SkinServer> skinServers = Lists.newArrayList();
private Map<UUID, Map<Type, ResourceLocation>> skinCache = Maps.newHashMap();
@ -81,10 +89,17 @@ public final class HDSkinManager implements IResourceManagerReloadListener {
private List<ISkinModifier> skinModifiers = Lists.newArrayList();
private SkinResourceManager resources = new SkinResourceManager();
// private ExecutorService executor = Executors.newCachedThreadPool();
// private ExecutorService executor = Executors.newCachedThreadPool();
private Class<? extends GuiSkins> skinsClass = null;
private HDSkinManager() {
// register default skin server types
addSkinServerType(LegacySkinServer.class);
addSkinServerType(ValhallaSkinServer.class);
}
public void setPrefferedSkinsGuiClass(Class<? extends GuiSkins> clazz) {
skinsClass = clazz;
}
@ -102,35 +117,42 @@ public final class HDSkinManager implements IResourceManagerReloadListener {
}
public Optional<ResourceLocation> getSkinLocation(GameProfile profile1, final Type type, boolean loadIfAbsent) {
if (!enabled)
if (!enabled) {
return Optional.empty();
}
ResourceLocation skin = this.resources.getPlayerTexture(profile1, type);
if (skin != null)
if (skin != null) {
return Optional.of(skin);
}
// try to recreate a broken gameprofile
// happens when server sends a random profile with skin and displayname
Property textures = Iterables.getFirst(profile1.getProperties().get("textures"), null);
if (textures != null) {
MinecraftTexturesPayload texturePayload = GSON.fromJson(new String(Base64.decodeBase64(textures.getValue())), MinecraftTexturesPayload.class);
String json = new String(Base64.getDecoder().decode(textures.getValue()), StandardCharsets.UTF_8);
MinecraftTexturesPayload texturePayload = GSON.fromJson(json, MinecraftTexturesPayload.class);
if (texturePayload != null) {
// name is optional
String name = texturePayload.getProfileName();
UUID uuid = texturePayload.getProfileId();
// uuid is required
if (uuid != null)
if (uuid != null) {
profile1 = new GameProfile(uuid, name);
}
// probably uses this texture for a reason. Don't mess with it.
if (!texturePayload.getTextures().isEmpty() && texturePayload.getProfileId() == null)
if (!texturePayload.getTextures().isEmpty() && texturePayload.getProfileId() == null) {
return Optional.empty();
}
}
}
final GameProfile profile = profile1;
// cannot get texture without id!
if (profile.getId() == null) return Optional.empty();
if (profile.getId() == null) {
return Optional.empty();
}
if (!this.skinCache.containsKey(profile.getId())) {
this.skinCache.put(profile.getId(), Maps.newHashMap());
@ -148,7 +170,7 @@ public final class HDSkinManager implements IResourceManagerReloadListener {
}
private String bustCache(String url) {
return url + (url.indexOf('?') > -1 ? '&' : '?') + Long.toString(new Date().getTime()/1000);
return url + (url.indexOf('?') > -1 ? '&' : '?') + Long.toString(new Date().getTime() / 1000);
}
private void loadTexture(GameProfile profile, final Type type, final SkinAvailableCallback callback) {
@ -194,8 +216,9 @@ public final class HDSkinManager implements IResourceManagerReloadListener {
for (SkinServer server : skinServers) {
Optional<MinecraftTexturesPayload> profileData = server.loadProfileData(profile);
profileData.map(MinecraftTexturesPayload::getTextures).ifPresent(it -> it.forEach(textures::putIfAbsent));
if (textures.size() == Type.values().length)
if (textures.size() == Type.values().length) {
break;
}
}
return textures;
@ -211,10 +234,25 @@ public final class HDSkinManager implements IResourceManagerReloadListener {
return textures;
}
public void addSkinServer(SkinServer skinServer) {
this.skinServers.add(0, skinServer);
public void addSkinServerType(Class<? extends SkinServer> type) {
Preconditions.checkArgument(!type.isInterface(), "type cannot be an interface");
Preconditions.checkArgument(!Modifier.isAbstract(type.getModifiers()), "type cannot be abstract");
ServerType st = type.getAnnotation(ServerType.class);
if (st == null) {
throw new IllegalArgumentException("class is not annotated with @ServerType");
}
this.skinServerTypes.put(st.value(), type);
}
public Class<? extends SkinServer> getSkinServerClass(String type) {
return this.skinServerTypes.get(type);
}
public void addSkinServer(SkinServer skinServer) {
this.skinServers.add(skinServer);
}
@Deprecated
public SkinServer getGatewayServer() {
return this.skinServers.get(0);
}

View file

@ -4,11 +4,13 @@ import static com.mojang.authlib.minecraft.MinecraftProfileTexture.Type.ELYTRA;
import static com.mojang.authlib.minecraft.MinecraftProfileTexture.Type.SKIN;
import static net.minecraft.client.renderer.GlStateManager.*;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mumfrey.liteloader.util.log.LiteLoaderLogger;
import com.voxelmodpack.hdskins.HDSkinManager;
import com.voxelmodpack.hdskins.skins.SkinServer;
import com.voxelmodpack.hdskins.skins.SkinUploadResponse;
import com.voxelmodpack.hdskins.upload.awt.ThreadOpenFilePNG;
import net.minecraft.client.Minecraft;
@ -57,6 +59,8 @@ public class GuiSkins extends GuiScreen {
private GuiButton btnModeSkinnySkin;
private GuiButton btnModeElytra;
private GuiButton btnAbout;
protected EntityPlayerModel localPlayer;
protected EntityPlayerModel remotePlayer;
@ -194,8 +198,10 @@ public class GuiSkins extends GuiScreen {
this.buttonList.add(this.btnModeSkin = new GuiItemStackButton(4, 2, 2, skin));
skin = new ItemStack(Items.LEATHER_LEGGINGS);
Items.LEATHER_LEGGINGS.setColor(skin, 0xfff500);
this.buttonList.add(this.btnModeSkinnySkin = new GuiItemStackButton(6, 2, 21, skin));
this.buttonList.add(this.btnModeElytra = new GuiItemStackButton(5, 2, 52, new ItemStack(Items.ELYTRA)));
this.buttonList.add(this.btnModeSkinnySkin = new GuiItemStackButton(6, 2, 21, skin));
this.buttonList.add(this.btnAbout = new GuiButton(-1, this.width - 25, this.height - 25, 20, 20, "?"));
this.btnUpload.enabled = false;
this.btnBrowse.enabled = !this.mc.isFullScreen();
@ -203,6 +209,7 @@ public class GuiSkins extends GuiScreen {
this.btnModeSkin.enabled = this.thinArmType;
this.btnModeSkinnySkin.enabled = !this.thinArmType;
this.btnModeElytra.enabled = this.textureType == SKIN;
}
private void enableDnd() {
@ -441,6 +448,10 @@ public class GuiSkins extends GuiScreen {
}
this.drawHoveringText(I18n.format(text), mouseX, y);
}
if (this.btnAbout.isMouseOver()) {
SkinServer gateway = HDSkinManager.INSTANCE.getGatewayServer();
this.drawHoveringText(Splitter.on("\r\n").splitToList(gateway.toString()), mouseX, mouseY);
}
if (this.fetchingSkin) {
String opacity1;

View file

@ -1,7 +1,9 @@
package com.voxelmodpack.hdskins.mod;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.mumfrey.liteloader.core.LiteLoader;
import com.mumfrey.liteloader.modconfig.AdvancedExposable;
import com.mumfrey.liteloader.modconfig.ConfigPanel;
import com.mumfrey.liteloader.modconfig.ConfigStrategy;
import com.mumfrey.liteloader.modconfig.ExposableOptions;
@ -9,26 +11,25 @@ import com.mumfrey.liteloader.util.ModUtilities;
import com.voxelmodpack.hdskins.HDSkinManager;
import com.voxelmodpack.hdskins.gui.EntityPlayerModel;
import com.voxelmodpack.hdskins.gui.GLWindow;
import com.voxelmodpack.hdskins.gui.GuiSkins;
import com.voxelmodpack.hdskins.gui.HDSkinsConfigPanel;
import com.voxelmodpack.hdskins.gui.RenderPlayerModel;
import com.voxelmodpack.hdskins.skins.SkinServer;
import com.voxelmodpack.hdskins.skins.SkinServerSerializer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.resources.IReloadableResourceManager;
import java.io.File;
import java.lang.reflect.Method;
import java.util.List;
@ExposableOptions(strategy = ConfigStrategy.Unversioned, filename = "hdskins")
public class LiteModHDSkinsMod implements HDSkinsMod {
public class LiteModHDSkinsMod implements HDSkinsMod, AdvancedExposable {
@Expose
public List<String> skin_servers = SkinServer.defaultServers;
public List<SkinServer> skin_servers = SkinServer.defaultServers;
@Expose
public boolean experimentalSkinDrop = true;
public boolean experimentalSkinDrop = false;
@Override
public String getName() {
@ -46,17 +47,6 @@ public class LiteModHDSkinsMod implements HDSkinsMod {
// register config
LiteLoader.getInstance().registerExposable(this, null);
// try it initialize voxelmenu button
try {
Class<?> ex = Class.forName("com.thevoxelbox.voxelmenu.GuiMainMenuVoxelBox");
Method mRegisterCustomScreen = ex.getDeclaredMethod("registerCustomScreen", Class.class, String.class);
mRegisterCustomScreen.invoke(null, GuiSkins.class, "HD Skins Manager");
} catch (ClassNotFoundException var4) {
// voxelmenu's not here, man
} catch (Exception var5) {
var5.printStackTrace();
}
IReloadableResourceManager irrm = (IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager();
irrm.registerReloadListener(HDSkinManager.INSTANCE);
@ -70,6 +60,16 @@ public class LiteModHDSkinsMod implements HDSkinsMod {
HDSkinManager.clearSkinCache();
}
@Override
public void setupGsonSerialiser(GsonBuilder gsonBuilder) {
gsonBuilder.registerTypeAdapter(SkinServer.class, new SkinServerSerializer());
}
@Override
public File getConfigFile(File configFile, File configFileLocation, String defaultFileName) {
return null;
}
@Override
public Class<? extends ConfigPanel> getConfigPanelClass() {
return HDSkinsConfigPanel.class;
@ -80,14 +80,7 @@ public class LiteModHDSkinsMod implements HDSkinsMod {
ModUtilities.addRenderer(EntityPlayerModel.class, new RenderPlayerModel<>(minecraft.getRenderManager()));
// register skin servers.
for (String s : skin_servers) {
try {
HDSkinManager.INSTANCE.addSkinServer(SkinServer.from(s));
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
skin_servers.forEach(HDSkinManager.INSTANCE::addSkinServer);
}
@Override

View file

@ -1,7 +0,0 @@
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
package com.voxelmodpack.hdskins.mod;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;

View file

@ -0,0 +1,18 @@
package com.voxelmodpack.hdskins.skins;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.builder.ToStringStyle;
public class IndentedToStringStyle extends ToStringStyle {
public static final ToStringStyle INSTANCE = new IndentedToStringStyle();
private IndentedToStringStyle() {
this.setContentStart(null);
this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + " ");
this.setFieldSeparatorAtStart(true);
this.setContentEnd(null);
this.setUseIdentityHashCode(false);
this.setUseShortClassName(true);
}
}

View file

@ -1,8 +1,8 @@
package com.voxelmodpack.hdskins.skins;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.gson.annotations.Expose;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.exceptions.AuthenticationException;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
@ -13,6 +13,7 @@ import com.voxelmodpack.hdskins.HDSkinManager;
import com.voxelmodpack.hdskins.upload.ThreadMultipartPostUpload;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Session;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@ -26,24 +27,21 @@ import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
@ServerType("legacy")
public class LegacySkinServer implements SkinServer {
private static final String SERVER_ID = "7853dfddc358333843ad55a2c7485c4aa0380a51";
private static final Logger logger = LogManager.getLogger();
@Expose
private final String address;
@Expose
private final String gateway;
public LegacySkinServer(String address) {
this(address, null);
}
public LegacySkinServer(String address, @Nullable String gateway) {
this.address = address;
this.gateway = gateway;
@ -144,24 +142,11 @@ public class LegacySkinServer implements SkinServer {
service.joinServer(session.getProfile(), session.getToken(), serverId);
}
/**
* Should be in the format {@code legacy:http://address;http://gateway}. Gateway is optional.
*/
static LegacySkinServer from(String parsed) {
Matcher matcher = Pattern.compile("^legacy:(.+?)(?:;(.*))?$").matcher(parsed);
if (matcher.find()) {
String addr = matcher.group(1);
String gate = matcher.group(2);
return new LegacySkinServer(addr, gate);
}
throw new IllegalArgumentException("server format string was not correct");
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("address", address)
.add("gateway", gateway)
.toString();
return new ToStringBuilder(this, IndentedToStringStyle.INSTANCE)
.append("address", this.address)
.append("gateway", this.gateway)
.build();
}
}

View file

@ -0,0 +1,13 @@
package com.voxelmodpack.hdskins.skins;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ServerType {
String value();
}

View file

@ -17,7 +17,9 @@ import javax.annotation.Nullable;
public interface SkinServer {
List<String> defaultServers = Lists.newArrayList("legacy:http://skins.voxelmodpack.com;http://skinmanager.voxelmodpack.com");
List<SkinServer> defaultServers = Lists.newArrayList(new LegacySkinServer(
"http://skins.voxelmodpack.com",
"http://skinmanager.voxelmodpack.com"));
Optional<MinecraftTexturesPayload> loadProfileData(GameProfile profile);
@ -28,18 +30,4 @@ public interface SkinServer {
CompletableFuture<SkinUploadResponse> uploadSkin(Session session, @Nullable URI image,
MinecraftProfileTexture.Type type, Map<String, String> metadata);
static SkinServer from(String server) {
int i = server.indexOf(':');
if (i >= 0) {
String type = server.substring(0, i);
switch (type) {
case "legacy":
return LegacySkinServer.from(server);
case "valhalla": {
return ValhallaSkinServer.from(server);
}
}
}
throw new IllegalArgumentException();
}
}

View file

@ -0,0 +1,34 @@
package com.voxelmodpack.hdskins.skins;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.voxelmodpack.hdskins.HDSkinManager;
import java.lang.reflect.Type;
public class SkinServerSerializer implements JsonSerializer<SkinServer>, JsonDeserializer<SkinServer> {
@Override
public JsonElement serialize(SkinServer src, Type typeOfSrc, JsonSerializationContext context) {
ServerType serverType = src.getClass().getAnnotation(ServerType.class);
if (serverType == null) {
throw new JsonIOException("Skin server class did not have a type: " + typeOfSrc);
}
JsonObject obj = context.serialize(src).getAsJsonObject();
obj.addProperty("type", serverType.value());
return obj;
}
@Override
public SkinServer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String type = json.getAsJsonObject().get("type").getAsString();
Class<? extends SkinServer> clas = HDSkinManager.INSTANCE.getSkinServerClass(type);
return context.deserialize(json, clas);
}
}

View file

@ -4,6 +4,7 @@ import com.google.common.base.Preconditions;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.annotations.Expose;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.exceptions.AuthenticationException;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
@ -12,6 +13,7 @@ import com.mojang.util.UUIDTypeAdapter;
import com.voxelmodpack.hdskins.HDSkinManager;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Session;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
@ -36,22 +38,22 @@ import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
@ServerType("valhalla")
public class ValhallaSkinServer implements SkinServer {
private final String baseURL;
@Expose
private final String address;
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(UUID.class, new UUIDTypeAdapter())
.create();
private String accessToken;
private transient String accessToken;
private ValhallaSkinServer(String baseURL) {
this.baseURL = baseURL;
public ValhallaSkinServer(String address) {
this.address = address;
}
@Override
@ -189,28 +191,27 @@ public class ValhallaSkinServer implements SkinServer {
private URI buildUserTextureUri(GameProfile profile, MinecraftProfileTexture.Type textureType) {
String user = UUIDTypeAdapter.fromUUID(profile.getId());
String skinType = textureType.name().toLowerCase(Locale.US);
return URI.create(String.format("%s/user/%s/%s", this.baseURL, user, skinType));
return URI.create(String.format("%s/user/%s/%s", this.address, user, skinType));
}
private URI getTexturesURI(GameProfile profile) {
Preconditions.checkNotNull(profile.getId(), "profile id required for skins");
return URI.create(String.format("%s/user/%s", this.baseURL, UUIDTypeAdapter.fromUUID(profile.getId())));
return URI.create(String.format("%s/user/%s", this.address, UUIDTypeAdapter.fromUUID(profile.getId())));
}
private URI getHandshakeURI() {
return URI.create(String.format("%s/auth/handshake", this.baseURL));
return URI.create(String.format("%s/auth/handshake", this.address));
}
private URI getResponseURI() {
return URI.create(String.format("%s/auth/response", this.baseURL));
return URI.create(String.format("%s/auth/response", this.address));
}
static ValhallaSkinServer from(String server) {
Matcher matcher = Pattern.compile("^valhalla:(.*)$").matcher(server);
if (matcher.find()) {
return new ValhallaSkinServer(matcher.group(1));
}
throw new IllegalArgumentException();
@Override
public String toString() {
return new ToStringBuilder(this, IndentedToStringStyle.INSTANCE)
.append("address", this.address)
.toString();
}
@SuppressWarnings("WeakerAccess")

View file

@ -7,6 +7,7 @@ import com.minelittlepony.pony.data.PonyDataSerialzier;
import com.minelittlepony.render.PonySkullRenderer;
import com.mumfrey.liteloader.core.LiteLoader;
import com.voxelmodpack.hdskins.HDSkinManager;
import com.voxelmodpack.hdskins.skins.LegacySkinServer;
import com.voxelmodpack.hdskins.skins.SkinServer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.RenderManager;
@ -27,7 +28,8 @@ public class MineLittlePony {
public static final String MOD_NAME = "Mine Little Pony";
public static final String MOD_VERSION = "@VERSION@";
private static final String MINELP_LEGACY_SERVER = "legacy:http://minelpskins.voxelmodpack.com;http://minelpskinmanager.voxelmodpack.com";
private static final String MINELP_LEGACY_SERVER = "http://minelpskins.voxelmodpack.com";
private static final String MINELP_LEGACY_GATEWAY = "http://minelpskinmanager.voxelmodpack.com";
private static final KeyBinding SETTINGS_GUI = new KeyBinding("Settings", Keyboard.KEY_F9, "Mine Little Pony");
@ -57,7 +59,7 @@ public class MineLittlePony {
ms.registerMetadataSectionType(new PonyDataSerialzier(), IPonyData.class);
// This also makes it the default gateway server.
SkinServer.defaultServers.add(MINELP_LEGACY_SERVER);
SkinServer.defaultServers.add(new LegacySkinServer(MINELP_LEGACY_SERVER, MINELP_LEGACY_GATEWAY));
}
/**