Inceptum/launcher/src/main/java/io/gitlab/jfronny/inceptum/launcher/model/inceptum/ModMeta.java

94 lines
3.4 KiB
Java

package io.gitlab.jfronny.inceptum.launcher.model.inceptum;
import io.gitlab.jfronny.commons.HashUtils;
import io.gitlab.jfronny.inceptum.common.Utils;
import io.gitlab.jfronny.inceptum.launcher.model.curseforge.response.FingerprintMatchesResponse;
import io.gitlab.jfronny.inceptum.launcher.api.CurseforgeApi;
import io.gitlab.jfronny.inceptum.launcher.api.ModrinthApi;
import io.gitlab.jfronny.inceptum.launcher.system.source.*;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
public class ModMeta {
public Map<ModSource, Optional<ModSource>> sources; //key: source, value: update
public String sha1;
public Long murmur2;
public List<String> dependents; // by file name
public List<String> dependencies; // by file name
public boolean explicit = true;
public boolean initialize(String gameVersion) {
boolean modrinth = false;
boolean curseforge = false;
for (ModSource source : sources.keySet().toArray(ModSource[]::new)) {
if (source instanceof ModrinthModSource) modrinth = true;
if (source instanceof CurseforgeModSource) curseforge = true;
addSource(source, gameVersion);
}
boolean changed = false;
if (!modrinth) {
try {
addSource(new ModrinthModSource(ModrinthApi.getVersionByHash(sha1).id), gameVersion);
changed = true;
} catch (IOException e) {
// not found
}
}
if (!curseforge) {
try {
FingerprintMatchesResponse.Result cf = CurseforgeApi.checkFingerprint(murmur2);
if (!cf.exactMatches.isEmpty()) {
FingerprintMatchesResponse.Result.Match f = cf.exactMatches.get(0);
addSource(new CurseforgeModSource(f.id, f.file.id), gameVersion);
changed = true;
}
} catch (IOException | URISyntaxException e) {
// not found
}
}
return changed;
}
public static ModMeta of(Path mod) {
ModMeta res = new ModMeta();
res.sources = new LinkedHashMap<>();
if (!Files.isDirectory(mod)) {
try {
byte[] data = Files.readAllBytes(mod);
res.sha1 = HashUtils.sha1(data);
res.murmur2 = HashUtils.murmur2(data);
} catch (IOException e) {
Utils.LOGGER.error("Could not read file hash", e);
}
}
res.dependents = new ArrayList<>();
res.dependencies = new ArrayList<>();
return res;
}
public static ModMeta of(String sha1, Long murmur2, @Nullable ModSource knownSource, String gameVersion) {
ModMeta res = new ModMeta();
res.sources = new LinkedHashMap<>();
res.sha1 = sha1;
res.murmur2 = murmur2;
res.dependents = new ArrayList<>();
res.dependencies = new ArrayList<>();
if (knownSource != null) res.addSource(knownSource, gameVersion);
res.initialize(gameVersion);
return res;
}
public void addSource(ModSource source, String gameVersion) {
try {
sources.put(source, source.getUpdate(gameVersion));
} catch (IOException e) {
Utils.LOGGER.error("Could not check " + source.getName() + " for updates", e);
}
}
}