Updater using plugin.yml

This commit is contained in:
rockyhawk64 2025-04-22 19:02:21 +10:00
parent f24a8057c7
commit 189539241f

View File

@ -1,6 +1,5 @@
package me.rockyhawk.commandpanels.updater; package me.rockyhawk.commandpanels.updater;
import com.google.gson.Gson;
import me.rockyhawk.commandpanels.CommandPanels; import me.rockyhawk.commandpanels.CommandPanels;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@ -12,34 +11,30 @@ import org.bukkit.scheduler.BukkitRunnable;
import java.io.*; import java.io.*;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.*; import java.util.Objects;
import java.util.logging.Level; import java.util.logging.Level;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class Updater implements Listener { public class Updater implements Listener {
// if this is set to something, it will download that version on restart //if this is set to something, it will download that version on restart
// can be a version number, 'latest' or 'cancel' //can be a version number, 'latest' or 'cancel'
public String downloadVersionManually = null; public String downloadVersionManually = null;
public String cachedLatestVersion = "null"; public String cachedLatestVersion = "null";
CommandPanels plugin; CommandPanels plugin;
public Updater(CommandPanels pl) { public Updater(CommandPanels pl) {
this.plugin = pl; this.plugin = pl;
} }
// send update message when the player joins the game with the permission //send update message when the player joins the game with the permission
@EventHandler @EventHandler
public void joinGame(PlayerJoinEvent e) { public void joinGame(PlayerJoinEvent e){
if (e.getPlayer().hasPermission("commandpanel.update") && plugin.config.getBoolean("updater.update-checks")) { if(e.getPlayer().hasPermission("commandpanel.update") && plugin.config.getBoolean("updater.update-checks")){
if (githubNewUpdate(false)) { if(githubNewUpdate(false)){
new BukkitRunnable() { new BukkitRunnable() {
@Override @Override
public void run() { public void run() {
plugin.tex.sendMessage(e.getPlayer(), ChatColor.YELLOW + "A new update is available for download!"); plugin.tex.sendMessage(e.getPlayer(),ChatColor.YELLOW + "A new update is available for download!");
plugin.tex.sendString(e.getPlayer(), ChatColor.YELLOW plugin.tex.sendString(e.getPlayer(),ChatColor.YELLOW
+ "Current version " + "Current version "
+ ChatColor.RED + plugin.getDescription().getVersion() + ChatColor.YELLOW + ChatColor.RED + plugin.getDescription().getVersion() + ChatColor.YELLOW
+ " Latest version " + ChatColor.GREEN + cachedLatestVersion); + " Latest version " + ChatColor.GREEN + cachedLatestVersion);
@ -50,22 +45,22 @@ public class Updater implements Listener {
} }
} }
public boolean githubNewUpdate(boolean sendMessages) { public boolean githubNewUpdate(boolean sendMessages){
// refresh latest version //refresh latest version
getLatestVersion(sendMessages); getLatestVersion(sendMessages);
if (plugin.getDescription().getVersion().contains("-")) { if(plugin.getDescription().getVersion().contains("SNAPSHOT")){
if (sendMessages) { if(sendMessages) {
Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + ChatColor.GREEN + " Running a custom version."); Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + ChatColor.GREEN + " Running a custom version.");
} }
return false; return false;
} }
// if update is true there is a new update //if update is true there is a new update
boolean update = !cachedLatestVersion.equals(plugin.getDescription().getVersion()); boolean update = !cachedLatestVersion.equals(plugin.getDescription().getVersion());
if (update) { if(update){
if (sendMessages) { if(sendMessages) {
Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + ChatColor.GOLD + " ================================================"); Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + ChatColor.GOLD + " ================================================");
Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + ChatColor.AQUA + " An update for CommandPanels is available."); Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + ChatColor.AQUA + " An update for CommandPanels is available.");
Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + " Download CommandPanels " + ChatColor.GOLD + cachedLatestVersion + ChatColor.WHITE + " using the"); Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + " Download CommandPanels " + ChatColor.GOLD + cachedLatestVersion + ChatColor.WHITE + " using the");
@ -77,60 +72,39 @@ public class Updater implements Listener {
return false; return false;
} }
public String getLatestVersion(boolean sendMessages) { public String getLatestVersion(boolean sendMessages){
// Default to current version if the cached version is null //check for null
if (cachedLatestVersion.equals("null")) { if(cachedLatestVersion.equals("null")){
cachedLatestVersion = plugin.getDescription().getVersion(); cachedLatestVersion = plugin.getDescription().getVersion();
} }
new BukkitRunnable() { //using an array allows editing while still being final
public void run() { new BukkitRunnable(){
public void run(){
HttpURLConnection connection; HttpURLConnection connection;
try { try {
// Connect to the MC_Versions.json file connection = (HttpURLConnection) new URL("https://raw.githubusercontent.com/rockyhawk64/CommandPanels/latest/resource/plugin.yml").openConnection();
connection = (HttpURLConnection) new URL("https://raw.githubusercontent.com/rockyhawk64/CommandPanels/latest/MC_Versions.json").openConnection(); connection.setConnectTimeout(5000); // 5 seconds
connection.setConnectTimeout(5000); // 5 seconds timeout connection.setReadTimeout(5000); // 5 seconds
connection.setReadTimeout(5000); // 5 seconds read timeout
connection.connect(); connection.connect();
cachedLatestVersion = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine().split("\\s")[1];
// Read the response into a String
StringBuilder response = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// Parse the JSON response using Gson
Gson gson = new Gson();
JsonObject jsonResponse = gson.fromJson(response.toString(), JsonObject.class);
// Get the Minecraft version from the current server version
// Eg "1.21.5-25-def0532 (MC: 1.21.5)"
String mcVersion = Bukkit.getVersion().split("\\s")[2].replace(")","");
// Check if the Minecraft version exists in the JSON
if (jsonResponse.has(mcVersion)) {
JsonArray versions = jsonResponse.getAsJsonArray(mcVersion);
if (versions.size() > 0) { //Gson from older MC versions does not have isEmpty()
// Get the latest plugin version
cachedLatestVersion = versions.get(0).getAsString();
}
} else {
Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + ChatColor.RED + " No updates found for Minecraft version " + mcVersion);
}
connection.disconnect(); connection.disconnect();
} catch (IOException e) { } catch (IOException ignore) {
Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + ChatColor.RED + " Could not access GitHub to check for updates."); Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + ChatColor.RED + " Could not access github.");
} }
} }
}.runTaskAsynchronously(plugin); }.runTaskAsynchronously(plugin);
if(cachedLatestVersion.contains("-")){
if(sendMessages) {
Bukkit.getConsoleSender().sendMessage("[CommandPanels]" + ChatColor.RED + " Cannot check for update.");
}
}
return cachedLatestVersion; return cachedLatestVersion;
} }
// the pluginFileName can only be obtained from the main class //the pluginFileName can only be obtained from the main class
public void autoUpdatePlugin(String pluginFileName) { public void autoUpdatePlugin(String pluginFileName){
if (Objects.requireNonNull(plugin.config.getString("updater.update-checks")).equalsIgnoreCase("false")) { if (Objects.requireNonNull(plugin.config.getString("updater.update-checks")).equalsIgnoreCase("false")) {
return; return;
} }
@ -138,28 +112,28 @@ public class Updater implements Listener {
String latestVersion = cachedLatestVersion; String latestVersion = cachedLatestVersion;
String thisVersion = plugin.getDescription().getVersion(); String thisVersion = plugin.getDescription().getVersion();
// manual download, only if it was requested //manual download, only if it was requested
if (downloadVersionManually != null) { if(downloadVersionManually != null) {
if (downloadVersionManually.equals("latest")) { if (downloadVersionManually.equals("latest")) {
downloadFile(latestVersion, pluginFileName); downloadFile(latestVersion, pluginFileName);
} else { }else{
downloadFile(downloadVersionManually, pluginFileName); downloadFile(downloadVersionManually, pluginFileName);
} }
return; return;
} }
if (latestVersion.equals(thisVersion) || thisVersion.contains("-")) { if(latestVersion.equals(thisVersion) || thisVersion.contains("-")){
// no need to update or running custom version //no need to update or running custom version
return; return;
} }
if (Objects.requireNonNull(plugin.config.getString("updater.auto-update")).equalsIgnoreCase("false")) { if (Objects.requireNonNull(plugin.config.getString("updater.auto-update")).equalsIgnoreCase("false")) {
// return if auto-update is false //return if auto-update is false
return; return;
} }
if (thisVersion.split("\\.")[1].equals(latestVersion.split("\\.")[1]) && thisVersion.split("\\.")[0].equals(latestVersion.split("\\.")[0])) { if(thisVersion.split("\\.")[1].equals(latestVersion.split("\\.")[1]) && thisVersion.split("\\.")[0].equals(latestVersion.split("\\.")[0])){
// only update if the latest version is a minor update //only update if the latest version is a minor update
// the first and second number of the version is the same, updates: [major.major.minor.minor] //the first and second number of the version is the same, updates: [major.major.minor.minor]
downloadFile(latestVersion, pluginFileName); downloadFile(latestVersion,pluginFileName);
} }
} }
@ -179,12 +153,12 @@ public class Updater implements Listener {
int count; int count;
int lastpercent = 0; int lastpercent = 0;
while ((count = in.read(data, 0, 1024)) != -1) { while((count = in.read(data, 0, 1024)) != -1) {
downloaded += count; downloaded += count;
fout.write(data, 0, count); fout.write(data, 0, count);
int percent = (int) (downloaded * 100L / (long) fileLength); int percent = (int)(downloaded * 100L / (long)fileLength);
if (percent != lastpercent && percent % 10 == 0) { if (percent != lastpercent && percent % 10 == 0) {
// show if the percentage is different from the last percentage and then show the bytes downloaded so far //show if the percentage is different from the last percentage and then show the bytes downloaded so far
this.plugin.getLogger().info("Downloading update: " + percent + "% " + downloaded + " of " + fileLength + " bytes."); this.plugin.getLogger().info("Downloading update: " + percent + "% " + downloaded + " of " + fileLength + " bytes.");
lastpercent = percent; lastpercent = percent;
} }
@ -210,5 +184,6 @@ public class Updater implements Listener {
} }
} }
} }
} }