|
| 1 | +package net.andrecarbajal.mine_control_cli.util.api; |
| 2 | + |
| 3 | +import lombok.RequiredArgsConstructor; |
| 4 | +import net.andrecarbajal.mine_control_cli.config.ApplicationProperties; |
| 5 | +import org.json.JSONArray; |
| 6 | + |
| 7 | +import java.util.Optional; |
| 8 | + |
| 9 | +@RequiredArgsConstructor |
| 10 | +public class UpdateChecker { |
| 11 | + private final ApplicationProperties applicationProperties; |
| 12 | + |
| 13 | + private static final String GITHUB_API_URL = "https://api.github.com/repos/MineControlCli/mine-control-cli/tags"; |
| 14 | + private static final String DOWNLOAD_URL = "https://github.com/MineControlCli/mine-control-cli/releases"; |
| 15 | + |
| 16 | + public Optional<UpdateInfo> checkForUpdates() { |
| 17 | + JSONArray jsonArray = ApiClient.getJsonArray(GITHUB_API_URL); |
| 18 | + String latestVersion = jsonArray.getJSONObject(0).getString("name"); |
| 19 | + return latestVersion != null && isNewerVersion(latestVersion) ? Optional.of(new UpdateInfo(latestVersion, DOWNLOAD_URL)) : Optional.empty(); |
| 20 | + } |
| 21 | + |
| 22 | + private boolean isNewerVersion(String latestVersion) { |
| 23 | + String normalizedLatestVersion = latestVersion.startsWith("v") ? latestVersion.substring(1) : latestVersion; |
| 24 | + |
| 25 | + String[] latestParts = normalizedLatestVersion.split("\\."); |
| 26 | + String[] currentParts = applicationProperties.getVersion().split("\\."); |
| 27 | + |
| 28 | + for (int i = 0; i < Math.min(latestParts.length, currentParts.length); i++) { |
| 29 | + int latestPart = Integer.parseInt(latestParts[i]); |
| 30 | + int currentPart = Integer.parseInt(currentParts[i]); |
| 31 | + |
| 32 | + if (latestPart > currentPart) { |
| 33 | + return true; |
| 34 | + } else if (latestPart < currentPart) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return latestParts.length > currentParts.length; |
| 40 | + } |
| 41 | + |
| 42 | + public record UpdateInfo(String version, String downloadUrl) { |
| 43 | + } |
| 44 | +} |
0 commit comments