mirror of
https://github.com/Grasscutters/Grasscutter.git
synced 2025-12-22 03:45:10 +01:00
Run Spotless on src/main
This commit is contained in:
@@ -1,35 +1,33 @@
|
||||
package emu.grasscutter.server.http;
|
||||
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.Handler;
|
||||
|
||||
/**
|
||||
* Defines routes for an {@link Javalin} instance.
|
||||
*/
|
||||
public interface Router {
|
||||
|
||||
/**
|
||||
* Called when the router is initialized by Express.
|
||||
*
|
||||
* @param javalin A Javalin instance.
|
||||
*/
|
||||
void applyRoutes(Javalin javalin);
|
||||
|
||||
/**
|
||||
* Applies this handler to all endpoint types
|
||||
*
|
||||
* @param javalin A Javalin instance.
|
||||
* @param path
|
||||
* @param ctx
|
||||
* @return The Javalin instance.
|
||||
*/
|
||||
default Javalin allRoutes(Javalin javalin, String path, Handler ctx) {
|
||||
javalin.get(path, ctx);
|
||||
javalin.post(path, ctx);
|
||||
javalin.put(path, ctx);
|
||||
javalin.patch(path, ctx);
|
||||
javalin.delete(path, ctx);
|
||||
|
||||
return javalin;
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http;
|
||||
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.Handler;
|
||||
|
||||
/** Defines routes for an {@link Javalin} instance. */
|
||||
public interface Router {
|
||||
|
||||
/**
|
||||
* Called when the router is initialized by Express.
|
||||
*
|
||||
* @param javalin A Javalin instance.
|
||||
*/
|
||||
void applyRoutes(Javalin javalin);
|
||||
|
||||
/**
|
||||
* Applies this handler to all endpoint types
|
||||
*
|
||||
* @param javalin A Javalin instance.
|
||||
* @param path
|
||||
* @param ctx
|
||||
* @return The Javalin instance.
|
||||
*/
|
||||
default Javalin allRoutes(Javalin javalin, String path, Handler ctx) {
|
||||
javalin.get(path, ctx);
|
||||
javalin.post(path, ctx);
|
||||
javalin.put(path, ctx);
|
||||
javalin.patch(path, ctx);
|
||||
javalin.delete(path, ctx);
|
||||
|
||||
return javalin;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,130 +1,160 @@
|
||||
package emu.grasscutter.server.http.dispatch;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.auth.AuthenticationSystem;
|
||||
import emu.grasscutter.auth.OAuthAuthenticator.ClientType;
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import emu.grasscutter.server.http.objects.ComboTokenReqJson;
|
||||
import emu.grasscutter.server.http.objects.ComboTokenReqJson.LoginTokenData;
|
||||
import emu.grasscutter.server.http.objects.LoginAccountRequestJson;
|
||||
import emu.grasscutter.server.http.objects.LoginTokenRequestJson;
|
||||
import emu.grasscutter.utils.JsonUtils;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.Context;
|
||||
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
|
||||
/**
|
||||
* Handles requests related to authentication. (aka dispatch)
|
||||
*/
|
||||
public final class DispatchHandler implements Router {
|
||||
/**
|
||||
* @route /hk4e_global/mdk/shield/api/login
|
||||
*/
|
||||
private static void clientLogin(Context ctx) {
|
||||
// Parse body data.
|
||||
String rawBodyData = ctx.body();
|
||||
var bodyData = JsonUtils.decode(rawBodyData, LoginAccountRequestJson.class);
|
||||
|
||||
// Validate body data.
|
||||
if (bodyData == null)
|
||||
return;
|
||||
|
||||
// Pass data to authentication handler.
|
||||
var responseData = Grasscutter.getAuthenticationSystem()
|
||||
.getPasswordAuthenticator()
|
||||
.authenticate(AuthenticationSystem.fromPasswordRequest(ctx, bodyData));
|
||||
// Send response.
|
||||
ctx.json(responseData);
|
||||
|
||||
// Log to console.
|
||||
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", ctx.ip()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @route /hk4e_global/mdk/shield/api/verify
|
||||
*/
|
||||
private static void tokenLogin(Context ctx) {
|
||||
// Parse body data.
|
||||
String rawBodyData = ctx.body();
|
||||
var bodyData = JsonUtils.decode(rawBodyData, LoginTokenRequestJson.class);
|
||||
|
||||
// Validate body data.
|
||||
if (bodyData == null)
|
||||
return;
|
||||
|
||||
// Pass data to authentication handler.
|
||||
var responseData = Grasscutter.getAuthenticationSystem()
|
||||
.getTokenAuthenticator()
|
||||
.authenticate(AuthenticationSystem.fromTokenRequest(ctx, bodyData));
|
||||
// Send response.
|
||||
ctx.json(responseData);
|
||||
|
||||
// Log to console.
|
||||
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", ctx.ip()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @route /hk4e_global/combo/granter/login/v2/login
|
||||
*/
|
||||
private static void sessionKeyLogin(Context ctx) {
|
||||
// Parse body data.
|
||||
String rawBodyData = ctx.body();
|
||||
var bodyData = JsonUtils.decode(rawBodyData, ComboTokenReqJson.class);
|
||||
|
||||
// Validate body data.
|
||||
if (bodyData == null || bodyData.data == null)
|
||||
return;
|
||||
|
||||
// Decode additional body data.
|
||||
var tokenData = JsonUtils.decode(bodyData.data, LoginTokenData.class);
|
||||
|
||||
// Pass data to authentication handler.
|
||||
var responseData = Grasscutter.getAuthenticationSystem()
|
||||
.getSessionKeyAuthenticator()
|
||||
.authenticate(AuthenticationSystem.fromComboTokenRequest(ctx, bodyData, tokenData));
|
||||
// Send response.
|
||||
ctx.json(responseData);
|
||||
|
||||
// Log to console.
|
||||
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", ctx.ip()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
// OS
|
||||
// Username & Password login (from client).
|
||||
javalin.post("/hk4e_global/mdk/shield/api/login", DispatchHandler::clientLogin);
|
||||
// Cached token login (from registry).
|
||||
javalin.post("/hk4e_global/mdk/shield/api/verify", DispatchHandler::tokenLogin);
|
||||
// Combo token login (from session key).
|
||||
javalin.post("/hk4e_global/combo/granter/login/v2/login", DispatchHandler::sessionKeyLogin);
|
||||
|
||||
// CN
|
||||
// Username & Password login (from client).
|
||||
javalin.post("/hk4e_cn/mdk/shield/api/login", DispatchHandler::clientLogin);
|
||||
// Cached token login (from registry).
|
||||
javalin.post("/hk4e_cn/mdk/shield/api/verify", DispatchHandler::tokenLogin);
|
||||
// Combo token login (from session key).
|
||||
javalin.post("/hk4e_cn/combo/granter/login/v2/login", DispatchHandler::sessionKeyLogin);
|
||||
|
||||
// External login (from other clients).
|
||||
javalin.get("/authentication/type", ctx -> ctx.result(Grasscutter.getAuthenticationSystem().getClass().getSimpleName()));
|
||||
javalin.post("/authentication/login", ctx -> Grasscutter.getAuthenticationSystem().getExternalAuthenticator()
|
||||
.handleLogin(AuthenticationSystem.fromExternalRequest(ctx)));
|
||||
javalin.post("/authentication/register", ctx -> Grasscutter.getAuthenticationSystem().getExternalAuthenticator()
|
||||
.handleAccountCreation(AuthenticationSystem.fromExternalRequest(ctx)));
|
||||
javalin.post("/authentication/change_password", ctx -> Grasscutter.getAuthenticationSystem().getExternalAuthenticator()
|
||||
.handlePasswordReset(AuthenticationSystem.fromExternalRequest(ctx)));
|
||||
|
||||
// External login (from OAuth2).
|
||||
javalin.post("/hk4e_global/mdk/shield/api/loginByThirdparty", ctx -> Grasscutter.getAuthenticationSystem().getOAuthAuthenticator()
|
||||
.handleLogin(AuthenticationSystem.fromExternalRequest(ctx)));
|
||||
javalin.get("/authentication/openid/redirect", ctx -> Grasscutter.getAuthenticationSystem().getOAuthAuthenticator()
|
||||
.handleTokenProcess(AuthenticationSystem.fromExternalRequest(ctx)));
|
||||
javalin.get("/Api/twitter_login", ctx -> Grasscutter.getAuthenticationSystem().getOAuthAuthenticator()
|
||||
.handleRedirection(AuthenticationSystem.fromExternalRequest(ctx), ClientType.DESKTOP));
|
||||
javalin.get("/sdkTwitterLogin.html", ctx -> Grasscutter.getAuthenticationSystem().getOAuthAuthenticator()
|
||||
.handleRedirection(AuthenticationSystem.fromExternalRequest(ctx), ClientType.MOBILE));
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.dispatch;
|
||||
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.auth.AuthenticationSystem;
|
||||
import emu.grasscutter.auth.OAuthAuthenticator.ClientType;
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import emu.grasscutter.server.http.objects.ComboTokenReqJson;
|
||||
import emu.grasscutter.server.http.objects.ComboTokenReqJson.LoginTokenData;
|
||||
import emu.grasscutter.server.http.objects.LoginAccountRequestJson;
|
||||
import emu.grasscutter.server.http.objects.LoginTokenRequestJson;
|
||||
import emu.grasscutter.utils.JsonUtils;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.Context;
|
||||
|
||||
/** Handles requests related to authentication. (aka dispatch) */
|
||||
public final class DispatchHandler implements Router {
|
||||
/**
|
||||
* @route /hk4e_global/mdk/shield/api/login
|
||||
*/
|
||||
private static void clientLogin(Context ctx) {
|
||||
// Parse body data.
|
||||
String rawBodyData = ctx.body();
|
||||
var bodyData = JsonUtils.decode(rawBodyData, LoginAccountRequestJson.class);
|
||||
|
||||
// Validate body data.
|
||||
if (bodyData == null) return;
|
||||
|
||||
// Pass data to authentication handler.
|
||||
var responseData =
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getPasswordAuthenticator()
|
||||
.authenticate(AuthenticationSystem.fromPasswordRequest(ctx, bodyData));
|
||||
// Send response.
|
||||
ctx.json(responseData);
|
||||
|
||||
// Log to console.
|
||||
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", ctx.ip()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @route /hk4e_global/mdk/shield/api/verify
|
||||
*/
|
||||
private static void tokenLogin(Context ctx) {
|
||||
// Parse body data.
|
||||
String rawBodyData = ctx.body();
|
||||
var bodyData = JsonUtils.decode(rawBodyData, LoginTokenRequestJson.class);
|
||||
|
||||
// Validate body data.
|
||||
if (bodyData == null) return;
|
||||
|
||||
// Pass data to authentication handler.
|
||||
var responseData =
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getTokenAuthenticator()
|
||||
.authenticate(AuthenticationSystem.fromTokenRequest(ctx, bodyData));
|
||||
// Send response.
|
||||
ctx.json(responseData);
|
||||
|
||||
// Log to console.
|
||||
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", ctx.ip()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @route /hk4e_global/combo/granter/login/v2/login
|
||||
*/
|
||||
private static void sessionKeyLogin(Context ctx) {
|
||||
// Parse body data.
|
||||
String rawBodyData = ctx.body();
|
||||
var bodyData = JsonUtils.decode(rawBodyData, ComboTokenReqJson.class);
|
||||
|
||||
// Validate body data.
|
||||
if (bodyData == null || bodyData.data == null) return;
|
||||
|
||||
// Decode additional body data.
|
||||
var tokenData = JsonUtils.decode(bodyData.data, LoginTokenData.class);
|
||||
|
||||
// Pass data to authentication handler.
|
||||
var responseData =
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getSessionKeyAuthenticator()
|
||||
.authenticate(AuthenticationSystem.fromComboTokenRequest(ctx, bodyData, tokenData));
|
||||
// Send response.
|
||||
ctx.json(responseData);
|
||||
|
||||
// Log to console.
|
||||
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", ctx.ip()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
// OS
|
||||
// Username & Password login (from client).
|
||||
javalin.post("/hk4e_global/mdk/shield/api/login", DispatchHandler::clientLogin);
|
||||
// Cached token login (from registry).
|
||||
javalin.post("/hk4e_global/mdk/shield/api/verify", DispatchHandler::tokenLogin);
|
||||
// Combo token login (from session key).
|
||||
javalin.post("/hk4e_global/combo/granter/login/v2/login", DispatchHandler::sessionKeyLogin);
|
||||
|
||||
// CN
|
||||
// Username & Password login (from client).
|
||||
javalin.post("/hk4e_cn/mdk/shield/api/login", DispatchHandler::clientLogin);
|
||||
// Cached token login (from registry).
|
||||
javalin.post("/hk4e_cn/mdk/shield/api/verify", DispatchHandler::tokenLogin);
|
||||
// Combo token login (from session key).
|
||||
javalin.post("/hk4e_cn/combo/granter/login/v2/login", DispatchHandler::sessionKeyLogin);
|
||||
|
||||
// External login (from other clients).
|
||||
javalin.get(
|
||||
"/authentication/type",
|
||||
ctx -> ctx.result(Grasscutter.getAuthenticationSystem().getClass().getSimpleName()));
|
||||
javalin.post(
|
||||
"/authentication/login",
|
||||
ctx ->
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getExternalAuthenticator()
|
||||
.handleLogin(AuthenticationSystem.fromExternalRequest(ctx)));
|
||||
javalin.post(
|
||||
"/authentication/register",
|
||||
ctx ->
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getExternalAuthenticator()
|
||||
.handleAccountCreation(AuthenticationSystem.fromExternalRequest(ctx)));
|
||||
javalin.post(
|
||||
"/authentication/change_password",
|
||||
ctx ->
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getExternalAuthenticator()
|
||||
.handlePasswordReset(AuthenticationSystem.fromExternalRequest(ctx)));
|
||||
|
||||
// External login (from OAuth2).
|
||||
javalin.post(
|
||||
"/hk4e_global/mdk/shield/api/loginByThirdparty",
|
||||
ctx ->
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getOAuthAuthenticator()
|
||||
.handleLogin(AuthenticationSystem.fromExternalRequest(ctx)));
|
||||
javalin.get(
|
||||
"/authentication/openid/redirect",
|
||||
ctx ->
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getOAuthAuthenticator()
|
||||
.handleTokenProcess(AuthenticationSystem.fromExternalRequest(ctx)));
|
||||
javalin.get(
|
||||
"/Api/twitter_login",
|
||||
ctx ->
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getOAuthAuthenticator()
|
||||
.handleRedirection(
|
||||
AuthenticationSystem.fromExternalRequest(ctx), ClientType.DESKTOP));
|
||||
javalin.get(
|
||||
"/sdkTwitterLogin.html",
|
||||
ctx ->
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getOAuthAuthenticator()
|
||||
.handleRedirection(
|
||||
AuthenticationSystem.fromExternalRequest(ctx), ClientType.MOBILE));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,304 +1,330 @@
|
||||
package emu.grasscutter.server.http.dispatch;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.Grasscutter.ServerRunMode;
|
||||
import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp;
|
||||
import emu.grasscutter.net.proto.QueryRegionListHttpRspOuterClass.QueryRegionListHttpRsp;
|
||||
import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo;
|
||||
import emu.grasscutter.net.proto.RegionSimpleInfoOuterClass.RegionSimpleInfo;
|
||||
import emu.grasscutter.server.event.dispatch.QueryAllRegionsEvent;
|
||||
import emu.grasscutter.server.event.dispatch.QueryCurrentRegionEvent;
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import emu.grasscutter.server.http.objects.QueryCurRegionRspJson;
|
||||
import emu.grasscutter.utils.Crypto;
|
||||
import emu.grasscutter.utils.Utils;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.Context;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.security.Signature;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.*;
|
||||
|
||||
/**
|
||||
* Handles requests related to region queries.
|
||||
*/
|
||||
public final class RegionHandler implements Router {
|
||||
private static final Map<String, RegionData> regions = new ConcurrentHashMap<>();
|
||||
private static String regionListResponse;
|
||||
private static String regionListResponsecn;
|
||||
|
||||
public RegionHandler() {
|
||||
try { // Read & initialize region data.
|
||||
this.initialize();
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().error("Failed to initialize region data.", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle query region list request.
|
||||
*
|
||||
* @param ctx The context object for handling the request.
|
||||
* @route /query_region_list
|
||||
*/
|
||||
private static void queryRegionList(Context ctx) {
|
||||
// Get logger and query parameters.
|
||||
Logger logger = Grasscutter.getLogger();
|
||||
if (ctx.queryParamMap().containsKey("version") && ctx.queryParamMap().containsKey("platform")) {
|
||||
String versionName = ctx.queryParam("version");
|
||||
String versionCode = versionName.replaceAll("[/.0-9]*", "");
|
||||
String platformName = ctx.queryParam("platform");
|
||||
|
||||
// Determine the region list to use based on the version and platform.
|
||||
if ("CNRELiOS".equals(versionCode) || "CNRELWin".equals(versionCode)
|
||||
|| "CNRELAndroid".equals(versionCode)) {
|
||||
// Use the CN region list.
|
||||
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponsecn);
|
||||
event.call();
|
||||
logger.debug("Connect to Chinese version");
|
||||
|
||||
// Respond with the event result.
|
||||
ctx.result(event.getRegionList());
|
||||
} else if ("OSRELiOS".equals(versionCode) || "OSRELWin".equals(versionCode)
|
||||
|| "OSRELAndroid".equals(versionCode)) {
|
||||
// Use the OS region list.
|
||||
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponse);
|
||||
event.call();
|
||||
logger.debug("Connect to global version");
|
||||
|
||||
// Respond with the event result.
|
||||
ctx.result(event.getRegionList());
|
||||
} else {
|
||||
/*
|
||||
* String regionListResponse = "CP///////////wE=";
|
||||
* QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponse);
|
||||
* event.call();
|
||||
* ctx.result(event.getRegionList());
|
||||
* return;
|
||||
*/
|
||||
// Use the default region list.
|
||||
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponse);
|
||||
event.call();
|
||||
logger.debug("Connect to global version");
|
||||
|
||||
// Respond with the event result.
|
||||
ctx.result(event.getRegionList());
|
||||
}
|
||||
} else {
|
||||
// Use the default region list.
|
||||
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponse);
|
||||
event.call();
|
||||
logger.debug("Connect to global version");
|
||||
|
||||
// Respond with the event result.
|
||||
ctx.result(event.getRegionList());
|
||||
}
|
||||
// Log the request to the console.
|
||||
Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", ctx.ip()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @route /query_cur_region/{region}
|
||||
*/
|
||||
private static void queryCurrentRegion(Context ctx) {
|
||||
// Get region to query.
|
||||
String regionName = ctx.pathParam("region");
|
||||
String versionName = ctx.queryParam("version");
|
||||
var region = regions.get(regionName);
|
||||
|
||||
// Get region data.
|
||||
String regionData = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw==";
|
||||
if (ctx.queryParamMap().values().size() > 0) {
|
||||
if (region != null)
|
||||
regionData = region.getBase64();
|
||||
}
|
||||
|
||||
String[] versionCode = versionName.replaceAll(Pattern.compile("[a-zA-Z]").pattern(), "").split("\\.");
|
||||
int versionMajor = Integer.parseInt(versionCode[0]);
|
||||
int versionMinor = Integer.parseInt(versionCode[1]);
|
||||
int versionFix = Integer.parseInt(versionCode[2]);
|
||||
|
||||
if (versionMajor >= 3 || (versionMajor == 2 && versionMinor == 7 && versionFix >= 50) || (versionMajor == 2 && versionMinor == 8)) {
|
||||
try {
|
||||
QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(regionData);
|
||||
event.call();
|
||||
|
||||
if (ctx.queryParam("dispatchSeed") == null) {
|
||||
// More love for UA Patch players
|
||||
var rsp = new QueryCurRegionRspJson();
|
||||
|
||||
rsp.content = event.getRegionInfo();
|
||||
rsp.sign = "TW9yZSBsb3ZlIGZvciBVQSBQYXRjaCBwbGF5ZXJz";
|
||||
|
||||
ctx.json(rsp);
|
||||
return;
|
||||
}
|
||||
|
||||
String key_id = ctx.queryParam("key_id");
|
||||
|
||||
if (key_id == null)
|
||||
throw new Exception("Key ID was not set");
|
||||
|
||||
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, Crypto.EncryptionKeys.get(Integer.valueOf(key_id)));
|
||||
var regionInfo = Utils.base64Decode(event.getRegionInfo());
|
||||
|
||||
//Encrypt regionInfo in chunks
|
||||
ByteArrayOutputStream encryptedRegionInfoStream = new ByteArrayOutputStream();
|
||||
|
||||
//Thank you so much GH Copilot
|
||||
int chunkSize = 256 - 11;
|
||||
int regionInfoLength = regionInfo.length;
|
||||
int numChunks = (int) Math.ceil(regionInfoLength / (double) chunkSize);
|
||||
|
||||
for (int i = 0; i < numChunks; i++) {
|
||||
byte[] chunk = Arrays.copyOfRange(regionInfo, i * chunkSize, Math.min((i + 1) * chunkSize, regionInfoLength));
|
||||
byte[] encryptedChunk = cipher.doFinal(chunk);
|
||||
encryptedRegionInfoStream.write(encryptedChunk);
|
||||
}
|
||||
|
||||
Signature privateSignature = Signature.getInstance("SHA256withRSA");
|
||||
privateSignature.initSign(Crypto.CUR_SIGNING_KEY);
|
||||
privateSignature.update(regionInfo);
|
||||
|
||||
var rsp = new QueryCurRegionRspJson();
|
||||
|
||||
rsp.content = Utils.base64Encode(encryptedRegionInfoStream.toByteArray());
|
||||
rsp.sign = Utils.base64Encode(privateSignature.sign());
|
||||
|
||||
ctx.json(rsp);
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("An error occurred while handling query_cur_region.", e);
|
||||
}
|
||||
} else {
|
||||
// Invoke event.
|
||||
QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(regionData);
|
||||
event.call();
|
||||
// Respond with event result.
|
||||
ctx.result(event.getRegionInfo());
|
||||
}
|
||||
// Log to console.
|
||||
Grasscutter.getLogger().info(String.format("Client %s request: query_cur_region/%s", ctx.ip(), regionName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current region query.
|
||||
*
|
||||
* @return A {@link QueryCurrRegionHttpRsp} object.
|
||||
*/
|
||||
public static QueryCurrRegionHttpRsp getCurrentRegion() {
|
||||
return SERVER.runMode == ServerRunMode.HYBRID ? regions.get("os_usa").getRegionQuery() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures region data according to configuration.
|
||||
*/
|
||||
private void initialize() {
|
||||
String dispatchDomain = "http" + (HTTP_ENCRYPTION.useInRouting ? "s" : "") + "://"
|
||||
+ lr(HTTP_INFO.accessAddress, HTTP_INFO.bindAddress) + ":"
|
||||
+ lr(HTTP_INFO.accessPort, HTTP_INFO.bindPort);
|
||||
|
||||
// Create regions.
|
||||
List<RegionSimpleInfo> servers = new ArrayList<>();
|
||||
List<String> usedNames = new ArrayList<>(); // List to check for potential naming conflicts.
|
||||
|
||||
var configuredRegions = new ArrayList<>(List.of(DISPATCH_INFO.regions));
|
||||
if (SERVER.runMode != ServerRunMode.HYBRID && configuredRegions.size() == 0) {
|
||||
Grasscutter.getLogger().error("[Dispatch] There are no game servers available. Exiting due to unplayable state.");
|
||||
System.exit(1);
|
||||
} else if (configuredRegions.size() == 0)
|
||||
configuredRegions.add(new Region("os_usa", DISPATCH_INFO.defaultName,
|
||||
lr(GAME_INFO.accessAddress, GAME_INFO.bindAddress),
|
||||
lr(GAME_INFO.accessPort, GAME_INFO.bindPort)));
|
||||
|
||||
configuredRegions.forEach(region -> {
|
||||
if (usedNames.contains(region.Name)) {
|
||||
Grasscutter.getLogger().error("Region name already in use.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Create a region identifier.
|
||||
var identifier = RegionSimpleInfo.newBuilder()
|
||||
.setName(region.Name).setTitle(region.Title).setType("DEV_PUBLIC")
|
||||
.setDispatchUrl(dispatchDomain + "/query_cur_region/" + region.Name)
|
||||
.build();
|
||||
usedNames.add(region.Name);
|
||||
servers.add(identifier);
|
||||
|
||||
// Create a region info object.
|
||||
var regionInfo = RegionInfo.newBuilder()
|
||||
.setGateserverIp(region.Ip).setGateserverPort(region.Port)
|
||||
.setSecretKey(ByteString.copyFrom(Crypto.DISPATCH_SEED))
|
||||
.build();
|
||||
// Create an updated region query.
|
||||
var updatedQuery = QueryCurrRegionHttpRsp.newBuilder().setRegionInfo(regionInfo).build();
|
||||
regions.put(region.Name, new RegionData(updatedQuery, Utils.base64Encode(updatedQuery.toByteString().toByteArray())));
|
||||
});
|
||||
|
||||
// Create a config object.
|
||||
byte[] customConfig = "{\"sdkenv\":\"2\",\"checkdevice\":\"false\",\"loadPatch\":\"false\",\"showexception\":\"false\",\"regionConfig\":\"pm|fk|add\",\"downloadMode\":\"0\"}".getBytes();
|
||||
Crypto.xor(customConfig, Crypto.DISPATCH_KEY); // XOR the config with the key.
|
||||
|
||||
// Create an updated region list.
|
||||
QueryRegionListHttpRsp updatedRegionList = QueryRegionListHttpRsp.newBuilder()
|
||||
.addAllRegionList(servers)
|
||||
.setClientSecretKey(ByteString.copyFrom(Crypto.DISPATCH_SEED))
|
||||
.setClientCustomConfigEncrypted(ByteString.copyFrom(customConfig))
|
||||
.setEnableLoginPc(true).build();
|
||||
|
||||
// Set the region list response.
|
||||
regionListResponse = Utils.base64Encode(updatedRegionList.toByteString().toByteArray());
|
||||
|
||||
// CN
|
||||
// Create a config object.
|
||||
byte[] customConfigcn = "{\"sdkenv\":\"0\",\"checkdevice\":\"true\",\"loadPatch\":\"false\",\"showexception\":\"false\",\"regionConfig\":\"pm|fk|add\",\"downloadMode\":\"0\"}".getBytes();
|
||||
Crypto.xor(customConfigcn, Crypto.DISPATCH_KEY); // XOR the config with the key.
|
||||
|
||||
// Create an updated region list.
|
||||
QueryRegionListHttpRsp updatedRegionListcn = QueryRegionListHttpRsp.newBuilder()
|
||||
.addAllRegionList(servers)
|
||||
.setClientSecretKey(ByteString.copyFrom(Crypto.DISPATCH_SEED))
|
||||
.setClientCustomConfigEncrypted(ByteString.copyFrom(customConfigcn))
|
||||
.setEnableLoginPc(true).build();
|
||||
|
||||
// Set the region list response.
|
||||
regionListResponsecn = Utils.base64Encode(updatedRegionListcn.toByteString().toByteArray());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
javalin.get("/query_region_list", RegionHandler::queryRegionList);
|
||||
javalin.get("/query_cur_region/{region}", RegionHandler::queryCurrentRegion);
|
||||
}
|
||||
|
||||
/**
|
||||
* Region data container.
|
||||
*/
|
||||
public static class RegionData {
|
||||
private final QueryCurrRegionHttpRsp regionQuery;
|
||||
private final String base64;
|
||||
|
||||
public RegionData(QueryCurrRegionHttpRsp prq, String b64) {
|
||||
this.regionQuery = prq;
|
||||
this.base64 = b64;
|
||||
}
|
||||
|
||||
public QueryCurrRegionHttpRsp getRegionQuery() {
|
||||
return this.regionQuery;
|
||||
}
|
||||
|
||||
public String getBase64() {
|
||||
return this.base64;
|
||||
}
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.dispatch;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.*;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.Grasscutter.ServerRunMode;
|
||||
import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp;
|
||||
import emu.grasscutter.net.proto.QueryRegionListHttpRspOuterClass.QueryRegionListHttpRsp;
|
||||
import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo;
|
||||
import emu.grasscutter.net.proto.RegionSimpleInfoOuterClass.RegionSimpleInfo;
|
||||
import emu.grasscutter.server.event.dispatch.QueryAllRegionsEvent;
|
||||
import emu.grasscutter.server.event.dispatch.QueryCurrentRegionEvent;
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import emu.grasscutter.server.http.objects.QueryCurRegionRspJson;
|
||||
import emu.grasscutter.utils.Crypto;
|
||||
import emu.grasscutter.utils.Utils;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.Context;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.security.Signature;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.crypto.Cipher;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
/** Handles requests related to region queries. */
|
||||
public final class RegionHandler implements Router {
|
||||
private static final Map<String, RegionData> regions = new ConcurrentHashMap<>();
|
||||
private static String regionListResponse;
|
||||
private static String regionListResponsecn;
|
||||
|
||||
public RegionHandler() {
|
||||
try { // Read & initialize region data.
|
||||
this.initialize();
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().error("Failed to initialize region data.", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle query region list request.
|
||||
*
|
||||
* @param ctx The context object for handling the request.
|
||||
* @route /query_region_list
|
||||
*/
|
||||
private static void queryRegionList(Context ctx) {
|
||||
// Get logger and query parameters.
|
||||
Logger logger = Grasscutter.getLogger();
|
||||
if (ctx.queryParamMap().containsKey("version") && ctx.queryParamMap().containsKey("platform")) {
|
||||
String versionName = ctx.queryParam("version");
|
||||
String versionCode = versionName.replaceAll("[/.0-9]*", "");
|
||||
String platformName = ctx.queryParam("platform");
|
||||
|
||||
// Determine the region list to use based on the version and platform.
|
||||
if ("CNRELiOS".equals(versionCode)
|
||||
|| "CNRELWin".equals(versionCode)
|
||||
|| "CNRELAndroid".equals(versionCode)) {
|
||||
// Use the CN region list.
|
||||
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponsecn);
|
||||
event.call();
|
||||
logger.debug("Connect to Chinese version");
|
||||
|
||||
// Respond with the event result.
|
||||
ctx.result(event.getRegionList());
|
||||
} else if ("OSRELiOS".equals(versionCode)
|
||||
|| "OSRELWin".equals(versionCode)
|
||||
|| "OSRELAndroid".equals(versionCode)) {
|
||||
// Use the OS region list.
|
||||
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponse);
|
||||
event.call();
|
||||
logger.debug("Connect to global version");
|
||||
|
||||
// Respond with the event result.
|
||||
ctx.result(event.getRegionList());
|
||||
} else {
|
||||
/*
|
||||
* String regionListResponse = "CP///////////wE=";
|
||||
* QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponse);
|
||||
* event.call();
|
||||
* ctx.result(event.getRegionList());
|
||||
* return;
|
||||
*/
|
||||
// Use the default region list.
|
||||
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponse);
|
||||
event.call();
|
||||
logger.debug("Connect to global version");
|
||||
|
||||
// Respond with the event result.
|
||||
ctx.result(event.getRegionList());
|
||||
}
|
||||
} else {
|
||||
// Use the default region list.
|
||||
QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListResponse);
|
||||
event.call();
|
||||
logger.debug("Connect to global version");
|
||||
|
||||
// Respond with the event result.
|
||||
ctx.result(event.getRegionList());
|
||||
}
|
||||
// Log the request to the console.
|
||||
Grasscutter.getLogger()
|
||||
.info(String.format("[Dispatch] Client %s request: query_region_list", ctx.ip()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @route /query_cur_region/{region}
|
||||
*/
|
||||
private static void queryCurrentRegion(Context ctx) {
|
||||
// Get region to query.
|
||||
String regionName = ctx.pathParam("region");
|
||||
String versionName = ctx.queryParam("version");
|
||||
var region = regions.get(regionName);
|
||||
|
||||
// Get region data.
|
||||
String regionData = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw==";
|
||||
if (ctx.queryParamMap().values().size() > 0) {
|
||||
if (region != null) regionData = region.getBase64();
|
||||
}
|
||||
|
||||
String[] versionCode =
|
||||
versionName.replaceAll(Pattern.compile("[a-zA-Z]").pattern(), "").split("\\.");
|
||||
int versionMajor = Integer.parseInt(versionCode[0]);
|
||||
int versionMinor = Integer.parseInt(versionCode[1]);
|
||||
int versionFix = Integer.parseInt(versionCode[2]);
|
||||
|
||||
if (versionMajor >= 3
|
||||
|| (versionMajor == 2 && versionMinor == 7 && versionFix >= 50)
|
||||
|| (versionMajor == 2 && versionMinor == 8)) {
|
||||
try {
|
||||
QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(regionData);
|
||||
event.call();
|
||||
|
||||
if (ctx.queryParam("dispatchSeed") == null) {
|
||||
// More love for UA Patch players
|
||||
var rsp = new QueryCurRegionRspJson();
|
||||
|
||||
rsp.content = event.getRegionInfo();
|
||||
rsp.sign = "TW9yZSBsb3ZlIGZvciBVQSBQYXRjaCBwbGF5ZXJz";
|
||||
|
||||
ctx.json(rsp);
|
||||
return;
|
||||
}
|
||||
|
||||
String key_id = ctx.queryParam("key_id");
|
||||
|
||||
if (key_id == null) throw new Exception("Key ID was not set");
|
||||
|
||||
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, Crypto.EncryptionKeys.get(Integer.valueOf(key_id)));
|
||||
var regionInfo = Utils.base64Decode(event.getRegionInfo());
|
||||
|
||||
// Encrypt regionInfo in chunks
|
||||
ByteArrayOutputStream encryptedRegionInfoStream = new ByteArrayOutputStream();
|
||||
|
||||
// Thank you so much GH Copilot
|
||||
int chunkSize = 256 - 11;
|
||||
int regionInfoLength = regionInfo.length;
|
||||
int numChunks = (int) Math.ceil(regionInfoLength / (double) chunkSize);
|
||||
|
||||
for (int i = 0; i < numChunks; i++) {
|
||||
byte[] chunk =
|
||||
Arrays.copyOfRange(
|
||||
regionInfo, i * chunkSize, Math.min((i + 1) * chunkSize, regionInfoLength));
|
||||
byte[] encryptedChunk = cipher.doFinal(chunk);
|
||||
encryptedRegionInfoStream.write(encryptedChunk);
|
||||
}
|
||||
|
||||
Signature privateSignature = Signature.getInstance("SHA256withRSA");
|
||||
privateSignature.initSign(Crypto.CUR_SIGNING_KEY);
|
||||
privateSignature.update(regionInfo);
|
||||
|
||||
var rsp = new QueryCurRegionRspJson();
|
||||
|
||||
rsp.content = Utils.base64Encode(encryptedRegionInfoStream.toByteArray());
|
||||
rsp.sign = Utils.base64Encode(privateSignature.sign());
|
||||
|
||||
ctx.json(rsp);
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("An error occurred while handling query_cur_region.", e);
|
||||
}
|
||||
} else {
|
||||
// Invoke event.
|
||||
QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(regionData);
|
||||
event.call();
|
||||
// Respond with event result.
|
||||
ctx.result(event.getRegionInfo());
|
||||
}
|
||||
// Log to console.
|
||||
Grasscutter.getLogger()
|
||||
.info(String.format("Client %s request: query_cur_region/%s", ctx.ip(), regionName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current region query.
|
||||
*
|
||||
* @return A {@link QueryCurrRegionHttpRsp} object.
|
||||
*/
|
||||
public static QueryCurrRegionHttpRsp getCurrentRegion() {
|
||||
return SERVER.runMode == ServerRunMode.HYBRID ? regions.get("os_usa").getRegionQuery() : null;
|
||||
}
|
||||
|
||||
/** Configures region data according to configuration. */
|
||||
private void initialize() {
|
||||
String dispatchDomain =
|
||||
"http"
|
||||
+ (HTTP_ENCRYPTION.useInRouting ? "s" : "")
|
||||
+ "://"
|
||||
+ lr(HTTP_INFO.accessAddress, HTTP_INFO.bindAddress)
|
||||
+ ":"
|
||||
+ lr(HTTP_INFO.accessPort, HTTP_INFO.bindPort);
|
||||
|
||||
// Create regions.
|
||||
List<RegionSimpleInfo> servers = new ArrayList<>();
|
||||
List<String> usedNames = new ArrayList<>(); // List to check for potential naming conflicts.
|
||||
|
||||
var configuredRegions = new ArrayList<>(List.of(DISPATCH_INFO.regions));
|
||||
if (SERVER.runMode != ServerRunMode.HYBRID && configuredRegions.size() == 0) {
|
||||
Grasscutter.getLogger()
|
||||
.error(
|
||||
"[Dispatch] There are no game servers available. Exiting due to unplayable state.");
|
||||
System.exit(1);
|
||||
} else if (configuredRegions.size() == 0)
|
||||
configuredRegions.add(
|
||||
new Region(
|
||||
"os_usa",
|
||||
DISPATCH_INFO.defaultName,
|
||||
lr(GAME_INFO.accessAddress, GAME_INFO.bindAddress),
|
||||
lr(GAME_INFO.accessPort, GAME_INFO.bindPort)));
|
||||
|
||||
configuredRegions.forEach(
|
||||
region -> {
|
||||
if (usedNames.contains(region.Name)) {
|
||||
Grasscutter.getLogger().error("Region name already in use.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Create a region identifier.
|
||||
var identifier =
|
||||
RegionSimpleInfo.newBuilder()
|
||||
.setName(region.Name)
|
||||
.setTitle(region.Title)
|
||||
.setType("DEV_PUBLIC")
|
||||
.setDispatchUrl(dispatchDomain + "/query_cur_region/" + region.Name)
|
||||
.build();
|
||||
usedNames.add(region.Name);
|
||||
servers.add(identifier);
|
||||
|
||||
// Create a region info object.
|
||||
var regionInfo =
|
||||
RegionInfo.newBuilder()
|
||||
.setGateserverIp(region.Ip)
|
||||
.setGateserverPort(region.Port)
|
||||
.setSecretKey(ByteString.copyFrom(Crypto.DISPATCH_SEED))
|
||||
.build();
|
||||
// Create an updated region query.
|
||||
var updatedQuery = QueryCurrRegionHttpRsp.newBuilder().setRegionInfo(regionInfo).build();
|
||||
regions.put(
|
||||
region.Name,
|
||||
new RegionData(
|
||||
updatedQuery, Utils.base64Encode(updatedQuery.toByteString().toByteArray())));
|
||||
});
|
||||
|
||||
// Create a config object.
|
||||
byte[] customConfig =
|
||||
"{\"sdkenv\":\"2\",\"checkdevice\":\"false\",\"loadPatch\":\"false\",\"showexception\":\"false\",\"regionConfig\":\"pm|fk|add\",\"downloadMode\":\"0\"}"
|
||||
.getBytes();
|
||||
Crypto.xor(customConfig, Crypto.DISPATCH_KEY); // XOR the config with the key.
|
||||
|
||||
// Create an updated region list.
|
||||
QueryRegionListHttpRsp updatedRegionList =
|
||||
QueryRegionListHttpRsp.newBuilder()
|
||||
.addAllRegionList(servers)
|
||||
.setClientSecretKey(ByteString.copyFrom(Crypto.DISPATCH_SEED))
|
||||
.setClientCustomConfigEncrypted(ByteString.copyFrom(customConfig))
|
||||
.setEnableLoginPc(true)
|
||||
.build();
|
||||
|
||||
// Set the region list response.
|
||||
regionListResponse = Utils.base64Encode(updatedRegionList.toByteString().toByteArray());
|
||||
|
||||
// CN
|
||||
// Create a config object.
|
||||
byte[] customConfigcn =
|
||||
"{\"sdkenv\":\"0\",\"checkdevice\":\"true\",\"loadPatch\":\"false\",\"showexception\":\"false\",\"regionConfig\":\"pm|fk|add\",\"downloadMode\":\"0\"}"
|
||||
.getBytes();
|
||||
Crypto.xor(customConfigcn, Crypto.DISPATCH_KEY); // XOR the config with the key.
|
||||
|
||||
// Create an updated region list.
|
||||
QueryRegionListHttpRsp updatedRegionListcn =
|
||||
QueryRegionListHttpRsp.newBuilder()
|
||||
.addAllRegionList(servers)
|
||||
.setClientSecretKey(ByteString.copyFrom(Crypto.DISPATCH_SEED))
|
||||
.setClientCustomConfigEncrypted(ByteString.copyFrom(customConfigcn))
|
||||
.setEnableLoginPc(true)
|
||||
.build();
|
||||
|
||||
// Set the region list response.
|
||||
regionListResponsecn = Utils.base64Encode(updatedRegionListcn.toByteString().toByteArray());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
javalin.get("/query_region_list", RegionHandler::queryRegionList);
|
||||
javalin.get("/query_cur_region/{region}", RegionHandler::queryCurrentRegion);
|
||||
}
|
||||
|
||||
/** Region data container. */
|
||||
public static class RegionData {
|
||||
private final QueryCurrRegionHttpRsp regionQuery;
|
||||
private final String base64;
|
||||
|
||||
public RegionData(QueryCurrRegionHttpRsp prq, String b64) {
|
||||
this.regionQuery = prq;
|
||||
this.base64 = b64;
|
||||
}
|
||||
|
||||
public QueryCurrRegionHttpRsp getRegionQuery() {
|
||||
return this.regionQuery;
|
||||
}
|
||||
|
||||
public String getBase64() {
|
||||
return this.base64;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
package emu.grasscutter.server.http.documentation;
|
||||
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import io.javalin.Javalin;
|
||||
|
||||
public final class DocumentationServerHandler implements Router {
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
final RootRequestHandler root = new RootRequestHandler();
|
||||
final HandbookRequestHandler handbook = new HandbookRequestHandler();
|
||||
final GachaMappingRequestHandler gachaMapping = new GachaMappingRequestHandler();
|
||||
|
||||
// TODO: Removal
|
||||
// TODO: Forward /documentation requests to https://grasscutter.io/wiki
|
||||
javalin.get("/documentation/handbook", handbook::handle);
|
||||
javalin.get("/documentation/gachamapping", gachaMapping::handle);
|
||||
javalin.get("/documentation", root::handle);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.documentation;
|
||||
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import io.javalin.Javalin;
|
||||
|
||||
public final class DocumentationServerHandler implements Router {
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
final RootRequestHandler root = new RootRequestHandler();
|
||||
final HandbookRequestHandler handbook = new HandbookRequestHandler();
|
||||
final GachaMappingRequestHandler gachaMapping = new GachaMappingRequestHandler();
|
||||
|
||||
// TODO: Removal
|
||||
// TODO: Forward /documentation requests to https://grasscutter.io/wiki
|
||||
javalin.get("/documentation/handbook", handbook::handle);
|
||||
javalin.get("/documentation/gachamapping", gachaMapping::handle);
|
||||
javalin.get("/documentation", root::handle);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,26 @@
|
||||
package emu.grasscutter.server.http.documentation;
|
||||
|
||||
import emu.grasscutter.tools.Tools;
|
||||
import emu.grasscutter.utils.Language;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DOCUMENT_LANGUAGE;
|
||||
|
||||
final class GachaMappingRequestHandler implements DocumentationHandler {
|
||||
private final List<String> gachaJsons;
|
||||
|
||||
GachaMappingRequestHandler() {
|
||||
this.gachaJsons = Tools.createGachaMappingJsons();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(Context ctx) {
|
||||
final int langIdx = Language.TextStrings.MAP_LANGUAGES.getOrDefault(DOCUMENT_LANGUAGE, 0); // TODO: This should really be based off the client language somehow
|
||||
ctx.contentType(ContentType.APPLICATION_JSON).result(gachaJsons.get(langIdx));
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.documentation;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DOCUMENT_LANGUAGE;
|
||||
|
||||
import emu.grasscutter.tools.Tools;
|
||||
import emu.grasscutter.utils.Language;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
import java.util.List;
|
||||
|
||||
final class GachaMappingRequestHandler implements DocumentationHandler {
|
||||
private final List<String> gachaJsons;
|
||||
|
||||
GachaMappingRequestHandler() {
|
||||
this.gachaJsons = Tools.createGachaMappingJsons();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(Context ctx) {
|
||||
final int langIdx =
|
||||
Language.TextStrings.MAP_LANGUAGES.getOrDefault(
|
||||
DOCUMENT_LANGUAGE,
|
||||
0); // TODO: This should really be based off the client language somehow
|
||||
ctx.contentType(ContentType.APPLICATION_JSON).result(gachaJsons.get(langIdx));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,148 +1,204 @@
|
||||
package emu.grasscutter.server.http.documentation;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.command.CommandMap;
|
||||
import emu.grasscutter.data.GameData;
|
||||
import emu.grasscutter.data.excels.AvatarData;
|
||||
import emu.grasscutter.data.excels.ItemData;
|
||||
import emu.grasscutter.data.excels.MonsterData;
|
||||
import emu.grasscutter.data.excels.SceneData;
|
||||
import emu.grasscutter.utils.FileUtils;
|
||||
import emu.grasscutter.utils.Language;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
final class HandbookRequestHandler implements DocumentationHandler {
|
||||
private List<String> handbookHtmls;
|
||||
|
||||
public HandbookRequestHandler() {
|
||||
var templatePath = FileUtils.getDataPath("documentation/handbook.html");
|
||||
try {
|
||||
this.handbookHtmls = generateHandbookHtmls(Files.readString(templatePath));
|
||||
} catch (IOException ignored) {
|
||||
Grasscutter.getLogger().warn("File does not exist: " + templatePath);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(Context ctx) {
|
||||
int langIdx = 0;
|
||||
String acceptLanguage = ctx.header("Accept-Language");
|
||||
if (acceptLanguage != null) {
|
||||
Pattern localePattern = Pattern.compile("[a-z]+-[A-Z]+");
|
||||
Matcher matcher = localePattern.matcher(acceptLanguage);
|
||||
if (matcher.find()) {
|
||||
String lang = matcher.group(0);
|
||||
langIdx = Language.TextStrings.MAP_GC_LANGUAGES.getOrDefault(lang, 0);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.handbookHtmls == null) {
|
||||
ctx.status(500);
|
||||
} else {
|
||||
if (langIdx <= this.handbookHtmls.size() - 1) {
|
||||
ctx.contentType(ContentType.TEXT_HTML);
|
||||
ctx.result(this.handbookHtmls.get(langIdx));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> generateHandbookHtmls(String template) {
|
||||
final int NUM_LANGUAGES = Language.TextStrings.NUM_LANGUAGES;
|
||||
final List<String> output = new ArrayList<>(NUM_LANGUAGES);
|
||||
final List<Language> languages = Language.TextStrings.getLanguages();
|
||||
final List<StringBuilder> sbs = new ArrayList<>(NUM_LANGUAGES);
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.add(new StringBuilder());
|
||||
|
||||
// Commands table
|
||||
CommandMap.getInstance().getHandlersAsList().forEach(cmd -> {
|
||||
String label = cmd.getLabel();
|
||||
String descKey = cmd.getDescriptionKey();
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.get(langIdx).append("<tr><td><code>" + label + "</code></td><td>" + languages.get(langIdx).get(descKey) + "</td></tr>\n");
|
||||
});
|
||||
sbs.forEach(sb -> sb.setLength(sb.length() - 1)); // Remove trailing \n
|
||||
final List<String> cmdsTable = sbs.stream().map(StringBuilder::toString).toList();
|
||||
|
||||
// Avatars table
|
||||
final Int2ObjectMap<AvatarData> avatarMap = GameData.getAvatarDataMap();
|
||||
sbs.forEach(sb -> sb.setLength(0));
|
||||
avatarMap.keySet().intStream().sorted().mapToObj(avatarMap::get).forEach(data -> {
|
||||
int id = data.getId();
|
||||
Language.TextStrings name = Language.getTextMapKey(data.getNameTextMapHash());
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.get(langIdx).append("<tr><td><code>" + id + "</code></td><td>" + name.get(langIdx) + "</td></tr>\n");
|
||||
});
|
||||
sbs.forEach(sb -> sb.setLength(sb.length() - 1)); // Remove trailing \n
|
||||
final List<String> avatarsTable = sbs.stream().map(StringBuilder::toString).toList();
|
||||
|
||||
// Items table
|
||||
final Int2ObjectMap<ItemData> itemMap = GameData.getItemDataMap();
|
||||
sbs.forEach(sb -> sb.setLength(0));
|
||||
itemMap.keySet().intStream().sorted().mapToObj(itemMap::get).forEach(data -> {
|
||||
int id = data.getId();
|
||||
Language.TextStrings name = Language.getTextMapKey(data.getNameTextMapHash());
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.get(langIdx).append("<tr><td><code>" + id + "</code></td><td>" + name.get(langIdx) + "</td></tr>\n");
|
||||
});
|
||||
sbs.forEach(sb -> sb.setLength(sb.length() - 1)); // Remove trailing \n
|
||||
final List<String> itemsTable = sbs.stream().map(StringBuilder::toString).toList();
|
||||
|
||||
// Scenes table
|
||||
final Int2ObjectMap<SceneData> sceneMap = GameData.getSceneDataMap();
|
||||
sceneMap.keySet().intStream().sorted().mapToObj(sceneMap::get).forEach(data -> {
|
||||
int id = data.getId();
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.get(langIdx).append("<tr><td><code>" + id + "</code></td><td>" + data.getScriptData() + "</td></tr>\n");
|
||||
});
|
||||
sbs.forEach(sb -> sb.setLength(sb.length() - 1)); // Remove trailing \n
|
||||
final List<String> scenesTable = sbs.stream().map(StringBuilder::toString).toList();
|
||||
|
||||
// Monsters table
|
||||
final Int2ObjectMap<MonsterData> monsterMap = GameData.getMonsterDataMap();
|
||||
monsterMap.keySet().intStream().sorted().mapToObj(monsterMap::get).forEach(data -> {
|
||||
int id = data.getId();
|
||||
Language.TextStrings name = Language.getTextMapKey(data.getNameTextMapHash());
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.get(langIdx).append("<tr><td><code>" + id + "</code></td><td>" + name.get(langIdx) + "</td></tr>\n");
|
||||
});
|
||||
sbs.forEach(sb -> sb.setLength(sb.length() - 1)); // Remove trailing \n
|
||||
final List<String> monstersTable = sbs.stream().map(StringBuilder::toString).toList();
|
||||
|
||||
// Add translated title etc. to the page.
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++) {
|
||||
Language lang = languages.get(langIdx);
|
||||
output.add(template
|
||||
.replace("{{TITLE}}", lang.get("documentation.handbook.title"))
|
||||
.replace("{{TITLE_COMMANDS}}", lang.get("documentation.handbook.title_commands"))
|
||||
.replace("{{TITLE_AVATARS}}", lang.get("documentation.handbook.title_avatars"))
|
||||
.replace("{{TITLE_ITEMS}}", lang.get("documentation.handbook.title_items"))
|
||||
.replace("{{TITLE_SCENES}}", lang.get("documentation.handbook.title_scenes"))
|
||||
.replace("{{TITLE_MONSTERS}}", lang.get("documentation.handbook.title_monsters"))
|
||||
.replace("{{HEADER_ID}}", lang.get("documentation.handbook.header_id"))
|
||||
.replace("{{HEADER_COMMAND}}", lang.get("documentation.handbook.header_command"))
|
||||
.replace("{{HEADER_DESCRIPTION}}", lang.get("documentation.handbook.header_description"))
|
||||
.replace("{{HEADER_AVATAR}}", lang.get("documentation.handbook.header_avatar"))
|
||||
.replace("{{HEADER_ITEM}}", lang.get("documentation.handbook.header_item"))
|
||||
.replace("{{HEADER_SCENE}}", lang.get("documentation.handbook.header_scene"))
|
||||
.replace("{{HEADER_MONSTER}}", lang.get("documentation.handbook.header_monster"))
|
||||
// Commands table
|
||||
.replace("{{COMMANDS_TABLE}}", cmdsTable.get(langIdx))
|
||||
.replace("{{AVATARS_TABLE}}", avatarsTable.get(langIdx))
|
||||
.replace("{{ITEMS_TABLE}}", itemsTable.get(langIdx))
|
||||
.replace("{{SCENES_TABLE}}", scenesTable.get(langIdx))
|
||||
.replace("{{MONSTERS_TABLE}}", monstersTable.get(langIdx))
|
||||
);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.documentation;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.command.CommandMap;
|
||||
import emu.grasscutter.data.GameData;
|
||||
import emu.grasscutter.data.excels.AvatarData;
|
||||
import emu.grasscutter.data.excels.ItemData;
|
||||
import emu.grasscutter.data.excels.MonsterData;
|
||||
import emu.grasscutter.data.excels.SceneData;
|
||||
import emu.grasscutter.utils.FileUtils;
|
||||
import emu.grasscutter.utils.Language;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
final class HandbookRequestHandler implements DocumentationHandler {
|
||||
private List<String> handbookHtmls;
|
||||
|
||||
public HandbookRequestHandler() {
|
||||
var templatePath = FileUtils.getDataPath("documentation/handbook.html");
|
||||
try {
|
||||
this.handbookHtmls = generateHandbookHtmls(Files.readString(templatePath));
|
||||
} catch (IOException ignored) {
|
||||
Grasscutter.getLogger().warn("File does not exist: " + templatePath);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(Context ctx) {
|
||||
int langIdx = 0;
|
||||
String acceptLanguage = ctx.header("Accept-Language");
|
||||
if (acceptLanguage != null) {
|
||||
Pattern localePattern = Pattern.compile("[a-z]+-[A-Z]+");
|
||||
Matcher matcher = localePattern.matcher(acceptLanguage);
|
||||
if (matcher.find()) {
|
||||
String lang = matcher.group(0);
|
||||
langIdx = Language.TextStrings.MAP_GC_LANGUAGES.getOrDefault(lang, 0);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.handbookHtmls == null) {
|
||||
ctx.status(500);
|
||||
} else {
|
||||
if (langIdx <= this.handbookHtmls.size() - 1) {
|
||||
ctx.contentType(ContentType.TEXT_HTML);
|
||||
ctx.result(this.handbookHtmls.get(langIdx));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> generateHandbookHtmls(String template) {
|
||||
final int NUM_LANGUAGES = Language.TextStrings.NUM_LANGUAGES;
|
||||
final List<String> output = new ArrayList<>(NUM_LANGUAGES);
|
||||
final List<Language> languages = Language.TextStrings.getLanguages();
|
||||
final List<StringBuilder> sbs = new ArrayList<>(NUM_LANGUAGES);
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++) sbs.add(new StringBuilder());
|
||||
|
||||
// Commands table
|
||||
CommandMap.getInstance()
|
||||
.getHandlersAsList()
|
||||
.forEach(
|
||||
cmd -> {
|
||||
String label = cmd.getLabel();
|
||||
String descKey = cmd.getDescriptionKey();
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.get(langIdx)
|
||||
.append(
|
||||
"<tr><td><code>"
|
||||
+ label
|
||||
+ "</code></td><td>"
|
||||
+ languages.get(langIdx).get(descKey)
|
||||
+ "</td></tr>\n");
|
||||
});
|
||||
sbs.forEach(sb -> sb.setLength(sb.length() - 1)); // Remove trailing \n
|
||||
final List<String> cmdsTable = sbs.stream().map(StringBuilder::toString).toList();
|
||||
|
||||
// Avatars table
|
||||
final Int2ObjectMap<AvatarData> avatarMap = GameData.getAvatarDataMap();
|
||||
sbs.forEach(sb -> sb.setLength(0));
|
||||
avatarMap
|
||||
.keySet()
|
||||
.intStream()
|
||||
.sorted()
|
||||
.mapToObj(avatarMap::get)
|
||||
.forEach(
|
||||
data -> {
|
||||
int id = data.getId();
|
||||
Language.TextStrings name = Language.getTextMapKey(data.getNameTextMapHash());
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.get(langIdx)
|
||||
.append(
|
||||
"<tr><td><code>"
|
||||
+ id
|
||||
+ "</code></td><td>"
|
||||
+ name.get(langIdx)
|
||||
+ "</td></tr>\n");
|
||||
});
|
||||
sbs.forEach(sb -> sb.setLength(sb.length() - 1)); // Remove trailing \n
|
||||
final List<String> avatarsTable = sbs.stream().map(StringBuilder::toString).toList();
|
||||
|
||||
// Items table
|
||||
final Int2ObjectMap<ItemData> itemMap = GameData.getItemDataMap();
|
||||
sbs.forEach(sb -> sb.setLength(0));
|
||||
itemMap
|
||||
.keySet()
|
||||
.intStream()
|
||||
.sorted()
|
||||
.mapToObj(itemMap::get)
|
||||
.forEach(
|
||||
data -> {
|
||||
int id = data.getId();
|
||||
Language.TextStrings name = Language.getTextMapKey(data.getNameTextMapHash());
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.get(langIdx)
|
||||
.append(
|
||||
"<tr><td><code>"
|
||||
+ id
|
||||
+ "</code></td><td>"
|
||||
+ name.get(langIdx)
|
||||
+ "</td></tr>\n");
|
||||
});
|
||||
sbs.forEach(sb -> sb.setLength(sb.length() - 1)); // Remove trailing \n
|
||||
final List<String> itemsTable = sbs.stream().map(StringBuilder::toString).toList();
|
||||
|
||||
// Scenes table
|
||||
final Int2ObjectMap<SceneData> sceneMap = GameData.getSceneDataMap();
|
||||
sceneMap
|
||||
.keySet()
|
||||
.intStream()
|
||||
.sorted()
|
||||
.mapToObj(sceneMap::get)
|
||||
.forEach(
|
||||
data -> {
|
||||
int id = data.getId();
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.get(langIdx)
|
||||
.append(
|
||||
"<tr><td><code>"
|
||||
+ id
|
||||
+ "</code></td><td>"
|
||||
+ data.getScriptData()
|
||||
+ "</td></tr>\n");
|
||||
});
|
||||
sbs.forEach(sb -> sb.setLength(sb.length() - 1)); // Remove trailing \n
|
||||
final List<String> scenesTable = sbs.stream().map(StringBuilder::toString).toList();
|
||||
|
||||
// Monsters table
|
||||
final Int2ObjectMap<MonsterData> monsterMap = GameData.getMonsterDataMap();
|
||||
monsterMap
|
||||
.keySet()
|
||||
.intStream()
|
||||
.sorted()
|
||||
.mapToObj(monsterMap::get)
|
||||
.forEach(
|
||||
data -> {
|
||||
int id = data.getId();
|
||||
Language.TextStrings name = Language.getTextMapKey(data.getNameTextMapHash());
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
|
||||
sbs.get(langIdx)
|
||||
.append(
|
||||
"<tr><td><code>"
|
||||
+ id
|
||||
+ "</code></td><td>"
|
||||
+ name.get(langIdx)
|
||||
+ "</td></tr>\n");
|
||||
});
|
||||
sbs.forEach(sb -> sb.setLength(sb.length() - 1)); // Remove trailing \n
|
||||
final List<String> monstersTable = sbs.stream().map(StringBuilder::toString).toList();
|
||||
|
||||
// Add translated title etc. to the page.
|
||||
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++) {
|
||||
Language lang = languages.get(langIdx);
|
||||
output.add(
|
||||
template
|
||||
.replace("{{TITLE}}", lang.get("documentation.handbook.title"))
|
||||
.replace("{{TITLE_COMMANDS}}", lang.get("documentation.handbook.title_commands"))
|
||||
.replace("{{TITLE_AVATARS}}", lang.get("documentation.handbook.title_avatars"))
|
||||
.replace("{{TITLE_ITEMS}}", lang.get("documentation.handbook.title_items"))
|
||||
.replace("{{TITLE_SCENES}}", lang.get("documentation.handbook.title_scenes"))
|
||||
.replace("{{TITLE_MONSTERS}}", lang.get("documentation.handbook.title_monsters"))
|
||||
.replace("{{HEADER_ID}}", lang.get("documentation.handbook.header_id"))
|
||||
.replace("{{HEADER_COMMAND}}", lang.get("documentation.handbook.header_command"))
|
||||
.replace(
|
||||
"{{HEADER_DESCRIPTION}}", lang.get("documentation.handbook.header_description"))
|
||||
.replace("{{HEADER_AVATAR}}", lang.get("documentation.handbook.header_avatar"))
|
||||
.replace("{{HEADER_ITEM}}", lang.get("documentation.handbook.header_item"))
|
||||
.replace("{{HEADER_SCENE}}", lang.get("documentation.handbook.header_scene"))
|
||||
.replace("{{HEADER_MONSTER}}", lang.get("documentation.handbook.header_monster"))
|
||||
// Commands table
|
||||
.replace("{{COMMANDS_TABLE}}", cmdsTable.get(langIdx))
|
||||
.replace("{{AVATARS_TABLE}}", avatarsTable.get(langIdx))
|
||||
.replace("{{ITEMS_TABLE}}", itemsTable.get(langIdx))
|
||||
.replace("{{SCENES_TABLE}}", scenesTable.get(langIdx))
|
||||
.replace("{{MONSTERS_TABLE}}", monstersTable.get(langIdx)));
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,41 +1,42 @@
|
||||
package emu.grasscutter.server.http.documentation;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.utils.FileUtils;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
|
||||
final class RootRequestHandler implements DocumentationHandler {
|
||||
|
||||
private final String template;
|
||||
|
||||
public RootRequestHandler() {
|
||||
var templatePath = FileUtils.getDataPath("documentation/index.html");
|
||||
String t = null;
|
||||
try {
|
||||
t = Files.readString(templatePath);
|
||||
} catch (IOException ignored) {
|
||||
Grasscutter.getLogger().warn("File does not exist: " + templatePath);
|
||||
}
|
||||
this.template = t;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(Context ctx) {
|
||||
if (template == null) {
|
||||
ctx.status(500);
|
||||
return;
|
||||
}
|
||||
|
||||
String content = template.replace("{{TITLE}}", translate("documentation.index.title"))
|
||||
.replace("{{ITEM_HANDBOOK}}", translate("documentation.index.handbook"))
|
||||
.replace("{{ITEM_GACHA_MAPPING}}", translate("documentation.index.gacha_mapping"));
|
||||
ctx.contentType(ContentType.TEXT_HTML);
|
||||
ctx.result(content);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.documentation;
|
||||
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.utils.FileUtils;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
|
||||
final class RootRequestHandler implements DocumentationHandler {
|
||||
|
||||
private final String template;
|
||||
|
||||
public RootRequestHandler() {
|
||||
var templatePath = FileUtils.getDataPath("documentation/index.html");
|
||||
String t = null;
|
||||
try {
|
||||
t = Files.readString(templatePath);
|
||||
} catch (IOException ignored) {
|
||||
Grasscutter.getLogger().warn("File does not exist: " + templatePath);
|
||||
}
|
||||
this.template = t;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(Context ctx) {
|
||||
if (template == null) {
|
||||
ctx.status(500);
|
||||
return;
|
||||
}
|
||||
|
||||
String content =
|
||||
template
|
||||
.replace("{{TITLE}}", translate("documentation.index.title"))
|
||||
.replace("{{ITEM_HANDBOOK}}", translate("documentation.index.handbook"))
|
||||
.replace("{{ITEM_GACHA_MAPPING}}", translate("documentation.index.gacha_mapping"));
|
||||
ctx.contentType(ContentType.TEXT_HTML);
|
||||
ctx.result(content);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,98 +1,121 @@
|
||||
package emu.grasscutter.server.http.handlers;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.data.DataLoader;
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import emu.grasscutter.server.http.objects.HttpJsonResponse;
|
||||
import emu.grasscutter.utils.FileUtils;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Objects;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.*;
|
||||
|
||||
/**
|
||||
* Handles requests related to the announcements page.
|
||||
*/
|
||||
public final class AnnouncementsHandler implements Router {
|
||||
private static void getAnnouncement(Context ctx) {
|
||||
String data = "";
|
||||
if (Objects.equals(ctx.endpointHandlerPath(), "/common/hk4e_global/announcement/api/getAnnContent")) {
|
||||
try {
|
||||
data = FileUtils.readToString(DataLoader.load("GameAnnouncement.json"));
|
||||
} catch (Exception e) {
|
||||
if (e.getClass() == IOException.class) {
|
||||
Grasscutter.getLogger().info("Unable to read file 'GameAnnouncementList.json'. \n" + e);
|
||||
}
|
||||
}
|
||||
} else if (Objects.equals(ctx.endpointHandlerPath(), "/common/hk4e_global/announcement/api/getAnnList")) {
|
||||
try {
|
||||
data = FileUtils.readToString(DataLoader.load("GameAnnouncementList.json"));
|
||||
} catch (Exception e) {
|
||||
if (e.getClass() == IOException.class) {
|
||||
Grasscutter.getLogger().info("Unable to read file 'GameAnnouncementList.json'. \n" + e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ctx.result("{\"retcode\":404,\"message\":\"Unknown request path\"}");
|
||||
}
|
||||
|
||||
if (data.isEmpty()) {
|
||||
ctx.result("{\"retcode\":500,\"message\":\"Unable to fetch requsted content\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
String dispatchDomain = "http" + (HTTP_ENCRYPTION.useInRouting ? "s" : "") + "://"
|
||||
+ lr(HTTP_INFO.accessAddress, HTTP_INFO.bindAddress) + ":"
|
||||
+ lr(HTTP_INFO.accessPort, HTTP_INFO.bindPort);
|
||||
|
||||
data = data
|
||||
.replace("{{DISPATCH_PUBLIC}}", dispatchDomain)
|
||||
.replace("{{SYSTEM_TIME}}", String.valueOf(System.currentTimeMillis()));
|
||||
ctx.result("{\"retcode\":0,\"message\":\"OK\",\"data\": " + data + "}");
|
||||
}
|
||||
|
||||
private static void getPageResources(Context ctx) {
|
||||
// Re-process the path - remove the first slash and prevent directory traversal
|
||||
// (the first slash will act as root path when resolving local path)
|
||||
String[] path = ctx.path().split("/");
|
||||
StringJoiner stringJoiner = new StringJoiner("/");
|
||||
for (String pathName : path) {
|
||||
// Filter the illegal payload to prevent directory traversal
|
||||
if (!pathName.isEmpty() && !pathName.equals("..") && !pathName.contains("\\")) {
|
||||
stringJoiner.add(pathName);
|
||||
}
|
||||
}
|
||||
try (InputStream filestream = DataLoader.load(stringJoiner.toString())) {
|
||||
String possibleFilename = ctx.path();
|
||||
|
||||
ContentType fromExtension = ContentType.getContentTypeByExtension(possibleFilename.substring(possibleFilename.lastIndexOf(".") + 1));
|
||||
ctx.contentType(fromExtension != null ? fromExtension : ContentType.APPLICATION_OCTET_STREAM);
|
||||
ctx.result(filestream.readAllBytes());
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().warn("File does not exist: " + ctx.path());
|
||||
ctx.status(404);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
// hk4e-api-os.hoyoverse.com
|
||||
this.allRoutes(javalin, "/common/hk4e_global/announcement/api/getAlertPic", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}"));
|
||||
// hk4e-api-os.hoyoverse.com
|
||||
this.allRoutes(javalin, "/common/hk4e_global/announcement/api/getAlertAnn", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}"));
|
||||
// hk4e-api-os.hoyoverse.com
|
||||
this.allRoutes(javalin, "/common/hk4e_global/announcement/api/getAnnList", AnnouncementsHandler::getAnnouncement);
|
||||
// hk4e-api-os-static.hoyoverse.com
|
||||
this.allRoutes(javalin, "/common/hk4e_global/announcement/api/getAnnContent", AnnouncementsHandler::getAnnouncement);
|
||||
// hk4e-sdk-os.hoyoverse.com
|
||||
this.allRoutes(javalin, "/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}"));
|
||||
|
||||
javalin.get("/hk4e/announcement/*", AnnouncementsHandler::getPageResources);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.handlers;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.*;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.data.DataLoader;
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import emu.grasscutter.server.http.objects.HttpJsonResponse;
|
||||
import emu.grasscutter.utils.FileUtils;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Objects;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
/** Handles requests related to the announcements page. */
|
||||
public final class AnnouncementsHandler implements Router {
|
||||
private static void getAnnouncement(Context ctx) {
|
||||
String data = "";
|
||||
if (Objects.equals(
|
||||
ctx.endpointHandlerPath(), "/common/hk4e_global/announcement/api/getAnnContent")) {
|
||||
try {
|
||||
data = FileUtils.readToString(DataLoader.load("GameAnnouncement.json"));
|
||||
} catch (Exception e) {
|
||||
if (e.getClass() == IOException.class) {
|
||||
Grasscutter.getLogger().info("Unable to read file 'GameAnnouncementList.json'. \n" + e);
|
||||
}
|
||||
}
|
||||
} else if (Objects.equals(
|
||||
ctx.endpointHandlerPath(), "/common/hk4e_global/announcement/api/getAnnList")) {
|
||||
try {
|
||||
data = FileUtils.readToString(DataLoader.load("GameAnnouncementList.json"));
|
||||
} catch (Exception e) {
|
||||
if (e.getClass() == IOException.class) {
|
||||
Grasscutter.getLogger().info("Unable to read file 'GameAnnouncementList.json'. \n" + e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ctx.result("{\"retcode\":404,\"message\":\"Unknown request path\"}");
|
||||
}
|
||||
|
||||
if (data.isEmpty()) {
|
||||
ctx.result("{\"retcode\":500,\"message\":\"Unable to fetch requsted content\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
String dispatchDomain =
|
||||
"http"
|
||||
+ (HTTP_ENCRYPTION.useInRouting ? "s" : "")
|
||||
+ "://"
|
||||
+ lr(HTTP_INFO.accessAddress, HTTP_INFO.bindAddress)
|
||||
+ ":"
|
||||
+ lr(HTTP_INFO.accessPort, HTTP_INFO.bindPort);
|
||||
|
||||
data =
|
||||
data.replace("{{DISPATCH_PUBLIC}}", dispatchDomain)
|
||||
.replace("{{SYSTEM_TIME}}", String.valueOf(System.currentTimeMillis()));
|
||||
ctx.result("{\"retcode\":0,\"message\":\"OK\",\"data\": " + data + "}");
|
||||
}
|
||||
|
||||
private static void getPageResources(Context ctx) {
|
||||
// Re-process the path - remove the first slash and prevent directory traversal
|
||||
// (the first slash will act as root path when resolving local path)
|
||||
String[] path = ctx.path().split("/");
|
||||
StringJoiner stringJoiner = new StringJoiner("/");
|
||||
for (String pathName : path) {
|
||||
// Filter the illegal payload to prevent directory traversal
|
||||
if (!pathName.isEmpty() && !pathName.equals("..") && !pathName.contains("\\")) {
|
||||
stringJoiner.add(pathName);
|
||||
}
|
||||
}
|
||||
try (InputStream filestream = DataLoader.load(stringJoiner.toString())) {
|
||||
String possibleFilename = ctx.path();
|
||||
|
||||
ContentType fromExtension =
|
||||
ContentType.getContentTypeByExtension(
|
||||
possibleFilename.substring(possibleFilename.lastIndexOf(".") + 1));
|
||||
ctx.contentType(fromExtension != null ? fromExtension : ContentType.APPLICATION_OCTET_STREAM);
|
||||
ctx.result(filestream.readAllBytes());
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().warn("File does not exist: " + ctx.path());
|
||||
ctx.status(404);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
// hk4e-api-os.hoyoverse.com
|
||||
this.allRoutes(
|
||||
javalin,
|
||||
"/common/hk4e_global/announcement/api/getAlertPic",
|
||||
new HttpJsonResponse(
|
||||
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}"));
|
||||
// hk4e-api-os.hoyoverse.com
|
||||
this.allRoutes(
|
||||
javalin,
|
||||
"/common/hk4e_global/announcement/api/getAlertAnn",
|
||||
new HttpJsonResponse(
|
||||
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}"));
|
||||
// hk4e-api-os.hoyoverse.com
|
||||
this.allRoutes(
|
||||
javalin,
|
||||
"/common/hk4e_global/announcement/api/getAnnList",
|
||||
AnnouncementsHandler::getAnnouncement);
|
||||
// hk4e-api-os-static.hoyoverse.com
|
||||
this.allRoutes(
|
||||
javalin,
|
||||
"/common/hk4e_global/announcement/api/getAnnContent",
|
||||
AnnouncementsHandler::getAnnouncement);
|
||||
// hk4e-sdk-os.hoyoverse.com
|
||||
this.allRoutes(
|
||||
javalin,
|
||||
"/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier",
|
||||
new HttpJsonResponse(
|
||||
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}"));
|
||||
|
||||
javalin.get("/hk4e/announcement/*", AnnouncementsHandler::getPageResources);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,140 +1,153 @@
|
||||
package emu.grasscutter.server.http.handlers;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.database.DatabaseHelper;
|
||||
import emu.grasscutter.game.Account;
|
||||
import emu.grasscutter.game.gacha.GachaBanner;
|
||||
import emu.grasscutter.game.gacha.GachaSystem;
|
||||
import emu.grasscutter.game.player.Player;
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import emu.grasscutter.utils.FileUtils;
|
||||
import emu.grasscutter.utils.Utils;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
import io.javalin.http.staticfiles.Location;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
|
||||
/**
|
||||
* Handles all gacha-related HTTP requests.
|
||||
*/
|
||||
public final class GachaHandler implements Router {
|
||||
@Getter
|
||||
private static final Path gachaMappingsPath = FileUtils.getDataUserPath("gacha/mappings.js");
|
||||
@Deprecated(forRemoval = true)
|
||||
public static final String gachaMappings = gachaMappingsPath.toString();
|
||||
|
||||
private static void gachaRecords(Context ctx) {
|
||||
String sessionKey = ctx.queryParam("s");
|
||||
Account account = DatabaseHelper.getAccountBySessionKey(sessionKey);
|
||||
if (account == null) {
|
||||
ctx.status(403).result("Requested account was not found");
|
||||
return;
|
||||
}
|
||||
Player player = Grasscutter.getGameServer().getPlayerByAccountId(account.getId());
|
||||
if (player == null) {
|
||||
ctx.status(403).result("No player associated with requested account");
|
||||
return;
|
||||
}
|
||||
|
||||
int page = 0, gachaType = 0;
|
||||
if (ctx.queryParam("p") != null)
|
||||
page = Integer.parseInt(ctx.queryParam("p"));
|
||||
if (ctx.queryParam("gachaType") != null)
|
||||
gachaType = Integer.parseInt(ctx.queryParam("gachaType"));
|
||||
|
||||
String records = DatabaseHelper.getGachaRecords(player.getUid(), page, gachaType).toString();
|
||||
long maxPage = DatabaseHelper.getGachaRecordsMaxPage(player.getUid(), page, gachaType);
|
||||
|
||||
String template = new String(FileUtils.read(FileUtils.getDataPath("gacha/records.html")), StandardCharsets.UTF_8)
|
||||
.replace("{{REPLACE_RECORDS}}", records)
|
||||
.replace("{{REPLACE_MAXPAGE}}", String.valueOf(maxPage))
|
||||
.replace("{{TITLE}}", translate(player, "gacha.records.title"))
|
||||
.replace("{{DATE}}", translate(player, "gacha.records.date"))
|
||||
.replace("{{ITEM}}", translate(player, "gacha.records.item"))
|
||||
.replace("{{LANGUAGE}}", Utils.getLanguageCode(account.getLocale()));
|
||||
ctx.contentType(ContentType.TEXT_HTML);
|
||||
ctx.result(template);
|
||||
}
|
||||
|
||||
private static void gachaDetails(Context ctx) {
|
||||
Path detailsTemplate = FileUtils.getDataPath("gacha/details.html");
|
||||
String sessionKey = ctx.queryParam("s");
|
||||
Account account = DatabaseHelper.getAccountBySessionKey(sessionKey);
|
||||
if (account == null) {
|
||||
ctx.status(403).result("Requested account was not found");
|
||||
return;
|
||||
}
|
||||
Player player = Grasscutter.getGameServer().getPlayerByAccountId(account.getId());
|
||||
if (player == null) {
|
||||
ctx.status(403).result("No player associated with requested account");
|
||||
return;
|
||||
}
|
||||
|
||||
String template;
|
||||
try {
|
||||
template = Files.readString(detailsTemplate);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().warn("Failed to read data/gacha/details.html");
|
||||
ctx.status(500);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add translated title etc. to the page.
|
||||
template = template.replace("{{TITLE}}", translate(player, "gacha.details.title"))
|
||||
.replace("{{AVAILABLE_FIVE_STARS}}", translate(player, "gacha.details.available_five_stars"))
|
||||
.replace("{{AVAILABLE_FOUR_STARS}}", translate(player, "gacha.details.available_four_stars"))
|
||||
.replace("{{AVAILABLE_THREE_STARS}}", translate(player, "gacha.details.available_three_stars"))
|
||||
.replace("{{LANGUAGE}}", Utils.getLanguageCode(account.getLocale()));
|
||||
|
||||
// Get the banner info for the banner we want.
|
||||
int scheduleId = Integer.parseInt(ctx.queryParam("scheduleId"));
|
||||
GachaSystem manager = Grasscutter.getGameServer().getGachaSystem();
|
||||
GachaBanner banner = manager.getGachaBanners().get(scheduleId);
|
||||
|
||||
// Add 5-star items.
|
||||
Set<String> fiveStarItems = new LinkedHashSet<>();
|
||||
|
||||
Arrays.stream(banner.getRateUpItems5()).forEach(i -> fiveStarItems.add(Integer.toString(i)));
|
||||
Arrays.stream(banner.getFallbackItems5Pool1()).forEach(i -> fiveStarItems.add(Integer.toString(i)));
|
||||
Arrays.stream(banner.getFallbackItems5Pool2()).forEach(i -> fiveStarItems.add(Integer.toString(i)));
|
||||
|
||||
template = template.replace("{{FIVE_STARS}}", "[" + String.join(",", fiveStarItems) + "]");
|
||||
|
||||
// Add 4-star items.
|
||||
Set<String> fourStarItems = new LinkedHashSet<>();
|
||||
|
||||
Arrays.stream(banner.getRateUpItems4()).forEach(i -> fourStarItems.add(Integer.toString(i)));
|
||||
Arrays.stream(banner.getFallbackItems4Pool1()).forEach(i -> fourStarItems.add(Integer.toString(i)));
|
||||
Arrays.stream(banner.getFallbackItems4Pool2()).forEach(i -> fourStarItems.add(Integer.toString(i)));
|
||||
|
||||
template = template.replace("{{FOUR_STARS}}", "[" + String.join(",", fourStarItems) + "]");
|
||||
|
||||
// Add 3-star items.
|
||||
Set<String> threeStarItems = new LinkedHashSet<>();
|
||||
Arrays.stream(banner.getFallbackItems3()).forEach(i -> threeStarItems.add(Integer.toString(i)));
|
||||
template = template.replace("{{THREE_STARS}}", "[" + String.join(",", threeStarItems) + "]");
|
||||
|
||||
// Done.
|
||||
ctx.contentType(ContentType.TEXT_HTML);
|
||||
ctx.result(template);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
javalin.get("/gacha", GachaHandler::gachaRecords);
|
||||
javalin.get("/gacha/details", GachaHandler::gachaDetails);
|
||||
|
||||
javalin._conf.addSinglePageRoot("/gacha/mappings", gachaMappingsPath.toString(), Location.EXTERNAL); // TODO: This ***must*** be changed to take the Path not a String. This might involve upgrading Javalin.
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.handlers;
|
||||
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.database.DatabaseHelper;
|
||||
import emu.grasscutter.game.Account;
|
||||
import emu.grasscutter.game.gacha.GachaBanner;
|
||||
import emu.grasscutter.game.gacha.GachaSystem;
|
||||
import emu.grasscutter.game.player.Player;
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import emu.grasscutter.utils.FileUtils;
|
||||
import emu.grasscutter.utils.Utils;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
import io.javalin.http.staticfiles.Location;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import lombok.Getter;
|
||||
|
||||
/** Handles all gacha-related HTTP requests. */
|
||||
public final class GachaHandler implements Router {
|
||||
@Getter
|
||||
private static final Path gachaMappingsPath = FileUtils.getDataUserPath("gacha/mappings.js");
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static final String gachaMappings = gachaMappingsPath.toString();
|
||||
|
||||
private static void gachaRecords(Context ctx) {
|
||||
String sessionKey = ctx.queryParam("s");
|
||||
Account account = DatabaseHelper.getAccountBySessionKey(sessionKey);
|
||||
if (account == null) {
|
||||
ctx.status(403).result("Requested account was not found");
|
||||
return;
|
||||
}
|
||||
Player player = Grasscutter.getGameServer().getPlayerByAccountId(account.getId());
|
||||
if (player == null) {
|
||||
ctx.status(403).result("No player associated with requested account");
|
||||
return;
|
||||
}
|
||||
|
||||
int page = 0, gachaType = 0;
|
||||
if (ctx.queryParam("p") != null) page = Integer.parseInt(ctx.queryParam("p"));
|
||||
if (ctx.queryParam("gachaType") != null)
|
||||
gachaType = Integer.parseInt(ctx.queryParam("gachaType"));
|
||||
|
||||
String records = DatabaseHelper.getGachaRecords(player.getUid(), page, gachaType).toString();
|
||||
long maxPage = DatabaseHelper.getGachaRecordsMaxPage(player.getUid(), page, gachaType);
|
||||
|
||||
String template =
|
||||
new String(
|
||||
FileUtils.read(FileUtils.getDataPath("gacha/records.html")), StandardCharsets.UTF_8)
|
||||
.replace("{{REPLACE_RECORDS}}", records)
|
||||
.replace("{{REPLACE_MAXPAGE}}", String.valueOf(maxPage))
|
||||
.replace("{{TITLE}}", translate(player, "gacha.records.title"))
|
||||
.replace("{{DATE}}", translate(player, "gacha.records.date"))
|
||||
.replace("{{ITEM}}", translate(player, "gacha.records.item"))
|
||||
.replace("{{LANGUAGE}}", Utils.getLanguageCode(account.getLocale()));
|
||||
ctx.contentType(ContentType.TEXT_HTML);
|
||||
ctx.result(template);
|
||||
}
|
||||
|
||||
private static void gachaDetails(Context ctx) {
|
||||
Path detailsTemplate = FileUtils.getDataPath("gacha/details.html");
|
||||
String sessionKey = ctx.queryParam("s");
|
||||
Account account = DatabaseHelper.getAccountBySessionKey(sessionKey);
|
||||
if (account == null) {
|
||||
ctx.status(403).result("Requested account was not found");
|
||||
return;
|
||||
}
|
||||
Player player = Grasscutter.getGameServer().getPlayerByAccountId(account.getId());
|
||||
if (player == null) {
|
||||
ctx.status(403).result("No player associated with requested account");
|
||||
return;
|
||||
}
|
||||
|
||||
String template;
|
||||
try {
|
||||
template = Files.readString(detailsTemplate);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().warn("Failed to read data/gacha/details.html");
|
||||
ctx.status(500);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add translated title etc. to the page.
|
||||
template =
|
||||
template
|
||||
.replace("{{TITLE}}", translate(player, "gacha.details.title"))
|
||||
.replace(
|
||||
"{{AVAILABLE_FIVE_STARS}}", translate(player, "gacha.details.available_five_stars"))
|
||||
.replace(
|
||||
"{{AVAILABLE_FOUR_STARS}}", translate(player, "gacha.details.available_four_stars"))
|
||||
.replace(
|
||||
"{{AVAILABLE_THREE_STARS}}",
|
||||
translate(player, "gacha.details.available_three_stars"))
|
||||
.replace("{{LANGUAGE}}", Utils.getLanguageCode(account.getLocale()));
|
||||
|
||||
// Get the banner info for the banner we want.
|
||||
int scheduleId = Integer.parseInt(ctx.queryParam("scheduleId"));
|
||||
GachaSystem manager = Grasscutter.getGameServer().getGachaSystem();
|
||||
GachaBanner banner = manager.getGachaBanners().get(scheduleId);
|
||||
|
||||
// Add 5-star items.
|
||||
Set<String> fiveStarItems = new LinkedHashSet<>();
|
||||
|
||||
Arrays.stream(banner.getRateUpItems5()).forEach(i -> fiveStarItems.add(Integer.toString(i)));
|
||||
Arrays.stream(banner.getFallbackItems5Pool1())
|
||||
.forEach(i -> fiveStarItems.add(Integer.toString(i)));
|
||||
Arrays.stream(banner.getFallbackItems5Pool2())
|
||||
.forEach(i -> fiveStarItems.add(Integer.toString(i)));
|
||||
|
||||
template = template.replace("{{FIVE_STARS}}", "[" + String.join(",", fiveStarItems) + "]");
|
||||
|
||||
// Add 4-star items.
|
||||
Set<String> fourStarItems = new LinkedHashSet<>();
|
||||
|
||||
Arrays.stream(banner.getRateUpItems4()).forEach(i -> fourStarItems.add(Integer.toString(i)));
|
||||
Arrays.stream(banner.getFallbackItems4Pool1())
|
||||
.forEach(i -> fourStarItems.add(Integer.toString(i)));
|
||||
Arrays.stream(banner.getFallbackItems4Pool2())
|
||||
.forEach(i -> fourStarItems.add(Integer.toString(i)));
|
||||
|
||||
template = template.replace("{{FOUR_STARS}}", "[" + String.join(",", fourStarItems) + "]");
|
||||
|
||||
// Add 3-star items.
|
||||
Set<String> threeStarItems = new LinkedHashSet<>();
|
||||
Arrays.stream(banner.getFallbackItems3()).forEach(i -> threeStarItems.add(Integer.toString(i)));
|
||||
template = template.replace("{{THREE_STARS}}", "[" + String.join(",", threeStarItems) + "]");
|
||||
|
||||
// Done.
|
||||
ctx.contentType(ContentType.TEXT_HTML);
|
||||
ctx.result(template);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
javalin.get("/gacha", GachaHandler::gachaRecords);
|
||||
javalin.get("/gacha/details", GachaHandler::gachaDetails);
|
||||
|
||||
javalin._conf.addSinglePageRoot(
|
||||
"/gacha/mappings",
|
||||
gachaMappingsPath.toString(),
|
||||
Location.EXTERNAL); // TODO: This ***must*** be changed to take the Path not a String. This
|
||||
// might involve upgrading Javalin.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,57 +1,85 @@
|
||||
package emu.grasscutter.server.http.handlers;
|
||||
|
||||
import emu.grasscutter.GameConstants;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import emu.grasscutter.server.http.objects.HttpJsonResponse;
|
||||
import emu.grasscutter.server.http.objects.WebStaticVersionResponse;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.Context;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.ACCOUNT;
|
||||
|
||||
/**
|
||||
* Handles all generic, hard-coded responses.
|
||||
*/
|
||||
public final class GenericHandler implements Router {
|
||||
private static void serverStatus(Context ctx) {
|
||||
int playerCount = Grasscutter.getGameServer().getPlayers().size();
|
||||
int maxPlayer = ACCOUNT.maxPlayer;
|
||||
String version = GameConstants.VERSION;
|
||||
|
||||
ctx.result("{\"retcode\":0,\"status\":{\"playerCount\":" + playerCount + ",\"maxPlayer\":" + maxPlayer + ",\"version\":\"" + version + "\"}}");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
// hk4e-sdk-os.hoyoverse.com
|
||||
javalin.get("/hk4e_global/mdk/agreement/api/getAgreementInfos", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}"));
|
||||
// hk4e-sdk-os.hoyoverse.com (this could be either GET or POST based on the observation of different clients)
|
||||
this.allRoutes(javalin, "/hk4e_global/combo/granter/api/compareProtocolVersion", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":true,\"protocol\":{\"id\":0,\"app_id\":4,\"language\":\"en\",\"user_proto\":\"\",\"priv_proto\":\"\",\"major\":7,\"minimum\":0,\"create_time\":\"0\",\"teenager_proto\":\"\",\"third_proto\":\"\"}}}"));
|
||||
|
||||
// api-account-os.hoyoverse.com
|
||||
javalin.post("/account/risky/api/check", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}"));
|
||||
|
||||
// sdk-os-static.hoyoverse.com
|
||||
javalin.get("/combo/box/api/config/sdk/combo", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"disable_email_bind_skip\":\"false\",\"email_bind_remind_interval\":\"7\",\"email_bind_remind\":\"true\"}}}"));
|
||||
// hk4e-sdk-os-static.hoyoverse.com
|
||||
javalin.get("/hk4e_global/combo/granter/api/getConfig", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"protocol\":true,\"qr_enabled\":false,\"log_level\":\"INFO\",\"announce_url\":\"https://webstatic-sea.hoyoverse.com/hk4e/announcement/index.html?sdk_presentation_style=fullscreen\\u0026sdk_screen_transparent=true\\u0026game_biz=hk4e_global\\u0026auth_appid=announcement\\u0026game=hk4e#/\",\"push_alias_type\":2,\"disable_ysdk_guard\":false,\"enable_announce_pic_popup\":true}}"));
|
||||
// hk4e-sdk-os-static.hoyoverse.com
|
||||
javalin.get("/hk4e_global/mdk/shield/api/loadConfig", new HttpJsonResponse("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":6,\"game_key\":\"hk4e_global\",\"client\":\"PC\",\"identity\":\"I_IDENTITY\",\"guest\":false,\"ignore_versions\":\"\",\"scene\":\"S_NORMAL\",\"name\":\"原神海外\",\"disable_regist\":false,\"enable_email_captcha\":false,\"thirdparty\":[\"fb\",\"tw\"],\"disable_mmt\":false,\"server_guest\":false,\"thirdparty_ignore\":{\"tw\":\"\",\"fb\":\"\"},\"enable_ps_bind_account\":false,\"thirdparty_login_configs\":{\"tw\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800},\"fb\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800}}}}"));
|
||||
// Test api?
|
||||
// abtest-api-data-sg.hoyoverse.com
|
||||
javalin.post("/data_abtest_api/config/experiment/list", new HttpJsonResponse("{\"retcode\":0,\"success\":true,\"message\":\"\",\"data\":[{\"code\":1000,\"type\":2,\"config_id\":\"14\",\"period_id\":\"6036_99\",\"version\":\"1\",\"configs\":{\"cardType\":\"old\"}}]}"));
|
||||
|
||||
// log-upload-os.mihoyo.com
|
||||
this.allRoutes(javalin, "/log/sdk/upload", new HttpJsonResponse("{\"code\":0}"));
|
||||
this.allRoutes(javalin, "/sdk/upload", new HttpJsonResponse("{\"code\":0}"));
|
||||
javalin.post("/sdk/dataUpload", new HttpJsonResponse("{\"code\":0}"));
|
||||
// /perf/config/verify?device_id=xxx&platform=x&name=xxx
|
||||
this.allRoutes(javalin, "/perf/config/verify", new HttpJsonResponse("{\"code\":0}"));
|
||||
|
||||
// webstatic-sea.hoyoverse.com
|
||||
javalin.get("/admin/mi18n/plat_oversea/*", new WebStaticVersionResponse());
|
||||
|
||||
javalin.get("/status/server", GenericHandler::serverStatus);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.handlers;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.ACCOUNT;
|
||||
|
||||
import emu.grasscutter.GameConstants;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import emu.grasscutter.server.http.objects.HttpJsonResponse;
|
||||
import emu.grasscutter.server.http.objects.WebStaticVersionResponse;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.Context;
|
||||
|
||||
/** Handles all generic, hard-coded responses. */
|
||||
public final class GenericHandler implements Router {
|
||||
private static void serverStatus(Context ctx) {
|
||||
int playerCount = Grasscutter.getGameServer().getPlayers().size();
|
||||
int maxPlayer = ACCOUNT.maxPlayer;
|
||||
String version = GameConstants.VERSION;
|
||||
|
||||
ctx.result(
|
||||
"{\"retcode\":0,\"status\":{\"playerCount\":"
|
||||
+ playerCount
|
||||
+ ",\"maxPlayer\":"
|
||||
+ maxPlayer
|
||||
+ ",\"version\":\""
|
||||
+ version
|
||||
+ "\"}}");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
// hk4e-sdk-os.hoyoverse.com
|
||||
javalin.get(
|
||||
"/hk4e_global/mdk/agreement/api/getAgreementInfos",
|
||||
new HttpJsonResponse(
|
||||
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}"));
|
||||
// hk4e-sdk-os.hoyoverse.com (this could be either GET or POST based on the observation of
|
||||
// different clients)
|
||||
this.allRoutes(
|
||||
javalin,
|
||||
"/hk4e_global/combo/granter/api/compareProtocolVersion",
|
||||
new HttpJsonResponse(
|
||||
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":true,\"protocol\":{\"id\":0,\"app_id\":4,\"language\":\"en\",\"user_proto\":\"\",\"priv_proto\":\"\",\"major\":7,\"minimum\":0,\"create_time\":\"0\",\"teenager_proto\":\"\",\"third_proto\":\"\"}}}"));
|
||||
|
||||
// api-account-os.hoyoverse.com
|
||||
javalin.post(
|
||||
"/account/risky/api/check",
|
||||
new HttpJsonResponse(
|
||||
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}"));
|
||||
|
||||
// sdk-os-static.hoyoverse.com
|
||||
javalin.get(
|
||||
"/combo/box/api/config/sdk/combo",
|
||||
new HttpJsonResponse(
|
||||
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"disable_email_bind_skip\":\"false\",\"email_bind_remind_interval\":\"7\",\"email_bind_remind\":\"true\"}}}"));
|
||||
// hk4e-sdk-os-static.hoyoverse.com
|
||||
javalin.get(
|
||||
"/hk4e_global/combo/granter/api/getConfig",
|
||||
new HttpJsonResponse(
|
||||
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"protocol\":true,\"qr_enabled\":false,\"log_level\":\"INFO\",\"announce_url\":\"https://webstatic-sea.hoyoverse.com/hk4e/announcement/index.html?sdk_presentation_style=fullscreen\\u0026sdk_screen_transparent=true\\u0026game_biz=hk4e_global\\u0026auth_appid=announcement\\u0026game=hk4e#/\",\"push_alias_type\":2,\"disable_ysdk_guard\":false,\"enable_announce_pic_popup\":true}}"));
|
||||
// hk4e-sdk-os-static.hoyoverse.com
|
||||
javalin.get(
|
||||
"/hk4e_global/mdk/shield/api/loadConfig",
|
||||
new HttpJsonResponse(
|
||||
"{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":6,\"game_key\":\"hk4e_global\",\"client\":\"PC\",\"identity\":\"I_IDENTITY\",\"guest\":false,\"ignore_versions\":\"\",\"scene\":\"S_NORMAL\",\"name\":\"原神海外\",\"disable_regist\":false,\"enable_email_captcha\":false,\"thirdparty\":[\"fb\",\"tw\"],\"disable_mmt\":false,\"server_guest\":false,\"thirdparty_ignore\":{\"tw\":\"\",\"fb\":\"\"},\"enable_ps_bind_account\":false,\"thirdparty_login_configs\":{\"tw\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800},\"fb\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800}}}}"));
|
||||
// Test api?
|
||||
// abtest-api-data-sg.hoyoverse.com
|
||||
javalin.post(
|
||||
"/data_abtest_api/config/experiment/list",
|
||||
new HttpJsonResponse(
|
||||
"{\"retcode\":0,\"success\":true,\"message\":\"\",\"data\":[{\"code\":1000,\"type\":2,\"config_id\":\"14\",\"period_id\":\"6036_99\",\"version\":\"1\",\"configs\":{\"cardType\":\"old\"}}]}"));
|
||||
|
||||
// log-upload-os.mihoyo.com
|
||||
this.allRoutes(javalin, "/log/sdk/upload", new HttpJsonResponse("{\"code\":0}"));
|
||||
this.allRoutes(javalin, "/sdk/upload", new HttpJsonResponse("{\"code\":0}"));
|
||||
javalin.post("/sdk/dataUpload", new HttpJsonResponse("{\"code\":0}"));
|
||||
// /perf/config/verify?device_id=xxx&platform=x&name=xxx
|
||||
this.allRoutes(javalin, "/perf/config/verify", new HttpJsonResponse("{\"code\":0}"));
|
||||
|
||||
// webstatic-sea.hoyoverse.com
|
||||
javalin.get("/admin/mi18n/plat_oversea/*", new WebStaticVersionResponse());
|
||||
|
||||
javalin.get("/status/server", GenericHandler::serverStatus);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
package emu.grasscutter.server.http.handlers;
|
||||
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.Context;
|
||||
|
||||
/**
|
||||
* Handles logging requests made to the server.
|
||||
*/
|
||||
public final class LogHandler implements Router {
|
||||
private static void log(Context ctx) {
|
||||
// TODO: Figure out how to dump request body and log to file.
|
||||
ctx.result("{\"code\":0}");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
// overseauspider.yuanshen.com
|
||||
javalin.post("/log", LogHandler::log);
|
||||
// log-upload-os.mihoyo.com
|
||||
javalin.post("/crash/dataUpload", LogHandler::log);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.handlers;
|
||||
|
||||
import emu.grasscutter.server.http.Router;
|
||||
import io.javalin.Javalin;
|
||||
import io.javalin.http.Context;
|
||||
|
||||
/** Handles logging requests made to the server. */
|
||||
public final class LogHandler implements Router {
|
||||
private static void log(Context ctx) {
|
||||
// TODO: Figure out how to dump request body and log to file.
|
||||
ctx.result("{\"code\":0}");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyRoutes(Javalin javalin) {
|
||||
// overseauspider.yuanshen.com
|
||||
javalin.post("/log", LogHandler::log);
|
||||
// log-upload-os.mihoyo.com
|
||||
javalin.post("/crash/dataUpload", LogHandler::log);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
public class ComboTokenReqJson {
|
||||
public int app_id;
|
||||
public int channel_id;
|
||||
public String data;
|
||||
public String device;
|
||||
public String sign;
|
||||
|
||||
public static class LoginTokenData {
|
||||
public String uid;
|
||||
public String token;
|
||||
public boolean guest;
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
public class ComboTokenReqJson {
|
||||
public int app_id;
|
||||
public int channel_id;
|
||||
public String data;
|
||||
public String device;
|
||||
public String sign;
|
||||
|
||||
public static class LoginTokenData {
|
||||
public String uid;
|
||||
public String token;
|
||||
public boolean guest;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
public class ComboTokenResJson {
|
||||
public String message;
|
||||
public int retcode;
|
||||
public LoginData data = new LoginData();
|
||||
|
||||
public static class LoginData {
|
||||
public int account_type = 1;
|
||||
public boolean heartbeat;
|
||||
public String combo_id;
|
||||
public String combo_token;
|
||||
public String open_id;
|
||||
public String data = "{\"guest\":false}";
|
||||
public String fatigue_remind = null; // ?
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
public class ComboTokenResJson {
|
||||
public String message;
|
||||
public int retcode;
|
||||
public LoginData data = new LoginData();
|
||||
|
||||
public static class LoginData {
|
||||
public int account_type = 1;
|
||||
public boolean heartbeat;
|
||||
public String combo_id;
|
||||
public String combo_token;
|
||||
public String open_id;
|
||||
public String data = "{\"guest\":false}";
|
||||
public String fatigue_remind = null; // ?
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,42 +1,52 @@
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.Grasscutter.ServerDebugMode;
|
||||
import io.javalin.http.Context;
|
||||
import io.javalin.http.Handler;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
|
||||
public final class HttpJsonResponse implements Handler {
|
||||
private final String response;
|
||||
private final String[] missingRoutes = { // TODO: When http requests for theses routes are found please remove it from this list and update the route request type in the DispatchServer
|
||||
"/common/hk4e_global/announcement/api/getAlertPic",
|
||||
"/common/hk4e_global/announcement/api/getAlertAnn",
|
||||
"/common/hk4e_global/announcement/api/getAnnList",
|
||||
"/common/hk4e_global/announcement/api/getAnnContent",
|
||||
"/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier",
|
||||
"/log/sdk/upload",
|
||||
"/sdk/upload",
|
||||
"/perf/config/verify",
|
||||
"/log",
|
||||
"/crash/dataUpload"
|
||||
};
|
||||
|
||||
public HttpJsonResponse(String response) {
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(@NotNull Context ctx) throws Exception {
|
||||
// Checking for ALL here isn't required as when ALL is enabled enableDevLogging() gets enabled
|
||||
if (DISPATCH_INFO.logRequests == ServerDebugMode.MISSING && Arrays.stream(missingRoutes).anyMatch(x -> Objects.equals(x, ctx.endpointHandlerPath()))) {
|
||||
Grasscutter.getLogger().info(translate("messages.dispatch.request", ctx.ip(), ctx.method(), ctx.endpointHandlerPath()) + (DISPATCH_INFO.logRequests == ServerDebugMode.MISSING ? "(MISSING)" : ""));
|
||||
}
|
||||
ctx.result(response);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.Grasscutter.ServerDebugMode;
|
||||
import io.javalin.http.Context;
|
||||
import io.javalin.http.Handler;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public final class HttpJsonResponse implements Handler {
|
||||
private final String response;
|
||||
private final String[]
|
||||
missingRoutes = { // TODO: When http requests for theses routes are found please remove it
|
||||
// from this list and update the route request type in the DispatchServer
|
||||
"/common/hk4e_global/announcement/api/getAlertPic",
|
||||
"/common/hk4e_global/announcement/api/getAlertAnn",
|
||||
"/common/hk4e_global/announcement/api/getAnnList",
|
||||
"/common/hk4e_global/announcement/api/getAnnContent",
|
||||
"/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier",
|
||||
"/log/sdk/upload",
|
||||
"/sdk/upload",
|
||||
"/perf/config/verify",
|
||||
"/log",
|
||||
"/crash/dataUpload"
|
||||
};
|
||||
|
||||
public HttpJsonResponse(String response) {
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(@NotNull Context ctx) throws Exception {
|
||||
// Checking for ALL here isn't required as when ALL is enabled enableDevLogging() gets enabled
|
||||
if (DISPATCH_INFO.logRequests == ServerDebugMode.MISSING
|
||||
&& Arrays.stream(missingRoutes)
|
||||
.anyMatch(x -> Objects.equals(x, ctx.endpointHandlerPath()))) {
|
||||
Grasscutter.getLogger()
|
||||
.info(
|
||||
translate(
|
||||
"messages.dispatch.request",
|
||||
ctx.ip(),
|
||||
ctx.method(),
|
||||
ctx.endpointHandlerPath())
|
||||
+ (DISPATCH_INFO.logRequests == ServerDebugMode.MISSING ? "(MISSING)" : ""));
|
||||
}
|
||||
ctx.result(response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
public class LoginAccountRequestJson {
|
||||
public String account;
|
||||
public String password;
|
||||
public boolean is_crypto;
|
||||
}
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
public class LoginAccountRequestJson {
|
||||
public String account;
|
||||
public String password;
|
||||
public boolean is_crypto;
|
||||
}
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
public class LoginResultJson {
|
||||
public String message;
|
||||
public int retcode;
|
||||
public VerifyData data = new VerifyData();
|
||||
|
||||
public static class VerifyData {
|
||||
public VerifyAccountData account = new VerifyAccountData();
|
||||
public boolean device_grant_required = false;
|
||||
public String realname_operation = "NONE";
|
||||
public boolean realperson_required = false;
|
||||
public boolean safe_mobile_required = false;
|
||||
}
|
||||
|
||||
public static class VerifyAccountData {
|
||||
public String uid;
|
||||
public String name = "";
|
||||
public String email = "";
|
||||
public String mobile = "";
|
||||
public String is_email_verify = "0";
|
||||
public String realname = "";
|
||||
public String identity_card = "";
|
||||
public String token;
|
||||
public String safe_mobile = "";
|
||||
public String facebook_name = "";
|
||||
public String twitter_name = "";
|
||||
public String game_center_name = "";
|
||||
public String google_name = "";
|
||||
public String apple_name = "";
|
||||
public String sony_name = "";
|
||||
public String tap_name = "";
|
||||
public String country = "US";
|
||||
public String reactivate_ticket = "";
|
||||
public String area_code = "**";
|
||||
public String device_grant_ticket = "";
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
public class LoginResultJson {
|
||||
public String message;
|
||||
public int retcode;
|
||||
public VerifyData data = new VerifyData();
|
||||
|
||||
public static class VerifyData {
|
||||
public VerifyAccountData account = new VerifyAccountData();
|
||||
public boolean device_grant_required = false;
|
||||
public String realname_operation = "NONE";
|
||||
public boolean realperson_required = false;
|
||||
public boolean safe_mobile_required = false;
|
||||
}
|
||||
|
||||
public static class VerifyAccountData {
|
||||
public String uid;
|
||||
public String name = "";
|
||||
public String email = "";
|
||||
public String mobile = "";
|
||||
public String is_email_verify = "0";
|
||||
public String realname = "";
|
||||
public String identity_card = "";
|
||||
public String token;
|
||||
public String safe_mobile = "";
|
||||
public String facebook_name = "";
|
||||
public String twitter_name = "";
|
||||
public String game_center_name = "";
|
||||
public String google_name = "";
|
||||
public String apple_name = "";
|
||||
public String sony_name = "";
|
||||
public String tap_name = "";
|
||||
public String country = "US";
|
||||
public String reactivate_ticket = "";
|
||||
public String area_code = "**";
|
||||
public String device_grant_ticket = "";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
public class LoginTokenRequestJson {
|
||||
public String uid;
|
||||
public String token;
|
||||
}
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
public class LoginTokenRequestJson {
|
||||
public String uid;
|
||||
public String token;
|
||||
}
|
||||
|
||||
@@ -1,35 +1,35 @@
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.utils.FileUtils;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
import io.javalin.http.Handler;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
|
||||
public class WebStaticVersionResponse implements Handler {
|
||||
|
||||
private static void getPageResources(String path, Context ctx) {
|
||||
try (InputStream filestream = FileUtils.readResourceAsStream(path)) {
|
||||
ContentType fromExtension = ContentType.getContentTypeByExtension(path.substring(path.lastIndexOf(".") + 1));
|
||||
ctx.contentType(fromExtension != null ? fromExtension : ContentType.APPLICATION_OCTET_STREAM);
|
||||
ctx.result(filestream.readAllBytes());
|
||||
} catch (Exception e) {
|
||||
if (DISPATCH_INFO.logRequests == Grasscutter.ServerDebugMode.MISSING) {
|
||||
Grasscutter.getLogger().warn("Webstatic File Missing: " + path);
|
||||
}
|
||||
ctx.status(404);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(Context ctx) throws IOException {
|
||||
String requestFor = ctx.path().substring(ctx.path().lastIndexOf("-") + 1);
|
||||
|
||||
getPageResources("/webstatic/" + requestFor, ctx);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.server.http.objects;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.utils.FileUtils;
|
||||
import io.javalin.http.ContentType;
|
||||
import io.javalin.http.Context;
|
||||
import io.javalin.http.Handler;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
public class WebStaticVersionResponse implements Handler {
|
||||
|
||||
private static void getPageResources(String path, Context ctx) {
|
||||
try (InputStream filestream = FileUtils.readResourceAsStream(path)) {
|
||||
ContentType fromExtension =
|
||||
ContentType.getContentTypeByExtension(path.substring(path.lastIndexOf(".") + 1));
|
||||
ctx.contentType(fromExtension != null ? fromExtension : ContentType.APPLICATION_OCTET_STREAM);
|
||||
ctx.result(filestream.readAllBytes());
|
||||
} catch (Exception e) {
|
||||
if (DISPATCH_INFO.logRequests == Grasscutter.ServerDebugMode.MISSING) {
|
||||
Grasscutter.getLogger().warn("Webstatic File Missing: " + path);
|
||||
}
|
||||
ctx.status(404);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(Context ctx) throws IOException {
|
||||
String requestFor = ctx.path().substring(ctx.path().lastIndexOf("-") + 1);
|
||||
|
||||
getPageResources("/webstatic/" + requestFor, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user