Support 1.20.2. (#266)

This commit is contained in:
ZekerZhayard authored and GitHub committed 2023-09-28 20:49:25 +08:00
1 parent d5ae6226ae
commit b8ca913848
27 files changed
+830 -446

No files matched your search

@@ -8,7 +8,7 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
@@ -49,8 +49,7 @@ public class CustomSkinLoader {
private static final ProfileCache profileCache = new ProfileCache();
private static final DynamicSkullManager dynamicSkullManager = new DynamicSkullManager();
private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(
config.threadPoolSize, config.threadPoolSize, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>());
public static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(config.threadPoolSize, config.threadPoolSize, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>());
//Correct thread name in thread pool
private static final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
@@ -71,26 +70,28 @@ public class CustomSkinLoader {
THREAD_POOL.execute(runnable);
}
public static void loadProfileLazily(
GameProfile gameProfile, Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>> consumer) {
public static Object loadProfileLazily(GameProfile gameProfile, Function<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>, ?> function) {
String username = gameProfile.getName();
String credential = MinecraftUtil.getCredential(gameProfile);
// Fix: http://hopper.minecraft.net/crashes/minecraft/MCX-2773713
if (username == null) {
logger.warning("Could not load profile: username is null.");
consumer.accept(Maps.newHashMap());
return;
return function.apply(Maps.newHashMap());
}
String tempName = Thread.currentThread().getName();
Thread.currentThread().setName(username); // Change Thread Name
if (profileCache.isLoading(credential)) {
profileCache.putLoader(credential, consumer);
profileCache.putLoader(credential, function);
Thread.currentThread().setName(tempName);
return;
return function.apply(Maps.newHashMap());
}
consumer.accept(loadProfile(gameProfile));
Object result = function.apply(loadProfile(gameProfile));
Thread.currentThread().setName(tempName);
profileCache.getLastLoader(credential).ifPresent(c -> loadProfileLazily(gameProfile, c));
Function<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>, ?> func = profileCache.getLastLoader(credential);
if (func != null) {
result = loadProfileLazily(gameProfile, func);
}
return result;
}
//For User Skin
@@ -194,8 +195,7 @@ public class CustomSkinLoader {
}
//For Skull
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadProfileFromCache(
final GameProfile gameProfile) {
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadProfileFromCache(final GameProfile gameProfile) {
String username = gameProfile.getName();
String credential = MinecraftUtil.getCredential(gameProfile);
@@ -230,12 +230,9 @@ public class CustomSkinLoader {
Logger logger = LogManager.getLogger("Core");
logger.info("CustomSkinLoader " + CustomSkinLoader_FULL_VERSION);
logger.info("DataDir: " + DATA_DIR.getAbsolutePath());
logger.info("Operating System: " + System.getProperty("os.name") +
" (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version"));
logger.info("Java Version: " + System.getProperty("java.version") +
", " + System.getProperty("java.vendor"));
logger.info("Java VM Version: " + System.getProperty("java.vm.name") +
" (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor"));
logger.info("Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version"));
logger.info("Java Version: " + System.getProperty("java.version") + ", " + System.getProperty("java.vendor"));
logger.info("Java VM Version: " + System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor"));
logger.info("Minecraft: " + MinecraftUtil.getMinecraftMainVersion());
return logger;
}
@@ -2,19 +2,20 @@ package customskinloader.fake;
import java.io.File;
import java.util.Map;
import java.util.Optional;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.utils.HttpTextureUtil;
import net.minecraft.util.ResourceLocation;
public class FakeMinecraftProfileTexture extends MinecraftProfileTexture {
private HttpTextureUtil.HttpTextureInfo info;
private final HttpTextureUtil.HttpTextureInfo info;
private final Map<String, String> metadata;
private ResourceLocation resourceLocation;
public FakeMinecraftProfileTexture(String url, Map<String, String> metadata) {
super(url, metadata);
this.info = HttpTextureUtil.toHttpTextureInfo(url);
this.metadata = metadata;
}
public void setResourceLocation(ResourceLocation resourceLocation) {
@@ -30,8 +31,10 @@ public class FakeMinecraftProfileTexture extends MinecraftProfileTexture {
return this.info.url;
}
public String getRawUrl() {
return super.getUrl();
public void setModule(String module) {
if (this.metadata != null) {
this.metadata.put("module", module);
}
}
@Override
@@ -2,39 +2,63 @@ package customskinloader.fake;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.properties.Property;
import customskinloader.CustomSkinLoader;
import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.MinecraftUtil;
import net.minecraft.client.renderer.texture.NativeImage;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.NativeImage;
import net.minecraft.client.resources.SkinManager;
import net.minecraft.client.resources.SkinManager.SkinAvailableCallback;
import net.minecraft.util.ResourceLocation;
public class FakeSkinManager {
private final TextureManager textureManager;
private final static Map<ResourceLocation, MinecraftProfileTexture> MODEL_CACHE = new ConcurrentHashMap<>();
private final Map<ResourceLocation, MinecraftProfileTexture> modelCache = new ConcurrentHashMap<>();
public FakeSkinManager(TextureManager textureManagerInstance, File skinCacheDirectory, MinecraftSessionService sessionService) {
this.textureManager = textureManagerInstance;
/**
* Invoked from {@link SkinManager(net.minecraft.client.renderer.texture.TextureManager, File, MinecraftSessionService)}
*/
public static void setSkinCacheDir(File skinCacheDirectory) {
HttpTextureUtil.defaultCacheDir = skinCacheDirectory;
}
/**
* Invoked from {@link SkinManager#loadSkin(MinecraftProfileTexture, MinecraftProfileTexture.Type, SkinAvailableCallback)}
* Invoked from {@link SkinManager(net.minecraft.client.renderer.texture.TextureManager, Path, MinecraftSessionService, java.util.concurrent.Executor)}
*/
public static void setSkinCacheDir(Path skinCacheDirectory) {
HttpTextureUtil.defaultCacheDir = skinCacheDirectory.toFile();
}
private static CacheLoader<Object, ?> cacheLoader;
/**
* Invoked from {@link SkinManager(net.minecraft.client.renderer.texture.TextureManager, Path, MinecraftSessionService, java.util.concurrent.Executor)}
*/
public static CacheLoader<Object, ?> setCacheLoader(CacheLoader<Object, ?> loader) {
return cacheLoader = loader;
}
/**
* Invoked from {@link SkinManager#getOrLoad(GameProfile)}
*/
public static Object loadCache(LoadingCache<?, ?> loadingCache, Object cacheKey) throws Exception {
return cacheLoader.load(cacheKey);
}
/**
* Invoked from {@link SkinManager#loadSkin(MinecraftProfileTexture, MinecraftProfileTexture.Type, SkinManager.SkinAvailableCallback)}
*/
public static ResourceLocation setResourceLocation(ResourceLocation resourceLocation, MinecraftProfileTexture profileTexture) {
if (profileTexture instanceof FakeMinecraftProfileTexture) {
@@ -44,19 +68,19 @@ public class FakeSkinManager {
}
/**
* Invoked from {@link SkinManager#loadSkin(MinecraftProfileTexture, MinecraftProfileTexture.Type, SkinAvailableCallback)}
* Invoked from {@link SkinManager#loadSkin(MinecraftProfileTexture, MinecraftProfileTexture.Type, SkinManager.SkinAvailableCallback)}
* <p>
* {@code skinAvailableCallback.skinAvailable(textureType, resourcelocation, profileTexture);} -> {@code skinAvailableCallback.skinAvailable(textureType, resourcelocation, this.fakeManager.getModelCache(profileTexture, resourcelocation));}
* <p>
*/
public static MinecraftProfileTexture getModelCache(MinecraftProfileTexture profileTexture, FakeSkinManager fakeManager, ResourceLocation location) {
return fakeManager.modelCache.getOrDefault(location, profileTexture);
public static MinecraftProfileTexture getModelCache(MinecraftProfileTexture profileTexture, ResourceLocation location) {
return MODEL_CACHE.getOrDefault(location, profileTexture);
}
/**
* Invoked from {@link SkinManager#loadSkin(MinecraftProfileTexture, MinecraftProfileTexture.Type, SkinAvailableCallback)}
* Invoked from {@link SkinManager#loadSkin(MinecraftProfileTexture, MinecraftProfileTexture.Type, SkinManager.SkinAvailableCallback)}
*/
public static Object[] createThreadDownloadImageData(ImmutableList<Object> list, FakeSkinManager fakeManager, MinecraftProfileTexture profileTexture, MinecraftProfileTexture.Type textureType, SkinManager.SkinAvailableCallback skinAvailableCallback) {
public static Object[] createThreadDownloadImageData(ImmutableList<Object> list, MinecraftProfileTexture profileTexture, MinecraftProfileTexture.Type textureType) {
Object[] params = list.toArray();
if (profileTexture instanceof FakeMinecraftProfileTexture && params.length > 1) {
FakeMinecraftProfileTexture fakeProfileTexture = (FakeMinecraftProfileTexture) profileTexture;
@@ -66,7 +90,7 @@ public class FakeSkinManager {
if (params[params.length - 2] instanceof Boolean) {
params[params.length - 2] = true;
}
params[params.length - 1] = fakeManager.new BaseBuffer(skinAvailableCallback, textureType, resourcelocation, fakeProfileTexture);
params[params.length - 1] = new BaseBuffer((Runnable) params[params.length - 1], textureType, resourcelocation, fakeProfileTexture);
}
}
return params;
@@ -75,7 +99,7 @@ public class FakeSkinManager {
private final static String KEY = "CustomSkinLoaderInfo";
/**
* Invoked from {@link SkinManager#loadProfileTextures(GameProfile, SkinAvailableCallback, boolean)}
* Invoked from {@link SkinManager#loadProfileTextures(GameProfile, SkinManager.SkinAvailableCallback, boolean)}
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void loadProfileTextures(Runnable runnable, GameProfile profile) {
@@ -83,9 +107,31 @@ public class FakeSkinManager {
// This is a hack.
((Multimap) profile.getProperties()).put(KEY, m);
runnable.run();
return null;
}));
}
/**
* 23w31a+
* Invoked from net.minecraft.client.resources.SkinManager$1#load(net.minecraft.client.resources.SkinManager$CacheKey, GameProfile)
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object[] loadProfileTextures(ImmutableList<Object> list, GameProfile profile) {
Object[] params = list.toArray();
if (!profile.getProperties().containsKey(SKULL_KEY)) {
final Supplier<?> supplier = (Supplier<?>) params[0];
params[0] = (Supplier<?>) () -> CustomSkinLoader.loadProfileLazily(profile, m -> {
// This is a hack.
((Multimap) profile.getProperties()).put(KEY, m);
return supplier.get();
});
params[1] = CustomSkinLoader.THREAD_POOL;
} else {
params[1] = Minecraft.getMinecraft();
}
return params;
}
/**
* Invoked from {@link SkinManager#lambda$loadProfileTextures$1(GameProfile, boolean, SkinAvailableCallback)}
*/
@@ -107,74 +153,80 @@ public class FakeSkinManager {
}
}
public Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadSkinFromCache(GameProfile profile) {
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = CustomSkinLoader.loadProfileFromCache(profile);
for (Iterator<Map.Entry<MinecraftProfileTexture.Type, MinecraftProfileTexture>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<MinecraftProfileTexture.Type, MinecraftProfileTexture> entry = it.next();
MinecraftProfileTexture texture = entry.getValue();
if (shouldJudgeType(texture)) {
texture = this.modelCache.get(MinecraftUtil.getSkinManager().loadSkin(texture, entry.getKey()));
if (texture == null) { // remove texture if was not loaded before
it.remove();
} else {
map.put(entry.getKey(), texture);
}
}
}
return map;
private final static String SKULL_KEY = "CSL$IsSkull";
/**
* 23w31a+
* Invoked from {@link SkinManager#getInsecureSkin(GameProfile)}
*/
public static void setSkullType(GameProfile profile) {
profile.getProperties().removeAll(SKULL_KEY);
profile.getProperties().put(SKULL_KEY, new Property(SKULL_KEY, "true"));
}
private static void makeCallback(SkinManager.SkinAvailableCallback callback, MinecraftProfileTexture.Type type, ResourceLocation location, MinecraftProfileTexture texture) {
if (callback != null)
callback.skinAvailable(type, location, texture);
/**
* 23w31a+
* Invoked from net.minecraft.client.resources.SkinManager$1#lambda$load$0(GameProfile)
*/
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadSkinFromCache(MinecraftSessionService sessionService, GameProfile profile, boolean requireSecure) {
if (profile.getProperties().containsKey(SKULL_KEY)) {
profile.getProperties().removeAll(SKULL_KEY);
return CustomSkinLoader.loadProfileFromCache(profile);
} else {
return getUserProfile(sessionService, profile, requireSecure);
}
}
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadSkinFromCache(GameProfile profile) {
return CustomSkinLoader.loadProfileFromCache(profile);
}
private static boolean shouldJudgeType(MinecraftProfileTexture texture) {
return texture != null && "auto".equals(texture.getMetadata("model"));
}
private class BaseBuffer implements IImageBuffer {
private static class BaseBuffer implements IImageBuffer {
private IImageBuffer buffer;
private SkinManager.SkinAvailableCallback callback;
private MinecraftProfileTexture.Type type;
private ResourceLocation location;
private FakeMinecraftProfileTexture texture;
private final Runnable callback;
private final ResourceLocation location;
private final FakeMinecraftProfileTexture texture;
public BaseBuffer(SkinManager.SkinAvailableCallback callback, MinecraftProfileTexture.Type type, ResourceLocation location, FakeMinecraftProfileTexture texture) {
public BaseBuffer(Runnable callback, MinecraftProfileTexture.Type type, ResourceLocation location, FakeMinecraftProfileTexture texture) {
switch (type) {
case SKIN: this.buffer = new FakeSkinBuffer(); break;
case CAPE: this.buffer = new FakeCapeBuffer(location); break;
}
this.callback = callback;
this.type = type;
this.location = location;
this.texture = texture;
}
@Override
public NativeImage func_195786_a(NativeImage image) {
return buffer instanceof FakeSkinBuffer ? ((FakeSkinBuffer) buffer).func_195786_a(image) : image;
}
@Override
public BufferedImage parseUserSkin(BufferedImage image) {
return buffer instanceof FakeSkinBuffer ? ((FakeSkinBuffer) buffer).parseUserSkin(image) : image;
}
@Override
public void skinAvailable() {
if (buffer != null) {
buffer.skinAvailable();
if (shouldJudgeType(texture) && buffer instanceof FakeSkinBuffer) {
//Auto judge skin type
Map<String, String> metadata = Maps.newHashMap();
String type = ((FakeSkinBuffer) buffer).judgeType();
metadata.put("model", type);
texture = new FakeMinecraftProfileTexture(texture.getRawUrl(), metadata);
FakeSkinManager.this.modelCache.put(location, texture);
texture.setModule(type);
MODEL_CACHE.put(location, texture);
}
}
FakeSkinManager.makeCallback(callback, type, location, texture);
if (this.callback != null) {
this.callback.run();
}
}
}
}
@@ -0,0 +1,10 @@
package customskinloader.fake.itf;
import net.minecraft.client.renderer.IImageBuffer;
public interface IFakeIImageBuffer extends Runnable {
@Override
default void run() {
((IImageBuffer) this).skinAvailable();
}
}
@@ -25,6 +25,7 @@ import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.TextureUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
@@ -111,8 +112,7 @@ public class MojangAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.I
private static final Map<String, GameProfile> gameProfileCache = new ConcurrentHashMap<>();
public static GameProfile loadGameProfileCached(String apiRoot, String username) {
return gameProfileCache.computeIfAbsent(apiRoot + " " + username,
ignored -> loadGameProfile(apiRoot, username));
return gameProfileCache.computeIfAbsent(apiRoot + " " + username, ignored -> loadGameProfile(apiRoot, username));
}
//Username -> UUID
@@ -120,10 +120,7 @@ public class MojangAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.I
//Doc (https://wiki.vg/Mojang_API#Playernames_-.3E_UUIDs)
Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(
new HttpRequestUtil.HttpRequest(apiRoot + "profiles/minecraft")
.setCacheTime(600).setPayload(gson.toJson(Collections.singletonList(username)))
);
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(apiRoot + "profiles/minecraft").setCacheTime(600).setPayload(gson.toJson(Collections.singletonList(username))));
if (StringUtils.isEmpty(responce.content)) {
return null;
}
@@ -153,23 +150,18 @@ public class MojangAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.I
return null;
}
UUID id = profile.getId();
return standard ? id.toString() : UUIDTypeAdapter.fromUUID(id);
return standard ? id.toString() : TextureUtil.fromUUID(id);
}
//UUID -> Profile
public static GameProfile fillGameProfile(String sessionRoot, GameProfile profile) {
//Doc (http://wiki.vg/Mojang_API#UUID_-.3E_Profile_.2B_Skin.2FCape)
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(
new HttpRequestUtil.HttpRequest(sessionRoot + "session/minecraft/profile/"
+ UUIDTypeAdapter.fromUUID(profile.getId())).setCacheTime(90));
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(sessionRoot + "session/minecraft/profile/" + TextureUtil.fromUUID(profile.getId())).setCacheTime(90));
if (StringUtils.isEmpty(responce.content)) {
return profile;
}
Gson gson = new GsonBuilder()
.registerTypeAdapter(UUID.class, new UUIDTypeAdapter())
.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer())
.create();
Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create();
MinecraftProfilePropertiesResponse propertiesResponce = gson.fromJson(responce.content, MinecraftProfilePropertiesResponse.class);
GameProfile newGameProfile = new GameProfile(propertiesResponce.getId(), propertiesResponce.getName());
newGameProfile.getProperties().putAll(propertiesResponce.getProperties());
@@ -185,23 +177,23 @@ public class MojangAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.I
if (textureProperty == null) {
return Maps.newHashMap();
}
String value = textureProperty.getValue();
String value = TextureUtil.getPropertyValue(textureProperty);
if (StringUtils.isBlank(value)) {
return Maps.newHashMap();
}
String json = new String(Base64.decodeBase64(value), StandardCharsets.UTF_8);
Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
MinecraftTexturesPayload result = gson.fromJson(json, MinecraftTexturesPayload.class);
if (result == null || result.getTextures() == null) {
if (result == null || TextureUtil.getMinecraftTexturesPayloadTextures(result) == null) {
return Maps.newHashMap();
}
return result.getTextures();
return TextureUtil.getMinecraftTexturesPayloadTextures(result);
}
@Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return (!StringUtils.isNoneEmpty(ssp0.apiRoot) || ssp0.apiRoot.equalsIgnoreCase(ssp1.apiRoot)) ||
(!StringUtils.isNoneEmpty(ssp0.sessionRoot) || ssp0.sessionRoot.equalsIgnoreCase(ssp1.sessionRoot));
return (!StringUtils.isNoneEmpty(ssp0.apiRoot) || ssp0.apiRoot.equalsIgnoreCase(ssp1.apiRoot)) || (!StringUtils.isNoneEmpty(ssp0.sessionRoot) || ssp0.sessionRoot.equalsIgnoreCase(ssp1.sessionRoot));
}
@Override
@@ -1,36 +1,35 @@
package customskinloader.profile;
import java.io.File;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.properties.Property;
import com.mojang.util.UUIDTypeAdapter;
import customskinloader.CustomSkinLoader;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpUtil0;
import customskinloader.utils.TextureUtil;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import com.mojang.authlib.properties.Property;
import com.mojang.util.UUIDTypeAdapter;
import customskinloader.CustomSkinLoader;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpRequestUtil.HttpRequest;
import customskinloader.utils.HttpRequestUtil.HttpResponce;
import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpUtil0;
public class DynamicSkullManager {
public static class SkullTexture{
public Map<Type,MinecraftProfileTexture> textures;
public static class SkullTexture {
public Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures;
public String index;//Index File
public ArrayList<String> skins;
public int interval;
@@ -39,121 +38,119 @@ public class DynamicSkullManager {
public long startTime;
public int period;
}
private Map<GameProfile, SkullTexture> dynamicTextures = new ConcurrentHashMap<>();
private Map<GameProfile, Map<Type, MinecraftProfileTexture>> staticTextures = new ConcurrentHashMap<>();
private List<GameProfile> loadingList=new ArrayList<GameProfile>();
private void parseGameProfile(GameProfile profile){
private Map<GameProfile, Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>> staticTextures = new ConcurrentHashMap<>();
private List<GameProfile> loadingList = Lists.newArrayList();
private void parseGameProfile(GameProfile profile) {
Property textureProperty = Iterables.getFirst(profile.getProperties().get("textures"), null);
if (textureProperty==null){
staticTextures.put(profile, Maps.<Type, MinecraftProfileTexture>newHashMap());
if (textureProperty == null) {
staticTextures.put(profile, Maps.newHashMap());
return;
}
String value=textureProperty.getValue();
if(StringUtils.isBlank(value)){
staticTextures.put(profile, Maps.<Type, MinecraftProfileTexture>newHashMap());
String value = TextureUtil.getPropertyValue(textureProperty);
if (StringUtils.isBlank(value)) {
staticTextures.put(profile, Maps.newHashMap());
return;
}
@SuppressWarnings("deprecation") String json = new String(Base64.decodeBase64(value), Charsets.UTF_8);
Gson gson=new GsonBuilder().registerTypeAdapter(UUID.class,new UUIDTypeAdapter()).create();
SkullTexture result=gson.fromJson(json,SkullTexture.class);
if(result==null){
staticTextures.put(profile, Maps.<Type, MinecraftProfileTexture>newHashMap());
Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
SkullTexture result = gson.fromJson(json, SkullTexture.class);
if (result == null) {
staticTextures.put(profile, Maps.newHashMap());
return;
}
staticTextures.put(profile, (result.textures==null || !result.textures.containsKey(Type.SKIN)) ?
Maps.<Type, MinecraftProfileTexture>newHashMap() : parseTextures(result.textures));
if(StringUtils.isNotEmpty(result.index)){
File indexFile=new File(CustomSkinLoader.DATA_DIR,result.index);
try{
String index=FileUtils.readFileToString(indexFile, "UTF-8");
if(StringUtils.isNotEmpty(index)){
staticTextures.put(profile, (result.textures == null || !result.textures.containsKey(MinecraftProfileTexture.Type.SKIN)) ? Maps.newHashMap() : parseTextures(result.textures));
if (StringUtils.isNotEmpty(result.index)) {
File indexFile = new File(CustomSkinLoader.DATA_DIR, result.index);
try {
String index = FileUtils.readFileToString(indexFile, "UTF-8");
if (StringUtils.isNotEmpty(index)) {
String[] skins = CustomSkinLoader.GSON.fromJson(index, String[].class);
if(skins != null && skins.length != 0)
if (skins != null && skins.length != 0)
result.skins = Lists.newArrayList(skins);
}
}catch(Exception e){
CustomSkinLoader.logger.warning("Exception occurs while parsing index file: "+e.toString());
} catch (Exception e) {
CustomSkinLoader.logger.warning("Exception occurs while parsing index file: " + e.toString());
}
}
if(!CustomSkinLoader.config.enableDynamicSkull||result.skins==null||result.skins.isEmpty())
if (!CustomSkinLoader.config.enableDynamicSkull || result.skins == null || result.skins.isEmpty())
return;
CustomSkinLoader.logger.info("Try to load Dynamic Skull: "+json);
for(int i=0;i<result.skins.size();i++){//check and cache skins
String skin=result.skins.get(i);
if(HttpUtil0.isLocal(skin)){
CustomSkinLoader.logger.info("Try to load Dynamic Skull: " + json);
for (int i = 0; i < result.skins.size(); i++) {//check and cache skins
String skin = result.skins.get(i);
if (HttpUtil0.isLocal(skin)) {
//Local Skin
File skinFile=new File(CustomSkinLoader.DATA_DIR,skin);
if(skinFile.isFile()&&skinFile.length()>0){
File skinFile = new File(CustomSkinLoader.DATA_DIR, skin);
if (skinFile.isFile() && skinFile.length() > 0) {
//Skin found
String fakeUrl=HttpTextureUtil.getLocalFakeUrl(skin);
String fakeUrl = HttpTextureUtil.getLocalFakeUrl(skin);
result.skins.set(i, fakeUrl);
}else{
} else {
//Could not find skin
result.skins.remove(i--);
}
}else{
} else {
//Online Skin
HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(skin).setCacheFile(HttpTextureUtil.getCacheFile(FilenameUtils.getBaseName(skin))).setCacheTime(0).setLoadContent(false));
if(!responce.success){
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(skin).setCacheFile(HttpTextureUtil.getCacheFile(FilenameUtils.getBaseName(skin))).setCacheTime(0).setLoadContent(false));
if (!responce.success) {
//Could not load skin
result.skins.remove(i--);
}
}
}
if(result.skins.isEmpty()){//Nothing loaded
if (result.skins.isEmpty()) {//Nothing loaded
CustomSkinLoader.logger.info("Failed: Nothing loaded.");
return;
}
result.interval=Math.max(result.interval, 50);
if(result.fromZero)
result.startTime=System.currentTimeMillis();
result.period=result.interval*result.skins.size();
CustomSkinLoader.logger.info("Successfully loaded Dynamic Skull: "+new Gson().toJson(result));
result.interval = Math.max(result.interval, 50);
if (result.fromZero)
result.startTime = System.currentTimeMillis();
result.period = result.interval * result.skins.size();
CustomSkinLoader.logger.info("Successfully loaded Dynamic Skull: " + new Gson().toJson(result));
dynamicTextures.put(profile, result);
staticTextures.remove(profile);
}
//Support local skin for skull
public Map<Type, MinecraftProfileTexture> parseTextures(Map<Type, MinecraftProfileTexture> textures) {
MinecraftProfileTexture skin=textures.get(Type.SKIN);
String skinUrl=skin.getUrl();
if(!HttpUtil0.isLocal(skinUrl))
public Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> parseTextures(Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures) {
MinecraftProfileTexture skin = textures.get(MinecraftProfileTexture.Type.SKIN);
String skinUrl = skin.getUrl();
if (!HttpUtil0.isLocal(skinUrl))
return textures;
File skinFile=new File(CustomSkinLoader.DATA_DIR,skinUrl);
if(!skinFile.isFile())
File skinFile = new File(CustomSkinLoader.DATA_DIR, skinUrl);
if (!skinFile.isFile())
return Maps.newHashMap();
textures.put(Type.SKIN, ModelManager0.getProfileTexture(HttpTextureUtil.getLocalFakeUrl(skinUrl), null));
textures.put(MinecraftProfileTexture.Type.SKIN, ModelManager0.getProfileTexture(HttpTextureUtil.getLocalFakeUrl(skinUrl), null));
return textures;
}
public Map<Type,MinecraftProfileTexture> getTexture(final GameProfile profile){
if(staticTextures.get(profile)!=null)
public Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getTexture(final GameProfile profile) {
if (staticTextures.get(profile) != null)
return staticTextures.get(profile);
if(loadingList.contains(profile))
if (loadingList.contains(profile))
return Maps.newHashMap();
if(dynamicTextures.containsKey(profile)){
SkullTexture texture=dynamicTextures.get(profile);
long time=System.currentTimeMillis()-texture.startTime;
int index=(int)Math.floor((time%texture.period)/texture.interval);
Map<Type,MinecraftProfileTexture> map=Maps.newHashMap();
map.put(Type.SKIN, ModelManager0.getProfileTexture(texture.skins.get(index), null));
if (dynamicTextures.containsKey(profile)) {
SkullTexture texture = dynamicTextures.get(profile);
long time = System.currentTimeMillis() - texture.startTime;
int index = (int) Math.floor((time % texture.period) / texture.interval);
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = Maps.newHashMap();
map.put(MinecraftProfileTexture.Type.SKIN, ModelManager0.getProfileTexture(texture.skins.get(index), null));
return map;
}
loadingList.add(profile);
Thread loadThread=new Thread(){
public void run(){
parseGameProfile(profile);//Load in thread
loadingList.remove(profile);
}
};
loadThread.setName("Skull "+profile.hashCode());
Thread loadThread = new Thread(() -> {
parseGameProfile(profile);//Load in thread
loadingList.remove(profile);
});
loadThread.setName("Skull " + profile.hashCode());
loadThread.start();
return Maps.newHashMap();
}
@@ -3,10 +3,9 @@ package customskinloader.profile;
import java.io.File;
import java.util.Deque;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.function.Consumer;
import java.util.function.Function;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.CustomSkinLoader;
@@ -18,7 +17,7 @@ public class ProfileCache {
private Map<String, CachedProfile> cachedProfiles = new ConcurrentHashMap<>();
private Map<String, UserProfile> localProfiles = new ConcurrentHashMap<>();
private Map<String, Deque<Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>>>> profileLoaders = new ConcurrentHashMap<>();
private Map<String, Deque<Function<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>, ?>>> profileLoaders = new ConcurrentHashMap<>();
@SuppressWarnings("ResultOfMethodCallIgnored")
public ProfileCache(){
@@ -53,12 +52,12 @@ public class ProfileCache {
return localProfiles.get(username.toLowerCase());
return loadLocalProfile(username);
}
public Optional<Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>>> getLastLoader(String username) {
Deque<Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>>> deque = this.profileLoaders.get(username);
public Function<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>, ?> getLastLoader(String username) {
Deque<Function<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>, ?>> deque = this.profileLoaders.get(username);
if (deque != null) {
return Optional.ofNullable(deque.pollLast());
return deque.pollLast();
}
return Optional.empty();
return null;
}
public void setLoading(String username,boolean loading){
@@ -75,7 +74,7 @@ public class ProfileCache {
return;
saveLocalProfile(username,profile);
}
public void putLoader(String username, Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>> loader) {
public void putLoader(String username, Function<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>, ?> loader) {
this.profileLoaders.putIfAbsent(username, new ConcurrentLinkedDeque<>());
this.profileLoaders.get(username).offerLast(loader);
}
@@ -1,11 +1,17 @@
package customskinloader.utils;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.UUID;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.yggdrasil.response.MinecraftTexturesPayload;
import customskinloader.CustomSkinLoader;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class TextureUtil {
/**
* Save and get fake url of base64 texture
@@ -30,4 +36,42 @@ public class TextureUtil {
return null;
}
}
// Some of the classes in Authlib used after Minecraft 23w31a were changed to record classes,
// resulting in changes to method names, so reflection is used here to be compatible with these changes.
private final static Field VALUE_FIELD;
private final static Field TEXTURES_FIELD;
static {
try {
VALUE_FIELD = Property.class.getDeclaredField("value");
VALUE_FIELD.setAccessible(true);
TEXTURES_FIELD = MinecraftTexturesPayload.class.getDeclaredField("textures");
TEXTURES_FIELD.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String getPropertyValue(Property property) {
try {
return (String) VALUE_FIELD.get(property);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getMinecraftTexturesPayloadTextures(MinecraftTexturesPayload payload) {
try {
return (Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>) TEXTURES_FIELD.get(payload);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String fromUUID(UUID value) {
return value.toString().replace("-", "");
}
}
@@ -2,17 +2,13 @@ package net.minecraft.client.renderer;
import java.awt.image.BufferedImage;
import customskinloader.fake.itf.IFakeIImageBuffer;
import net.minecraft.client.renderer.texture.NativeImage;
public interface IImageBuffer extends Runnable {
public interface IImageBuffer extends IFakeIImageBuffer {
BufferedImage parseUserSkin(BufferedImage image);
NativeImage func_195786_a(NativeImage image);
void skinAvailable();
@Override
default void run() {
this.skinAvailable();
}
}