diff --git a/1.12-mcp940/src/minecraft/net/minecraft/client/gui/GuiPlayerTabOverlay.java b/1.12-mcp940/src/minecraft/net/minecraft/client/gui/GuiPlayerTabOverlay.java index aed4ba7..e4c6d43 100644 --- a/1.12-mcp940/src/minecraft/net/minecraft/client/gui/GuiPlayerTabOverlay.java +++ b/1.12-mcp940/src/minecraft/net/minecraft/client/gui/GuiPlayerTabOverlay.java @@ -97,7 +97,7 @@ public class GuiPlayerTabOverlay extends Gui } //boolean flag = this.mc.isIntegratedServerRunning() || this.mc.getConnection().getNetworkManager().isEncrypted(); - boolean flag = true;//Modified + boolean flag = true;//Modified int l; if (scoreObjectiveIn != null) diff --git a/1.12-mcp940/src/minecraft/net/minecraft/client/gui/spectator/PlayerMenuObject.java b/1.12-mcp940/src/minecraft/net/minecraft/client/gui/spectator/PlayerMenuObject.java index 8a464a6..3896709 100644 --- a/1.12-mcp940/src/minecraft/net/minecraft/client/gui/spectator/PlayerMenuObject.java +++ b/1.12-mcp940/src/minecraft/net/minecraft/client/gui/spectator/PlayerMenuObject.java @@ -21,11 +21,11 @@ public class PlayerMenuObject implements ISpectatorMenuObject public PlayerMenuObject(GameProfile profileIn) { this.profile = profileIn; - /* + /* this.resourceLocation = AbstractClientPlayer.getLocationSkin(profileIn.getName()); AbstractClientPlayer.getDownloadImageSkin(this.resourceLocation, profileIn.getName()); - */ - this.resourceLocation = customskinloader.fake.FakeClientPlayer.getLocationSkin(profileIn.getName()); + */ + this.resourceLocation = customskinloader.fake.FakeClientPlayer.getLocationSkin(profileIn.getName()); customskinloader.fake.FakeClientPlayer.getDownloadImageSkin(this.resourceLocation, profileIn.getName()); } diff --git a/1.12-mcp940/src/minecraft/net/minecraft/client/resources/SkinManager.java b/1.12-mcp940/src/minecraft/net/minecraft/client/resources/SkinManager.java index e60b05f..ca4aa01 100644 --- a/1.12-mcp940/src/minecraft/net/minecraft/client/resources/SkinManager.java +++ b/1.12-mcp940/src/minecraft/net/minecraft/client/resources/SkinManager.java @@ -70,7 +70,7 @@ public class SkinManager */ public ResourceLocation loadSkin(final MinecraftProfileTexture profileTexture, final Type textureType, @Nullable final SkinManager.SkinAvailableCallback skinAvailableCallback) { - return this.fakeManager.loadSkin(profileTexture, textureType, skinAvailableCallback); + return this.fakeManager.loadSkin(profileTexture, textureType, skinAvailableCallback); } public void loadProfileTextures(final GameProfile profile, final SkinManager.SkinAvailableCallback skinAvailableCallback, final boolean requireSecure) diff --git a/1.12.1-test/src/minecraft/net/minecraft/client/gui/GuiPlayerTabOverlay.java b/1.12.1-test/src/minecraft/net/minecraft/client/gui/GuiPlayerTabOverlay.java index aed4ba7..e4c6d43 100644 --- a/1.12.1-test/src/minecraft/net/minecraft/client/gui/GuiPlayerTabOverlay.java +++ b/1.12.1-test/src/minecraft/net/minecraft/client/gui/GuiPlayerTabOverlay.java @@ -97,7 +97,7 @@ public class GuiPlayerTabOverlay extends Gui } //boolean flag = this.mc.isIntegratedServerRunning() || this.mc.getConnection().getNetworkManager().isEncrypted(); - boolean flag = true;//Modified + boolean flag = true;//Modified int l; if (scoreObjectiveIn != null) diff --git a/1.12.1-test/src/minecraft/net/minecraft/client/gui/spectator/PlayerMenuObject.java b/1.12.1-test/src/minecraft/net/minecraft/client/gui/spectator/PlayerMenuObject.java index 8a464a6..3896709 100644 --- a/1.12.1-test/src/minecraft/net/minecraft/client/gui/spectator/PlayerMenuObject.java +++ b/1.12.1-test/src/minecraft/net/minecraft/client/gui/spectator/PlayerMenuObject.java @@ -21,11 +21,11 @@ public class PlayerMenuObject implements ISpectatorMenuObject public PlayerMenuObject(GameProfile profileIn) { this.profile = profileIn; - /* + /* this.resourceLocation = AbstractClientPlayer.getLocationSkin(profileIn.getName()); AbstractClientPlayer.getDownloadImageSkin(this.resourceLocation, profileIn.getName()); - */ - this.resourceLocation = customskinloader.fake.FakeClientPlayer.getLocationSkin(profileIn.getName()); + */ + this.resourceLocation = customskinloader.fake.FakeClientPlayer.getLocationSkin(profileIn.getName()); customskinloader.fake.FakeClientPlayer.getDownloadImageSkin(this.resourceLocation, profileIn.getName()); } diff --git a/1.12.1-test/src/minecraft/net/minecraft/client/resources/SkinManager.java b/1.12.1-test/src/minecraft/net/minecraft/client/resources/SkinManager.java index 35e2015..c06aedb 100644 --- a/1.12.1-test/src/minecraft/net/minecraft/client/resources/SkinManager.java +++ b/1.12.1-test/src/minecraft/net/minecraft/client/resources/SkinManager.java @@ -71,7 +71,7 @@ public class SkinManager */ public ResourceLocation loadSkin(final MinecraftProfileTexture profileTexture, final Type textureType, @Nullable final SkinManager.SkinAvailableCallback skinAvailableCallback) { - return this.fakeManager.loadSkin(profileTexture, textureType, skinAvailableCallback); + return this.fakeManager.loadSkin(profileTexture, textureType, skinAvailableCallback); } public void loadProfileTextures(final GameProfile profile, final SkinManager.SkinAvailableCallback skinAvailableCallback, final boolean requireSecure) diff --git a/Common/source/customskinloader/CustomSkinLoader.java b/Common/source/customskinloader/CustomSkinLoader.java index 83530c2..7176edf 100644 --- a/Common/source/customskinloader/CustomSkinLoader.java +++ b/Common/source/customskinloader/CustomSkinLoader.java @@ -25,153 +25,153 @@ import customskinloader.utils.MinecraftUtil; * @version @MOD_FULL_VERSION@ */ public class CustomSkinLoader { - public static final String CustomSkinLoader_VERSION="@MOD_VERSION@"; - public static final String CustomSkinLoader_FULL_VERSION="@MOD_FULL_VERSION@"; - - public static final File DATA_DIR=new File(MinecraftUtil.getMinecraftDataDir(),"CustomSkinLoader"), - LOG_FILE=new File(DATA_DIR,"CustomSkinLoader.log"), - CONFIG_FILE=new File(DATA_DIR,"CustomSkinLoader.json"); - public static final SkinSiteProfile[] DEFAULT_LOAD_LIST={ - SkinSiteProfile.createMojangAPI("Mojang"), - SkinSiteProfile.createCustomSkinAPI("LittleSkin","https://mcskin.littleservice.cn/"), - SkinSiteProfile.createCustomSkinAPI("BlessingSkin","http://skin.prinzeugen.net/"), - //OneSkin has been removed temporarily - //SkinSiteProfile.createCustomSkinAPI("OneSkin","http://fleey.cn/skin/skin_user/skin_json.php/"), - //Minecrack could not load skin correctly - //SkinSiteProfile.creatLegacy("Minecrack","http://minecrack.fr.nf/mc/skinsminecrackd/{USERNAME}.png","http://minecrack.fr.nf/mc/cloaksminecrackd/{USERNAME}.png",null), - SkinSiteProfile.createUniSkinAPI("SkinMe","http://www.skinme.cc/uniskin/"), - SkinSiteProfile.createLegacy("LocalSkin","LocalSkin/skins/{USERNAME}.png","LocalSkin/capes/{USERNAME}.png","LocalSkin/elytras/{USERNAME}.png")}; - - public static final Gson GSON=new GsonBuilder().setPrettyPrinting().create(); - public static final Logger logger=initLogger(); - public static final Config config=Config.loadConfig0(); - - private static final ProfileCache profileCache=new ProfileCache(); - private static final DynamicSkullManager dynamicSkullManager=new DynamicSkullManager(); - - //For User Skin - public static Map loadProfile(GameProfile gameProfile){ - 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."); - return Maps.newHashMap(); - } - String tempName=Thread.currentThread().getName(); - Thread.currentThread().setName(username);//Change Thread Name - UserProfile profile=null; - if(profileCache.isReady(credential)){ - logger.info("Cached profile will be used."); - profile=profileCache.getProfile(credential); - if(profile==null){ - logger.warning("(!Cached Profile is empty!) Expiry:"+profileCache.getExpiry(credential)); - if(profileCache.isExpired(credential))//force load - profile=loadProfile0(gameProfile); - } - else - logger.info(profile.toString(profileCache.getExpiry(credential))); - }else{ - profileCache.setLoading(credential, true); - profile=loadProfile0(gameProfile); - } - Thread.currentThread().setName(tempName); - return ModelManager0.fromUserProfile(profile); - } - //Core - public static UserProfile loadProfile0(GameProfile gameProfile){ - String username=gameProfile.getName(); - String credential=MinecraftUtil.getCredential(gameProfile); - - profileCache.setLoading(credential, true); - logger.info("Loading "+username+"'s profile."); - if(config.loadlist==null||config.loadlist.isEmpty()){ - logger.info("LoadList is Empty."); - return null; - } - - UserProfile profile0=new UserProfile(); - for(int i=0;i loadProfileFromCache(final GameProfile gameProfile) { - String username=gameProfile.getName(); - String credential=MinecraftUtil.getCredential(gameProfile); - - if(credential==null) - return dynamicSkullManager.getTexture(gameProfile); - if(config.enableUpdateSkull?profileCache.isReady(credential):profileCache.isExist(credential)){ - UserProfile profile=profileCache.getProfile(credential); - return ModelManager0.fromUserProfile(profile); - } - //profileCache.setLoading(username, true); - Thread loadThread=new Thread(){ - public void run(){ - loadProfile0(gameProfile);//Load in thread - } - }; - loadThread.setName(username+"'s skull"); - loadThread.start(); - return Maps.newHashMap(); - } - - private static Logger initLogger() { - Logger logger=new Logger(LOG_FILE); - logger.info("CustomSkinLoader "+CustomSkinLoader_FULL_VERSION); - logger.info("DataDir: "+DATA_DIR.getAbsolutePath()); - logger.info("Minecraft: "+MinecraftUtil.getMinecraftMainVersion()+"("+MinecraftUtil.getMinecraftVersionText()+")"); - return logger; - } + public static final String CustomSkinLoader_VERSION="@MOD_VERSION@"; + public static final String CustomSkinLoader_FULL_VERSION="@MOD_FULL_VERSION@"; + + public static final File DATA_DIR=new File(MinecraftUtil.getMinecraftDataDir(),"CustomSkinLoader"), + LOG_FILE=new File(DATA_DIR,"CustomSkinLoader.log"), + CONFIG_FILE=new File(DATA_DIR,"CustomSkinLoader.json"); + public static final SkinSiteProfile[] DEFAULT_LOAD_LIST={ + SkinSiteProfile.createMojangAPI("Mojang"), + SkinSiteProfile.createCustomSkinAPI("LittleSkin","https://mcskin.littleservice.cn/"), + SkinSiteProfile.createCustomSkinAPI("BlessingSkin","http://skin.prinzeugen.net/"), + //OneSkin has been removed temporarily + //SkinSiteProfile.createCustomSkinAPI("OneSkin","http://fleey.cn/skin/skin_user/skin_json.php/"), + //Minecrack could not load skin correctly + //SkinSiteProfile.creatLegacy("Minecrack","http://minecrack.fr.nf/mc/skinsminecrackd/{USERNAME}.png","http://minecrack.fr.nf/mc/cloaksminecrackd/{USERNAME}.png",null), + SkinSiteProfile.createUniSkinAPI("SkinMe","http://www.skinme.cc/uniskin/"), + SkinSiteProfile.createLegacy("LocalSkin","LocalSkin/skins/{USERNAME}.png","LocalSkin/capes/{USERNAME}.png","LocalSkin/elytras/{USERNAME}.png")}; + + public static final Gson GSON=new GsonBuilder().setPrettyPrinting().create(); + public static final Logger logger=initLogger(); + public static final Config config=Config.loadConfig0(); + + private static final ProfileCache profileCache=new ProfileCache(); + private static final DynamicSkullManager dynamicSkullManager=new DynamicSkullManager(); + + //For User Skin + public static Map loadProfile(GameProfile gameProfile){ + 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."); + return Maps.newHashMap(); + } + String tempName=Thread.currentThread().getName(); + Thread.currentThread().setName(username);//Change Thread Name + UserProfile profile=null; + if(profileCache.isReady(credential)){ + logger.info("Cached profile will be used."); + profile=profileCache.getProfile(credential); + if(profile==null){ + logger.warning("(!Cached Profile is empty!) Expiry:"+profileCache.getExpiry(credential)); + if(profileCache.isExpired(credential))//force load + profile=loadProfile0(gameProfile); + } + else + logger.info(profile.toString(profileCache.getExpiry(credential))); + }else{ + profileCache.setLoading(credential, true); + profile=loadProfile0(gameProfile); + } + Thread.currentThread().setName(tempName); + return ModelManager0.fromUserProfile(profile); + } + //Core + public static UserProfile loadProfile0(GameProfile gameProfile){ + String username=gameProfile.getName(); + String credential=MinecraftUtil.getCredential(gameProfile); + + profileCache.setLoading(credential, true); + logger.info("Loading "+username+"'s profile."); + if(config.loadlist==null||config.loadlist.isEmpty()){ + logger.info("LoadList is Empty."); + return null; + } + + UserProfile profile0=new UserProfile(); + for(int i=0;i loadProfileFromCache(final GameProfile gameProfile) { + String username=gameProfile.getName(); + String credential=MinecraftUtil.getCredential(gameProfile); + + if(credential==null) + return dynamicSkullManager.getTexture(gameProfile); + if(config.enableUpdateSkull?profileCache.isReady(credential):profileCache.isExist(credential)){ + UserProfile profile=profileCache.getProfile(credential); + return ModelManager0.fromUserProfile(profile); + } + //profileCache.setLoading(username, true); + Thread loadThread=new Thread(){ + public void run(){ + loadProfile0(gameProfile);//Load in thread + } + }; + loadThread.setName(username+"'s skull"); + loadThread.start(); + return Maps.newHashMap(); + } + + private static Logger initLogger() { + Logger logger=new Logger(LOG_FILE); + logger.info("CustomSkinLoader "+CustomSkinLoader_FULL_VERSION); + logger.info("DataDir: "+DATA_DIR.getAbsolutePath()); + logger.info("Minecraft: "+MinecraftUtil.getMinecraftMainVersion()+"("+MinecraftUtil.getMinecraftVersionText()+")"); + return logger; + } } diff --git a/Common/source/customskinloader/Logger.java b/Common/source/customskinloader/Logger.java index dfe3e90..ec1b678 100644 --- a/Common/source/customskinloader/Logger.java +++ b/Common/source/customskinloader/Logger.java @@ -8,88 +8,88 @@ import java.text.SimpleDateFormat; import java.util.Date; public class Logger { - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - public enum Level{ - DEBUG("DEBUG",false), - INFO("INFO",true), - WARNING("WARNING",true); - - - String name; - boolean display; - Level(String name,boolean display){ - this.name=name; - this.display=display; - } - public String getName(){ - return name; - } - public boolean display(){ - return display; - } - } - private BufferedWriter writer=null; - public Logger(){ - //Logger isn't created. - } - public Logger(File logFile){ - try { - if(!logFile.getParentFile().exists()){ - logFile.getParentFile().mkdirs(); - } - if(!logFile.exists()) - logFile.createNewFile(); - - writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(logFile), "UTF-8")); - } catch (Exception e) { - e.printStackTrace(); - } - } - public void close(){ - if(writer!=null){ - try { - writer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void log(Level level,String msg){ - if(!level.display()&&writer==null) - return; - StringBuilder sb=new StringBuilder(); - sb.append("[").append(Thread.currentThread().getName()).append(" ").append(level.getName()).append("] "); - sb.append(msg); - if(level.display()) - System.out.println(sb.toString()); - if(writer==null) - return; - try { - StringBuilder sb2=new StringBuilder(); - sb2.append("[").append(DATE_FORMAT.format(new Date())).append("] "); - sb2.append(sb.toString()).append("\r\n"); - writer.write(sb2.toString()); - writer.flush(); - } catch (Exception e) { - e.printStackTrace(); - } - } - public void debug(String msg){ - log(Level.DEBUG,msg); - } - public void info(String msg){ - log(Level.INFO,msg); - } - public void warning(String msg){ - log(Level.WARNING,msg); - } - public void warning(Throwable e){ - log(Level.WARNING,"Exception: "+e.toString()); - StackTraceElement[] stes=e.getStackTrace(); - for(StackTraceElement ste : stes){ - log(Level.WARNING,ste.toString()); - } - } + private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + public enum Level{ + DEBUG("DEBUG",false), + INFO("INFO",true), + WARNING("WARNING",true); + + + String name; + boolean display; + Level(String name,boolean display){ + this.name=name; + this.display=display; + } + public String getName(){ + return name; + } + public boolean display(){ + return display; + } + } + private BufferedWriter writer=null; + public Logger(){ + //Logger isn't created. + } + public Logger(File logFile){ + try { + if(!logFile.getParentFile().exists()){ + logFile.getParentFile().mkdirs(); + } + if(!logFile.exists()) + logFile.createNewFile(); + + writer = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(logFile), "UTF-8")); + } catch (Exception e) { + e.printStackTrace(); + } + } + public void close(){ + if(writer!=null){ + try { + writer.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + public void log(Level level,String msg){ + if(!level.display()&&writer==null) + return; + StringBuilder sb=new StringBuilder(); + sb.append("[").append(Thread.currentThread().getName()).append(" ").append(level.getName()).append("] "); + sb.append(msg); + if(level.display()) + System.out.println(sb.toString()); + if(writer==null) + return; + try { + StringBuilder sb2=new StringBuilder(); + sb2.append("[").append(DATE_FORMAT.format(new Date())).append("] "); + sb2.append(sb.toString()).append("\r\n"); + writer.write(sb2.toString()); + writer.flush(); + } catch (Exception e) { + e.printStackTrace(); + } + } + public void debug(String msg){ + log(Level.DEBUG,msg); + } + public void info(String msg){ + log(Level.INFO,msg); + } + public void warning(String msg){ + log(Level.WARNING,msg); + } + public void warning(Throwable e){ + log(Level.WARNING,"Exception: "+e.toString()); + StackTraceElement[] stes=e.getStackTrace(); + for(StackTraceElement ste : stes){ + log(Level.WARNING,ste.toString()); + } + } } diff --git a/Common/source/customskinloader/config/Config.java b/Common/source/customskinloader/config/Config.java index 5b9db6d..af44d36 100644 --- a/Common/source/customskinloader/config/Config.java +++ b/Common/source/customskinloader/config/Config.java @@ -15,181 +15,181 @@ import customskinloader.utils.HttpTextureUtil; import customskinloader.utils.HttpUtil0; public class Config { - //Program - public String version; - public List loadlist; - - //Function - public boolean enableDynamicSkull=true; - public boolean enableTransparentSkin=true; - public boolean ignoreHttpsCertificate=false; - public boolean forceLoadAllTextures=false; - - //Cache - public int cacheExpiry=10; - public boolean enableUpdateSkull=false; - public boolean enableLocalProfileCache=false; - public boolean enableCacheAutoClean=false; - - - //Init config - public Config(SkinSiteProfile[] loadlist){ - this.version=CustomSkinLoader.CustomSkinLoader_VERSION; - this.loadlist=Arrays.asList(loadlist); - } - - public static Config loadConfig0() { - Config config=loadConfig(); - - //LoadList null checker - if(config.loadlist==null){ - config.loadlist=new ArrayList(); - }else{ - for(int i=0;i configVersion){ - CustomSkinLoader.logger.info("Config File is out of date: "+config.version); - config.version=CustomSkinLoader.CustomSkinLoader_VERSION; - writeConfig(config,true); - } - - return config; - } + //Program + public String version; + public List loadlist; + + //Function + public boolean enableDynamicSkull=true; + public boolean enableTransparentSkin=true; + public boolean ignoreHttpsCertificate=false; + public boolean forceLoadAllTextures=false; + + //Cache + public int cacheExpiry=10; + public boolean enableUpdateSkull=false; + public boolean enableLocalProfileCache=false; + public boolean enableCacheAutoClean=false; + + + //Init config + public Config(SkinSiteProfile[] loadlist){ + this.version=CustomSkinLoader.CustomSkinLoader_VERSION; + this.loadlist=Arrays.asList(loadlist); + } + + public static Config loadConfig0() { + Config config=loadConfig(); + + //LoadList null checker + if(config.loadlist==null){ + config.loadlist=new ArrayList(); + }else{ + for(int i=0;i configVersion){ + CustomSkinLoader.logger.info("Config File is out of date: "+config.version); + config.version=CustomSkinLoader.CustomSkinLoader_VERSION; + writeConfig(config,true); + } + + return config; + } - private static Config loadConfig() { - CustomSkinLoader.logger.info("Config File: "+CustomSkinLoader.CONFIG_FILE.getAbsolutePath()); - if(!CustomSkinLoader.CONFIG_FILE.exists()){ - CustomSkinLoader.logger.info("Config file not found, use default instead."); - return initConfig(); - } - try { - CustomSkinLoader.logger.info("Try to load config."); - String json=FileUtils.readFileToString(CustomSkinLoader.CONFIG_FILE,Charsets.UTF_8); - Config config=CustomSkinLoader.GSON.fromJson(json, Config.class); - CustomSkinLoader.logger.info("Successfully load config."); - return config; - }catch (Exception e) { - CustomSkinLoader.logger.info("Failed to load config, use default instead.("+e.toString()+")"); - File brokenFile=new File(CustomSkinLoader.DATA_DIR,"BROKEN-CustomSkinLoader.json"); - if(brokenFile.exists()) - brokenFile.delete(); - CustomSkinLoader.CONFIG_FILE.renameTo(brokenFile); - return initConfig(); - } - } - - private void loadExtraList(){ - File listAddition=new File(CustomSkinLoader.DATA_DIR,"ExtraList"); - if(!listAddition.isDirectory()){ - listAddition.mkdirs(); - return; - } - List adds=new ArrayList(); - File[] files=listAddition.listFiles(); - for(File file:files){ - if(!file.getName().toLowerCase().endsWith(".json")&&!file.getName().toLowerCase().endsWith(".txt")) - continue; - try { - CustomSkinLoader.logger.info("Try to load Extra List.("+file.getName()+")"); - String json=FileUtils.readFileToString(file,Charsets.UTF_8); - SkinSiteProfile ssp=CustomSkinLoader.GSON.fromJson(json, SkinSiteProfile.class); - CustomSkinLoader.logger.info("Successfully load Extra List."); - file.delete(); - ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase()); - if(loader==null){ - CustomSkinLoader.logger.info("Extra List will be ignore: Type '"+ssp.type+"' is not defined."); - continue; - } - boolean duplicate=false; - for(SkinSiteProfile ssp0:this.loadlist){ - if(!ssp0.type.equalsIgnoreCase(ssp.type)) - continue; - if(loader.compare(ssp0, ssp)){ - duplicate=true; - break; - } - } - if(!duplicate){ - adds.add(ssp); - CustomSkinLoader.logger.info("Successfully apply Extra List.("+ssp.name+")"); - }else{ - CustomSkinLoader.logger.info("Extra List will be ignore: Duplicate.("+ssp.name+")"); - } - }catch (Exception e) { - CustomSkinLoader.logger.info("Failed to load Extra List.("+e.toString()+")"); - } - } - if(adds.size()!=0){ - adds.addAll(this.loadlist); - this.loadlist=adds; - writeConfig(this,true); - } - } - - private void initLocalFolder(){ - for(SkinSiteProfile ssp:this.loadlist){ - ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase()); - if(loader==null) - continue; - loader.initLocalFolder(ssp); - } - } + private static Config loadConfig() { + CustomSkinLoader.logger.info("Config File: "+CustomSkinLoader.CONFIG_FILE.getAbsolutePath()); + if(!CustomSkinLoader.CONFIG_FILE.exists()){ + CustomSkinLoader.logger.info("Config file not found, use default instead."); + return initConfig(); + } + try { + CustomSkinLoader.logger.info("Try to load config."); + String json=FileUtils.readFileToString(CustomSkinLoader.CONFIG_FILE,Charsets.UTF_8); + Config config=CustomSkinLoader.GSON.fromJson(json, Config.class); + CustomSkinLoader.logger.info("Successfully load config."); + return config; + }catch (Exception e) { + CustomSkinLoader.logger.info("Failed to load config, use default instead.("+e.toString()+")"); + File brokenFile=new File(CustomSkinLoader.DATA_DIR,"BROKEN-CustomSkinLoader.json"); + if(brokenFile.exists()) + brokenFile.delete(); + CustomSkinLoader.CONFIG_FILE.renameTo(brokenFile); + return initConfig(); + } + } + + private void loadExtraList(){ + File listAddition=new File(CustomSkinLoader.DATA_DIR,"ExtraList"); + if(!listAddition.isDirectory()){ + listAddition.mkdirs(); + return; + } + List adds=new ArrayList(); + File[] files=listAddition.listFiles(); + for(File file:files){ + if(!file.getName().toLowerCase().endsWith(".json")&&!file.getName().toLowerCase().endsWith(".txt")) + continue; + try { + CustomSkinLoader.logger.info("Try to load Extra List.("+file.getName()+")"); + String json=FileUtils.readFileToString(file,Charsets.UTF_8); + SkinSiteProfile ssp=CustomSkinLoader.GSON.fromJson(json, SkinSiteProfile.class); + CustomSkinLoader.logger.info("Successfully load Extra List."); + file.delete(); + ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase()); + if(loader==null){ + CustomSkinLoader.logger.info("Extra List will be ignore: Type '"+ssp.type+"' is not defined."); + continue; + } + boolean duplicate=false; + for(SkinSiteProfile ssp0:this.loadlist){ + if(!ssp0.type.equalsIgnoreCase(ssp.type)) + continue; + if(loader.compare(ssp0, ssp)){ + duplicate=true; + break; + } + } + if(!duplicate){ + adds.add(ssp); + CustomSkinLoader.logger.info("Successfully apply Extra List.("+ssp.name+")"); + }else{ + CustomSkinLoader.logger.info("Extra List will be ignore: Duplicate.("+ssp.name+")"); + } + }catch (Exception e) { + CustomSkinLoader.logger.info("Failed to load Extra List.("+e.toString()+")"); + } + } + if(adds.size()!=0){ + adds.addAll(this.loadlist); + this.loadlist=adds; + writeConfig(this,true); + } + } + + private void initLocalFolder(){ + for(SkinSiteProfile ssp:this.loadlist){ + ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase()); + if(loader==null) + continue; + loader.initLocalFolder(ssp); + } + } - private static Config initConfig() { - Config config=new Config(CustomSkinLoader.DEFAULT_LOAD_LIST); - writeConfig(config,false); - return config; - } - private static void writeConfig(Config config,boolean update){ - String json=CustomSkinLoader.GSON.toJson(config); - if(CustomSkinLoader.CONFIG_FILE.exists()) - CustomSkinLoader.CONFIG_FILE.delete(); - try { - CustomSkinLoader.CONFIG_FILE.createNewFile(); - FileUtils.write(CustomSkinLoader.CONFIG_FILE, json, Charsets.UTF_8); - CustomSkinLoader.logger.info("Successfully "+(update?"update":"create")+" config."); - } catch (Exception e) { - CustomSkinLoader.logger.info("Failed to "+(update?"update":"create")+" config.("+e.toString()+")"); - } - } + private static Config initConfig() { + Config config=new Config(CustomSkinLoader.DEFAULT_LOAD_LIST); + writeConfig(config,false); + return config; + } + private static void writeConfig(Config config,boolean update){ + String json=CustomSkinLoader.GSON.toJson(config); + if(CustomSkinLoader.CONFIG_FILE.exists()) + CustomSkinLoader.CONFIG_FILE.delete(); + try { + CustomSkinLoader.CONFIG_FILE.createNewFile(); + FileUtils.write(CustomSkinLoader.CONFIG_FILE, json, Charsets.UTF_8); + CustomSkinLoader.logger.info("Successfully "+(update?"update":"create")+" config."); + } catch (Exception e) { + CustomSkinLoader.logger.info("Failed to "+(update?"update":"create")+" config.("+e.toString()+")"); + } + } } diff --git a/Common/source/customskinloader/config/SkinSiteProfile.java b/Common/source/customskinloader/config/SkinSiteProfile.java index fc1f7dc..f5b63fb 100644 --- a/Common/source/customskinloader/config/SkinSiteProfile.java +++ b/Common/source/customskinloader/config/SkinSiteProfile.java @@ -3,62 +3,62 @@ package customskinloader.config; import customskinloader.loader.jsonapi.CustomSkinAPIPlus.CustomSkinAPIPlusPrivacy; public class SkinSiteProfile { - public String name; - public String type; - public String userAgent; - - public String root; - public CustomSkinAPIPlusPrivacy privacy; - - public Boolean checkPNG;//Not suitable for local skin - public String skin; - public String model; - public String cape; - public String elytra; - - public static SkinSiteProfile createMojangAPI(String name){ - SkinSiteProfile ssp=new SkinSiteProfile(); - ssp.name=name; - ssp.type="MojangAPI"; - return ssp; - } - public static SkinSiteProfile createCustomSkinAPI(String name,String root){ - SkinSiteProfile ssp=new SkinSiteProfile(); - ssp.name=name; - ssp.type="CustomSkinAPI"; - ssp.root=root; - return ssp; - } - public static SkinSiteProfile creatCustomSkinAPIPlus(String name,String root){ - SkinSiteProfile ssp=new SkinSiteProfile(); - ssp.name=name; - ssp.type="CustomSkinAPIPlus"; - ssp.root=root; - ssp.privacy=new CustomSkinAPIPlusPrivacy(); - return ssp; - } - public static SkinSiteProfile createUniSkinAPI(String name,String root){ - SkinSiteProfile ssp=new SkinSiteProfile(); - ssp.name=name; - ssp.type="UniSkinAPI"; - ssp.root=root; - return ssp; - } - public static SkinSiteProfile createLegacy(String name,String skin,String cape,String elytra){ - SkinSiteProfile ssp=new SkinSiteProfile(); - ssp.name=name; - ssp.type="Legacy"; - ssp.checkPNG=false; - ssp.skin=skin; - ssp.model="default"; - ssp.cape=cape; - ssp.elytra=elytra; - return ssp; - } - public static SkinSiteProfile createElfSkin(String name){ - SkinSiteProfile ssp=new SkinSiteProfile(); - ssp.name=name; - ssp.type="ElfSkin"; - return ssp; - } + public String name; + public String type; + public String userAgent; + + public String root; + public CustomSkinAPIPlusPrivacy privacy; + + public Boolean checkPNG;//Not suitable for local skin + public String skin; + public String model; + public String cape; + public String elytra; + + public static SkinSiteProfile createMojangAPI(String name){ + SkinSiteProfile ssp=new SkinSiteProfile(); + ssp.name=name; + ssp.type="MojangAPI"; + return ssp; + } + public static SkinSiteProfile createCustomSkinAPI(String name,String root){ + SkinSiteProfile ssp=new SkinSiteProfile(); + ssp.name=name; + ssp.type="CustomSkinAPI"; + ssp.root=root; + return ssp; + } + public static SkinSiteProfile creatCustomSkinAPIPlus(String name,String root){ + SkinSiteProfile ssp=new SkinSiteProfile(); + ssp.name=name; + ssp.type="CustomSkinAPIPlus"; + ssp.root=root; + ssp.privacy=new CustomSkinAPIPlusPrivacy(); + return ssp; + } + public static SkinSiteProfile createUniSkinAPI(String name,String root){ + SkinSiteProfile ssp=new SkinSiteProfile(); + ssp.name=name; + ssp.type="UniSkinAPI"; + ssp.root=root; + return ssp; + } + public static SkinSiteProfile createLegacy(String name,String skin,String cape,String elytra){ + SkinSiteProfile ssp=new SkinSiteProfile(); + ssp.name=name; + ssp.type="Legacy"; + ssp.checkPNG=false; + ssp.skin=skin; + ssp.model="default"; + ssp.cape=cape; + ssp.elytra=elytra; + return ssp; + } + public static SkinSiteProfile createElfSkin(String name){ + SkinSiteProfile ssp=new SkinSiteProfile(); + ssp.name=name; + ssp.type="ElfSkin"; + return ssp; + } } diff --git a/Common/source/customskinloader/fake/FakeClientPlayer.java b/Common/source/customskinloader/fake/FakeClientPlayer.java index 0e2b536..a784fa8 100644 --- a/Common/source/customskinloader/fake/FakeClientPlayer.java +++ b/Common/source/customskinloader/fake/FakeClientPlayer.java @@ -20,59 +20,59 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.StringUtils; public class FakeClientPlayer { - //For Legacy Skin - public static ThreadDownloadImageData getDownloadImageSkin(ResourceLocation resourceLocationIn, String username) - { - //CustomSkinLoader.logger.debug("FakeClientPlayer/getDownloadImageSkin "+username); - TextureManager textman = Minecraft.getMinecraft().getTextureManager(); - ITextureObject ito = textman.getTexture(resourceLocationIn); + //For Legacy Skin + public static ThreadDownloadImageData getDownloadImageSkin(ResourceLocation resourceLocationIn, String username) + { + //CustomSkinLoader.logger.debug("FakeClientPlayer/getDownloadImageSkin "+username); + TextureManager textman = Minecraft.getMinecraft().getTextureManager(); + ITextureObject ito = textman.getTexture(resourceLocationIn); - if (ito == null || !(ito instanceof ThreadDownloadImageData)) - { - //if Legacy Skin for username not loaded yet - SkinManager skinman = Minecraft.getMinecraft().getSkinManager(); - UUID offlineUUID=EntityPlayer.getOfflineUUID(username); - GameProfile offlineProfile=new GameProfile(offlineUUID,username); - - //Load Default Skin - ResourceLocation defaultSkin=DefaultPlayerSkin.getDefaultSkin(offlineUUID); - ITextureObject defaultSkinObj=new SimpleTexture(defaultSkin); - textman.loadTexture(resourceLocationIn, defaultSkinObj); - - //Load Skin from SkinManager - skinman.loadProfileTextures(offlineProfile, new LegacyBuffer(resourceLocationIn), false); - } + if (ito == null || !(ito instanceof ThreadDownloadImageData)) + { + //if Legacy Skin for username not loaded yet + SkinManager skinman = Minecraft.getMinecraft().getSkinManager(); + UUID offlineUUID=EntityPlayer.getOfflineUUID(username); + GameProfile offlineProfile=new GameProfile(offlineUUID,username); + + //Load Default Skin + ResourceLocation defaultSkin=DefaultPlayerSkin.getDefaultSkin(offlineUUID); + ITextureObject defaultSkinObj=new SimpleTexture(defaultSkin); + textman.loadTexture(resourceLocationIn, defaultSkinObj); + + //Load Skin from SkinManager + skinman.loadProfileTextures(offlineProfile, new LegacyBuffer(resourceLocationIn), false); + } - if(ito instanceof ThreadDownloadImageData) - return (ThreadDownloadImageData)ito; - else - return null; - } + if(ito instanceof ThreadDownloadImageData) + return (ThreadDownloadImageData)ito; + else + return null; + } - public static ResourceLocation getLocationSkin(String username) - { - //CustomSkinLoader.logger.debug("FakeClientPlayer/getLocationSkin "+username); - return new ResourceLocation("skins/legacy-" + StringUtils.stripControlCodes(username)); - } - - private static class LegacyBuffer implements SkinAvailableCallback{ - ResourceLocation resourceLocationIn; - - public LegacyBuffer(ResourceLocation resourceLocationIn) { - CustomSkinLoader.logger.debug("Loading Legacy Texture "+resourceLocationIn); - this.resourceLocationIn=resourceLocationIn; - } + public static ResourceLocation getLocationSkin(String username) + { + //CustomSkinLoader.logger.debug("FakeClientPlayer/getLocationSkin "+username); + return new ResourceLocation("skins/legacy-" + StringUtils.stripControlCodes(username)); + } + + private static class LegacyBuffer implements SkinAvailableCallback{ + ResourceLocation resourceLocationIn; + + public LegacyBuffer(ResourceLocation resourceLocationIn) { + CustomSkinLoader.logger.debug("Loading Legacy Texture "+resourceLocationIn); + this.resourceLocationIn=resourceLocationIn; + } - @Override - public void skinAvailable(Type typeIn, ResourceLocation location, MinecraftProfileTexture profileTexture) { - if(typeIn!=Type.SKIN) - return; - CustomSkinLoader.logger.debug("Legacy Texture Loaded "+resourceLocationIn); - TextureManager textman = Minecraft.getMinecraft().getTextureManager(); - ITextureObject ito = textman.getTexture(location); - textman.loadTexture(resourceLocationIn, ito); - //textman.bindTexture(resourceLocationIn); - } - - } + @Override + public void skinAvailable(Type typeIn, ResourceLocation location, MinecraftProfileTexture profileTexture) { + if(typeIn!=Type.SKIN) + return; + CustomSkinLoader.logger.debug("Legacy Texture Loaded "+resourceLocationIn); + TextureManager textman = Minecraft.getMinecraft().getTextureManager(); + ITextureObject ito = textman.getTexture(location); + textman.loadTexture(resourceLocationIn, ito); + //textman.bindTexture(resourceLocationIn); + } + + } } diff --git a/Common/source/customskinloader/fake/FakeSkinBuffer.java b/Common/source/customskinloader/fake/FakeSkinBuffer.java index cf659c6..35145c4 100644 --- a/Common/source/customskinloader/fake/FakeSkinBuffer.java +++ b/Common/source/customskinloader/fake/FakeSkinBuffer.java @@ -8,110 +8,110 @@ import java.awt.image.ImageObserver; public class FakeSkinBuffer implements net.minecraft.client.renderer.IImageBuffer { - private int[] imageData; - private int ratio=1; - - @Override - public BufferedImage parseUserSkin(BufferedImage image) { - if(image==null) - return null; - ratio = image.getWidth() / 64; - BufferedImage bufferedimage = new BufferedImage(64 * ratio, 64 * ratio, 2); - Graphics graphics = bufferedimage.getGraphics(); - graphics.setColor(new Color(0,0,0,0)); - graphics.fillRect(0,0,64,64); - graphics.drawImage(image,0,0,(ImageObserver)null); - if (image.getHeight() == 32 * ratio){//Single Layer - //Revert to original algorithm - //Right Leg -> Left Leg - graphics.drawImage(bufferedimage, 24 * ratio, 48 * ratio, 20 * ratio, 52 * ratio, 4 * ratio, 16 * ratio, 8 * ratio, 20 * ratio, (ImageObserver)null);//Top - graphics.drawImage(bufferedimage, 28 * ratio, 48 * ratio, 24 * ratio, 52 * ratio, 8 * ratio, 16 * ratio, 12 * ratio, 20 * ratio, (ImageObserver)null);//Bottom - graphics.drawImage(bufferedimage, 20 * ratio, 52 * ratio, 16 * ratio, 64 * ratio, 8 * ratio, 20 * ratio, 12 * ratio, 32 * ratio, (ImageObserver)null);//Left - graphics.drawImage(bufferedimage, 24 * ratio, 52 * ratio, 20 * ratio, 64 * ratio, 4 * ratio, 20 * ratio, 8 * ratio, 32 * ratio, (ImageObserver)null);//Front - graphics.drawImage(bufferedimage, 28 * ratio, 52 * ratio, 24 * ratio, 64 * ratio, 0 * ratio, 20 * ratio, 4 * ratio, 32 * ratio, (ImageObserver)null);//Right - graphics.drawImage(bufferedimage, 32 * ratio, 52 * ratio, 28 * ratio, 64 * ratio, 12 * ratio, 20 * ratio, 16 * ratio, 32 * ratio, (ImageObserver)null);//Back - //Right Arm -> Left Arm - graphics.drawImage(bufferedimage, 40 * ratio, 48 * ratio, 36 * ratio, 52 * ratio, 44 * ratio, 16 * ratio, 48 * ratio, 20 * ratio, (ImageObserver)null);//Top - graphics.drawImage(bufferedimage, 44 * ratio, 48 * ratio, 40 * ratio, 52 * ratio, 48 * ratio, 16 * ratio, 52 * ratio, 20 * ratio, (ImageObserver)null);//Bottom - graphics.drawImage(bufferedimage, 36 * ratio, 52 * ratio, 32 * ratio, 64 * ratio, 48 * ratio, 20 * ratio, 52 * ratio, 32 * ratio, (ImageObserver)null);//Left - graphics.drawImage(bufferedimage, 40 * ratio, 52 * ratio, 36 * ratio, 64 * ratio, 44 * ratio, 20 * ratio, 48 * ratio, 32 * ratio, (ImageObserver)null);//Front - graphics.drawImage(bufferedimage, 44 * ratio, 52 * ratio, 40 * ratio, 64 * ratio, 40 * ratio, 20 * ratio, 44 * ratio, 32 * ratio, (ImageObserver)null);//Right - graphics.drawImage(bufferedimage, 48 * ratio, 52 * ratio, 44 * ratio, 64 * ratio, 52 * ratio, 20 * ratio, 56 * ratio, 32 * ratio, (ImageObserver)null);//Back - } - graphics.dispose(); - this.imageData = ((DataBufferInt)bufferedimage.getRaster().getDataBuffer()).getData(); - - setAreaDueToConfig( 0 * ratio, 0 * ratio,32 * ratio,16 * ratio);//Head - 1 - setAreaTransparent(32 * ratio, 0 * ratio,64 * ratio,16 * ratio);//Head - 2 - - setAreaDueToConfig( 0 * ratio,16 * ratio,16 * ratio,32 * ratio);//Right Leg - 1 - setAreaDueToConfig(16 * ratio,16 * ratio,40 * ratio,32 * ratio);//Body - 1 - setAreaDueToConfig(40 * ratio,16 * ratio,56 * ratio,32 * ratio);//Right Arm - 1 - - setAreaTransparent( 0 * ratio,32 * ratio,16 * ratio,48 * ratio);//Right Leg - 2 - setAreaTransparent(16 * ratio,32 * ratio,40 * ratio,48 * ratio);//Body - 2 - setAreaTransparent(40 * ratio,32 * ratio,56 * ratio,48 * ratio);//Right Arm - 2 - - setAreaTransparent( 0 * ratio,48 * ratio,16 * ratio,64 * ratio);//Left Leg - 2 - setAreaDueToConfig(16 * ratio,48 * ratio,32 * ratio,64 * ratio);//Left Leg - 1 - setAreaDueToConfig(32 * ratio,48 * ratio,48 * ratio,64 * ratio);//Left Arm - 1 - setAreaTransparent(48 * ratio,48 * ratio,64 * ratio,64 * ratio);//Left Arm - 2 - - return bufferedimage; - } - - /* 2^24-1 - * 00000000 11111111 11111111 11111111 */ - private static final int A=16777215; - private static final int WHITE=getARGB(255,255,255,255); - private static final int BLACK=getARGB(255,0,0,0); - private boolean isFilled(int x0,int y0,int x1,int y1){ - int data=this.imageData[getPosition(x0,y0)]; - if(data!=WHITE && data!=BLACK) - return false; - for (int x=x0;x - * 11111110 11111111 11111111 11111111 -> - * 11111111 00000000 00000000 00000000 */ - private static final int B=-16777216; - private void setAreaOpaque(int x0,int y0,int x1,int y1){ - for (int x=x0;x Left Leg + graphics.drawImage(bufferedimage, 24 * ratio, 48 * ratio, 20 * ratio, 52 * ratio, 4 * ratio, 16 * ratio, 8 * ratio, 20 * ratio, (ImageObserver)null);//Top + graphics.drawImage(bufferedimage, 28 * ratio, 48 * ratio, 24 * ratio, 52 * ratio, 8 * ratio, 16 * ratio, 12 * ratio, 20 * ratio, (ImageObserver)null);//Bottom + graphics.drawImage(bufferedimage, 20 * ratio, 52 * ratio, 16 * ratio, 64 * ratio, 8 * ratio, 20 * ratio, 12 * ratio, 32 * ratio, (ImageObserver)null);//Left + graphics.drawImage(bufferedimage, 24 * ratio, 52 * ratio, 20 * ratio, 64 * ratio, 4 * ratio, 20 * ratio, 8 * ratio, 32 * ratio, (ImageObserver)null);//Front + graphics.drawImage(bufferedimage, 28 * ratio, 52 * ratio, 24 * ratio, 64 * ratio, 0 * ratio, 20 * ratio, 4 * ratio, 32 * ratio, (ImageObserver)null);//Right + graphics.drawImage(bufferedimage, 32 * ratio, 52 * ratio, 28 * ratio, 64 * ratio, 12 * ratio, 20 * ratio, 16 * ratio, 32 * ratio, (ImageObserver)null);//Back + //Right Arm -> Left Arm + graphics.drawImage(bufferedimage, 40 * ratio, 48 * ratio, 36 * ratio, 52 * ratio, 44 * ratio, 16 * ratio, 48 * ratio, 20 * ratio, (ImageObserver)null);//Top + graphics.drawImage(bufferedimage, 44 * ratio, 48 * ratio, 40 * ratio, 52 * ratio, 48 * ratio, 16 * ratio, 52 * ratio, 20 * ratio, (ImageObserver)null);//Bottom + graphics.drawImage(bufferedimage, 36 * ratio, 52 * ratio, 32 * ratio, 64 * ratio, 48 * ratio, 20 * ratio, 52 * ratio, 32 * ratio, (ImageObserver)null);//Left + graphics.drawImage(bufferedimage, 40 * ratio, 52 * ratio, 36 * ratio, 64 * ratio, 44 * ratio, 20 * ratio, 48 * ratio, 32 * ratio, (ImageObserver)null);//Front + graphics.drawImage(bufferedimage, 44 * ratio, 52 * ratio, 40 * ratio, 64 * ratio, 40 * ratio, 20 * ratio, 44 * ratio, 32 * ratio, (ImageObserver)null);//Right + graphics.drawImage(bufferedimage, 48 * ratio, 52 * ratio, 44 * ratio, 64 * ratio, 52 * ratio, 20 * ratio, 56 * ratio, 32 * ratio, (ImageObserver)null);//Back + } + graphics.dispose(); + this.imageData = ((DataBufferInt)bufferedimage.getRaster().getDataBuffer()).getData(); + + setAreaDueToConfig( 0 * ratio, 0 * ratio,32 * ratio,16 * ratio);//Head - 1 + setAreaTransparent(32 * ratio, 0 * ratio,64 * ratio,16 * ratio);//Head - 2 + + setAreaDueToConfig( 0 * ratio,16 * ratio,16 * ratio,32 * ratio);//Right Leg - 1 + setAreaDueToConfig(16 * ratio,16 * ratio,40 * ratio,32 * ratio);//Body - 1 + setAreaDueToConfig(40 * ratio,16 * ratio,56 * ratio,32 * ratio);//Right Arm - 1 + + setAreaTransparent( 0 * ratio,32 * ratio,16 * ratio,48 * ratio);//Right Leg - 2 + setAreaTransparent(16 * ratio,32 * ratio,40 * ratio,48 * ratio);//Body - 2 + setAreaTransparent(40 * ratio,32 * ratio,56 * ratio,48 * ratio);//Right Arm - 2 + + setAreaTransparent( 0 * ratio,48 * ratio,16 * ratio,64 * ratio);//Left Leg - 2 + setAreaDueToConfig(16 * ratio,48 * ratio,32 * ratio,64 * ratio);//Left Leg - 1 + setAreaDueToConfig(32 * ratio,48 * ratio,48 * ratio,64 * ratio);//Left Arm - 1 + setAreaTransparent(48 * ratio,48 * ratio,64 * ratio,64 * ratio);//Left Arm - 2 + + return bufferedimage; + } + + /* 2^24-1 + * 00000000 11111111 11111111 11111111 */ + private static final int A=16777215; + private static final int WHITE=getARGB(255,255,255,255); + private static final int BLACK=getARGB(255,0,0,0); + private boolean isFilled(int x0,int y0,int x1,int y1){ + int data=this.imageData[getPosition(x0,y0)]; + if(data!=WHITE && data!=BLACK) + return false; + for (int x=x0;x + * 11111110 11111111 11111111 11111111 -> + * 11111111 00000000 00000000 00000000 */ + private static final int B=-16777216; + private void setAreaOpaque(int x0,int y0,int x1,int y1){ + for (int x=x0;x map = Maps.newHashMap(); - map.putAll(customskinloader.CustomSkinLoader.loadProfile(profile)); + if (itextureobject != null)//Have already loaded + makeCallback(skinAvailableCallback,textureType, resourcelocation, profileTexture); + else{ + ThreadDownloadImageData threaddownloadimagedata = new ThreadDownloadImageData(info.cacheFile, info.url, DefaultPlayerSkin.getDefaultSkinLegacy(), + new BaseBuffer(skinAvailableCallback, textureType, resourcelocation, profileTexture)); + this.textureManager.loadTexture(resourcelocation, threaddownloadimagedata); + } + return resourcelocation; + } + public void loadProfileTextures(final GameProfile profile, final SkinAvailableCallback skinAvailableCallback, final boolean requireSecure){ + THREAD_POOL.submit(new Runnable(){ + public void run(){ + final Map map = Maps.newHashMap(); + map.putAll(customskinloader.CustomSkinLoader.loadProfile(profile)); - Minecraft.getMinecraft().addScheduledTask(new Runnable(){ - public void run(){ - for(Type type:Type.values()) - if(map.containsKey(type)) - FakeSkinManager.this.loadSkin((MinecraftProfileTexture)map.get(type), type, skinAvailableCallback); - } - }); - } - }); - } - public Map loadSkinFromCache(GameProfile profile){ - return CustomSkinLoader.loadProfileFromCache(profile); - } - - private static void makeCallback(SkinAvailableCallback callback,Type type, ResourceLocation location, MinecraftProfileTexture texture){ - if(callback!=null) - callback.skinAvailable(type, location, texture); - } - private class BaseBuffer implements IImageBuffer{ - private IImageBuffer buffer; - - private SkinAvailableCallback callback; - private Type type; - private ResourceLocation location; - private MinecraftProfileTexture texture; - public BaseBuffer(SkinAvailableCallback callback,Type type,ResourceLocation location,MinecraftProfileTexture texture){ - this.buffer=(type==Type.SKIN?new FakeSkinBuffer():null); - - this.callback=callback; - this.type=type; - this.location=location; - this.texture=texture; - } - - public BufferedImage parseUserSkin(BufferedImage image){ - return buffer==null?image:buffer.parseUserSkin(image); - } - public void skinAvailable(){ - if (buffer != null) - buffer.skinAvailable(); + Minecraft.getMinecraft().addScheduledTask(new Runnable(){ + public void run(){ + for(Type type:Type.values()) + if(map.containsKey(type)) + FakeSkinManager.this.loadSkin((MinecraftProfileTexture)map.get(type), type, skinAvailableCallback); + } + }); + } + }); + } + public Map loadSkinFromCache(GameProfile profile){ + return CustomSkinLoader.loadProfileFromCache(profile); + } + + private static void makeCallback(SkinAvailableCallback callback,Type type, ResourceLocation location, MinecraftProfileTexture texture){ + if(callback!=null) + callback.skinAvailable(type, location, texture); + } + private class BaseBuffer implements IImageBuffer{ + private IImageBuffer buffer; + + private SkinAvailableCallback callback; + private Type type; + private ResourceLocation location; + private MinecraftProfileTexture texture; + public BaseBuffer(SkinAvailableCallback callback,Type type,ResourceLocation location,MinecraftProfileTexture texture){ + this.buffer=(type==Type.SKIN?new FakeSkinBuffer():null); + + this.callback=callback; + this.type=type; + this.location=location; + this.texture=texture; + } + + public BufferedImage parseUserSkin(BufferedImage image){ + return buffer==null?image:buffer.parseUserSkin(image); + } + public void skinAvailable(){ + if (buffer != null) + buffer.skinAvailable(); - FakeSkinManager.makeCallback(callback,type, location, texture); - } - } + FakeSkinManager.makeCallback(callback,type, location, texture); + } + } } diff --git a/Common/source/customskinloader/loader/JsonAPILoader.java b/Common/source/customskinloader/loader/JsonAPILoader.java index 961fff2..7067706 100644 --- a/Common/source/customskinloader/loader/JsonAPILoader.java +++ b/Common/source/customskinloader/loader/JsonAPILoader.java @@ -18,84 +18,84 @@ import customskinloader.utils.HttpRequestUtil.HttpRequest; import customskinloader.utils.HttpRequestUtil.HttpResponce; public class JsonAPILoader implements ProfileLoader.IProfileLoader { - - public interface IJsonAPI { - public String toJsonUrl(String root,String username); - public String getPayload(SkinSiteProfile ssp); - public UserProfile toUserProfile(String root,String json,boolean local); - public String getName(); - } - public static class ErrorProfile{ - public int errno; - public String msg; - } - public static enum Type{ - CustomSkinAPI(new CustomSkinAPI()),CustomSkinAPIPlus(new CustomSkinAPIPlus()),UniSkinAPI(new UniSkinAPI()); - public IJsonAPI jsonAPI; - private Type(IJsonAPI jsonAPI){ - this.jsonAPI=jsonAPI; - } - } - - private Type type; - public JsonAPILoader(Type type){ - this.type=type; - } - - @Override - public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception { - String username=gameProfile.getName(); - boolean local=HttpUtil0.isLocal(ssp.root); - if(ssp.root==null||ssp.root.equals("")){ - CustomSkinLoader.logger.info("Root not defined."); - return null; - } - String jsonUrl=type.jsonAPI.toJsonUrl(ssp.root, username); - String json; - if(local){ - File jsonFile=new File(jsonUrl); - if(!jsonFile.exists()){ - CustomSkinLoader.logger.info("Profile File not found."); - return null; - } - json=IOUtils.toString(new FileInputStream(jsonFile)); - }else{ - HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(jsonUrl).setCacheTime(60).setUserAgent(ssp.userAgent).setPayload(type.jsonAPI.getPayload(ssp))); - json=responce.content; - } - if(json==null||json.equals("")){ - CustomSkinLoader.logger.info("Profile not found."); - return null; - } - - ErrorProfile profile=CustomSkinLoader.GSON.fromJson(json, ErrorProfile.class); - if(profile.errno!=0){ - CustomSkinLoader.logger.info("Error "+profile.errno+": "+profile.msg); - return null; - } - - UserProfile p=type.jsonAPI.toUserProfile(ssp.root, json, local); - if(p==null||p.isEmpty()){ - CustomSkinLoader.logger.info("Both skin and cape not found."); - return null; - }else{ - return p; - } - } - @Override - public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { - return StringUtils.isNoneEmpty(ssp0.root)?ssp0.root.equalsIgnoreCase(ssp1.root):true; - } - @Override - public String getName() { - return type.jsonAPI.getName(); - } - @Override - public void initLocalFolder(SkinSiteProfile ssp) { - if(HttpUtil0.isLocal(ssp.root)){ - File f=new File(ssp.root); - if(!f.exists()) - f.mkdirs(); - } - } + + public interface IJsonAPI { + public String toJsonUrl(String root,String username); + public String getPayload(SkinSiteProfile ssp); + public UserProfile toUserProfile(String root,String json,boolean local); + public String getName(); + } + public static class ErrorProfile{ + public int errno; + public String msg; + } + public static enum Type{ + CustomSkinAPI(new CustomSkinAPI()),CustomSkinAPIPlus(new CustomSkinAPIPlus()),UniSkinAPI(new UniSkinAPI()); + public IJsonAPI jsonAPI; + private Type(IJsonAPI jsonAPI){ + this.jsonAPI=jsonAPI; + } + } + + private Type type; + public JsonAPILoader(Type type){ + this.type=type; + } + + @Override + public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception { + String username=gameProfile.getName(); + boolean local=HttpUtil0.isLocal(ssp.root); + if(ssp.root==null||ssp.root.equals("")){ + CustomSkinLoader.logger.info("Root not defined."); + return null; + } + String jsonUrl=type.jsonAPI.toJsonUrl(ssp.root, username); + String json; + if(local){ + File jsonFile=new File(jsonUrl); + if(!jsonFile.exists()){ + CustomSkinLoader.logger.info("Profile File not found."); + return null; + } + json=IOUtils.toString(new FileInputStream(jsonFile)); + }else{ + HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(jsonUrl).setCacheTime(60).setUserAgent(ssp.userAgent).setPayload(type.jsonAPI.getPayload(ssp))); + json=responce.content; + } + if(json==null||json.equals("")){ + CustomSkinLoader.logger.info("Profile not found."); + return null; + } + + ErrorProfile profile=CustomSkinLoader.GSON.fromJson(json, ErrorProfile.class); + if(profile.errno!=0){ + CustomSkinLoader.logger.info("Error "+profile.errno+": "+profile.msg); + return null; + } + + UserProfile p=type.jsonAPI.toUserProfile(ssp.root, json, local); + if(p==null||p.isEmpty()){ + CustomSkinLoader.logger.info("Both skin and cape not found."); + return null; + }else{ + return p; + } + } + @Override + public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { + return StringUtils.isNoneEmpty(ssp0.root)?ssp0.root.equalsIgnoreCase(ssp1.root):true; + } + @Override + public String getName() { + return type.jsonAPI.getName(); + } + @Override + public void initLocalFolder(SkinSiteProfile ssp) { + if(HttpUtil0.isLocal(ssp.root)){ + File f=new File(ssp.root); + if(!f.exists()) + f.mkdirs(); + } + } } diff --git a/Common/source/customskinloader/loader/LegacyLoader.java b/Common/source/customskinloader/loader/LegacyLoader.java index 0a667f3..f55a7de 100644 --- a/Common/source/customskinloader/loader/LegacyLoader.java +++ b/Common/source/customskinloader/loader/LegacyLoader.java @@ -17,78 +17,78 @@ import customskinloader.utils.HttpTextureUtil; import customskinloader.utils.HttpUtil0; public class LegacyLoader implements ProfileLoader.IProfileLoader { - public static final String USERNAME_REGEX="\\{USERNAME\\}"; - - @Override - public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception { - String username=gameProfile.getName(); - UserProfile profile=new UserProfile(); - if(StringUtils.isNoneEmpty(ssp.skin)){ - String skin=ssp.skin.replaceAll(USERNAME_REGEX, username); - if(HttpUtil0.isLocal(ssp.skin)){ - File skinFile=new File(CustomSkinLoader.DATA_DIR,skin); - if(skinFile.exists()&&skinFile.isFile()) - profile.skinUrl=HttpTextureUtil.getLocalLegacyFakeUrl(skin, HttpTextureUtil.getHash(skin, skinFile.length(), skinFile.lastModified())); - }else{ - HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(skin).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG!=null&&ssp.checkPNG!=false).setLoadContent(false).setCacheTime(60)); - if(responce.success) - profile.skinUrl=HttpTextureUtil.getLegacyFakeUrl(skin); - } - profile.model=profile.hasSkinUrl()?ssp.model:null; - } - if(StringUtils.isNoneEmpty(ssp.cape)){ - String cape=ssp.cape.replaceAll(USERNAME_REGEX, username); - if(HttpUtil0.isLocal(ssp.cape)){ - File capeFile=new File(CustomSkinLoader.DATA_DIR,cape); - if(capeFile.exists()&&capeFile.isFile()) - profile.capeUrl=HttpTextureUtil.getLocalLegacyFakeUrl(cape, HttpTextureUtil.getHash(cape, capeFile.length(), capeFile.lastModified())); - }else{ - HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(cape).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG!=null&&ssp.checkPNG!=false).setLoadContent(false).setCacheTime(60)); - if(responce.success) - profile.capeUrl=HttpTextureUtil.getLegacyFakeUrl(cape); - } - } - if(ModelManager0.isElytraSupported()&&StringUtils.isNoneEmpty(ssp.elytra)){ - String elytra=ssp.elytra.replaceAll(USERNAME_REGEX, username); - if(HttpUtil0.isLocal(ssp.elytra)){ - File elytraFile=new File(CustomSkinLoader.DATA_DIR,elytra); - if(elytraFile.exists()&&elytraFile.isFile()) - profile.elytraUrl=HttpTextureUtil.getLocalLegacyFakeUrl(elytra, HttpTextureUtil.getHash(elytra, elytraFile.length(), elytraFile.lastModified())); - }else{ - HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(elytra).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG!=null&&ssp.checkPNG!=false).setLoadContent(false).setCacheTime(60)); - if(responce.success) - profile.elytraUrl=HttpTextureUtil.getLegacyFakeUrl(elytra); - } - } - if(profile.isEmpty()){ - CustomSkinLoader.logger.info("Both skin and cape not found."); - return null; - } - return profile; - } + public static final String USERNAME_REGEX="\\{USERNAME\\}"; + + @Override + public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception { + String username=gameProfile.getName(); + UserProfile profile=new UserProfile(); + if(StringUtils.isNoneEmpty(ssp.skin)){ + String skin=ssp.skin.replaceAll(USERNAME_REGEX, username); + if(HttpUtil0.isLocal(ssp.skin)){ + File skinFile=new File(CustomSkinLoader.DATA_DIR,skin); + if(skinFile.exists()&&skinFile.isFile()) + profile.skinUrl=HttpTextureUtil.getLocalLegacyFakeUrl(skin, HttpTextureUtil.getHash(skin, skinFile.length(), skinFile.lastModified())); + }else{ + HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(skin).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG!=null&&ssp.checkPNG!=false).setLoadContent(false).setCacheTime(60)); + if(responce.success) + profile.skinUrl=HttpTextureUtil.getLegacyFakeUrl(skin); + } + profile.model=profile.hasSkinUrl()?ssp.model:null; + } + if(StringUtils.isNoneEmpty(ssp.cape)){ + String cape=ssp.cape.replaceAll(USERNAME_REGEX, username); + if(HttpUtil0.isLocal(ssp.cape)){ + File capeFile=new File(CustomSkinLoader.DATA_DIR,cape); + if(capeFile.exists()&&capeFile.isFile()) + profile.capeUrl=HttpTextureUtil.getLocalLegacyFakeUrl(cape, HttpTextureUtil.getHash(cape, capeFile.length(), capeFile.lastModified())); + }else{ + HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(cape).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG!=null&&ssp.checkPNG!=false).setLoadContent(false).setCacheTime(60)); + if(responce.success) + profile.capeUrl=HttpTextureUtil.getLegacyFakeUrl(cape); + } + } + if(ModelManager0.isElytraSupported()&&StringUtils.isNoneEmpty(ssp.elytra)){ + String elytra=ssp.elytra.replaceAll(USERNAME_REGEX, username); + if(HttpUtil0.isLocal(ssp.elytra)){ + File elytraFile=new File(CustomSkinLoader.DATA_DIR,elytra); + if(elytraFile.exists()&&elytraFile.isFile()) + profile.elytraUrl=HttpTextureUtil.getLocalLegacyFakeUrl(elytra, HttpTextureUtil.getHash(elytra, elytraFile.length(), elytraFile.lastModified())); + }else{ + HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(elytra).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG!=null&&ssp.checkPNG!=false).setLoadContent(false).setCacheTime(60)); + if(responce.success) + profile.elytraUrl=HttpTextureUtil.getLegacyFakeUrl(elytra); + } + } + if(profile.isEmpty()){ + CustomSkinLoader.logger.info("Both skin and cape not found."); + return null; + } + return profile; + } - @Override - public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { - return (StringUtils.isNoneEmpty(ssp0.skin)?ssp0.skin.equalsIgnoreCase(ssp1.skin):true) || (StringUtils.isNoneEmpty(ssp0.cape)?ssp0.cape.equalsIgnoreCase(ssp1.cape):true); - } - @Override - public String getName() { - return "Legacy"; - } + @Override + public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { + return (StringUtils.isNoneEmpty(ssp0.skin)?ssp0.skin.equalsIgnoreCase(ssp1.skin):true) || (StringUtils.isNoneEmpty(ssp0.cape)?ssp0.cape.equalsIgnoreCase(ssp1.cape):true); + } + @Override + public String getName() { + return "Legacy"; + } - @Override - public void initLocalFolder(SkinSiteProfile ssp) { - if(HttpUtil0.isLocal(ssp.skin)) - initFolder(ssp.skin); - if(HttpUtil0.isLocal(ssp.cape)) - initFolder(ssp.cape); - if(HttpUtil0.isLocal(ssp.elytra)) - initFolder(ssp.elytra); - } - private void initFolder(String target){ - String file=target.replaceAll(USERNAME_REGEX, "init"); - File folder=new File(CustomSkinLoader.DATA_DIR,file).getParentFile(); - if(folder!=null&&!folder.exists()) - folder.mkdirs(); - } + @Override + public void initLocalFolder(SkinSiteProfile ssp) { + if(HttpUtil0.isLocal(ssp.skin)) + initFolder(ssp.skin); + if(HttpUtil0.isLocal(ssp.cape)) + initFolder(ssp.cape); + if(HttpUtil0.isLocal(ssp.elytra)) + initFolder(ssp.elytra); + } + private void initFolder(String target){ + String file=target.replaceAll(USERNAME_REGEX, "init"); + File folder=new File(CustomSkinLoader.DATA_DIR,file).getParentFile(); + if(folder!=null&&!folder.exists()) + folder.mkdirs(); + } } diff --git a/Common/source/customskinloader/loader/MojangAPILoader.java b/Common/source/customskinloader/loader/MojangAPILoader.java index 2e8dc5e..8e834c1 100644 --- a/Common/source/customskinloader/loader/MojangAPILoader.java +++ b/Common/source/customskinloader/loader/MojangAPILoader.java @@ -29,66 +29,80 @@ import customskinloader.utils.MinecraftUtil; public class MojangAPILoader implements ProfileLoader.IProfileLoader { - public static final MinecraftSessionService defaultSessionService=MinecraftUtil.getSessionService(); - @Override - public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception { - Map map=getTextures(gameProfile); - if(!map.isEmpty()){ - CustomSkinLoader.logger.info("Default profile will be used."); - return ModelManager0.toUserProfile(map); - } - String username=gameProfile.getName(); - GameProfile newGameProfile=loadGameProfile(username); - if(newGameProfile==null){ - CustomSkinLoader.logger.info("Profile not found.("+username+"'s profile not found.)"); - return null; - } - newGameProfile=defaultSessionService.fillProfileProperties(newGameProfile, false); - map=getTextures(newGameProfile); - if(!map.isEmpty()){ - gameProfile.getProperties().putAll(newGameProfile.getProperties()); - return ModelManager0.toUserProfile(map); - } - CustomSkinLoader.logger.info("Profile not found.("+username+" doesn't have skin/cape.)"); - return null; - } - - public static GameProfile loadGameProfile(String username) throws Exception{ - //Doc (http://wiki.vg/Mojang_API#Username_-.3E_UUID_at_time) - HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest("https://api.mojang.com/users/profiles/minecraft/"+username).setCacheTime(0)); - if(StringUtils.isEmpty(responce.content)) - return null; - Gson gson=new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create(); - GameProfile gameProfile=gson.fromJson(responce.content, GameProfile.class); - if(gameProfile.getId()==null) - return null; - return new GameProfile(gameProfile.getId(),gameProfile.getName()); - } - public static Map getTextures(GameProfile gameProfile) throws Exception{ - Property textureProperty=(Property)Iterables.getFirst(gameProfile.getProperties().get("textures"), null); - if (textureProperty==null) - return new HashMap(); - String value=textureProperty.getValue(); - if(StringUtils.isBlank(value)) - return new HashMap(); - String json=new String(Base64.decodeBase64(value),Charsets.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) - return new HashMap(); - return result.getTextures(); - } - - @Override - public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { - return true; - } - @Override - public String getName() { - return "MojangAPI"; - } + public static final MinecraftSessionService defaultSessionService=MinecraftUtil.getSessionService(); + @Override + public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception { + Map map=getTextures(gameProfile); + if(!map.isEmpty()){ + CustomSkinLoader.logger.info("Default profile will be used."); + return ModelManager0.toUserProfile(map); + } + String username=gameProfile.getName(); + GameProfile newGameProfile=loadGameProfile(username); + if(newGameProfile==null){ + CustomSkinLoader.logger.info("Profile not found.("+username+"'s profile not found.)"); + return null; + } + newGameProfile=fillGameProfile(newGameProfile); + map=getTextures(newGameProfile); + if(!map.isEmpty()){ + gameProfile.getProperties().putAll(newGameProfile.getProperties()); + return ModelManager0.toUserProfile(map); + } + CustomSkinLoader.logger.info("Profile not found.("+username+" doesn't have skin/cape.)"); + return null; + } + + //Username -> UUID + public static GameProfile loadGameProfile(String username) throws Exception{ + //Doc (http://wiki.vg/Mojang_API#Username_-.3E_UUID_at_time) + HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest("https://api.mojang.com/users/profiles/minecraft/"+username).setCacheTime(0)); + if(StringUtils.isEmpty(responce.content)) + return null; + Gson gson=new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create(); + GameProfile gameProfile=gson.fromJson(responce.content, GameProfile.class); + if(gameProfile.getId()==null) + return null; + return new GameProfile(gameProfile.getId(),gameProfile.getName()); + } + //UUID -> Profile + public static GameProfile fillGameProfile(GameProfile profile) throws Exception{ + //Doc (http://wiki.vg/Mojang_API#UUID_-.3E_Profile_.2B_Skin.2FCape) + HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest("https://sessionserver.mojang.com/session/minecraft/profile/"+UUIDTypeAdapter.fromUUID(profile.getId())).setCacheTime(60)); + if(StringUtils.isEmpty(responce.content)) + return profile; + Gson gson=new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create(); + GameProfile gameProfile=gson.fromJson(responce.content, GameProfile.class); + return gameProfile; + } + + public static Map getTextures(GameProfile gameProfile) throws Exception{ + if(gameProfile==null) + return new HashMap(); + Property textureProperty=(Property)Iterables.getFirst(gameProfile.getProperties().get("textures"), null); + if (textureProperty==null) + return new HashMap(); + String value=textureProperty.getValue(); + if(StringUtils.isBlank(value)) + return new HashMap(); + String json=new String(Base64.decodeBase64(value),Charsets.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) + return new HashMap(); + return result.getTextures(); + } + + @Override + public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { + return true; + } + @Override + public String getName() { + return "MojangAPI"; + } - @Override - public void initLocalFolder(SkinSiteProfile ssp) { - } + @Override + public void initLocalFolder(SkinSiteProfile ssp) { + } } diff --git a/Common/source/customskinloader/loader/ProfileLoader.java b/Common/source/customskinloader/loader/ProfileLoader.java index b60a720..6e17e33 100644 --- a/Common/source/customskinloader/loader/ProfileLoader.java +++ b/Common/source/customskinloader/loader/ProfileLoader.java @@ -8,27 +8,27 @@ import customskinloader.config.SkinSiteProfile; import customskinloader.profile.UserProfile; public class ProfileLoader { - private static final IProfileLoader[] DEFAULT_LOADERS={ - new MojangAPILoader(), - new JsonAPILoader(JsonAPILoader.Type.CustomSkinAPI), - new JsonAPILoader(JsonAPILoader.Type.CustomSkinAPIPlus), - new LegacyLoader(), - new JsonAPILoader(JsonAPILoader.Type.UniSkinAPI)}; - - public static final HashMap LOADERS=initLoaders(); - - private static HashMap initLoaders() { - HashMap loaders=new HashMap(); - for(IProfileLoader loader:DEFAULT_LOADERS){ - loaders.put(loader.getName().toLowerCase(), loader); - } - return loaders; - } - - public interface IProfileLoader { - public UserProfile loadProfile(SkinSiteProfile ssp,GameProfile gameProfile) throws Exception; - public boolean compare(SkinSiteProfile ssp0,SkinSiteProfile ssp1); - public String getName(); - public void initLocalFolder(SkinSiteProfile ssp); - } + private static final IProfileLoader[] DEFAULT_LOADERS={ + new MojangAPILoader(), + new JsonAPILoader(JsonAPILoader.Type.CustomSkinAPI), + new JsonAPILoader(JsonAPILoader.Type.CustomSkinAPIPlus), + new LegacyLoader(), + new JsonAPILoader(JsonAPILoader.Type.UniSkinAPI)}; + + public static final HashMap LOADERS=initLoaders(); + + private static HashMap initLoaders() { + HashMap loaders=new HashMap(); + for(IProfileLoader loader:DEFAULT_LOADERS){ + loaders.put(loader.getName().toLowerCase(), loader); + } + return loaders; + } + + public interface IProfileLoader { + public UserProfile loadProfile(SkinSiteProfile ssp,GameProfile gameProfile) throws Exception; + public boolean compare(SkinSiteProfile ssp0,SkinSiteProfile ssp1); + public String getName(); + public void initLocalFolder(SkinSiteProfile ssp); + } } diff --git a/Common/source/customskinloader/loader/jsonapi/CustomSkinAPI.java b/Common/source/customskinloader/loader/jsonapi/CustomSkinAPI.java index b47735d..86d63b9 100644 --- a/Common/source/customskinloader/loader/jsonapi/CustomSkinAPI.java +++ b/Common/source/customskinloader/loader/jsonapi/CustomSkinAPI.java @@ -14,77 +14,77 @@ import customskinloader.profile.UserProfile; import customskinloader.utils.HttpTextureUtil; public class CustomSkinAPI implements IJsonAPI { - private static final String TEXTURES="textures/"; - private static final String SUFFIX=".json"; + private static final String TEXTURES="textures/"; + private static final String SUFFIX=".json"; - @Override - public String toJsonUrl(String root, String username) { - return new StringBuilder().append(root).append(username).append(SUFFIX).toString(); - } + @Override + public String toJsonUrl(String root, String username) { + return new StringBuilder().append(root).append(username).append(SUFFIX).toString(); + } - @Override - public UserProfile toUserProfile(String root, String json, boolean local) { - CustomSkinAPIProfile profile=CustomSkinLoader.GSON.fromJson(json, CustomSkinAPIProfile.class); - UserProfile p=new UserProfile(); - - if(StringUtils.isNotBlank(profile.skin)){ - p.skinUrl=root+TEXTURES+profile.skin; - if(local) - p.skinUrl=HttpTextureUtil.getLocalFakeUrl(p.skinUrl); - } - if(StringUtils.isNotBlank(profile.cape)){ - p.capeUrl=root+TEXTURES+profile.cape; - if(local) - p.capeUrl=HttpTextureUtil.getLocalFakeUrl(p.capeUrl); - } - if(StringUtils.isNotBlank(profile.elytra)){ - p.elytraUrl=root+TEXTURES+profile.elytra; - if(local) - p.elytraUrl=HttpTextureUtil.getLocalFakeUrl(p.elytraUrl); - } - - Map textures=new LinkedHashMap(); - if(profile.skins!=null) - textures.putAll(profile.skins); - if(profile.textures!=null) - textures.putAll(profile.textures); - if(textures.isEmpty()) - return p; - - boolean hasSkin=false; - for(String model:textures.keySet()){ - Model enumModel=ModelManager0.getEnumModel(model); - if(enumModel==null||StringUtils.isEmpty(textures.get(model))) - continue; - if(ModelManager0.isSkin(enumModel)) - if(hasSkin) - continue; - else - hasSkin=true; - String url=root+TEXTURES+textures.get(model); - if(local) - url=HttpTextureUtil.getLocalFakeUrl(url); - p.put(enumModel, url); - } - - return p; - } - private class CustomSkinAPIProfile{ - public String username; - public LinkedHashMap textures; - - public LinkedHashMap skins; - - public String skin; - public String cape; - public String elytra; - } - @Override - public String getPayload(SkinSiteProfile ssp) { - return null; - } - @Override - public String getName() { - return "CustomSkinAPI"; - } + @Override + public UserProfile toUserProfile(String root, String json, boolean local) { + CustomSkinAPIProfile profile=CustomSkinLoader.GSON.fromJson(json, CustomSkinAPIProfile.class); + UserProfile p=new UserProfile(); + + if(StringUtils.isNotBlank(profile.skin)){ + p.skinUrl=root+TEXTURES+profile.skin; + if(local) + p.skinUrl=HttpTextureUtil.getLocalFakeUrl(p.skinUrl); + } + if(StringUtils.isNotBlank(profile.cape)){ + p.capeUrl=root+TEXTURES+profile.cape; + if(local) + p.capeUrl=HttpTextureUtil.getLocalFakeUrl(p.capeUrl); + } + if(StringUtils.isNotBlank(profile.elytra)){ + p.elytraUrl=root+TEXTURES+profile.elytra; + if(local) + p.elytraUrl=HttpTextureUtil.getLocalFakeUrl(p.elytraUrl); + } + + Map textures=new LinkedHashMap(); + if(profile.skins!=null) + textures.putAll(profile.skins); + if(profile.textures!=null) + textures.putAll(profile.textures); + if(textures.isEmpty()) + return p; + + boolean hasSkin=false; + for(String model:textures.keySet()){ + Model enumModel=ModelManager0.getEnumModel(model); + if(enumModel==null||StringUtils.isEmpty(textures.get(model))) + continue; + if(ModelManager0.isSkin(enumModel)) + if(hasSkin) + continue; + else + hasSkin=true; + String url=root+TEXTURES+textures.get(model); + if(local) + url=HttpTextureUtil.getLocalFakeUrl(url); + p.put(enumModel, url); + } + + return p; + } + private class CustomSkinAPIProfile{ + public String username; + public LinkedHashMap textures; + + public LinkedHashMap skins; + + public String skin; + public String cape; + public String elytra; + } + @Override + public String getPayload(SkinSiteProfile ssp) { + return null; + } + @Override + public String getName() { + return "CustomSkinAPI"; + } } diff --git a/Common/source/customskinloader/loader/jsonapi/CustomSkinAPIPlus.java b/Common/source/customskinloader/loader/jsonapi/CustomSkinAPIPlus.java index 1b20390..7badc4e 100644 --- a/Common/source/customskinloader/loader/jsonapi/CustomSkinAPIPlus.java +++ b/Common/source/customskinloader/loader/jsonapi/CustomSkinAPIPlus.java @@ -16,67 +16,67 @@ import customskinloader.utils.MinecraftUtil; public class CustomSkinAPIPlus implements IJsonAPI { - private static String clientID=null; - public CustomSkinAPIPlus(){ - File clientIDFile=new File(CustomSkinLoader.DATA_DIR,"CustomSkinAPIPlus-ClientID"); - - if(clientIDFile.isFile()) - try{ - clientID=FileUtils.readFileToString(clientIDFile); - }catch(Exception e){ - e.printStackTrace(); - } - if(clientID==null){ - clientID=UUID.randomUUID().toString(); - try { - FileUtils.write(clientIDFile, clientID); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - @Override - public String toJsonUrl(String root, String username) { - return JsonAPILoader.Type.CustomSkinAPI.jsonAPI.toJsonUrl(root, username); - } + private static String clientID=null; + public CustomSkinAPIPlus(){ + File clientIDFile=new File(CustomSkinLoader.DATA_DIR,"CustomSkinAPIPlus-ClientID"); + + if(clientIDFile.isFile()) + try{ + clientID=FileUtils.readFileToString(clientIDFile); + }catch(Exception e){ + e.printStackTrace(); + } + if(clientID==null){ + clientID=UUID.randomUUID().toString(); + try { + FileUtils.write(clientIDFile, clientID); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + @Override + public String toJsonUrl(String root, String username) { + return JsonAPILoader.Type.CustomSkinAPI.jsonAPI.toJsonUrl(root, username); + } - @Override - public String getPayload(SkinSiteProfile ssp) { - if(ssp.privacy==null) - ssp.privacy=new CustomSkinAPIPlusPrivacy(); - return new Gson().toJson(new CustomSkinAPIPlusPayload(ssp.privacy)); - } + @Override + public String getPayload(SkinSiteProfile ssp) { + if(ssp.privacy==null) + ssp.privacy=new CustomSkinAPIPlusPrivacy(); + return new Gson().toJson(new CustomSkinAPIPlusPayload(ssp.privacy)); + } - @Override - public UserProfile toUserProfile(String root, String json, boolean local) { - return JsonAPILoader.Type.CustomSkinAPI.jsonAPI.toUserProfile(root, json, local); - } + @Override + public UserProfile toUserProfile(String root, String json, boolean local) { + return JsonAPILoader.Type.CustomSkinAPI.jsonAPI.toUserProfile(root, json, local); + } - @Override - public String getName() { - return "CustomSKinAPIPlus"; - } + @Override + public String getName() { + return "CustomSKinAPIPlus"; + } - public static class CustomSkinAPIPlusPayload{ - public String gameVersion;//minecraft version - public String modVersion;//mod version - public String serverAddress;//ip:port - public String clientID;//Minecraft Client ID - public CustomSkinAPIPlusPayload(CustomSkinAPIPlusPrivacy privacy){ - if(privacy.gameVersion) - gameVersion=MinecraftUtil.getMinecraftMainVersion(); - if(privacy.modVersion) - modVersion=CustomSkinLoader.CustomSkinLoader_VERSION; - if(privacy.serverAddress) - serverAddress=MinecraftUtil.isLanServer()?null:MinecraftUtil.getStandardServerAddress(); - if(privacy.clientID) - clientID=CustomSkinAPIPlus.clientID; - } - } - public static class CustomSkinAPIPlusPrivacy{ - public boolean gameVersion=true; - public boolean modVersion=true; - public boolean serverAddress=true; - public boolean clientID=true; - } + public static class CustomSkinAPIPlusPayload{ + public String gameVersion;//minecraft version + public String modVersion;//mod version + public String serverAddress;//ip:port + public String clientID;//Minecraft Client ID + public CustomSkinAPIPlusPayload(CustomSkinAPIPlusPrivacy privacy){ + if(privacy.gameVersion) + gameVersion=MinecraftUtil.getMinecraftMainVersion(); + if(privacy.modVersion) + modVersion=CustomSkinLoader.CustomSkinLoader_VERSION; + if(privacy.serverAddress) + serverAddress=MinecraftUtil.isLanServer()?null:MinecraftUtil.getStandardServerAddress(); + if(privacy.clientID) + clientID=CustomSkinAPIPlus.clientID; + } + } + public static class CustomSkinAPIPlusPrivacy{ + public boolean gameVersion=true; + public boolean modVersion=true; + public boolean serverAddress=true; + public boolean clientID=true; + } } diff --git a/Common/source/customskinloader/loader/jsonapi/UniSkinAPI.java b/Common/source/customskinloader/loader/jsonapi/UniSkinAPI.java index 7c51d4d..c466a9c 100644 --- a/Common/source/customskinloader/loader/jsonapi/UniSkinAPI.java +++ b/Common/source/customskinloader/loader/jsonapi/UniSkinAPI.java @@ -14,67 +14,67 @@ import customskinloader.profile.ModelManager0.Model; import customskinloader.utils.HttpTextureUtil; public class UniSkinAPI implements IJsonAPI { - private static final String TEXTURES="textures/"; - private static final String SUFFIX=".json"; + private static final String TEXTURES="textures/"; + private static final String SUFFIX=".json"; - @Override - public String toJsonUrl(String root, String username) { - return new StringBuilder().append(root).append(username).append(SUFFIX).toString(); - } + @Override + public String toJsonUrl(String root, String username) { + return new StringBuilder().append(root).append(username).append(SUFFIX).toString(); + } - @Override - public UserProfile toUserProfile(String root, String json, boolean local) { - UniSkinAPIProfile profile=CustomSkinLoader.GSON.fromJson(json, UniSkinAPIProfile.class); - UserProfile p=new UserProfile(); - - if(StringUtils.isNotBlank(profile.cape)){ - p.capeUrl=root+TEXTURES+profile.cape; - if(local) - p.capeUrl=HttpTextureUtil.getLocalFakeUrl(p.capeUrl); - } - - if(profile.skins==null||profile.skins.isEmpty()) - return p; - if(profile.model_preference==null||profile.model_preference.isEmpty()) - return p; - - boolean hasSkin=false; - for(String model:profile.model_preference){ - Model enumModel=ModelManager0.getEnumModel(model); - if(enumModel==null||StringUtils.isEmpty(profile.skins.get(model))) - continue; - if(ModelManager0.isSkin(enumModel)) - if(hasSkin) - continue; - else - hasSkin=true; - String url=root+TEXTURES+profile.skins.get(model); - if(local) - url=HttpTextureUtil.getLocalFakeUrl(url); - p.put(enumModel, url); - } - - return p; - } - /** - * Json profile for UniSkinAPI - * Source Code: https://github.com/RecursiveG/UniSkinMod/blob/master/src/main/java/org/devinprogress/uniskinmod/UniSkinApiProfile.java#L18-L22 - * @author RecursiveG - */ - private class UniSkinAPIProfile{ - public String player_name; - public long last_update; - public List model_preference; - public Map skins; - - public String cape; - } - @Override - public String getPayload(SkinSiteProfile ssp) { - return null; - } - @Override - public String getName() { - return "UniSkinAPI"; - } + @Override + public UserProfile toUserProfile(String root, String json, boolean local) { + UniSkinAPIProfile profile=CustomSkinLoader.GSON.fromJson(json, UniSkinAPIProfile.class); + UserProfile p=new UserProfile(); + + if(StringUtils.isNotBlank(profile.cape)){ + p.capeUrl=root+TEXTURES+profile.cape; + if(local) + p.capeUrl=HttpTextureUtil.getLocalFakeUrl(p.capeUrl); + } + + if(profile.skins==null||profile.skins.isEmpty()) + return p; + if(profile.model_preference==null||profile.model_preference.isEmpty()) + return p; + + boolean hasSkin=false; + for(String model:profile.model_preference){ + Model enumModel=ModelManager0.getEnumModel(model); + if(enumModel==null||StringUtils.isEmpty(profile.skins.get(model))) + continue; + if(ModelManager0.isSkin(enumModel)) + if(hasSkin) + continue; + else + hasSkin=true; + String url=root+TEXTURES+profile.skins.get(model); + if(local) + url=HttpTextureUtil.getLocalFakeUrl(url); + p.put(enumModel, url); + } + + return p; + } + /** + * Json profile for UniSkinAPI + * Source Code: https://github.com/RecursiveG/UniSkinMod/blob/master/src/main/java/org/devinprogress/uniskinmod/UniSkinApiProfile.java#L18-L22 + * @author RecursiveG + */ + private class UniSkinAPIProfile{ + public String player_name; + public long last_update; + public List model_preference; + public Map skins; + + public String cape; + } + @Override + public String getPayload(SkinSiteProfile ssp) { + return null; + } + @Override + public String getName() { + return "UniSkinAPI"; + } } diff --git a/Common/source/customskinloader/profile/DynamicSkullManager.java b/Common/source/customskinloader/profile/DynamicSkullManager.java index cb97905..054e49f 100644 --- a/Common/source/customskinloader/profile/DynamicSkullManager.java +++ b/Common/source/customskinloader/profile/DynamicSkullManager.java @@ -31,133 +31,133 @@ import customskinloader.utils.HttpTextureUtil; import customskinloader.utils.HttpUtil0; public class DynamicSkullManager { - public static class SkullTexture{ - public Map textures; - public String index;//Index File - public ArrayList skins; - public int interval; - public boolean fromZero; - //For program - public long startTime; - public int period; - } - private Map dynamicTextures=new HashMap(); - private Map> staticTextures=new HashMap>(); - private List loadingList=new ArrayList(); - - private void parseGameProfile(GameProfile profile){ - Property textureProperty=(Property)Iterables.getFirst(profile.getProperties().get("textures"), null); - if (textureProperty==null){ - staticTextures.put(profile, new HashMap()); - return; - } - String value=textureProperty.getValue(); - if(StringUtils.isBlank(value)){ - staticTextures.put(profile, new HashMap()); - return; - } - 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, new HashMap()); - return; - } - staticTextures.put(profile, (result.textures==null||!result.textures.containsKey(Type.SKIN))?new HashMap():parseTextures(result.textures)); - - if(StringUtils.isNotEmpty(result.index)){ - File indexFile=new File(CustomSkinLoader.DATA_DIR,result.index); - try{ - String index=FileUtils.readFileToString(indexFile, Charsets.UTF_8); - if(StringUtils.isNotEmpty(index)){ - ArrayList skins=CustomSkinLoader.GSON.fromJson(index, ArrayList.class); - if(skins!=null&&!skins.isEmpty()) - result.skins=skins; - } - }catch(Exception e){ - CustomSkinLoader.logger.warning("Exception occurs while parsing index file: "+e.toString()); - } - } - - if(!CustomSkinLoader.config.enableDynamicSkull||result.skins==null||result.skins.isEmpty()) - return; - - CustomSkinLoader.logger.info("Try to load Dynamic Skull: "+json); - - for(int i=0;i0){ - //Skin found - String fakeUrl=HttpTextureUtil.getLocalFakeUrl(skin); - result.skins.set(i, fakeUrl); - }else{ - //Could not find skin - result.skins.remove(i--); - continue; - } - }else{ - //Online Skin - HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(skin).setCacheFile(HttpTextureUtil.getCacheFile(FilenameUtils.getBaseName(skin))).setCacheTime(0).setLoadContent(false)); - if(!responce.success){ - //Could not load skin - result.skins.remove(i--); - continue; - } - } - } - - 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)); - dynamicTextures.put(profile, result); - staticTextures.remove(profile); - } - - //Support local skin for skull - public Map parseTextures(Map textures) { - MinecraftProfileTexture skin=textures.get(Type.SKIN); - String skinUrl=skin.getUrl(); - if(!HttpUtil0.isLocal(skinUrl)) - return textures; - File skinFile=new File(CustomSkinLoader.DATA_DIR,skinUrl); - if(!skinFile.isFile()) - return new HashMap(); - textures.put(Type.SKIN, ModelManager0.getProfileTexture(HttpTextureUtil.getLocalFakeUrl(skinUrl), null)); - return textures; - } + public static class SkullTexture{ + public Map textures; + public String index;//Index File + public ArrayList skins; + public int interval; + public boolean fromZero; + //For program + public long startTime; + public int period; + } + private Map dynamicTextures=new HashMap(); + private Map> staticTextures=new HashMap>(); + private List loadingList=new ArrayList(); + + private void parseGameProfile(GameProfile profile){ + Property textureProperty=(Property)Iterables.getFirst(profile.getProperties().get("textures"), null); + if (textureProperty==null){ + staticTextures.put(profile, new HashMap()); + return; + } + String value=textureProperty.getValue(); + if(StringUtils.isBlank(value)){ + staticTextures.put(profile, new HashMap()); + return; + } + 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, new HashMap()); + return; + } + staticTextures.put(profile, (result.textures==null||!result.textures.containsKey(Type.SKIN))?new HashMap():parseTextures(result.textures)); + + if(StringUtils.isNotEmpty(result.index)){ + File indexFile=new File(CustomSkinLoader.DATA_DIR,result.index); + try{ + String index=FileUtils.readFileToString(indexFile, Charsets.UTF_8); + if(StringUtils.isNotEmpty(index)){ + ArrayList skins=CustomSkinLoader.GSON.fromJson(index, ArrayList.class); + if(skins!=null&&!skins.isEmpty()) + result.skins=skins; + } + }catch(Exception e){ + CustomSkinLoader.logger.warning("Exception occurs while parsing index file: "+e.toString()); + } + } + + if(!CustomSkinLoader.config.enableDynamicSkull||result.skins==null||result.skins.isEmpty()) + return; + + CustomSkinLoader.logger.info("Try to load Dynamic Skull: "+json); + + for(int i=0;i0){ + //Skin found + String fakeUrl=HttpTextureUtil.getLocalFakeUrl(skin); + result.skins.set(i, fakeUrl); + }else{ + //Could not find skin + result.skins.remove(i--); + continue; + } + }else{ + //Online Skin + HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(skin).setCacheFile(HttpTextureUtil.getCacheFile(FilenameUtils.getBaseName(skin))).setCacheTime(0).setLoadContent(false)); + if(!responce.success){ + //Could not load skin + result.skins.remove(i--); + continue; + } + } + } + + 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)); + dynamicTextures.put(profile, result); + staticTextures.remove(profile); + } + + //Support local skin for skull + public Map parseTextures(Map textures) { + MinecraftProfileTexture skin=textures.get(Type.SKIN); + String skinUrl=skin.getUrl(); + if(!HttpUtil0.isLocal(skinUrl)) + return textures; + File skinFile=new File(CustomSkinLoader.DATA_DIR,skinUrl); + if(!skinFile.isFile()) + return new HashMap(); + textures.put(Type.SKIN, ModelManager0.getProfileTexture(HttpTextureUtil.getLocalFakeUrl(skinUrl), null)); + return textures; + } - public Map getTexture(final GameProfile profile){ - if(staticTextures.get(profile)!=null) - return staticTextures.get(profile); - if(loadingList.contains(profile)) - return new HashMap(); - 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 map=Maps.newHashMap(); - map.put(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()); - loadThread.start(); - return new HashMap(); - } + public Map getTexture(final GameProfile profile){ + if(staticTextures.get(profile)!=null) + return staticTextures.get(profile); + if(loadingList.contains(profile)) + return new HashMap(); + 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 map=Maps.newHashMap(); + map.put(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()); + loadThread.start(); + return new HashMap(); + } } diff --git a/Common/source/customskinloader/profile/ModelManager0.java b/Common/source/customskinloader/profile/ModelManager0.java index e095f96..48d9ed7 100644 --- a/Common/source/customskinloader/profile/ModelManager0.java +++ b/Common/source/customskinloader/profile/ModelManager0.java @@ -16,106 +16,106 @@ import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type; * @since 13.1 */ public class ModelManager0 { - public static enum Model{ - SKIN_DEFAULT, - SKIN_SLIM, - CAPE, - ELYTRA - } - private static HashMap models=new HashMap(); - private static Type typeElytra=null; - static{ - for(Type type:Type.values()){ - if(type.ordinal()==2)//ELYTRA - typeElytra=type; - } - models.put("default", Model.SKIN_DEFAULT); - models.put("slim", Model.SKIN_SLIM); - models.put("cape", Model.CAPE); - if(typeElytra!=null) - models.put("elytra", Model.ELYTRA); - } - - /** - * Get enum for the model. - * @param model - string model - * @since 14.5 - */ - public static Model getEnumModel(String model){ - return models.get(model); - } - - /** - * Check if model is skin. - * @since 14.5 - * */ - public static boolean isSkin(Model model){ - return model==Model.SKIN_DEFAULT||model==Model.SKIN_SLIM; - } - - /** - * Check if elytra is supported. - * @since 14.5 - */ - public static boolean isElytraSupported(){ - return typeElytra!=null; - } - - /** - * Parse hashMapProfile to UserProfile - * @param profile - hashMapProfile (HashMap) - * @return profile - UserProfile instance - * @since 13.1 - */ - public static UserProfile toUserProfile(Map profile){ - UserProfile userProfile=new UserProfile(); - if(profile==null) - return userProfile; - MinecraftProfileTexture skin=(MinecraftProfileTexture)profile.get(Type.SKIN); - userProfile.skinUrl= skin==null?null:skin.getUrl();//Avoid NullPointerException - userProfile.model= skin==null?null:skin.getMetadata("model"); - if(StringUtils.isEmpty(userProfile.model)) - userProfile.model="default"; - - MinecraftProfileTexture cape=(MinecraftProfileTexture)profile.get(Type.CAPE); - userProfile.capeUrl= cape==null?null:cape.getUrl(); - return userProfile; - } - - /** - * Parse UserProfile to hashMapProfile - * @param profile - UserProfile instance - * @return profile - hashMapProfile (HashMap) - * @since 13.1 - */ - public static Map fromUserProfile(UserProfile profile){ - Map map=Maps.newHashMap(); - if(profile==null) - return map; - if(profile.skinUrl!=null){ - Map metadata=null; - if(profile.model!=null&&profile.model.equals("slim")){ - metadata = Maps.newHashMap(); - metadata.put("model", "slim"); - } - map.put(Type.SKIN, getProfileTexture(profile.skinUrl,metadata)); - } - if(profile.capeUrl!=null) - map.put(Type.CAPE, getProfileTexture(profile.capeUrl,null)); - if(typeElytra!=null && profile.elytraUrl!=null) - map.put(typeElytra, getProfileTexture(profile.elytraUrl,null)); - return map; - } - - /** - * Parse url to MinecraftProfileTexture - * - * @param url - textureUrl - * metadata - metadata - * @return MinecraftProfileTexture - * @since 14.5 - */ - public static MinecraftProfileTexture getProfileTexture(String url,Map metadata){ - return new MinecraftProfileTexture(url,metadata); - } + public static enum Model{ + SKIN_DEFAULT, + SKIN_SLIM, + CAPE, + ELYTRA + } + private static HashMap models=new HashMap(); + private static Type typeElytra=null; + static{ + for(Type type:Type.values()){ + if(type.ordinal()==2)//ELYTRA + typeElytra=type; + } + models.put("default", Model.SKIN_DEFAULT); + models.put("slim", Model.SKIN_SLIM); + models.put("cape", Model.CAPE); + if(typeElytra!=null) + models.put("elytra", Model.ELYTRA); + } + + /** + * Get enum for the model. + * @param model - string model + * @since 14.5 + */ + public static Model getEnumModel(String model){ + return models.get(model); + } + + /** + * Check if model is skin. + * @since 14.5 + * */ + public static boolean isSkin(Model model){ + return model==Model.SKIN_DEFAULT||model==Model.SKIN_SLIM; + } + + /** + * Check if elytra is supported. + * @since 14.5 + */ + public static boolean isElytraSupported(){ + return typeElytra!=null; + } + + /** + * Parse hashMapProfile to UserProfile + * @param profile - hashMapProfile (HashMap) + * @return profile - UserProfile instance + * @since 13.1 + */ + public static UserProfile toUserProfile(Map profile){ + UserProfile userProfile=new UserProfile(); + if(profile==null) + return userProfile; + MinecraftProfileTexture skin=(MinecraftProfileTexture)profile.get(Type.SKIN); + userProfile.skinUrl= skin==null?null:skin.getUrl();//Avoid NullPointerException + userProfile.model= skin==null?null:skin.getMetadata("model"); + if(StringUtils.isEmpty(userProfile.model)) + userProfile.model="default"; + + MinecraftProfileTexture cape=(MinecraftProfileTexture)profile.get(Type.CAPE); + userProfile.capeUrl= cape==null?null:cape.getUrl(); + return userProfile; + } + + /** + * Parse UserProfile to hashMapProfile + * @param profile - UserProfile instance + * @return profile - hashMapProfile (HashMap) + * @since 13.1 + */ + public static Map fromUserProfile(UserProfile profile){ + Map map=Maps.newHashMap(); + if(profile==null) + return map; + if(profile.skinUrl!=null){ + Map metadata=null; + if(profile.model!=null&&profile.model.equals("slim")){ + metadata = Maps.newHashMap(); + metadata.put("model", "slim"); + } + map.put(Type.SKIN, getProfileTexture(profile.skinUrl,metadata)); + } + if(profile.capeUrl!=null) + map.put(Type.CAPE, getProfileTexture(profile.capeUrl,null)); + if(typeElytra!=null && profile.elytraUrl!=null) + map.put(typeElytra, getProfileTexture(profile.elytraUrl,null)); + return map; + } + + /** + * Parse url to MinecraftProfileTexture + * + * @param url - textureUrl + * metadata - metadata + * @return MinecraftProfileTexture + * @since 14.5 + */ + public static MinecraftProfileTexture getProfileTexture(String url,Map metadata){ + return new MinecraftProfileTexture(url,metadata); + } } diff --git a/Common/source/customskinloader/profile/ProfileCache.java b/Common/source/customskinloader/profile/ProfileCache.java index 9fb028d..c083add 100644 --- a/Common/source/customskinloader/profile/ProfileCache.java +++ b/Common/source/customskinloader/profile/ProfileCache.java @@ -11,96 +11,96 @@ import customskinloader.CustomSkinLoader; import customskinloader.utils.TimeUtil; public class ProfileCache { - public static File PROFILE_CACHE_DIR=new File(CustomSkinLoader.DATA_DIR,"ProfileCache"); - - private HashMap cachedProfiles=new HashMap(); - private HashMap localProfiles=new HashMap(); - - public ProfileCache(){ - if(!PROFILE_CACHE_DIR.exists()) - PROFILE_CACHE_DIR.mkdir(); - } - - public boolean isExist(String username){ - return cachedProfiles.containsKey(username.toLowerCase()); - } - public boolean isReady(String username){ - CachedProfile cp=cachedProfiles.get(username.toLowerCase()); - return cp==null?false:(cp.loading||cp.expiryTime>TimeUtil.getCurrentUnixTimestamp()); - } - public boolean isExpired(String username){ - CachedProfile cp=cachedProfiles.get(username.toLowerCase()); - return cp==null?true:(cp.expiryTime<=TimeUtil.getCurrentUnixTimestamp()); - } - - public UserProfile getProfile(String username){ - return getCachedProfile(username).profile; - } - public long getExpiry(String username){ - return getCachedProfile(username).expiryTime; - } - public UserProfile getLocalProfile(String username){ - if(localProfiles.containsKey(username.toLowerCase())) - return localProfiles.get(username.toLowerCase()); - return loadLocalProfile(username); - } - - public void setLoading(String username,boolean loading){ - getCachedProfile(username).loading=loading; - } - public void updateCache(String username,UserProfile profile){ - updateCache(username,profile,CustomSkinLoader.config.enableLocalProfileCache); - } - public void updateCache(String username,UserProfile profile,boolean saveLocalProfile){ - CachedProfile cp=getCachedProfile(username); - cp.profile=profile; - cp.expiryTime=TimeUtil.getUnixTimestampRandomDelay(CustomSkinLoader.config.cacheExpiry); - if(!saveLocalProfile) - return; - saveLocalProfile(username,profile); - } - - private CachedProfile getCachedProfile(String username){ - CachedProfile cp=cachedProfiles.get(username.toLowerCase()); - if(cp!=null) - return cp; - cp=new CachedProfile(); - cachedProfiles.put(username.toLowerCase(), cp); - return cp; - } - private UserProfile loadLocalProfile(String username){ - File localProfile=new File(PROFILE_CACHE_DIR,username.toLowerCase()+".json"); - if(!localProfile.exists()){ - localProfiles.put(username.toLowerCase(), null); - } - try{ - String json=IOUtils.toString(new FileInputStream(localProfile)); - UserProfile profile=CustomSkinLoader.GSON.fromJson(json, UserProfile.class); - localProfiles.put(username.toLowerCase(), profile); - CustomSkinLoader.logger.info("Successfully load LocalProfile."); - return profile; - }catch(Exception e){ - CustomSkinLoader.logger.info("Failed to load LocalProfile.("+e.toString()+")"); - localProfiles.put(username.toLowerCase(), null); - } - return null; - } - private void saveLocalProfile(String username,UserProfile profile){ - String json=CustomSkinLoader.GSON.toJson(profile); - File localProfile=new File(PROFILE_CACHE_DIR,username+".json"); - if(localProfile.exists()) - localProfile.delete(); - try { - localProfile.createNewFile(); - IOUtils.write(json, new FileOutputStream(localProfile)); - CustomSkinLoader.logger.info("Successfully save LocalProfile."); - } catch (Exception e) { - CustomSkinLoader.logger.info("Failed to save LocalProfile.("+e.toString()+")"); - } - } + public static File PROFILE_CACHE_DIR=new File(CustomSkinLoader.DATA_DIR,"ProfileCache"); + + private HashMap cachedProfiles=new HashMap(); + private HashMap localProfiles=new HashMap(); + + public ProfileCache(){ + if(!PROFILE_CACHE_DIR.exists()) + PROFILE_CACHE_DIR.mkdir(); + } + + public boolean isExist(String username){ + return cachedProfiles.containsKey(username.toLowerCase()); + } + public boolean isReady(String username){ + CachedProfile cp=cachedProfiles.get(username.toLowerCase()); + return cp==null?false:(cp.loading||cp.expiryTime>TimeUtil.getCurrentUnixTimestamp()); + } + public boolean isExpired(String username){ + CachedProfile cp=cachedProfiles.get(username.toLowerCase()); + return cp==null?true:(cp.expiryTime<=TimeUtil.getCurrentUnixTimestamp()); + } + + public UserProfile getProfile(String username){ + return getCachedProfile(username).profile; + } + public long getExpiry(String username){ + return getCachedProfile(username).expiryTime; + } + public UserProfile getLocalProfile(String username){ + if(localProfiles.containsKey(username.toLowerCase())) + return localProfiles.get(username.toLowerCase()); + return loadLocalProfile(username); + } + + public void setLoading(String username,boolean loading){ + getCachedProfile(username).loading=loading; + } + public void updateCache(String username,UserProfile profile){ + updateCache(username,profile,CustomSkinLoader.config.enableLocalProfileCache); + } + public void updateCache(String username,UserProfile profile,boolean saveLocalProfile){ + CachedProfile cp=getCachedProfile(username); + cp.profile=profile; + cp.expiryTime=TimeUtil.getUnixTimestampRandomDelay(CustomSkinLoader.config.cacheExpiry); + if(!saveLocalProfile) + return; + saveLocalProfile(username,profile); + } + + private CachedProfile getCachedProfile(String username){ + CachedProfile cp=cachedProfiles.get(username.toLowerCase()); + if(cp!=null) + return cp; + cp=new CachedProfile(); + cachedProfiles.put(username.toLowerCase(), cp); + return cp; + } + private UserProfile loadLocalProfile(String username){ + File localProfile=new File(PROFILE_CACHE_DIR,username.toLowerCase()+".json"); + if(!localProfile.exists()){ + localProfiles.put(username.toLowerCase(), null); + } + try{ + String json=IOUtils.toString(new FileInputStream(localProfile)); + UserProfile profile=CustomSkinLoader.GSON.fromJson(json, UserProfile.class); + localProfiles.put(username.toLowerCase(), profile); + CustomSkinLoader.logger.info("Successfully load LocalProfile."); + return profile; + }catch(Exception e){ + CustomSkinLoader.logger.info("Failed to load LocalProfile.("+e.toString()+")"); + localProfiles.put(username.toLowerCase(), null); + } + return null; + } + private void saveLocalProfile(String username,UserProfile profile){ + String json=CustomSkinLoader.GSON.toJson(profile); + File localProfile=new File(PROFILE_CACHE_DIR,username+".json"); + if(localProfile.exists()) + localProfile.delete(); + try { + localProfile.createNewFile(); + IOUtils.write(json, new FileOutputStream(localProfile)); + CustomSkinLoader.logger.info("Successfully save LocalProfile."); + } catch (Exception e) { + CustomSkinLoader.logger.info("Failed to save LocalProfile.("+e.toString()+")"); + } + } } class CachedProfile{ - public UserProfile profile; - public long expiryTime=0; - public boolean loading=false; + public UserProfile profile; + public long expiryTime=0; + public boolean loading=false; } \ No newline at end of file diff --git a/Common/source/customskinloader/profile/UserProfile.java b/Common/source/customskinloader/profile/UserProfile.java index cbeb689..bbd2775 100644 --- a/Common/source/customskinloader/profile/UserProfile.java +++ b/Common/source/customskinloader/profile/UserProfile.java @@ -9,94 +9,94 @@ import customskinloader.profile.ModelManager0.Model; * @since 13.1 */ public class UserProfile { - - /** - * Direct url for skin. - * @since 13.1 - */ - public String skinUrl=null; - - /** - * Model for skin. - * default/slim - * @since 13.1 - */ - public String model=null; - - /** - * Direct url for cape. - * @since 13.1 - */ - public String capeUrl=null; - - /** - * Direct url for elytra. - * @since 14.5 - */ - public String elytraUrl=null; - - public void put(Model model,String url){ - if(model==null||StringUtils.isEmpty(url)) - return; - switch(model){ - case SKIN_DEFAULT: - this.skinUrl=url; - this.model="default"; - return; - case SKIN_SLIM: - this.skinUrl=url; - this.model="slim"; - return; - case CAPE: - this.capeUrl=url; - return; - case ELYTRA: - this.capeUrl=url; - return; - } - } - - /** - * Get parsed String to output the instance. - */ - @Override - public String toString(){ - return toString(0); - } - public String toString(long expiry){ - return "(SkinUrl: "+skinUrl+ - " , Model: "+model+ - " , CapeUrl: "+capeUrl+ - (StringUtils.isBlank(elytraUrl)?" ":" , ElytraUrl: "+elytraUrl)+ - (expiry==0?"":(" , Expiry: "+expiry))+")"; - } - - /** - * Check if the instance is empty. - * @return status (true - empty) - */ - public boolean isEmpty(){ - return StringUtils.isEmpty(skinUrl) && StringUtils.isEmpty(capeUrl) && StringUtils.isEmpty(elytraUrl); - } - /** - * Check if the instance is full(Both skin and cape). - * @return status (true - full) - * @since 14.7 - */ - public boolean isFull(){ - return StringUtils.isNoneBlank(skinUrl,capeUrl); - } - public boolean hasSkinUrl(){ - return StringUtils.isNotEmpty(skinUrl); - } - public void mix(UserProfile profile){ - if(profile==null) - return; - if(StringUtils.isEmpty(this.skinUrl)) - this.skinUrl=profile.skinUrl; - if(StringUtils.isEmpty(this.capeUrl)) - this.capeUrl=profile.capeUrl; - if(StringUtils.isEmpty(this.elytraUrl)) - this.elytraUrl=profile.elytraUrl; - } + + /** + * Direct url for skin. + * @since 13.1 + */ + public String skinUrl=null; + + /** + * Model for skin. + * default/slim + * @since 13.1 + */ + public String model=null; + + /** + * Direct url for cape. + * @since 13.1 + */ + public String capeUrl=null; + + /** + * Direct url for elytra. + * @since 14.5 + */ + public String elytraUrl=null; + + public void put(Model model,String url){ + if(model==null||StringUtils.isEmpty(url)) + return; + switch(model){ + case SKIN_DEFAULT: + this.skinUrl=url; + this.model="default"; + return; + case SKIN_SLIM: + this.skinUrl=url; + this.model="slim"; + return; + case CAPE: + this.capeUrl=url; + return; + case ELYTRA: + this.capeUrl=url; + return; + } + } + + /** + * Get parsed String to output the instance. + */ + @Override + public String toString(){ + return toString(0); + } + public String toString(long expiry){ + return "(SkinUrl: "+skinUrl+ + " , Model: "+model+ + " , CapeUrl: "+capeUrl+ + (StringUtils.isBlank(elytraUrl)?" ":" , ElytraUrl: "+elytraUrl)+ + (expiry==0?"":(" , Expiry: "+expiry))+")"; + } + + /** + * Check if the instance is empty. + * @return status (true - empty) + */ + public boolean isEmpty(){ + return StringUtils.isEmpty(skinUrl) && StringUtils.isEmpty(capeUrl) && StringUtils.isEmpty(elytraUrl); + } + /** + * Check if the instance is full(Both skin and cape). + * @return status (true - full) + * @since 14.7 + */ + public boolean isFull(){ + return StringUtils.isNoneBlank(skinUrl,capeUrl); + } + public boolean hasSkinUrl(){ + return StringUtils.isNotEmpty(skinUrl); + } + public void mix(UserProfile profile){ + if(profile==null) + return; + if(StringUtils.isEmpty(this.skinUrl)) + this.skinUrl=profile.skinUrl; + if(StringUtils.isEmpty(this.capeUrl)) + this.capeUrl=profile.capeUrl; + if(StringUtils.isEmpty(this.elytraUrl)) + this.elytraUrl=profile.elytraUrl; + } } diff --git a/Common/source/customskinloader/tweaker/ClassTransformer.java b/Common/source/customskinloader/tweaker/ClassTransformer.java index fada590..1e8d733 100644 --- a/Common/source/customskinloader/tweaker/ClassTransformer.java +++ b/Common/source/customskinloader/tweaker/ClassTransformer.java @@ -17,109 +17,109 @@ import net.minecraft.launchwrapper.IClassTransformer; public class ClassTransformer implements IClassTransformer { - private ZipFile zipFile = null; - private ArrayList classes=new ArrayList(); + private ZipFile zipFile = null; + private ArrayList classes=new ArrayList(); - public ClassTransformer() { - ModSystemTweaker.logger.info("ClassTransformer Begin"); - try { - URLClassLoader ucl = (URLClassLoader)this.getClass().getClassLoader(); - URL urls[] = ucl.getURLs(); - for (URL url : urls) { - if(MinecraftUtil.isCoreFile(url)){ - ModSystemTweaker.logger.debug(url.toString()+" : SKIP (core file)."); - continue; - } - if(MinecraftUtil.isLibraryFile(url)){ - ModSystemTweaker.logger.debug(url.toString()+" : SKIP (library file)."); - continue; - } - File file = new File(url.toURI()); - if(file==null||!file.isFile()){ - ModSystemTweaker.logger.info(url.toString()+" : EXCEPTION (file not found)."); - continue; - } - ZipFile tempZipFile = getZipFile(file); - if(tempZipFile==null){ - ModSystemTweaker.logger.info(url.toString()+" : EXCEPTION (^ Message ^)."); - continue; - } - if (tempZipFile.getEntry("customskinloader/tweaker/ClassTransformer.class") == null){ - tempZipFile.close(); - ModSystemTweaker.logger.debug(url.toString()+" : FINISH (not target)."); - continue; - } - zipFile = tempZipFile; - Enumeration entries=(Enumeration) zipFile.entries(); - StringBuilder sb=new StringBuilder(); - while(entries.hasMoreElements()){ - ZipEntry entry=entries.nextElement(); - String name=entry.getName(); - if(name.endsWith(".class")&&(!name.contains("/")||name.startsWith("net"))){ - classes.add(name); - sb.append(" "); - sb.append(name); - } - } - ModSystemTweaker.logger.info(url.toString()+" : CHOOSE."); - ModSystemTweaker.logger.info("Classes:" + sb.toString()); - break; - } - } catch (Exception e) { - ModSystemTweaker.logger.warning(e); - } - if (zipFile == null) { - ModSystemTweaker.logger.info("Can not find JAR in the classpath."); - } - } + public ClassTransformer() { + ModSystemTweaker.logger.info("ClassTransformer Begin"); + try { + URLClassLoader ucl = (URLClassLoader)this.getClass().getClassLoader(); + URL urls[] = ucl.getURLs(); + for (URL url : urls) { + if(MinecraftUtil.isCoreFile(url)){ + ModSystemTweaker.logger.debug(url.toString()+" : SKIP (core file)."); + continue; + } + if(MinecraftUtil.isLibraryFile(url)){ + ModSystemTweaker.logger.debug(url.toString()+" : SKIP (library file)."); + continue; + } + File file = new File(url.toURI()); + if(file==null||!file.isFile()){ + ModSystemTweaker.logger.info(url.toString()+" : EXCEPTION (file not found)."); + continue; + } + ZipFile tempZipFile = getZipFile(file); + if(tempZipFile==null){ + ModSystemTweaker.logger.info(url.toString()+" : EXCEPTION (^ Message ^)."); + continue; + } + if (tempZipFile.getEntry("customskinloader/tweaker/ClassTransformer.class") == null){ + tempZipFile.close(); + ModSystemTweaker.logger.debug(url.toString()+" : FINISH (not target)."); + continue; + } + zipFile = tempZipFile; + Enumeration entries=(Enumeration) zipFile.entries(); + StringBuilder sb=new StringBuilder(); + while(entries.hasMoreElements()){ + ZipEntry entry=entries.nextElement(); + String name=entry.getName(); + if(name.endsWith(".class")&&(!name.contains("/")||name.startsWith("net"))){ + classes.add(name); + sb.append(" "); + sb.append(name); + } + } + ModSystemTweaker.logger.info(url.toString()+" : CHOOSE."); + ModSystemTweaker.logger.info("Classes:" + sb.toString()); + break; + } + } catch (Exception e) { + ModSystemTweaker.logger.warning(e); + } + if (zipFile == null) { + ModSystemTweaker.logger.info("Can not find JAR in the classpath."); + } + } - private static ZipFile getZipFile(File file) - { - ZipFile zipFile0=null; - try { - zipFile0 = new ZipFile(file); - return zipFile0; - } catch (Exception e) { - ModSystemTweaker.logger.warning(e); - } - return null; - } + private static ZipFile getZipFile(File file) + { + ZipFile zipFile0=null; + try { + zipFile0 = new ZipFile(file); + return zipFile0; + } catch (Exception e) { + ModSystemTweaker.logger.warning(e); + } + return null; + } - public byte[] transform(String name, String transformedName, byte bytes[]) { - if (zipFile == null) - return bytes; - - String fullName = new StringBuilder().append(name.startsWith("net") ? name.replaceAll("\\.", "\\/") : name).append(".class").toString();//Notch(Run)/MCP(Dev) Class Name - if(!classes.contains(fullName)){//Check Name - if(name.equals(transformedName)) - return bytes; - fullName = new StringBuilder().append(transformedName.replaceAll("\\.", "\\/")).append(".class").toString();//MCP Class Name - if(!classes.contains(fullName))//check Again - return bytes; - } - ZipEntry ze = zipFile.getEntry(fullName); - if (ze == null) - return bytes; - byte diBytes[] = getClass(ze); - if (diBytes != null) { - ModSystemTweaker.logger.info("Class '" + name + "'("+transformedName+") transformed."); - return diBytes; - } - else - return bytes; - } + public byte[] transform(String name, String transformedName, byte bytes[]) { + if (zipFile == null) + return bytes; + + String fullName = new StringBuilder().append(name.startsWith("net") ? name.replaceAll("\\.", "\\/") : name).append(".class").toString();//Notch(Run)/MCP(Dev) Class Name + if(!classes.contains(fullName)){//Check Name + if(name.equals(transformedName)) + return bytes; + fullName = new StringBuilder().append(transformedName.replaceAll("\\.", "\\/")).append(".class").toString();//MCP Class Name + if(!classes.contains(fullName))//check Again + return bytes; + } + ZipEntry ze = zipFile.getEntry(fullName); + if (ze == null) + return bytes; + byte diBytes[] = getClass(ze); + if (diBytes != null) { + ModSystemTweaker.logger.info("Class '" + name + "'("+transformedName+") transformed."); + return diBytes; + } + else + return bytes; + } - private byte[] getClass(ZipEntry ze) { - try { - InputStream is = zipFile.getInputStream(ze); - byte[] bytes = IOUtils.toByteArray(is); - if ((long)bytes.length == ze.getSize()) - return bytes; - ModSystemTweaker.logger.info("Failed: " + ze.getName() + " " + bytes.length + " / " + ze.getSize()); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - - } + private byte[] getClass(ZipEntry ze) { + try { + InputStream is = zipFile.getInputStream(ze); + byte[] bytes = IOUtils.toByteArray(is); + if ((long)bytes.length == ze.getSize()) + return bytes; + ModSystemTweaker.logger.info("Failed: " + ze.getName() + " " + bytes.length + " / " + ze.getSize()); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + + } } diff --git a/Common/source/customskinloader/tweaker/ModSystemTweaker.java b/Common/source/customskinloader/tweaker/ModSystemTweaker.java index 9d3af04..2637b43 100644 --- a/Common/source/customskinloader/tweaker/ModSystemTweaker.java +++ b/Common/source/customskinloader/tweaker/ModSystemTweaker.java @@ -9,30 +9,30 @@ import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.LaunchClassLoader; public class ModSystemTweaker implements ITweaker { - - public static Logger logger = new Logger(); + + public static Logger logger = new Logger(); - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { - File tweakerLogFile = new File(gameDir,"CustomSkinLoader/Tweaker.log"); - logger = new Logger(tweakerLogFile); - - logger.info("Using ModSystemTweaker"); - logger.info("ModSystemTweaker: acceptOptions"); - } + public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { + File tweakerLogFile = new File(gameDir,"CustomSkinLoader/Tweaker.log"); + logger = new Logger(tweakerLogFile); + + logger.info("Using ModSystemTweaker"); + logger.info("ModSystemTweaker: acceptOptions"); + } - public void injectIntoClassLoader(LaunchClassLoader classLoader) { - logger.info("ModSystemTweaker: injectIntoClassLoader"); - classLoader.registerTransformer("customskinloader.tweaker.ClassTransformer"); - logger.info("ClassTransformer Registered"); - } + public void injectIntoClassLoader(LaunchClassLoader classLoader) { + logger.info("ModSystemTweaker: injectIntoClassLoader"); + classLoader.registerTransformer("customskinloader.tweaker.ClassTransformer"); + logger.info("ClassTransformer Registered"); + } - public String getLaunchTarget() { - logger.info("ModSystemTweaker: getLaunchTarget"); - return "net.minecraft.client.main.Main"; - } + public String getLaunchTarget() { + logger.info("ModSystemTweaker: getLaunchTarget"); + return "net.minecraft.client.main.Main"; + } - public String[] getLaunchArguments() { - logger.info("ModSystemTweaker: getLaunchArguments"); - return new String[0]; - } + public String[] getLaunchArguments() { + logger.info("ModSystemTweaker: getLaunchArguments"); + return new String[0]; + } } diff --git a/Common/source/customskinloader/tweaker/Tweaker.java b/Common/source/customskinloader/tweaker/Tweaker.java index dcc899f..adbc5c2 100644 --- a/Common/source/customskinloader/tweaker/Tweaker.java +++ b/Common/source/customskinloader/tweaker/Tweaker.java @@ -12,33 +12,33 @@ import net.minecraft.launchwrapper.LaunchClassLoader; public class Tweaker implements ITweaker { - private String[] args; - - public static Logger logger = new Logger(); + private String[] args; + + public static Logger logger = new Logger(); - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { - File tweakerLogFile = new File(gameDir,"CustomSkinLoader/Tweaker.log"); - logger = new Logger(tweakerLogFile); - - logger.info("Using Tweaker"); - logger.info("Tweaker: acceptOptions"); - - String[] temp={"--gameDir",gameDir.getAbsolutePath(),"--assetsDir",assetsDir.getAbsolutePath(),"--version",profile}; - this.args=ArrayUtils.addAll(args.toArray(new String[args.size()]), temp); - } + public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { + File tweakerLogFile = new File(gameDir,"CustomSkinLoader/Tweaker.log"); + logger = new Logger(tweakerLogFile); + + logger.info("Using Tweaker"); + logger.info("Tweaker: acceptOptions"); + + String[] temp={"--gameDir",gameDir.getAbsolutePath(),"--assetsDir",assetsDir.getAbsolutePath(),"--version",profile}; + this.args=ArrayUtils.addAll(args.toArray(new String[args.size()]), temp); + } - public void injectIntoClassLoader(LaunchClassLoader classLoader) { - logger.info("Tweaker: injectIntoClassLoader"); - logger.info("Loaded as a library."); - } + public void injectIntoClassLoader(LaunchClassLoader classLoader) { + logger.info("Tweaker: injectIntoClassLoader"); + logger.info("Loaded as a library."); + } - public String getLaunchTarget() { - logger.info("Tweaker: getLaunchTarget"); - return "net.minecraft.client.main.Main"; - } + public String getLaunchTarget() { + logger.info("Tweaker: getLaunchTarget"); + return "net.minecraft.client.main.Main"; + } - public String[] getLaunchArguments() { - logger.info("Tweaker: getLaunchArguments"); - return args; - } + public String[] getLaunchArguments() { + logger.info("Tweaker: getLaunchArguments"); + return args; + } } diff --git a/Common/source/customskinloader/utils/HttpRequestUtil.java b/Common/source/customskinloader/utils/HttpRequestUtil.java index 590b6fc..acce848 100644 --- a/Common/source/customskinloader/utils/HttpRequestUtil.java +++ b/Common/source/customskinloader/utils/HttpRequestUtil.java @@ -20,193 +20,193 @@ import org.apache.commons.lang3.StringUtils; import customskinloader.CustomSkinLoader; public class HttpRequestUtil { - public static class HttpRequest{ - public String url; - public String userAgent=null; - public String payload=null; - public boolean loadContent=true; - public boolean checkPNG=false; - - public int cacheTime=600;//-1=No Cache 0=Always Cache t=Default Cache Time(second) - public File cacheFile=null;//Default Cache File - - public HttpRequest(String url){ - this.url=url; - } - public HttpRequest setUserAgent(String userAgent){ - this.userAgent=userAgent; - return this; - } - public HttpRequest setPayload(String payload){ - this.payload=payload; - return this; - } - public HttpRequest setLoadContent(boolean loadContent){ - this.loadContent=loadContent; - return this; - } - public HttpRequest setCheckPNG(boolean checkPNG){ - this.checkPNG=checkPNG; - return this; - } - public HttpRequest setCacheTime(int cacheTime){ - this.cacheTime=cacheTime; - return this; - } - public HttpRequest setCacheFile(File cacheFile){ - this.cacheFile=cacheFile; - return this; - } - } - public static class HttpResponce{ - public String content=null; - public int responceCode=-1; - public boolean success=false; - public boolean fromCache=false; - } - public static class CacheInfo{ - public String url; - public String etag=null; - - public long lastModified=-1;//ms - public long expire=-1;//UNIX timestamp - } - public static final File CACHE_DIR=new File(CustomSkinLoader.DATA_DIR,"caches"); - - public static HttpResponce makeHttpRequest(HttpRequest request){ - try{ - CustomSkinLoader.logger.info("Try to request '"+request.url+(request.userAgent==null?"'.":"' with user agent '"+request.userAgent+"'.")); - //Check Cache - if(StringUtils.isNotEmpty(request.payload)) - request.cacheTime=-1;//No Cache - File cacheInfoFile=null; - CacheInfo cacheInfo=new CacheInfo(); - if(request.cacheFile==null && request.cacheTime>=0){ - String hash=DigestUtils.sha1Hex(request.url); - request.cacheFile=new File(CACHE_DIR,hash); - cacheInfoFile=new File(CACHE_DIR,hash+".json"); - } - if(request.cacheTime==0 && request.cacheFile.isFile()) - return loadFromCache(request,new HttpResponce()); - if(cacheInfoFile!=null&&cacheInfoFile.isFile()){ - String json=FileUtils.readFileToString(cacheInfoFile); - if(StringUtils.isNotEmpty(json)) - cacheInfo=CustomSkinLoader.GSON.fromJson(json, CacheInfo.class); - if(cacheInfo==null) - cacheInfo=new CacheInfo(); - if(cacheInfo.expire>=TimeUtil.getCurrentUnixTimestamp()) - return loadFromCache(request,new HttpResponce(),cacheInfo.expire); - } - - //Init Connection - String url=new URI(request.url).toASCIIString(); - if(!url.equalsIgnoreCase(request.url)) - CustomSkinLoader.logger.info("Encoded URL: "+url); - HttpURLConnection c = (HttpURLConnection) (new URL(url)).openConnection(); - c.setReadTimeout(1000 * 10); - c.setConnectTimeout(1000 * 10); - c.setDoInput(true); - c.setUseCaches(false); - c.setInstanceFollowRedirects(true); - - //Make Connection - if(cacheInfo.lastModified>=0) - c.setIfModifiedSince(cacheInfo.lastModified); - if(cacheInfo.etag!=null) - c.setRequestProperty("If-None-Match",cacheInfo.etag); - c.setRequestProperty("Accept-Encoding","gzip"); - if(request.userAgent!=null) - c.setRequestProperty("User-Agent",request.userAgent); - if(StringUtils.isNotEmpty(request.payload)){ - CustomSkinLoader.logger.info("Payload: "+request.payload); - c.setDoOutput(true); - OutputStream os=c.getOutputStream(); - IOUtils.write(request.payload, os); - IOUtils.closeQuietly(os); - } - c.connect(); - - //Check Connection - HttpResponce responce=new HttpResponce(); - responce.responceCode=c.getResponseCode(); - int res=c.getResponseCode()/100; - if(res==4||res==5){//Failed - CustomSkinLoader.logger.info("Failed to request (Response Code: "+c.getResponseCode()+")"); - return responce; - } - responce.success=true; - CustomSkinLoader.logger.info("Successfully request (Response Code: "+c.getResponseCode()+" , Content Length: "+c.getContentLength()+")"); - if(responce.responceCode==HttpURLConnection.HTTP_NOT_MODIFIED) - return loadFromCache(request,responce); - - //Load Content - InputStream is="gzip".equals(c.getContentEncoding())?new GZIPInputStream(c.getInputStream()):c.getInputStream(); - byte [] bytes = IOUtils.toByteArray(is); - if(request.checkPNG&&(bytes.length<=4||bytes[1]!=(byte)'P'||bytes[2]!=(byte)'N'||bytes[3]!=(byte)'G')){ - CustomSkinLoader.logger.info("Failed to request (Not Standard PNG)"); - responce.success=false; - return responce; - } - if(request.cacheFile!=null){ - FileUtils.writeByteArrayToFile(request.cacheFile, bytes); - if(cacheInfoFile!=null){ - cacheInfo.url=request.url; - cacheInfo.etag=c.getHeaderField("ETag"); - cacheInfo.lastModified=c.getLastModified(); - cacheInfo.expire=getExpire(c,request.cacheTime); - FileUtils.write(cacheInfoFile, CustomSkinLoader.GSON.toJson(cacheInfo)); - } - CustomSkinLoader.logger.info("Saved to cache (Length: "+request.cacheFile.length()+" , Path: '"+request.cacheFile.getAbsolutePath()+"' , Expire: "+cacheInfo.expire+")"); - } - if(!request.loadContent) - return responce; - responce.content=new String(bytes,Charsets.UTF_8); - CustomSkinLoader.logger.info("Content: "+responce.content); - return responce; - - }catch(Exception e){ - CustomSkinLoader.logger.info("Failed to request (Exception: "+e.toString()+")"); - return loadFromCache(request,new HttpResponce()); - } - } - - public static File getCacheFile(String hash){ - return new File(CACHE_DIR,hash); - } - private static HttpResponce loadFromCache(HttpRequest request,HttpResponce responce){ - return loadFromCache(request,responce,0); - } - private static HttpResponce loadFromCache(HttpRequest request,HttpResponce responce,long expireTime){ - if(request.cacheFile==null||!request.cacheFile.isFile()) - return responce; - CustomSkinLoader.logger.info("Cache file found (Length: "+request.cacheFile.length()+" , Path: '"+request.cacheFile.getAbsolutePath()+"' , Expire: "+expireTime+"')"); - responce.fromCache=true; - responce.success=true; - if(!request.loadContent) - return responce; - - CustomSkinLoader.logger.info("Try to load from cache '"+request.cacheFile.getAbsolutePath()+"'."); - try { - responce.content=FileUtils.readFileToString(request.cacheFile); - CustomSkinLoader.logger.info("Successfully load from cache"); - } catch (IOException e) { - CustomSkinLoader.logger.info("Failed to load from cache (Exception: "+e.toString()+")"); - responce.success=false; - } - return responce; - } - private final static Pattern MAX_AGE_PATTERN = Pattern.compile(".*?max-age=(\\d+).*?"); - private static long getExpire(HttpURLConnection connection,int cacheTime){ - String cacheControl=connection.getHeaderField("Cache-Control"); - if(StringUtils.isNotEmpty(cacheControl)){ - Matcher m=MAX_AGE_PATTERN.matcher(cacheControl); - if(m!=null && m.matches()) - return TimeUtil.getUnixTimestamp(Long.parseLong(m.group(m.groupCount()))); - } - long expires=connection.getExpiration(); - if(expires>0) - return expires/1000; - return TimeUtil.getUnixTimestampRandomDelay(cacheTime==0 ? 86400 : cacheTime); - - } + public static class HttpRequest{ + public String url; + public String userAgent=null; + public String payload=null; + public boolean loadContent=true; + public boolean checkPNG=false; + + public int cacheTime=600;//-1=No Cache 0=Always Cache t=Default Cache Time(second) + public File cacheFile=null;//Default Cache File + + public HttpRequest(String url){ + this.url=url; + } + public HttpRequest setUserAgent(String userAgent){ + this.userAgent=userAgent; + return this; + } + public HttpRequest setPayload(String payload){ + this.payload=payload; + return this; + } + public HttpRequest setLoadContent(boolean loadContent){ + this.loadContent=loadContent; + return this; + } + public HttpRequest setCheckPNG(boolean checkPNG){ + this.checkPNG=checkPNG; + return this; + } + public HttpRequest setCacheTime(int cacheTime){ + this.cacheTime=cacheTime; + return this; + } + public HttpRequest setCacheFile(File cacheFile){ + this.cacheFile=cacheFile; + return this; + } + } + public static class HttpResponce{ + public String content=null; + public int responceCode=-1; + public boolean success=false; + public boolean fromCache=false; + } + public static class CacheInfo{ + public String url; + public String etag=null; + + public long lastModified=-1;//ms + public long expire=-1;//UNIX timestamp + } + public static final File CACHE_DIR=new File(CustomSkinLoader.DATA_DIR,"caches"); + + public static HttpResponce makeHttpRequest(HttpRequest request){ + try{ + CustomSkinLoader.logger.info("Try to request '"+request.url+(request.userAgent==null?"'.":"' with user agent '"+request.userAgent+"'.")); + //Check Cache + if(StringUtils.isNotEmpty(request.payload)) + request.cacheTime=-1;//No Cache + File cacheInfoFile=null; + CacheInfo cacheInfo=new CacheInfo(); + if(request.cacheFile==null && request.cacheTime>=0){ + String hash=DigestUtils.sha1Hex(request.url); + request.cacheFile=new File(CACHE_DIR,hash); + cacheInfoFile=new File(CACHE_DIR,hash+".json"); + } + if(request.cacheTime==0 && request.cacheFile.isFile()) + return loadFromCache(request,new HttpResponce()); + if(cacheInfoFile!=null&&cacheInfoFile.isFile()){ + String json=FileUtils.readFileToString(cacheInfoFile); + if(StringUtils.isNotEmpty(json)) + cacheInfo=CustomSkinLoader.GSON.fromJson(json, CacheInfo.class); + if(cacheInfo==null) + cacheInfo=new CacheInfo(); + if(cacheInfo.expire>=TimeUtil.getCurrentUnixTimestamp()) + return loadFromCache(request,new HttpResponce(),cacheInfo.expire); + } + + //Init Connection + String url=new URI(request.url).toASCIIString(); + if(!url.equalsIgnoreCase(request.url)) + CustomSkinLoader.logger.info("Encoded URL: "+url); + HttpURLConnection c = (HttpURLConnection) (new URL(url)).openConnection(); + c.setReadTimeout(1000 * 10); + c.setConnectTimeout(1000 * 10); + c.setDoInput(true); + c.setUseCaches(false); + c.setInstanceFollowRedirects(true); + + //Make Connection + if(cacheInfo.lastModified>=0) + c.setIfModifiedSince(cacheInfo.lastModified); + if(cacheInfo.etag!=null) + c.setRequestProperty("If-None-Match",cacheInfo.etag); + c.setRequestProperty("Accept-Encoding","gzip"); + if(request.userAgent!=null) + c.setRequestProperty("User-Agent",request.userAgent); + if(StringUtils.isNotEmpty(request.payload)){ + CustomSkinLoader.logger.info("Payload: "+request.payload); + c.setDoOutput(true); + OutputStream os=c.getOutputStream(); + IOUtils.write(request.payload, os); + IOUtils.closeQuietly(os); + } + c.connect(); + + //Check Connection + HttpResponce responce=new HttpResponce(); + responce.responceCode=c.getResponseCode(); + int res=c.getResponseCode()/100; + if(res==4||res==5){//Failed + CustomSkinLoader.logger.info("Failed to request (Response Code: "+c.getResponseCode()+")"); + return responce; + } + responce.success=true; + CustomSkinLoader.logger.info("Successfully request (Response Code: "+c.getResponseCode()+" , Content Length: "+c.getContentLength()+")"); + if(responce.responceCode==HttpURLConnection.HTTP_NOT_MODIFIED) + return loadFromCache(request,responce); + + //Load Content + InputStream is="gzip".equals(c.getContentEncoding())?new GZIPInputStream(c.getInputStream()):c.getInputStream(); + byte [] bytes = IOUtils.toByteArray(is); + if(request.checkPNG&&(bytes.length<=4||bytes[1]!=(byte)'P'||bytes[2]!=(byte)'N'||bytes[3]!=(byte)'G')){ + CustomSkinLoader.logger.info("Failed to request (Not Standard PNG)"); + responce.success=false; + return responce; + } + if(request.cacheFile!=null){ + FileUtils.writeByteArrayToFile(request.cacheFile, bytes); + if(cacheInfoFile!=null){ + cacheInfo.url=request.url; + cacheInfo.etag=c.getHeaderField("ETag"); + cacheInfo.lastModified=c.getLastModified(); + cacheInfo.expire=getExpire(c,request.cacheTime); + FileUtils.write(cacheInfoFile, CustomSkinLoader.GSON.toJson(cacheInfo)); + } + CustomSkinLoader.logger.info("Saved to cache (Length: "+request.cacheFile.length()+" , Path: '"+request.cacheFile.getAbsolutePath()+"' , Expire: "+cacheInfo.expire+")"); + } + if(!request.loadContent) + return responce; + responce.content=new String(bytes,Charsets.UTF_8); + CustomSkinLoader.logger.info("Content: "+responce.content); + return responce; + + }catch(Exception e){ + CustomSkinLoader.logger.info("Failed to request (Exception: "+e.toString()+")"); + return loadFromCache(request,new HttpResponce()); + } + } + + public static File getCacheFile(String hash){ + return new File(CACHE_DIR,hash); + } + private static HttpResponce loadFromCache(HttpRequest request,HttpResponce responce){ + return loadFromCache(request,responce,0); + } + private static HttpResponce loadFromCache(HttpRequest request,HttpResponce responce,long expireTime){ + if(request.cacheFile==null||!request.cacheFile.isFile()) + return responce; + CustomSkinLoader.logger.info("Cache file found (Length: "+request.cacheFile.length()+" , Path: '"+request.cacheFile.getAbsolutePath()+"' , Expire: "+expireTime+"')"); + responce.fromCache=true; + responce.success=true; + if(!request.loadContent) + return responce; + + CustomSkinLoader.logger.info("Try to load from cache '"+request.cacheFile.getAbsolutePath()+"'."); + try { + responce.content=FileUtils.readFileToString(request.cacheFile); + CustomSkinLoader.logger.info("Successfully load from cache"); + } catch (IOException e) { + CustomSkinLoader.logger.info("Failed to load from cache (Exception: "+e.toString()+")"); + responce.success=false; + } + return responce; + } + private final static Pattern MAX_AGE_PATTERN = Pattern.compile(".*?max-age=(\\d+).*?"); + private static long getExpire(HttpURLConnection connection,int cacheTime){ + String cacheControl=connection.getHeaderField("Cache-Control"); + if(StringUtils.isNotEmpty(cacheControl)){ + Matcher m=MAX_AGE_PATTERN.matcher(cacheControl); + if(m!=null && m.matches()) + return TimeUtil.getUnixTimestamp(Long.parseLong(m.group(m.groupCount()))); + } + long expires=connection.getExpiration(); + if(expires>0) + return expires/1000; + return TimeUtil.getUnixTimestampRandomDelay(cacheTime==0 ? 86400 : cacheTime); + + } } diff --git a/Common/source/customskinloader/utils/HttpTextureUtil.java b/Common/source/customskinloader/utils/HttpTextureUtil.java index 7569d6e..e7d0303 100644 --- a/Common/source/customskinloader/utils/HttpTextureUtil.java +++ b/Common/source/customskinloader/utils/HttpTextureUtil.java @@ -8,75 +8,75 @@ import org.apache.commons.io.FilenameUtils; import customskinloader.CustomSkinLoader; public class HttpTextureUtil { - public static class HttpTextureInfo{ - public String url=""; - public File cacheFile; - public String hash; - } - private static final String - LEGACY_MARK="(LEGACY)", - LOCAL_MARK="(LOCAL)", - LOCAL_LEGACY_MARK="(LOCAL_LEGACY)"; - public static File defaultCacheDir; - public static void cleanCacheDir(){ - if(defaultCacheDir!=null){ - defaultCacheDir.delete(); - defaultCacheDir.mkdirs(); - } - } - public static File getCacheDir(){ - return defaultCacheDir==null?new File(MinecraftUtil.getMinecraftDataDir(),"assets/skins"):defaultCacheDir; - } - - public static HttpTextureInfo toHttpTextureInfo(String fakeUrl){ - HttpTextureInfo info=new HttpTextureInfo(); - if(fakeUrl.startsWith("http")){ - info.url=fakeUrl; - info.hash=FilenameUtils.getBaseName(fakeUrl); + public static class HttpTextureInfo{ + public String url=""; + public File cacheFile; + public String hash; + } + private static final String + LEGACY_MARK="(LEGACY)", + LOCAL_MARK="(LOCAL)", + LOCAL_LEGACY_MARK="(LOCAL_LEGACY)"; + public static File defaultCacheDir; + public static void cleanCacheDir(){ + if(defaultCacheDir!=null){ + defaultCacheDir.delete(); + defaultCacheDir.mkdirs(); + } + } + public static File getCacheDir(){ + return defaultCacheDir==null?new File(MinecraftUtil.getMinecraftDataDir(),"assets/skins"):defaultCacheDir; + } + + public static HttpTextureInfo toHttpTextureInfo(String fakeUrl){ + HttpTextureInfo info=new HttpTextureInfo(); + if(fakeUrl.startsWith("http")){ + info.url=fakeUrl; + info.hash=FilenameUtils.getBaseName(fakeUrl); info.cacheFile=getCacheFile(info.hash); return info; - } - if(fakeUrl.startsWith(LOCAL_LEGACY_MARK)){ - fakeUrl=fakeUrl.replace(LOCAL_LEGACY_MARK, ""); - String[] t=fakeUrl.split(",",2); - if(t.length!=2) - return info; - info.cacheFile=new File(CustomSkinLoader.DATA_DIR,t[1]); - info.hash=t[0]; - return info; - } - if(fakeUrl.startsWith(LOCAL_MARK)){ - fakeUrl=fakeUrl.replace(LOCAL_MARK, ""); - info.cacheFile=new File(CustomSkinLoader.DATA_DIR,fakeUrl); - info.hash=FilenameUtils.getBaseName(fakeUrl); - return info; - } - if(fakeUrl.startsWith(LEGACY_MARK)){ - fakeUrl=fakeUrl.replace(LEGACY_MARK, ""); - info.url=fakeUrl; - info.hash=DigestUtils.sha1Hex(info.url);; + } + if(fakeUrl.startsWith(LOCAL_LEGACY_MARK)){ + fakeUrl=fakeUrl.replace(LOCAL_LEGACY_MARK, ""); + String[] t=fakeUrl.split(",",2); + if(t.length!=2) + return info; + info.cacheFile=new File(CustomSkinLoader.DATA_DIR,t[1]); + info.hash=t[0]; + return info; + } + if(fakeUrl.startsWith(LOCAL_MARK)){ + fakeUrl=fakeUrl.replace(LOCAL_MARK, ""); + info.cacheFile=new File(CustomSkinLoader.DATA_DIR,fakeUrl); + info.hash=FilenameUtils.getBaseName(fakeUrl); + return info; + } + if(fakeUrl.startsWith(LEGACY_MARK)){ + fakeUrl=fakeUrl.replace(LEGACY_MARK, ""); + info.url=fakeUrl; + info.hash=DigestUtils.sha1Hex(info.url);; info.cacheFile=HttpTextureUtil.getCacheFile(info.hash); - return info; - } - return info; - } - - public static String getLegacyFakeUrl(String url){ - return LEGACY_MARK+url; - } - public static String getLocalFakeUrl(String path){ - return LOCAL_MARK+path; - } - public static String getLocalLegacyFakeUrl(String path,String hash){ - return LOCAL_LEGACY_MARK+hash+","+path; - } - public static String getHash(String url,long size,long lastModified){ - return DigestUtils.sha1Hex(size+url+lastModified); - } - public static File getCacheFile(String hash){ - return getCacheFile(defaultCacheDir,hash); - } - public static File getCacheFile(File cacheDir,String hash){ - return new File(new File(cacheDir,hash.length()>2?hash.substring(0,2):"xx"), hash); - } + return info; + } + return info; + } + + public static String getLegacyFakeUrl(String url){ + return LEGACY_MARK+url; + } + public static String getLocalFakeUrl(String path){ + return LOCAL_MARK+path; + } + public static String getLocalLegacyFakeUrl(String path,String hash){ + return LOCAL_LEGACY_MARK+hash+","+path; + } + public static String getHash(String url,long size,long lastModified){ + return DigestUtils.sha1Hex(size+url+lastModified); + } + public static File getCacheFile(String hash){ + return getCacheFile(defaultCacheDir,hash); + } + public static File getCacheFile(File cacheDir,String hash){ + return new File(new File(cacheDir,hash.length()>2?hash.substring(0,2):"xx"), hash); + } } diff --git a/Common/source/customskinloader/utils/HttpUtil0.java b/Common/source/customskinloader/utils/HttpUtil0.java index 7e6109f..d89398d 100644 --- a/Common/source/customskinloader/utils/HttpUtil0.java +++ b/Common/source/customskinloader/utils/HttpUtil0.java @@ -14,66 +14,66 @@ import javax.net.ssl.X509TrustManager; import org.apache.commons.lang3.StringUtils; public class HttpUtil0 { - public static boolean isLocal(String url){ - return url==null? false : !url.startsWith("http"); - } - - //From: http://blog.csdn.net/xiyushiyi/article/details/46685387 - public static void ignoreHttpsCertificate(){ - HostnameVerifier doNotVerify = new HostnameVerifier() { + public static boolean isLocal(String url){ + return url==null? false : !url.startsWith("http"); + } + + //From: http://blog.csdn.net/xiyushiyi/article/details/46685387 + public static void ignoreHttpsCertificate(){ + HostnameVerifier doNotVerify = new HostnameVerifier() { - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[] {}; - } - public void checkClientTrusted(X509Certificate[] chain, String authType){} - public void checkServerTrusted(X509Certificate[] chain, String authType){} - }}; + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[] {}; + } + public void checkClientTrusted(X509Certificate[] chain, String authType){} + public void checkServerTrusted(X509Certificate[] chain, String authType){} + }}; - try { - SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); - HttpsURLConnection.setDefaultHostnameVerifier(doNotVerify); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static String parseAddress(String address) { - if(StringUtils.isEmpty(address)) - return null; - String[] addresses=address.split(":"); - InetAddress add; - try { - add = InetAddress.getByName(addresses[0]); - } catch (UnknownHostException e) { - e.printStackTrace(); - return null; - } - return add.getHostAddress()+(addresses.length==2 ? addresses[1] : "25565"); - } - public static boolean isLanServer(String standardAddress){ - if(StringUtils.isEmpty(standardAddress)) - return true; - String[] addresses=standardAddress.split(":"); - int numIp=getNumIp(addresses[0]); - return numIp==0||numIp==getNumIp("127.0.0.1")|| - (numIp>=getNumIp("192.168.0.0")&&numIp<=getNumIp("192.168.255.255"))|| - (numIp>=getNumIp("10.0.0.0")&&numIp<=getNumIp("10.255.255.255"))|| - (numIp>=getNumIp("172.16.0.0")&&numIp<=getNumIp("172.31.255.255")); - } - public static int getNumIp(String ip){ - int num=0; - String[] ips=ip.split("\\."); - if(ips.length!=4) - return 0; - for(int i=0;i<4;i++) - num+=Integer.parseInt(ips[i])*(256^(3-i)); - return num; - } + try { + SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + HttpsURLConnection.setDefaultHostnameVerifier(doNotVerify); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static String parseAddress(String address) { + if(StringUtils.isEmpty(address)) + return null; + String[] addresses=address.split(":"); + InetAddress add; + try { + add = InetAddress.getByName(addresses[0]); + } catch (UnknownHostException e) { + e.printStackTrace(); + return null; + } + return add.getHostAddress()+(addresses.length==2 ? addresses[1] : "25565"); + } + public static boolean isLanServer(String standardAddress){ + if(StringUtils.isEmpty(standardAddress)) + return true; + String[] addresses=standardAddress.split(":"); + int numIp=getNumIp(addresses[0]); + return numIp==0||numIp==getNumIp("127.0.0.1")|| + (numIp>=getNumIp("192.168.0.0")&&numIp<=getNumIp("192.168.255.255"))|| + (numIp>=getNumIp("10.0.0.0")&&numIp<=getNumIp("10.255.255.255"))|| + (numIp>=getNumIp("172.16.0.0")&&numIp<=getNumIp("172.31.255.255")); + } + public static int getNumIp(String ip){ + int num=0; + String[] ips=ip.split("\\."); + if(ips.length!=4) + return 0; + for(int i=0;i<4;i++) + num+=Integer.parseInt(ips[i])*(256^(3-i)); + return num; + } } \ No newline at end of file diff --git a/Common/source/customskinloader/utils/MinecraftUtil.java b/Common/source/customskinloader/utils/MinecraftUtil.java index b3fc911..a9f78f2 100644 --- a/Common/source/customskinloader/utils/MinecraftUtil.java +++ b/Common/source/customskinloader/utils/MinecraftUtil.java @@ -21,113 +21,113 @@ import net.minecraft.client.renderer.texture.TextureManager; * */ public class MinecraftUtil { - public static File getMinecraftDataDir(){ - return net.minecraft.client.Minecraft.getMinecraft().mcDataDir; - } - public static MinecraftSessionService getSessionService(){ - return net.minecraft.client.Minecraft.getMinecraft().getSessionService(); - } - public static TextureManager getTextureManager(){ - return net.minecraft.client.Minecraft.getMinecraft().getTextureManager(); - } - - private static ArrayList minecraftVersion=new ArrayList(); - private static String minecraftMainVersion=null; - private final static Pattern MINECRAFT_VERSION_PATTERN = Pattern.compile(".*?(\\d+\\.\\d+[\\.]?\\d*).*?"); - public static ArrayList getMinecraftVersions(){ - if(minecraftVersion!=null&&!minecraftVersion.isEmpty()) - return minecraftVersion; - testProbe(); - return minecraftVersion; - } - public static String getMinecraftVersionText(){ - StringBuilder sb=new StringBuilder(); - for(String version:getMinecraftVersions()) - sb.append(version).append(" "); - return StringUtils.trim(sb.toString()); - } - public static String getMinecraftMainVersion(){ - if(minecraftMainVersion!=null) - return minecraftMainVersion; - for(String version:getMinecraftVersions()){ - Matcher m = null; - try{ - m=MINECRAFT_VERSION_PATTERN.matcher(version); - }catch(Exception e){ - e.printStackTrace(); - } - if(m==null || !m.matches()) - continue; - minecraftMainVersion=m.group(m.groupCount()); - break; - } - return minecraftMainVersion; - } - - // (domain|ip)(:port) - public static String getServerAddress(){ - net.minecraft.client.multiplayer.ServerData data=net.minecraft.client.Minecraft.getMinecraft().getCurrentServerData(); - if(data==null)//Single Player - return null; - return data.serverIP; - } - // ip:port - public static String getStandardServerAddress(){ - return HttpUtil0.parseAddress(getServerAddress()); - } - public static boolean isLanServer(){ - return HttpUtil0.isLanServer(getStandardServerAddress()); - } - public static String getCurrentUsername(){ - return net.minecraft.client.Minecraft.getMinecraft().getSession().getProfile().getName(); - } - - private final static Pattern MINECRAFT_CORE_FILE_PATTERN = Pattern.compile("^(.*?)/versions/([^\\/\\\\]*?)/([^\\/\\\\]*?).jar$"); - private static void testProbe(){ - minecraftVersion.clear(); - URLClassLoader ucl = (URLClassLoader)new MinecraftUtil().getClass().getClassLoader(); - URL urls[] = ucl.getURLs(); - for(URL url:urls){ - Matcher m = null; - try{ - m=MINECRAFT_CORE_FILE_PATTERN.matcher(URLDecoder.decode(url.getPath(),"UTF-8")); - }catch(Exception e){ - e.printStackTrace(); - } - if(m==null || !m.matches()) - continue; - minecraftVersion.add(m.group(2)); - } - } - - public static boolean isCoreFile(URL url){ - Matcher m = null; - try{ - m=MINECRAFT_CORE_FILE_PATTERN.matcher(URLDecoder.decode(url.getPath(),"UTF-8")); - }catch(Exception e){ - e.printStackTrace(); - return false; - } - return m!=null && m.matches(); - } - - private final static Pattern LIBRARY_FILE_PATTERN = Pattern.compile("^(.*?)/libraries/(.*?)/([^\\/\\\\]*?).jar$"); - public static boolean isLibraryFile(URL url){ - Matcher m = null; - try{ - m=LIBRARY_FILE_PATTERN.matcher(URLDecoder.decode(url.getPath(),"UTF-8")); - }catch(Exception e){ - e.printStackTrace(); - return false; - } - return m!=null && m.matches(); - } - - public static String getCredential(GameProfile profile) { - if(profile!=null&&profile.hashCode()!=0) - return new StringBuilder(). - append(profile.getName()).append("-").append(profile.getId().toString()).toString(); - else - return null; - } + public static File getMinecraftDataDir(){ + return net.minecraft.client.Minecraft.getMinecraft().mcDataDir; + } + public static MinecraftSessionService getSessionService(){ + return net.minecraft.client.Minecraft.getMinecraft().getSessionService(); + } + public static TextureManager getTextureManager(){ + return net.minecraft.client.Minecraft.getMinecraft().getTextureManager(); + } + + private static ArrayList minecraftVersion=new ArrayList(); + private static String minecraftMainVersion=null; + private final static Pattern MINECRAFT_VERSION_PATTERN = Pattern.compile(".*?(\\d+\\.\\d+[\\.]?\\d*).*?"); + public static ArrayList getMinecraftVersions(){ + if(minecraftVersion!=null&&!minecraftVersion.isEmpty()) + return minecraftVersion; + testProbe(); + return minecraftVersion; + } + public static String getMinecraftVersionText(){ + StringBuilder sb=new StringBuilder(); + for(String version:getMinecraftVersions()) + sb.append(version).append(" "); + return StringUtils.trim(sb.toString()); + } + public static String getMinecraftMainVersion(){ + if(minecraftMainVersion!=null) + return minecraftMainVersion; + for(String version:getMinecraftVersions()){ + Matcher m = null; + try{ + m=MINECRAFT_VERSION_PATTERN.matcher(version); + }catch(Exception e){ + e.printStackTrace(); + } + if(m==null || !m.matches()) + continue; + minecraftMainVersion=m.group(m.groupCount()); + break; + } + return minecraftMainVersion; + } + + // (domain|ip)(:port) + public static String getServerAddress(){ + net.minecraft.client.multiplayer.ServerData data=net.minecraft.client.Minecraft.getMinecraft().getCurrentServerData(); + if(data==null)//Single Player + return null; + return data.serverIP; + } + // ip:port + public static String getStandardServerAddress(){ + return HttpUtil0.parseAddress(getServerAddress()); + } + public static boolean isLanServer(){ + return HttpUtil0.isLanServer(getStandardServerAddress()); + } + public static String getCurrentUsername(){ + return net.minecraft.client.Minecraft.getMinecraft().getSession().getProfile().getName(); + } + + private final static Pattern MINECRAFT_CORE_FILE_PATTERN = Pattern.compile("^(.*?)/versions/([^\\/\\\\]*?)/([^\\/\\\\]*?).jar$"); + private static void testProbe(){ + minecraftVersion.clear(); + URLClassLoader ucl = (URLClassLoader)new MinecraftUtil().getClass().getClassLoader(); + URL urls[] = ucl.getURLs(); + for(URL url:urls){ + Matcher m = null; + try{ + m=MINECRAFT_CORE_FILE_PATTERN.matcher(URLDecoder.decode(url.getPath(),"UTF-8")); + }catch(Exception e){ + e.printStackTrace(); + } + if(m==null || !m.matches()) + continue; + minecraftVersion.add(m.group(2)); + } + } + + public static boolean isCoreFile(URL url){ + Matcher m = null; + try{ + m=MINECRAFT_CORE_FILE_PATTERN.matcher(URLDecoder.decode(url.getPath(),"UTF-8")); + }catch(Exception e){ + e.printStackTrace(); + return false; + } + return m!=null && m.matches(); + } + + private final static Pattern LIBRARY_FILE_PATTERN = Pattern.compile("^(.*?)/libraries/(.*?)/([^\\/\\\\]*?).jar$"); + public static boolean isLibraryFile(URL url){ + Matcher m = null; + try{ + m=LIBRARY_FILE_PATTERN.matcher(URLDecoder.decode(url.getPath(),"UTF-8")); + }catch(Exception e){ + e.printStackTrace(); + return false; + } + return m!=null && m.matches(); + } + + public static String getCredential(GameProfile profile) { + if(profile!=null&&profile.hashCode()!=0) + return new StringBuilder(). + append(profile.getName()).append("-").append(profile.getId().toString()).toString(); + else + return null; + } } diff --git a/Common/source/customskinloader/utils/TimeUtil.java b/Common/source/customskinloader/utils/TimeUtil.java index a12e727..9c71352 100644 --- a/Common/source/customskinloader/utils/TimeUtil.java +++ b/Common/source/customskinloader/utils/TimeUtil.java @@ -1,17 +1,17 @@ package customskinloader.utils; public class TimeUtil { - public static long getCurrentUnixTimestamp(){ - return System.currentTimeMillis()/1000l; - } - public static long getUnixTimestamp(long offset){ - return getCurrentUnixTimestamp()+offset; - } - public static long getUnixTimestampRandomDelay(long offset){ - return getCurrentUnixTimestamp()+offset+random(0,5); - } - - private static int random(int min,int max){ - return (int)(Math.random()*(max-min+1))+min; - } + public static long getCurrentUnixTimestamp(){ + return System.currentTimeMillis()/1000l; + } + public static long getUnixTimestamp(long offset){ + return getCurrentUnixTimestamp()+offset; + } + public static long getUnixTimestampRandomDelay(long offset){ + return getCurrentUnixTimestamp()+offset+random(0,5); + } + + private static int random(int min,int max){ + return (int)(Math.random()*(max-min+1))+min; + } } diff --git a/Forge/source/customskinloader/forge/PlayerTabTransformer.java b/Forge/source/customskinloader/forge/PlayerTabTransformer.java index 8b49ea4..4f91217 100644 --- a/Forge/source/customskinloader/forge/PlayerTabTransformer.java +++ b/Forge/source/customskinloader/forge/PlayerTabTransformer.java @@ -13,24 +13,24 @@ import customskinloader.forge.TransformerManager.IMethodTransformer; import customskinloader.forge.TransformerManager.TransformTarget; public class PlayerTabTransformer { - @TransformTarget(className="net.minecraft.client.gui.GuiPlayerTabOverlay", - methodNames={"func_175249_a","renderPlayerlist"}, - desc="(ILnet/minecraft/scoreboard/Scoreboard;Lnet/minecraft/scoreboard/ScoreObjective;)V") - public static class ScoreObjectiveTransformer implements IMethodTransformer{ - //From: http://git.oschina.net/AsteriskTeam/TabIconHackForge/blob/master/src/main/java/kengxxiao/tabiconhack/coremod/TabIconHackForgeClassTransformer.java#L30-L43 - @Override - public void transform(ClassNode cn, MethodNode mn) { - ListIterator iterator = mn.instructions.iterator(); + @TransformTarget(className="net.minecraft.client.gui.GuiPlayerTabOverlay", + methodNames={"func_175249_a","renderPlayerlist"}, + desc="(ILnet/minecraft/scoreboard/Scoreboard;Lnet/minecraft/scoreboard/ScoreObjective;)V") + public static class ScoreObjectiveTransformer implements IMethodTransformer{ + //From: http://git.oschina.net/AsteriskTeam/TabIconHackForge/blob/master/src/main/java/kengxxiao/tabiconhack/coremod/TabIconHackForgeClassTransformer.java#L30-L43 + @Override + public void transform(ClassNode cn, MethodNode mn) { + ListIterator iterator = mn.instructions.iterator(); while (iterator.hasNext()) { - AbstractInsnNode node = iterator.next(); - if (node instanceof VarInsnNode) - { - VarInsnNode varNode = (VarInsnNode) node; - if (varNode.getOpcode() == Opcodes.ISTORE && varNode.var == 11) - mn.instructions.set(varNode.getPrevious(), new InsnNode(Opcodes.ICONST_1)); - } + AbstractInsnNode node = iterator.next(); + if (node instanceof VarInsnNode) + { + VarInsnNode varNode = (VarInsnNode) node; + if (varNode.getOpcode() == Opcodes.ISTORE && varNode.var == 11) + mn.instructions.set(varNode.getPrevious(), new InsnNode(Opcodes.ICONST_1)); + } } - } - } + } + } } \ No newline at end of file diff --git a/Forge/source/customskinloader/forge/SkinManagerTransformer.java b/Forge/source/customskinloader/forge/SkinManagerTransformer.java index 6c9b8a2..1337311 100644 --- a/Forge/source/customskinloader/forge/SkinManagerTransformer.java +++ b/Forge/source/customskinloader/forge/SkinManagerTransformer.java @@ -14,75 +14,75 @@ import customskinloader.forge.TransformerManager.IMethodTransformer; import customskinloader.forge.TransformerManager.TransformTarget; public class SkinManagerTransformer { - @TransformTarget(className="net.minecraft.client.resources.SkinManager", - methodNames={""}, - desc="(Lnet/minecraft/client/renderer/texture/TextureManager;Ljava/io/File;Lcom/mojang/authlib/minecraft/MinecraftSessionService;)V") - public static class InitTransformer implements IMethodTransformer{ - @Override - public void transform(ClassNode cn,MethodNode mn) { - cn.fields.add(new FieldNode(Opcodes.ACC_PRIVATE, "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;", null, null)); - mn.instructions.clear(); + @TransformTarget(className="net.minecraft.client.resources.SkinManager", + methodNames={""}, + desc="(Lnet/minecraft/client/renderer/texture/TextureManager;Ljava/io/File;Lcom/mojang/authlib/minecraft/MinecraftSessionService;)V") + public static class InitTransformer implements IMethodTransformer{ + @Override + public void transform(ClassNode cn,MethodNode mn) { + cn.fields.add(new FieldNode(Opcodes.ACC_PRIVATE, "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;", null, null)); + mn.instructions.clear(); mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,0)); - mn.instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,"java/lang/Object","","()V", false)); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,0)); - mn.instructions.add(new TypeInsnNode(Opcodes.NEW, "customskinloader/fake/FakeSkinManager")); - mn.instructions.add(new InsnNode(Opcodes.DUP)); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,1)); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,2)); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,3)); - mn.instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,"customskinloader/fake/FakeSkinManager","", - "(Lnet/minecraft/client/renderer/texture/TextureManager;Ljava/io/File;Lcom/mojang/authlib/minecraft/MinecraftSessionService;)V", false)); - mn.instructions.add(new FieldInsnNode(Opcodes.PUTFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;")); - mn.instructions.add(new InsnNode(Opcodes.RETURN)); - } - } - @TransformTarget(className="net.minecraft.client.resources.SkinManager", - methodNames={"func_152789_a","loadSkin"}, - desc="(Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;)Lnet/minecraft/util/ResourceLocation;") - public static class LoadSkinTransformer implements IMethodTransformer{ - @Override - public void transform(ClassNode cn,MethodNode mn) { - mn.instructions.clear(); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,0)); - mn.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;")); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,1)); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,2)); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,3)); - mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,"customskinloader/fake/FakeSkinManager","loadSkin", - "(Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;)Lnet/minecraft/util/ResourceLocation;", false)); - mn.instructions.add(new InsnNode(Opcodes.ARETURN)); - } - } - @TransformTarget(className="net.minecraft.client.resources.SkinManager", - methodNames={"func_152790_a","loadProfileTextures"}, - desc="(Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;Z)V") - public static class LoadProfileTexturesTransformer implements IMethodTransformer{ - @Override - public void transform(ClassNode cn,MethodNode mn) { - mn.instructions.clear(); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,0)); - mn.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;")); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,1)); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,2)); - mn.instructions.add(new VarInsnNode(Opcodes.ILOAD,3)); - mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,"customskinloader/fake/FakeSkinManager","loadProfileTextures", - "(Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;Z)V", false)); - mn.instructions.add(new InsnNode(Opcodes.RETURN)); - } - } - @TransformTarget(className="net.minecraft.client.resources.SkinManager", - methodNames={"func_152788_a","loadSkinFromCache"}, - desc="(Lcom/mojang/authlib/GameProfile;)Ljava/util/Map;") - public static class LoadSkinFromCacheTransformer implements IMethodTransformer{ - @Override - public void transform(ClassNode cn,MethodNode mn) { - mn.instructions.clear(); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,0)); - mn.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;")); - mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,1)); - mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,"customskinloader/fake/FakeSkinManager","loadSkinFromCache", - "(Lcom/mojang/authlib/GameProfile;)Ljava/util/Map;", false)); - mn.instructions.add(new InsnNode(Opcodes.ARETURN)); - } - } + mn.instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,"java/lang/Object","","()V", false)); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,0)); + mn.instructions.add(new TypeInsnNode(Opcodes.NEW, "customskinloader/fake/FakeSkinManager")); + mn.instructions.add(new InsnNode(Opcodes.DUP)); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,1)); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,2)); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,3)); + mn.instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,"customskinloader/fake/FakeSkinManager","", + "(Lnet/minecraft/client/renderer/texture/TextureManager;Ljava/io/File;Lcom/mojang/authlib/minecraft/MinecraftSessionService;)V", false)); + mn.instructions.add(new FieldInsnNode(Opcodes.PUTFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;")); + mn.instructions.add(new InsnNode(Opcodes.RETURN)); + } + } + @TransformTarget(className="net.minecraft.client.resources.SkinManager", + methodNames={"func_152789_a","loadSkin"}, + desc="(Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;)Lnet/minecraft/util/ResourceLocation;") + public static class LoadSkinTransformer implements IMethodTransformer{ + @Override + public void transform(ClassNode cn,MethodNode mn) { + mn.instructions.clear(); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,0)); + mn.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;")); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,1)); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,2)); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,3)); + mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,"customskinloader/fake/FakeSkinManager","loadSkin", + "(Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;)Lnet/minecraft/util/ResourceLocation;", false)); + mn.instructions.add(new InsnNode(Opcodes.ARETURN)); + } + } + @TransformTarget(className="net.minecraft.client.resources.SkinManager", + methodNames={"func_152790_a","loadProfileTextures"}, + desc="(Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;Z)V") + public static class LoadProfileTexturesTransformer implements IMethodTransformer{ + @Override + public void transform(ClassNode cn,MethodNode mn) { + mn.instructions.clear(); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,0)); + mn.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;")); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,1)); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,2)); + mn.instructions.add(new VarInsnNode(Opcodes.ILOAD,3)); + mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,"customskinloader/fake/FakeSkinManager","loadProfileTextures", + "(Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;Z)V", false)); + mn.instructions.add(new InsnNode(Opcodes.RETURN)); + } + } + @TransformTarget(className="net.minecraft.client.resources.SkinManager", + methodNames={"func_152788_a","loadSkinFromCache"}, + desc="(Lcom/mojang/authlib/GameProfile;)Ljava/util/Map;") + public static class LoadSkinFromCacheTransformer implements IMethodTransformer{ + @Override + public void transform(ClassNode cn,MethodNode mn) { + mn.instructions.clear(); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,0)); + mn.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;")); + mn.instructions.add(new VarInsnNode(Opcodes.ALOAD,1)); + mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,"customskinloader/fake/FakeSkinManager","loadSkinFromCache", + "(Lcom/mojang/authlib/GameProfile;)Ljava/util/Map;", false)); + mn.instructions.add(new InsnNode(Opcodes.ARETURN)); + } + } } diff --git a/Forge/source/customskinloader/forge/SpectatorMenuTransformer.java b/Forge/source/customskinloader/forge/SpectatorMenuTransformer.java index a41ffb6..80820ce 100644 --- a/Forge/source/customskinloader/forge/SpectatorMenuTransformer.java +++ b/Forge/source/customskinloader/forge/SpectatorMenuTransformer.java @@ -13,36 +13,36 @@ import customskinloader.forge.TransformerManager.IMethodTransformer; import customskinloader.forge.TransformerManager.TransformTarget; public class SpectatorMenuTransformer { - @TransformTarget(className="net.minecraft.client.gui.spectator.PlayerMenuObject", - methodNames={""}, - desc="(Lcom/mojang/authlib/GameProfile;)V") - public static class PlayerMenuObjectTransformer implements IMethodTransformer{ + @TransformTarget(className="net.minecraft.client.gui.spectator.PlayerMenuObject", + methodNames={""}, + desc="(Lcom/mojang/authlib/GameProfile;)V") + public static class PlayerMenuObjectTransformer implements IMethodTransformer{ - @Override - public void transform(ClassNode cn, MethodNode mn) { - InsnList il=mn.instructions; - ListIterator li=il.iterator(); - - boolean flag=false; - while(li.hasNext()) { - AbstractInsnNode ain=li.next(); - if(ain.getOpcode()!=Opcodes.INVOKESTATIC) - continue; - //MethodInsnNode min=(MethodInsnNode)nn; - //min.owner="customskinloader/fake/FakeClientPlayer"; - if(!flag) { - //First InvokeStatic - il.set(ain, new MethodInsnNode(Opcodes.INVOKESTATIC,"customskinloader/fake/FakeClientPlayer","getLocationSkin", - "(Ljava/lang/String;)Lnet/minecraft/util/ResourceLocation;",false)); - flag=true; - }else { - //Second InvokeStatic - il.set(ain, new MethodInsnNode(Opcodes.INVOKESTATIC,"customskinloader/fake/FakeClientPlayer","getDownloadImageSkin", - "(Lnet/minecraft/util/ResourceLocation;Ljava/lang/String;)Lnet/minecraft/client/renderer/ThreadDownloadImageData;",false)); - break; - } - } - } - - } + @Override + public void transform(ClassNode cn, MethodNode mn) { + InsnList il=mn.instructions; + ListIterator li=il.iterator(); + + boolean flag=false; + while(li.hasNext()) { + AbstractInsnNode ain=li.next(); + if(ain.getOpcode()!=Opcodes.INVOKESTATIC) + continue; + //MethodInsnNode min=(MethodInsnNode)nn; + //min.owner="customskinloader/fake/FakeClientPlayer"; + if(!flag) { + //First InvokeStatic + il.set(ain, new MethodInsnNode(Opcodes.INVOKESTATIC,"customskinloader/fake/FakeClientPlayer","getLocationSkin", + "(Ljava/lang/String;)Lnet/minecraft/util/ResourceLocation;",false)); + flag=true; + }else { + //Second InvokeStatic + il.set(ain, new MethodInsnNode(Opcodes.INVOKESTATIC,"customskinloader/fake/FakeClientPlayer","getDownloadImageSkin", + "(Lnet/minecraft/util/ResourceLocation;Ljava/lang/String;)Lnet/minecraft/client/renderer/ThreadDownloadImageData;",false)); + break; + } + } + } + + } } diff --git a/Forge/source/customskinloader/forge/TransformerManager.java b/Forge/source/customskinloader/forge/TransformerManager.java index 06a15f3..da08530 100644 --- a/Forge/source/customskinloader/forge/TransformerManager.java +++ b/Forge/source/customskinloader/forge/TransformerManager.java @@ -22,76 +22,76 @@ import customskinloader.forge.SkinManagerTransformer.*; import customskinloader.forge.SpectatorMenuTransformer.PlayerMenuObjectTransformer; public class TransformerManager implements IClassTransformer { - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.TYPE) - public @interface TransformTarget{ - public String className(); - public String[] methodNames(); - public String desc(); - } - public interface IMethodTransformer{ - public void transform(ClassNode cn,MethodNode mn); - } - private static final IMethodTransformer[] TRANFORMERS={ - new InitTransformer(), - new LoadSkinTransformer(), - new LoadProfileTexturesTransformer(), - new LoadSkinFromCacheTransformer(), - new ScoreObjectiveTransformer(), - new PlayerMenuObjectTransformer()}; - private Map> map; - public TransformerManager(){ - map = new HashMap>(); - for(IMethodTransformer t:TRANFORMERS){ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + public @interface TransformTarget{ + public String className(); + public String[] methodNames(); + public String desc(); + } + public interface IMethodTransformer{ + public void transform(ClassNode cn,MethodNode mn); + } + private static final IMethodTransformer[] TRANFORMERS={ + new InitTransformer(), + new LoadSkinTransformer(), + new LoadProfileTexturesTransformer(), + new LoadSkinFromCacheTransformer(), + new ScoreObjectiveTransformer(), + new PlayerMenuObjectTransformer()}; + private Map> map; + public TransformerManager(){ + map = new HashMap>(); + for(IMethodTransformer t:TRANFORMERS){ FMLRelaunchLog.info("[CSL DEBUG] REGISTERING TRANSFORMER %s",t.getClass().getName()); - if(!t.getClass().isAnnotationPresent(TransformTarget.class)){ - FMLRelaunchLog.info("[CSL DEBUG] ERROR occurs while parsing Annotation."); - continue; - } - addMethodTransformer(t.getClass().getAnnotation(TransformTarget.class),t); - } - } - private void addMethodTransformer(TransformTarget target, IMethodTransformer transformer) { - if (!map.containsKey(target.className())) - map.put(target.className(), new HashMap()); - for(String methodName:target.methodNames()){ - map.get(target.className()).put(methodName + target.desc(), transformer); - FMLRelaunchLog.info("[CSL DEBUG] REGISTERING METHOD %s(%s)",target.className(),methodName + target.desc()); - } - } - - //From: https://github.com/RecursiveG/UniSkinMod/blob/1.9.4/src/main/java/org/devinprogress/uniskinmod/coremod/BaseAsmTransformer.java#L83-L114 - @Override - public byte[] transform(String obfClassName, String className, byte[] bytes) { - if (!map.containsKey(className)) return bytes; - FMLRelaunchLog.info("[CSL DEBUG] CLASS %s will be transformed", className); - Map transMap = map.get(className); - - ClassReader cr = new ClassReader(bytes); - ClassNode cn = new ClassNode(); - cr.accept(cn, 0); + if(!t.getClass().isAnnotationPresent(TransformTarget.class)){ + FMLRelaunchLog.info("[CSL DEBUG] ERROR occurs while parsing Annotation."); + continue; + } + addMethodTransformer(t.getClass().getAnnotation(TransformTarget.class),t); + } + } + private void addMethodTransformer(TransformTarget target, IMethodTransformer transformer) { + if (!map.containsKey(target.className())) + map.put(target.className(), new HashMap()); + for(String methodName:target.methodNames()){ + map.get(target.className()).put(methodName + target.desc(), transformer); + FMLRelaunchLog.info("[CSL DEBUG] REGISTERING METHOD %s(%s)",target.className(),methodName + target.desc()); + } + } + + //From: https://github.com/RecursiveG/UniSkinMod/blob/1.9.4/src/main/java/org/devinprogress/uniskinmod/coremod/BaseAsmTransformer.java#L83-L114 + @Override + public byte[] transform(String obfClassName, String className, byte[] bytes) { + if (!map.containsKey(className)) return bytes; + FMLRelaunchLog.info("[CSL DEBUG] CLASS %s will be transformed", className); + Map transMap = map.get(className); + + ClassReader cr = new ClassReader(bytes); + ClassNode cn = new ClassNode(); + cr.accept(cn, 0); - // NOTE: `map` = convert obfuscated name to srgName; - List ml = new ArrayList(); - ml.addAll(cn.methods); - for (MethodNode mn : ml) { - String methodName = FMLDeobfuscatingRemapper.INSTANCE.mapMethodName(obfClassName, mn.name, mn.desc); - String methodDesc = FMLDeobfuscatingRemapper.INSTANCE.mapMethodDesc(mn.desc); - if (transMap.containsKey(methodName + methodDesc)) { - try { - FMLRelaunchLog.info("[CSL DEBUG] Transforming method %s in class %s(%s)", methodName + methodDesc, obfClassName, className); - transMap.get(methodName + methodDesc).transform(cn,mn); - FMLRelaunchLog.info("[CSL DEBUG] Successfully transformed method %s in class %s(%s)", methodName + methodDesc, obfClassName, className); - } catch (Exception e) { - FMLRelaunchLog.warning("[CSL DEBUG] An error happened when transforming method %s in class %s(%s). The whole class was not modified.", methodName + methodDesc, obfClassName, className); - e.printStackTrace(); - return bytes; - } - } - } + // NOTE: `map` = convert obfuscated name to srgName; + List ml = new ArrayList(); + ml.addAll(cn.methods); + for (MethodNode mn : ml) { + String methodName = FMLDeobfuscatingRemapper.INSTANCE.mapMethodName(obfClassName, mn.name, mn.desc); + String methodDesc = FMLDeobfuscatingRemapper.INSTANCE.mapMethodDesc(mn.desc); + if (transMap.containsKey(methodName + methodDesc)) { + try { + FMLRelaunchLog.info("[CSL DEBUG] Transforming method %s in class %s(%s)", methodName + methodDesc, obfClassName, className); + transMap.get(methodName + methodDesc).transform(cn,mn); + FMLRelaunchLog.info("[CSL DEBUG] Successfully transformed method %s in class %s(%s)", methodName + methodDesc, obfClassName, className); + } catch (Exception e) { + FMLRelaunchLog.warning("[CSL DEBUG] An error happened when transforming method %s in class %s(%s). The whole class was not modified.", methodName + methodDesc, obfClassName, className); + e.printStackTrace(); + return bytes; + } + } + } - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - cn.accept(cw); - return cw.toByteArray(); - } + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + cn.accept(cw); + return cw.toByteArray(); + } } diff --git a/build.gradle b/build.gradle index dfc0b1b..46da81c 100644 --- a/build.gradle +++ b/build.gradle @@ -15,7 +15,7 @@ buildscript { url = "http://forgemavenmirror.sinaapp.com/maven" } */ - jcenter() + jcenter() maven { name = "forge" url = "http://files.minecraftforge.net/maven" diff --git a/common.gradle b/common.gradle index c6f6117..f093d36 100644 --- a/common.gradle +++ b/common.gradle @@ -74,7 +74,7 @@ processResources { forgeVersion:config.forge_version, //gitVersion:System.getenv("GIT_COMMIT"), //buildUrl:System.getenv("BUILD_URL") - gitVersion:System.getenv("CIRCLE_SHA1"), + gitVersion:System.getenv("CIRCLE_SHA1"), buildUrl:System.getenv("CIRCLE_BUILD_URL") ]) } @@ -101,7 +101,7 @@ task afterBuild << { copy { from 'build/libs' into '../build/libs' - include '**/*.jar' + include '**/*.jar' exclude '**/*-srg.jar' exclude '**/*-dev.jar' exclude '**/*-sources.jar'