Skip to content

Commit ca68960

Browse files
committed
clean up
1 parent a1ef964 commit ca68960

File tree

10 files changed

+250
-231
lines changed

10 files changed

+250
-231
lines changed

urlimg-common/src/main/java/com/paulzzh/urlimg/Image.java

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33
import java.math.BigDecimal;
44
import java.math.RoundingMode;
55

6-
public class Image {
6+
public class Image<I> {
77
private String hash;
8-
private Object image;
8+
private I image;
99
private int width;
1010
private int height;
1111

12-
public Image(String hash, Object image, int width, int height, int maxHeight) {
12+
public Image(String hash, I image, int width, int height, int maxHeight) {
1313
this.hash = hash;
1414
this.image = image;
1515
BigDecimal b = new BigDecimal((float) height / width);
@@ -22,17 +22,13 @@ public Image(String hash, Object image, int width, int height, int maxHeight) {
2222
this.height = maxHeight;
2323
this.width = (int) (maxHeight / hx);
2424
}
25-
while ((this.width > 300 || this.height > maxHeight) && this.height > 16) {
26-
this.height--;
27-
this.width = (int) (this.height / hx);
28-
}
2925
}
3026

3127
public String getHash() {
3228
return this.hash;
3329
}
3430

35-
public Object getImage() {
31+
public I getImage() {
3632
return this.image;
3733
}
3834

Lines changed: 74 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
11
package com.paulzzh.urlimg;
22

3+
import javax.net.ssl.HttpsURLConnection;
4+
import java.io.File;
5+
import java.io.FileInputStream;
36
import java.io.InputStream;
7+
import java.net.HttpURLConnection;
8+
import java.net.MalformedURLException;
49
import java.net.URL;
10+
import java.net.URLConnection;
511
import java.nio.charset.StandardCharsets;
612
import java.nio.file.Files;
7-
import java.nio.file.Path;
813
import java.nio.file.Paths;
914
import java.security.MessageDigest;
1015
import java.util.*;
16+
import java.util.concurrent.ExecutorService;
17+
import java.util.concurrent.Executors;
18+
import java.util.concurrent.Future;
1119

12-
public interface ImageManager {
13-
Map<String, Image> cache = Collections.synchronizedMap(new HashMap<>());
14-
Map<String, List<Image>> images = Collections.synchronizedMap(new HashMap<>());
20+
public abstract class ImageManager {
21+
private static final Map<String, Image<?>> cache = Collections.synchronizedMap(new HashMap<>());
22+
private static final Map<String, List<Image<?>>> images = Collections.synchronizedMap(new HashMap<>());
23+
private static final List<String> hashes = Collections.synchronizedList(new ArrayList<>());
24+
private final ExecutorService executor = Executors.newCachedThreadPool();
25+
private final ExecutorService executor2 = Executors.newCachedThreadPool();
1526

16-
static String bytesToHex(byte[] hash) {
27+
public static String bytesToHex(byte[] hash) {
1728
StringBuilder hexString = new StringBuilder(2 * hash.length);
1829
for (byte b : hash) {
1930
String hex = Integer.toHexString(0xff & b);
@@ -25,69 +36,89 @@ static String bytesToHex(byte[] hash) {
2536
return hexString.toString();
2637
}
2738

28-
static Image getImage(String hash) {
29-
return cache.get(hash);
30-
}
39+
public abstract Image<?> readImage(String hash, InputStream in);
40+
41+
public abstract Image<?> readAndSaveImage(String hash, InputStream in, File out);
42+
43+
public abstract void showImages(String id);
3144

32-
static List<Image> getImages(String hash) {
33-
return images.get(hash);
45+
public List<Image<?>> getImages(String hash) {
46+
synchronized (images) {
47+
return images.get(hash);
48+
}
3449
}
3550

36-
default void addImages(List<String> list) {
37-
new Thread(() -> {
38-
List<Image> imgs = new ArrayList<>();
51+
public void addImages(List<String> list) {
52+
executor.submit(() -> {
53+
List<Image<?>> imgs = new ArrayList<>();
54+
List<Future<Image<?>>> futures = new ArrayList<>();
3955
for (String url : list) {
40-
Image img = addImage(url);
41-
if (img != null) {
42-
imgs.add(img);
56+
futures.add(executor2.submit(() -> addImage(url)));
57+
}
58+
for (Future<Image<?>> future : futures) {
59+
try {
60+
Image<?> img = future.get();
61+
if (img != null) {
62+
imgs.add(img);
63+
}
64+
} catch (Exception ignored) {
65+
4366
}
4467
}
4568
if (!imgs.isEmpty()) {
4669
final String uuid = UUID.randomUUID().toString().replace("-", "");
47-
images.put(uuid, imgs);
70+
synchronized (images) {
71+
images.put(uuid, imgs);
72+
}
4873
showImages(uuid);
4974
}
50-
}).start();
75+
});
5176
}
5277

53-
default Image addImage(String url) {
78+
public Image<?> addImage(String url) {
5479
try {
5580
MessageDigest md = MessageDigest.getInstance("MD5");
5681
String hash = bytesToHex(md.digest(url.getBytes(StandardCharsets.UTF_8)));
57-
Path path = Paths.get("urlimgcache/" + hash + ".png");
82+
File out = Paths.get("urlimgcache/" + hash + ".png").toFile();
5883
Files.createDirectories(Paths.get("urlimgcache/"));
59-
if (cache.containsKey(hash)) {
60-
return cache.get(hash);
61-
} else if (path.toFile().isFile()) {
62-
Image img = readImage(hash, Files.newInputStream(path));
63-
if (img == null) {
64-
img = readImage(hash, new URL(url).openStream());
65-
if (img != null) {
66-
saveImage(img, path);
84+
synchronized (hashes) {
85+
if (hashes.contains(hash)) {
86+
hash = hashes.get(hashes.indexOf(hash));
87+
} else {
88+
hashes.add(hash);
89+
}
90+
}
91+
synchronized (hash) {
92+
synchronized (cache) {
93+
if (cache.containsKey(hash)) {
94+
return cache.get(hash);
6795
}
6896
}
69-
if (img != null) {
70-
cache.put(hash, img);
71-
return cache.get(hash);
97+
Image<?> img;
98+
if (out.isFile()) {
99+
img = readImage(hash, new FileInputStream(out));
100+
} else {
101+
URL u = new URL(url);
102+
URLConnection conn = u.openConnection();
103+
if (conn instanceof HttpURLConnection || conn instanceof HttpsURLConnection) {
104+
conn.setConnectTimeout(10000);
105+
conn.setReadTimeout(10000);
106+
conn.setRequestProperty("User-Agent", "urlimg");
107+
img = readAndSaveImage(hash, conn.getInputStream(), out);
108+
} else {
109+
throw new MalformedURLException("no protocol: " + u.getProtocol());
110+
}
72111
}
73-
} else {
74-
Image img = readImage(hash, new URL(url).openStream());
75112
if (img != null) {
76-
saveImage(img, path);
77-
cache.put(hash, img);
78-
return cache.get(hash);
113+
synchronized (cache) {
114+
cache.put(hash, img);
115+
}
79116
}
117+
return img;
80118
}
81119
} catch (Exception e) {
82120
e.printStackTrace();
83121
return null;
84122
}
85-
return null;
86123
}
87-
88-
Image readImage(String hash, InputStream bin);
89-
90-
void saveImage(Image obj, Path out);
91-
92-
void showImages(String id);
93124
}

urlimg-fabric/urlimg-fabric-1.19.4/src/main/java/com/paulzzh/urlimg/Mod.java

Lines changed: 41 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -15,25 +15,59 @@
1515

1616
import javax.imageio.ImageIO;
1717
import java.awt.image.BufferedImage;
18-
import java.io.ByteArrayInputStream;
19-
import java.io.ByteArrayOutputStream;
18+
import java.io.File;
19+
import java.io.FileInputStream;
2020
import java.io.InputStream;
21-
import java.nio.file.Path;
2221
import java.util.ArrayList;
2322
import java.util.HashMap;
2423
import java.util.List;
2524
import java.util.Map;
2625

2726
import static net.minecraft.text.ClickEvent.Action.OPEN_URL;
2827

29-
public class Mod implements ClientModInitializer, ImageManager {
28+
public class Mod implements ClientModInitializer {
3029
// This logger is used to write text to the console and the log file.
3130
// It is considered best practice to use your mod id as the logger's name.
3231
// That way, it's clear which mod wrote info, warnings, and errors.
3332
public static final Logger LOGGER = LoggerFactory.getLogger("urlimg");
3433
public static final Map<OrderedText, StringVisitable> line_map = new HashMap<>();
3534
private static final int line = 5;
3635
private static final int line_height = 10;
36+
public static final ImageManager IM = new ImageManager() {
37+
public void showImages(String msg) {
38+
MinecraftClient mc = MinecraftClient.getInstance();
39+
mc.inGameHud.getChatHud().addMessage(Text.of("urlimg=" + msg));
40+
for (int i = 0; i < line; i++) {
41+
mc.inGameHud.getChatHud().addMessage(Text.of(""));
42+
}
43+
}
44+
45+
@Override
46+
public Image<NativeImage> readImage(String hash, InputStream in) {
47+
try {
48+
NativeImage nativeImage = NativeImage.read(in);
49+
Identifier id = Identifier.of("urlimg", hash);
50+
MinecraftClient.getInstance().getTextureManager().registerTexture(id, new NativeImageBackedTexture(nativeImage));
51+
return new Image<>(hash, nativeImage, nativeImage.getWidth(), nativeImage.getHeight(), line * line_height);
52+
} catch (Exception e) {
53+
e.printStackTrace();
54+
return null;
55+
}
56+
}
57+
58+
@Override
59+
public Image<NativeImage> readAndSaveImage(String hash, InputStream in, File out) {
60+
try {
61+
BufferedImage bufferedImage = ImageIO.read(in); //1.20.3+ can't read jpeg
62+
ImageIO.write(bufferedImage, "png", out);
63+
LOGGER.info("cache image: {}", out.getName());
64+
return readImage(hash, new FileInputStream(out));
65+
} catch (Exception e) {
66+
e.printStackTrace();
67+
return null;
68+
}
69+
}
70+
};
3771

3872
public static List<String> getLinksFromChat(Text message) {
3973
List<String> list = new ArrayList<>();
@@ -56,51 +90,15 @@ public static void getLinksFromChat1(List<String> list, Text message) {
5690
String url = event.getValue();
5791
if (!list.contains(url)) {
5892
list.add(url);
59-
LOGGER.info(url);
93+
//LOGGER.info(url);
6094
}
6195
}
6296
}
6397

6498
@Override
6599
public void onInitializeClient() {
66100
LOGGER.info("Hello Fabric world!");
67-
ClientReceiveMessageEvents.CHAT.register((message, signedMessage, sender, params, receptionTimestamp) -> {
68-
addImages(getLinksFromChat(message));
69-
});
70-
ClientReceiveMessageEvents.GAME.register((message, overlay) -> {
71-
addImages(getLinksFromChat(message));
72-
});
73-
}
74-
75-
public void showImages(String msg) {
76-
MinecraftClient mc = MinecraftClient.getInstance();
77-
mc.inGameHud.getChatHud().addMessage(Text.of("urlimg=" + msg));
78-
for (int i = 0; i < line; i++) {
79-
mc.inGameHud.getChatHud().addMessage(Text.of(""));
80-
}
81-
}
82-
83-
public Image readImage(String hash, InputStream bin) {
84-
try {
85-
BufferedImage bufferedImage = ImageIO.read(bin); //1.20.3+ can't read jpeg
86-
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
87-
ImageIO.write(bufferedImage, "png", byteArrayOut);
88-
NativeImage nativeImage = NativeImage.read(new ByteArrayInputStream(byteArrayOut.toByteArray()));
89-
Identifier id = Identifier.of("urlimg", hash);
90-
MinecraftClient.getInstance().getTextureManager().registerTexture(id, new NativeImageBackedTexture(nativeImage));
91-
return new Image(hash, nativeImage, nativeImage.getWidth(), nativeImage.getHeight(), line * line_height);
92-
} catch (Exception e) {
93-
e.printStackTrace();
94-
return null;
95-
}
96-
}
97-
98-
public void saveImage(Image image, Path out) {
99-
try {
100-
NativeImage nativeImage = (NativeImage) image.getImage();
101-
nativeImage.writeTo(out);
102-
} catch (Exception e) {
103-
e.printStackTrace();
104-
}
101+
ClientReceiveMessageEvents.CHAT.register((message, signedMessage, sender, params, receptionTimestamp) -> IM.addImages(getLinksFromChat(message)));
102+
ClientReceiveMessageEvents.GAME.register((message, overlay) -> IM.addImages(getLinksFromChat(message)));
105103
}
106104
}

urlimg-fabric/urlimg-fabric-1.19.4/src/main/java/com/paulzzh/urlimg/mixin/MixinChatHud.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import com.llamalad7.mixinextras.sugar.ref.LocalIntRef;
55
import com.mojang.blaze3d.systems.RenderSystem;
66
import com.paulzzh.urlimg.Image;
7-
import com.paulzzh.urlimg.ImageManager;
87
import net.minecraft.client.font.TextRenderer;
98
import net.minecraft.client.gui.hud.ChatHud;
109
import net.minecraft.client.util.math.MatrixStack;
@@ -15,6 +14,7 @@
1514
import org.spongepowered.asm.mixin.injection.At;
1615
import org.spongepowered.asm.mixin.injection.Redirect;
1716

17+
import static com.paulzzh.urlimg.Mod.IM;
1818
import static com.paulzzh.urlimg.Mod.line_map;
1919
import static net.minecraft.client.gui.DrawableHelper.drawTexture;
2020

@@ -34,7 +34,7 @@ private int injected3(TextRenderer instance, MatrixStack matrixStack, OrderedTex
3434
String uuid = sv.getString().substring(7, 39);
3535
RenderSystem.enableBlend();
3636
int indexX = 0;
37-
for (Image img : ImageManager.getImages(uuid)) {
37+
for (Image<?> img : IM.getImages(uuid)) {
3838
RenderSystem.setShaderTexture(0, Identifier.of("urlimg", img.getHash()));
3939
drawTexture(matrixStack, indexX, argRef.get(), 0, 0, img.getWidth(), img.getHeight(), img.getWidth(), img.getHeight());
4040
indexX += img.getWidth();

0 commit comments

Comments
 (0)