|
| 1 | +package fr.sandro642.github.update; |
| 2 | + |
| 3 | +import com.google.gson.Gson; |
| 4 | +import com.google.gson.JsonArray; |
| 5 | +import com.google.gson.JsonObject; |
| 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 | + |
| 12 | +/** |
| 13 | + * RetrieveLastVersion is a class that retrieves the latest version of the software. |
| 14 | + * It contains a field to store the latest version and can be extended to include methods for fetching |
| 15 | + */ |
| 16 | + |
| 17 | +public class RetrieveLastVersion { |
| 18 | + |
| 19 | + /** |
| 20 | + * The latest version of the software. |
| 21 | + * Default is set to the current version defined in the Version class. |
| 22 | + */ |
| 23 | + private String latestVersion = Version.VERSION; |
| 24 | + |
| 25 | + /** |
| 26 | + * Fetches the latest version from the GitHub API. |
| 27 | + * It sends a GET request to the tags endpoint of the ConnectLib repository |
| 28 | + * and retrieves the name of the first tag, which represents the latest version. |
| 29 | + * @return |
| 30 | + */ |
| 31 | + public String fetchVersion() { |
| 32 | + try { |
| 33 | + HttpClient client = HttpClient.newHttpClient(); |
| 34 | + HttpRequest request = HttpRequest.newBuilder() |
| 35 | + .uri(URI.create("https://api.github.com/repos/Sandro642/ConnectLib/tags")) |
| 36 | + .build(); |
| 37 | + |
| 38 | + HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); |
| 39 | + |
| 40 | + Gson gson = new Gson(); |
| 41 | + JsonArray data = gson.fromJson(response.body(), JsonArray.class); |
| 42 | + |
| 43 | + if (data != null && data.size() > 0) { |
| 44 | + JsonObject firstTag = data.get(0).getAsJsonObject(); |
| 45 | + return firstTag.get("name").getAsString(); |
| 46 | + } else { |
| 47 | + return "No tags found"; |
| 48 | + } |
| 49 | + |
| 50 | + } catch (Exception e) { |
| 51 | + return "Error"; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Compares the fetched version with the current version. |
| 57 | + * If they are different, it prints a message indicating that a new version is available. |
| 58 | + */ |
| 59 | + public void isLatestVersion() { |
| 60 | + String fetchedVersion = fetchVersion(); |
| 61 | + if (fetchedVersion.equals("Error") || fetchedVersion.equals("No tags found")) { |
| 62 | + System.out.println("Could not fetch the latest version."); |
| 63 | + } else if (!fetchedVersion.equals(Version.VERSION)) { |
| 64 | + System.out.println("A new version is available: " + fetchedVersion + ". You can download it from https://connectlib.xyz/#downloads"); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | +} |
0 commit comments