Skip to content

Commit

Permalink
Add SHA256 digest to cached file name
Browse files Browse the repository at this point in the history
Fixes caching failure when URL is too long (e.g. discord hosted ones).
Fixes illegal characters on Windows (namely '\') that can show up in base64.
  • Loading branch information
zFERDQFREZrzfq committed Apr 19, 2024
1 parent da657cb commit d5ae0ba
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/main/java/me/srrapero720/watermedia/api/cache/CacheAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@
import me.srrapero720.watermedia.WaterMedia;
import me.srrapero720.watermedia.api.WaterMediaAPI;
import me.srrapero720.watermedia.loaders.ILoader;
import me.srrapero720.watermedia.tools.IOTool;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;

import java.io.*;
import java.nio.file.Files;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -134,6 +138,12 @@ private static boolean updateIndex() {
}

static File entry$getFile(String url) {
return new File(dir, Base64.getEncoder().encodeToString(url.getBytes()));
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return new File(dir, IOTool.encodeHexString(digest.digest(url.getBytes(StandardCharsets.UTF_8))));
} catch (NoSuchAlgorithmException e) { LOGGER.error(IT, "Failed to initalize digest", e); }

// Fallback to old naming
return new File(dir, Base64.getEncoder().encodeToString(url.getBytes()));
}
}
}
11 changes: 11 additions & 0 deletions src/main/java/me/srrapero720/watermedia/tools/IOTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,15 @@ public static void unzip(Marker it, Path zipFilePath, Path destDirectory) throws
while ((read = zipIn.read(bytesIn)) != -1) output.write(bytesIn, 0, read);
}
}

private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String encodeHexString(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
}

0 comments on commit d5ae0ba

Please sign in to comment.