Update Updater & other tiny changes

This commit is contained in:
h31ix committed 2013-01-14 21:59:49 -05:00
1 parent d5d705fbe4
commit a166367781
3 files changed
+295 -225

No files matched your search

@@ -138,8 +138,7 @@ public class AnticheatAPI {
*/ */
public static boolean isXrayer(Player player) { public static boolean isXrayer(Player player) {
String name = player.getName(); String name = player.getName();
if (xtracker.sufficientData(name) && xtracker.hasAbnormal(name)) { return true; } return xtracker.sufficientData(name) && xtracker.hasAbnormal(name);
return false;
} }
// Advanced Users Only API. // Advanced Users Only API.
@@ -1,30 +1,17 @@
/* /*
* AntiCheat for Bukkit. * Updater for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
* *
* This program is free software: you can redistribute it and/or modify * This class provides the means to safetly and easily update a plugin, or check to see if it is updated using dev.bukkit.org
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package net.h31ix.anticheat.update; package net.h31ix.anticheat.update;
import java.io.*; import java.io.*;
import java.lang.Runnable;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventReader;
@@ -37,29 +24,34 @@ import org.bukkit.plugin.Plugin;
/** /**
* Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed. * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed.
* <p> * <p>
* <strong>VERY, VERY IMPORTANT</strong>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating. <br> * <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating.
* It is a <strong>BUKKIT POLICY</strong> that you include a boolean value in your config that prevents the auto-updater from running <strong>AT ALL</strong>. <br> * <br>
* If you fail to include this option in your config, your plugin will be <strong>REJECTED</strong> when you attempt to submit it to dev.bukkit.org. * It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>.
* <br>
* If you fail to include this option in your config, your plugin will be <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org.
* <p> * <p>
* An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater. <br> * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater.
* <br>
* If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l
* *
* @author H31IX * @author H31IX
*/ */
public class Updater { public class Updater
{
private Plugin plugin; private Plugin plugin;
private UpdateType type; private UpdateType type;
private String versionTitle; private String versionTitle;
private String versionLink; private String versionLink;
private long totalSize; // Holds the total size of the file private long totalSize; // Holds the total size of the file
private double downloadedSize; // TODO: Holds the number of bytes downloaded //private double downloadedSize; TODO: Holds the number of bytes downloaded
private int sizeLine; // Used for detecting file size private int sizeLine; // Used for detecting file size
private int multiplier; // Used for determining when to broadcast download updates private int multiplier; // Used for determining when to broadcast download updates
private boolean announce; // Whether to announce file downloads private boolean announce; // Whether to announce file downloads
private URL url; // Connecting to RSS private URL url; // Connecting to RSS
private File file; // The plugin's file
private static final String DBOUrl = "http://dev.bukkit.org/server-mods/"; // Slugs will be appended to this to get to the project's RSS feed private static final String DBOUrl = "http://dev.bukkit.org/server-mods/"; // Slugs will be appended to this to get to the project's RSS feed
private String[] noUpdateTag = { "-DEV", "-PRE" }; // If the version number contains one of these, don't update. private String [] noUpdateTag = {"-DEV","-PRE"}; // If the version number contains one of these, don't update.
private static final int BYTE_SIZE = 1024; // Used for downloading files private static final int BYTE_SIZE = 1024; // Used for downloading files
private String updateFolder = YamlConfiguration.loadConfiguration(new File("bukkit.yml")).getString("settings.update-folder"); // The folder that downloads will be placed in private String updateFolder = YamlConfiguration.loadConfiguration(new File("bukkit.yml")).getString("settings.update-folder"); // The folder that downloads will be placed in
private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process
@@ -72,182 +64,129 @@ public class Updater {
/** /**
* Gives the dev the result of the update process. Can be obtained by called getResult(). * Gives the dev the result of the update process. Can be obtained by called getResult().
*/ */
public enum UpdateResult { public enum UpdateResult
{
/** /**
* The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads.
*/ */
SUCCESS(1), SUCCESS,
/** /**
* The updater did not find an update, and nothing was downloaded. * The updater did not find an update, and nothing was downloaded.
*/ */
NO_UPDATE(2), NO_UPDATE,
/** /**
* The updater found an update, but was unable to download it. * The updater found an update, but was unable to download it.
*/ */
FAIL_DOWNLOAD(3), FAIL_DOWNLOAD,
/** /**
* For some reason, the updater was unable to contact dev.bukkit.org to download the file. * For some reason, the updater was unable to contact dev.bukkit.org to download the file.
*/ */
FAIL_DBO(4), FAIL_DBO,
/** /**
* When running the version check, the file on DBO did not contain the a version in the format 'vVersion' such as 'v1.0'. * When running the version check, the file on DBO did not contain the a version in the format 'vVersion' such as 'v1.0'.
*/ */
FAIL_NOVERSION(5), FAIL_NOVERSION,
/** /**
* The slug provided by the plugin running the updater was invalid and doesn't exist on DBO. * The slug provided by the plugin running the updater was invalid and doesn't exist on DBO.
*/ */
FAIL_BADSLUG(6), FAIL_BADSLUG,
/** /**
* The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded.
*/ */
UPDATE_AVAILABLE(7), UPDATE_AVAILABLE
/**
* The update was unable to update due to a unknown exception thrown.
*/
UNKNOWN_ERROR(8);
private static final Map<Integer, Updater.UpdateResult> valueList = new HashMap<Integer, Updater.UpdateResult>();
private final int value;
private UpdateResult(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public static Updater.UpdateResult getResult(int value) {
return valueList.get(value);
}
static {
for (Updater.UpdateResult result : Updater.UpdateResult.values()) {
valueList.put(result.value, result);
}
}
} }
/** /**
* Allows the dev to specify the type of update that will be run. * Allows the dev to specify the type of update that will be run.
*/ */
public enum UpdateType { public enum UpdateType
{
/** /**
* Run a version check, and then if the file is out of date, download the newest version. * Run a version check, and then if the file is out of date, download the newest version.
*/ */
DEFAULT(1), DEFAULT,
/** /**
* Don't run a version check, just find the latest update and download it. * Don't run a version check, just find the latest update and download it.
*/ */
NO_VERSION_CHECK(2), NO_VERSION_CHECK,
/** /**
* Get information about the version and the download size, but don't actually download anything. * Get information about the version and the download size, but don't actually download anything.
*/ */
NO_DOWNLOAD(3); NO_DOWNLOAD
private static final Map<Integer, Updater.UpdateType> valueList = new HashMap<Integer, Updater.UpdateType>();
private final int value;
private UpdateType(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public static Updater.UpdateType getResult(int value) {
return valueList.get(value);
}
static {
for (Updater.UpdateType result : Updater.UpdateType.values()) {
valueList.put(result.value, result);
}
}
} }
/** /**
* Initialize the updater * Initialize the updater
* *
* @param plugin The plugin that is checking for an update. * @param plugin
* @param slug The dev.bukkit.org slug of the project (http://dev.bukkit.org/server-mods/SLUG_IS_HERE) * The plugin that is checking for an update.
* @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. * @param slug
* @param type Specify the type of update this will be. See {@link UpdateType} * The dev.bukkit.org slug of the project (http://dev.bukkit.org/server-mods/SLUG_IS_HERE)
* @param announce True if the program should announce the progress of new updates in console * @param file
* The file that the plugin is running from, get this by doing this.getFile() from within your main class.
* @param type
* Specify the type of update this will be. See {@link UpdateType}
* @param announce
* True if the program should announce the progress of new updates in console
*/ */
public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) { public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce)
{
this.plugin = plugin; this.plugin = plugin;
this.type = type; this.type = type;
this.announce = announce; this.announce = announce;
try { this.file = file;
try
{
// Obtain the results of the project's file feed // Obtain the results of the project's file feed
url = new URL(DBOUrl + slug + "/files.rss"); url = new URL(DBOUrl + slug + "/files.rss");
if (url != null) {
// Obtain the results of the project's file feed
readFeed();
if (versionCheck(versionTitle)) {
String fileLink = getFile(versionLink);
if (fileLink != null && type != UpdateType.NO_DOWNLOAD) {
String name = file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name
if (fileLink.endsWith(".zip")) {
String[] split = fileLink.split("/");
name = split[split.length - 1];
}
saveFile(new File("plugins/" + updateFolder), name, fileLink);
} else {
result = UpdateResult.UPDATE_AVAILABLE;
}
}
}
} catch (MalformedURLException ex) {
// The slug doesn't exist
plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system");
plugin.getLogger().warning("The project slug added ('" + slug + "') is invalid, and does not exist on dev.bukkit.org");
result = Updater.UpdateResult.FAIL_BADSLUG; // Bad slug! Bad!
} catch (RuntimeException ex) {
// Something went wrong with the updater and can't check for updates.
if (result == Updater.UpdateResult.SUCCESS) {
plugin.getLogger().warning("An error had occured and Auto Update was unable to check for updates");
plugin.getLogger().warning("Here is a stacktrace of what happened: ");
ex.printStackTrace();
result = Updater.UpdateResult.UNKNOWN_ERROR;
}
} }
catch (MalformedURLException ex)
{
// Invalid slug
plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system");
plugin.getLogger().warning("The project slug given ('" + slug + "') is invalid. Please nag the author about this.");
result = Updater.UpdateResult.FAIL_BADSLUG; // Bad slug! Bad!
}
new Thread(new UpdateRunnable()).start();
} }
/** /**
* Get the result of the update process. * Get the result of the update process.
*/ */
public Updater.UpdateResult getResult() { public Updater.UpdateResult getResult()
{
return result; return result;
} }
/** /**
* Get the total bytes of the file (can only be used after running a version check or a normal run). * Get the total bytes of the file (can only be used after running a version check or a normal run).
*/ */
public long getFileSize() { public long getFileSize()
{
return totalSize; return totalSize;
} }
/** /**
* Get the version string latest file avaliable online. * Get the version string latest file avaliable online.
*/ */
public String getLatestVersionString() { public String getLatestVersionString()
{
return versionTitle; return versionTitle;
} }
/** /**
* Save an update from dev.bukkit.org into the server's update folder. * Save an update from dev.bukkit.org into the server's update folder.
*/ */
private void saveFile(File folder, String file, String u) { private void saveFile(File folder, String file, String u)
if (!folder.exists()) { {
if(!folder.exists())
{
folder.mkdir(); folder.mkdir();
} }
BufferedInputStream in = null; BufferedInputStream in = null;
FileOutputStream fout = null; FileOutputStream fout = null;
try { try
{
// Download the file // Download the file
URL url = new URL(u); URL url = new URL(u);
int fileLength = url.openConnection().getContentLength(); int fileLength = url.openConnection().getContentLength();
@@ -256,73 +195,96 @@ public class Updater {
byte[] data = new byte[BYTE_SIZE]; byte[] data = new byte[BYTE_SIZE];
int count; int count;
if (announce) plugin.getLogger().info("About to download a new update: " + versionTitle); if(announce) plugin.getLogger().info("About to download a new update: " + versionTitle);
long downloaded = 0; long downloaded = 0;
while ((count = in.read(data, 0, BYTE_SIZE)) != -1) { while ((count = in.read(data, 0, BYTE_SIZE)) != -1)
{
downloaded += count; downloaded += count;
fout.write(data, 0, count); fout.write(data, 0, count);
int percent = (int) (downloaded * 100 / fileLength); int percent = (int) (downloaded * 100 / fileLength);
if (announce & (percent % 10 == 0)) { if(announce & (percent % 10 == 0))
{
plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes.");
} }
} }
// Just a quick check to make sure we didn't leave any files from last time... //Just a quick check to make sure we didn't leave any files from last time...
for (File xFile : new File("plugins/" + updateFolder).listFiles()) { for(File xFile : new File("plugins/" + updateFolder).listFiles())
if (xFile.getName().endsWith(".zip")) { {
if(xFile.getName().endsWith(".zip"))
{
xFile.delete(); xFile.delete();
} }
} }
// Check to see if it's a zip file, if it is, unzip it. // Check to see if it's a zip file, if it is, unzip it.
File dFile = new File(folder.getAbsolutePath() + "/" + file); File dFile = new File(folder.getAbsolutePath() + "/" + file);
if (dFile.getName().endsWith(".zip")) { if(dFile.getName().endsWith(".zip"))
{
// Unzip // Unzip
unzip(dFile.getCanonicalPath()); unzip(dFile.getCanonicalPath());
} }
if (announce) plugin.getLogger().info("Finished updating."); if(announce) plugin.getLogger().info("Finished updating.");
} catch (Exception ex) { }
catch (Exception ex)
{
plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DOWNLOAD; result = Updater.UpdateResult.FAIL_DOWNLOAD;
} finally { }
try { finally
if (in != null) { {
try
{
if (in != null)
{
in.close(); in.close();
} }
if (fout != null) { if (fout != null)
{
fout.close(); fout.close();
} }
} catch (Exception ex) {} }
catch (Exception ex)
{
}
} }
} }
/** /**
* Part of Zip-File-Extractor, modified by H31IX for use with Bukkit * Part of Zip-File-Extractor, modified by H31IX for use with Bukkit
*/ */
private void unzip(String file) { private void unzip(String file)
try { {
try
{
File fSourceZip = new File(file); File fSourceZip = new File(file);
String zipPath = file.substring(0, file.length() - 4); String zipPath = file.substring(0, file.length()-4);
ZipFile zipFile = new ZipFile(fSourceZip); ZipFile zipFile = new ZipFile(fSourceZip);
Enumeration e = zipFile.entries(); Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements()) { while(e.hasMoreElements())
ZipEntry entry = (ZipEntry) e.nextElement(); {
File destinationFilePath = new File(zipPath, entry.getName()); ZipEntry entry = (ZipEntry)e.nextElement();
File destinationFilePath = new File(zipPath,entry.getName());
destinationFilePath.getParentFile().mkdirs(); destinationFilePath.getParentFile().mkdirs();
if (entry.isDirectory()) { if(entry.isDirectory())
{
continue; continue;
} else { }
else
{
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
int b; int b;
byte buffer[] = new byte[BYTE_SIZE]; byte buffer[] = new byte[BYTE_SIZE];
FileOutputStream fos = new FileOutputStream(destinationFilePath); FileOutputStream fos = new FileOutputStream(destinationFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE); BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE);
while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) { while((b = bis.read(buffer, 0, BYTE_SIZE)) != -1)
{
bos.write(buffer, 0, b); bos.write(buffer, 0, b);
} }
bos.flush(); bos.flush();
bos.close(); bos.close();
bis.close(); bis.close();
String name = destinationFilePath.getName(); String name = destinationFilePath.getName();
if (name.endsWith(".jar") && pluginFile(name)) { if(name.endsWith(".jar") && pluginFile(name))
{
destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name)); destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name));
} }
} }
@@ -333,25 +295,32 @@ public class Updater {
zipFile.close(); zipFile.close();
zipFile = null; zipFile = null;
// Move any plugin data folders that were included to the right place, Bukkit won't do this for us. // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
for (File dFile : new File(zipPath).listFiles()) { for(File dFile : new File(zipPath).listFiles())
if (dFile.isDirectory()) { {
if (pluginFile(dFile.getName())) { if(dFile.isDirectory())
{
if(pluginFile(dFile.getName()))
{
File oFile = new File("plugins/" + dFile.getName()); // Get current dir File oFile = new File("plugins/" + dFile.getName()); // Get current dir
File[] contents = oFile.listFiles(); // List of existing files in the current dir File [] contents = oFile.listFiles(); // List of existing files in the current dir
for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir for(File cFile : dFile.listFiles()) // Loop through all the files in the new dir
{ {
boolean found = false; boolean found = false;
for (File xFile : contents) // Loop through contents to see if it exists for(File xFile : contents) // Loop through contents to see if it exists
{ {
if (xFile.getName().equals(cFile.getName())) { if(xFile.getName().equals(cFile.getName()))
{
found = true; found = true;
break; break;
} }
} }
if (!found) { if(!found)
{
// Move the new file into the current dir // Move the new file into the current dir
cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName()));
} else { }
else
{
// This file already exists, so we don't need it anymore. // This file already exists, so we don't need it anymore.
cFile.delete(); cFile.delete();
} }
@@ -362,7 +331,9 @@ public class Updater {
} }
new File(zipPath).delete(); new File(zipPath).delete();
fSourceZip.delete(); fSourceZip.delete();
} catch (IOException ex) { }
catch(IOException ex)
{
ex.printStackTrace(); ex.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DOWNLOAD; result = Updater.UpdateResult.FAIL_DOWNLOAD;
@@ -373,9 +344,14 @@ public class Updater {
/** /**
* Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip.
*/ */
public boolean pluginFile(String name) { public boolean pluginFile(String name)
for (File file : new File("plugins").listFiles()) { {
if (file.getName().equals(name)) { return true; } for(File file : new File("plugins").listFiles())
{
if(file.getName().equals(name))
{
return true;
}
} }
return false; return false;
} }
@@ -383,9 +359,11 @@ public class Updater {
/** /**
* Obtain the direct download file url from the file's page. * Obtain the direct download file url from the file's page.
*/ */
private String getFile(String link) { private String getFile(String link)
{
String download = null; String download = null;
try { try
{
// Open a connection to the page // Open a connection to the page
URL url = new URL(link); URL url = new URL(link);
URLConnection urlConn = url.openConnection(); URLConnection urlConn = url.openConnection();
@@ -394,28 +372,35 @@ public class Updater {
int counter = 0; int counter = 0;
String line; String line;
while ((line = buff.readLine()) != null) { while((line = buff.readLine()) != null)
{
counter++; counter++;
// Search for the download link // Search for the download link
if (line.contains("<li class=\"user-action user-action-download\">")) { if(line.contains("<li class=\"user-action user-action-download\">"))
{
// Get the raw link // Get the raw link
download = line.split("<a href=\"")[1].split("\">Download</a>")[0]; download = line.split("<a href=\"")[1].split("\">Download</a>")[0];
} }
// Search for size // Search for size
else if (line.contains("<dt>Size</dt>")) { else if (line.contains("<dt>Size</dt>"))
sizeLine = counter + 1; {
} else if (counter == sizeLine) { sizeLine = counter+1;
}
else if(counter == sizeLine)
{
String size = line.replaceAll("<dd>", "").replaceAll("</dd>", ""); String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "");
multiplier = size.contains("MiB") ? 1048576 : 1024; multiplier = size.contains("MiB") ? 1048576 : 1024;
size = size.replace(" KiB", "").replace(" MiB", ""); size = size.replace(" KiB", "").replace(" MiB", "");
totalSize = (long) (Double.parseDouble(size) * multiplier); totalSize = (long)(Double.parseDouble(size)*multiplier);
} }
} }
urlConn = null; urlConn = null;
inStream = null; inStream = null;
buff.close(); buff.close();
buff = null; buff = null;
} catch (Exception ex) { }
catch (Exception ex)
{
ex.printStackTrace(); ex.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DBO; result = Updater.UpdateResult.FAIL_DBO;
@@ -427,40 +412,73 @@ public class Updater {
/** /**
* Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated * Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated
*/ */
private boolean versionCheck(String title) { private boolean versionCheck(String title)
if (type != UpdateType.NO_VERSION_CHECK) { {
if(type != UpdateType.NO_VERSION_CHECK)
{
String version = plugin.getDescription().getVersion(); String version = plugin.getDescription().getVersion();
if (title.split("v").length == 2) { if(title.split(" v").length == 2)
String remoteVersion = title.split("v")[1].split(" ")[0]; // Get the newest file's version number {
if (hasTag(version, remoteVersion) || version.equalsIgnoreCase(remoteVersion)) { String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number
int remVer = -1,curVer=0;
try
{
remVer = calVer(remoteVersion);
curVer = calVer(version);
}
catch(NumberFormatException nfe)
{
remVer=-1;
}
if(hasTag(version)||version.equalsIgnoreCase(remoteVersion)||curVer>=remVer)
{
// We already have the latest version, or this build is tagged for no-update // We already have the latest version, or this build is tagged for no-update
result = Updater.UpdateResult.NO_UPDATE; result = Updater.UpdateResult.NO_UPDATE;
return false; return false;
} }
} else { }
else
{
// The file's name did not contain the string 'vVersion' // The file's name did not contain the string 'vVersion'
plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system"); plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system");
plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0"); plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0");
plugin.getLogger().warning("Please notify the author (" + plugin.getDescription().getAuthors().get(0) + ") of this error."); plugin.getLogger().warning("Please notify the author of this error.");
result = Updater.UpdateResult.FAIL_NOVERSION; result = Updater.UpdateResult.FAIL_NOVERSION;
return false; return false;
} }
} }
return true; return true;
} }
/**
* Used to calculate the version string as an Integer
*/
private Integer calVer(String s) throws NumberFormatException
{
if(s.contains("."))
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i <s.length(); i++)
{
Character c = s.charAt(i);
if (Character.isLetterOrDigit(c))
{
sb.append(c);
}
}
return Integer.parseInt(sb.toString());
}
return Integer.parseInt(s);
}
/** /**
* Evaluate whether the version number is marked showing that it should not be updated by this program * Evaluate whether the version number is marked showing that it should not be updated by this program
*/ */
private boolean hasTag(String version, String remoteVersion) { private boolean hasTag(String version)
for (String string : noUpdateTag) { {
if (version.contains(string)) { for(String string : noUpdateTag)
if (version.replaceAll(string, "").equals(remoteVersion)) { {
// The build has a tag, but the version was upgraded to release so we should do an update anyway if(version.contains(string))
return false; {
} else { return true;
return true;
}
} }
} }
return false; return false;
@@ -469,9 +487,10 @@ public class Updater {
/** /**
* Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit * Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit
*/ */
@SuppressWarnings({ "deprecation", "restriction" }) private boolean readFeed()
private void readFeed() { {
try { try
{
// Set header values intial to the empty string // Set header values intial to the empty string
String title = ""; String title = "";
String link = ""; String link = "";
@@ -479,47 +498,99 @@ public class Updater {
XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader // Setup a new eventReader
InputStream in = read(); InputStream in = read();
XMLEventReader eventReader = inputFactory.createXMLEventReader(in); if(in != null)
// Read the XML document {
while (eventReader.hasNext()) { XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
XMLEvent event = eventReader.nextEvent(); // Read the XML document
if (event.isStartElement()) { while (eventReader.hasNext())
if (event.asStartElement().getName().getLocalPart().equals(TITLE)) { {
event = eventReader.nextEvent(); XMLEvent event = eventReader.nextEvent();
title = event.asCharacters().getData(); if (event.isStartElement())
continue; {
if (event.asStartElement().getName().getLocalPart().equals(TITLE))
{
event = eventReader.nextEvent();
title = event.asCharacters().getData();
continue;
}
if (event.asStartElement().getName().getLocalPart().equals(LINK))
{
event = eventReader.nextEvent();
link = event.asCharacters().getData();
continue;
}
} }
if (event.asStartElement().getName().getLocalPart().equals(LINK)) { else if (event.isEndElement())
event = eventReader.nextEvent(); {
link = event.asCharacters().getData(); if (event.asEndElement().getName().getLocalPart().equals(ITEM))
continue; {
} // Store the title and link of the first entry we get - the first file on the list is all we need
} else if (event.isEndElement()) { versionTitle = title;
if (event.asEndElement().getName().getLocalPart().equals(ITEM)) { versionLink = link;
// Store the title and link of the first entry we get - the first file on the list is all we need // All done, we don't need to know about older files.
versionTitle = title; break;
versionLink = link; }
// All done, we don't need to know about older files.
break;
} }
} }
return true;
} }
} catch (XMLStreamException e) { else
throw new RuntimeException(e); {
return false;
}
}
catch (XMLStreamException e)
{
plugin.getLogger().warning("Could not reach dev.bukkit.org for update checking. Is it offline?");
return false;
} }
} }
/** /**
* Open the RSS feed * Open the RSS feed
*/ */
private InputStream read() { private InputStream read()
try { {
try
{
return url.openStream(); return url.openStream();
} catch (IOException e) { }
e.printStackTrace(); catch (IOException e)
plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); {
result = Updater.UpdateResult.FAIL_DBO; plugin.getLogger().warning("Could not reach BukkitDev file stream for update checking. Is dev.bukkit.org offline?");
return null; return null;
} }
} }
private class UpdateRunnable implements Runnable {
public void run() {
if(url != null)
{
// Obtain the results of the project's file feed
if(readFeed())
{
if(versionCheck(versionTitle))
{
String fileLink = getFile(versionLink);
if(fileLink != null && type != UpdateType.NO_DOWNLOAD)
{
String name = file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name
if(fileLink.endsWith(".zip"))
{
String [] split = fileLink.split("/");
name = split[split.length-1];
}
saveFile(new File("plugins/" + updateFolder), name, fileLink);
}
else
{
result = UpdateResult.UPDATE_AVAILABLE;
}
}
}
}
}
}
} }
@@ -3,7 +3,7 @@ package net.h31ix.anticheat.util;
public class CheckResult { public class CheckResult {
public enum Result { public enum Result {
PASSED,FAILED; PASSED,FAILED
} }
private Result result; private Result result;