Add support for Redis messaging, close #50

This commit is contained in:
William committed 2021-10-02 21:49:28 +01:00
1 parent 48906c018b
commit 4cdb39ba65
16 files changed
+526 -291

No files matched your search

+16 -12
View File
@@ -10,20 +10,13 @@
<packaging>jar</packaging>
<name>HuskHomes</name>
<description>A powerful, intuitive and flexible teleportation suite</description>
<url>https://timetobattle.net</url>
<properties>
<java.version>16</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<url>https://timetobattle.net</url>
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>https://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
@@ -44,15 +37,19 @@
<relocations>
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>me.william278.huskhomes2.bstats</shadedPattern>
<shadedPattern>me.william278.huskhomes2.libraries.bstats</shadedPattern>
</relocation>
<relocation>
<pattern>de.themoep.minedown</pattern>
<shadedPattern>me.william278.huskhomes2.minedown</shadedPattern>
<shadedPattern>me.william278.huskhomes2.libraries.minedown</shadedPattern>
</relocation>
<relocation>
<pattern>io.papermc.lib</pattern>
<shadedPattern>me.william278.huskhomes2.paperlib</shadedPattern>
<shadedPattern>me.william278.huskhomes2.libraries.paperlib</shadedPattern>
</relocation>
<relocation>
<pattern>redis.clients.jedis</pattern>
<shadedPattern>me.william278.huskhomes2.libraries.jedis</shadedPattern>
</relocation>
</relocations>
</configuration>
@@ -179,5 +176,12 @@
<version>1.0.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
@@ -12,7 +12,7 @@ import me.william278.huskhomes2.integrations.map.Map;
import me.william278.huskhomes2.integrations.VaultIntegration;
import me.william278.huskhomes2.integrations.map.Pl3xMap;
import me.william278.huskhomes2.listeners.PlayerListener;
import me.william278.huskhomes2.listeners.PluginMessageListener;
import me.william278.huskhomes2.data.message.pluginmessage.PluginMessageReceiver;
import me.william278.huskhomes2.migrators.UpgradeDatabase;
import me.william278.huskhomes2.teleport.SettingHandler;
import me.william278.huskhomes2.util.PlayerList;
@@ -122,7 +122,7 @@ public final class HuskHomes extends JavaPlugin {
private void setupBungeeChannels() {
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new PluginMessageListener());
Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new PluginMessageReceiver());
}
private void registerCommands() {
@@ -19,10 +19,11 @@ public class Settings {
// Bungee settings
private boolean doBungee;
private int clusterID;
private int clusterId;
private String server;
private boolean doCrossServerTabCompletion;
private int crossServerTabUpdateDelay;
private String messengerType;
// Data storage settings
private String storageType;
@@ -39,6 +40,11 @@ public class Settings {
private String mySQLPassword;
private String mySQLParams;
// Redis connection settings
private int redisPort;
private String redisHost;
private String redisPassword;
// Dynmap integration settings
private boolean doMapIntegration;
private String mapPlugin;
@@ -115,9 +121,10 @@ public class Settings {
this.doBungee = config.getBoolean("bungee_options.enable_bungee_mode", false);
this.server = config.getString("bungee_options.server_id", "server");
this.clusterID = config.getInt("bungee_options.cluster_id", 0);
this.clusterId = config.getInt("bungee_options.cluster_id", 0);
this.doCrossServerTabCompletion = config.getBoolean("bungee_options.tab_complete_cross_server.enabled", true);
this.crossServerTabUpdateDelay = config.getInt("bungee_options.tab_complete_cross_server.delay", 60);
this.messengerType = config.getString("bungee_options.messenger_type", "pluginmessage");
this.storageType = config.getString("data_storage_options.storage_type", "SQLite");
this.playerDataTable = config.getString("data_storage_options.table_names.player_data", "huskhomes_player_data");
@@ -140,6 +147,10 @@ public class Settings {
this.mySQLPort = config.getInt("data_storage_options.mysql_credentials.port", 3306);
this.mySQLParams = config.getString("data_storage_options.mysql_credentials.params", "?autoReconnect=true&useSSL=false");
this.redisHost = config.getString("bungee_options.redis_credentials.host", "localhost");
this.redisPort = config.getInt("bungee_options.redis_credentials.port", 6379);
this.redisPassword = config.getString("bungee_options.redis_credentials.password", "");
this.doMapIntegration = config.getBoolean("map_integration.enabled", false);
this.mapPlugin = config.getString("map_integration.plugin", "dynmap");
@@ -280,8 +291,8 @@ public class Settings {
return server;
}
public int getClusterID() {
return clusterID;
public int getClusterId() {
return clusterId;
}
public boolean doBungee() {
@@ -451,4 +462,20 @@ public class Settings {
public boolean doUnicodeInDescriptions() {
return allowUnicodeInDescriptions;
}
public String getMessengerType() {
return messengerType;
}
public int getRedisPort() {
return redisPort;
}
public String getRedisHost() {
return redisHost;
}
public String getRedisPassword() {
return redisPassword;
}
}
@@ -1,12 +1,10 @@
package me.william278.huskhomes2.listeners;
package me.william278.huskhomes2.data.message;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import me.william278.huskhomes2.HuskHomes;
import me.william278.huskhomes2.MessageManager;
import me.william278.huskhomes2.data.DataManager;
import me.william278.huskhomes2.data.pluginmessage.PluginMessage;
import me.william278.huskhomes2.data.pluginmessage.PluginMessageType;
import me.william278.huskhomes2.data.message.pluginmessage.PluginMessage;
import me.william278.huskhomes2.data.message.redis.RedisMessage;
import me.william278.huskhomes2.integrations.VanishChecker;
import me.william278.huskhomes2.teleport.TeleportManager;
import me.william278.huskhomes2.teleport.TeleportRequest;
@@ -14,41 +12,38 @@ import me.william278.huskhomes2.teleport.TeleportRequestHandler;
import me.william278.huskhomes2.teleport.points.TeleportationPoint;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.StringJoiner;
import java.util.logging.Level;
public class PluginMessageListener implements org.bukkit.plugin.messaging.PluginMessageListener {
public class CrossServerMessageHandler {
private static final HuskHomes plugin = HuskHomes.getInstance();
private void handlePluginMessage(PluginMessage pluginMessage, Player recipient) {
public static void handlePluginMessage(Message receivedMessage, Player recipient) {
Connection connection = HuskHomes.getConnection();
switch (pluginMessage.getMessageType()) {
switch (receivedMessage.getMessageType()) {
case SET_TP_DESTINATION -> Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
DataManager.setPlayerDestinationLocation(pluginMessage.getMessageData(),
DataManager.setPlayerDestinationLocation(receivedMessage.getMessageData(),
new TeleportationPoint(recipient.getLocation(), HuskHomes.getSettings().getServerID()), connection);
new PluginMessage(pluginMessage.getMessageData(), PluginMessageType.CONFIRM_DESTINATION_SET, "confirmed").send(recipient);
new PluginMessage(receivedMessage.getMessageData(), Message.MessageType.CONFIRM_DESTINATION_SET, "confirmed").send(recipient);
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred responding to a plugin message teleport destination update");
}
});
case CONFIRM_DESTINATION_SET -> {
if (pluginMessage.getMessageData().equals("confirmed")) {
if (receivedMessage.getMessageData().equals("confirmed")) {
TeleportManager.teleportPlayer(recipient);
}
}
case TPA_REQUEST -> {
if (!VanishChecker.isVanished(recipient)) {
if (!HuskHomes.isIgnoringTeleportRequests(recipient.getUniqueId())) {
TeleportRequestHandler.teleportRequests.put(recipient, new TeleportRequest(pluginMessage.getMessageData(), TeleportRequest.RequestType.TPA));
MessageManager.sendMessage(recipient, "tpa_request_ask", pluginMessage.getMessageData());
TeleportRequestHandler.teleportRequests.put(recipient, new TeleportRequest(receivedMessage.getMessageData(), TeleportRequest.RequestType.TPA));
MessageManager.sendMessage(recipient, "tpa_request_ask", receivedMessage.getMessageData());
MessageManager.sendMessage(recipient, "teleport_request_options");
}
}
@@ -56,15 +51,15 @@ public class PluginMessageListener implements org.bukkit.plugin.messaging.Plugin
case TPA_HERE_REQUEST -> {
if (!VanishChecker.isVanished(recipient)) {
if (!HuskHomes.isIgnoringTeleportRequests(recipient.getUniqueId())) {
TeleportRequestHandler.teleportRequests.put(recipient, new TeleportRequest(pluginMessage.getMessageData(), TeleportRequest.RequestType.TPA_HERE));
MessageManager.sendMessage(recipient, "tpahere_request_ask", pluginMessage.getMessageData());
TeleportRequestHandler.teleportRequests.put(recipient, new TeleportRequest(receivedMessage.getMessageData(), TeleportRequest.RequestType.TPA_HERE));
MessageManager.sendMessage(recipient, "tpahere_request_ask", receivedMessage.getMessageData());
MessageManager.sendMessage(recipient, "teleport_request_options");
}
}
}
case TPA_REQUEST_REPLY -> {
final String tpaReplierName = pluginMessage.getMessageDataItems()[0];
final boolean tpaAccepted = Boolean.parseBoolean(pluginMessage.getMessageDataItems()[1]);
final String tpaReplierName = receivedMessage.getMessageDataItems()[0];
final boolean tpaAccepted = Boolean.parseBoolean(receivedMessage.getMessageDataItems()[1]);
if (tpaAccepted) {
MessageManager.sendMessage(recipient, "tpa_has_accepted", tpaReplierName);
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
@@ -79,8 +74,8 @@ public class PluginMessageListener implements org.bukkit.plugin.messaging.Plugin
}
}
case TPA_HERE_REQUEST_REPLY -> {
final String tpaHereReplierName = pluginMessage.getMessageDataItems()[0];
final boolean tpaHereAccepted = Boolean.parseBoolean(pluginMessage.getMessageDataItems()[1]);
final String tpaHereReplierName = receivedMessage.getMessageDataItems()[0];
final boolean tpaHereAccepted = Boolean.parseBoolean(receivedMessage.getMessageDataItems()[1]);
if (tpaHereAccepted) {
MessageManager.sendMessage(recipient, "tpa_has_accepted", tpaHereReplierName);
} else {
@@ -89,79 +84,43 @@ public class PluginMessageListener implements org.bukkit.plugin.messaging.Plugin
}
case TELEPORT_TO_ME -> Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
TeleportManager.teleportPlayer(recipient, pluginMessage.getMessageData(), connection);
TeleportManager.teleportPlayer(recipient, receivedMessage.getMessageData(), connection);
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred responding to a plugin message teleport-to-me request");
}
});
case GET_PLAYER_LIST -> {
final String requestingServer = pluginMessage.getMessageData();
StringBuilder playerList = new StringBuilder();
final String requestingServer = receivedMessage.getMessageData();
StringJoiner playerList = new StringJoiner("£");
for (Player p : Bukkit.getOnlinePlayers()) {
playerList.append(p.getName());
playerList.append("£");
playerList.add(p.getName());
}
if (playerList.toString().equals("")) {
return;
}
new PluginMessage(PluginMessageType.RETURN_PLAYER_LIST, playerList.substring(0, playerList.length() - 1)).sendToServer(recipient, requestingServer);
CrossServerMessageHandler.getMessage(Message.MessageType.RETURN_PLAYER_LIST, playerList.toString()).sendToServer(recipient, requestingServer);
}
case RETURN_PLAYER_LIST -> {
final String[] returningPlayers = pluginMessage.getMessageData().split("£");
final String[] returningPlayers = receivedMessage.getMessageData().split("£");
HuskHomes.getPlayerList().addPlayers(returningPlayers);
}
default -> HuskHomes.getInstance().getLogger().log(Level.WARNING, "Received a HuskHomes plugin message with an unrecognised type. Is your version of HuskHomes up to date?");
}
}
@Override @SuppressWarnings("UnstableApiUsage")
public void onPluginMessageReceived(String channel, @NotNull Player player, byte[] message) {
// Return if the message is not a Bungee message
if (!channel.equals("BungeeCord")) {
return;
}
ByteArrayDataInput input = ByteStreams.newDataInput(message);
// Plugin messages are formatted as such:
// HuskHomes:<cluster_id>:<message_type>, followed by the message arguments and data.
String messageType = input.readUTF();
int clusterID;
// Return if the message was not sent by HuskHomes
if (!messageType.contains("HuskHomes:")) {
return;
}
// Ensure the cluster ID matches
try {
clusterID = Integer.parseInt(messageType.split(":")[1]);
} catch (Exception e) {
// In case the message is malformed or the cluster ID is invalid
HuskHomes.getInstance().getLogger().warning("Received a HuskHomes plugin message with an invalid server Cluster ID! \n" +
"Please ensure that the cluster ID is set to a valid integer on all servers.");
return;
}
if (HuskHomes.getSettings().getClusterID() != clusterID) {
return;
}
// Get the message data packets
String messageData = "";
short messageLength = input.readShort();
byte[] messageBytes = new byte[messageLength];
input.readFully(messageBytes);
DataInputStream messageIn = new DataInputStream(new ByteArrayInputStream(messageBytes));
// Get the message data string from the packets received
try {
messageData = messageIn.readUTF();
} catch (IOException e) {
Bukkit.getLogger().warning("An error occurred trying to read a plugin message (" + e.getCause() + ")");
e.printStackTrace();
}
// Handle the plugin message appropriately
handlePluginMessage(new PluginMessage(clusterID, player.getName(), messageType.split(":")[2], messageData), player);
public static Message getMessage(String targetPlayerName, Message.MessageType pluginMessageType, String... messageData) {
return switch (HuskHomes.getSettings().getMessengerType().toLowerCase()) {
case "pluginmessage" -> new PluginMessage(targetPlayerName, pluginMessageType, messageData);
case "redis" -> new RedisMessage(targetPlayerName, pluginMessageType, messageData);
default -> null;
};
}
public static Message getMessage(Message.MessageType pluginMessageType, String... messageData) {
return switch (HuskHomes.getSettings().getMessengerType().toLowerCase()) {
case "pluginmessage" -> new PluginMessage(pluginMessageType, messageData);
case "redis" -> new RedisMessage(pluginMessageType, messageData);
default -> null;
};
}
}
@@ -0,0 +1,93 @@
package me.william278.huskhomes2.data.message;
import me.william278.huskhomes2.HuskHomes;
import org.bukkit.entity.Player;
import java.util.Locale;
import java.util.StringJoiner;
public abstract class Message {
private static final String MESSAGE_DATA_SEPARATOR = "$";
private final int clusterId;
private final Message.MessageType messageType;
private final String targetPlayerName;
private final String messageData;
public Message(String targetPlayerName, MessageType pluginMessageType, String... messageData) {
this.clusterId = HuskHomes.getSettings().getClusterId();
this.messageType = pluginMessageType;
StringJoiner newMessageData = new StringJoiner(MESSAGE_DATA_SEPARATOR);
for (String dataItem : messageData) {
newMessageData.add(dataItem);
}
this.messageData = newMessageData.toString();
this.targetPlayerName = targetPlayerName;
}
public Message(MessageType pluginMessageType, String... messageData) {
this.clusterId = HuskHomes.getSettings().getClusterId();
this.messageType = pluginMessageType;
StringJoiner newMessageData = new StringJoiner(MESSAGE_DATA_SEPARATOR);
for (String dataItem : messageData) {
newMessageData.add(dataItem);
}
this.messageData = newMessageData.toString();
this.targetPlayerName = null;
}
public Message(int clusterId, String targetPlayerName, String pluginMessageType, String... messageData) {
this.clusterId = clusterId;
this.messageType = MessageType.valueOf(pluginMessageType.toUpperCase(Locale.ENGLISH));
StringJoiner newMessageData = new StringJoiner(MESSAGE_DATA_SEPARATOR);
for (String dataItem : messageData) {
newMessageData.add(dataItem);
}
this.messageData = newMessageData.toString();
this.targetPlayerName = targetPlayerName;
}
// Get the string version of the plugin message type
protected String getPluginMessageString(Message.MessageType type) {
return type.name().toLowerCase(Locale.ENGLISH);
}
public int getClusterId() {
return clusterId;
}
public Message.MessageType getMessageType() {
return messageType;
}
public String getTargetPlayerName() {
return targetPlayerName;
}
public String getMessageData() {
return messageData;
}
public String[] getMessageDataItems() {
return messageData.split("\\" + MESSAGE_DATA_SEPARATOR);
}
public abstract void send(Player sender);
public abstract void sendToAllServers(Player sender);
public abstract void sendToServer(Player sender, String server);
public enum MessageType {
SET_TP_DESTINATION,
CONFIRM_DESTINATION_SET,
TPA_REQUEST,
TPA_HERE_REQUEST,
TPA_REQUEST_REPLY,
TPA_HERE_REQUEST_REPLY,
TELEPORT_TO_ME,
GET_PLAYER_LIST,
RETURN_PLAYER_LIST
}
}
@@ -0,0 +1,95 @@
package me.william278.huskhomes2.data.message.pluginmessage;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import me.william278.huskhomes2.HuskHomes;
import me.william278.huskhomes2.data.message.Message;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class PluginMessage extends Message {
private static final HuskHomes plugin = HuskHomes.getInstance();
public PluginMessage(String targetPlayerName, MessageType pluginMessageType, String... messageData) {
super(targetPlayerName, pluginMessageType, messageData);
}
public PluginMessage(MessageType pluginMessageType, String... messageData) {
super(pluginMessageType, messageData);
}
public PluginMessage(int clusterID, String targetPlayerName, String pluginMessageType, String... messageData) {
super(clusterID, targetPlayerName, pluginMessageType, messageData);
}
@SuppressWarnings("UnstableApiUsage")
public void send(Player sender) {
Bukkit.getScheduler().runTask(plugin, () -> {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
// Send a plugin message to the specified player name
out.writeUTF("ForwardToPlayer");
out.writeUTF(getTargetPlayerName());
// Send the HuskHomes message with a specific type
out.writeUTF("HuskHomes:" + getClusterId() + ":" + getPluginMessageString(getMessageType()));
ByteArrayOutputStream messageBytes = new ByteArrayOutputStream();
DataOutputStream messageOut = new DataOutputStream(messageBytes);
// Send the message data; output an exception if there's an error
try {
messageOut.writeUTF(getMessageData());
} catch (IOException e) {
plugin.getLogger().warning("An error occurred trying to send a plugin message (" + e.getCause() + ")");
e.printStackTrace();
}
// Write the messages to the output packet
out.writeShort(messageBytes.toByteArray().length);
out.write(messageBytes.toByteArray());
// Send the constructed plugin message packet
sender.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
});
}
public void sendToAllServers(Player sender) {
sendToServer(sender, "ALL");
}
@SuppressWarnings("UnstableApiUsage")
public void sendToServer(Player sender, String server) {
Bukkit.getScheduler().runTask(plugin, () -> {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
// Send a plugin message to the specified player name
out.writeUTF("Forward");
out.writeUTF(server);
// Send the HuskHomes message with a specific type
out.writeUTF("HuskHomes:" + getClusterId() + ":" + getPluginMessageString(getMessageType()));
ByteArrayOutputStream messageBytes = new ByteArrayOutputStream();
DataOutputStream messageOut = new DataOutputStream(messageBytes);
// Send the message data; output an exception if there's an error
try {
messageOut.writeUTF(getMessageData());
} catch (IOException e) {
plugin.getLogger().warning("An error occurred trying to send a plugin message to a server (" + e.getCause() + ")");
e.printStackTrace();
}
// Write the messages to the output packet
out.writeShort(messageBytes.toByteArray().length);
out.write(messageBytes.toByteArray());
// Send the constructed plugin message packet
sender.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
});
}
}
@@ -0,0 +1,68 @@
package me.william278.huskhomes2.data.message.pluginmessage;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import me.william278.huskhomes2.HuskHomes;
import me.william278.huskhomes2.data.message.CrossServerMessageHandler;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class PluginMessageReceiver implements PluginMessageListener {
@Override @SuppressWarnings("UnstableApiUsage")
public void onPluginMessageReceived(String channel, @NotNull Player player, byte[] message) {
// Return if the message is not a Bungee message
if (!channel.equals("BungeeCord")) {
return;
}
ByteArrayDataInput input = ByteStreams.newDataInput(message);
// Plugin messages are formatted as such:
// HuskHomes:<cluster_id>:<message_type>, followed by the message arguments and data.
String messageType = input.readUTF();
int clusterID;
// Return if the message was not sent by HuskHomes
if (!messageType.contains("HuskHomes:")) {
return;
}
// Ensure the cluster ID matches
try {
clusterID = Integer.parseInt(messageType.split(":")[1]);
} catch (Exception e) {
// In case the message is malformed or the cluster ID is invalid
HuskHomes.getInstance().getLogger().warning("Received a HuskHomes plugin message with an invalid server Cluster ID! \n" +
"Please ensure that the cluster ID is set to a valid integer on all servers.");
return;
}
if (HuskHomes.getSettings().getClusterId() != clusterID) {
return;
}
// Get the message data packets
String messageData = "";
short messageLength = input.readShort();
byte[] messageBytes = new byte[messageLength];
input.readFully(messageBytes);
DataInputStream messageIn = new DataInputStream(new ByteArrayInputStream(messageBytes));
// Get the message data string from the packets received
try {
messageData = messageIn.readUTF();
} catch (IOException e) {
Bukkit.getLogger().warning("An error occurred trying to read a plugin message (" + e.getCause() + ")");
e.printStackTrace();
}
// Handle the plugin message appropriately
CrossServerMessageHandler.handlePluginMessage(new PluginMessage(clusterID, player.getName(), messageType.split(":")[2], messageData), player);
}
}
@@ -0,0 +1,52 @@
package me.william278.huskhomes2.data.message.redis;
import me.william278.huskhomes2.HuskHomes;
import me.william278.huskhomes2.data.message.Message;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import redis.clients.jedis.Jedis;
public class RedisMessage extends Message {
private static final HuskHomes plugin = HuskHomes.getInstance();
public RedisMessage(String targetPlayerName, MessageType pluginMessageType, String... messageData) {
super(targetPlayerName, pluginMessageType, messageData);
}
public RedisMessage(MessageType pluginMessageType, String... messageData) {
super(pluginMessageType, messageData);
}
public RedisMessage(int clusterId, String targetPlayerName, String pluginMessageType, String... messageData) {
super(clusterId, targetPlayerName, pluginMessageType, messageData);
}
private void dispatchRedisMessage(String target) {
Bukkit.getScheduler().runTask(plugin, () -> {
try (Jedis publisher = new Jedis(HuskHomes.getSettings().getRedisHost(), HuskHomes.getSettings().getRedisPort())) {
final String jedisPassword = HuskHomes.getSettings().getRedisPassword();
if (!jedisPassword.equals("")) {
publisher.auth(jedisPassword);
}
publisher.connect();
publisher.publish(RedisReceiver.REDIS_CHANNEL, "HuskHomes:" + getClusterId() + ":" + getPluginMessageString(getMessageType()) + ":" + target);
}
});
}
@Override
public void send(Player sender) {
dispatchRedisMessage(getTargetPlayerName());
}
@Override
public void sendToAllServers(Player sender) {
dispatchRedisMessage("-all-");
}
@Override
public void sendToServer(Player sender, String server) {
dispatchRedisMessage("server-" + server + "");
}
}
@@ -0,0 +1,93 @@
package me.william278.huskhomes2.data.message.redis;
import me.william278.huskhomes2.HuskHomes;
import me.william278.huskhomes2.data.message.CrossServerMessageHandler;
import me.william278.huskhomes2.data.message.pluginmessage.PluginMessage;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import java.util.ArrayList;
import java.util.Collections;
public class RedisReceiver {
public static final String REDIS_CHANNEL = "HuskHomes";
public static Player getRandomReceiver() {
ArrayList<Player> players = new ArrayList<>(Bukkit.getOnlinePlayers());
if (players.isEmpty()) {
return null;
}
Collections.shuffle(players);
return players.get(0);
}
public static void listen() {
Jedis jedis = new Jedis(HuskHomes.getSettings().getRedisHost(), HuskHomes.getSettings().getRedisPort());
final String jedisPassword = HuskHomes.getSettings().getRedisPassword();
if (!jedisPassword.equals("")) {
jedis.auth(jedisPassword);
}
jedis.connect();
new Thread(() -> jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
if (!channel.equals(REDIS_CHANNEL)) {
return;
}
// Redis messages are formatted as such:
// HuskHomes:<cluster_id>:<message_type>:<target_player>£ followed by the message arguments and data.
final String[] splitMessage = message.split("£");
final String messageType = splitMessage[0];
int clusterID;
// Return if the message was not sent by HuskHomes
if (!messageType.contains("HuskHomes:")) {
return;
}
// Ensure the cluster ID matches
try {
clusterID = Integer.parseInt(messageType.split(":")[1]);
} catch (Exception e) {
// In case the message is malformed or the cluster ID is invalid
HuskHomes.getInstance().getLogger().warning("Received a HuskHomes redis message with an invalid server Cluster ID! \n" +
"Please ensure that the cluster ID is set to a valid integer on all servers.");
return;
}
if (HuskHomes.getSettings().getClusterId() != clusterID) {
return;
}
// Get the player targeted by the message and make sure they are online
final String target = messageType.split(":")[3];
Player receiver = Bukkit.getPlayerExact(target);
// If the redis message was targeting this server
if (target.equalsIgnoreCase("-all-")) {
receiver = getRandomReceiver();
} else if (target.contains("server-")) { //todo In the future, allow redis messages to execute without a player online. For now it's duplicating the behaviour of plugin messages for consistency.
if (target.split("-")[1].equalsIgnoreCase(HuskHomes.getSettings().getServerID())) {
receiver = getRandomReceiver();
} else {
return; // The message was targeting another server
}
}
// Return if the target is not available
if (receiver == null) {
return;
}
if (!receiver.isOnline()) {
return;
}
final String messageData = splitMessage[1];
CrossServerMessageHandler.handlePluginMessage(new PluginMessage(clusterID, receiver.getName(), messageType.split(":")[2], messageData), receiver);
}
}, REDIS_CHANNEL), "Redis Subscriber").start();
}
}
@@ -1,168 +0,0 @@
package me.william278.huskhomes2.data.pluginmessage;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import me.william278.huskhomes2.HuskHomes;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Locale;
public class PluginMessage {
private static final HuskHomes plugin = HuskHomes.getInstance();
// Move a player to a different server in the bungee network
@SuppressWarnings("UnstableApiUsage")
public static void sendPlayer(Player p, String targetServer) {
Bukkit.getScheduler().runTask(plugin, () -> {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(targetServer);
p.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
});
}
private static final String MESSAGE_DATA_SEPARATOR = "$";
private final int clusterID;
private final PluginMessageType messageType;
private final String targetPlayerName;
private final String messageData;
/**
* Creates a Plugin Message ready to be sent
* @param targetPlayerName Name of the player the message will be sent to over Bungee
* @param pluginMessageType Type of the plugin message
* @param messageData Associated message data
*/
public PluginMessage(String targetPlayerName, PluginMessageType pluginMessageType, String... messageData) {
this.clusterID = HuskHomes.getSettings().getClusterID();
this.messageType = pluginMessageType;
StringBuilder newMessageData = new StringBuilder();
for (String s : messageData) {
newMessageData.append(s).append(MESSAGE_DATA_SEPARATOR);
}
this.messageData = newMessageData.substring(0, newMessageData.toString().length()-1);
this.targetPlayerName = targetPlayerName;
}
public PluginMessage(PluginMessageType pluginMessageType, String... messageData) {
this.clusterID = HuskHomes.getSettings().getClusterID();
this.messageType = pluginMessageType;
StringBuilder newMessageData = new StringBuilder();
for (String s : messageData) {
newMessageData.append(s).append(MESSAGE_DATA_SEPARATOR);
}
this.messageData = newMessageData.substring(0, newMessageData.toString().length()-1);
this.targetPlayerName = null;
}
public PluginMessage(int clusterID, String targetPlayerName, String pluginMessageType, String... messageData) {
this.clusterID = clusterID;
this.messageType = PluginMessageType.valueOf(pluginMessageType.toUpperCase(Locale.ENGLISH));
StringBuilder newMessageData = new StringBuilder();
for (String s : messageData) {
newMessageData.append(s).append(MESSAGE_DATA_SEPARATOR);
}
this.messageData = newMessageData.substring(0, newMessageData.toString().length()-1);
this.targetPlayerName = targetPlayerName;
}
// Get the string version of the plugin message type
private String getPluginMessageString(PluginMessageType type) {
return type.name().toLowerCase(Locale.ENGLISH);
}
/**
* Send the plugin message
* @param sender The player to send the message
*/
@SuppressWarnings("UnstableApiUsage")
public void send(Player sender) {
Bukkit.getScheduler().runTask(plugin, () -> {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
// Send a plugin message to the specified player name
out.writeUTF("ForwardToPlayer");
out.writeUTF(targetPlayerName);
// Send the HuskHomes message with a specific type
out.writeUTF("HuskHomes:" + clusterID + ":" + getPluginMessageString(messageType));
ByteArrayOutputStream messageBytes = new ByteArrayOutputStream();
DataOutputStream messageOut = new DataOutputStream(messageBytes);
// Send the message data; output an exception if there's an error
try {
messageOut.writeUTF(messageData);
} catch (IOException e) {
plugin.getLogger().warning("An error occurred trying to send a plugin message (" + e.getCause() + ")");
e.printStackTrace();
}
// Write the messages to the output packet
out.writeShort(messageBytes.toByteArray().length);
out.write(messageBytes.toByteArray());
// Send the constructed plugin message packet
sender.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
});
}
public void sendToServer(Player sender) {
sendToServer(sender, "ALL");
}
@SuppressWarnings("UnstableApiUsage")
public void sendToServer(Player sender, String server) {
Bukkit.getScheduler().runTask(plugin, () -> {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
// Send a plugin message to the specified player name
out.writeUTF("Forward");
out.writeUTF(server);
// Send the HuskHomes message with a specific type
out.writeUTF("HuskHomes:" + clusterID + ":" + getPluginMessageString(messageType));
ByteArrayOutputStream messageBytes = new ByteArrayOutputStream();
DataOutputStream messageOut = new DataOutputStream(messageBytes);
// Send the message data; output an exception if there's an error
try {
messageOut.writeUTF(messageData);
} catch (IOException e) {
plugin.getLogger().warning("An error occurred trying to send a plugin message to a server (" + e.getCause() + ")");
e.printStackTrace();
}
// Write the messages to the output packet
out.writeShort(messageBytes.toByteArray().length);
out.write(messageBytes.toByteArray());
// Send the constructed plugin message packet
sender.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
});
}
public int getClusterID() {
return clusterID;
}
public PluginMessageType getMessageType() {
return messageType;
}
public String getTargetPlayerName() {
return targetPlayerName;
}
public String getMessageData() {
return messageData;
}
public String[] getMessageDataItems() {
return messageData.split("\\" + MESSAGE_DATA_SEPARATOR);
}
}
@@ -1,13 +0,0 @@
package me.william278.huskhomes2.data.pluginmessage;
public enum PluginMessageType {
SET_TP_DESTINATION,
CONFIRM_DESTINATION_SET,
TPA_REQUEST,
TPA_HERE_REQUEST,
TPA_REQUEST_REPLY,
TPA_HERE_REQUEST_REPLY,
TELEPORT_TO_ME,
GET_PLAYER_LIST,
RETURN_PLAYER_LIST
}
@@ -1,11 +1,13 @@
package me.william278.huskhomes2.teleport;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import io.papermc.lib.PaperLib;
import me.william278.huskhomes2.HuskHomes;
import me.william278.huskhomes2.MessageManager;
import me.william278.huskhomes2.data.DataManager;
import me.william278.huskhomes2.data.pluginmessage.PluginMessage;
import me.william278.huskhomes2.data.pluginmessage.PluginMessageType;
import me.william278.huskhomes2.data.message.CrossServerMessageHandler;
import me.william278.huskhomes2.data.message.Message;
import me.william278.huskhomes2.integrations.VaultIntegration;
import me.william278.huskhomes2.teleport.points.RandomPoint;
import me.william278.huskhomes2.teleport.points.TeleportationPoint;
@@ -37,6 +39,17 @@ public class TeleportManager {
teleportPlayer(player);
}
// Move a player to a different server in the bungee network
@SuppressWarnings("UnstableApiUsage")
private static void movePlayerServer(Player p, String targetServer) {
Bukkit.getScheduler().runTask(plugin, () -> {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(targetServer);
p.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
});
}
public static void teleportPlayer(Player p) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
@@ -56,7 +69,7 @@ public class TeleportManager {
} else if (HuskHomes.getSettings().doBungee()) {
DataManager.setPlayerDestinationLocation(p, teleportationPoint, connection);
DataManager.setPlayerTeleporting(p, true, connection);
PluginMessage.sendPlayer(p, server);
movePlayerServer(p, server);
}
}
} catch (SQLException sqlException) {
@@ -192,11 +205,11 @@ public class TeleportManager {
}
private static void teleportHereCrossServer(Player requester, String targetPlayerName) {
new PluginMessage(targetPlayerName, PluginMessageType.TELEPORT_TO_ME, requester.getName()).send(requester);
CrossServerMessageHandler.getMessage(targetPlayerName, Message.MessageType.TELEPORT_TO_ME, requester.getName()).send(requester);
}
private static void setTeleportationDestinationCrossServer(Player requester, String targetPlayerName) {
new PluginMessage(targetPlayerName, PluginMessageType.SET_TP_DESTINATION, requester.getName()).send(requester);
CrossServerMessageHandler.getMessage(targetPlayerName, Message.MessageType.SET_TP_DESTINATION, requester.getName()).send(requester);
}
public static void setPlayerDestinationFromTargetPlayer(Player requester, String targetPlayerName, Connection connection) throws SQLException {
@@ -2,8 +2,9 @@ package me.william278.huskhomes2.teleport;
import me.william278.huskhomes2.HuskHomes;
import me.william278.huskhomes2.MessageManager;
import me.william278.huskhomes2.data.pluginmessage.PluginMessage;
import me.william278.huskhomes2.data.pluginmessage.PluginMessageType;
import me.william278.huskhomes2.data.message.CrossServerMessageHandler;
import me.william278.huskhomes2.data.message.Message;
import me.william278.huskhomes2.data.message.pluginmessage.PluginMessage;
import me.william278.huskhomes2.integrations.VanishChecker;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@@ -23,17 +24,17 @@ public class TeleportRequestHandler {
private static void sendTeleportRequestCrossServer(Player requester, String targetPlayerName, TeleportRequest.RequestType requestType) {
if (requestType == TeleportRequest.RequestType.TPA) {
new PluginMessage(targetPlayerName, PluginMessageType.TPA_REQUEST, requester.getName()).send(requester);
CrossServerMessageHandler.getMessage(targetPlayerName, Message.MessageType.TPA_REQUEST, requester.getName()).send(requester);
} else if (requestType == TeleportRequest.RequestType.TPA_HERE) {
new PluginMessage(targetPlayerName, PluginMessageType.TPA_HERE_REQUEST, requester.getName()).send(requester);
CrossServerMessageHandler.getMessage(targetPlayerName, Message.MessageType.TPA_HERE_REQUEST, requester.getName()).send(requester);
}
}
private static void replyTeleportRequestCrossServer(Player replier, String requesterName, TeleportRequest.RequestType requestType, boolean accepted) {
if (requestType == TeleportRequest.RequestType.TPA) {
new PluginMessage(requesterName, PluginMessageType.TPA_REQUEST_REPLY, replier.getName(), Boolean.toString(accepted)).send(replier);
CrossServerMessageHandler.getMessage(requesterName, Message.MessageType.TPA_REQUEST_REPLY, replier.getName(), Boolean.toString(accepted)).send(replier);
} else if (requestType == TeleportRequest.RequestType.TPA_HERE) {
new PluginMessage(requesterName, PluginMessageType.TPA_HERE_REQUEST_REPLY, replier.getName(), Boolean.toString(accepted)).send(replier);
CrossServerMessageHandler.getMessage(requesterName, Message.MessageType.TPA_HERE_REQUEST_REPLY, replier.getName(), Boolean.toString(accepted)).send(replier);
}
}
@@ -1,8 +1,9 @@
package me.william278.huskhomes2.util;
import me.william278.huskhomes2.HuskHomes;
import me.william278.huskhomes2.data.pluginmessage.PluginMessage;
import me.william278.huskhomes2.data.pluginmessage.PluginMessageType;
import me.william278.huskhomes2.data.message.CrossServerMessageHandler;
import me.william278.huskhomes2.data.message.Message;
import me.william278.huskhomes2.data.message.pluginmessage.PluginMessage;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@@ -33,7 +34,7 @@ public class PlayerList {
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
players.clear();
if (HuskHomes.getSettings().doBungee() && HuskHomes.getSettings().doCrossServerTabCompletion()) {
Bukkit.getScheduler().runTask(plugin, () -> new PluginMessage(PluginMessageType.GET_PLAYER_LIST, HuskHomes.getSettings().getServerID()).sendToServer(updateRequester));
Bukkit.getScheduler().runTask(plugin, () -> CrossServerMessageHandler.getMessage(Message.MessageType.GET_PLAYER_LIST, HuskHomes.getSettings().getServerID()).sendToAllServers(updateRequester));
}
for (Player player : Bukkit.getOnlinePlayers()) {
players.add(player.getName());
@@ -25,12 +25,17 @@ public class UpdateChecker {
this.latestVersion = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())).readLine();
} catch (IOException e) {
this.plugin.getLogger().log(Level.WARNING, "An IOException occurred when trying to check for updates.");
this.latestVersion = "Unknown";
} catch (Exception e) {
this.plugin.getLogger().log(Level.WARNING, "An exception occurred when trying to check for updates.");
this.latestVersion = "Unknown";
}
}
public boolean isUpToDate() {
if (latestVersion.equalsIgnoreCase("Unknown")) {
return true;
}
return latestVersion.equals(currentVersion);
}
+5
View File
@@ -40,6 +40,11 @@ bungee_options:
enable_bungee_mode: false
server_id: 'server'
cluster_id: 0
messenger_type: 'pluginmessage'
redis_credentials:
host: localhost
port: 6379
password: ''
tab_complete_cross_server:
enabled: true
delay: 60