/* * Updater for Bukkit. * * This class provides the means to safely and easily update a plugin, or check to see if it is updated using dev.bukkit.org */ package me.maker56.survivalgames; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import me.maker56.survivalgames.listener.UpdateListener; import org.bukkit.plugin.Plugin; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; /** * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed. * <p/> * <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. * <br> * 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/> * 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 * * @author Gravity * @version 2.1 */ public class UpdateCheck { private Plugin plugin; private String versionName; private String versionLink; private String versionType; private String versionGameVersion; private URL url; // Connecting to RSS private Thread thread; // Updater thread private int id = -1; // Project's Curse ID private String apiKey = null; // BukkitDev ServerMods API key private static final String TITLE_VALUE = "name"; // Gets remote file's title private static final String LINK_VALUE = "downloadUrl"; // Gets remote file's download link private static final String TYPE_VALUE = "releaseType"; // Gets remote file's release type private static final String VERSION_VALUE = "gameVersion"; // Gets remote file's build version private static final String QUERY = "/servermods/files?projectIds="; // Path to GET private static final String HOST = "https://api.curseforge.com"; // Slugs will be appended to this to get to the project's RSS feed private static final String USER_AGENT = "Updater (by Gravity)"; private UpdateCheck.UpdateResult result = UpdateCheck.UpdateResult.SUCCESS; // Used for determining the outcome of the update process /** * Gives the developer the result of the update process. Can be obtained by called {@link #getResult()} */ public enum UpdateResult { /** * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. */ SUCCESS, /** * The updater did not find an update, and nothing was downloaded. */ NO_UPDATE, /** * The server administrator has disabled the updating system. */ DISABLED, /** * The updater found an update, but was unable to download it. */ FAIL_DOWNLOAD, /** * For some reason, the updater was unable to contact dev.bukkit.org to download the file. */ FAIL_DBO, /** * When running the version check, the file on DBO did not contain a recognizable version. */ FAIL_NOVERSION, /** * The id provided by the plugin running the updater was invalid and doesn't exist on DBO. */ FAIL_BADID, /** * The server administrator has improperly configured their API key in the configuration. */ FAIL_APIKEY, /** * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. */ UPDATE_AVAILABLE } /** * Allows the developer to specify the type of update that will be run. */ public enum UpdateType { /** * Run a version check, and then if the file is out of date, download the newest version. */ DEFAULT, /** * Don't run a version check, just find the latest update and download it. */ NO_VERSION_CHECK, /** * Get information about the version and the download size, but don't actually download anything. */ NO_DOWNLOAD } /** * Represents the various release types of a file on BukkitDev. */ public enum ReleaseType { /** * An "alpha" file. */ ALPHA, /** * A "beta" file. */ BETA, /** * A "release" file. */ RELEASE } /** * Initialize the updater. * * @param plugin The plugin that is checking for an update. * @param id The dev.bukkit.org id of the project. * @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 UpdateCheck(Plugin plugin, int id) { this.plugin = plugin; this.id = id; if(!SurvivalGames.instance.getConfig().getBoolean("enable-update-check")) { System.out.println("[SurvivalGames] Update checking is disabled."); this.result = UpdateResult.DISABLED; return; } try { this.url = new URL(UpdateCheck.HOST + UpdateCheck.QUERY + id); } catch (final MalformedURLException e) { plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + id + " is invalid.", e); this.result = UpdateResult.FAIL_BADID; } this.thread = new Thread(new UpdateRunnable()); this.thread.start(); } /** * Get the result of the update process. * * @return result of the update process. * @see UpdateResult */ public UpdateCheck.UpdateResult getResult() { this.waitForThread(); return this.result; } /** * Get the latest version's release type. * * @return latest version's release type. * @see ReleaseType */ public ReleaseType getLatestType() { this.waitForThread(); if (this.versionType != null) { for (ReleaseType type : ReleaseType.values()) { if (this.versionType.equals(type.name().toLowerCase())) { return type; } } } return null; } /** * Get the latest version's game version (such as "CB 1.2.5-R1.0"). * * @return latest version's game version. */ public String getLatestGameVersion() { this.waitForThread(); return this.versionGameVersion; } /** * Get the latest version's name (such as "Project v1.0"). * * @return latest version's name. */ public String getLatestName() { this.waitForThread(); return this.versionName; } /** * Get the latest version's direct file link. * * @return latest version's file link. */ public String getLatestFileLink() { this.waitForThread(); return this.versionLink; } /** * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish * before allowing anyone to check the result. */ private void waitForThread() { if ((this.thread != null) && this.thread.isAlive()) { try { this.thread.join(); } catch (final InterruptedException e) { plugin.getLogger().log(Level.SEVERE, null, e); } } } /** * <b>If you wish to run mathematical versioning checks, edit this method.</b> * <p> * With default behavior, Updater will NOT verify that a remote version available on BukkitDev * which is not this version is indeed an "update". * If a version is present on BukkitDev that is not the version that is currently running, * Updater will assume that it is a newer version. * This is because there is no standard versioning scheme, and creating a calculation that can * determine whether a new update is actually an update is sometimes extremely complicated. * </p> * <p> * Updater will call this method from {@link #versionCheck(String)} before deciding whether * the remote version is actually an update. * If you have a specific versioning scheme with which a mathematical determination can * be reliably made to decide whether one version is higher than another, you may * revise this method, using the local and remote version parameters, to execute the * appropriate check. * </p> * <p> * Returning a value of <b>false</b> will tell the update process that this is NOT a new version. * Without revision, this method will always consider a remote version at all different from * that of the local version a new update. * </p> * @param localVersion the current version * @param remoteVersion the remote version * @return true if Updater should consider the remote version an update, false if not. */ public boolean shouldUpdate(String localVersion, String remoteVersion) { return !localVersion.equalsIgnoreCase(remoteVersion); } /** * Make a connection to the BukkitDev API and request the newest file's details. * * @return true if successful. */ private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", UpdateCheck.USER_AGENT); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } return false; } } private class UpdateRunnable implements Runnable { @Override public void run() { if (UpdateCheck.this.url != null) { // Obtain the results of the project's file feed if (UpdateCheck.this.read()) { if(!SurvivalGames.version.equals(UpdateCheck.this.versionName)) { UpdateListener.update(UpdateCheck.this.versionName); } } } } } }