|
| 1 | +package tk.fungy.wsformc; |
| 2 | + |
| 3 | +import com.google.gson.JsonArray; |
| 4 | +import com.google.gson.JsonObject; |
| 5 | +import com.google.gson.JsonParser; |
| 6 | +import org.bukkit.Bukkit; |
| 7 | +import org.bukkit.ChatColor; |
| 8 | +import org.bukkit.Color; |
| 9 | +import org.bukkit.entity.Player; |
| 10 | +import org.bukkit.event.EventHandler; |
| 11 | +import org.bukkit.event.Listener; |
| 12 | +import org.bukkit.event.player.PlayerJoinEvent; |
| 13 | + |
| 14 | +import java.io.BufferedReader; |
| 15 | +import java.io.InputStreamReader; |
| 16 | +import java.net.URL; |
| 17 | + |
| 18 | +public class Updater implements Listener { |
| 19 | + private static String currentVersion; |
| 20 | + private static String latestVersion; |
| 21 | + public static void startUpdater() { |
| 22 | + currentVersion = Main.getInstance().getDescription().getVersion(); |
| 23 | + Bukkit.getScheduler().runTaskTimerAsynchronously(Main.instance, new Runnable() { |
| 24 | + @Override |
| 25 | + public void run() { |
| 26 | + checkForUpdates(); |
| 27 | + } |
| 28 | + }, 0L, 20 * 60 * 60 * 24); // Schedule the task to run every 24 hours |
| 29 | + } |
| 30 | + private void checkForUpdates() { |
| 31 | + try { |
| 32 | + URL url = new URL("https://api.github.com/repos/CodeITForFun/WSForMC/releases"); // Replace with the URL to your GitHub releases |
| 33 | + BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); |
| 34 | + StringBuilder result = new StringBuilder(); |
| 35 | + String line; |
| 36 | + while ((line = reader.readLine()) != null) { |
| 37 | + result.append(line); |
| 38 | + } |
| 39 | + |
| 40 | + JsonArray releases = new JsonParser().parse(result.toString()).getAsJsonArray(); |
| 41 | + JsonObject latestRelease = releases.get(0).getAsJsonObject(); |
| 42 | + latestVersion = latestRelease.get("tag_name").getAsString().replace("v", ""); |
| 43 | + |
| 44 | + if (!currentVersion.equals(latestVersion)) { |
| 45 | + Bukkit.getLogger().info("A new update is available: " + latestVersion); |
| 46 | + } |
| 47 | + } catch (Exception e) { |
| 48 | + Bukkit.getLogger().warning("Failed to check for updates: " + e.getMessage()); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + @EventHandler |
| 53 | + public void onPlayerJoin(PlayerJoinEvent event) { |
| 54 | + Player player = event.getPlayer(); |
| 55 | + if (player.hasPermission("ws.update") || player.hasPermission("ws.*") && !currentVersion.equals(latestVersion)) { |
| 56 | + player.sendMessage(ChatColor.AQUA + "A new update for your plugin is available: " + latestVersion); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments