| 1 | package me.fridtjof.minecarttrains.utils; |
| 2 | |
| 3 | import com.google.gson.JsonArray; |
| 4 | import com.google.gson.JsonParser; |
| 5 | import org.bukkit.plugin.java.JavaPlugin; |
| 6 | |
| 7 | import java.net.URI; |
| 8 | import java.net.http.HttpClient; |
| 9 | import java.net.http.HttpRequest; |
| 10 | import java.net.http.HttpResponse; |
| 11 | import java.time.Duration; |
| 12 | |
| 13 | public final class ModrinthUpdateChecker |
| 14 | { |
| 15 | |
| 16 | public ModrinthUpdateChecker(JavaPlugin plugin, String projectId) |
| 17 | { |
| 18 | String currentVersion = plugin.getPluginMeta().getVersion(); |
| 19 | |
| 20 | plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> |
| 21 | { |
| 22 | try |
| 23 | { |
| 24 | HttpClient client = HttpClient.newBuilder() |
| 25 | .connectTimeout(Duration.ofSeconds(5)) |
| 26 | .build(); |
| 27 | HttpRequest request = HttpRequest.newBuilder() |
| 28 | .uri(URI.create("https://api.modrinth.com/v2/project/" + projectId + "/version")) |
| 29 | .header("User-Agent", "MinecartTrains/" + currentVersion) |
| 30 | .timeout(Duration.ofSeconds(8)) |
| 31 | .GET() |
| 32 | .build(); |
| 33 | |
| 34 | HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); |
| 35 | if (response.statusCode() != 200) |
| 36 | { |
| 37 | return; |
| 38 | } |
| 39 | |
| 40 | JsonArray versions = JsonParser.parseString(response.body()).getAsJsonArray(); |
| 41 | if (versions.isEmpty()) |
| 42 | { |
| 43 | return; |
| 44 | } |
| 45 | |
| 46 | String latest = versions.get(0).getAsJsonObject().get("version_number").getAsString(); |
| 47 | if (!latest.equalsIgnoreCase(currentVersion)) |
| 48 | { |
| 49 | plugin.getLogger().info("A newer MinecartTrains version is available on Modrinth: " + latest |
| 50 | + " (current: " + currentVersion + ")"); |
| 51 | } |
| 52 | } |
| 53 | catch (Exception exception) |
| 54 | { |
| 55 | plugin.getLogger().fine("Could not check Modrinth for updates: " + exception.getMessage()); |
| 56 | } |
| 57 | }); |
| 58 | } |
| 59 | } |