Respackopts/src/main/java/io/gitlab/jfronny/respackopts/filters/util/FileRpoSearchProvider.java

54 lines
2.2 KiB
Java
Raw Normal View History

2021-09-15 17:13:14 +02:00
package io.gitlab.jfronny.respackopts.filters.util;
import io.gitlab.jfronny.libjf.ResourcePath;
import io.gitlab.jfronny.respackopts.Respackopts;
2022-12-08 19:00:41 +01:00
import io.gitlab.jfronny.respackopts.gson.AttachmentHolder;
2021-11-14 15:37:01 +01:00
import io.gitlab.jfronny.respackopts.model.FileRpo;
2022-12-08 19:00:41 +01:00
import io.gitlab.jfronny.respackopts.model.cache.CachedPackState;
import io.gitlab.jfronny.respackopts.util.MetaCache;
2022-12-08 19:00:41 +01:00
import net.minecraft.resource.InputSupplier;
import net.minecraft.resource.ResourcePack;
2021-09-15 17:13:14 +02:00
2022-12-08 19:00:41 +01:00
import java.io.*;
import java.util.Map;
2021-09-15 17:13:14 +02:00
public class FileRpoSearchProvider {
public static boolean isRpo(String fileName) {
return fileName.endsWith(Respackopts.FILE_EXTENSION);
2021-09-15 17:13:14 +02:00
}
2022-12-08 19:00:41 +01:00
public static <T> T modifyWithRpo(String fileName, ResourcePack pack, Action<T> action, T defaultValue) {
if (isRpo(fileName)) return defaultValue;
CachedPackState state = MetaCache.getState(MetaCache.getKeyByPack(pack));
2022-12-08 19:00:41 +01:00
Map<String, FileRpo> rpoCache = state.cachedFileRPOs();
String rpoPathS = fileName + Respackopts.FILE_EXTENSION;
if (rpoCache.containsKey(rpoPathS)) return action.run(rpoCache.get(rpoPathS));
2022-01-22 22:55:51 +01:00
ResourcePath rpoPath = null;
2022-12-08 19:00:41 +01:00
InputSupplier<InputStream> is;
2022-01-22 22:55:51 +01:00
if (fileName.contains("/")) {
try {
2022-12-08 19:00:41 +01:00
rpoPath = new ResourcePath(rpoPathS);
is = pack.open(rpoPath.getType(), rpoPath.getId());
2022-01-22 22:55:51 +01:00
} catch (Throwable e) {
Respackopts.LOGGER.error("Could not check file filter status", e);
2021-09-15 17:13:14 +02:00
return defaultValue;
2022-01-22 22:55:51 +01:00
}
2022-12-08 19:00:41 +01:00
} else is = pack.openRoot(rpoPathS);
if (is == null) return defaultValue;
try (Reader w = new InputStreamReader(is.get())) {
FileRpo frp = AttachmentHolder.deserialize(state.metadata().version, w, FileRpo.class);
2022-12-08 19:00:41 +01:00
frp.path = rpoPathS;
rpoCache.put(rpoPathS, frp);
return action.run(frp);
2021-09-15 17:13:14 +02:00
}
catch (Exception e) {
2022-12-08 19:00:41 +01:00
Respackopts.LOGGER.error("Could not get replacement for " + (rpoPath == null ? fileName : rpoPath.getName()) + " in " + pack.getName(), e);
2021-09-15 17:13:14 +02:00
return defaultValue;
}
}
2022-12-08 19:00:41 +01:00
public interface Action<T> {
T run(FileRpo rpo);
2021-09-15 17:13:14 +02:00
}
}