Skip to content

Commit

Permalink
Migrate update checker to Java 11 HTTP client
Browse files Browse the repository at this point in the history
  • Loading branch information
Gaming32 committed Jul 3, 2024
1 parent 10605a5 commit 68fd215
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 56 deletions.
48 changes: 30 additions & 18 deletions src/main/java/io/github/gaming32/worldhost/WorldHost.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@
import net.minecraft.server.players.GameProfileCache;
import org.apache.commons.io.function.IOFunction;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.EnglishReasonPhraseCatalog;
import org.jetbrains.annotations.Nullable;
import org.quiltmc.parsers.json.JsonReader;
import org.quiltmc.parsers.json.JsonWriter;
Expand All @@ -61,6 +60,9 @@
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
Expand Down Expand Up @@ -200,6 +202,11 @@ public class WorldHost
//$$ false;
//#endif

public static final HttpClient HTTP_CLIENT = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.executor(Util.ioPool())
.build();

private static boolean hasScannedForUpnp;
public static Gateway upnpGateway;

Expand Down Expand Up @@ -804,12 +811,11 @@ public static int getMMCLines(boolean isPause) {
return 0;
}

public static <T> T httpGet(
CloseableHttpClient client,
public static <T> CompletableFuture<T> httpGet(
String baseUri,
Consumer<URIBuilder> buildAction,
IOFunction<InputStream, T> handler
) throws IOException {
) {
final URI uri;
try {
final URIBuilder uriBuilder = new URIBuilder(baseUri);
Expand All @@ -818,19 +824,25 @@ public static <T> T httpGet(
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
try (var response = client.execute(new HttpGet(uri))) {
final var status = response.getStatusLine();
if (status.getStatusCode() != 200) {
throw new IOException("Failed to GET " + uri + ": " + status.getStatusCode() + " " + status.getReasonPhrase());
}
final var entity = response.getEntity();
if (entity == null) {
throw new IOException("GET " + uri + " returned no body.");
}
try (InputStream is = response.getEntity().getContent()) {
return handler.apply(is);
}
}
final HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
.header("User-Agent", "World Host/" + getModVersion(MOD_ID))
.GET()
.build();
return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream())
.thenComposeAsync(response -> {
if (response.statusCode() != 200) {
final String reason = EnglishReasonPhraseCatalog.INSTANCE.getReason(response.statusCode(), null);
return CompletableFuture.failedFuture(new IOException(
"Failed to GET " + response.request().uri() + ": " + response.statusCode() + " " + reason
));
}
try {
return CompletableFuture.completedFuture(handler.apply(response.body()));
} catch (Throwable t) {
return CompletableFuture.failedFuture(t);
}
}, Util.ioPool());
}

private static Path getGameDir() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
package io.github.gaming32.worldhost;

import net.minecraft.Util;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.quiltmc.parsers.json.JsonReader;
import org.semver4j.Semver;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
Expand All @@ -17,43 +12,38 @@ public class WorldHostUpdateChecker {
public static final String MODRINTH_ID = "world-host";

public static CompletableFuture<Optional<String>> checkForUpdates() {
return CompletableFuture.<Optional<String>>supplyAsync(() -> {
try (CloseableHttpClient client = HttpClients.createMinimal()) {
final String latestVersion = WorldHost.httpGet(
client, "https://api.modrinth.com/v2/project/" + MODRINTH_ID + "/version",
builder -> builder
.addParameter("game_versions", "[\"" + WorldHost.getModVersion("minecraft") + "\"]")
.addParameter("loaders", "[\"" + WorldHost.MOD_LOADER + "\"]"),
input -> {
try (JsonReader reader = JsonReader.json(new InputStreamReader(input, StandardCharsets.UTF_8))) {
reader.beginArray();
if (!reader.hasNext()) {
return null;
}
reader.beginObject();
while (reader.hasNext()) {
final String key = reader.nextName();
if (!key.equals("version_number")) {
reader.skipValue();
continue;
}
return reader.nextString();
}
return null;
return WorldHost.httpGet(
"https://api.modrinth.com/v2/project/" + MODRINTH_ID + "/version",
builder -> builder
.addParameter("game_versions", "[\"" + WorldHost.getModVersion("minecraft") + "\"]")
.addParameter("loaders", "[\"" + WorldHost.MOD_LOADER + "\"]"),
input -> {
try (JsonReader reader = JsonReader.json(new InputStreamReader(input, StandardCharsets.UTF_8))) {
reader.beginArray();
if (!reader.hasNext()) {
return null;
}
reader.beginObject();
while (reader.hasNext()) {
final String key = reader.nextName();
if (!key.equals("version_number")) {
reader.skipValue();
continue;
}
return reader.nextString();
}
);
if (latestVersion == null) {
return Optional.empty();
}
if (new Semver(WorldHost.getModVersion(WorldHost.MOD_ID)).compareTo(new Semver(latestVersion)) >= 0) {
return Optional.empty();
return null;
}
return Optional.of(latestVersion);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}, Util.ioPool()).exceptionally(t -> {
).<Optional<String>>thenApply(latestVersion -> {
if (latestVersion == null) {
return Optional.empty();
}
if (new Semver(WorldHost.getModVersion(WorldHost.MOD_ID)).compareTo(new Semver(latestVersion)) >= 0) {
return Optional.empty();
}
return Optional.of(latestVersion);
}).exceptionally(t -> {
WorldHost.LOGGER.error("Failed to check for updates", t);
return Optional.empty();
});
Expand Down

0 comments on commit 68fd215

Please sign in to comment.