forked from AlexIIL/BetterLoadingScreen_1.7
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathRemoteCacheManager.java
More file actions
204 lines (163 loc) · 7.6 KB
/
RemoteCacheManager.java
File metadata and controls
204 lines (163 loc) · 7.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package alexiil.mods.load;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import net.minecraft.client.renderer.texture.AbstractTexture;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.config.Configuration;
import alexiil.mods.load.imgur.LateInitDynamicTexture;
public abstract class RemoteCacheManager<C extends AutoCloseable> {
private static final boolean OFFLINE_MODE = Boolean.getBoolean("bls.offlineMode");
private final String cacheDir;
private final String providerName;
private final Map<String, AbstractTexture> textureCache = new ConcurrentHashMap<>();
private volatile boolean cancelSetup;
protected RemoteCacheManager(String cacheDir, String providerName) {
this.cacheDir = cacheDir;
this.providerName = providerName;
}
public abstract void loadConfig(Configuration config);
protected abstract C createClient() throws Exception;
protected abstract List<ImageEntry> fetchRemoteImages(C client) throws Exception;
protected abstract byte[] downloadImage(C client, ImageEntry entry) throws Exception;
public AbstractTexture getCachedTexture(ResourceLocation location) {
if (!location.getResourceDomain().equals(cacheDir)) return null;
return textureCache.get(location.getResourcePath());
}
public void cleanUp() {
textureCache.values().forEach(AbstractTexture::deleteGlTexture);
textureCache.clear();
cancelSetup = true;
}
public void setup(Consumer<ResourceLocation> textureLocationConsumer) {
Path cacheFolder = Paths.get(cacheDir);
if (Files.notExists(cacheFolder)) {
try {
Files.createDirectory(cacheFolder);
} catch (IOException e) {
BetterLoadingScreen.log.error("Error while creating " + providerName + " cache directory", e);
return;
}
}
List<String> cachedImageIDs = getCachedImageIDs();
if (cachedImageIDs == null) return;
// Load any image that is already cached to get something rendering quickly
loadAnyImageFromDisk(cachedImageIDs, textureLocationConsumer);
CompletableFuture.runAsync(() -> {
try (C client = OFFLINE_MODE ? null : createClient()) {
Consumer<ImageEntry> imageHandler = entry -> {
String imageID = entry.cacheId;
synchronized (cachedImageIDs) {
cachedImageIDs.remove(imageID);
}
if (cancelSetup) return;
if (textureCache.containsKey(imageID)) return;
Path imageFile = getCachedImagePath(imageID);
try {
if (Files.exists(imageFile)) {
readAndCacheImageFromStream(
imageID,
new BufferedInputStream(Files.newInputStream(imageFile), 1024 * 1024),
false);
} else {
if (OFFLINE_MODE) return;
readAndCacheImageFromStream(
imageID,
new ByteArrayInputStream(downloadImage(client, entry)),
true);
}
} catch (Exception e) {
BetterLoadingScreen.log.error("Error while loading " + providerName + " image", e);
return;
}
synchronized (textureLocationConsumer) {
textureLocationConsumer.accept(new ResourceLocation(cacheDir, imageID));
}
};
if (OFFLINE_MODE) {
cachedImageIDs.stream().parallel().map(id -> new ImageEntry(id, id)).forEach(imageHandler);
} else {
fetchRemoteImages(client).stream().parallel().forEach(imageHandler);
}
} catch (Exception e) {
BetterLoadingScreen.log.error("Error while fetching " + providerName + " images", e);
}
}).thenRunAsync(() -> {
if (OFFLINE_MODE) return;
// Delete cached images that are no longer in the album
try {
for (String id : cachedImageIDs) {
Files.deleteIfExists(getCachedImagePath(id));
}
} catch (IOException e) {
BetterLoadingScreen.log.error("Error while deleting unused cached " + providerName + " images", e);
}
});
}
private void loadAnyImageFromDisk(List<String> cachedImageIDs, Consumer<ResourceLocation> textureLocationConsumer) {
if (cachedImageIDs.isEmpty()) return;
String imageID = cachedImageIDs.get(ThreadLocalRandom.current().nextInt(cachedImageIDs.size()));
try {
readAndCacheImageFromDisk(imageID);
} catch (IOException e) {
BetterLoadingScreen.log.error("Error while loading first cached " + providerName + " image", e);
return;
}
synchronized (textureLocationConsumer) {
textureLocationConsumer.accept(new ResourceLocation(cacheDir, imageID));
}
}
private void readAndCacheImageFromStream(String imageID, InputStream imageStream, boolean saveToDisk)
throws IOException {
BufferedImage image = ImageIO.read(imageStream);
textureCache.put(imageID, new LateInitDynamicTexture(image, image.getWidth(), image.getHeight()));
if (saveToDisk && Files.notExists(getCachedImagePath(imageID))) writeImageToCache(imageID, image);
}
private void readAndCacheImageFromDisk(String imageID) throws IOException {
readAndCacheImageFromStream(
imageID,
new BufferedInputStream(Files.newInputStream(getCachedImagePath(imageID)), 1024 * 1024),
false);
}
private void writeImageToCache(String imageID, BufferedImage image) throws IOException {
ImageIO.write(
image,
"png",
new BufferedOutputStream(Files.newOutputStream(getCachedImagePath(imageID)), 1024 * 1024));
}
private Path getCachedImagePath(String imageID) {
return Paths.get(cacheDir).resolve(imageID + ".png");
}
private List<String> getCachedImageIDs() {
try (Stream<Path> cacheFolderStream = Files.list(Paths.get(cacheDir))) {
return cacheFolderStream.map(path -> path.getFileName().toString().replace(".png", ""))
.collect(Collectors.toList());
} catch (IOException e) {
BetterLoadingScreen.log.error("Error while iterating " + providerName + " cache folder", e);
return null;
}
}
public static class ImageEntry {
public final String cacheId;
public final String downloadRef;
public ImageEntry(String cacheId, String downloadRef) {
this.cacheId = cacheId;
this.downloadRef = downloadRef;
}
}
}