Skip to content

Commit

Permalink
enable modrinth update checking
Browse files Browse the repository at this point in the history
  • Loading branch information
moehreag committed Dec 23, 2023
1 parent 7f71ad7 commit a659a73
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 40 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ logs

Thumbs.db
*.psd
.profileconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,7 @@ public void renderOutOfBounds(int index, int mouseX, int mouseY) {
public void render(int index, int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered) {
if (updateTextEntry) {
UpdateAvailableBadge.renderBadge(x + indent, y);
x+=11;
}
textRenderer.drawWithShadow(text, x + indent, y, 0xAAAAAA);
}
Expand Down
84 changes: 44 additions & 40 deletions src/main/java/com/terraformersmc/modmenu/util/ModrinthUtil.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
package com.terraformersmc.modmenu.util;

import java.io.IOException;
import java.net.URI;
import java.util.*;
import java.util.concurrent.CompletableFuture;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.annotations.SerializedName;
Expand All @@ -8,28 +14,21 @@
import com.terraformersmc.modmenu.util.mod.Mod;
import com.terraformersmc.modmenu.util.mod.ModrinthData;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.SharedConstants;
import net.minecraft.client.Minecraft;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Utils;

import java.io.IOException;
import java.net.URI;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.FutureTask;

import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ModrinthUtil {
public static final Logger LOGGER = LogManager.getLogger("Mod Menu/Update Checker");

private static final HttpClient client = HttpClientBuilder.create().build();
private static boolean apiV2Deprecated = false;

private static boolean allowsUpdateChecks(Mod mod) {
return mod.allowsUpdateChecks();
Expand All @@ -40,7 +39,7 @@ public static void checkForUpdates() {
return;
}

/* CompletableFuture.runAsync(() -> {
CompletableFuture.runAsync(() -> {
LOGGER.info("Checking mod updates...");

Map<String, Set<Mod>> modHashes = new HashMap<>();
Expand All @@ -60,49 +59,54 @@ public static void checkForUpdates() {
}
});

String environment = ModMenu.devEnvironment ? "/development": "";
String environment = ModMenu.devEnvironment ? "/development" : "";
String primaryLoader = ModMenu.runningQuilt ? "quilt" : "fabric";
List<String> loaders = ModMenu.runningQuilt ? Arrays.asList("fabric", "quilt") : Arrays.asList("fabric");
List<String> loaders = ModMenu.runningQuilt ? Arrays.asList("fabric", "quilt") : Collections.singletonList("fabric");

String mcVer = SharedConstants.getGameVersion().getName();
String mcVer = FabricLoader.getInstance().getModContainer("minecraft").get()
.getMetadata().getVersion().getFriendlyString();
String[] splitVersion = FabricLoader.getInstance().getModContainer(ModMenu.MOD_ID)
.get().getMetadata().getVersion().getFriendlyString().split("\\+", 1); // Strip build metadata for privacy
.get().getMetadata().getVersion().getFriendlyString().split("\\+", 1); // Strip build metadata for privacy
final String modMenuVersion = splitVersion.length > 1 ? splitVersion[1] : splitVersion[0];
final String userAgent = "%s/%s (%s/%s%s)".formatted(ModMenu.GITHUB_REF, modMenuVersion, mcVer, primaryLoader, environment);
final String userAgent = String.format("%s/%s (%s/%s%s)", ModMenu.GITHUB_REF, modMenuVersion, mcVer, primaryLoader, environment);
String body = ModMenu.GSON_MINIFIED.toJson(new LatestVersionsFromHashesBody(modHashes.keySet(), loaders, mcVer));
LOGGER.debug("User agent: " + userAgent);
LOGGER.debug("Body: " + body);
var latestVersionsRequest = HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString(body))
.header("User-Agent", userAgent)
.header("Content-Type", "application/json")
.uri(URI.create("https://api.modrinth.com/v2/version_files/update"))
.build();

try {
var latestVersionsResponse = client.send(latestVersionsRequest, HttpResponse.BodyHandlers.ofString());
HttpUriRequest latestVersionsRequest = RequestBuilder.post()
.setEntity(new StringEntity(body))
.addHeader("User-Agent", userAgent)
.addHeader("Content-Type", "application/json")
.setUri(URI.create("https://api.modrinth.com/v2/version_files/update"))
.build();

HttpResponse latestVersionsResponse = client.execute(latestVersionsRequest);

int status = latestVersionsResponse.statusCode();
int status = latestVersionsResponse.getStatusLine().getStatusCode();
LOGGER.debug("Status: " + status);
if (status == 410) {
apiV2Deprecated = true;
LOGGER.warn("Modrinth API v2 is deprecated, unable to check for mod updates.");
} else if (status == 200) {
JsonObject responseObject = JsonParser.parseString(latestVersionsResponse.body()).getAsJsonObject();
JsonObject responseObject = new JsonParser().parse(EntityUtils.toString(latestVersionsResponse.getEntity())).getAsJsonObject();
LOGGER.debug(String.valueOf(responseObject));
responseObject.asMap().forEach((lookupHash, versionJson) -> {
var versionObj = versionJson.getAsJsonObject();
var projectId = versionObj.get("project_id").getAsString();
var versionNumber = versionObj.get("version_number").getAsString();
var versionId = versionObj.get("id").getAsString();
var primaryFile = versionObj.get("files").getAsJsonArray().asList().stream()
.filter(file -> file.getAsJsonObject().get("primary").getAsBoolean()).findFirst();
if (primaryFile.isEmpty()) {
responseObject.entrySet().forEach(entry -> {
String lookupHash = entry.getKey();
JsonObject versionObj = entry.getValue().getAsJsonObject();
String projectId = versionObj.get("project_id").getAsString();
String versionNumber = versionObj.get("version_number").getAsString();
String versionId = versionObj.get("id").getAsString();
List<JsonElement> files = new ArrayList<>();
versionObj.get("files").getAsJsonArray().forEach(files::add);
Optional<JsonElement> primaryFile = files.stream()
.filter(file -> file.getAsJsonObject().get("primary").getAsBoolean()).findFirst();

if (!primaryFile.isPresent()) {
return;
}

var versionHash = primaryFile.get().getAsJsonObject().get("hashes").getAsJsonObject().get("sha512").getAsString();
String versionHash = primaryFile.get().getAsJsonObject().get("hashes").getAsJsonObject().get("sha512").getAsString();

if (!Objects.equals(versionHash, lookupHash)) {
// hashes different, there's an update.
Expand All @@ -113,10 +117,10 @@ public static void checkForUpdates() {
}
});
}
} catch (IOException | InterruptedException e) {
} catch (IOException e) {
LOGGER.error("Error checking for updates: ", e);
}
});*/
});
}

public static class LatestVersionsFromHashesBody {
Expand Down

0 comments on commit a659a73

Please sign in to comment.