Merge branch 'master' into master

This commit is contained in:
Josh (Vicarious) authored and GitHub committed 2020-08-17 02:13:14 -07:00
commit 79301523a9
28 files changed
+710 -499

No files matched your search

@@ -3,6 +3,7 @@ package net.draycia.carbon;
import net.draycia.carbon.channels.contexts.impl.DistanceContext;
import net.draycia.carbon.listeners.*;
import net.draycia.carbon.managers.*;
import net.draycia.carbon.messaging.MessageManager;
import net.draycia.carbon.storage.UserService;
import net.draycia.carbon.storage.impl.JSONUserService;
import net.draycia.carbon.storage.impl.MySQLUserService;
@@ -16,14 +17,13 @@ public final class CarbonChat extends JavaPlugin {
private Permission permission;
private PluginMessageManager pluginMessageManager;
private CommandManager commandManager;
private ChannelManager channelManager;
private RedisManager redisManager = null;
private AdventureManager adventureManager;
private ContextManager contextManager;
private UserService userService;
private MessageManager messageManager;
private ItemStackUtils itemStackUtils;
@@ -48,15 +48,10 @@ public final class CarbonChat extends JavaPlugin {
saveDefaultConfig();
// Initialize managers
pluginMessageManager = new PluginMessageManager(this);
commandManager = new CommandManager(this);
channelManager = new ChannelManager(this);
contextManager = new ContextManager();
if (getConfig().getBoolean("redis.enabled")) {
getLogger().info("Enabling Redis support!");
redisManager = new RedisManager(this);
}
messageManager = new MessageManager(this);
String storageType = getConfig().getString("storage.type");
@@ -78,7 +73,7 @@ public final class CarbonChat extends JavaPlugin {
@Override
public void onDisable() {
userService.cleanUp();
userService.onDisable();
}
private void setupListeners() {
@@ -115,12 +110,8 @@ public final class CarbonChat extends JavaPlugin {
return channelManager;
}
public PluginMessageManager getPluginMessageManager() {
return pluginMessageManager;
}
public RedisManager getRedisManager() {
return redisManager;
public MessageManager getMessageManager() {
return messageManager;
}
public UserService getUserService() {
@@ -15,7 +15,7 @@ public abstract class ChatChannel implements ForwardingAudience {
/**
* @return The color that represents this channel. Optionally used in formatting.
*/
public abstract TextColor getColor();
public abstract TextColor getChannelColor(ChatUser user);
/**
* @return The MiniMessage styled format for the group in this channel.
@@ -1,5 +1,6 @@
package net.draycia.carbon.channels.impls;
import me.clip.placeholderapi.PlaceholderAPI;
import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.channels.ChatChannel;
import net.draycia.carbon.events.ChatComponentEvent;
@@ -65,6 +66,10 @@ public class CarbonChatChannel extends ChatChannel {
if (user.isOnline()) {
if (user.getNickname() != null) {
user.asPlayer().setDisplayName(user.getNickname());
if (carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
user.asPlayer().setPlayerListName(user.getNickname());
}
}
}
}
@@ -75,7 +80,7 @@ public class CarbonChatChannel extends ChatChannel {
if (userColor != null) {
return userColor;
} else {
return getColor();
return getChannelColor(user);
}
}
@@ -91,7 +96,12 @@ public class CarbonChatChannel extends ChatChannel {
Bukkit.getPluginManager().callEvent(preFormatEvent);
// Return if cancelled or message is emptied
if (preFormatEvent.isCancelled() || preFormatEvent.getMessage().isEmpty()) {
if (preFormatEvent.isCancelled()) {
return;
}
if (preFormatEvent.getMessage().trim().isEmpty()) {
return;
}
@@ -101,11 +111,15 @@ public class CarbonChatChannel extends ChatChannel {
ChatFormatEvent formatEvent = new ChatFormatEvent(user, target, this, preFormatEvent.getFormat(), preFormatEvent.getMessage());
Bukkit.getPluginManager().callEvent(formatEvent);
// Afain, return if cancelled or message is emptied
if (formatEvent.isCancelled() || formatEvent.getMessage().isEmpty()) {
// Again, return if cancelled or message is emptied
if (formatEvent.isCancelled()) {
continue;
}
if (formatEvent.getMessage().trim().isEmpty()) {
return;
}
TextComponent formattedMessage = (TextComponent) carbonChat.getAdventureManager().processMessage(formatEvent.getFormat(),
"br", "\n",
"color", "<" + getColor(target).asHexString() + ">",
@@ -128,31 +142,31 @@ public class CarbonChatChannel extends ChatChannel {
target.sendMessage(newEvent.getComponent());
}
TextComponent consoleMessage = (TextComponent) carbonChat.getAdventureManager().processMessage(preFormatEvent.getFormat(),
ChatFormatEvent consoleFormatEvent = new ChatFormatEvent(user, null, this, preFormatEvent.getFormat(),
preFormatEvent.getMessage());
Bukkit.getPluginManager().callEvent(consoleFormatEvent);
TextComponent consoleMessage = (TextComponent) carbonChat.getAdventureManager().processMessage(consoleFormatEvent.getFormat(),
"br", "\n",
"color", "<" + getColor().asHexString() + ">",
"color", "<" + getColor(user).asHexString() + ">",
"phase", Long.toString(System.currentTimeMillis() % 25),
"server", carbonChat.getConfig().getString("server-name", "Server"),
"message", preFormatEvent.getMessage());
"message", consoleFormatEvent.getMessage());
ChatComponentEvent consoleEvent = new ChatComponentEvent(user, null, this, consoleMessage,
preFormatEvent.getMessage());
consoleFormatEvent.getMessage());
Bukkit.getPluginManager().callEvent(consoleEvent);
// Log message to console
String sm = user.isShadowMuted() ? "[SM] " : "";
System.out.println(sm + CarbonChat.LEGACY.serialize(consoleEvent.getComponent()));
System.out.println(CarbonChat.LEGACY.serialize(consoleEvent.getComponent()));
// Route message to bungee / discord (if message originates from this server)
// Use instanceof and not isOnline, if this message originates from another then the instanceof will
// fail, but isOnline may succeed if the player is online on both servers (somehow).
if (user.isOnline() && !fromRemote && shouldBungee()) {
if (shouldForwardFormatting()) {
sendMessageToBungee(user.asPlayer(), consoleEvent.getComponent());
} else {
sendMessageToBungee(user.asPlayer(), message);
}
sendMessageToBungee(user.asPlayer(), consoleEvent.getComponent());
}
}
@@ -231,11 +245,10 @@ public class CarbonChatChannel extends ChatChannel {
}
public void sendMessageToBungee(Player player, Component component) {
carbonChat.getPluginMessageManager().sendComponent(this, player, component);
}
public void sendMessageToBungee(Player player, String message) {
carbonChat.getPluginMessageManager().sendMessage(this, player, message);
carbonChat.getMessageManager().sendMessage("channel-component", player.getUniqueId(), (byteArray) -> {
byteArray.writeUTF(this.getKey());
byteArray.writeUTF(carbonChat.getAdventureManager().getAudiences().gsonSerializer().serialize(component));
});
}
public Boolean canPlayerSee(ChatUser target, boolean checkSpying) {
@@ -285,8 +298,14 @@ public class CarbonChatChannel extends ChatChannel {
}
@Override
public TextColor getColor() {
return TextColor.fromHexString(getString("color"));
public TextColor getChannelColor(ChatUser user) {
String color = getString("color");
if (user.isOnline()) {
return TextColor.fromHexString(PlaceholderAPI.setPlaceholders(user.asPlayer(), color));
}
return TextColor.fromHexString(color);
}
private String getDefaultFormatName() {
@@ -34,7 +34,7 @@ public class AliasedChannelCommand extends BaseCommand {
user.setSelectedChannel(getChatChannel());
user.sendMessage(carbonChat.getAdventureManager().processMessage(getChatChannel().getSwitchMessage(),
"color", "<" + getChatChannel().getColor().toString() + ">",
"color", "<" + getChatChannel().getChannelColor(user).toString() + ">",
"channel", getChatChannel().getName()));
} else {
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> {
@@ -26,7 +26,7 @@ public class ChannelCommand extends BaseCommand {
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, channel.getSwitchMessage(),
"br", "\n",
"color", "<" + channel.getColor().toString() + ">",
"color", "<" + channel.getChannelColor(user).toString() + ">",
"channel", channel.getName()));
} else {
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> {
@@ -45,10 +45,10 @@ public class ChannelCommand extends BaseCommand {
String otherMessage = channel.getSwitchOtherMessage();
user.sendMessage(carbonChat.getAdventureManager().processMessage(message, "br", "\n",
"color", "<color:" + channel.getColor().toString() + ">", "channel", channel.getName()));
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName()));
carbonChat.getAdventureManager().getAudiences().audience(sender).sendMessage(carbonChat.getAdventureManager().processMessage(otherMessage, "br", "\n",
"color", "<color:" + channel.getColor().toString() + ">", "channel", channel.getName(),
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName(),
"player", user.asOfflinePlayer().getName()));
}
@@ -33,7 +33,7 @@ public class SpyChannelCommand extends BaseCommand {
}
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n",
"color", "<color:" + channel.getColor().toString() + ">", "channel", channel.getName()));
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName()));
}
@Subcommand("whispers")
@@ -34,7 +34,7 @@ public class ToggleCommand extends BaseCommand {
}
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n",
"color", "<color:" + channel.getColor().toString() + ">", "channel", channel.getName()));
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName()));
}
@CommandPermission("carbonchat.toggle.others")
@@ -57,10 +57,10 @@ public class ToggleCommand extends BaseCommand {
}
user.sendMessage(carbonChat.getAdventureManager().processMessage(message, "br", "\n",
"color", "<color:" + channel.getColor().toString() + ">", "channel", channel.getName()));
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName()));
carbonChat.getAdventureManager().getAudiences().audience(sender).sendMessage(carbonChat.getAdventureManager().processMessage(otherMessage,
"br", "\n", "color", "<color:" + channel.getColor().toString() + ">",
"br", "\n", "color", "<color:" + channel.getChannelColor(user).toString() + ">",
"channel", channel.getName(), "player", user.asOfflinePlayer().getName()));
}
}
@@ -9,6 +9,10 @@ public class IgnoredPlayerHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(ChatFormatEvent event) {
if (event.getTarget() == null) {
return;
}
if (event.getTarget().isIgnoringUser(event.getSender())) {
event.setCancelled(true);
}
@@ -27,8 +27,9 @@ public class PingHandler implements Listener {
}
String senderName = event.getSender().asOfflinePlayer().getName();
String prefix = carbonChat.getConfig().getString("pings.prefix", "");
if (senderName == null || !event.getOriginalMessage().contains(senderName)) {
if (senderName == null || !event.getOriginalMessage().contains(prefix + senderName)) {
return;
}
@@ -5,6 +5,7 @@ import net.draycia.carbon.storage.ChatUser;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class PlayerJoinListener implements Listener {
@@ -18,9 +19,20 @@ public class PlayerJoinListener implements Listener {
public void onPlayerJoin(PlayerJoinEvent event) {
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer());
carbonChat.getUserService().validate(user);
if (user.getNickname() != null) {
user.setNickname(user.getNickname());
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
ChatUser user = carbonChat.getUserService().wrapIfLoaded(event.getPlayer());
if (user != null) {
carbonChat.getUserService().invalidate(user);
}
}
}
@@ -11,6 +11,10 @@ public class RelationalPlaceholderHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(ChatFormatEvent event) {
if (event.getTarget() == null) {
return;
}
if (!event.getSender().isOnline() || !event.getTarget().isOnline()) {
return;
}
@@ -1,178 +0,0 @@
package net.draycia.carbon.managers;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import io.github.leonardosnt.bungeechannelapi.BungeeChannelApi;
import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.channels.ChatChannel;
import net.draycia.carbon.storage.ChatUser;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public class PluginMessageManager implements PluginMessageListener {
private final CarbonChat carbonChat;
private final BungeeChannelApi api;
public PluginMessageManager(CarbonChat carbonChat) {
this.carbonChat = carbonChat;
carbonChat.getServer().getMessenger().registerOutgoingPluginChannel(carbonChat, "BungeeCord");
carbonChat.getServer().getMessenger().registerIncomingPluginChannel(carbonChat, "BungeeCord", this);
api = BungeeChannelApi.of(carbonChat);
}
@Override
public void onPluginMessageReceived(String channel, @NotNull Player player, @NotNull byte[] message) {
if (!channel.equals("BungeeCord")) {
return;
}
ByteArrayDataInput input = ByteStreams.newDataInput(message);
String subchannel = input.readUTF();
short length = input.readShort();
byte[] msgbytes = new byte[length];
input.readFully(msgbytes);
ByteArrayDataInput msg = ByteStreams.newDataInput(msgbytes);
switch (subchannel) {
case "carbonchat:message":
onMessageReceived(msg);
break;
case "carbonchat:component":
onComponentReceived(msg);
break;
case "carbonchat:whisper":
onWhisperReceived(msg);
break;
}
}
private void onMessageReceived(ByteArrayDataInput in) {
String chatChannelName = in.readUTF();
ChatChannel chatChannel = carbonChat.getChannelManager().getRegistry().get(chatChannelName);
if (chatChannel == null) {
return;
}
UUID playerUUID;
try {
playerUUID = UUID.fromString(in.readUTF());
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
ChatUser user = carbonChat.getUserService().wrap(playerUUID);
String chatMessage = in.readUTF();
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> {
chatChannel.sendMessage(user, chatMessage, true);
});
}
public void onComponentReceived(ByteArrayDataInput in) {
String chatChannelName = in.readUTF();
ChatChannel chatChannel = carbonChat.getChannelManager().getRegistry().get(chatChannelName);
if (chatChannel == null) {
return;
}
UUID playerUUID;
try {
playerUUID = UUID.fromString(in.readUTF());
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
ChatUser user = carbonChat.getUserService().wrap(playerUUID);
String chatMessage = in.readUTF();
Bukkit.getScheduler().scheduleAsyncDelayedTask(carbonChat, () -> {
chatChannel.sendComponent(user, carbonChat.getAdventureManager().processMessage(chatMessage, "br", "\n"));
});
}
private void onWhisperReceived(ByteArrayDataInput in) {
UUID targetUUID;
UUID senderUUID;
try {
senderUUID = UUID.fromString(in.readUTF());
targetUUID = UUID.fromString(in.readUTF());
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
String chatMessage = in.readUTF();
ChatUser target = carbonChat.getUserService().wrap(targetUUID);
if (!target.isIgnoringUser(senderUUID)) {
target.setReplyTarget(senderUUID);
target.sendMessage(carbonChat.getAdventureManager().processMessage(chatMessage, "br", "\n"));
}
}
public void sendMessage(ChatChannel chatChannel, Player player, String message) {
ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeUTF(chatChannel.getKey());
msg.writeUTF(player.getUniqueId().toString());
msg.writeUTF(message);
api.forward("ALL", "carbonchat:message", msg.toByteArray());
}
public void sendComponent(ChatChannel chatChannel, Player player, Component component) {
ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeUTF(chatChannel.getKey());
msg.writeUTF(player.getUniqueId().toString());
msg.writeUTF(MiniMessage.get().serialize(component));
api.forward("ALL", "carbonchat:component", msg.toByteArray());
}
public void sendComponentToPlayer(ChatUser sender, ChatUser target, Component toComponent, Component fromComponent) {
api.getPlayerList("ALL").whenComplete((result, error) -> {
if (!result.contains(target.asOfflinePlayer().getName())) {
return;
}
sender.sendMessage(toComponent);
if (sender.isShadowMuted()) {
return;
}
ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeUTF(sender.getUUID().toString());
msg.writeUTF(target.getUUID().toString());
msg.writeUTF(MiniMessage.get().serialize(fromComponent));
api.forward("ALL", "carbonchat:whisper", msg.toByteArray());
});
}
}
@@ -1,182 +0,0 @@
package net.draycia.carbon.managers;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.pubsub.api.sync.RedisPubSubCommands;
import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.storage.ChatUser;
import net.draycia.carbon.util.RedisListener;
import net.kyori.adventure.text.format.TextColor;
import java.util.UUID;
public class RedisManager {
private final CarbonChat carbonChat;
private final RedisClient client;
private final StatefulRedisPubSubConnection<String, String> subscribeConnection;
private final RedisPubSubCommands<String, String> subscribeSync;
private final StatefulRedisPubSubConnection<String, String> publishConnection;
private final RedisPubSubCommands<String, String> publishSync;
private final UUID serverUUID = UUID.randomUUID();
public RedisManager(CarbonChat carbonChat) {
this.carbonChat = carbonChat;
String host = carbonChat.getConfig().getString("redis.host");
String password = carbonChat.getConfig().getString("redis.password");
int port = carbonChat.getConfig().getInt("redis.port");
int database = carbonChat.getConfig().getInt("redis.database");
RedisURI.Builder builder = RedisURI.Builder.redis(host, port)
.withDatabase(database);
if (password != null) {
builder.withPassword(password.toCharArray());
}
this.client = RedisClient.create(builder.build());
this.subscribeConnection = client.connectPubSub();
this.subscribeSync = subscribeConnection.sync();
this.publishConnection = client.connectPubSub();
this.publishSync = publishConnection.sync();
subscribeConnection.addListener((RedisListener)(channel, message) -> {
String[] messagePieces = message.split(":");
UUID messageUUID = UUID.fromString(messagePieces[0]);
if (messageUUID.equals(serverUUID)) {
return;
}
UUID uuid = UUID.fromString(messagePieces[1]);
ChatUser user = carbonChat.getUserService().wrapIfLoaded(uuid);
if (user == null) {
return;
}
String value = messagePieces[2];
switch (channel.toLowerCase()) {
case "nickname":
handleNicknameChange(user, value);
break;
case "nickname-reset":
handleNicknameResetChange(user, value);
break;
case "selected-channel":
handleSelectedChannelChange(user, value);
break;
case "spying-whispers":
handleSpyingWhispersChange(user, value);
break;
case "muted":
handleMutedChange(user, value);
break;
case "shadow-muted":
handleShadowMutedChange(user, value);
break;
case "reply-target":
handleReplyTargetChange(user, value);
break;
case "ignoring-user":
handleIgnoringUserChange(user, value, true);
break;
case "unignoring-user":
handleIgnoringUserChange(user, value, false);
break;
case "ignoring-channel":
handleIgnoringChannelChange(user, value, true);
break;
case "unignoring-channel":
handleIgnoringChannelChange(user, value, false);
break;
case "spying-channel":
handleSpyingChannelChange(user, value, true);
break;
case "unspying-channel":
handleSpyingChannelChange(user, value, false);
break;
case "channel-color":
handleChannelColorChange(user, value);
break;
}
});
subscribeSync.subscribe("nickname", "selected-channel", "spying-whispers", "muted", "shadow-muted",
"reply-target", "ignoring-user", "unignoring-user", "ignoring-channel", "unignoring-channel",
"spying-channel", "unspying-channel", "channel-color");
}
private void handleChannelColorChange(ChatUser user, String value) {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(value)).setColor(TextColor.fromHexString(value), true);
}
private void handleSpyingChannelChange(ChatUser user, String value, boolean b) {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(value)).setSpying(b, true);
}
private void handleIgnoringChannelChange(ChatUser user, String value, boolean b) {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(value)).setIgnoring(b, true);
}
private void handleIgnoringUserChange(ChatUser user, String value, boolean b) {
user.setIgnoringUser(UUID.fromString(value), b, true);
}
private void handleReplyTargetChange(ChatUser user, String value) {
user.setReplyTarget(UUID.fromString(value), true);
}
private void handleShadowMutedChange(ChatUser user, String value) {
user.setShadowMuted(value.equalsIgnoreCase("true"), true);
}
private void handleMutedChange(ChatUser user, String value) {
user.setMuted(value.equalsIgnoreCase("true"), true);
}
private void handleSpyingWhispersChange(ChatUser user, String value) {
user.setSpyingWhispers(value.equalsIgnoreCase("true"), true);
}
private void handleSelectedChannelChange(ChatUser user, String value) {
user.setSelectedChannel(carbonChat.getChannelManager().getRegistry().get(value), true);
}
private void handleNicknameResetChange(ChatUser user, String value) {
user.setNickname(null, true);
if (user.isOnline()) {
String message = carbonChat.getConfig().getString("language.nickname-reset");
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(user.asPlayer(),
message, "nickname", ""));
}
}
private void handleNicknameChange(ChatUser user, String value) {
user.setNickname(value, true);
if (user.isOnline()) {
String message = carbonChat.getConfig().getString("language.nickname-set");
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(user.asPlayer(),
message, "nickname", value));
}
}
public void publishChange(UUID uuid, String field, String value) {
publishSync.publish(field, serverUUID + ":" + uuid.toString() + ":" + value);
}
}
@@ -0,0 +1,152 @@
package net.draycia.carbon.messaging;
import com.google.common.io.ByteArrayDataOutput;
import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.channels.ChatChannel;
import net.draycia.carbon.messaging.impl.BungeeMessageService;
import net.draycia.carbon.messaging.impl.EmptyMessageService;
import net.draycia.carbon.messaging.impl.RedisMessageService;
import net.draycia.carbon.storage.ChatUser;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import java.util.UUID;
import java.util.function.Consumer;
public class MessageManager {
private final CarbonChat carbonChat;
private final MessageService messageService;
private final GsonComponentSerializer gsonSerializer;
public MessageManager(CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.gsonSerializer = carbonChat.getAdventureManager().getAudiences().gsonSerializer();
String messageSystem = carbonChat.getConfig().getString("message-system", "none");
if (messageSystem == null) {
messageSystem = "none";
}
switch(messageSystem.toLowerCase()) {
case "bungee":
carbonChat.getLogger().info("Using Bungee Plugin Messaging for message forwarding!");
messageService = new BungeeMessageService(carbonChat);
break;
case "redis":
carbonChat.getLogger().info("Using Redis for message forwarding!");
messageService = new RedisMessageService(carbonChat);
break;
case "none":
messageService = new EmptyMessageService();
break;
default:
carbonChat.getLogger().info("Invalid message service selected! Disabling syncing until next restart!");
messageService = new EmptyMessageService();
break;
}
this.registerDefaultListeners();
}
private void registerDefaultListeners() {
getMessageService().registerUserMessageListener("nickname", (user, byteArray) -> {
String nickname = byteArray.readUTF();
user.setNickname(nickname, true);
if (user.isOnline()) {
String message = carbonChat.getConfig().getString("language.nickname-set");
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(user.asPlayer(),
message, "nickname", nickname));
}
});
getMessageService().registerUserMessageListener("nickname-reset", (user, byteArray) -> {
user.setNickname(null, true);
if (user.isOnline()) {
String message = carbonChat.getConfig().getString("language.nickname-reset");
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(user.asPlayer(), message));
}
});
getMessageService().registerUserMessageListener("selected-channel", (user, byteArray) -> {
user.setSelectedChannel(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()), true);
});
getMessageService().registerUserMessageListener("spying-whispers", (user, byteArray) -> {
user.setSpyingWhispers(byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("muted", (user, byteArray) -> {
user.setMuted(byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("shadow-muted", (user, byteArray) -> {
user.setShadowMuted(byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("reply-target", (user, byteArray) -> {
user.setReplyTarget(new UUID(byteArray.readLong(), byteArray.readLong()), true);
});
getMessageService().registerUserMessageListener("ignoring-user", (user, byteArray) -> {
user.setIgnoringUser(new UUID(byteArray.readLong(), byteArray.readLong()), byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("ignoring-channel", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()))
.setIgnoring(byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("spying-channel", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()))
.setSpying(byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("channel-color", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()))
.setColor(TextColor.fromHexString(byteArray.readUTF()), true);
});
getMessageService().registerUserMessageListener("channel-color-reset", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()))
.setColor(null, true);
});
getMessageService().registerUUIDMessageListener("channel-component", (uuid, byteArray) -> {
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF());
ChatUser user = carbonChat.getUserService().wrap(uuid);
if (channel != null) {
channel.sendComponent(user, gsonSerializer.deserialize(byteArray.readUTF()));
}
});
getMessageService().registerUUIDMessageListener("whisper-component", (uuid, byteArray) -> {
UUID recipient = new UUID(byteArray.readLong(), byteArray.readLong());
ChatUser target = carbonChat.getUserService().wrap(recipient);
String message = byteArray.readUTF();
if (!target.isIgnoringUser(uuid)) {
target.setReplyTarget(uuid);
target.sendMessage(gsonSerializer.deserialize(message));
}
});
}
public MessageService getMessageService() {
return messageService;
}
public void sendMessage(String key, UUID uuid, Consumer<ByteArrayDataOutput> consumer) {
getMessageService().sendMessage(key, uuid, consumer);
}
}
@@ -0,0 +1,20 @@
package net.draycia.carbon.messaging;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import net.draycia.carbon.storage.ChatUser;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
public interface MessageService {
void registerUserMessageListener(String key, BiConsumer<ChatUser, ByteArrayDataInput> listener);
void registerUUIDMessageListener(String key, BiConsumer<UUID, ByteArrayDataInput> listener);
void unregisterMessageListener(String key);
void sendMessage(String key, UUID uuid, Consumer<ByteArrayDataOutput> consumer);
}
@@ -0,0 +1,113 @@
package net.draycia.carbon.messaging.impl;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import io.github.leonardosnt.bungeechannelapi.BungeeChannelApi;
import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.messaging.MessageService;
import net.draycia.carbon.storage.ChatUser;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
public class BungeeMessageService implements PluginMessageListener, MessageService {
private final CarbonChat carbonChat;
private final BungeeChannelApi api;
private Map<String, BiConsumer<ChatUser, ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
private Map<String, BiConsumer<UUID, ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
private final UUID serverUUID = UUID.randomUUID();
public BungeeMessageService(CarbonChat carbonChat) {
this.carbonChat = carbonChat;
carbonChat.getServer().getMessenger().registerOutgoingPluginChannel(carbonChat, "BungeeCord");
carbonChat.getServer().getMessenger().registerIncomingPluginChannel(carbonChat, "BungeeCord", this);
api = BungeeChannelApi.of(carbonChat);
}
@Override
public void onPluginMessageReceived(String channel, @NotNull Player player, @NotNull byte[] message) {
if (!channel.equals("BungeeCord")) {
return;
}
ByteArrayDataInput input = ByteStreams.newDataInput(message);
String key = input.readUTF();
short length = input.readShort();
byte[] msgbytes = new byte[length];
input.readFully(msgbytes);
ByteArrayDataInput msg = ByteStreams.newDataInput(msgbytes);
UUID messageUUID = new UUID(msg.readLong(), msg.readLong());
if (messageUUID.equals(serverUUID)) {
return;
}
UUID uuid = new UUID(msg.readLong(), msg.readLong());
this.receiveMessage(uuid, key, msg);
}
private void receiveMessage(UUID uuid, String key, ByteArrayDataInput value) {
ChatUser user = carbonChat.getUserService().wrapIfLoaded(uuid);
if (user != null) {
for (Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value);
}
}
}
for (Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value);
}
}
}
@Override
public void registerUserMessageListener(String key, BiConsumer<ChatUser, ByteArrayDataInput> listener) {
userLoadedListeners.put(key, listener);
}
@Override
public void registerUUIDMessageListener(String key, BiConsumer<UUID, ByteArrayDataInput> listener) {
userNotLoadedListeners.put(key, listener);
}
@Override
public void unregisterMessageListener(String key) {
userLoadedListeners.remove(key);
userNotLoadedListeners.remove(key);
}
@Override
public void sendMessage(String key, UUID uuid, Consumer<ByteArrayDataOutput> consumer) {
ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeLong(serverUUID.getMostSignificantBits());
msg.writeLong(serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits());
msg.writeLong(uuid.getLeastSignificantBits());
consumer.accept(msg);
api.forward("ALL", key, msg.toByteArray());
}
}
@@ -0,0 +1,34 @@
package net.draycia.carbon.messaging.impl;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import net.draycia.carbon.messaging.MessageService;
import net.draycia.carbon.storage.ChatUser;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
public class EmptyMessageService implements MessageService {
@Override
public void registerUserMessageListener(String key, BiConsumer<ChatUser, ByteArrayDataInput> listener) {
// do nothing
}
@Override
public void registerUUIDMessageListener(String key, BiConsumer<UUID, ByteArrayDataInput> listener) {
// do nothing
}
@Override
public void unregisterMessageListener(String key) {
// do nothing
}
@Override
public void sendMessage(String key, UUID uuid, Consumer<ByteArrayDataOutput> consumer) {
// do nothing
}
}
@@ -0,0 +1,123 @@
package net.draycia.carbon.messaging.impl;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.pubsub.api.sync.RedisPubSubCommands;
import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.messaging.MessageService;
import net.draycia.carbon.storage.ChatUser;
import net.draycia.carbon.util.RedisListener;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
public class RedisMessageService implements MessageService {
private Map<String, BiConsumer<ChatUser, ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
private Map<String, BiConsumer<UUID, ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
private final RedisPubSubCommands<String, String> subscribeSync;
private final RedisPubSubCommands<String, String> publishSync;
private final UUID serverUUID = UUID.randomUUID();
private final CarbonChat carbonChat;
public RedisMessageService(CarbonChat carbonChat) {
this.carbonChat = carbonChat;
String host = carbonChat.getConfig().getString("redis.host");
String password = carbonChat.getConfig().getString("redis.password");
int port = carbonChat.getConfig().getInt("redis.port");
int database = carbonChat.getConfig().getInt("redis.database");
RedisURI.Builder builder = RedisURI.Builder.redis(host, port)
.withDatabase(database);
if (password != null) {
builder.withPassword(password.toCharArray());
}
RedisClient client = RedisClient.create(builder.build());
StatefulRedisPubSubConnection<String, String> subscribeConnection = client.connectPubSub();
this.subscribeSync = subscribeConnection.sync();
StatefulRedisPubSubConnection<String, String> publishConnection = client.connectPubSub();
this.publishSync = publishConnection.sync();
subscribeConnection.addListener((RedisListener)(channel, message) -> {
ByteArrayDataInput input = ByteStreams.newDataInput(Base64.getDecoder().decode(message));
UUID messageUUID = new UUID(input.readLong(), input.readLong());
if (messageUUID.equals(serverUUID)) {
return;
}
UUID uuid = new UUID(input.readLong(), input.readLong());
this.receiveMessage(uuid, channel, input);
});
}
private void receiveMessage(UUID uuid, String key, ByteArrayDataInput value) {
ChatUser user = carbonChat.getUserService().wrapIfLoaded(uuid);
if (user != null) {
for (Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value);
}
}
}
for (Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value);
}
}
}
@Override
public void registerUserMessageListener(String key, BiConsumer<ChatUser, ByteArrayDataInput> listener) {
userLoadedListeners.put(key, listener);
subscribeSync.subscribe(key);
}
@Override
public void registerUUIDMessageListener(String key, BiConsumer<UUID, ByteArrayDataInput> listener) {
userNotLoadedListeners.put(key, listener);
subscribeSync.subscribe(key);
}
@Override
public void unregisterMessageListener(String key) {
userLoadedListeners.remove(key);
userNotLoadedListeners.remove(key);
subscribeSync.unsubscribe(key);
}
@Override
public void sendMessage(String key, UUID uuid, Consumer<ByteArrayDataOutput> consumer) {
ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeLong(serverUUID.getMostSignificantBits());
msg.writeLong(serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits());
msg.writeLong(uuid.getLeastSignificantBits());
consumer.accept(msg);
publishSync.publish(key, Base64.getEncoder().encodeToString(msg.toByteArray()));
}
}
@@ -19,8 +19,11 @@ public interface UserService {
@Nullable
ChatUser wrapIfLoaded(UUID uuid);
void refreshUser(UUID uuid);
ChatUser refreshUser(UUID uuid);
void cleanUp();
void onDisable();
void invalidate(ChatUser user);
void validate(ChatUser user);
}
@@ -82,17 +82,24 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
nickname = CarbonChat.LEGACY.serialize(component);
}
this.nickname = nickname;
final String newNickname = nickname;
this.nickname = newNickname;
if (isOnline()) {
this.asPlayer().setDisplayName(null);
this.asPlayer().setDisplayName(newNickname);
if (carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
this.asPlayer().setPlayerListName(newNickname);
}
}
if (!fromRemote) {
if (nickname == null) {
this.publishChangeToRedis("nickname-reset", "true");
carbonChat.getMessageManager().sendMessage("nickname-reset", this.getUUID(), (byteArray) -> {});
} else {
this.publishChangeToRedis("nickname", nickname);
carbonChat.getMessageManager().sendMessage("nickname", this.getUUID(), (byteArray) -> {
byteArray.writeUTF(newNickname);
});
}
}
}
@@ -120,7 +127,9 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
this.selectedChannel = chatChannel.getKey();
if (!fromRemote) {
this.publishChangeToRedis("selected-channel", chatChannel.getKey());
carbonChat.getMessageManager().sendMessage("selected-channel", this.getUUID(), (byteArray) -> {
byteArray.writeUTF(chatChannel.getKey());
});
}
}
@@ -137,18 +146,18 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override
public void setIgnoringUser(UUID uuid, boolean ignoring, boolean fromRemote) {
if (ignoring) {
if (!fromRemote) {
this.publishChangeToRedis("ignoring-user", uuid.toString());
}
ignoredUsers.add(uuid);
} else {
if (!fromRemote) {
this.publishChangeToRedis("unignoring-user", uuid.toString());
}
ignoredUsers.remove(uuid);
}
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("ignoring-user", this.getUUID(), (byteArray) -> {
byteArray.writeLong(uuid.getMostSignificantBits());
byteArray.writeLong(uuid.getLeastSignificantBits());
byteArray.writeBoolean(ignoring);
});
}
}
public List<UUID> getIgnoredUsers() {
@@ -160,7 +169,9 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
this.muted = muted;
if (!fromRemote) {
this.publishChangeToRedis("muted", muted ? "true" : "false");
carbonChat.getMessageManager().sendMessage("muted", this.getUUID(), (byteArray) -> {
byteArray.writeBoolean(muted);
});
}
}
@@ -174,7 +185,9 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
this.shadowMuted = shadowMuted;
if (!fromRemote) {
this.publishChangeToRedis("shadow-muted", shadowMuted ? "true" : "false");
carbonChat.getMessageManager().sendMessage("shadow-muted", this.getUUID(), (byteArray) -> {
byteArray.writeBoolean(shadowMuted);
});
}
}
@@ -194,7 +207,10 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
this.replyTarget = target;
if (!fromRemote) {
this.publishChangeToRedis("reply-target", target.toString());
carbonChat.getMessageManager().sendMessage("reply-target", this.getUUID(), (byteArray) -> {
byteArray.writeLong(target.getMostSignificantBits());
byteArray.writeLong(target.getLeastSignificantBits());
});
}
}
@@ -214,7 +230,9 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
this.spyingWhispers = spyingWhispers;
if (!fromRemote) {
this.publishChangeToRedis("spying-whispers", spyingWhispers ? "true" : "false");
carbonChat.getMessageManager().sendMessage("spying-whispers", this.getUUID(), (byteArray) -> {
byteArray.writeBoolean(spyingWhispers);
});
}
}
@@ -286,7 +304,14 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
}
}
} else if (sender.isOnline()) {
carbonChat.getPluginMessageManager().sendComponentToPlayer(sender, this, toPlayerComponent, fromPlayerComponent);
sender.sendMessage(toPlayerComponent);
// TODO: make sure this works lol
carbonChat.getMessageManager().sendMessage("whisper-component", sender.getUUID(), (byteArray) -> {
byteArray.writeLong(this.getUUID().getMostSignificantBits());
byteArray.writeLong(this.getUUID().getLeastSignificantBits());
byteArray.writeUTF(carbonChat.getAdventureManager().getAudiences().gsonSerializer().serialize(fromPlayerComponent));
});
}
for (Player player : Bukkit.getOnlinePlayers()) {
@@ -306,12 +331,4 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
"target", targetName, "sender", senderName));
}
}
/* package */ void publishChangeToRedis(String key, String value) {
if (carbonChat.getRedisManager() == null) {
return;
}
carbonChat.getRedisManager().publishChange(uuid, key, value);
}
}
@@ -21,14 +21,12 @@ import java.io.IOException;
import java.lang.reflect.Type;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class JSONUserService implements UserService {
private final CarbonChat carbonChat;
private final LoadingCache<UUID, CarbonChatUser> userCache = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(this::saveUser)
.build(CacheLoader.from(this::loadUser));
@@ -41,6 +39,12 @@ public class JSONUserService implements UserService {
Bukkit.getScheduler().scheduleSyncRepeatingTask(carbonChat, userCache::cleanUp, 0L, 20 * 60 * 10);
}
@Override
public void onDisable() {
userCache.invalidateAll();
userCache.cleanUp();
}
@Override
public ChatUser wrap(String name) {
Player player = Bukkit.getPlayer(name);
@@ -74,14 +78,20 @@ public class JSONUserService implements UserService {
}
@Override
public void refreshUser(UUID uuid) {
public ChatUser refreshUser(UUID uuid) {
userCache.invalidate(uuid);
return this.wrap(uuid);
}
@Override
public void cleanUp() {
userCache.invalidateAll();
userCache.cleanUp();
public void invalidate(ChatUser user) {
userCache.invalidate(user.getUUID());
}
@Override
public void validate(ChatUser user) {
userCache.put(user.getUUID(), (CarbonChatUser)user);
}
private CarbonChatUser loadUser(UUID uuid) {
@@ -23,12 +23,10 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class MySQLUserService implements UserService {
private final LoadingCache<UUID, CarbonChatUser> userCache = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(this::saveUser)
.build(CacheLoader.from(this::loadUser));
@@ -70,8 +68,13 @@ public class MySQLUserService implements UserService {
} catch (SQLException e) {
e.printStackTrace();
}
}
Bukkit.getScheduler().scheduleSyncRepeatingTask(carbonChat, userCache::cleanUp, 0L, 20 * 60 * 10);
@Override
public void onDisable() {
userCache.invalidateAll();
userCache.cleanUp();
database.close();
}
@Override
@@ -107,15 +110,20 @@ public class MySQLUserService implements UserService {
}
@Override
public void cleanUp() {
userCache.invalidateAll();
userCache.cleanUp();
database.close();
public ChatUser refreshUser(UUID uuid) {
userCache.invalidate(uuid);
return this.wrap(uuid);
}
@Override
public void refreshUser(UUID uuid) {
userCache.invalidate(uuid);
public void invalidate(ChatUser user) {
userCache.invalidate(user.getUUID());
}
@Override
public void validate(ChatUser user) {
userCache.put(user.getUUID(), (CarbonChatUser)user);
}
private CarbonChatUser loadUser(UUID uuid) {
@@ -136,18 +144,18 @@ public class MySQLUserService implements UserService {
ChatChannel channel = carbonChat.getChannelManager().getChannelOrDefault(users.getString("channel"));
if (channel != null) {
user.setSelectedChannel(channel);
user.setSelectedChannel(channel, true);
}
String nickname = users.getString("nickname");
if (nickname != null) {
user.setNickname(nickname);
user.setNickname(nickname, true);
}
user.setMuted(users.<Boolean>get("muted"));
user.setShadowMuted(users.<Boolean>get("shadowmuted"));
user.setSpyingWhispers(users.<Boolean>get("spyingwhispers"));
user.setMuted(users.<Boolean>get("muted"), true);
user.setShadowMuted(users.<Boolean>get("shadowmuted"), true);
user.setSpyingWhispers(users.<Boolean>get("spyingwhispers"), true);
for (DbRow channelSetting : channelSettings) {
ChatChannel chatChannel = carbonChat.getChannelManager().getRegistry().get(channelSetting.getString("channel"));
@@ -155,19 +163,19 @@ public class MySQLUserService implements UserService {
if (chatChannel != null) {
UserChannelSettings settings = user.getChannelSettings(chatChannel);
settings.setSpying(channelSetting.<Boolean>get("spying"));
settings.setIgnoring(channelSetting.<Boolean>get("ignored"));
settings.setSpying(channelSetting.<Boolean>get("spying"), true);
settings.setIgnoring(channelSetting.<Boolean>get("ignored"), true);
String color = channelSetting.getString("color");
if (color != null) {
settings.setColor(TextColor.fromHexString(color));
settings.setColor(TextColor.fromHexString(color), true);
}
}
}
for (DbRow ignoredUser : ignoredUsers) {
user.setIgnoringUser(UUID.fromString(ignoredUser.getString("user")), true);
user.setIgnoringUser(UUID.fromString(ignoredUser.getString("user")), true, true);
}
} catch (SQLException e) {
e.printStackTrace();
@@ -17,14 +17,16 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
private final UUID uuid;
private final String channel;
private transient CarbonChat carbonChat;
public SimpleUserChannelSettings(UUID uuid, String channel) {
this.uuid = uuid;
this.channel = channel;
carbonChat = (CarbonChat)Bukkit.getPluginManager().getPlugin("CarbonChat");
}
private CarbonChatUser getUser() {
CarbonChat carbonChat = (CarbonChat)Bukkit.getPluginManager().getPlugin("CarbonChat");
return (CarbonChatUser)carbonChat.getUserService().wrap(uuid);
}
@@ -37,12 +39,11 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
public void setSpying(boolean spying, boolean fromRemote) {
this.spying = spying;
if (fromRemote) {
if (spying) {
getUser().publishChangeToRedis("spying-channel", channel);
} else {
getUser().publishChangeToRedis("unspying-channel", channel);
}
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("spying-channel", uuid, (byteArray) -> {
byteArray.writeUTF(channel);
byteArray.writeBoolean(spying);
});
}
}
@@ -55,12 +56,11 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
public void setIgnoring(boolean ignored, boolean fromRemote) {
this.ignored = ignored;
if (fromRemote) {
if (spying) {
getUser().publishChangeToRedis("ignoring-channel", channel);
} else {
getUser().publishChangeToRedis("unignoring-channel", channel);
}
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("ignoring-channel", uuid, (byteArray) -> {
byteArray.writeUTF(channel);
byteArray.writeBoolean(ignored);
});
}
}
@@ -81,8 +81,10 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
this.color = color.asHexString();
}
if (fromRemote) {
getUser().publishChangeToRedis("channel-color", this.color);
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("channel-color", uuid, (byteArray) -> {
byteArray.writeUTF(color.asHexString());
});
}
}
+11 -4
View File
@@ -37,12 +37,11 @@ default:
vault-balance: 0
# charges on every chat message. 0 to disable. Requires a vault-compatible economy plugin
vault-cost: 0
# The <color> placeholder in channel formats (and other formats).
# This option does support PlaceholderAPI placeholders, however the resulting string must be a valid color!
color: '#FFFFFF'
# Can players /toggle this channel and hide its messages?
ignorable: true
# Setting this to false causes all other servers to re-format the message locally.
# Unadvised unless you have notably different formatting on each server.
forward-format: true
# Enables/disables cross server chat for this channel
should-bungee: true
# If true, plugin will only use the format corresponding to the user's primary group (vault).
@@ -115,10 +114,13 @@ item-link-placeholders:
spy-prefix: '<color>[SPY] '
nicknames-set-tab-name: true
pings:
enabled: true
source: 'PLAYER'
sound: 'minecraft:entity.experience_orb.pickup'
prefix: '@'
volume: 10.0
pitch: 1.0
highlight: true # independent of the "enabled" option!
@@ -139,8 +141,13 @@ storage:
hostname: 'localhost'
port: 3306
# Options:
# 'bungee' - Uses bungee plugin messaging, requires BungeeCord or another proxy which supports it (Velocity!)
# 'redis' - Uses redis for cross server syncing, does not require a server proxy
# 'none' - Do not sync anything cross server, this is the default
message-system: 'none'
redis:
enabled: false
host: 'localhost'
port: 6379
#password: 'password'
@@ -38,7 +38,7 @@ public final class CarbonChatModeration extends JavaPlugin {
Bukkit.getPluginManager().registerEvents(new CapsHandler(this), this);
Bukkit.getPluginManager().registerEvents(new FilterHandler(this), this);
Bukkit.getPluginManager().registerEvents(new MuteHandler(), this);
Bukkit.getPluginManager().registerEvents(new ShadowMuteHandler(), this);
Bukkit.getPluginManager().registerEvents(new ShadowMuteHandler(this), this);
}
@Override
@@ -9,7 +9,10 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -17,8 +20,39 @@ public class FilterHandler implements Listener {
private final CarbonChatModeration moderation;
private final Map<String, List<Pattern>> patternReplacements = new HashMap<>();
private final List<Pattern> blockedWords = new ArrayList<>();
public FilterHandler(CarbonChatModeration moderation) {
this.moderation = moderation;
FileConfiguration config = moderation.getConfig();
ConfigurationSection filters = config.getConfigurationSection("filters.filters");
for (String replacement : filters.getKeys(false)) {
List<Pattern> patterns = new ArrayList<>();
for (String word : filters.getStringList(replacement)) {
if (moderation.getConfig().getBoolean("filters.case-sensitive")) {
patterns.add(Pattern.compile(word));
} else {
patterns.add(Pattern.compile(word, Pattern.CASE_INSENSITIVE));
}
}
patternReplacements.put(replacement, patterns);
}
for (String replacement : config.getStringList("filters.blocked-words")) {
for (String word : filters.getStringList(replacement)) {
if (moderation.getConfig().getBoolean("filters.case-sensitive")) {
blockedWords.add(Pattern.compile(word));
} else {
blockedWords.add(Pattern.compile(word, Pattern.CASE_INSENSITIVE));
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
@@ -31,31 +65,25 @@ public class FilterHandler implements Listener {
return;
}
FileConfiguration config = moderation.getConfig();
ConfigurationSection filters = config.getConfigurationSection("filters.filters");
String message = event.getMessage();
//Matcher matcher;
for (String replacement : filters.getKeys(false)) {
List<String> filteredWords = filters.getStringList(replacement);
for (Map.Entry<String, List<Pattern>> entry : patternReplacements.entrySet()) {
for (Pattern pattern : entry.getValue()) {
Matcher matcher = pattern.matcher(message);
for (String word : filteredWords) {
Matcher matcher;
if (config.getBoolean("filters.case-sensitive")) {
matcher = Pattern.compile(word).matcher(event.getMessage());
if (entry.getKey().equals("_")) {
message = matcher.replaceAll("");
} else {
matcher = Pattern.compile(word, Pattern.CASE_INSENSITIVE).matcher(event.getMessage());
}
if (replacement.equals("_")) {
event.setMessage(matcher.replaceAll(""));
} else {
event.setMessage(matcher.replaceAll(replacement));
message = matcher.replaceAll(entry.getKey());
}
}
}
for (String blockedWord : config.getStringList("filters.blocked-words")) {
if (Pattern.compile(blockedWord, Pattern.CASE_INSENSITIVE).matcher(event.getMessage()).find()) {
event.setMessage(message);
for (Pattern blockedWord : blockedWords) {
if (blockedWord.matcher(event.getMessage()).find()) {
event.setCancelled(true);
break;
}
@@ -1,12 +1,20 @@
package net.draycia.carbonmoderation.listeners;
import net.draycia.carbon.events.ChatComponentEvent;
import net.draycia.carbon.events.ChatFormatEvent;
import net.draycia.carbonmoderation.CarbonChatModeration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
public class ShadowMuteHandler implements Listener {
private final CarbonChatModeration moderation;
public ShadowMuteHandler(CarbonChatModeration moderation) {
this.moderation = moderation;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onComponent(ChatComponentEvent event) {
if (event.getSender().isShadowMuted()) {
@@ -14,8 +22,21 @@ public class ShadowMuteHandler implements Listener {
event.setCancelled(true);
}
}
}
// TODO: figure out a way to add the console "[SM]" prefix for shadow muted players
@EventHandler
public void on(ChatFormatEvent event) {
if (event.getTarget() != null) {
return;
}
if (!event.getSender().isShadowMuted()) {
return;
}
String prefix = moderation.getConfig().getString("shadow-mute-prefix", "[SM] ");
event.setFormat(prefix + event.getFormat());
}
}
@@ -4,6 +4,8 @@ caps-protection:
percent-caps: 80
block-message: false
shadow-mute-prefix: '[SM] '
filters:
enabled: true
case-sensitive: false