This commit is contained in:
xfl03 committed 2015-06-07 11:44:53 +08:00
1 parent bcbe2d2813
commit c786185b18
5 files changed
+645

No files matched your search

@@ -0,0 +1,340 @@
package idv.jlchntoz;
import net.minecraft.src.Minecraft;
import java.io.*;
import java.net.*;
import java.util.logging.*;
import java.util.regex.*;
/**
* Custom skin loader mod for Minecraft.
*
* @version 12th Revision 2nd Subversion 2015.6.7
* @author (C) Jeremy Lam [JLChnToZ] 2013 & Alexander Xia [xfl03] 2014-2015
*/
public class CustomSkinLoader {
public final static String VERSION="12.2";
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$");
private final static File DATA_DIR=new File(Minecraft.getMinecraft().mcDataDir,"CustomSkinLoader");
private final static File SKIN_DIR=new File(DATA_DIR,"skins");
private final static File CLOAK_DIR=new File(DATA_DIR,"cloaks");
private final static MainLogger logger = new MainLogger(new File(DATA_DIR,"CustomSkinLoader.log"));
private static String[] cloakURLs = null, skinURLs = null;
private HttpURLConnection C = null;
private boolean loadFromCache=false;
public InputStream getPlayerSkinStream(String path) {
if(!DATA_DIR.exists())
DATA_DIR.mkdir();
logger.info("Get a request: "+path);
Matcher m = newURLPattern.matcher(path);
if (!m.matches())//Is not new url
{
m = oldURLPattern.matcher(path);//If is old url
}
if (m.matches()) {
if (m.group(1).contains("Skin")) // Skin
return getPlayerSkinStream(false, m.group(2));
else if (m.group(1).contains("Cloak")) // Cloak
return getPlayerSkinStream(true, m.group(2));
}else{
m = newResPattern.matcher(path);
if(m.matches()){
logger.info("Matches");
if (m.group(2).contains("Skin")) // Skin
return getPlayerSkinStream(false, m.group(3));
else if (m.group(2).contains("Cloak")) // Cloak
return getPlayerSkinStream(true, m.group(3));
}
}
return getStream(path, false); // Neither skin nor cloak...
}
public InputStream getPlayerSkinStream(Boolean isCloak, String playerName) {
if (skinURLs == null || cloakURLs == null || skinURLs.length <= 0
|| cloakURLs.length <= 0)
refreshSkinURL(); // If the list is blank or null, try to load again.
InputStream S=null;
File temp=null;
if(isCloak)
temp=new File(CLOAK_DIR,playerName+".png");
else
temp=new File(SKIN_DIR,playerName+".png");
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);
long last=0;
if(temp.exists()&&temp.length()>0){
last=temp.lastModified();
}
S = getStream(loc, true,last);
if(loadFromCache){
logger.info("" + (isCloak ? "Cloak" : "Skin") + " in " + loc + "will be load from cache.");
break;
}
if (S == null){
logger.log(Level.INFO, "No " + (isCloak ? "cloak" : "skin")
+ " found in " + loc);
}else{
logger.info("Succeessfully load " + (isCloak ? "cloak" : "skin") + " in " + loc);
break;
}
}
if(S==null){
try{//Read Local Skin File
if(temp.exists() && temp.length()>1){
logger.info("Try load local " + (isCloak ? "cloak" : "skin") + " in " + temp.getAbsolutePath());
InputStream in = new FileInputStream(temp);
BufferedInputStream bis=new BufferedInputStream(in);
if(bis.available()<=0){
logger.info("Cannot load local " + (isCloak ? "cloak" : "skin") + " in " + temp.getAbsolutePath());
}else{
logger.info("Successfully load " + (isCloak ? "cloak" : "skin") + " in " + temp.getAbsolutePath());
return bis;
}
}else{
logger.info("No local " + (isCloak ? "cloak" : "skin") + " found in " + temp.getAbsolutePath());
}
}catch(Exception e){
logger.log(Level.WARNING, e.getMessage());
}
}else{
String user= Minecraft.getMinecraft().getSession().getUsername();
if(user.equalsIgnoreCase(playerName)){//Only save user's skin
logger.info("Try save local " + (isCloak ? "cloak" : "skin") + " to " + temp.getAbsolutePath());
FileOutputStream fs=null;
int times=0;
try{//Save to Local Skin File
//logger.info(user);
if(!temp.getParentFile().exists())
temp.getParentFile().mkdir();
else if(temp.exists()){
temp.delete();
}
//temp.createNewFile();
fs = new FileOutputStream(temp);
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(temp.length()>1){
logger.info("Successfully save " + (isCloak ? "cloak" : "skin") + " to " + temp.getAbsolutePath());
}else{
temp.delete();
logger.info("Cannot save local " + (isCloak ? "cloak" : "skin") + " to " + temp.getAbsolutePath());
}
}catch(Exception e){
e.printStackTrace();
logger.info(times+"");
logger.warning(e);
}finally{
try {
if(fs!=null)
fs.close();
S.reset();
logger.info((isCloak ? "Cloak" : "Skin")+" size : "+S.available());
} catch (IOException e) {
logger.warning(e);
}
}
}
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;
try {
URL U = new URL(URL);
C = (HttpURLConnection) U.openConnection();
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
logger.info("Not Modified!");
loadFromCache=true;
return null;
}
if(C.getContentLength()<=0){
return null;
}
InputStream IS=new BufferedInputStream(C.getInputStream());
if (!CheckPNG){ // If no need to check PNG header, just skip it.
success=true;
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
IS.reset();
success=true;
return IS;
}
}
} catch (Exception ex) {
success=false;
logger.log(Level.WARNING, ex.getMessage());
}finally{
if(!success)
disconnect();
}
return null;
}
public void disconnect() {
if (C != null)
C.disconnect();
}
private static void refreshSkinURL() {
try {
skinURLs = readAllLines(DATA_DIR, "skinurls.txt");
cloakURLs = readAllLines(DATA_DIR, "capeurls.txt");
} catch (Exception ex) {
logger.log(Level.WARNING, ex.getMessage());
} finally {
if(skinURLs.length==0&&cloakURLs.length==0){
logger.info("No skinURLs and cloak URLS found, try to show GUI.");
showGUI();
}else{
logger.log(Level.INFO, "Skin URLs Refreshed. Skin count = "
+ skinURLs.length + ", Cloak count = " + cloakURLs.length);
}
}
}
private static String[] readAllLines(File dir, String path) {
try {
File F = new File(dir, path);
logger.log(Level.INFO, "Config file: " + F.getAbsolutePath());
if (!F.exists()) {
logger.log(Level.INFO, "Config file not found.");
return new String[0];
} else if (F.length() <= 0) {
logger.log(Level.INFO, "Config file is blank, skipped.");
return new String[0];
} else {
byte[] b = new byte[(int) F.length()];
BufferedInputStream S = new BufferedInputStream(
new FileInputStream(F));
S.read(b);
S.close();
logger.log(Level.INFO, "Config file loaded.");
String[] re= str_replace("\r", "\n",
str_replace("\r\n", "\n", new String(b))).split("\n");
for(int i=0;i<re.length;i++){
if(re[i].startsWith("#"))
re[i]=null;
else{
for(int g=0;g<re.length;g++){
if(i==g)
continue;
if(re[i].equalsIgnoreCase(re[g])){
re[i]=null;
break;
}
}
}
}
return re;
}
} catch (Exception ex) {
logger.log(Level.WARNING, ex.getMessage());
return new String[0];
}
}
private static String str_replace(String search, String replace,
String subject) {
StringBuffer result = new StringBuffer(subject);
int pos;
while ((pos = result.indexOf(search)) != -1)
result.replace(pos, pos + search.length(), replace);
return result.toString();
}
public static void showGUI(){
try{
Class clazz=Class.forName("idv.jlchntoz.CustomSkinLoaderGUI");
String[] arg={"f",VERSION,"in"};
CustomSkinLoaderGUI.main(arg);
return;
}catch(Exception e){
logger.warning(e.getMessage());
}
File a=new File(DATA_DIR,"CustomSkinLoaderGUI.jar");
if(!a.exists()||a.length()<1){
a.delete();
logger.info("No GUI file found, try to download one to "+a.getAbsolutePath());
downloadFile("https://raw.githubusercontent.com/JLChnToZ/MCCustomSkinLoader/GUI/CustomSkinLoaderGUI.jar",a);
}
try{
String toRun="java -jar \""+a.getAbsolutePath()+"\" f "+VERSION;
logger.info("Run: "+toRun);
Runtime.getRuntime().exec(toRun);
}catch(Exception e){
logger.warning(e.getMessage());
}
}
public static boolean downloadFile(String remote,File local){
try {
File LCK=new File(local.getParentFile(),"download.lck");
if(LCK.exists()&&LCK.lastModified()>=System.currentTimeMillis()-10000){
logger.info("'download.lck' found! Download will not start.");
return false;
}
LCK.createNewFile();
logger.info("Downloading "+remote+" to "+local.getAbsolutePath());
URL url = new URL(remote);
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream(local);
int byteRead = 0;
byte[] buffer = new byte[1024];
while (( byteRead = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteRead);
}
fs.close();
LCK.delete();
logger.info("Download successfully!");
return local.exists();
}catch (Exception e) {
logger.warning(e.getMessage());
return false;
}
}
}
@@ -0,0 +1,71 @@
package idv.jlchntoz;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
public class MainLogger {
private static final int LOWEST_DISPLAY_LEVEL=Level.INFO.intValue();
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private BufferedWriter writer;
public MainLogger(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.intValue()>=LOWEST_DISPLAY_LEVEL)
System.out.println(msg);
try {
writer.write("[");
writer.write(DATE_FORMAT.format(new Date()));
writer.write(" ");
writer.write(Thread.currentThread().getName());
writer.write(" ");
writer.write(level.getName());
writer.write("] ");
writer.write(msg);
writer.write("\r\n");
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public void info(String msg){
log(Level.INFO,msg);
}
public void warning(String msg){
log(Level.WARNING,msg);
}
public void warning(Exception e){
log(Level.WARNING,"Exception occurs while running: "+e.getMessage());
StackTraceElement[] stes=e.getStackTrace();
for(StackTraceElement ste : stes){
log(Level.WARNING,ste.toString());
}
log(Level.WARNING,"");
}
}
@@ -0,0 +1,92 @@
package net.minecraft.src;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.ImageObserver;
public class ImageBufferDownload implements IImageBuffer
{
private int[] imageData;
private int imageWidth;
private int imageHeight;
public BufferedImage parseUserSkin(BufferedImage par1BufferedImage)
{
if (par1BufferedImage == null)
{
return null;
}
else
{
this.imageWidth = par1BufferedImage.getWidth();//Default: 64
this.imageHeight = par1BufferedImage.getHeight();//Default: 32
BufferedImage var2 = new BufferedImage(this.imageWidth, this.imageHeight, 2);
Graphics var3 = var2.getGraphics();
var3.drawImage(par1BufferedImage, 0, 0, (ImageObserver)null);
var3.dispose();
this.imageData = ((DataBufferInt)var2.getRaster().getDataBuffer()).getData();
//this.setAreaOpaque(0, 0, 32, 16);
//this.setAreaTransparent(32, 0, 64, 32);
//this.setAreaOpaque(0, 16, 64, 32);
this.setAreaOpaque(0, 0, imageWidth / 2, imageHeight / 2);
this.setAreaTransparent(imageWidth / 2, 0, imageWidth, imageHeight);
this.setAreaOpaque(0, imageHeight / 2, imageWidth, imageHeight);
return var2;
}
}
/**
* Makes the given area of the image transparent if it was previously completely opaque (used to remove the outer
* layer of a skin around the head if it was saved all opaque; this would be redundant so it's assumed that the skin
* maker is just using an image editor without an alpha channel)
*/
private void setAreaTransparent(int par1, int par2, int par3, int par4)
{
if (!this.hasTransparency(par1, par2, par3, par4))
{
for (int var5 = par1; var5 < par3; ++var5)
{
for (int var6 = par2; var6 < par4; ++var6)
{
this.imageData[var5 + var6 * this.imageWidth] &= 16777215;
}
}
}
}
/**
* Makes the given area of the image opaque
*/
private void setAreaOpaque(int par1, int par2, int par3, int par4)
{
for (int var5 = par1; var5 < par3; ++var5)
{
for (int var6 = par2; var6 < par4; ++var6)
{
this.imageData[var5 + var6 * this.imageWidth] |= -16777216;
}
}
}
/**
* Returns true if the given area of the image contains transparent pixels
*/
private boolean hasTransparency(int par1, int par2, int par3, int par4)
{
for (int var5 = par1; var5 < par3; ++var5)
{
for (int var6 = par2; var6 < par4; ++var6)
{
int var7 = this.imageData[var5 + var6 * this.imageWidth];
if ((var7 >> 24 & 255) < 128)
{
return true;
}
}
}
return false;
}
}
@@ -0,0 +1,79 @@
package net.minecraft.src;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class ThreadDownloadImageData extends AbstractTexture
{
private final String imageUrl;
private final IImageBuffer imageBuffer;
private BufferedImage bufferedImage;
private Thread imageThread;
private SimpleTexture imageLocation;
private boolean textureUploaded;
public ThreadDownloadImageData(String par1Str, ResourceLocation par2ResourceLocation, IImageBuffer par3IImageBuffer)
{
this.imageUrl = par1Str;
this.imageBuffer = par3IImageBuffer;
this.imageLocation = par2ResourceLocation != null ? new SimpleTexture(par2ResourceLocation) : null;
}
public int getGlTextureId()
{
int var1 = super.getGlTextureId();
if (!this.textureUploaded && this.bufferedImage != null)
{
TextureUtil.uploadTextureImage(var1, this.bufferedImage);
this.textureUploaded = true;
}
return var1;
}
public void getBufferedImage(BufferedImage par1BufferedImage)
{
this.bufferedImage = par1BufferedImage;
}
public void loadTexture(ResourceManager par1ResourceManager) throws IOException
{
if (this.bufferedImage == null)
{
if (this.imageLocation != null)
{
this.imageLocation.loadTexture(par1ResourceManager);
this.glTextureId = this.imageLocation.getGlTextureId();
}
}
else
{
TextureUtil.uploadTextureImage(this.getGlTextureId(), this.bufferedImage);
}
if (this.imageThread == null)
{
this.imageThread = new ThreadDownloadImageDataINNER1(this);
this.imageThread.setDaemon(true);
//this.imageThread.setName("Skin downloader: " + this.imageUrl);
this.imageThread.start();
}
}
public boolean isTextureUploaded()
{
this.getGlTextureId();
return this.textureUploaded;
}
static String getImageUrl(ThreadDownloadImageData par0ThreadDownloadImageData)
{
return par0ThreadDownloadImageData.imageUrl;
}
static IImageBuffer getImageBuffer(ThreadDownloadImageData par0ThreadDownloadImageData)
{
return par0ThreadDownloadImageData.imageBuffer;
}
}
@@ -0,0 +1,63 @@
package net.minecraft.src;
import idv.jlchntoz.CustomSkinLoader;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.imageio.ImageIO;
class ThreadDownloadImageDataINNER1 extends Thread
{
final ThreadDownloadImageData theThreadDownloadImageData;
ThreadDownloadImageDataINNER1(ThreadDownloadImageData par1ThreadDownloadImageData)
{
this.theThreadDownloadImageData = par1ThreadDownloadImageData;
}
public void run()
{
//HttpURLConnection var1 = null;
CustomSkinLoader loader=new CustomSkinLoader();
try
{
/*
var1 = (HttpURLConnection)(new URL(ThreadDownloadImageData.getImageUrl(this.theThreadDownloadImageData))).openConnection(Minecraft.getMinecraft().getProxy());
var1.setDoInput(true);
var1.setDoOutput(false);
var1.connect();
if (var1.getResponseCode() / 100 != 2)
{
return;
}
BufferedImage var2 = ImageIO.read(var1.getInputStream());
*/
BufferedImage var2 = ImageIO.read(loader.getPlayerSkinStream(
ThreadDownloadImageData.getImageUrl(this.theThreadDownloadImageData)));
if (ThreadDownloadImageData.getImageBuffer(this.theThreadDownloadImageData) != null)
{
var2 = ThreadDownloadImageData.getImageBuffer(this.theThreadDownloadImageData).parseUserSkin(var2);
}
this.theThreadDownloadImageData.getBufferedImage(var2);
}
catch (Exception var6)
{
var6.printStackTrace();
}
finally
{
/*
if (var1 != null)
{
var1.disconnect();
}*/
loader.disconnect();
}
}
}