Updater.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. /*
  2. * Updater for Bukkit.
  3. *
  4. * This class provides the means to safely and easily update a plugin, or check to see if it is updated using dev.bukkit.org
  5. */
  6. package net.h31ix.updater;
  7. import javax.xml.stream.XMLEventReader;
  8. import javax.xml.stream.XMLInputFactory;
  9. import javax.xml.stream.XMLStreamException;
  10. import javax.xml.stream.events.XMLEvent;
  11. import java.io.BufferedInputStream;
  12. import java.io.BufferedOutputStream;
  13. import java.io.BufferedReader;
  14. import java.io.File;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.io.InputStreamReader;
  19. import java.net.MalformedURLException;
  20. import java.net.URL;
  21. import java.net.URLConnection;
  22. import java.util.Enumeration;
  23. import java.util.zip.ZipEntry;
  24. import java.util.zip.ZipFile;
  25. import org.bukkit.configuration.file.YamlConfiguration;
  26. import org.bukkit.plugin.Plugin;
  27. /**
  28. * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed.
  29. * <p/>
  30. * <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.
  31. * <br>
  32. * 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>.
  33. * <br>
  34. * 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.
  35. * <p/>
  36. * 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.
  37. * <br>
  38. * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l
  39. *
  40. * @author H31IX
  41. */
  42. public class Updater {
  43. private Plugin plugin;
  44. private UpdateType type;
  45. private String versionTitle;
  46. private String versionLink;
  47. private long totalSize; // Holds the total size of the file
  48. //private double downloadedSize; TODO: Holds the number of bytes downloaded
  49. private int sizeLine; // Used for detecting file size
  50. private int multiplier; // Used for determining when to broadcast download updates
  51. private boolean announce; // Whether to announce file downloads
  52. private URL url; // Connecting to RSS
  53. private File file; // The plugin's file
  54. private Thread thread; // Updater thread
  55. 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
  56. private String[] noUpdateTag = {}; // If the version number contains one of these, don't update.
  57. private static final int BYTE_SIZE = 1024; // Used for downloading files
  58. private String updateFolder = YamlConfiguration.loadConfiguration(new File("bukkit.yml")).getString("settings.update-folder"); // The folder that downloads will be placed in
  59. private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process
  60. // Strings for reading RSS
  61. private static final String TITLE = "title";
  62. private static final String LINK = "link";
  63. private static final String ITEM = "item";
  64. /**
  65. * Gives the dev the result of the update process. Can be obtained by called getResult().
  66. */
  67. public enum UpdateResult {
  68. /**
  69. * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads.
  70. */
  71. SUCCESS,
  72. /**
  73. * The updater did not find an update, and nothing was downloaded.
  74. */
  75. NO_UPDATE,
  76. /**
  77. * The updater found an update, but was unable to download it.
  78. */
  79. FAIL_DOWNLOAD,
  80. /**
  81. * For some reason, the updater was unable to contact dev.bukkit.org to download the file.
  82. */
  83. FAIL_DBO,
  84. /**
  85. * When running the version check, the file on DBO did not contain the a version in the format 'vVersion' such as 'v1.0'.
  86. */
  87. FAIL_NOVERSION,
  88. /**
  89. * The slug provided by the plugin running the updater was invalid and doesn't exist on DBO.
  90. */
  91. FAIL_BADSLUG,
  92. /**
  93. * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded.
  94. */
  95. UPDATE_AVAILABLE
  96. }
  97. /**
  98. * Allows the dev to specify the type of update that will be run.
  99. */
  100. public enum UpdateType {
  101. /**
  102. * Run a version check, and then if the file is out of date, download the newest version.
  103. */
  104. DEFAULT,
  105. /**
  106. * Don't run a version check, just find the latest update and download it.
  107. */
  108. NO_VERSION_CHECK,
  109. /**
  110. * Get information about the version and the download size, but don't actually download anything.
  111. */
  112. NO_DOWNLOAD
  113. }
  114. /**
  115. * Initialize the updater
  116. *
  117. * @param plugin The plugin that is checking for an update.
  118. * @param slug The dev.bukkit.org slug of the project (http://dev.bukkit.org/server-mods/SLUG_IS_HERE)
  119. * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class.
  120. * @param type Specify the type of update this will be. See {@link UpdateType}
  121. * @param announce True if the program should announce the progress of new updates in console
  122. */
  123. public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) {
  124. this.plugin = plugin;
  125. this.type = type;
  126. this.announce = announce;
  127. this.file = file;
  128. try {
  129. // Obtain the results of the project's file feed
  130. url = new URL(DBOUrl + slug + "/files.rss");
  131. }
  132. catch (MalformedURLException ex) {
  133. // Invalid slug
  134. plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system");
  135. plugin.getLogger().warning("The project slug given ('" + slug + "') is invalid. Please nag the author about this.");
  136. result = Updater.UpdateResult.FAIL_BADSLUG; // Bad slug! Bad!
  137. }
  138. thread = new Thread(new UpdateRunnable());
  139. thread.start();
  140. }
  141. /**
  142. * Get the result of the update process.
  143. */
  144. public Updater.UpdateResult getResult() {
  145. waitForThread();
  146. return result;
  147. }
  148. /**
  149. * Get the total bytes of the file (can only be used after running a version check or a normal run).
  150. */
  151. public long getFileSize() {
  152. waitForThread();
  153. return totalSize;
  154. }
  155. /**
  156. * Get the version string latest file avaliable online.
  157. */
  158. public String getLatestVersionString() {
  159. waitForThread();
  160. return versionTitle;
  161. }
  162. /**
  163. * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish
  164. * before alloowing anyone to check the result.
  165. */
  166. public void waitForThread() {
  167. if (thread.isAlive()) {
  168. try {
  169. thread.join();
  170. }
  171. catch (InterruptedException e) {
  172. e.printStackTrace();
  173. }
  174. }
  175. }
  176. /**
  177. * Save an update from dev.bukkit.org into the server's update folder.
  178. */
  179. private void saveFile(File folder, String file, String u) {
  180. if (!folder.exists()) {
  181. folder.mkdir();
  182. }
  183. BufferedInputStream in = null;
  184. FileOutputStream fout = null;
  185. try {
  186. // Download the file
  187. URL url = new URL(u);
  188. int fileLength = url.openConnection().getContentLength();
  189. in = new BufferedInputStream(url.openStream());
  190. fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file);
  191. byte[] data = new byte[BYTE_SIZE];
  192. int count;
  193. if (announce) {
  194. plugin.getLogger().info("About to download a new update: " + versionTitle);
  195. }
  196. long downloaded = 0;
  197. while ((count = in.read(data, 0, BYTE_SIZE)) != -1) {
  198. downloaded += count;
  199. fout.write(data, 0, count);
  200. int percent = (int) (downloaded * 100 / fileLength);
  201. if (announce & (percent % 10 == 0)) {
  202. plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes.");
  203. }
  204. }
  205. //Just a quick check to make sure we didn't leave any files from last time...
  206. for (File xFile : new File("plugins/" + updateFolder).listFiles()) {
  207. if (xFile.getName().endsWith(".zip")) {
  208. xFile.delete();
  209. }
  210. }
  211. // Check to see if it's a zip file, if it is, unzip it.
  212. File dFile = new File(folder.getAbsolutePath() + "/" + file);
  213. if (dFile.getName().endsWith(".zip")) {
  214. // Unzip
  215. unzip(dFile.getCanonicalPath());
  216. }
  217. if (announce) {
  218. plugin.getLogger().info("Finished updating.");
  219. }
  220. }
  221. catch (Exception ex) {
  222. plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful.");
  223. result = Updater.UpdateResult.FAIL_DOWNLOAD;
  224. }
  225. finally {
  226. try {
  227. if (in != null) {
  228. in.close();
  229. }
  230. if (fout != null) {
  231. fout.close();
  232. }
  233. }
  234. catch (Exception ex) {
  235. }
  236. }
  237. }
  238. /**
  239. * Part of Zip-File-Extractor, modified by H31IX for use with Bukkit
  240. */
  241. private void unzip(String file) {
  242. try {
  243. File fSourceZip = new File(file);
  244. String zipPath = file.substring(0, file.length() - 4);
  245. ZipFile zipFile = new ZipFile(fSourceZip);
  246. Enumeration<? extends ZipEntry> e = zipFile.entries();
  247. while (e.hasMoreElements()) {
  248. ZipEntry entry = (ZipEntry) e.nextElement();
  249. File destinationFilePath = new File(zipPath, entry.getName());
  250. destinationFilePath.getParentFile().mkdirs();
  251. if (entry.isDirectory()) {
  252. continue;
  253. }
  254. else {
  255. BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
  256. int b;
  257. byte buffer[] = new byte[BYTE_SIZE];
  258. FileOutputStream fos = new FileOutputStream(destinationFilePath);
  259. BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE);
  260. while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) {
  261. bos.write(buffer, 0, b);
  262. }
  263. bos.flush();
  264. bos.close();
  265. bis.close();
  266. String name = destinationFilePath.getName();
  267. if (name.endsWith(".jar") && pluginFile(name)) {
  268. destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name));
  269. }
  270. }
  271. entry = null;
  272. destinationFilePath = null;
  273. }
  274. e = null;
  275. zipFile.close();
  276. zipFile = null;
  277. // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
  278. for (File dFile : new File(zipPath).listFiles()) {
  279. if (dFile.isDirectory()) {
  280. if (pluginFile(dFile.getName())) {
  281. File oFile = new File("plugins/" + dFile.getName()); // Get current dir
  282. File[] contents = oFile.listFiles(); // List of existing files in the current dir
  283. for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir
  284. {
  285. boolean found = false;
  286. for (File xFile : contents) // Loop through contents to see if it exists
  287. {
  288. if (xFile.getName().equals(cFile.getName())) {
  289. found = true;
  290. break;
  291. }
  292. }
  293. if (!found) {
  294. // Move the new file into the current dir
  295. cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName()));
  296. }
  297. else {
  298. // This file already exists, so we don't need it anymore.
  299. cFile.delete();
  300. }
  301. }
  302. }
  303. }
  304. dFile.delete();
  305. }
  306. new File(zipPath).delete();
  307. fSourceZip.delete();
  308. }
  309. catch (IOException ex) {
  310. ex.printStackTrace();
  311. plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
  312. result = Updater.UpdateResult.FAIL_DOWNLOAD;
  313. }
  314. new File(file).delete();
  315. }
  316. /**
  317. * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip.
  318. */
  319. public boolean pluginFile(String name) {
  320. for (File file : new File("plugins").listFiles()) {
  321. if (file.getName().equals(name)) {
  322. return true;
  323. }
  324. }
  325. return false;
  326. }
  327. /**
  328. * Obtain the direct download file url from the file's page.
  329. */
  330. private String getFile(String link) {
  331. String download = null;
  332. try {
  333. // Open a connection to the page
  334. URL url = new URL(link);
  335. URLConnection urlConn = url.openConnection();
  336. InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
  337. BufferedReader buff = new BufferedReader(inStream);
  338. int counter = 0;
  339. String line;
  340. while ((line = buff.readLine()) != null) {
  341. counter++;
  342. // Search for the download link
  343. if (line.contains("<li class=\"user-action user-action-download\">")) {
  344. // Get the raw link
  345. download = line.split("<a href=\"")[1].split("\">Download</a>")[0];
  346. }
  347. // Search for size
  348. else if (line.contains("<dt>Size</dt>")) {
  349. sizeLine = counter + 1;
  350. }
  351. else if (counter == sizeLine) {
  352. String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "");
  353. multiplier = size.contains("MiB") ? 1048576 : 1024;
  354. size = size.replace(" KiB", "").replace(" MiB", "");
  355. totalSize = (long) (Double.parseDouble(size) * multiplier);
  356. }
  357. }
  358. urlConn = null;
  359. inStream = null;
  360. buff.close();
  361. buff = null;
  362. }
  363. catch (Exception ex) {
  364. ex.printStackTrace();
  365. plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful.");
  366. result = Updater.UpdateResult.FAIL_DBO;
  367. return null;
  368. }
  369. return download;
  370. }
  371. /**
  372. * Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated
  373. */
  374. private boolean versionCheck(String title) {
  375. if (type != UpdateType.NO_VERSION_CHECK) {
  376. String version = plugin.getDescription().getVersion();
  377. title = title.substring(6);
  378. String[] oldTokens = version.split("-");
  379. String[] newTokens = title.split("-");
  380. int oldVersion = Integer.parseInt(oldTokens[0].replaceAll(".", ""));
  381. int newVersion = Integer.parseInt(newTokens[0].replaceAll(".", ""));
  382. // Check versions
  383. if (oldVersion < newVersion) {
  384. return true;
  385. }
  386. // Check release vs. beta & dev
  387. if (newTokens.length == 0 && oldTokens.length == 2 && oldVersion == newVersion) {
  388. return true;
  389. }
  390. // Check beta vs. dev
  391. if (version.contains("dev") && title.contains("beta")) {
  392. if (Integer.parseInt(oldTokens[1].substring(3)) < Integer.parseInt(newTokens[1].substring(4))) {
  393. return true;
  394. }
  395. result = UpdateResult.NO_UPDATE;
  396. return false;
  397. }
  398. // Check beta vs. beta
  399. if (version.contains("beta") && title.contains("beta")) {
  400. if (Integer.parseInt(oldTokens[1].substring(4)) < Integer.parseInt(newTokens[1].substring(4))) {
  401. return true;
  402. }
  403. result = UpdateResult.NO_UPDATE;
  404. return false;
  405. }
  406. if (oldTokens.length == 2 && !version.contains("beta") && !version.contains("dev")) {
  407. plugin.getLogger().warning("Could not get information about this mcMMO version; perhaps you are running a custom one?");
  408. result = UpdateResult.FAIL_NOVERSION;
  409. return false;
  410. }
  411. }
  412. return true;
  413. }
  414. /**
  415. * Used to calculate the version string as an Integer
  416. */
  417. private Integer calVer(String s) throws NumberFormatException {
  418. if (s.contains(".")) {
  419. StringBuilder sb = new StringBuilder();
  420. for (int i = 0; i < s.length(); i++) {
  421. Character c = s.charAt(i);
  422. if (Character.isLetterOrDigit(c)) {
  423. sb.append(c);
  424. }
  425. }
  426. return Integer.parseInt(sb.toString());
  427. }
  428. return Integer.parseInt(s);
  429. }
  430. /**
  431. * Evaluate whether the version number is marked showing that it should not be updated by this program
  432. */
  433. private boolean hasTag(String version) {
  434. for (String string : noUpdateTag) {
  435. if (version.contains(string)) {
  436. return true;
  437. }
  438. }
  439. return false;
  440. }
  441. /**
  442. * Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit
  443. */
  444. private boolean readFeed() {
  445. try {
  446. // Set header values intial to the empty string
  447. String title = "";
  448. String link = "";
  449. // First create a new XMLInputFactory
  450. XMLInputFactory inputFactory = XMLInputFactory.newInstance();
  451. // Setup a new eventReader
  452. InputStream in = read();
  453. if (in != null) {
  454. XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
  455. // Read the XML document
  456. while (eventReader.hasNext()) {
  457. XMLEvent event = eventReader.nextEvent();
  458. if (event.isStartElement()) {
  459. if (event.asStartElement().getName().getLocalPart().equals(TITLE)) {
  460. event = eventReader.nextEvent();
  461. title = event.asCharacters().getData();
  462. continue;
  463. }
  464. if (event.asStartElement().getName().getLocalPart().equals(LINK)) {
  465. event = eventReader.nextEvent();
  466. link = event.asCharacters().getData();
  467. continue;
  468. }
  469. }
  470. else if (event.isEndElement()) {
  471. if (event.asEndElement().getName().getLocalPart().equals(ITEM)) {
  472. // Store the title and link of the first entry we get - the first file on the list is all we need
  473. versionTitle = title;
  474. versionLink = link;
  475. // All done, we don't need to know about older files.
  476. break;
  477. }
  478. }
  479. }
  480. return true;
  481. }
  482. else {
  483. return false;
  484. }
  485. }
  486. catch (XMLStreamException e) {
  487. plugin.getLogger().warning("Could not reach dev.bukkit.org for update checking. Is it offline?");
  488. return false;
  489. }
  490. }
  491. /**
  492. * Open the RSS feed
  493. */
  494. private InputStream read() {
  495. try {
  496. return url.openStream();
  497. }
  498. catch (IOException e) {
  499. plugin.getLogger().warning("Could not reach BukkitDev file stream for update checking. Is dev.bukkit.org offline?");
  500. return null;
  501. }
  502. }
  503. private class UpdateRunnable implements Runnable {
  504. public void run() {
  505. if (url != null) {
  506. // Obtain the results of the project's file feed
  507. if (readFeed()) {
  508. if (versionCheck(versionTitle)) {
  509. String fileLink = getFile(versionLink);
  510. if (fileLink != null && type != UpdateType.NO_DOWNLOAD) {
  511. String name = file.getName();
  512. // If it's a zip file, it shouldn't be downloaded as the plugin's name
  513. if (fileLink.endsWith(".zip")) {
  514. String[] split = fileLink.split("/");
  515. name = split[split.length - 1];
  516. }
  517. saveFile(new File("plugins/" + updateFolder), name, fileLink);
  518. }
  519. else {
  520. result = UpdateResult.UPDATE_AVAILABLE;
  521. }
  522. }
  523. }
  524. }
  525. }
  526. }
  527. }