Skip to content

Commit

Permalink
Add UpdaterService
Browse files Browse the repository at this point in the history
  • Loading branch information
monst committed Feb 18, 2023
1 parent c5ed447 commit 9dfb2bf
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 110 deletions.
111 changes: 12 additions & 99 deletions src/main/java/com/monst/bankingplugin/BankingPlugin.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
package com.monst.bankingplugin;

import com.earth2me.essentials.Essentials;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.monst.bankingplugin.command.ClickAction;
import com.monst.bankingplugin.command.SubCommand;
import com.monst.bankingplugin.command.account.AccountCommand;
import com.monst.bankingplugin.command.bank.BankCommand;
import com.monst.bankingplugin.command.plugin.BPCommand;
Expand Down Expand Up @@ -36,11 +30,7 @@
import org.codemc.worldguardwrapper.flag.WrappedState;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
Expand All @@ -55,6 +45,7 @@ public class BankingPlugin extends JavaPlugin {
private Database database;

/* Services */
private UpdaterService updaterService;
private SchedulerService schedulerService;
private PaymentService paymentService;
private Worths worths;
Expand All @@ -67,9 +58,6 @@ public class BankingPlugin extends JavaPlugin {
private GriefPrevention griefPrevention;
private WorldEditPlugin worldEdit;

/* Update Package */
private Update update;

/* Debug */
private Logger debugger = Logger.NO_OP; // Default to no-op logger, will be replaced by a real logger if debug is enabled

Expand Down Expand Up @@ -113,15 +101,12 @@ public void onEnable() {
account.updateChestTitle();
}

updaterService = new UpdaterService(this);
schedulerService = new SchedulerService(this);
paymentService = new PaymentService(this);

new AccountCommand(this);
new BankCommand(this);
new BPCommand(this);


if (config().enableStartupUpdateCheck.get()) {
checkForUpdates().then(update -> {
updaterService.checkForUpdate().then(update -> {
if (update == null)
return;
log(Level.WARNING, "Version " + update.getVersion() + " of BankingPlugin is available!");
Expand All @@ -130,6 +115,10 @@ public void onEnable() {
}).catchError(error -> getLogger().warning("Failed to check for updates!"));
}

new AccountCommand(this);
new BankCommand(this);
new BPCommand(this);

registerListeners();
enableMetrics();
}
Expand All @@ -141,9 +130,6 @@ public void onDisable() {
for (Account account : getAccountService().findAll())
account.resetChestTitle();

ClickAction.clear();
SubCommand.clearCache();

setDebugLogEnabled(false);
if (database != null)
database.shutdown();
Expand Down Expand Up @@ -214,83 +200,6 @@ private void loadSoftDependencies() {
WorldGuardWrapper.getInstance().registerEvents(this);
}

/**
* Checks if an update is needed.
*/
public Promise<Update> checkForUpdates() {
debug("Checking for updates...");
return Promise.async(this, () -> {
JsonElement response;
URL url = new URL("https://api.github.com/repos/FreshLlamanade/BankingPlugin/releases");
URLConnection con = url.openConnection();
con.setConnectTimeout(5000);
con.setRequestProperty("User-Agent", "BankingPlugin");
con.setDoOutput(true);

response = new JsonParser().parse(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));

// Releases are sorted by date, newest first
JsonArray releases = response.getAsJsonArray();

if (releases.size() == 0)
// No versions available
return update;

String versionNumber = null;
JsonObject jar = null;
for (int i = releases.size() - 1; i >= 0; i--) {
JsonObject version = releases.get(i).getAsJsonObject();
versionNumber = version.get("name").getAsString();
debug("Checking version " + versionNumber);

if (versionNumber.compareTo(getDescription().getVersion()) <= 0) {
// This version is no newer than current version
// No need to check further
return update;
}

if (config().ignoreUpdatesContaining.ignore(versionNumber)) { // This version is ignored
debug("Skipping version " + versionNumber + " because it contains an ignored tag.");
continue;
}

for (JsonElement asset : version.get("assets").getAsJsonArray()) {
if (((JsonObject) asset).get("name").getAsString().endsWith(".jar")) {
// Found the latest non-ignored jar available, and it is newer than the current version
jar = (JsonObject) asset;
break;
}
}
}

if (jar == null)
// No suitable update found
return update;

debug("Found latest version: " + versionNumber);

// An update already exists newer or equal to this one
if (update != null && update.getVersion().compareTo(versionNumber) > 0)
return update;

if (update != null)
update.setOutdated();

// Create a new update package
debug("Creating new update package.");
URL fileURL;
fileURL = new URL(jar.get("browser_download_url").getAsString());
String checksum = Optional.ofNullable(jar.get("md5")).map(JsonElement::getAsString).orElse(null);
int downloadSize = jar.get("size").getAsInt();

return update = new Update(this, versionNumber, fileURL, checksum, downloadSize);
});
}

public Update getUpdate() {
return update;
}

/**
* Register all listeners necessary for BankingPlugin to function.
* @see AccountBalanceListener
Expand Down Expand Up @@ -456,6 +365,10 @@ public AccountTransactionService getAccountTransactionService() {
public BankIncomeService getBankIncomeService() {
return database.getBankIncomeService();
}

public UpdaterService getUpdaterService() {
return updaterService;
}

public SchedulerService getSchedulerService() {
return schedulerService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,31 +34,29 @@ protected Message getNoPermissionMessage() {
@Override
protected void execute(CommandSender sender, String[] args) {
sender.sendMessage(Message.UPDATE_CHECKING.translate(plugin));

plugin.checkForUpdates().catchError(error -> {
sender.sendMessage(Message.UPDATE_CHECK_ERROR.translate(plugin));
plugin.debug(error);
}).then(update -> {

plugin.getUpdaterService().checkForUpdate().then(update -> {
if (update == null) {
sender.sendMessage(Message.NO_UPDATE_AVAILABLE.translate(plugin));
return;
}
boolean download = args.length > 0 && args[0].equalsIgnoreCase("download");
boolean download = plugin.config().downloadUpdatesAutomatically.get()
|| args.length > 0 && args[0].equalsIgnoreCase("download");
if (sender instanceof Player) {
new UpdateGUI(plugin, (Player) sender, update).open();
if (plugin.config().downloadUpdatesAutomatically.get() || download)
if (download)
update.download();
} else {
sender.sendMessage(Message.UPDATE_AVAILABLE.with(Placeholder.VERSION).as(update.getVersion()).translate(plugin));
if (plugin.config().downloadUpdatesAutomatically.get() || download) {
if (download) {
sender.sendMessage(Message.UPDATE_DOWNLOADING.translate(plugin));
update.download()
.onValidating(() -> sender.sendMessage(Message.UPDATE_VALIDATING.translate(plugin)))
.onDownloadComplete(() -> sender.sendMessage(Message.UPDATE_DOWNLOAD_COMPLETE.translate(plugin)))
.catchError(error -> sender.sendMessage(Message.UPDATE_DOWNLOAD_FAILED.translate(plugin)));
}
}
});
}).catchError(error -> sender.sendMessage(Message.UPDATE_CHECK_ERROR.translate(plugin)));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ public NotifyPlayerOnJoinListener(BankingPlugin plugin) {
public void onPlayerJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();

Update update = plugin.getUpdate();
Update update = plugin.getUpdaterService().getUpdateIfAvailable();
if (update != null && !update.isCompleted() && Permissions.UPDATE.ownedBy(player))
player.sendMessage(Message.UPDATE_AVAILABLE
.with(Placeholder.VERSION).as(plugin.getUpdate().getVersion())
.with(Placeholder.VERSION).as(update.getVersion())
.translate(plugin));

Instant lastSeenTime = plugin.getLastSeenService().getLastSeenTime(player);
Expand Down
102 changes: 102 additions & 0 deletions src/main/java/com/monst/bankingplugin/util/UpdaterService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package com.monst.bankingplugin.util;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.monst.bankingplugin.BankingPlugin;

import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

public class UpdaterService {

private final BankingPlugin plugin;
private Update update;

public UpdaterService(BankingPlugin plugin) {
this.plugin = plugin;
}

/**
* Checks if an update is needed.
*/
public Promise<Update> checkForUpdate() {
plugin.debug("Checking for updates...");
return Promise.async(plugin, () -> {
JsonElement response;
URL url = new URL("https://api.github.com/repos/FreshLlamanade/BankingPlugin/releases");
URLConnection con = url.openConnection();
con.setConnectTimeout(5000);
con.setRequestProperty("User-Agent", "BankingPlugin");
con.setDoOutput(true);

response = new JsonParser().parse(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));

// Releases are sorted by date, newest first
JsonArray releases = response.getAsJsonArray();

if (releases.size() == 0)
// No versions available
return update;

String versionNumber = null;
JsonObject jar = null;
for (int i = releases.size() - 1; i >= 0; i--) {
JsonObject version = releases.get(i).getAsJsonObject();
versionNumber = version.get("name").getAsString();
plugin.debug("Checking version " + versionNumber);

if (versionNumber.compareTo(plugin.getDescription().getVersion()) <= 0) {
// This version is no newer than current version
// No need to check further
return update;
}

if (plugin.config().ignoreUpdatesContaining.ignore(versionNumber)) { // This version is ignored
plugin.debug("Skipping version " + versionNumber + " because it contains an ignored tag.");
continue;
}

for (JsonElement asset : version.get("assets").getAsJsonArray()) {
if (((JsonObject) asset).get("name").getAsString().endsWith(".jar")) {
// Found the latest non-ignored jar available, and it is newer than the current version
jar = (JsonObject) asset;
break;
}
}
}

if (jar == null)
// No suitable update found
return update;

plugin.debug("Found latest version: " + versionNumber);

// An update already exists newer or equal to this one
if (update != null && update.getVersion().compareTo(versionNumber) > 0)
return update;

if (update != null)
update.setOutdated();

// Create a new update package
plugin.debug("Creating new update package.");
URL fileURL;
fileURL = new URL(jar.get("browser_download_url").getAsString());
String checksum = Optional.ofNullable(jar.get("md5")).map(JsonElement::getAsString).orElse(null);
int downloadSize = jar.get("size").getAsInt();

update = new Update(plugin, versionNumber, fileURL, checksum, downloadSize);
return update;
});
}

public Update getUpdateIfAvailable() {
return update;
}

}

0 comments on commit 9dfb2bf

Please sign in to comment.