package io.gitlab.jfronny.inceptum.launcher.api; import io.gitlab.jfronny.gson.compile.util.GList; import io.gitlab.jfronny.gson.stream.JsonReader; import io.gitlab.jfronny.inceptum.common.Net; import io.gitlab.jfronny.inceptum.launcher.model.modrinth.*; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.StringReader; import java.util.*; public class ModrinthApi { private static final String API_HOST = "https://api.modrinth.com/"; private static final int ITEMS_PER_PAGE = 20; //TODO search by categories: facets:[["versions:$ver","versions:$ver"],["categories:$cat","categories:$cat"]] //TODO filter server/client-only mods public static ModrinthSearchResult search(String query, int page, String version, ModrinthProjectType type) throws IOException { return Net.downloadObject(Net.buildUrl(API_HOST, "v2/search", Map.of( "query", query, "facets", "[[\"versions:" + version + "\"],[\"categories:fabric\"],[\"project_type:" + type + "\"]]", "index", "relevance", "offset", Integer.toString(page * ITEMS_PER_PAGE), "limit", Integer.toString(ITEMS_PER_PAGE) )), GC_ModrinthSearchResult::read); } public static ModrinthProject getMod(String id) throws IOException { return Net.downloadObject(API_HOST + "v2/project/" + id, GC_ModrinthProject::read); } public static List getVersions(String mod) throws IOException { List versions = Net.downloadObject(API_HOST + "v2/project/" + mod + "/version", s -> { try (JsonReader r = new JsonReader(new StringReader(s))) { return GList.read(r, GC_ModrinthVersion::read); } }); versions.sort(Comparator.comparing(ModrinthVersion::date_published)); return versions; } public static ModrinthVersion getVersion(String id) throws IOException { return Net.downloadObject(API_HOST + "v2/version/" + id, GC_ModrinthVersion::read); } public static ModrinthLatest getLatestVersions(String mod, String gameVersion) throws IOException { ModrinthVersion stable = null; ModrinthVersion beta = null; ModrinthVersion latest = null; for (ModrinthVersion version : ModrinthApi.getVersions(mod)) { if (version.game_versions().contains(gameVersion) && version.loaders().contains("fabric")) { latest = version; if (version.version_type() == ModrinthVersion.VersionType.beta || version.version_type() == ModrinthVersion.VersionType.release) beta = version; if (version.version_type() == ModrinthVersion.VersionType.release) stable = version; } } return new ModrinthLatest(stable, beta, latest); } public static ModrinthVersion getVersionByHash(String sha1) throws IOException { return Net.downloadObject(API_HOST + "v2/version_file/" + sha1 + "?algorithm=sha1", GC_ModrinthVersion::read); } }