Archive eaglerxpaper (plugin, 1.8.8 - 26.x, clean)
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
|
||||
plugins {
|
||||
id "java-library"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly(libs.guava)
|
||||
compileOnly(libs.bundles.netty.all)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
|
||||
plugins {
|
||||
id "java"
|
||||
}
|
||||
|
||||
configurations {
|
||||
sqliteDriver
|
||||
}
|
||||
|
||||
dependencies {
|
||||
sqliteDriver(libs.jdbc.sqlite)
|
||||
}
|
||||
|
||||
jar {
|
||||
entryCompression = ZipEntryCompression.STORED
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
from {
|
||||
configurations.sqliteDriver.collect { it.isDirectory() ? it : zipTree(it) }
|
||||
}
|
||||
exclude "org/sqlite/native/FreeBSD/x86/*"
|
||||
exclude "org/sqlite/native/Linux/arm/*"
|
||||
exclude "org/sqlite/native/Linux/armv6/*"
|
||||
exclude "org/sqlite/native/Linux/ppc64/*"
|
||||
exclude "org/sqlite/native/Linux/riscv64/*"
|
||||
exclude "org/sqlite/native/Linux/x86/*"
|
||||
exclude "org/sqlite/native/Linux-Android/x86/*"
|
||||
exclude "org/sqlite/native/Linux-Android/x86_64/*"
|
||||
exclude "org/sqlite/native/Linux-Musl/x86/*"
|
||||
exclude "org/sqlite/native/Windows/armv7/*"
|
||||
exclude "org/sqlite/native/Windows/x86/*"
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
/*
|
||||
* Decompiled with CFR 0.152.
|
||||
*
|
||||
* Could not load the following classes:
|
||||
* com.google.common.cache.Cache
|
||||
* com.google.common.cache.CacheBuilder
|
||||
* io.netty.bootstrap.Bootstrap
|
||||
* io.netty.buffer.ByteBuf
|
||||
* io.netty.channel.Channel
|
||||
* io.netty.channel.ChannelFuture
|
||||
* io.netty.channel.ChannelFutureListener
|
||||
* io.netty.channel.ChannelHandler
|
||||
* io.netty.channel.ChannelHandlerContext
|
||||
* io.netty.channel.ChannelInitializer
|
||||
* io.netty.channel.ChannelOption
|
||||
* io.netty.channel.SimpleChannelInboundHandler
|
||||
* io.netty.handler.codec.http.DefaultHttpRequest
|
||||
* io.netty.handler.codec.http.HttpClientCodec
|
||||
* io.netty.handler.codec.http.HttpContent
|
||||
* io.netty.handler.codec.http.HttpMethod
|
||||
* io.netty.handler.codec.http.HttpObject
|
||||
* io.netty.handler.codec.http.HttpResponse
|
||||
* io.netty.handler.codec.http.HttpVersion
|
||||
* io.netty.handler.codec.http.LastHttpContent
|
||||
* io.netty.handler.ssl.SslContext
|
||||
* io.netty.handler.ssl.SslHandler
|
||||
* io.netty.handler.timeout.ReadTimeoutHandler
|
||||
* io.netty.util.concurrent.GenericFutureListener
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.skin_cache;
|
||||
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
import io.netty.handler.codec.http.DefaultHttpRequest;
|
||||
import io.netty.handler.codec.http.HttpClientCodec;
|
||||
import io.netty.handler.codec.http.HttpContent;
|
||||
import io.netty.handler.codec.http.HttpMethod;
|
||||
import io.netty.handler.codec.http.HttpObject;
|
||||
import io.netty.handler.codec.http.HttpResponse;
|
||||
import io.netty.handler.codec.http.HttpVersion;
|
||||
import io.netty.handler.codec.http.LastHttpContent;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
import io.netty.handler.ssl.SslHandler;
|
||||
import io.netty.handler.timeout.ReadTimeoutHandler;
|
||||
import io.netty.util.concurrent.GenericFutureListener;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import javax.net.ssl.SSLEngine;
|
||||
import net.lax1dude.eaglercraft.backend.skin_cache.IHTTPClient;
|
||||
|
||||
public class HTTPClient
|
||||
implements IHTTPClient {
|
||||
public static final int MAX_REDIRECTS = 8;
|
||||
private final Cache<String, InetAddress> addressCache = CacheBuilder.newBuilder().expireAfterWrite(15L, TimeUnit.MINUTES).build();
|
||||
private final Supplier<Bootstrap> bootstrapper;
|
||||
private final String userAgent;
|
||||
|
||||
private static SslContext buildClientSslContext() throws Exception {
|
||||
Class<?> builderClass = Class.forName("io.netty.handler.ssl.SslContextBuilder");
|
||||
Object builder = builderClass.getMethod("forClient", new Class[0]).invoke(null, new Object[0]);
|
||||
return (SslContext)builderClass.getMethod("build", new Class[0]).invoke(builder, new Object[0]);
|
||||
}
|
||||
|
||||
public HTTPClient(Supplier<Bootstrap> bootstrapper, String userAgent) {
|
||||
this.bootstrapper = bootstrapper;
|
||||
this.userAgent = userAgent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void asyncRequest(String method, URI uri, Consumer<IHTTPClient.Response> responseCallback) {
|
||||
this.asyncRequest(uri, responseCallback, new RedirectTracker(method));
|
||||
}
|
||||
|
||||
private void asyncRequest(URI uri, Consumer<IHTTPClient.Response> responseCallback, RedirectTracker redirectTracker) {
|
||||
String host;
|
||||
InetAddress inetHost;
|
||||
int port = uri.getPort();
|
||||
boolean ssl = false;
|
||||
String scheme = uri.getScheme();
|
||||
if (scheme == null) {
|
||||
responseCallback.accept(new IHTTPClient.Response(new UnsupportedOperationException("URI is missing a scheme: " + uri)));
|
||||
return;
|
||||
}
|
||||
switch (scheme) {
|
||||
case "http": {
|
||||
if (port != -1) break;
|
||||
port = 80;
|
||||
break;
|
||||
}
|
||||
case "https": {
|
||||
if (port == -1) {
|
||||
port = 443;
|
||||
}
|
||||
ssl = true;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
responseCallback.accept(new IHTTPClient.Response(new UnsupportedOperationException("Unsupported scheme: " + scheme)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if ((inetHost = (InetAddress)this.addressCache.getIfPresent(host = uri.getHost())) == null) {
|
||||
try {
|
||||
inetHost = InetAddress.getByName(host);
|
||||
}
|
||||
catch (UnknownHostException ex) {
|
||||
responseCallback.accept(new IHTTPClient.Response(ex));
|
||||
return;
|
||||
}
|
||||
this.addressCache.put(host, inetHost);
|
||||
}
|
||||
InetSocketAddress addr = new InetSocketAddress(inetHost, port);
|
||||
((Bootstrap)((Bootstrap)((Bootstrap)this.bootstrapper.get().handler((ChannelHandler)new NettyHttpChannelInitializer(responseCallback, redirectTracker, ssl, host, port, uri))).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)).option(ChannelOption.TCP_NODELAY, true)).remoteAddress((SocketAddress)addr).connect().addListener((GenericFutureListener)new NettyHttpChannelFutureListener(redirectTracker.method, uri, responseCallback));
|
||||
}
|
||||
|
||||
private static class RedirectTracker {
|
||||
private int redirects = 0;
|
||||
private String method;
|
||||
|
||||
private RedirectTracker(String method) {
|
||||
this.method = method;
|
||||
}
|
||||
}
|
||||
|
||||
private class NettyHttpChannelInitializer
|
||||
extends ChannelInitializer<Channel> {
|
||||
protected final Consumer<IHTTPClient.Response> responseCallback;
|
||||
protected final RedirectTracker redirectTracker;
|
||||
protected final boolean ssl;
|
||||
protected final String host;
|
||||
protected final int port;
|
||||
protected final URI requestURI;
|
||||
|
||||
protected NettyHttpChannelInitializer(Consumer<IHTTPClient.Response> responseCallback, RedirectTracker redirectTracker, boolean ssl, String host, int port, URI requestURI) {
|
||||
this.responseCallback = responseCallback;
|
||||
this.redirectTracker = redirectTracker;
|
||||
this.ssl = ssl;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.requestURI = requestURI;
|
||||
}
|
||||
|
||||
protected void initChannel(Channel ch) throws Exception {
|
||||
ch.pipeline().addLast("timeout", (ChannelHandler)new ReadTimeoutHandler(5L, TimeUnit.SECONDS));
|
||||
if (this.ssl) {
|
||||
SSLEngine engine = HTTPClient.buildClientSslContext().newEngine(ch.alloc(), this.host, this.port);
|
||||
ch.pipeline().addLast("ssl", (ChannelHandler)new SslHandler(engine));
|
||||
}
|
||||
ch.pipeline().addLast("http", (ChannelHandler)new HttpClientCodec());
|
||||
ch.pipeline().addLast("handler", (ChannelHandler)new NettyHttpResponseHandler(this.responseCallback, this.redirectTracker, this.requestURI));
|
||||
}
|
||||
}
|
||||
|
||||
private class NettyHttpChannelFutureListener
|
||||
implements ChannelFutureListener {
|
||||
protected final String method;
|
||||
protected final URI requestURI;
|
||||
protected final Consumer<IHTTPClient.Response> responseCallback;
|
||||
|
||||
protected NettyHttpChannelFutureListener(String method, URI requestURI, Consumer<IHTTPClient.Response> responseCallback) {
|
||||
this.method = method;
|
||||
this.requestURI = requestURI;
|
||||
this.responseCallback = responseCallback;
|
||||
}
|
||||
|
||||
public void operationComplete(ChannelFuture future) throws Exception {
|
||||
if (future.isSuccess()) {
|
||||
String path = this.requestURI.getRawPath() + (this.requestURI.getRawQuery() == null ? "" : "?" + this.requestURI.getRawQuery());
|
||||
DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf((String)this.method), path);
|
||||
request.headers().set("Host", (Object)this.requestURI.getHost());
|
||||
request.headers().set("User-Agent", (Object)HTTPClient.this.userAgent);
|
||||
future.channel().writeAndFlush((Object)request);
|
||||
} else {
|
||||
HTTPClient.this.addressCache.invalidate(this.requestURI.getHost());
|
||||
this.responseCallback.accept(new IHTTPClient.Response(new IOException("Connection failed")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class NettyHttpResponseHandler
|
||||
extends SimpleChannelInboundHandler<HttpObject> {
|
||||
protected final Consumer<IHTTPClient.Response> responseCallback;
|
||||
protected final RedirectTracker redirectTracker;
|
||||
protected final URI requestURI;
|
||||
protected int responseCode = -1;
|
||||
protected ByteBuf buffer = null;
|
||||
|
||||
protected NettyHttpResponseHandler(Consumer<IHTTPClient.Response> responseCallback, RedirectTracker redirectTracker, URI requestURI) {
|
||||
this.responseCallback = responseCallback;
|
||||
this.redirectTracker = redirectTracker;
|
||||
this.requestURI = requestURI;
|
||||
}
|
||||
|
||||
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
|
||||
if (msg instanceof HttpResponse) {
|
||||
HttpResponse response = (HttpResponse)msg;
|
||||
this.responseCode = response.getStatus().code();
|
||||
if (this.responseCode == 301 || this.responseCode == 302 || this.responseCode == 303 || this.responseCode == 307 || this.responseCode == 308) {
|
||||
ctx.channel().pipeline().remove((ChannelHandler)this);
|
||||
ctx.channel().close();
|
||||
if (this.responseCode == 303) {
|
||||
this.redirectTracker.method = "GET";
|
||||
}
|
||||
this.redirect(response);
|
||||
return;
|
||||
}
|
||||
if (this.responseCode == 204) {
|
||||
this.done(ctx);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (msg instanceof HttpContent) {
|
||||
HttpContent content = (HttpContent)msg;
|
||||
if (this.buffer == null) {
|
||||
this.buffer = ctx.alloc().buffer();
|
||||
}
|
||||
this.buffer.writeBytes(content.content());
|
||||
if (msg instanceof LastHttpContent) {
|
||||
this.done(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
||||
if (this.buffer != null) {
|
||||
try {
|
||||
this.buffer.release();
|
||||
}
|
||||
catch (Throwable throwable) {
|
||||
// empty catch block
|
||||
}
|
||||
this.buffer = null;
|
||||
}
|
||||
this.responseCallback.accept(new IHTTPClient.Response(cause));
|
||||
ctx.close();
|
||||
}
|
||||
|
||||
private void redirect(HttpResponse response) {
|
||||
if (this.buffer != null) {
|
||||
try {
|
||||
this.buffer.release();
|
||||
}
|
||||
catch (Throwable throwable) {
|
||||
// empty catch block
|
||||
}
|
||||
this.buffer = null;
|
||||
}
|
||||
if (++this.redirectTracker.redirects >= 8) {
|
||||
this.responseCallback.accept(new IHTTPClient.Response(new IllegalStateException("Too many redirects!")));
|
||||
} else {
|
||||
String target = response.headers().get("Location");
|
||||
if (target != null) {
|
||||
URI uri;
|
||||
try {
|
||||
uri = this.requestURI.resolve(target.toString());
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
this.responseCallback.accept(new IHTTPClient.Response(new IllegalStateException("Invalid redirect address in 3xx response!", ex)));
|
||||
return;
|
||||
}
|
||||
HTTPClient.this.asyncRequest(uri, this.responseCallback, this.redirectTracker);
|
||||
} else {
|
||||
this.responseCallback.accept(new IHTTPClient.Response(new IllegalStateException("Missing redirect address in 3xx response!")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void done(ChannelHandlerContext ctx) {
|
||||
try {
|
||||
this.responseCallback.accept(new IHTTPClient.Response(this.responseCode, this.redirectTracker.redirects > 0, this.buffer));
|
||||
}
|
||||
finally {
|
||||
ctx.channel().pipeline().remove((ChannelHandler)this);
|
||||
ctx.channel().close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.skin_cache;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
|
||||
public interface IHTTPClient {
|
||||
|
||||
public static class Response {
|
||||
|
||||
public final int code;
|
||||
public final boolean redirected;
|
||||
public final ByteBuf data;
|
||||
public final Throwable exception;
|
||||
|
||||
public Response(int code, boolean redirected, ByteBuf data) {
|
||||
this.code = code;
|
||||
this.redirected = redirected;
|
||||
this.data = data;
|
||||
this.exception = null;
|
||||
}
|
||||
|
||||
public Response(Throwable exception) {
|
||||
this.code = -1;
|
||||
this.redirected = false;
|
||||
this.data = null;
|
||||
this.exception = exception;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void asyncRequest(String method, URI uri, Consumer<Response> responseCallback);
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.skin_cache;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface ISkinCacheDatastore {
|
||||
|
||||
void loadSkin(String skinURL, Consumer<byte[]> callback);
|
||||
|
||||
void loadCape(String capeURL, Consumer<byte[]> callback);
|
||||
|
||||
void storeSkin(String skinURL, byte[] data);
|
||||
|
||||
void storeCape(String capeURL, byte[] data);
|
||||
|
||||
void tick();
|
||||
|
||||
void dispose();
|
||||
|
||||
int getTotalStoredSkins();
|
||||
|
||||
int getTotalStoredCapes();
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.skin_cache;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface ISkinCacheDownloader {
|
||||
|
||||
void downloadSkin(String skinURL, Consumer<byte[]> callback);
|
||||
|
||||
void downloadCape(String skinURL, Consumer<byte[]> callback);
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.skin_cache;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface ISkinCacheService {
|
||||
|
||||
byte[] ERROR = new byte[0];
|
||||
|
||||
void resolveSkinByURL(String skinURL, Consumer<byte[]> callback);
|
||||
|
||||
void resolveCapeByURL(String capeURL, Consumer<byte[]> callback);
|
||||
|
||||
void tick();
|
||||
|
||||
int getTotalMemorySkins();
|
||||
|
||||
int getTotalMemoryCapes();
|
||||
|
||||
int getTotalStoredSkins();
|
||||
|
||||
int getTotalStoredCapes();
|
||||
|
||||
}
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
/*
|
||||
* Decompiled with CFR 0.152.
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.skin_cache;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.zip.DataFormatException;
|
||||
import java.util.zip.Deflater;
|
||||
import java.util.zip.Inflater;
|
||||
import net.lax1dude.eaglercraft.backend.skin_cache.ISkinCacheDatastore;
|
||||
import net.lax1dude.eaglercraft.backend.skin_cache.SkinCacheTable;
|
||||
import net.lax1dude.eaglercraft.backend.util.ILoggerAdapter;
|
||||
import net.lax1dude.eaglercraft.backend.util.SteadyTime;
|
||||
|
||||
public class SkinCacheDatastore
|
||||
implements ISkinCacheDatastore {
|
||||
public static final int SKIN_LENGTH = 12288;
|
||||
public static final int CAPE_LENGTH = 1173;
|
||||
protected final ILoggerAdapter logger;
|
||||
protected final SkinCacheDatastoreThreadEnv[] threads;
|
||||
protected final BlockingQueue<SkinCacheDatastoreRunnable> databaseQueue = new LinkedBlockingQueue<SkinCacheDatastoreRunnable>();
|
||||
protected final CountDownLatch disposeLatch;
|
||||
protected long lastCleanup = 0L;
|
||||
protected int keepObjectsDays;
|
||||
protected int maxObjects;
|
||||
protected final boolean sqliteCompatible;
|
||||
protected final SkinCacheTable skin;
|
||||
protected final SkinCacheTable cape;
|
||||
protected final Object dbWriteLock = new Object();
|
||||
private static final SkinCacheDatastoreRunnable TERMINATE = env -> {};
|
||||
|
||||
public SkinCacheDatastore(Connection[] conn, int threadCount, int keepObjectsDays, int maxObjects, int compressionLevel, boolean sqliteCompatible, ILoggerAdapter logger) throws SQLException {
|
||||
this.keepObjectsDays = keepObjectsDays;
|
||||
this.maxObjects = maxObjects;
|
||||
this.sqliteCompatible = sqliteCompatible;
|
||||
this.logger = logger;
|
||||
this.skin = new SkinCacheTable("eagler_skins", conn[0], sqliteCompatible, logger, this.dbWriteLock);
|
||||
this.cape = new SkinCacheTable("eagler_capes", conn[0], sqliteCompatible, logger, this.dbWriteLock);
|
||||
this.disposeLatch = new CountDownLatch(threadCount);
|
||||
this.threads = new SkinCacheDatastoreThreadEnv[threadCount];
|
||||
for (int i = 0; i < threadCount; ++i) {
|
||||
this.threads[i] = new SkinCacheDatastoreThreadEnv(i, compressionLevel, conn[conn.length > 1 ? i : 0]);
|
||||
}
|
||||
}
|
||||
|
||||
private void execute(SkinCacheDatastoreRunnable runnable) {
|
||||
this.databaseQueue.add(runnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadSkin(String skinURL, Consumer<byte[]> callback) {
|
||||
this.execute(env -> {
|
||||
byte[] result;
|
||||
try {
|
||||
result = this.skin.loadSkin(env.skinEnv, skinURL);
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
this.logger.error("Could not load skin \"" + skinURL + "\" from database!");
|
||||
callback.accept(null);
|
||||
return;
|
||||
}
|
||||
if (result != null) {
|
||||
byte[] res;
|
||||
try {
|
||||
res = this.decompressSkin(env, result, 12288);
|
||||
}
|
||||
catch (DataFormatException ex) {
|
||||
this.logger.warn("Skin \"" + skinURL + "\" could not be decompressed!");
|
||||
callback.accept(null);
|
||||
return;
|
||||
}
|
||||
callback.accept(res);
|
||||
} else {
|
||||
callback.accept(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadCape(String capeURL, Consumer<byte[]> callback) {
|
||||
this.execute(env -> {
|
||||
byte[] result;
|
||||
try {
|
||||
result = this.cape.loadSkin(env.capeEnv, capeURL);
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
this.logger.error("Could not load cape \"" + capeURL + "\" from database!");
|
||||
callback.accept(null);
|
||||
return;
|
||||
}
|
||||
if (result != null) {
|
||||
byte[] res;
|
||||
try {
|
||||
res = this.decompressSkin(env, result, 1173);
|
||||
}
|
||||
catch (DataFormatException ex) {
|
||||
this.logger.warn("Cape \"" + capeURL + "\" could not be decompressed!");
|
||||
callback.accept(null);
|
||||
return;
|
||||
}
|
||||
callback.accept(res);
|
||||
} else {
|
||||
callback.accept(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private byte[] decompressSkin(SkinCacheDatastoreThreadEnv env, byte[] input, int len) throws DataFormatException {
|
||||
if (env.inflater == null && input.length == len) {
|
||||
return input;
|
||||
}
|
||||
byte[] ret = new byte[len];
|
||||
env.inflater.reset();
|
||||
env.inflater.setInput(input, 0, input.length);
|
||||
if (env.inflater.inflate(ret, 0, len) != len) {
|
||||
throw new DataFormatException();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void storeSkin(String skinURL, byte[] data) {
|
||||
if (data.length != 12288) {
|
||||
throw new IllegalArgumentException("Skin length is not 12288 bytes!");
|
||||
}
|
||||
this.execute(env -> {
|
||||
try {
|
||||
this.skin.storeSkin(env.skinEnv, skinURL, this.sha1Digest(env, data), this.compressSkin(env, data));
|
||||
}
|
||||
catch (IllegalStateException | SQLException e) {
|
||||
this.logger.error("Skin \"" + skinURL + "\" could not be stored in the database!", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void storeCape(String capeURL, byte[] data) {
|
||||
if (data.length != 1173) {
|
||||
throw new IllegalArgumentException("Cape length is not 1173 bytes!");
|
||||
}
|
||||
this.execute(env -> {
|
||||
try {
|
||||
this.cape.storeSkin(env.capeEnv, capeURL, this.sha1Digest(env, data), this.compressSkin(env, data));
|
||||
}
|
||||
catch (IllegalStateException | SQLException e) {
|
||||
this.logger.error("Cape \"" + capeURL + "\" could not be stored in the database!", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private byte[] compressSkin(SkinCacheDatastoreThreadEnv env, byte[] data) {
|
||||
if (env.deflater == null) {
|
||||
return data;
|
||||
}
|
||||
env.deflater.reset();
|
||||
env.deflater.setInput(data, 0, data.length);
|
||||
env.deflater.finish();
|
||||
int i = env.deflater.deflate(env.compressionTmp, 0, env.compressionTmp.length);
|
||||
if (i <= 0) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
return Arrays.copyOf(env.compressionTmp, i);
|
||||
}
|
||||
|
||||
private byte[] sha1Digest(SkinCacheDatastoreThreadEnv env, byte[] data) {
|
||||
env.sha1Digest.update(data);
|
||||
return env.sha1Digest.digest();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
long millisSteady = SteadyTime.millis();
|
||||
if (millisSteady - this.lastCleanup > 600000L) {
|
||||
this.lastCleanup = millisSteady;
|
||||
try {
|
||||
this.runCleanup();
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
this.logger.error("Could not clean up skin cache!", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* WARNING - Removed try catching itself - possible behaviour change.
|
||||
*/
|
||||
private synchronized void runCleanup() throws SQLException {
|
||||
long millis = System.currentTimeMillis();
|
||||
long expiry = millis - (long)this.keepObjectsDays * 86400000L;
|
||||
Object object = this.dbWriteLock;
|
||||
synchronized (object) {
|
||||
this.skin.runCleanup(this.maxObjects, expiry);
|
||||
this.cape.runCleanup(this.maxObjects, expiry);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dispose() {
|
||||
for (int i = 0; i < this.threads.length; ++i) {
|
||||
this.databaseQueue.add(TERMINATE);
|
||||
}
|
||||
try {
|
||||
if (!this.disposeLatch.await(10L, TimeUnit.SECONDS)) {
|
||||
this.logger.warn("Skin cache datastore workers did not terminate in time");
|
||||
}
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
this.skin.dispose();
|
||||
this.cape.dispose();
|
||||
}
|
||||
|
||||
static void disposeStmt(PreparedStatement stmt) {
|
||||
if (stmt != null) {
|
||||
try {
|
||||
stmt.close();
|
||||
}
|
||||
catch (SQLException sQLException) {
|
||||
// empty catch block
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized int getTotalStoredSkins() {
|
||||
return this.skin.countSkins();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized int getTotalStoredCapes() {
|
||||
return this.cape.countSkins();
|
||||
}
|
||||
|
||||
private static interface SkinCacheDatastoreRunnable {
|
||||
public void run(SkinCacheDatastoreThreadEnv var1);
|
||||
}
|
||||
|
||||
private class SkinCacheDatastoreThreadEnv {
|
||||
protected final Thread thread;
|
||||
protected final SkinCacheTable.SkinCacheTableThreadEnv skinEnv;
|
||||
protected final SkinCacheTable.SkinCacheTableThreadEnv capeEnv;
|
||||
protected final byte[] compressionTmp;
|
||||
protected final Deflater deflater;
|
||||
protected final Inflater inflater;
|
||||
protected final MessageDigest sha1Digest;
|
||||
|
||||
protected SkinCacheDatastoreThreadEnv(int i, int compressionLevel, Connection conn) throws SQLException {
|
||||
this.skinEnv = SkinCacheDatastore.this.skin.createThreadEnv(conn);
|
||||
this.capeEnv = SkinCacheDatastore.this.cape.createThreadEnv(conn);
|
||||
this.compressionTmp = new byte[65535];
|
||||
this.deflater = compressionLevel > 0 ? new Deflater(compressionLevel) : null;
|
||||
this.inflater = compressionLevel > 0 ? new Inflater() : null;
|
||||
try {
|
||||
this.sha1Digest = MessageDigest.getInstance("SHA-1");
|
||||
}
|
||||
catch (NoSuchAlgorithmException ex) {
|
||||
throw new RuntimeException("This JRE does not support SHA-1!", ex);
|
||||
}
|
||||
this.thread = new Thread(() -> {
|
||||
while (true) {
|
||||
try {
|
||||
SkinCacheDatastoreRunnable runnable;
|
||||
while ((runnable = SkinCacheDatastore.this.databaseQueue.take()) != TERMINATE) {
|
||||
runnable.run(this);
|
||||
}
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
if (ex instanceof ThreadDeath) {
|
||||
ThreadDeath exx = (ThreadDeath)ex;
|
||||
throw exx;
|
||||
}
|
||||
SkinCacheDatastore.this.logger.error("Caught exception in worker thread #" + (i + 1), ex);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
this.dispose();
|
||||
SkinCacheDatastore.this.disposeLatch.countDown();
|
||||
}, "SkinCacheDatastore Thread #" + (i + 1));
|
||||
this.thread.setDaemon(true);
|
||||
this.thread.start();
|
||||
}
|
||||
|
||||
public void dispose() {
|
||||
this.skinEnv.dispose();
|
||||
this.capeEnv.dispose();
|
||||
if (this.deflater != null) {
|
||||
this.deflater.end();
|
||||
}
|
||||
if (this.inflater != null) {
|
||||
this.inflater.end();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.skin_cache;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import io.netty.buffer.ByteBufInputStream;
|
||||
|
||||
public class SkinCacheDownloader implements ISkinCacheDownloader {
|
||||
|
||||
private final IHTTPClient httpClient;
|
||||
private final Set<String> validSkinHosts;
|
||||
|
||||
public SkinCacheDownloader(IHTTPClient httpClient, Set<String> validSkinHosts) {
|
||||
this.httpClient = httpClient;
|
||||
this.validSkinHosts = validSkinHosts;
|
||||
}
|
||||
|
||||
private URI validateSkinURL(String url) {
|
||||
try {
|
||||
URI uri = URI.create(url);
|
||||
String host = uri.getHost();
|
||||
if (host == null || !validSkinHosts.contains(host.toLowerCase())) {
|
||||
return null;
|
||||
}
|
||||
return uri;
|
||||
} catch (IllegalArgumentException t) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void downloadTexture(String skinURL, Consumer<BufferedImage> callback) {
|
||||
URI uri = validateSkinURL(skinURL);
|
||||
if (uri != null) {
|
||||
httpClient.asyncRequest("GET", uri, (res) -> {
|
||||
if (res.exception != null || res.data == null) {
|
||||
callback.accept(null);
|
||||
} else {
|
||||
BufferedImage img = null;
|
||||
try {
|
||||
if (res.code == 200) {
|
||||
img = ImageIO.read(new ByteBufInputStream(res.data));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// 200 response with a broken image body — log it so
|
||||
// it's visible why the download failed
|
||||
System.err.println("[EaglerXServer] Failed to decode skin image from "
|
||||
+ skinURL + ": " + e.getMessage());
|
||||
} finally {
|
||||
res.data.release();
|
||||
}
|
||||
callback.accept(img);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
callback.accept(null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void downloadSkin(String skinURL, Consumer<byte[]> callback) {
|
||||
downloadTexture(skinURL, (res) -> {
|
||||
if (res != null) {
|
||||
if (res.getWidth() == 64) {
|
||||
byte[] pixels;
|
||||
if (res.getHeight() == 32) {
|
||||
int[] pixelsIn = res.getRGB(0, 0, 64, 32, null, 0, 64);
|
||||
pixels = new byte[64 * 64 * 3];
|
||||
SkinConverter.convert64x32To64x64(pixelsIn, pixels);
|
||||
} else if (res.getHeight() == 64) {
|
||||
int[] pixelsIn = res.getRGB(0, 0, 64, 64, null, 0, 64);
|
||||
pixels = new byte[64 * 64 * 3];
|
||||
SkinConverter.convertToBytes(pixelsIn, pixels);
|
||||
} else {
|
||||
callback.accept(null);
|
||||
return;
|
||||
}
|
||||
callback.accept(pixels);
|
||||
} else {
|
||||
callback.accept(null);
|
||||
}
|
||||
} else {
|
||||
callback.accept(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void downloadCape(String skinURL, Consumer<byte[]> callback) {
|
||||
downloadTexture(skinURL, (res) -> {
|
||||
if (res != null) {
|
||||
if (res.getWidth() == 64 && res.getHeight() == 32) {
|
||||
int[] pixelsIn = res.getRGB(0, 0, 64, 32, null, 0, 64);
|
||||
byte[] pixels = new byte[1173];
|
||||
SkinConverter.convertCape64x32RGBAto23x17RGB(pixelsIn, pixels);
|
||||
callback.accept(pixels);
|
||||
} else {
|
||||
callback.accept(null);
|
||||
}
|
||||
} else {
|
||||
callback.accept(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.skin_cache;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.util.ConcurrentLazyLoader;
|
||||
import net.lax1dude.eaglercraft.backend.util.ILoggerAdapter;
|
||||
|
||||
public class SkinCacheService implements ISkinCacheService {
|
||||
|
||||
protected final ILoggerAdapter logger;
|
||||
protected final ISkinCacheDownloader downloader;
|
||||
protected final ISkinCacheDatastore datastore;
|
||||
|
||||
protected final LoadingCache<String, ConcurrentLazyLoader<byte[]>> skinCache;
|
||||
protected final LoadingCache<String, ConcurrentLazyLoader<byte[]>> capeCache;
|
||||
|
||||
protected long lastFlush = 0l;
|
||||
protected final ReadWriteLock failedSkinLookupsLock = new ReentrantReadWriteLock();
|
||||
protected final Map<String, Long> failedSkinLookups = new HashMap<>();
|
||||
protected final ReadWriteLock failedCapeLookupsLock = new ReentrantReadWriteLock();
|
||||
protected final Map<String, Long> failedCapeLookups = new HashMap<>();
|
||||
|
||||
private class SkinCacheEntry extends ConcurrentLazyLoader<byte[]> {
|
||||
|
||||
protected final String key;
|
||||
|
||||
protected SkinCacheEntry(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void loadImpl(Consumer<byte[]> callback) {
|
||||
datastore.loadSkin(key, (data) -> {
|
||||
if (data != null) {
|
||||
callback.accept(data);
|
||||
} else {
|
||||
downloader.downloadSkin(key, (ddata) -> {
|
||||
if (ddata != null) {
|
||||
datastore.storeSkin(key, ddata);
|
||||
callback.accept(ddata);
|
||||
} else {
|
||||
long millis = System.nanoTime() / 1000000l;
|
||||
failedSkinLookupsLock.writeLock().lock();
|
||||
try {
|
||||
failedSkinLookups.put(key, millis);
|
||||
} finally {
|
||||
failedSkinLookupsLock.writeLock().unlock();
|
||||
}
|
||||
callback.accept(ISkinCacheService.ERROR);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ILoggerAdapter getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private class CapeCacheEntry extends ConcurrentLazyLoader<byte[]> {
|
||||
|
||||
protected final String key;
|
||||
|
||||
protected CapeCacheEntry(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void loadImpl(Consumer<byte[]> callback) {
|
||||
datastore.loadCape(key, (data) -> {
|
||||
if (data != null) {
|
||||
callback.accept(data);
|
||||
} else {
|
||||
downloader.downloadCape(key, (ddata) -> {
|
||||
if (ddata != null) {
|
||||
datastore.storeCape(key, ddata);
|
||||
callback.accept(ddata);
|
||||
} else {
|
||||
long millis = System.nanoTime() / 1000000l;
|
||||
failedCapeLookupsLock.writeLock().lock();
|
||||
try {
|
||||
failedCapeLookups.put(key, millis);
|
||||
} finally {
|
||||
failedCapeLookupsLock.writeLock().unlock();
|
||||
}
|
||||
callback.accept(ISkinCacheService.ERROR);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ILoggerAdapter getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public SkinCacheService(ISkinCacheDownloader downloader, ISkinCacheDatastore datastore, int expireAfterSec,
|
||||
int maxSize, ILoggerAdapter logger) {
|
||||
this(downloader, datastore, expireAfterSec, Math.min(256, maxSize), maxSize, logger);
|
||||
}
|
||||
|
||||
public SkinCacheService(ISkinCacheDownloader downloader, ISkinCacheDatastore datastore, int expireAfterSec,
|
||||
int initialSize, int maxSize, ILoggerAdapter logger) {
|
||||
this.logger = logger;
|
||||
this.downloader = downloader;
|
||||
this.datastore = datastore;
|
||||
this.skinCache = CacheBuilder.newBuilder().expireAfterAccess(expireAfterSec, TimeUnit.SECONDS)
|
||||
.initialCapacity(initialSize).maximumSize(maxSize).concurrencyLevel(16)
|
||||
.build(new CacheLoader<String, ConcurrentLazyLoader<byte[]>>() {
|
||||
@Override
|
||||
public ConcurrentLazyLoader<byte[]> load(String key) throws Exception {
|
||||
return new SkinCacheEntry(key);
|
||||
}
|
||||
});
|
||||
this.capeCache = CacheBuilder.newBuilder().expireAfterAccess(expireAfterSec, TimeUnit.SECONDS)
|
||||
.initialCapacity(initialSize).maximumSize(maxSize).concurrencyLevel(16)
|
||||
.build(new CacheLoader<String, ConcurrentLazyLoader<byte[]>>() {
|
||||
@Override
|
||||
public ConcurrentLazyLoader<byte[]> load(String key) throws Exception {
|
||||
return new CapeCacheEntry(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resolveSkinByURL(String skinURL, Consumer<byte[]> callback) {
|
||||
failedSkinLookupsLock.readLock().lock();
|
||||
boolean b;
|
||||
try {
|
||||
b = failedSkinLookups.containsKey(skinURL);
|
||||
} finally {
|
||||
failedSkinLookupsLock.readLock().unlock();
|
||||
}
|
||||
if (b) {
|
||||
callback.accept(ISkinCacheService.ERROR);
|
||||
} else {
|
||||
try {
|
||||
skinCache.get(skinURL).load(callback);
|
||||
} catch (ExecutionException e) {
|
||||
callback.accept(ISkinCacheService.ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resolveCapeByURL(String capeURL, Consumer<byte[]> callback) {
|
||||
failedCapeLookupsLock.readLock().lock();
|
||||
boolean b;
|
||||
try {
|
||||
b = failedCapeLookups.containsKey(capeURL);
|
||||
} finally {
|
||||
failedCapeLookupsLock.readLock().unlock();
|
||||
}
|
||||
if (b) {
|
||||
callback.accept(ISkinCacheService.ERROR);
|
||||
} else {
|
||||
try {
|
||||
capeCache.get(capeURL).load(callback);
|
||||
} catch (ExecutionException e) {
|
||||
callback.accept(ISkinCacheService.ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
datastore.tick();
|
||||
long millis = System.nanoTime() / 1000000l;
|
||||
if (millis - lastFlush > 60000l) {
|
||||
lastFlush = millis;
|
||||
failedSkinLookupsLock.writeLock().lock();
|
||||
try {
|
||||
Iterator<Long> itr = failedSkinLookups.values().iterator();
|
||||
while (itr.hasNext()) {
|
||||
if (millis - itr.next().longValue() > (60000l * 10l)) {
|
||||
itr.remove();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
failedSkinLookupsLock.writeLock().unlock();
|
||||
}
|
||||
failedCapeLookupsLock.writeLock().lock();
|
||||
try {
|
||||
Iterator<Long> itr = failedCapeLookups.values().iterator();
|
||||
while (itr.hasNext()) {
|
||||
if (millis - itr.next().longValue() > (60000l * 10l)) {
|
||||
itr.remove();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
failedCapeLookupsLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTotalMemorySkins() {
|
||||
return (int) skinCache.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTotalMemoryCapes() {
|
||||
return (int) capeCache.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTotalStoredSkins() {
|
||||
return datastore.getTotalStoredSkins();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTotalStoredCapes() {
|
||||
return datastore.getTotalStoredCapes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disposes the datastore (worker threads, zlib state, PreparedStatements).
|
||||
* Must be called BEFORE the JDBC connection is closed. Without this, every
|
||||
* /reload or PlugMan toggle leaks the datastore worker threads.
|
||||
*/
|
||||
public void dispose() {
|
||||
try {
|
||||
datastore.dispose();
|
||||
} catch (Throwable t) {
|
||||
logger.error("SkinCacheService.dispose() failed", t);
|
||||
}
|
||||
skinCache.invalidateAll();
|
||||
capeCache.invalidateAll();
|
||||
failedSkinLookupsLock.writeLock().lock();
|
||||
try {
|
||||
failedSkinLookups.clear();
|
||||
} finally {
|
||||
failedSkinLookupsLock.writeLock().unlock();
|
||||
}
|
||||
failedCapeLookupsLock.writeLock().lock();
|
||||
try {
|
||||
failedCapeLookups.clear();
|
||||
} finally {
|
||||
failedCapeLookupsLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.skin_cache;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Date;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.util.ILoggerAdapter;
|
||||
|
||||
class SkinCacheTable {
|
||||
|
||||
class SkinCacheTableThreadEnv {
|
||||
|
||||
protected final PreparedStatement statementLoad;
|
||||
protected final PreparedStatement statementStore;
|
||||
protected final PreparedStatement statementStoreIndex;
|
||||
|
||||
protected SkinCacheTableThreadEnv(Connection conn) throws SQLException {
|
||||
statementLoad = conn.prepareStatement("SELECT " + name + "_objects.TextureData " + "FROM " + name
|
||||
+ "_objects " + "INNER JOIN " + name + "_indices ON " + name + "_objects.TextureID = " + name
|
||||
+ "_indices.TextureData " + "WHERE " + name + "_indices.TextureURL = ?");
|
||||
if (sqlite) {
|
||||
statementStore = conn.prepareStatement("INSERT OR IGNORE INTO " + name
|
||||
+ "_objects (TextureTime, TextureHash, TextureData) " + "VALUES(?, ?, ?)");
|
||||
statementStoreIndex = conn
|
||||
.prepareStatement("INSERT OR REPLACE INTO " + name + "_indices (TextureURL, TextureData) "
|
||||
+ "SELECT ?, TextureID FROM " + name + "_objects WHERE TextureHash = ?");
|
||||
} else {
|
||||
statementStore = conn.prepareStatement("INSERT IGNORE INTO " + name
|
||||
+ "_objects (TextureTime, TextureHash, TextureData) " + "VALUES(?, ?, ?)");
|
||||
statementStoreIndex = conn
|
||||
.prepareStatement("REPLACE INTO " + name + "_indices (TextureURL, TextureData) "
|
||||
+ "SELECT ?, TextureID FROM " + name + "_objects WHERE TextureHash = ?");
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
SkinCacheDatastore.disposeStmt(statementLoad);
|
||||
SkinCacheDatastore.disposeStmt(statementStore);
|
||||
SkinCacheDatastore.disposeStmt(statementStoreIndex);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected final String name;
|
||||
protected final boolean sqlite;
|
||||
protected final ILoggerAdapter logger;
|
||||
protected final Object writeLock;
|
||||
|
||||
protected final PreparedStatement statementCount;
|
||||
|
||||
// for sqlite databases
|
||||
protected final PreparedStatement statementSQLiteListExpired;
|
||||
protected final PreparedStatement statementSQLiteListOld;
|
||||
protected final PreparedStatement statementSQLiteDeleteObject;
|
||||
protected final PreparedStatement statementSQLiteDeleteIndex;
|
||||
|
||||
// for non-sqlite databases
|
||||
protected final PreparedStatement statementDeleteExpired;
|
||||
protected final PreparedStatement statementDeleteOld;
|
||||
|
||||
SkinCacheTable(String name, Connection conn, boolean sqlite, ILoggerAdapter logger, Object writeLock) throws SQLException {
|
||||
this.name = name;
|
||||
this.sqlite = sqlite;
|
||||
this.logger = logger;
|
||||
this.writeLock = writeLock;
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
if (sqlite) {
|
||||
// TextureID will be used by SQLite as rowid
|
||||
stmt.execute("CREATE TABLE IF NOT EXISTS " + name + "_objects (" + "TextureID INTEGER NOT NULL,"
|
||||
+ "TextureTime DATETIME NOT NULL," + "TextureHash BLOB NOT NULL," + "TextureData BLOB NOT NULL,"
|
||||
+ "PRIMARY KEY(TextureID ASC))");
|
||||
} else {
|
||||
stmt.execute("CREATE TABLE IF NOT EXISTS " + name + "_objects ("
|
||||
+ "TextureID BIGINT NOT NULL AUTO_INCREMENT," + "TextureTime DATETIME NOT NULL,"
|
||||
+ "TextureHash BLOB NOT NULL," + "TextureData BLOB NOT NULL," + "PRIMARY KEY(TextureID))");
|
||||
}
|
||||
stmt.execute("CREATE UNIQUE INDEX IF NOT EXISTS " + name + "_hash_index " + "ON " + name
|
||||
+ "_objects (TextureHash)");
|
||||
if (sqlite) {
|
||||
stmt.execute("CREATE TABLE IF NOT EXISTS " + name + "_indices (" + "TextureURL VARCHAR(256) NOT NULL,"
|
||||
+ "TextureData INTEGER NOT NULL," + "PRIMARY KEY(TextureURL))");
|
||||
} else {
|
||||
stmt.execute("CREATE TABLE IF NOT EXISTS " + name + "_indices (" + "TextureURL VARCHAR(256) NOT NULL,"
|
||||
+ "TextureData BIGINT NOT NULL," + "PRIMARY KEY(TextureURL))");
|
||||
}
|
||||
stmt.execute(
|
||||
"CREATE INDEX IF NOT EXISTS " + name + "_indices_index " + "ON " + name + "_indices (TextureData)");
|
||||
}
|
||||
this.statementCount = conn.prepareStatement("SELECT COUNT(*) AS total_skins FROM " + name + "_objects");
|
||||
if (sqlite) {
|
||||
statementSQLiteListExpired = conn
|
||||
.prepareStatement("SELECT TextureID FROM " + name + "_objects WHERE textureTime < ?");
|
||||
statementSQLiteListOld = conn
|
||||
.prepareStatement("SELECT TextureID FROM " + name + "_objects ORDER BY TextureTime ASC LIMIT ?");
|
||||
statementSQLiteDeleteObject = conn.prepareStatement("DELETE FROM " + name + "_objects WHERE TextureID = ?");
|
||||
statementSQLiteDeleteIndex = conn
|
||||
.prepareStatement("DELETE FROM " + name + "_indices WHERE TextureData = ?");
|
||||
statementDeleteExpired = null;
|
||||
statementDeleteOld = null;
|
||||
} else {
|
||||
statementSQLiteListExpired = null;
|
||||
statementSQLiteListOld = null;
|
||||
statementSQLiteDeleteObject = null;
|
||||
statementSQLiteDeleteIndex = null;
|
||||
statementDeleteExpired = conn.prepareStatement("DELETE o, i FROM " + name + "_objects o " + "JOIN " + name
|
||||
+ "_indices i ON o.TextureID = i.TextureData " + "WHERE o.textureTime < ?");
|
||||
statementDeleteOld = conn.prepareStatement("DELETE o, i FROM " + name + "_objects o " + "JOIN " + name
|
||||
+ "_indices i ON o.TextureID = i.TextureData " + "WHERE o.TextureID IN" + "(SELECT TextureID FROM "
|
||||
+ "(SELECT TextureID FROM " + name + "_objects " + "ORDER BY TextureTime ASC LIMIT ?)"
|
||||
+ " AS eagler)");
|
||||
}
|
||||
}
|
||||
|
||||
SkinCacheTableThreadEnv createThreadEnv(Connection conn) throws SQLException {
|
||||
return new SkinCacheTableThreadEnv(conn);
|
||||
}
|
||||
|
||||
byte[] loadSkin(SkinCacheTableThreadEnv env, String skinURL) throws SQLException {
|
||||
PreparedStatement stmt = env.statementLoad;
|
||||
stmt.setString(1, skinURL);
|
||||
byte[] result = null;
|
||||
try (ResultSet set = stmt.executeQuery()) {
|
||||
if (set.next()) {
|
||||
result = set.getBytes(1);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void storeSkin(SkinCacheTableThreadEnv env, String skinURL, byte[] hash, byte[] data) throws SQLException {
|
||||
// both tables can share one JDBC connection across several worker
|
||||
// threads, so the transaction state changes must be serialized
|
||||
synchronized (writeLock) {
|
||||
Connection conn = env.statementStore.getConnection();
|
||||
boolean prevAutoCommit = conn.getAutoCommit();
|
||||
conn.setAutoCommit(false);
|
||||
try {
|
||||
PreparedStatement stmt = env.statementStore;
|
||||
stmt.setDate(1, new Date(System.currentTimeMillis()));
|
||||
stmt.setBytes(2, hash);
|
||||
stmt.setBytes(3, data);
|
||||
stmt.executeUpdate();
|
||||
stmt = env.statementStoreIndex;
|
||||
stmt.setString(1, skinURL);
|
||||
stmt.setBytes(2, hash);
|
||||
stmt.executeUpdate();
|
||||
conn.commit();
|
||||
} catch (SQLException e) {
|
||||
try {
|
||||
conn.rollback();
|
||||
} catch (SQLException re) {
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
try {
|
||||
conn.setAutoCommit(prevAutoCommit);
|
||||
} catch (SQLException ae) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void runCleanup(int maxObjects, long expiryObjectsMillis) throws SQLException {
|
||||
Date expiryObjects = new Date(expiryObjectsMillis);
|
||||
if (sqlite) {
|
||||
statementSQLiteListExpired.setDate(1, expiryObjects);
|
||||
try (ResultSet resultSet = statementSQLiteListExpired.executeQuery()) {
|
||||
while (resultSet.next()) {
|
||||
int id = resultSet.getInt(1);
|
||||
statementSQLiteDeleteObject.setInt(1, id);
|
||||
statementSQLiteDeleteObject.executeUpdate();
|
||||
statementSQLiteDeleteIndex.setInt(1, id);
|
||||
statementSQLiteDeleteIndex.executeUpdate();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
statementDeleteExpired.setDate(1, expiryObjects);
|
||||
statementDeleteExpired.executeUpdate();
|
||||
}
|
||||
int totalSkins;
|
||||
try (ResultSet set = statementCount.executeQuery()) {
|
||||
if (set.next()) {
|
||||
totalSkins = set.getInt(1);
|
||||
} else {
|
||||
throw new SQLException("Empty ResultSet recieved when checking \"" + name + "_objects\" row count");
|
||||
}
|
||||
}
|
||||
if (totalSkins > maxObjects) {
|
||||
int deleteCount = totalSkins - maxObjects + (maxObjects >> 3);
|
||||
logger.warn(name + " object cache has passed " + maxObjects + " skins in size (" + totalSkins
|
||||
+ "), deleting " + deleteCount + " skins from the cache to free space");
|
||||
if (sqlite) {
|
||||
statementSQLiteListOld.setInt(1, deleteCount);
|
||||
try (ResultSet resultSet = statementSQLiteListOld.executeQuery()) {
|
||||
while (resultSet.next()) {
|
||||
int id = resultSet.getInt(1);
|
||||
statementSQLiteDeleteObject.setInt(1, id);
|
||||
statementSQLiteDeleteObject.executeUpdate();
|
||||
statementSQLiteDeleteIndex.setInt(1, id);
|
||||
statementSQLiteDeleteIndex.executeUpdate();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
statementDeleteOld.setInt(1, deleteCount);
|
||||
statementDeleteOld.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int countSkins() {
|
||||
try (ResultSet set = statementCount.executeQuery()) {
|
||||
if (set.next()) {
|
||||
return set.getInt(1);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
logger.error("Could not count stored " + name + "!", ex);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
SkinCacheDatastore.disposeStmt(statementCount);
|
||||
SkinCacheDatastore.disposeStmt(statementSQLiteListExpired);
|
||||
SkinCacheDatastore.disposeStmt(statementSQLiteListOld);
|
||||
SkinCacheDatastore.disposeStmt(statementSQLiteDeleteObject);
|
||||
SkinCacheDatastore.disposeStmt(statementSQLiteDeleteIndex);
|
||||
SkinCacheDatastore.disposeStmt(statementDeleteExpired);
|
||||
SkinCacheDatastore.disposeStmt(statementDeleteOld);
|
||||
}
|
||||
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright (c) 2022-2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.skin_cache;
|
||||
|
||||
public class SkinConverter {
|
||||
|
||||
public static void convertToBytes(int[] imageIn, byte[] imageOut) {
|
||||
for (int i = 0, j, k; i < 4096; ++i) {
|
||||
j = i * 3;
|
||||
k = imageIn[i];
|
||||
imageOut[j] = (byte) k;
|
||||
imageOut[j + 1] = (byte) (k >>> 8);
|
||||
imageOut[j + 2] = (byte) (((k >>> 17) & 0x7F) | ((k >>> 24) & 0x80));
|
||||
}
|
||||
}
|
||||
|
||||
public static void convert64x32To64x64(int[] imageIn, byte[] imageOut) {
|
||||
copyRawPixels(imageIn, imageOut, 0, 0, 0, 0, 64, 32, 64, 64, false);
|
||||
copyRawPixels(imageIn, imageOut, 24, 48, 20, 52, 4, 16, 8, 20, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 28, 48, 24, 52, 8, 16, 12, 20, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 20, 52, 16, 64, 8, 20, 12, 32, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 24, 52, 20, 64, 4, 20, 8, 32, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 28, 52, 24, 64, 0, 20, 4, 32, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 32, 52, 28, 64, 12, 20, 16, 32, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 40, 48, 36, 52, 44, 16, 48, 20, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 44, 48, 40, 52, 48, 16, 52, 20, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 36, 52, 32, 64, 48, 20, 52, 32, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 40, 52, 36, 64, 44, 20, 48, 32, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 44, 52, 40, 64, 40, 20, 44, 32, 64, 64);
|
||||
copyRawPixels(imageIn, imageOut, 48, 52, 44, 64, 52, 20, 56, 32, 64, 64);
|
||||
}
|
||||
|
||||
private static void copyRawPixels(int[] imageIn, byte[] imageOut, int dx1, int dy1, int dx2, int dy2, int sx1,
|
||||
int sy1, int sx2, int sy2, int imgSrcWidth, int imgDstWidth) {
|
||||
if (dx1 > dx2) {
|
||||
copyRawPixels(imageIn, imageOut, sx1, sy1, dx2, dy1, sx2 - sx1, sy2 - sy1, imgSrcWidth, imgDstWidth, true);
|
||||
} else {
|
||||
copyRawPixels(imageIn, imageOut, sx1, sy1, dx1, dy1, sx2 - sx1, sy2 - sy1, imgSrcWidth, imgDstWidth, false);
|
||||
}
|
||||
}
|
||||
|
||||
private static void copyRawPixels(int[] imageIn, byte[] imageOut, int srcX, int srcY, int dstX, int dstY, int width,
|
||||
int height, int imgSrcWidth, int imgDstWidth, boolean flip) {
|
||||
int i, j;
|
||||
for (int y = 0; y < height; ++y) {
|
||||
for (int x = 0; x < width; ++x) {
|
||||
i = imageIn[(srcY + y) * imgSrcWidth + srcX + x];
|
||||
if (flip) {
|
||||
j = (dstY + y) * imgDstWidth + dstX + width - x - 1;
|
||||
} else {
|
||||
j = (dstY + y) * imgDstWidth + dstX + x;
|
||||
}
|
||||
j = j * 3;
|
||||
imageOut[j] = (byte) i;
|
||||
imageOut[j + 1] = (byte) (i >>> 8);
|
||||
imageOut[j + 2] = (byte) (((i >>> 17) & 0x7F) | ((i >>> 24) & 0x80));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void convertCape64x32RGBAto23x17RGB(int[] skinIn, byte[] skinOut) {
|
||||
int i, j;
|
||||
for (int y = 0; y < 17; ++y) {
|
||||
for (int x = 0; x < 22; ++x) {
|
||||
i = skinIn[y * 64 + x];
|
||||
j = (y * 23 + x) * 3;
|
||||
skinOut[j] = (byte) i;
|
||||
skinOut[j + 1] = (byte) (i >>> 8);
|
||||
skinOut[j + 2] = (byte) (i >>> 16);
|
||||
}
|
||||
}
|
||||
for (int y = 0; y < 11; ++y) {
|
||||
i = skinIn[(y + 11) * 64 + 22];
|
||||
j = ((y + 6) * 23 + 22) * 3;
|
||||
skinOut[j] = (byte) i;
|
||||
skinOut[j + 1] = (byte) (i >>> 8);
|
||||
skinOut[j + 2] = (byte) (i >>> 16);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* Decompiled with CFR 0.152.
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import net.lax1dude.eaglercraft.backend.util.ILoggerAdapter;
|
||||
|
||||
public abstract class ConcurrentLazyLoader<T> {
|
||||
private List<Consumer<T>> waitingCallbacks = null;
|
||||
private volatile T result = null;
|
||||
|
||||
protected abstract void loadImpl(Consumer<T> var1);
|
||||
|
||||
protected abstract ILoggerAdapter getLogger();
|
||||
|
||||
/*
|
||||
* WARNING - Removed try catching itself - possible behaviour change.
|
||||
*/
|
||||
public void load(Consumer<T> callback) {
|
||||
T val = this.result;
|
||||
if (val != null) {
|
||||
callback.accept(val);
|
||||
} else {
|
||||
ConcurrentLazyLoader concurrentLazyLoader = this;
|
||||
synchronized (concurrentLazyLoader) {
|
||||
val = this.result;
|
||||
if (val != null) {
|
||||
} else {
|
||||
if (this.waitingCallbacks != null) {
|
||||
this.waitingCallbacks.add(callback);
|
||||
return;
|
||||
}
|
||||
this.waitingCallbacks = new ArrayList<Consumer<T>>();
|
||||
this.waitingCallbacks.add(callback);
|
||||
}
|
||||
}
|
||||
if (val != null) {
|
||||
callback.accept(val);
|
||||
return;
|
||||
}
|
||||
this.loadImpl(res -> {
|
||||
List<Consumer<T>> toCall;
|
||||
if (res == null) {
|
||||
throw new NullPointerException("result must not be null");
|
||||
}
|
||||
synchronized (this) {
|
||||
if (this.result != null) {
|
||||
return;
|
||||
}
|
||||
this.result = res;
|
||||
toCall = this.waitingCallbacks;
|
||||
this.waitingCallbacks = null;
|
||||
}
|
||||
if (toCall != null) {
|
||||
int l = toCall.size();
|
||||
for (int i = 0; i < l; ++i) {
|
||||
try {
|
||||
toCall.get(i).accept(res);
|
||||
continue;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
this.getLogger().error("Caught error from lazy load callback", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public T getIfLoaded() {
|
||||
return this.result;
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
this.result = null;
|
||||
}
|
||||
}
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* Decompiled with CFR 0.152.
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.sql.Connection;
|
||||
import java.sql.Driver;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import net.lax1dude.eaglercraft.backend.util.ILoggerAdapter;
|
||||
|
||||
public class EaglerDrivers {
|
||||
private static final Map<String, ClassLoader> driversJARs = new HashMap<String, ClassLoader>();
|
||||
private static final Map<String, Driver> driversDrivers = new HashMap<String, Driver>();
|
||||
|
||||
private static Driver initializeDriver(String address, String driverClass, File baseFolder, ILoggerAdapter logger) {
|
||||
Class<?> loadedDriver;
|
||||
ClassLoader classLoader;
|
||||
if (address.equalsIgnoreCase("classpath")) {
|
||||
classLoader = EaglerDrivers.class.getClassLoader();
|
||||
} else {
|
||||
classLoader = driversJARs.get(address);
|
||||
if (classLoader == null) {
|
||||
URL driverURL;
|
||||
File driver;
|
||||
if (address.equalsIgnoreCase("internal")) {
|
||||
driver = new File(baseFolder, "drivers/sqlite-jdbc.jar");
|
||||
driver.getParentFile().mkdirs();
|
||||
if (!driver.isFile()) {
|
||||
try (InputStream is = EaglerDrivers.class.getResourceAsStream("/net/lax1dude/eaglercraft/backend/skin_cache/libs/sqlite-jdbc.library");){
|
||||
if (is == null) {
|
||||
throw new IOException("Missing classpath resource: net/lax1dude/eaglercraft/backend/skin_cache/libs/sqlite-jdbc.library");
|
||||
}
|
||||
try (FileOutputStream os = new FileOutputStream(driver);){
|
||||
int n;
|
||||
byte[] buf = new byte[8192];
|
||||
while ((n = is.read(buf)) != -1) {
|
||||
((OutputStream)os).write(buf, 0, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
driver = new File(address);
|
||||
}
|
||||
try {
|
||||
driverURL = driver.toURI().toURL();
|
||||
}
|
||||
catch (MalformedURLException ex) {
|
||||
logger.error("Invalid JDBC driver path: " + address);
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
classLoader = URLClassLoader.newInstance(new URL[]{driverURL}, ClassLoader.getSystemClassLoader());
|
||||
driversJARs.put(address, classLoader);
|
||||
}
|
||||
}
|
||||
try {
|
||||
loadedDriver = classLoader.loadClass(driverClass);
|
||||
}
|
||||
catch (ClassNotFoundException ex) {
|
||||
logger.error("Could not find JDBC driver class: " + driverClass);
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
Driver sqlDriver = null;
|
||||
try {
|
||||
sqlDriver = (Driver)loadedDriver.getConstructor(new Class[0]).newInstance(new Object[0]);
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
logger.error("Could not initialize JDBC driver class: " + driverClass);
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
return sqlDriver;
|
||||
}
|
||||
|
||||
public static Connection[] connectToDatabase(String address, String driverClass, String driverPath, Properties props, File baseFolder, ILoggerAdapter logger, int count) throws SQLException {
|
||||
Connection[] arr;
|
||||
block12: {
|
||||
if (driverClass.equalsIgnoreCase("internal")) {
|
||||
driverClass = "org.sqlite.JDBC";
|
||||
}
|
||||
arr = new Connection[count];
|
||||
try {
|
||||
if (driverPath == null) {
|
||||
try {
|
||||
Class.forName(driverClass);
|
||||
}
|
||||
catch (ClassNotFoundException e) {
|
||||
throw new SQLException("Driver class not found in JRE: " + driverClass, e);
|
||||
}
|
||||
for (int i = 0; i < count; ++i) {
|
||||
arr[i] = DriverManager.getConnection(address, props);
|
||||
}
|
||||
break block12;
|
||||
}
|
||||
String driverMapPath = "" + driverPath + "?" + driverClass;
|
||||
Driver dv = driversDrivers.get(driverMapPath);
|
||||
if (dv == null) {
|
||||
dv = EaglerDrivers.initializeDriver(driverPath, driverClass, baseFolder, logger);
|
||||
driversDrivers.put(driverMapPath, dv);
|
||||
}
|
||||
for (int i = 0; i < count; ++i) {
|
||||
arr[i] = dv.connect(address, props);
|
||||
}
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
for (int i = 0; i < count; ++i) {
|
||||
if (arr[i] == null) continue;
|
||||
try {
|
||||
arr[i].close();
|
||||
continue;
|
||||
}
|
||||
catch (SQLException exx) {
|
||||
ex.addSuppressed(exx);
|
||||
}
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
}
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.util;
|
||||
|
||||
public interface ILoggerAdapter {
|
||||
|
||||
void info(String msg);
|
||||
|
||||
void info(String msg, Throwable thrown);
|
||||
|
||||
void warn(String msg);
|
||||
|
||||
void warn(String msg, Throwable thrown);
|
||||
|
||||
void error(String msg);
|
||||
|
||||
void error(String msg, Throwable thrown);
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.util;
|
||||
|
||||
public class SteadyTime {
|
||||
|
||||
public static long millis() {
|
||||
return System.nanoTime() / 1000000l;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user