mirror of
https://github.com/Grasscutters/Grasscutter.git
synced 2026-06-05 05:15:10 +08:00
Merge unstable into development (#2173)
* Remove more scene synchronized
* Fix worktop options not appearing
* Format code [skip actions]
* Fix delay with server tasks
* Format code [skip actions]
* Fully fix fairy clock (#2146)
* Fix scene transition
* fully fix fairy clock
* Re-add call to `Player#updatePlayerGameTime`
* Format code [skip actions]
* Initialize the script loader in `ResourceLoader#loadAll`
* Fix region removal checking
* Format code [skip actions]
* Use Lombok's `EqualsAndHashCode` for comparing scene regions
* Format code [skip actions]
* Move 'invalid gather object' to `trace`
* Add more information to the 'unknown condition handler' message
* Move invalid ability action to trace
* Make `KcpTunnel` public
* Validate the NPC being talked to
* Format code [skip actions]
* NPCs are not spawned server side; change logic to handle it
* Format code [skip actions]
* unload scene when there are no players (#2147)
* unload scene when there are no players
* Update src/main/java/emu/grasscutter/game/world/Scene.java
Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>
---------
Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>
* Check if a command should be copied or HTTP should be used
* Lint Code [skip actions]
* Fix character names rendering incorrectly
* Add basic troubleshooting command
* Implement handbook teleporting
also a few formatting changes and sort data by logical sense
* Fix listener `ConcurrentModificationException` issue
* Add color change to `Join the Community!`
* Lint Code [skip actions]
* Make clickable buttons appear clickable
* Remove 'Mechanicus' entities from the list of entities
* Format code [skip actions]
* Fix going back returning a blank screen
* Implement entity spawning
* Add setting level to entity card
* Add support for 'plain text' mode
* Make descriptions of objects scrollable
* Lint Code [skip actions]
* Format code [skip actions]
* Change the way existing hooks work
* Format code [skip actions]
* Upgrade Javalin to 5.5.0 & Fix project warnings
* Upgrade logging libraries
* Fix gacha mappings static file issue
* Add temporary backwards compatability for `ServerHelper`
* Format code [skip actions]
* Remove artifact signatures from VCS
* Fix forge queue data protocol definition
* Run `spotlessApply`
* Format code [skip actions]
* Download data required for building artifacts
* Add call for Facebook logins
* Add the wiki page as a submodule
* Format code [skip actions]
* Update translation (#2150)
* Update translation
* Update translation
* Separate the dispatch and game servers (pt. 1)
gacha is still broken, handbook still needs to be done
* Format code [skip actions]
* Separate the dispatch and game servers (pt. 2)
this commit fixes the gacha page
* Add description for '/troubleshoot'
* Set default avatar talent level to 10
* Separate the dispatch and game servers (pt. 3)
implement handbook across servers!
* Format code [skip actions]
* Update GitHub Actions to use 'download-file' over 'wget'
* Gm handbook lmao (#2149)
* Fix font issue
* Fix avatars
* Fix text overflow in commands
* Fix virtualized lists and items page 😭😭
* magix why 💀
* use hover style in all minicards
* button
* remove console.log
* lint
* Add icons
* magix asked
* Fix overflow padding issue
* Fix achievement text overflow
* remove icons from repo
* Change command icon
* Add the wiki page as a submodule
* total magix moment
* fix text overflow in commands
* Fix discord button
* Make text scale on Minicard
* import icons and font from another source
* Add hover effects to siebar buttons
* move font and readme to submodule repo
* Make data folder a submodule
* import icons and font from data submodule
* Update README.md
* total magix moment
* magix moment v2
* submodule change
* Import `.webp` files
* Resize `HomeButton`
* Fix 'Copy Command' reappearing after changing pages
---------
Co-authored-by: KingRainbow44 <kobedo11@gmail.com>
* Lint Code [skip actions]
* Download data for the build, not for the lint
* format imports
this is really just to see if build handbook works kek
* Implement proper handbook authentication (pt. 1)
* Implement proper handbook authentication (pt. 2)
* Format code [skip actions]
* Add quest data dumping for the handbook
* Change colors to fit _something suitable_
* Format code [skip actions]
* Fix force pushing to branches after linting
* Fix logic of `SetPlayerPropReq`
* Move more group loading to `trace`
* Add handbook IP authentication in hybrid mode
* Fix player level up not displaying on the client properly
* Format code [skip actions]
* Fix game time locking
* Format code [skip actions]
* Update player properties
* Format code [skip actions]
* Move `warn`s for groups to `debug`
* Fix player pausing
* Move more logs to `trace`
* Use `removeItemById` for deleting items via quests
* Clean up logger more
* Pause in-game time when the world is paused
* Format code [skip actions]
* More player property documentation
* Multi-threaded resource loading
* Format code [skip actions]
* Add quest widgets
* Add quests page (basic impl.)
* Add/fix colors
also fix tailwind
* Remove banned packets
client modifications already perform the job of blocking malicious packets from being executed, no point in having this if self-windy is wanted
* Re-add `BeginCameraSceneLookNotify`
* Fix being unable to attack (#2157)
* Add `PlayerOpenChestEvent`
* Add methods to get players from the server
* Add static methods to register an event handler
* Add `PlayerEnterDungeonEvent`
* Remove legacy documentation from `PlayerMoveEvent`
* Add `PlayerChatEvent`
* Add defaults to `Position`
* Clean up `.utils`
* Revert `Multi-threaded resource loading`
* Fix changing target UID when talking to the server
* Lint Code [skip actions]
* Format code [skip actions]
* fix NPC talk triggering main quest in 46101 (#2158)
Make it so that only talks where the param matches the talkId are checked.
* Format code [skip actions]
* Partially fix Chasing Shadows (#2159)
* Partially fix Chasing Shadows
* Go ahead and move it before the return before Magix tells me to.
* Format code [skip actions]
* Bring back period lol (#2160)
* Disable SNI for the HTTPS server
* Add `EntityCreationEvent`
* Add initial startup message
this is so the server appears like its preparing to start
* Format code [skip actions]
* Enable debug mode for plugin loggers if enabled for the primary logger
* Add documentation about `WorldAreaConfigData`
* Make more fields in excels accessible
* Remove deprecated fields from `GetShopRsp`
* Run `spotlessApply` on definitions
* Add `PlayerEnterAreaEvent`
* Optimize event calls
* Fix event invokes
* Format code [skip actions]
* Remove manual autofinish for main quests. (#2162)
* Add world areas to the textmap cache
* Format code [skip actions]
* Don't overdefine variables in extended classes (#2163)
* Add dumper for world areas
* Format code [skip actions]
* instantiate personalLineList (#2165)
* Fix protocol definitions
thank you Nazrin! (+ hiro for raw definitions)
* Fix the background color leaking from the character widget
* Change HTML spacing to 2 spaces
* Implement hiding widgets
* Change scrollbar to a vibrant color
* Add _some_ scaling to the home buttons and its text
* Build the handbook with Gradle
* Fix the 'finer details' with the handbook UI
* Lint Code [skip actions]
* Fix target destination for the Gradle-built handbook
* Implement fetching a player across servers & Add a chainable JsonObject
useful for plugins! might be used in grasscutter eventually
* Fix GitHub actions
* Fix event calling & canceling
* Run `spotlessApply`
* Rename fields (might be wrong)
* Add/update all/more protocol definitions
* Add/update all/more protocol definitions
* Remove outdated packet
* Fix protocol definitions
* Format code [skip actions]
* Implement some lua variables for less console spam (#2172)
* Implement some lua variables for less console spam
* Add GetHostQuestState
This fixes some chapter 3 stuff.
* Format code [skip actions]
* Fix merge import
* Format code [skip actions]
* Fully fix fairy clock for real this time (#2167)
* Fully fix fairy clock For real this time
* Make it so relogging keeps the time lock state.
* Refactor out questLockTime
* Per Hartie, the client packet needs to be changed too
* Update src/main/java/emu/grasscutter/game/world/World.java
Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>
* Update src/main/java/emu/grasscutter/server/packet/recv/HandlerClientLockGameTimeNotify.java
* Remove all code not needed to get clock working
---------
Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>
* Implement a proper ability system (#2166)
* Apply fix `21dec2fe`
* Apply fix `89d01d5f`
* Apply fix `d900f154`
this one was already implemented; updated to use call from previous commit
* Ability changing commit
TODO: change info to debug
* Remove use of deprecated methods/fields
* Temp commit v2
(Adding LoseHP and some fixes)
* Oopsie
* Probably fix monster battle
* Fix issue with reflecting into fields
* Fix some things
* Fix ability names for 3.6 resources
* Improve logging
---------
Co-authored-by: StartForKiller <jesussanz2003@gmail.com>
* Format code [skip actions]
* Add system for sending messages between servers
* Format some code
* Remove protocol definitions from Spotless
* Default debug to false; enable with `-debug`
* Implement completely useless global value copying
* HACK: Return the avatar which holds the weapon when the weapon is referred to by ID
* Add properties to `AbilityModifier`
* Change the way HTML is served after authentication
* Use thread executors to speed up the database loading process
* Format code [skip actions]
* Add system for setting handbook address and port
* Lint Code [skip actions]
* Format code [skip actions]
* Fix game-related data not saving
* Format code [skip actions]
* Fix handbook server details
* Lint Code [skip actions]
* Format code [skip actions]
* Use the headers provided by a context to get the IP address
should acknowledge #1975
* Format code [skip actions]
* Move more logs to `trace`
* Format code [skip actions]
* more trace
* Fix something and implement weapon entities
* Format code [skip actions]
* Fix `EntityWeapon`
* Remove deprecated API & Fix resource checking
* Fix unnecessary warning for first-time setup
* Implement handbook request limiting
* Format code [skip actions]
* Fix new avatar weapons being null
* Format code [skip actions]
* Fix issue with 35303 being un-completable & Try to fix fulfilled quest conditions being met
* Load activity config on server startup
* Require plugins to specify an API version and match with the server
* Add default open state ignore list
* Format code [skip actions]
* Quick fix for questing, needs more investigation
This would make the questing work again
* Remove existing hack for 35303
* Fix ignored open states from being set
* Format code [skip actions]
* fix the stupidest bug ive ever seen
* Optimize player kicking on server close
* Format code [skip actions]
* Re-add hack to fix 35303
* Update GitHub actions
* Format code [skip actions]
* Potentially fix issues with regions
* Download additional handbook data
* Revert "Potentially fix issues with regions"
This reverts commit 84e3823695.
---------
Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: scooterboo <lewasite@yahoo.com>
Co-authored-by: Tesutarin <105267106+Tesutarin@users.noreply.github.com>
Co-authored-by: Scald <104459145+Arikatsu@users.noreply.github.com>
Co-authored-by: StartForKiller <jesussanz2003@gmail.com>
This commit is contained in:
@@ -0,0 +1,224 @@
|
||||
package emu.grasscutter.server.dispatch;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.database.DatabaseHelper;
|
||||
import emu.grasscutter.server.event.dispatch.ServerMessageEvent;
|
||||
import emu.grasscutter.server.game.GameServer;
|
||||
import emu.grasscutter.server.http.handlers.GachaHandler;
|
||||
import emu.grasscutter.utils.Crypto;
|
||||
import emu.grasscutter.utils.DispatchUtils;
|
||||
import emu.grasscutter.utils.JsonUtils;
|
||||
import emu.grasscutter.utils.objects.HandbookBody;
|
||||
import java.net.ConnectException;
|
||||
import java.net.URI;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import lombok.Getter;
|
||||
import org.java_websocket.WebSocket;
|
||||
import org.java_websocket.client.WebSocketClient;
|
||||
import org.java_websocket.handshake.ServerHandshake;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public final class DispatchClient extends WebSocketClient implements IDispatcher {
|
||||
@Getter private final Logger logger = Grasscutter.getLogger();
|
||||
@Getter private final Map<Integer, BiConsumer<WebSocket, JsonElement>> handlers = new HashMap<>();
|
||||
|
||||
@Getter private final Map<Integer, List<Consumer<JsonElement>>> callbacks = new HashMap<>();
|
||||
|
||||
public DispatchClient(URI serverUri) {
|
||||
super(serverUri);
|
||||
|
||||
// Mark this client as authenticated.
|
||||
this.setAttachment(true);
|
||||
|
||||
this.registerHandler(PacketIds.GachaHistoryReq, this::fetchGachaHistory);
|
||||
this.registerHandler(PacketIds.GmTalkReq, this::handleHandbookAction);
|
||||
this.registerHandler(PacketIds.GetPlayerFieldsReq, this::fetchPlayerFields);
|
||||
this.registerHandler(PacketIds.GetPlayerByAccountReq, this::fetchPlayerByAccount);
|
||||
this.registerHandler(PacketIds.ServerMessageNotify, ServerMessageEvent::invoke);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the gacha history request packet sent by the client.
|
||||
*
|
||||
* @param socket The socket the packet was received from.
|
||||
* @param object The packet data.
|
||||
*/
|
||||
private void fetchGachaHistory(WebSocket socket, JsonElement object) {
|
||||
var message = IDispatcher.decode(object);
|
||||
var accountId = message.get("accountId").getAsString();
|
||||
var page = message.get("page").getAsInt();
|
||||
var type = message.get("gachaType").getAsInt();
|
||||
|
||||
// Create a response object.
|
||||
var response = new JsonObject();
|
||||
|
||||
// Find a player with the specified account ID.
|
||||
var player = DatabaseHelper.getPlayerByAccount(accountId);
|
||||
if (player == null) {
|
||||
response.addProperty("retcode", 1);
|
||||
this.sendMessage(PacketIds.GachaHistoryRsp, response);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch the gacha records.
|
||||
GachaHandler.fetchGachaRecords(player, response, page, type);
|
||||
|
||||
// Send the response.
|
||||
this.sendMessage(PacketIds.GachaHistoryRsp, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the handbook action packet sent by the client.
|
||||
*
|
||||
* @param socket The socket the packet was received from.
|
||||
* @param object The packet data.
|
||||
*/
|
||||
private void handleHandbookAction(WebSocket socket, JsonElement object) {
|
||||
var message = IDispatcher.decode(object);
|
||||
var actionStr = message.get("action").getAsString();
|
||||
var data = message.getAsJsonObject("data");
|
||||
|
||||
// Parse the action into an enum.
|
||||
var action = HandbookBody.Action.valueOf(actionStr);
|
||||
|
||||
// Produce a handbook response.
|
||||
var response =
|
||||
DispatchUtils.performHandbookAction(
|
||||
action,
|
||||
switch (action) {
|
||||
case GRANT_AVATAR -> JsonUtils.decode(data, HandbookBody.GrantAvatar.class);
|
||||
case GIVE_ITEM -> JsonUtils.decode(data, HandbookBody.GiveItem.class);
|
||||
case TELEPORT_TO -> JsonUtils.decode(data, HandbookBody.TeleportTo.class);
|
||||
case SPAWN_ENTITY -> JsonUtils.decode(data, HandbookBody.SpawnEntity.class);
|
||||
});
|
||||
|
||||
// Check if the response's status is '1'.
|
||||
if (response.getStatus() == 1) return;
|
||||
|
||||
// Send the response to the server.
|
||||
this.sendMessage(PacketIds.GmTalkRsp, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the fields of a player.
|
||||
*
|
||||
* @param socket The socket the packet was received from.
|
||||
* @param object The packet data.
|
||||
*/
|
||||
private void fetchPlayerFields(WebSocket socket, JsonElement object) {
|
||||
var message = IDispatcher.decode(object);
|
||||
var playerId = message.get("playerId").getAsInt();
|
||||
var fieldsRaw = message.get("fields").getAsJsonArray();
|
||||
|
||||
// Get the player with the specified ID.
|
||||
var player = Grasscutter.getGameServer().getPlayerByUid(playerId, true);
|
||||
if (player == null) return;
|
||||
|
||||
// Convert the fields array.
|
||||
var fieldsList = new ArrayList<String>();
|
||||
for (var field : fieldsRaw) fieldsList.add(field.getAsString());
|
||||
var fields = fieldsList.toArray(new String[0]);
|
||||
|
||||
// Return the response object.
|
||||
this.sendMessage(PacketIds.GetPlayerFieldsRsp, DispatchUtils.getPlayerFields(playerId, fields));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the fields of a player by the account.
|
||||
*
|
||||
* @param socket The socket the packet was received from.
|
||||
* @param object The packet data.
|
||||
*/
|
||||
private void fetchPlayerByAccount(WebSocket socket, JsonElement object) {
|
||||
var message = IDispatcher.decode(object);
|
||||
var accountId = message.get("accountId").getAsString();
|
||||
var fieldsRaw = message.get("fields").getAsJsonArray();
|
||||
|
||||
// Get the player with the specified ID.
|
||||
var player = Grasscutter.getGameServer().getPlayerByAccountId(accountId);
|
||||
if (player == null) return;
|
||||
|
||||
// Convert the fields array.
|
||||
var fieldsList = new ArrayList<String>();
|
||||
for (var field : fieldsRaw) fieldsList.add(field.getAsString());
|
||||
var fields = fieldsList.toArray(new String[0]);
|
||||
|
||||
// Return the response object.
|
||||
this.sendMessage(
|
||||
PacketIds.GetPlayerByAccountRsp, DispatchUtils.getPlayerByAccount(accountId, fields));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a serialized encrypted message to the server.
|
||||
*
|
||||
* @param message The message to send.
|
||||
*/
|
||||
public void sendMessage(int packetId, Object message) {
|
||||
var serverMessage = this.encodeMessage(packetId, message);
|
||||
// Serialize the message into JSON.
|
||||
var serialized = JSON.toJson(serverMessage).getBytes(StandardCharsets.UTF_8);
|
||||
// Encrypt the message.
|
||||
Crypto.xor(serialized, DISPATCH_INFO.encryptionKey);
|
||||
// Send the message.
|
||||
this.send(serialized);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(ServerHandshake handshake) {
|
||||
// Attempt to handshake with the server.
|
||||
this.sendMessage(PacketIds.LoginNotify, DISPATCH_INFO.dispatchKey);
|
||||
|
||||
this.getLogger().info("Dispatch connection opened.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(String message) {
|
||||
this.getLogger().debug("Received dispatch message from server:\n{}", message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(ByteBuffer bytes) {
|
||||
this.handleMessage(this, bytes.array());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(int code, String reason, boolean remote) {
|
||||
this.getLogger().info("Dispatch connection closed.");
|
||||
|
||||
// Attempt to reconnect.
|
||||
new Thread(
|
||||
() -> {
|
||||
try {
|
||||
// Wait 5 seconds before reconnecting.
|
||||
Thread.sleep(5000L);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
|
||||
// Attempt to reconnect.
|
||||
Grasscutter.getGameServer()
|
||||
.setDispatchClient(new DispatchClient(GameServer.getDispatchUrl()));
|
||||
Grasscutter.getGameServer().getDispatchClient().connect();
|
||||
})
|
||||
.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Exception ex) {
|
||||
if (ex instanceof ConnectException) {
|
||||
this.getLogger().info("Failed to reconnect, trying again in 5s...");
|
||||
} else {
|
||||
this.getLogger().error("Dispatch connection error.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package emu.grasscutter.server.dispatch;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.database.DatabaseHelper;
|
||||
import emu.grasscutter.server.event.dispatch.ServerMessageEvent;
|
||||
import emu.grasscutter.utils.Crypto;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import lombok.Getter;
|
||||
import org.java_websocket.WebSocket;
|
||||
import org.java_websocket.handshake.ClientHandshake;
|
||||
import org.java_websocket.server.WebSocketServer;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
/* Internal communications server. */
|
||||
public final class DispatchServer extends WebSocketServer implements IDispatcher {
|
||||
@Getter private final Logger logger = Grasscutter.getLogger();
|
||||
@Getter private final Map<Integer, BiConsumer<WebSocket, JsonElement>> handlers = new HashMap<>();
|
||||
|
||||
@Getter private final Map<Integer, List<Consumer<JsonElement>>> callbacks = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Constructs a new {@code DispatchServer} instance.
|
||||
*
|
||||
* @param address The address to bind to.
|
||||
* @param port The port to bind to.
|
||||
*/
|
||||
public DispatchServer(String address, int port) {
|
||||
super(new InetSocketAddress(address, port));
|
||||
|
||||
this.registerHandler(PacketIds.LoginNotify, this::handleLogin);
|
||||
this.registerHandler(PacketIds.TokenValidateReq, this::validateToken);
|
||||
this.registerHandler(PacketIds.GetAccountReq, this::fetchAccount);
|
||||
this.registerHandler(PacketIds.ServerMessageNotify, ServerMessageEvent::invoke);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the login packet sent by the client.
|
||||
*
|
||||
* @param socket The socket the packet was received from.
|
||||
* @param object The packet data.
|
||||
*/
|
||||
private void handleLogin(WebSocket socket, JsonElement object) {
|
||||
var dispatchKey = object.getAsString().replaceAll("\"", "");
|
||||
|
||||
// Check if the dispatch key is valid.
|
||||
if (!dispatchKey.equals(DISPATCH_INFO.dispatchKey)) {
|
||||
this.getLogger()
|
||||
.warn("Invalid dispatch key received from {}.", socket.getRemoteSocketAddress());
|
||||
this.getLogger().debug("Expected: {}, Received: {}", DISPATCH_INFO.dispatchKey, dispatchKey);
|
||||
socket.close();
|
||||
} else {
|
||||
socket.setAttachment(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the token validation packet sent by the client.
|
||||
*
|
||||
* @param socket The socket the packet was received from.
|
||||
* @param object The packet data.
|
||||
*/
|
||||
private void validateToken(WebSocket socket, JsonElement object) {
|
||||
var message = IDispatcher.decode(object);
|
||||
var accountId = message.get("uid").getAsString();
|
||||
var token = message.get("token").getAsString();
|
||||
|
||||
// Get the account from the database.
|
||||
var account = DatabaseHelper.getAccountById(accountId);
|
||||
var valid = account != null && account.getToken().equals(token);
|
||||
// Create the response message.
|
||||
var response = new JsonObject();
|
||||
response.addProperty("valid", valid);
|
||||
if (valid) response.add("account", JSON.toJsonTree(account));
|
||||
|
||||
// Send the response.
|
||||
this.sendMessage(socket, PacketIds.TokenValidateRsp, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches an account by its ID.
|
||||
*
|
||||
* @param socket The socket the packet was received from.
|
||||
* @param object The packet data.
|
||||
*/
|
||||
private void fetchAccount(WebSocket socket, JsonElement object) {
|
||||
var message = IDispatcher.decode(object);
|
||||
var accountId = message.get("accountId").getAsString();
|
||||
|
||||
// Get the account from the database.
|
||||
var account = DatabaseHelper.getAccountById(accountId);
|
||||
// Send the account.
|
||||
this.sendMessage(socket, PacketIds.GetAccountRsp, JSON.toJsonTree(account));
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcasts an encrypted message to all connected clients.
|
||||
*
|
||||
* @param message The message to broadcast.
|
||||
*/
|
||||
public void sendMessage(int packetId, Object message) {
|
||||
var serverMessage = this.encodeMessage(packetId, message);
|
||||
this.getConnections().forEach(socket -> this.sendMessage(socket, serverMessage));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a serialized encrypted message to the client.
|
||||
*
|
||||
* @param socket The socket to send the message to.
|
||||
* @param message The message to send.
|
||||
*/
|
||||
public void sendMessage(WebSocket socket, Object message) {
|
||||
// Serialize the message into JSON.
|
||||
var serialized = JSON.toJson(message).getBytes(StandardCharsets.UTF_8);
|
||||
// Encrypt the message.
|
||||
Crypto.xor(serialized, DISPATCH_INFO.encryptionKey);
|
||||
// Send the message.
|
||||
socket.send(serialized);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a serialized encrypted message to the client.
|
||||
*
|
||||
* @param socket The socket to send the message to.
|
||||
* @param packetId The packet ID to send.
|
||||
* @param message The message to send.
|
||||
*/
|
||||
public void sendMessage(WebSocket socket, int packetId, Object message) {
|
||||
this.sendMessage(socket, this.encodeMessage(packetId, message));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
this.getLogger().info("Dispatch server started on port {}.", this.getPort());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(WebSocket conn, ClientHandshake handshake) {
|
||||
this.getLogger().debug("Dispatch client connected from {}.", conn.getRemoteSocketAddress());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(WebSocket conn, String message) {
|
||||
this.getLogger()
|
||||
.debug("Received dispatch message from {}:\n{}", conn.getRemoteSocketAddress(), message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(WebSocket conn, ByteBuffer message) {
|
||||
this.handleMessage(conn, message.array());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
|
||||
this.getLogger().debug("Dispatch client disconnected from {}.", conn.getRemoteSocketAddress());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(WebSocket conn, Exception ex) {
|
||||
this.getLogger().warn("Dispatch server error.", ex);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package emu.grasscutter.server.dispatch;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import emu.grasscutter.utils.Crypto;
|
||||
import emu.grasscutter.utils.JsonAdapters.ByteArrayAdapter;
|
||||
import emu.grasscutter.utils.objects.JObject;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.java_websocket.WebSocket;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public interface IDispatcher {
|
||||
Gson JSON =
|
||||
new GsonBuilder()
|
||||
.disableHtmlEscaping()
|
||||
.registerTypeAdapter(byte[].class, new ByteArrayAdapter())
|
||||
.registerTypeAdapter(JObject.class, new JObject.Adapter())
|
||||
.create();
|
||||
|
||||
Function<JsonElement, JsonObject> DEFAULT_PARSER =
|
||||
(packet) -> IDispatcher.decode(packet, JsonObject.class);
|
||||
|
||||
/**
|
||||
* Decodes an escaped JSON message.
|
||||
*
|
||||
* @param element The element to decode.
|
||||
* @return The decoded JSON object.
|
||||
*/
|
||||
static JsonObject decode(JsonElement element) {
|
||||
return IDispatcher.decode(element, JsonObject.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes an escaped JSON message.
|
||||
*
|
||||
* @param element The element to decode.
|
||||
* @return The decoded JSON object.
|
||||
*/
|
||||
static <T> T decode(JsonElement element, Class<T> type) {
|
||||
if (element.isJsonObject()) {
|
||||
return JSON.fromJson(element, type);
|
||||
} else {
|
||||
var data = element.getAsString();
|
||||
|
||||
// Check if the element starts and ends with quotes.
|
||||
if (data.startsWith("\"") && data.endsWith("\"")) {
|
||||
// Remove the quotes.
|
||||
data = data.substring(1, data.length() - 1);
|
||||
}
|
||||
|
||||
// Un-escape the data.
|
||||
data = data.replaceAll("\\\\\"", "\"");
|
||||
data = data.replaceAll("\\\\", "");
|
||||
|
||||
// De-serialize the data.
|
||||
return JSON.fromJson(data, type);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a request from the other server to be fulfilled.
|
||||
*
|
||||
* @param request The request data.
|
||||
* @param requestId The request packet ID.
|
||||
* @param responseId the response packet ID.
|
||||
* @param parser The parser for the response data.
|
||||
* @return The fulfilled data, or null.
|
||||
* @param <T> The type of data to be returned.
|
||||
*/
|
||||
default <T> T await(
|
||||
JsonObject request, int requestId, int responseId, Function<JsonElement, T> parser) {
|
||||
// Perform the setup for the request.
|
||||
var future = this.async(request, requestId, responseId, parser);
|
||||
|
||||
try {
|
||||
// Try to return the value.
|
||||
return future.get(5L, TimeUnit.SECONDS);
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a callback for a packet to be received. Sends a packet with the provided request.
|
||||
*
|
||||
* @param request The request object.
|
||||
* @param requestId The packet ID of the request packet.
|
||||
* @param responseId The packet ID of the response packet.
|
||||
* @return A promise containing the parsed JSON data.
|
||||
*/
|
||||
default CompletableFuture<JsonObject> async(JsonObject request, int requestId, int responseId) {
|
||||
return this.async(request, requestId, responseId, DEFAULT_PARSER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a callback for a packet to be received. Sends a packet with the provided request.
|
||||
*
|
||||
* @param request The request object.
|
||||
* @param requestId The packet ID of the request packet.
|
||||
* @param responseId The packet ID of the response packet.
|
||||
* @param parser The parser for the received data.
|
||||
* @return A promise containing the parsed JSON data.
|
||||
*/
|
||||
default <T> CompletableFuture<T> async(
|
||||
JsonObject request, int requestId, int responseId, Function<JsonElement, T> parser) {
|
||||
// Create the future.
|
||||
var future = new CompletableFuture<T>();
|
||||
// Listen for the response.
|
||||
this.registerCallback(responseId, packet -> future.complete(parser.apply(packet)));
|
||||
// Broadcast the packet.
|
||||
this.sendMessage(requestId, request);
|
||||
|
||||
return future;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internally used method to broadcast a packet.
|
||||
*
|
||||
* @param packetId The packet ID.
|
||||
* @param message The packet data.
|
||||
*/
|
||||
void sendMessage(int packetId, Object message);
|
||||
|
||||
/**
|
||||
* Decodes a message from the client.
|
||||
*
|
||||
* @param message The message to decode.
|
||||
* @return The decoded message.
|
||||
*/
|
||||
default JsonObject decodeMessage(byte[] message) {
|
||||
// Decrypt the message.
|
||||
Crypto.xor(message, DISPATCH_INFO.encryptionKey);
|
||||
// Deserialize the message.
|
||||
return JSON.fromJson(new String(message, StandardCharsets.UTF_8), JsonObject.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an encoded message.
|
||||
*
|
||||
* @param packetId The packet ID.
|
||||
* @param message The message data.
|
||||
* @return The encoded message.
|
||||
*/
|
||||
default JsonObject encodeMessage(int packetId, Object message) {
|
||||
// Create a message from the message data.
|
||||
var serverMessage = new JsonObject();
|
||||
serverMessage.addProperty("packetId", packetId);
|
||||
serverMessage.addProperty("message", JSON.toJson(message));
|
||||
|
||||
return serverMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a message from the client.
|
||||
*
|
||||
* @param socket The socket the message was received from.
|
||||
* @param messageData The message data.
|
||||
*/
|
||||
default void handleMessage(WebSocket socket, byte[] messageData) {
|
||||
// Decode the message.
|
||||
var decoded = this.decodeMessage(messageData);
|
||||
if (decoded == null) {
|
||||
this.getLogger().warn("Received invalid message.");
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the packet ID.
|
||||
var packetId = decoded.get("packetId").getAsInt();
|
||||
// Get the packet data.
|
||||
var packetData = decoded.get("message");
|
||||
|
||||
// Check to see if the client has authenticated.
|
||||
if (packetId != PacketIds.LoginNotify) {
|
||||
if (socket.getAttachment() instanceof Boolean authenticated) {
|
||||
if (!authenticated) {
|
||||
this.getLogger().warn("Received packet ID {} from unauthenticated client.", packetId);
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
} else return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if the packet ID is registered.
|
||||
if (this.getHandlers().containsKey(packetId)) {
|
||||
// Get the handler.
|
||||
var handler = this.getHandlers().get(packetId);
|
||||
// Handle the packet.
|
||||
handler.accept(socket, packetData);
|
||||
}
|
||||
|
||||
// Check if the packet ID has callbacks.
|
||||
if (this.getCallbacks().containsKey(packetId)) {
|
||||
// Get the callbacks.
|
||||
var callbacks = this.getCallbacks().get(packetId);
|
||||
// Call the callbacks.
|
||||
callbacks.forEach(callback -> callback.accept(packetData));
|
||||
callbacks.clear();
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
this.getLogger().warn("Exception occurred while handling packet {}.", packetId);
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a message handler.
|
||||
*
|
||||
* @param packetId The packet ID to register.
|
||||
* @param handler The handler to register.
|
||||
*/
|
||||
default void registerHandler(int packetId, BiConsumer<WebSocket, JsonElement> handler) {
|
||||
// Check if the packet ID is already registered.
|
||||
if (this.getHandlers().containsKey(packetId))
|
||||
throw new IllegalArgumentException("Packet ID already registered.");
|
||||
|
||||
// Register the handler.
|
||||
this.getHandlers().put(packetId, handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a callback.
|
||||
*
|
||||
* @param packetId The packet ID to register.
|
||||
* @param callback The callback to register.
|
||||
*/
|
||||
default void registerCallback(int packetId, Consumer<JsonElement> callback) {
|
||||
// Check if the packet ID has a list for callbacks.
|
||||
if (!this.getCallbacks().containsKey(packetId))
|
||||
this.getCallbacks().put(packetId, new LinkedList<>());
|
||||
|
||||
// Register the callback.
|
||||
this.getCallbacks().get(packetId).add(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a server message to the client.
|
||||
*
|
||||
* @param data The data to send.
|
||||
* @param binary Whether the data is binary.
|
||||
*/
|
||||
default void sendServerMessage(byte[] data, boolean binary) {
|
||||
var message =
|
||||
new JObject()
|
||||
.add("binary", binary)
|
||||
.add("data", Base64.getEncoder().encodeToString(data))
|
||||
.gson();
|
||||
|
||||
this.sendMessage(PacketIds.ServerMessageNotify, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a server message to the client. The data is sent as a string.
|
||||
*
|
||||
* @param data The data to send.
|
||||
*/
|
||||
default void sendServerMessage(String data) {
|
||||
this.sendServerMessage(data.getBytes(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a server message to the client. The data is sent as a byte array.
|
||||
*
|
||||
* @param data The data to send.
|
||||
*/
|
||||
default void sendServerMessage(byte[] data) {
|
||||
this.sendServerMessage(data, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a server message to the client. The data is sent as a JSON object.
|
||||
*
|
||||
* @param data The data to send.
|
||||
*/
|
||||
default void sendServerMessage(Object data) {
|
||||
this.sendServerMessage(JSON.toJson(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The logger for the dispatcher.
|
||||
*/
|
||||
Logger getLogger();
|
||||
|
||||
/**
|
||||
* @return The message handlers.
|
||||
*/
|
||||
Map<Integer, BiConsumer<WebSocket, JsonElement>> getHandlers();
|
||||
|
||||
/**
|
||||
* @return The callbacks.
|
||||
*/
|
||||
Map<Integer, List<Consumer<JsonElement>>> getCallbacks();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package emu.grasscutter.server.dispatch;
|
||||
|
||||
import emu.grasscutter.net.packet.PacketOpcodes;
|
||||
|
||||
/* Packet IDs for the dispatch server. */
|
||||
public interface PacketIds {
|
||||
int LoginNotify = 1;
|
||||
int TokenValidateReq = 2;
|
||||
int TokenValidateRsp = 3;
|
||||
int GachaHistoryReq = 4;
|
||||
int GachaHistoryRsp = 5;
|
||||
int GmTalkReq = PacketOpcodes.GmTalkReq;
|
||||
int GmTalkRsp = PacketOpcodes.GmTalkRsp;
|
||||
int GetAccountReq = 6;
|
||||
int GetAccountRsp = 7;
|
||||
int GetPlayerFieldsReq = 8;
|
||||
int GetPlayerFieldsRsp = 9;
|
||||
int GetPlayerByAccountReq = 10;
|
||||
int GetPlayerByAccountRsp = 11;
|
||||
int ServerMessageNotify = 12;
|
||||
}
|
||||
Reference in New Issue
Block a user