From 2e59f9db7c54d06fb84517c763ae1751e86c997f Mon Sep 17 00:00:00 2001 From: xfl03 Date: Sat, 1 Aug 2015 22:15:14 +0800 Subject: [PATCH] Better cache, less code --- .../minecraft/idv/jlchntoz/CachedUser.java | 6 - .../idv/jlchntoz/CustomSkinLoader.java | 315 +++++++----------- .../minecraft/idv/jlchntoz/CachedUser.java | 6 - .../idv/jlchntoz/CustomSkinLoader.java | 315 +++++++----------- .../minecraft/idv/jlchntoz/CachedUser.java | 6 - .../idv/jlchntoz/CustomSkinLoader.java | 315 +++++++----------- .../minecraft/idv/jlchntoz/CachedUser.java | 6 - .../idv/jlchntoz/CustomSkinLoader.java | 315 +++++++----------- 8 files changed, 448 insertions(+), 836 deletions(-) delete mode 100644 1.6.4-mcp811/src/minecraft/idv/jlchntoz/CachedUser.java delete mode 100644 1.7.10-mcp908/src/minecraft/idv/jlchntoz/CachedUser.java delete mode 100644 1.7.2-mcp903/src/minecraft/idv/jlchntoz/CachedUser.java delete mode 100644 1.8-mcp910/src/minecraft/idv/jlchntoz/CachedUser.java diff --git a/1.6.4-mcp811/src/minecraft/idv/jlchntoz/CachedUser.java b/1.6.4-mcp811/src/minecraft/idv/jlchntoz/CachedUser.java deleted file mode 100644 index 4ac97cc..0000000 --- a/1.6.4-mcp811/src/minecraft/idv/jlchntoz/CachedUser.java +++ /dev/null @@ -1,6 +0,0 @@ -package idv.jlchntoz; - -public class CachedUser { - public String skin; - public String cloak; -} diff --git a/1.6.4-mcp811/src/minecraft/idv/jlchntoz/CustomSkinLoader.java b/1.6.4-mcp811/src/minecraft/idv/jlchntoz/CustomSkinLoader.java index 3824e01..bb57970 100644 --- a/1.6.4-mcp811/src/minecraft/idv/jlchntoz/CustomSkinLoader.java +++ b/1.6.4-mcp811/src/minecraft/idv/jlchntoz/CustomSkinLoader.java @@ -8,6 +8,7 @@ import java.net.*; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.logging.*; import java.util.regex.*; @@ -19,32 +20,30 @@ import com.google.gson.reflect.TypeToken; /** * Custom skin loader mod for Minecraft. * - * @version 12th Revision 4th Subversion 2015.6.22 + * @version 12th Revision 5th Subversion 2015.8.1 * * @author (C) Jeremy Lam [JLChnToZ] 2013 & Alexander Xia [xfl03] 2014-2015 */ public class CustomSkinLoader { - public final static String VERSION="12.4"; + public final static String VERSION="12.5"; public final static String DefaultSkinURL = "http://skins.minecraft.net/MinecraftSkins/*.png"; public final static String DefaultCloakURL = "http://skins.minecraft.net/MinecraftCloaks/*.png"; private final static Pattern newResPattern = Pattern.compile("^http://textures.minecraft.net/texture/(.*?)?(Skin|Cloak)=(.*?)$"), - newURLPattern = Pattern.compile("^http://skins.minecraft.net/Minecraft(Skin|Cloak)s/(.*?).png$"), - oldURLPattern = Pattern.compile("^http://s3.amazonaws.com/Minecraft(Skin|Cloak)s/(.*?).png$"), - optifineCapeURLPattern = Pattern.compile("^http://s.optifine.net/capes/(.*?).png$"); + newURLPattern = Pattern.compile("^http://skins.minecraft.net/Minecraft(Skin|Cloak)s/(.*?).png$"), + oldURLPattern = Pattern.compile("^http://s3.amazonaws.com/Minecraft(Skin|Cloak)s/(.*?).png$"), + optifineCapeURLPattern = Pattern.compile("^http://s.optifine.net/capes/(.*?).png$"); - private final static File DATA_DIR=new File(Minecraft.getMinecraft().mcDataDir,"CustomSkinLoader"); - private final static File CACHE_DIR=new File(DATA_DIR,"caches"); - private final static File CACHE_JSON=new File(CACHE_DIR,"caches"); - private final static MainLogger logger = new MainLogger(new File(DATA_DIR,"CustomSkinLoader.log")); + private final static File DATA_DIR=new File(Minecraft.getMinecraft().mcDataDir,"CustomSkinLoader"), + CACHE_DIR=new File(DATA_DIR,"caches"), + LOG_FILE=new File(DATA_DIR,"CustomSkinLoader.log"); + private final static MainLogger logger = new MainLogger(LOG_FILE); private static String[] cloakURLs = null, skinURLs = null; private HttpURLConnection C = null; - private boolean loadFromCache=false; - private boolean cacheSelfOnly=false; - + //Entrance public InputStream getPlayerSkinStream(String path) { if(!DATA_DIR.exists()) DATA_DIR.mkdir(); @@ -54,7 +53,7 @@ public class CustomSkinLoader { Matcher m = newURLPattern.matcher(path); if (!m.matches())//Is not new url { - m = oldURLPattern.matcher(path);//If is old url + m = oldURLPattern.matcher(path);//May be old url } if (m.matches()) { if (m.group(1).contains("Skin")) // Skin @@ -82,217 +81,139 @@ public class CustomSkinLoader { || cloakURLs.length <= 0) refreshSkinURL(); // If the list is blank or null, try to load again. InputStream S=null; - String json=""; - Gson gson=new GsonBuilder().setPrettyPrinting().create(); - HashMap users=null; - - if(CACHE_JSON.exists()&&CACHE_JSON.length()>20){ - try { - json=read(CACHE_JSON); - } catch (Exception e) { - logger.warning(e.getMessage()); - } - if(!json.equalsIgnoreCase("")){ - users=gson.fromJson(json, new TypeToken>(){}.getType()); - }else{ - users=new HashMap(); - } - }else{ - users=new HashMap(); - try { - CACHE_JSON.createNewFile(); - } catch (IOException e) { - logger.log(Level.WARNING, e.getMessage()); - } - } - - CachedUser cu=users.get(playerName); - boolean hasCache=false; - File cacheFile=null; - if(cu!=null){ - if(isCloak&&cu.cloak!=null&&!cu.cloak.equalsIgnoreCase("")) - cacheFile=new File(CACHE_DIR,cu.cloak); - else if(cu.skin!=null&&!cu.skin.equalsIgnoreCase("")) - cacheFile=new File(CACHE_DIR,cu.skin); - } - - long last=0; - if(cacheFile!=null&&cacheFile.exists()&&cacheFile.length()>0){//Have cached - last=cacheFile.lastModified(); - if(last<=0) - last=1; - } for (String l : isCloak ? cloakURLs : skinURLs) { if(l==null||l.equalsIgnoreCase("")) continue; String loc = str_replace("*", playerName, l); logger.log(Level.INFO, "Try to load " + (isCloak ? "cloak" : "skin") + " in " + loc); - S = getStream(loc, true,last); - if(last>0&&loadFromCache){ - logger.info("" + (isCloak ? "Cloak" : "Skin") + " in " + loc + " will be load from cache."); - break; - } + S = getStream(loc, true); + if (S == null){ - logger.log(Level.INFO, "No " + (isCloak ? "cloak" : "skin") - + " found in " + loc); + logger.log(Level.INFO, "No " + (isCloak ? "cloak" : "skin") + " found in " + loc); }else{ logger.info("Succeessfully load " + (isCloak ? "cloak" : "skin") + " in " + loc); - break; + return S; } } - if(S==null){ - try{//Read Local Skin File - if(last>0){ - if(cacheFile.exists() && cacheFile.length()>1){ - logger.info("Try load local " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - InputStream in = new FileInputStream(cacheFile); - BufferedInputStream bis=new BufferedInputStream(in); - if(bis.available()<=0){ - logger.info("Cannot load local " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - }else{ - logger.info("Successfully load " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - return bis; - } - }else{ - logger.info("No local " + (isCloak ? "cloak" : "skin") + " found in " + cacheFile.getAbsolutePath()); - } - }else{ - logger.info("No local " + (isCloak ? "cloak" : "skin") + " found for " + playerName); - } - }catch(Exception e){ - logger.log(Level.WARNING, e.getMessage()); - } - }else{ - File tempFile=null; - if(isCloak) - tempFile=new File(CACHE_DIR,playerName+"-cloak"); - else - tempFile=new File(CACHE_DIR,playerName+"-skin"); - logger.info("Try save local " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - FileOutputStream fs=null; - int times=0; - try{//Save to Local Skin File - //logger.info(user); - if(tempFile.exists()){ - tempFile.delete(); - } - //temp.createNewFile(); - fs = new FileOutputStream(tempFile); - int byteRead = 0; - byte[] buffer = new byte[1024]; - //S.reset(); - while (( byteRead = S.read(buffer)) != -1) { - times+=byteRead; - //logger.info(""+S.available()); - fs.write(buffer, 0, byteRead); - if(times>=C.getContentLength()){ - //logger.info(times+" "+C.getContentLength()); - break; - } - } - - if(tempFile.length()>1){ - logger.info("Successfully save " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - String md5=getMd5ByFile(tempFile); - cacheFile=new File(CACHE_DIR,md5); - fs.close(); - fs=null; - logger.info("Try to move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - if(!cacheFile.exists()||!getMd5ByFile(cacheFile).equalsIgnoreCase(md5)){ - if(tempFile.renameTo(cacheFile)){ - logger.info("Successfully move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - }else{ - logger.info("Cannot move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - } - } - if(cu==null){ - cu=new CachedUser(); - users.put(playerName, cu); - } - if(isCloak){ - cu.cloak=md5; - }else{ - cu.skin=md5; - } - String json2=gson.toJson(users); - if(!json2.equalsIgnoreCase(json)) - write(CACHE_JSON,json2); - }else{ - tempFile.delete(); - logger.info("Cannot save local " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - } - }catch(Exception e){ - //e.printStackTrace(); - //logger.info(""+times); - logger.warning(e.getMessage()); - }finally{ - try { - if(fs!=null) - fs.close(); - S.reset(); - logger.info((isCloak ? "Cloak" : "Skin")+" size : "+S.available()); - } catch (IOException e) { - logger.warning(e.getMessage()); - } - } - return S; - } logger.log(Level.INFO, "Try to load skin in default URL instead."); return getStream(str_replace("*", playerName, isCloak ? DefaultCloakURL : DefaultSkinURL), true); } + private InputStream getStream(String URL, Boolean CheckPNG) { - return getStream(URL,CheckPNG,0); - } - private InputStream getStream(String URL, Boolean CheckPNG,long last) { boolean success=false; + File cacheFile=new File(CACHE_DIR,MD5(URL)); + boolean alreadyCached=false; + if(cacheFile.exists()&&cacheFile.length()>1){ + alreadyCached=true; + logger.info("Cache File Found"); + } try { URL U = new URL(URL); C = (HttpURLConnection) U.openConnection(); + C.setReadTimeout(15000); C.setDoInput(true); C.setDoOutput(false); - if(last>0) - C.setIfModifiedSince(last); C.connect(); logger.info("RC: "+C.getResponseCode()); int respcode = C.getResponseCode() / 100; - if (respcode != 4 && respcode != 5) { // Successful (?) to get skin. - //logger.info(last+" "+C.getLastModified()); - if(C.getResponseCode()==HttpURLConnection.HTTP_NOT_MODIFIED){//304 + if (respcode != 4 && respcode != 5) { // Successful to get skin. + if(alreadyCached && C.getLastModified()==cacheFile.lastModified()){ logger.info("Not Modified!"); - loadFromCache=true; - return null; + return getStreamFromCache(cacheFile); } - if(C.getContentLength()<=0){ + if(C.getContentLength()<=0){//Nothing to get return null; } InputStream IS=new BufferedInputStream(C.getInputStream()); if (!CheckPNG){ // If no need to check PNG header, just skip it. success=true; + saveToCache(IS,cacheFile); return IS; } //logger.info(C.getContentLength()+" "+IS.available()); IS.mark(C.getContentLength()+10); byte[] ib = new byte[4]; IS.read(ib); - if (ib[1] == (byte) 'P' && ib[2] == (byte) 'N' - && ib[3] == (byte) 'G') { // Check PNG Header if needed + if (ib[1] == (byte) 'P' && ib[2] == (byte) 'N' && ib[3] == (byte) 'G') { // Check PNG Header if needed IS.reset(); success=true; + saveToCache(IS,cacheFile); return IS; } } } catch (Exception ex) { success=false; logger.log(Level.WARNING, ex.getMessage()); + if(alreadyCached) + return getStreamFromCache(cacheFile); }finally{ if(!success) disconnect(); } return null; } - + private InputStream getStreamFromCache(File cacheFile) { + try{ + logger.info("Try load local cache in " + cacheFile.getAbsolutePath()); + InputStream in = new FileInputStream(cacheFile); + BufferedInputStream bis=new BufferedInputStream(in); + if(bis.available()<=0){ + logger.info("Cannot load local cache in " + cacheFile.getAbsolutePath()); + return null; + }else{ + logger.info("Successfully load cache in " + cacheFile.getAbsolutePath()); + return bis; + } + }catch(Exception e){ + logger.log(Level.WARNING, e.getMessage()); + return null; + } + } + private void saveToCache(InputStream is,File to){ + logger.info("Try save local cache to " + to.getAbsolutePath()); + FileOutputStream fs=null; + int times=0; + try{//Save to Local Skin File + if(to.exists()){ + to.delete(); + } + fs = new FileOutputStream(to); + int byteRead = 0; + byte[] buffer = new byte[1024]; + while (( byteRead = is.read(buffer)) != -1) { + times+=byteRead; + fs.write(buffer, 0, byteRead); + if(times>=C.getContentLength()){ + //logger.info(times+" "+C.getContentLength()); + break; + } + } + + if(to.length()>1){ + logger.info("Successfully save cache to " + to.getAbsolutePath()); + }else{ + to.delete(); + logger.info("Cannot save local cache to " + to.getAbsolutePath()); + } + }catch(Exception e){ + logger.warning(e.getMessage()); + }finally{ + try { + if(fs!=null) + fs.close(); + is.reset(); + logger.info("Cache size : "+is.available()); + } catch (IOException e) { + logger.warning(e.getMessage()); + } + if(to.exists()){ + to.setLastModified(C.getLastModified()); + } + } + } + public void disconnect() { if (C != null) C.disconnect(); @@ -364,6 +285,7 @@ public class CustomSkinLoader { result.replace(pos, pos + search.length(), replace); return result.toString(); } + public static void showGUI(){ try{ Class clazz=Class.forName("idv.jlchntoz.CustomSkinLoaderGUI"); @@ -415,35 +337,22 @@ public class CustomSkinLoader { return false; } } - private void write(File file,String Data) throws Exception{ - System.out.println("Write to "+file.getAbsolutePath()); - FileWriter fw=null; - fw = new FileWriter(file); - fw.write(Data,0,Data.length()); - fw.flush(); - fw.close(); - } - private String read(File file) throws Exception{ - System.out.println("Read from "+file.getAbsolutePath()); - BufferedReader br = null; - String data=""; - br = new BufferedReader(new FileReader(file)); - data = br.readLine(); - while( br.ready()){ - data += "\r\n"+br.readLine(); - } - br.close(); - return data; - } - private String getMd5ByFile(File file) throws Exception { - String value = null; - FileInputStream in = new FileInputStream(file); - MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); - MessageDigest md5 = MessageDigest.getInstance("MD5"); - md5.update(byteBuffer); - BigInteger bi = new BigInteger(1, md5.digest()); - value = bi.toString(16); - in.close(); - return value; - } + public String MD5(String str){ + byte [] buf = str.getBytes(); + MessageDigest md5; + try { + md5 = MessageDigest.getInstance("MD5"); + md5.update(buf); + byte [] tmp = md5.digest(); + StringBuilder sb = new StringBuilder(); + for (byte b:tmp) { + sb.append(Integer.toHexString(b&0xff)); + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + logger.warning(e.getMessage()); + } + return "Fail"; + + } } diff --git a/1.7.10-mcp908/src/minecraft/idv/jlchntoz/CachedUser.java b/1.7.10-mcp908/src/minecraft/idv/jlchntoz/CachedUser.java deleted file mode 100644 index 4ac97cc..0000000 --- a/1.7.10-mcp908/src/minecraft/idv/jlchntoz/CachedUser.java +++ /dev/null @@ -1,6 +0,0 @@ -package idv.jlchntoz; - -public class CachedUser { - public String skin; - public String cloak; -} diff --git a/1.7.10-mcp908/src/minecraft/idv/jlchntoz/CustomSkinLoader.java b/1.7.10-mcp908/src/minecraft/idv/jlchntoz/CustomSkinLoader.java index 9aacee3..ed6d4f6 100644 --- a/1.7.10-mcp908/src/minecraft/idv/jlchntoz/CustomSkinLoader.java +++ b/1.7.10-mcp908/src/minecraft/idv/jlchntoz/CustomSkinLoader.java @@ -8,6 +8,7 @@ import java.net.*; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.logging.*; import java.util.regex.*; @@ -19,32 +20,30 @@ import com.google.gson.reflect.TypeToken; /** * Custom skin loader mod for Minecraft. * - * @version 12th Revision 4th Subversion 2015.6.22 + * @version 12th Revision 5th Subversion 2015.8.1 * * @author (C) Jeremy Lam [JLChnToZ] 2013 & Alexander Xia [xfl03] 2014-2015 */ public class CustomSkinLoader { - public final static String VERSION="12.4"; + public final static String VERSION="12.5"; public final static String DefaultSkinURL = "http://skins.minecraft.net/MinecraftSkins/*.png"; public final static String DefaultCloakURL = "http://skins.minecraft.net/MinecraftCloaks/*.png"; private final static Pattern newResPattern = Pattern.compile("^http://textures.minecraft.net/texture/(.*?)?(Skin|Cloak)=(.*?)$"), - newURLPattern = Pattern.compile("^http://skins.minecraft.net/Minecraft(Skin|Cloak)s/(.*?).png$"), - oldURLPattern = Pattern.compile("^http://s3.amazonaws.com/Minecraft(Skin|Cloak)s/(.*?).png$"), - optifineCapeURLPattern = Pattern.compile("^http://s.optifine.net/capes/(.*?).png$"); + newURLPattern = Pattern.compile("^http://skins.minecraft.net/Minecraft(Skin|Cloak)s/(.*?).png$"), + oldURLPattern = Pattern.compile("^http://s3.amazonaws.com/Minecraft(Skin|Cloak)s/(.*?).png$"), + optifineCapeURLPattern = Pattern.compile("^http://s.optifine.net/capes/(.*?).png$"); - private final static File DATA_DIR=new File(Minecraft.getMinecraft().mcDataDir,"CustomSkinLoader"); - private final static File CACHE_DIR=new File(DATA_DIR,"caches"); - private final static File CACHE_JSON=new File(CACHE_DIR,"caches"); - private final static MainLogger logger = new MainLogger(new File(DATA_DIR,"CustomSkinLoader.log")); + private final static File DATA_DIR=new File(Minecraft.getMinecraft().mcDataDir,"CustomSkinLoader"), + CACHE_DIR=new File(DATA_DIR,"caches"), + LOG_FILE=new File(DATA_DIR,"CustomSkinLoader.log"); + private final static MainLogger logger = new MainLogger(LOG_FILE); private static String[] cloakURLs = null, skinURLs = null; private HttpURLConnection C = null; - private boolean loadFromCache=false; - private boolean cacheSelfOnly=false; - + //Entrance public InputStream getPlayerSkinStream(String path) { if(!DATA_DIR.exists()) DATA_DIR.mkdir(); @@ -54,7 +53,7 @@ public class CustomSkinLoader { Matcher m = newURLPattern.matcher(path); if (!m.matches())//Is not new url { - m = oldURLPattern.matcher(path);//If is old url + m = oldURLPattern.matcher(path);//May be old url } if (m.matches()) { if (m.group(1).contains("Skin")) // Skin @@ -82,217 +81,139 @@ public class CustomSkinLoader { || cloakURLs.length <= 0) refreshSkinURL(); // If the list is blank or null, try to load again. InputStream S=null; - String json=""; - Gson gson=new GsonBuilder().setPrettyPrinting().create(); - HashMap users=null; - - if(CACHE_JSON.exists()&&CACHE_JSON.length()>20){ - try { - json=read(CACHE_JSON); - } catch (Exception e) { - logger.warning(e.getMessage()); - } - if(!json.equalsIgnoreCase("")){ - users=gson.fromJson(json, new TypeToken>(){}.getType()); - }else{ - users=new HashMap(); - } - }else{ - users=new HashMap(); - try { - CACHE_JSON.createNewFile(); - } catch (IOException e) { - logger.log(Level.WARNING, e.getMessage()); - } - } - - CachedUser cu=users.get(playerName); - boolean hasCache=false; - File cacheFile=null; - if(cu!=null){ - if(isCloak&&cu.cloak!=null&&!cu.cloak.equalsIgnoreCase("")) - cacheFile=new File(CACHE_DIR,cu.cloak); - else if(cu.skin!=null&&!cu.skin.equalsIgnoreCase("")) - cacheFile=new File(CACHE_DIR,cu.skin); - } - - long last=0; - if(cacheFile!=null&&cacheFile.exists()&&cacheFile.length()>0){//Have cached - last=cacheFile.lastModified(); - if(last<=0) - last=1; - } for (String l : isCloak ? cloakURLs : skinURLs) { if(l==null||l.equalsIgnoreCase("")) continue; String loc = str_replace("*", playerName, l); logger.log(Level.INFO, "Try to load " + (isCloak ? "cloak" : "skin") + " in " + loc); - S = getStream(loc, true,last); - if(last>0&&loadFromCache){ - logger.info("" + (isCloak ? "Cloak" : "Skin") + " in " + loc + " will be load from cache."); - break; - } + S = getStream(loc, true); + if (S == null){ - logger.log(Level.INFO, "No " + (isCloak ? "cloak" : "skin") - + " found in " + loc); + logger.log(Level.INFO, "No " + (isCloak ? "cloak" : "skin") + " found in " + loc); }else{ logger.info("Succeessfully load " + (isCloak ? "cloak" : "skin") + " in " + loc); - break; + return S; } } - if(S==null){ - try{//Read Local Skin File - if(last>0){ - if(cacheFile.exists() && cacheFile.length()>1){ - logger.info("Try load local " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - InputStream in = new FileInputStream(cacheFile); - BufferedInputStream bis=new BufferedInputStream(in); - if(bis.available()<=0){ - logger.info("Cannot load local " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - }else{ - logger.info("Successfully load " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - return bis; - } - }else{ - logger.info("No local " + (isCloak ? "cloak" : "skin") + " found in " + cacheFile.getAbsolutePath()); - } - }else{ - logger.info("No local " + (isCloak ? "cloak" : "skin") + " found for " + playerName); - } - }catch(Exception e){ - logger.log(Level.WARNING, e.getMessage()); - } - }else{ - File tempFile=null; - if(isCloak) - tempFile=new File(CACHE_DIR,playerName+"-cloak"); - else - tempFile=new File(CACHE_DIR,playerName+"-skin"); - logger.info("Try save local " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - FileOutputStream fs=null; - int times=0; - try{//Save to Local Skin File - //logger.info(user); - if(tempFile.exists()){ - tempFile.delete(); - } - //temp.createNewFile(); - fs = new FileOutputStream(tempFile); - int byteRead = 0; - byte[] buffer = new byte[1024]; - //S.reset(); - while (( byteRead = S.read(buffer)) != -1) { - times+=byteRead; - //logger.info(""+S.available()); - fs.write(buffer, 0, byteRead); - if(times>=C.getContentLength()){ - //logger.info(times+" "+C.getContentLength()); - break; - } - } - - if(tempFile.length()>1){ - logger.info("Successfully save " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - String md5=getMd5ByFile(tempFile); - cacheFile=new File(CACHE_DIR,md5); - fs.close(); - fs=null; - logger.info("Try to move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - if(!cacheFile.exists()||!getMd5ByFile(cacheFile).equalsIgnoreCase(md5)){ - if(tempFile.renameTo(cacheFile)){ - logger.info("Successfully move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - }else{ - logger.info("Cannot move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - } - } - if(cu==null){ - cu=new CachedUser(); - users.put(playerName, cu); - } - if(isCloak){ - cu.cloak=md5; - }else{ - cu.skin=md5; - } - String json2=gson.toJson(users); - if(!json2.equalsIgnoreCase(json)) - write(CACHE_JSON,json2); - }else{ - tempFile.delete(); - logger.info("Cannot save local " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - } - }catch(Exception e){ - //e.printStackTrace(); - //logger.info(""+times); - logger.warning(e.getMessage()); - }finally{ - try { - if(fs!=null) - fs.close(); - S.reset(); - logger.info((isCloak ? "Cloak" : "Skin")+" size : "+S.available()); - } catch (IOException e) { - logger.warning(e.getMessage()); - } - } - return S; - } logger.log(Level.INFO, "Try to load skin in default URL instead."); return getStream(str_replace("*", playerName, isCloak ? DefaultCloakURL : DefaultSkinURL), true); } + private InputStream getStream(String URL, Boolean CheckPNG) { - return getStream(URL,CheckPNG,0); - } - private InputStream getStream(String URL, Boolean CheckPNG,long last) { boolean success=false; + File cacheFile=new File(CACHE_DIR,MD5(URL)); + boolean alreadyCached=false; + if(cacheFile.exists()&&cacheFile.length()>1){ + alreadyCached=true; + logger.info("Cache File Found"); + } try { URL U = new URL(URL); C = (HttpURLConnection) U.openConnection(); + C.setReadTimeout(15000); C.setDoInput(true); C.setDoOutput(false); - if(last>0) - C.setIfModifiedSince(last); C.connect(); logger.info("RC: "+C.getResponseCode()); int respcode = C.getResponseCode() / 100; - if (respcode != 4 && respcode != 5) { // Successful (?) to get skin. - //logger.info(last+" "+C.getLastModified()); - if(C.getResponseCode()==HttpURLConnection.HTTP_NOT_MODIFIED){//304 + if (respcode != 4 && respcode != 5) { // Successful to get skin. + if(alreadyCached && C.getLastModified()==cacheFile.lastModified()){ logger.info("Not Modified!"); - loadFromCache=true; - return null; + return getStreamFromCache(cacheFile); } - if(C.getContentLength()<=0){ + if(C.getContentLength()<=0){//Nothing to get return null; } InputStream IS=new BufferedInputStream(C.getInputStream()); if (!CheckPNG){ // If no need to check PNG header, just skip it. success=true; + saveToCache(IS,cacheFile); return IS; } //logger.info(C.getContentLength()+" "+IS.available()); IS.mark(C.getContentLength()+10); byte[] ib = new byte[4]; IS.read(ib); - if (ib[1] == (byte) 'P' && ib[2] == (byte) 'N' - && ib[3] == (byte) 'G') { // Check PNG Header if needed + if (ib[1] == (byte) 'P' && ib[2] == (byte) 'N' && ib[3] == (byte) 'G') { // Check PNG Header if needed IS.reset(); success=true; + saveToCache(IS,cacheFile); return IS; } } } catch (Exception ex) { success=false; logger.log(Level.WARNING, ex.getMessage()); + if(alreadyCached) + return getStreamFromCache(cacheFile); }finally{ if(!success) disconnect(); } return null; } - + private InputStream getStreamFromCache(File cacheFile) { + try{ + logger.info("Try load local cache in " + cacheFile.getAbsolutePath()); + InputStream in = new FileInputStream(cacheFile); + BufferedInputStream bis=new BufferedInputStream(in); + if(bis.available()<=0){ + logger.info("Cannot load local cache in " + cacheFile.getAbsolutePath()); + return null; + }else{ + logger.info("Successfully load cache in " + cacheFile.getAbsolutePath()); + return bis; + } + }catch(Exception e){ + logger.log(Level.WARNING, e.getMessage()); + return null; + } + } + private void saveToCache(InputStream is,File to){ + logger.info("Try save local cache to " + to.getAbsolutePath()); + FileOutputStream fs=null; + int times=0; + try{//Save to Local Skin File + if(to.exists()){ + to.delete(); + } + fs = new FileOutputStream(to); + int byteRead = 0; + byte[] buffer = new byte[1024]; + while (( byteRead = is.read(buffer)) != -1) { + times+=byteRead; + fs.write(buffer, 0, byteRead); + if(times>=C.getContentLength()){ + //logger.info(times+" "+C.getContentLength()); + break; + } + } + + if(to.length()>1){ + logger.info("Successfully save cache to " + to.getAbsolutePath()); + }else{ + to.delete(); + logger.info("Cannot save local cache to " + to.getAbsolutePath()); + } + }catch(Exception e){ + logger.warning(e.getMessage()); + }finally{ + try { + if(fs!=null) + fs.close(); + is.reset(); + logger.info("Cache size : "+is.available()); + } catch (IOException e) { + logger.warning(e.getMessage()); + } + if(to.exists()){ + to.setLastModified(C.getLastModified()); + } + } + } + public void disconnect() { if (C != null) C.disconnect(); @@ -364,6 +285,7 @@ public class CustomSkinLoader { result.replace(pos, pos + search.length(), replace); return result.toString(); } + public static void showGUI(){ try{ Class clazz=Class.forName("idv.jlchntoz.CustomSkinLoaderGUI"); @@ -415,35 +337,22 @@ public class CustomSkinLoader { return false; } } - private void write(File file,String Data) throws Exception{ - System.out.println("Write to "+file.getAbsolutePath()); - FileWriter fw=null; - fw = new FileWriter(file); - fw.write(Data,0,Data.length()); - fw.flush(); - fw.close(); - } - private String read(File file) throws Exception{ - System.out.println("Read from "+file.getAbsolutePath()); - BufferedReader br = null; - String data=""; - br = new BufferedReader(new FileReader(file)); - data = br.readLine(); - while( br.ready()){ - data += "\r\n"+br.readLine(); - } - br.close(); - return data; - } - private String getMd5ByFile(File file) throws Exception { - String value = null; - FileInputStream in = new FileInputStream(file); - MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); - MessageDigest md5 = MessageDigest.getInstance("MD5"); - md5.update(byteBuffer); - BigInteger bi = new BigInteger(1, md5.digest()); - value = bi.toString(16); - in.close(); - return value; - } + public String MD5(String str){ + byte [] buf = str.getBytes(); + MessageDigest md5; + try { + md5 = MessageDigest.getInstance("MD5"); + md5.update(buf); + byte [] tmp = md5.digest(); + StringBuilder sb = new StringBuilder(); + for (byte b:tmp) { + sb.append(Integer.toHexString(b&0xff)); + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + logger.warning(e.getMessage()); + } + return "Fail"; + + } } diff --git a/1.7.2-mcp903/src/minecraft/idv/jlchntoz/CachedUser.java b/1.7.2-mcp903/src/minecraft/idv/jlchntoz/CachedUser.java deleted file mode 100644 index 4ac97cc..0000000 --- a/1.7.2-mcp903/src/minecraft/idv/jlchntoz/CachedUser.java +++ /dev/null @@ -1,6 +0,0 @@ -package idv.jlchntoz; - -public class CachedUser { - public String skin; - public String cloak; -} diff --git a/1.7.2-mcp903/src/minecraft/idv/jlchntoz/CustomSkinLoader.java b/1.7.2-mcp903/src/minecraft/idv/jlchntoz/CustomSkinLoader.java index 9aacee3..ed6d4f6 100644 --- a/1.7.2-mcp903/src/minecraft/idv/jlchntoz/CustomSkinLoader.java +++ b/1.7.2-mcp903/src/minecraft/idv/jlchntoz/CustomSkinLoader.java @@ -8,6 +8,7 @@ import java.net.*; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.logging.*; import java.util.regex.*; @@ -19,32 +20,30 @@ import com.google.gson.reflect.TypeToken; /** * Custom skin loader mod for Minecraft. * - * @version 12th Revision 4th Subversion 2015.6.22 + * @version 12th Revision 5th Subversion 2015.8.1 * * @author (C) Jeremy Lam [JLChnToZ] 2013 & Alexander Xia [xfl03] 2014-2015 */ public class CustomSkinLoader { - public final static String VERSION="12.4"; + public final static String VERSION="12.5"; public final static String DefaultSkinURL = "http://skins.minecraft.net/MinecraftSkins/*.png"; public final static String DefaultCloakURL = "http://skins.minecraft.net/MinecraftCloaks/*.png"; private final static Pattern newResPattern = Pattern.compile("^http://textures.minecraft.net/texture/(.*?)?(Skin|Cloak)=(.*?)$"), - newURLPattern = Pattern.compile("^http://skins.minecraft.net/Minecraft(Skin|Cloak)s/(.*?).png$"), - oldURLPattern = Pattern.compile("^http://s3.amazonaws.com/Minecraft(Skin|Cloak)s/(.*?).png$"), - optifineCapeURLPattern = Pattern.compile("^http://s.optifine.net/capes/(.*?).png$"); + newURLPattern = Pattern.compile("^http://skins.minecraft.net/Minecraft(Skin|Cloak)s/(.*?).png$"), + oldURLPattern = Pattern.compile("^http://s3.amazonaws.com/Minecraft(Skin|Cloak)s/(.*?).png$"), + optifineCapeURLPattern = Pattern.compile("^http://s.optifine.net/capes/(.*?).png$"); - private final static File DATA_DIR=new File(Minecraft.getMinecraft().mcDataDir,"CustomSkinLoader"); - private final static File CACHE_DIR=new File(DATA_DIR,"caches"); - private final static File CACHE_JSON=new File(CACHE_DIR,"caches"); - private final static MainLogger logger = new MainLogger(new File(DATA_DIR,"CustomSkinLoader.log")); + private final static File DATA_DIR=new File(Minecraft.getMinecraft().mcDataDir,"CustomSkinLoader"), + CACHE_DIR=new File(DATA_DIR,"caches"), + LOG_FILE=new File(DATA_DIR,"CustomSkinLoader.log"); + private final static MainLogger logger = new MainLogger(LOG_FILE); private static String[] cloakURLs = null, skinURLs = null; private HttpURLConnection C = null; - private boolean loadFromCache=false; - private boolean cacheSelfOnly=false; - + //Entrance public InputStream getPlayerSkinStream(String path) { if(!DATA_DIR.exists()) DATA_DIR.mkdir(); @@ -54,7 +53,7 @@ public class CustomSkinLoader { Matcher m = newURLPattern.matcher(path); if (!m.matches())//Is not new url { - m = oldURLPattern.matcher(path);//If is old url + m = oldURLPattern.matcher(path);//May be old url } if (m.matches()) { if (m.group(1).contains("Skin")) // Skin @@ -82,217 +81,139 @@ public class CustomSkinLoader { || cloakURLs.length <= 0) refreshSkinURL(); // If the list is blank or null, try to load again. InputStream S=null; - String json=""; - Gson gson=new GsonBuilder().setPrettyPrinting().create(); - HashMap users=null; - - if(CACHE_JSON.exists()&&CACHE_JSON.length()>20){ - try { - json=read(CACHE_JSON); - } catch (Exception e) { - logger.warning(e.getMessage()); - } - if(!json.equalsIgnoreCase("")){ - users=gson.fromJson(json, new TypeToken>(){}.getType()); - }else{ - users=new HashMap(); - } - }else{ - users=new HashMap(); - try { - CACHE_JSON.createNewFile(); - } catch (IOException e) { - logger.log(Level.WARNING, e.getMessage()); - } - } - - CachedUser cu=users.get(playerName); - boolean hasCache=false; - File cacheFile=null; - if(cu!=null){ - if(isCloak&&cu.cloak!=null&&!cu.cloak.equalsIgnoreCase("")) - cacheFile=new File(CACHE_DIR,cu.cloak); - else if(cu.skin!=null&&!cu.skin.equalsIgnoreCase("")) - cacheFile=new File(CACHE_DIR,cu.skin); - } - - long last=0; - if(cacheFile!=null&&cacheFile.exists()&&cacheFile.length()>0){//Have cached - last=cacheFile.lastModified(); - if(last<=0) - last=1; - } for (String l : isCloak ? cloakURLs : skinURLs) { if(l==null||l.equalsIgnoreCase("")) continue; String loc = str_replace("*", playerName, l); logger.log(Level.INFO, "Try to load " + (isCloak ? "cloak" : "skin") + " in " + loc); - S = getStream(loc, true,last); - if(last>0&&loadFromCache){ - logger.info("" + (isCloak ? "Cloak" : "Skin") + " in " + loc + " will be load from cache."); - break; - } + S = getStream(loc, true); + if (S == null){ - logger.log(Level.INFO, "No " + (isCloak ? "cloak" : "skin") - + " found in " + loc); + logger.log(Level.INFO, "No " + (isCloak ? "cloak" : "skin") + " found in " + loc); }else{ logger.info("Succeessfully load " + (isCloak ? "cloak" : "skin") + " in " + loc); - break; + return S; } } - if(S==null){ - try{//Read Local Skin File - if(last>0){ - if(cacheFile.exists() && cacheFile.length()>1){ - logger.info("Try load local " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - InputStream in = new FileInputStream(cacheFile); - BufferedInputStream bis=new BufferedInputStream(in); - if(bis.available()<=0){ - logger.info("Cannot load local " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - }else{ - logger.info("Successfully load " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - return bis; - } - }else{ - logger.info("No local " + (isCloak ? "cloak" : "skin") + " found in " + cacheFile.getAbsolutePath()); - } - }else{ - logger.info("No local " + (isCloak ? "cloak" : "skin") + " found for " + playerName); - } - }catch(Exception e){ - logger.log(Level.WARNING, e.getMessage()); - } - }else{ - File tempFile=null; - if(isCloak) - tempFile=new File(CACHE_DIR,playerName+"-cloak"); - else - tempFile=new File(CACHE_DIR,playerName+"-skin"); - logger.info("Try save local " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - FileOutputStream fs=null; - int times=0; - try{//Save to Local Skin File - //logger.info(user); - if(tempFile.exists()){ - tempFile.delete(); - } - //temp.createNewFile(); - fs = new FileOutputStream(tempFile); - int byteRead = 0; - byte[] buffer = new byte[1024]; - //S.reset(); - while (( byteRead = S.read(buffer)) != -1) { - times+=byteRead; - //logger.info(""+S.available()); - fs.write(buffer, 0, byteRead); - if(times>=C.getContentLength()){ - //logger.info(times+" "+C.getContentLength()); - break; - } - } - - if(tempFile.length()>1){ - logger.info("Successfully save " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - String md5=getMd5ByFile(tempFile); - cacheFile=new File(CACHE_DIR,md5); - fs.close(); - fs=null; - logger.info("Try to move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - if(!cacheFile.exists()||!getMd5ByFile(cacheFile).equalsIgnoreCase(md5)){ - if(tempFile.renameTo(cacheFile)){ - logger.info("Successfully move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - }else{ - logger.info("Cannot move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - } - } - if(cu==null){ - cu=new CachedUser(); - users.put(playerName, cu); - } - if(isCloak){ - cu.cloak=md5; - }else{ - cu.skin=md5; - } - String json2=gson.toJson(users); - if(!json2.equalsIgnoreCase(json)) - write(CACHE_JSON,json2); - }else{ - tempFile.delete(); - logger.info("Cannot save local " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - } - }catch(Exception e){ - //e.printStackTrace(); - //logger.info(""+times); - logger.warning(e.getMessage()); - }finally{ - try { - if(fs!=null) - fs.close(); - S.reset(); - logger.info((isCloak ? "Cloak" : "Skin")+" size : "+S.available()); - } catch (IOException e) { - logger.warning(e.getMessage()); - } - } - return S; - } logger.log(Level.INFO, "Try to load skin in default URL instead."); return getStream(str_replace("*", playerName, isCloak ? DefaultCloakURL : DefaultSkinURL), true); } + private InputStream getStream(String URL, Boolean CheckPNG) { - return getStream(URL,CheckPNG,0); - } - private InputStream getStream(String URL, Boolean CheckPNG,long last) { boolean success=false; + File cacheFile=new File(CACHE_DIR,MD5(URL)); + boolean alreadyCached=false; + if(cacheFile.exists()&&cacheFile.length()>1){ + alreadyCached=true; + logger.info("Cache File Found"); + } try { URL U = new URL(URL); C = (HttpURLConnection) U.openConnection(); + C.setReadTimeout(15000); C.setDoInput(true); C.setDoOutput(false); - if(last>0) - C.setIfModifiedSince(last); C.connect(); logger.info("RC: "+C.getResponseCode()); int respcode = C.getResponseCode() / 100; - if (respcode != 4 && respcode != 5) { // Successful (?) to get skin. - //logger.info(last+" "+C.getLastModified()); - if(C.getResponseCode()==HttpURLConnection.HTTP_NOT_MODIFIED){//304 + if (respcode != 4 && respcode != 5) { // Successful to get skin. + if(alreadyCached && C.getLastModified()==cacheFile.lastModified()){ logger.info("Not Modified!"); - loadFromCache=true; - return null; + return getStreamFromCache(cacheFile); } - if(C.getContentLength()<=0){ + if(C.getContentLength()<=0){//Nothing to get return null; } InputStream IS=new BufferedInputStream(C.getInputStream()); if (!CheckPNG){ // If no need to check PNG header, just skip it. success=true; + saveToCache(IS,cacheFile); return IS; } //logger.info(C.getContentLength()+" "+IS.available()); IS.mark(C.getContentLength()+10); byte[] ib = new byte[4]; IS.read(ib); - if (ib[1] == (byte) 'P' && ib[2] == (byte) 'N' - && ib[3] == (byte) 'G') { // Check PNG Header if needed + if (ib[1] == (byte) 'P' && ib[2] == (byte) 'N' && ib[3] == (byte) 'G') { // Check PNG Header if needed IS.reset(); success=true; + saveToCache(IS,cacheFile); return IS; } } } catch (Exception ex) { success=false; logger.log(Level.WARNING, ex.getMessage()); + if(alreadyCached) + return getStreamFromCache(cacheFile); }finally{ if(!success) disconnect(); } return null; } - + private InputStream getStreamFromCache(File cacheFile) { + try{ + logger.info("Try load local cache in " + cacheFile.getAbsolutePath()); + InputStream in = new FileInputStream(cacheFile); + BufferedInputStream bis=new BufferedInputStream(in); + if(bis.available()<=0){ + logger.info("Cannot load local cache in " + cacheFile.getAbsolutePath()); + return null; + }else{ + logger.info("Successfully load cache in " + cacheFile.getAbsolutePath()); + return bis; + } + }catch(Exception e){ + logger.log(Level.WARNING, e.getMessage()); + return null; + } + } + private void saveToCache(InputStream is,File to){ + logger.info("Try save local cache to " + to.getAbsolutePath()); + FileOutputStream fs=null; + int times=0; + try{//Save to Local Skin File + if(to.exists()){ + to.delete(); + } + fs = new FileOutputStream(to); + int byteRead = 0; + byte[] buffer = new byte[1024]; + while (( byteRead = is.read(buffer)) != -1) { + times+=byteRead; + fs.write(buffer, 0, byteRead); + if(times>=C.getContentLength()){ + //logger.info(times+" "+C.getContentLength()); + break; + } + } + + if(to.length()>1){ + logger.info("Successfully save cache to " + to.getAbsolutePath()); + }else{ + to.delete(); + logger.info("Cannot save local cache to " + to.getAbsolutePath()); + } + }catch(Exception e){ + logger.warning(e.getMessage()); + }finally{ + try { + if(fs!=null) + fs.close(); + is.reset(); + logger.info("Cache size : "+is.available()); + } catch (IOException e) { + logger.warning(e.getMessage()); + } + if(to.exists()){ + to.setLastModified(C.getLastModified()); + } + } + } + public void disconnect() { if (C != null) C.disconnect(); @@ -364,6 +285,7 @@ public class CustomSkinLoader { result.replace(pos, pos + search.length(), replace); return result.toString(); } + public static void showGUI(){ try{ Class clazz=Class.forName("idv.jlchntoz.CustomSkinLoaderGUI"); @@ -415,35 +337,22 @@ public class CustomSkinLoader { return false; } } - private void write(File file,String Data) throws Exception{ - System.out.println("Write to "+file.getAbsolutePath()); - FileWriter fw=null; - fw = new FileWriter(file); - fw.write(Data,0,Data.length()); - fw.flush(); - fw.close(); - } - private String read(File file) throws Exception{ - System.out.println("Read from "+file.getAbsolutePath()); - BufferedReader br = null; - String data=""; - br = new BufferedReader(new FileReader(file)); - data = br.readLine(); - while( br.ready()){ - data += "\r\n"+br.readLine(); - } - br.close(); - return data; - } - private String getMd5ByFile(File file) throws Exception { - String value = null; - FileInputStream in = new FileInputStream(file); - MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); - MessageDigest md5 = MessageDigest.getInstance("MD5"); - md5.update(byteBuffer); - BigInteger bi = new BigInteger(1, md5.digest()); - value = bi.toString(16); - in.close(); - return value; - } + public String MD5(String str){ + byte [] buf = str.getBytes(); + MessageDigest md5; + try { + md5 = MessageDigest.getInstance("MD5"); + md5.update(buf); + byte [] tmp = md5.digest(); + StringBuilder sb = new StringBuilder(); + for (byte b:tmp) { + sb.append(Integer.toHexString(b&0xff)); + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + logger.warning(e.getMessage()); + } + return "Fail"; + + } } diff --git a/1.8-mcp910/src/minecraft/idv/jlchntoz/CachedUser.java b/1.8-mcp910/src/minecraft/idv/jlchntoz/CachedUser.java deleted file mode 100644 index 4ac97cc..0000000 --- a/1.8-mcp910/src/minecraft/idv/jlchntoz/CachedUser.java +++ /dev/null @@ -1,6 +0,0 @@ -package idv.jlchntoz; - -public class CachedUser { - public String skin; - public String cloak; -} diff --git a/1.8-mcp910/src/minecraft/idv/jlchntoz/CustomSkinLoader.java b/1.8-mcp910/src/minecraft/idv/jlchntoz/CustomSkinLoader.java index 9aacee3..ed6d4f6 100644 --- a/1.8-mcp910/src/minecraft/idv/jlchntoz/CustomSkinLoader.java +++ b/1.8-mcp910/src/minecraft/idv/jlchntoz/CustomSkinLoader.java @@ -8,6 +8,7 @@ import java.net.*; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.logging.*; import java.util.regex.*; @@ -19,32 +20,30 @@ import com.google.gson.reflect.TypeToken; /** * Custom skin loader mod for Minecraft. * - * @version 12th Revision 4th Subversion 2015.6.22 + * @version 12th Revision 5th Subversion 2015.8.1 * * @author (C) Jeremy Lam [JLChnToZ] 2013 & Alexander Xia [xfl03] 2014-2015 */ public class CustomSkinLoader { - public final static String VERSION="12.4"; + public final static String VERSION="12.5"; public final static String DefaultSkinURL = "http://skins.minecraft.net/MinecraftSkins/*.png"; public final static String DefaultCloakURL = "http://skins.minecraft.net/MinecraftCloaks/*.png"; private final static Pattern newResPattern = Pattern.compile("^http://textures.minecraft.net/texture/(.*?)?(Skin|Cloak)=(.*?)$"), - newURLPattern = Pattern.compile("^http://skins.minecraft.net/Minecraft(Skin|Cloak)s/(.*?).png$"), - oldURLPattern = Pattern.compile("^http://s3.amazonaws.com/Minecraft(Skin|Cloak)s/(.*?).png$"), - optifineCapeURLPattern = Pattern.compile("^http://s.optifine.net/capes/(.*?).png$"); + newURLPattern = Pattern.compile("^http://skins.minecraft.net/Minecraft(Skin|Cloak)s/(.*?).png$"), + oldURLPattern = Pattern.compile("^http://s3.amazonaws.com/Minecraft(Skin|Cloak)s/(.*?).png$"), + optifineCapeURLPattern = Pattern.compile("^http://s.optifine.net/capes/(.*?).png$"); - private final static File DATA_DIR=new File(Minecraft.getMinecraft().mcDataDir,"CustomSkinLoader"); - private final static File CACHE_DIR=new File(DATA_DIR,"caches"); - private final static File CACHE_JSON=new File(CACHE_DIR,"caches"); - private final static MainLogger logger = new MainLogger(new File(DATA_DIR,"CustomSkinLoader.log")); + private final static File DATA_DIR=new File(Minecraft.getMinecraft().mcDataDir,"CustomSkinLoader"), + CACHE_DIR=new File(DATA_DIR,"caches"), + LOG_FILE=new File(DATA_DIR,"CustomSkinLoader.log"); + private final static MainLogger logger = new MainLogger(LOG_FILE); private static String[] cloakURLs = null, skinURLs = null; private HttpURLConnection C = null; - private boolean loadFromCache=false; - private boolean cacheSelfOnly=false; - + //Entrance public InputStream getPlayerSkinStream(String path) { if(!DATA_DIR.exists()) DATA_DIR.mkdir(); @@ -54,7 +53,7 @@ public class CustomSkinLoader { Matcher m = newURLPattern.matcher(path); if (!m.matches())//Is not new url { - m = oldURLPattern.matcher(path);//If is old url + m = oldURLPattern.matcher(path);//May be old url } if (m.matches()) { if (m.group(1).contains("Skin")) // Skin @@ -82,217 +81,139 @@ public class CustomSkinLoader { || cloakURLs.length <= 0) refreshSkinURL(); // If the list is blank or null, try to load again. InputStream S=null; - String json=""; - Gson gson=new GsonBuilder().setPrettyPrinting().create(); - HashMap users=null; - - if(CACHE_JSON.exists()&&CACHE_JSON.length()>20){ - try { - json=read(CACHE_JSON); - } catch (Exception e) { - logger.warning(e.getMessage()); - } - if(!json.equalsIgnoreCase("")){ - users=gson.fromJson(json, new TypeToken>(){}.getType()); - }else{ - users=new HashMap(); - } - }else{ - users=new HashMap(); - try { - CACHE_JSON.createNewFile(); - } catch (IOException e) { - logger.log(Level.WARNING, e.getMessage()); - } - } - - CachedUser cu=users.get(playerName); - boolean hasCache=false; - File cacheFile=null; - if(cu!=null){ - if(isCloak&&cu.cloak!=null&&!cu.cloak.equalsIgnoreCase("")) - cacheFile=new File(CACHE_DIR,cu.cloak); - else if(cu.skin!=null&&!cu.skin.equalsIgnoreCase("")) - cacheFile=new File(CACHE_DIR,cu.skin); - } - - long last=0; - if(cacheFile!=null&&cacheFile.exists()&&cacheFile.length()>0){//Have cached - last=cacheFile.lastModified(); - if(last<=0) - last=1; - } for (String l : isCloak ? cloakURLs : skinURLs) { if(l==null||l.equalsIgnoreCase("")) continue; String loc = str_replace("*", playerName, l); logger.log(Level.INFO, "Try to load " + (isCloak ? "cloak" : "skin") + " in " + loc); - S = getStream(loc, true,last); - if(last>0&&loadFromCache){ - logger.info("" + (isCloak ? "Cloak" : "Skin") + " in " + loc + " will be load from cache."); - break; - } + S = getStream(loc, true); + if (S == null){ - logger.log(Level.INFO, "No " + (isCloak ? "cloak" : "skin") - + " found in " + loc); + logger.log(Level.INFO, "No " + (isCloak ? "cloak" : "skin") + " found in " + loc); }else{ logger.info("Succeessfully load " + (isCloak ? "cloak" : "skin") + " in " + loc); - break; + return S; } } - if(S==null){ - try{//Read Local Skin File - if(last>0){ - if(cacheFile.exists() && cacheFile.length()>1){ - logger.info("Try load local " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - InputStream in = new FileInputStream(cacheFile); - BufferedInputStream bis=new BufferedInputStream(in); - if(bis.available()<=0){ - logger.info("Cannot load local " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - }else{ - logger.info("Successfully load " + (isCloak ? "cloak" : "skin") + " in " + cacheFile.getAbsolutePath()); - return bis; - } - }else{ - logger.info("No local " + (isCloak ? "cloak" : "skin") + " found in " + cacheFile.getAbsolutePath()); - } - }else{ - logger.info("No local " + (isCloak ? "cloak" : "skin") + " found for " + playerName); - } - }catch(Exception e){ - logger.log(Level.WARNING, e.getMessage()); - } - }else{ - File tempFile=null; - if(isCloak) - tempFile=new File(CACHE_DIR,playerName+"-cloak"); - else - tempFile=new File(CACHE_DIR,playerName+"-skin"); - logger.info("Try save local " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - FileOutputStream fs=null; - int times=0; - try{//Save to Local Skin File - //logger.info(user); - if(tempFile.exists()){ - tempFile.delete(); - } - //temp.createNewFile(); - fs = new FileOutputStream(tempFile); - int byteRead = 0; - byte[] buffer = new byte[1024]; - //S.reset(); - while (( byteRead = S.read(buffer)) != -1) { - times+=byteRead; - //logger.info(""+S.available()); - fs.write(buffer, 0, byteRead); - if(times>=C.getContentLength()){ - //logger.info(times+" "+C.getContentLength()); - break; - } - } - - if(tempFile.length()>1){ - logger.info("Successfully save " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - String md5=getMd5ByFile(tempFile); - cacheFile=new File(CACHE_DIR,md5); - fs.close(); - fs=null; - logger.info("Try to move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - if(!cacheFile.exists()||!getMd5ByFile(cacheFile).equalsIgnoreCase(md5)){ - if(tempFile.renameTo(cacheFile)){ - logger.info("Successfully move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - }else{ - logger.info("Cannot move " + tempFile.getAbsolutePath() + " to " + cacheFile.getAbsolutePath()); - } - } - if(cu==null){ - cu=new CachedUser(); - users.put(playerName, cu); - } - if(isCloak){ - cu.cloak=md5; - }else{ - cu.skin=md5; - } - String json2=gson.toJson(users); - if(!json2.equalsIgnoreCase(json)) - write(CACHE_JSON,json2); - }else{ - tempFile.delete(); - logger.info("Cannot save local " + (isCloak ? "cloak" : "skin") + " to " + tempFile.getAbsolutePath()); - } - }catch(Exception e){ - //e.printStackTrace(); - //logger.info(""+times); - logger.warning(e.getMessage()); - }finally{ - try { - if(fs!=null) - fs.close(); - S.reset(); - logger.info((isCloak ? "Cloak" : "Skin")+" size : "+S.available()); - } catch (IOException e) { - logger.warning(e.getMessage()); - } - } - return S; - } logger.log(Level.INFO, "Try to load skin in default URL instead."); return getStream(str_replace("*", playerName, isCloak ? DefaultCloakURL : DefaultSkinURL), true); } + private InputStream getStream(String URL, Boolean CheckPNG) { - return getStream(URL,CheckPNG,0); - } - private InputStream getStream(String URL, Boolean CheckPNG,long last) { boolean success=false; + File cacheFile=new File(CACHE_DIR,MD5(URL)); + boolean alreadyCached=false; + if(cacheFile.exists()&&cacheFile.length()>1){ + alreadyCached=true; + logger.info("Cache File Found"); + } try { URL U = new URL(URL); C = (HttpURLConnection) U.openConnection(); + C.setReadTimeout(15000); C.setDoInput(true); C.setDoOutput(false); - if(last>0) - C.setIfModifiedSince(last); C.connect(); logger.info("RC: "+C.getResponseCode()); int respcode = C.getResponseCode() / 100; - if (respcode != 4 && respcode != 5) { // Successful (?) to get skin. - //logger.info(last+" "+C.getLastModified()); - if(C.getResponseCode()==HttpURLConnection.HTTP_NOT_MODIFIED){//304 + if (respcode != 4 && respcode != 5) { // Successful to get skin. + if(alreadyCached && C.getLastModified()==cacheFile.lastModified()){ logger.info("Not Modified!"); - loadFromCache=true; - return null; + return getStreamFromCache(cacheFile); } - if(C.getContentLength()<=0){ + if(C.getContentLength()<=0){//Nothing to get return null; } InputStream IS=new BufferedInputStream(C.getInputStream()); if (!CheckPNG){ // If no need to check PNG header, just skip it. success=true; + saveToCache(IS,cacheFile); return IS; } //logger.info(C.getContentLength()+" "+IS.available()); IS.mark(C.getContentLength()+10); byte[] ib = new byte[4]; IS.read(ib); - if (ib[1] == (byte) 'P' && ib[2] == (byte) 'N' - && ib[3] == (byte) 'G') { // Check PNG Header if needed + if (ib[1] == (byte) 'P' && ib[2] == (byte) 'N' && ib[3] == (byte) 'G') { // Check PNG Header if needed IS.reset(); success=true; + saveToCache(IS,cacheFile); return IS; } } } catch (Exception ex) { success=false; logger.log(Level.WARNING, ex.getMessage()); + if(alreadyCached) + return getStreamFromCache(cacheFile); }finally{ if(!success) disconnect(); } return null; } - + private InputStream getStreamFromCache(File cacheFile) { + try{ + logger.info("Try load local cache in " + cacheFile.getAbsolutePath()); + InputStream in = new FileInputStream(cacheFile); + BufferedInputStream bis=new BufferedInputStream(in); + if(bis.available()<=0){ + logger.info("Cannot load local cache in " + cacheFile.getAbsolutePath()); + return null; + }else{ + logger.info("Successfully load cache in " + cacheFile.getAbsolutePath()); + return bis; + } + }catch(Exception e){ + logger.log(Level.WARNING, e.getMessage()); + return null; + } + } + private void saveToCache(InputStream is,File to){ + logger.info("Try save local cache to " + to.getAbsolutePath()); + FileOutputStream fs=null; + int times=0; + try{//Save to Local Skin File + if(to.exists()){ + to.delete(); + } + fs = new FileOutputStream(to); + int byteRead = 0; + byte[] buffer = new byte[1024]; + while (( byteRead = is.read(buffer)) != -1) { + times+=byteRead; + fs.write(buffer, 0, byteRead); + if(times>=C.getContentLength()){ + //logger.info(times+" "+C.getContentLength()); + break; + } + } + + if(to.length()>1){ + logger.info("Successfully save cache to " + to.getAbsolutePath()); + }else{ + to.delete(); + logger.info("Cannot save local cache to " + to.getAbsolutePath()); + } + }catch(Exception e){ + logger.warning(e.getMessage()); + }finally{ + try { + if(fs!=null) + fs.close(); + is.reset(); + logger.info("Cache size : "+is.available()); + } catch (IOException e) { + logger.warning(e.getMessage()); + } + if(to.exists()){ + to.setLastModified(C.getLastModified()); + } + } + } + public void disconnect() { if (C != null) C.disconnect(); @@ -364,6 +285,7 @@ public class CustomSkinLoader { result.replace(pos, pos + search.length(), replace); return result.toString(); } + public static void showGUI(){ try{ Class clazz=Class.forName("idv.jlchntoz.CustomSkinLoaderGUI"); @@ -415,35 +337,22 @@ public class CustomSkinLoader { return false; } } - private void write(File file,String Data) throws Exception{ - System.out.println("Write to "+file.getAbsolutePath()); - FileWriter fw=null; - fw = new FileWriter(file); - fw.write(Data,0,Data.length()); - fw.flush(); - fw.close(); - } - private String read(File file) throws Exception{ - System.out.println("Read from "+file.getAbsolutePath()); - BufferedReader br = null; - String data=""; - br = new BufferedReader(new FileReader(file)); - data = br.readLine(); - while( br.ready()){ - data += "\r\n"+br.readLine(); - } - br.close(); - return data; - } - private String getMd5ByFile(File file) throws Exception { - String value = null; - FileInputStream in = new FileInputStream(file); - MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); - MessageDigest md5 = MessageDigest.getInstance("MD5"); - md5.update(byteBuffer); - BigInteger bi = new BigInteger(1, md5.digest()); - value = bi.toString(16); - in.close(); - return value; - } + public String MD5(String str){ + byte [] buf = str.getBytes(); + MessageDigest md5; + try { + md5 = MessageDigest.getInstance("MD5"); + md5.update(buf); + byte [] tmp = md5.digest(); + StringBuilder sb = new StringBuilder(); + for (byte b:tmp) { + sb.append(Integer.toHexString(b&0xff)); + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + logger.warning(e.getMessage()); + } + return "Fail"; + + } }