cleanup project

This commit is contained in:
Draycia committed 2021-05-07 15:37:17 -07:00
1 parent 1231946184
commit 6681c22288
106 files changed
+10 -9601

No files matched your search

@@ -1,59 +0,0 @@
package net.draycia.carbon.common.adventure;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.adventure.MessageProcessor;
import net.draycia.carbon.common.utils.ColorUtils;
import net.kyori.adventure.platform.AudienceProvider;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public class AdventureManager implements MessageProcessor {
private final @NonNull AudienceProvider provider;
private final @NonNull CarbonChat carbonChat;
public AdventureManager(final @NonNull AudienceProvider provider) {
this.provider = provider;
this.carbonChat = CarbonChatProvider.carbonChat();
}
@Override
public @NonNull Component processMessage(final @Nullable String input, final @NonNull String @NonNull ... placeholders) {
if (input == null || input.trim().isEmpty()) {
return Component.empty();
}
String format = ColorUtils.translateAlternateColors(input)
.replace("\\n", "\n")
.replace("<br>", "\n")
.replace("<server>", this.carbonChat.carbonSettings().serverName());
format = this.processPlaceholders(format, placeholders);
return MiniMessage.get().parse(format);
}
private @NonNull Component processMojang(final @NonNull String input) {
return this.carbonChat.gsonSerializer().deserialize(input);
}
private @NonNull String processPlaceholders(@NonNull String input, final @NonNull String @NonNull ... placeholders) {
for (int i = 0; i < placeholders.length; i += 2) {
final String placeholder = placeholders[i];
final String replacement = placeholders[i + 1];
input = input.replace("<" + placeholder + ">", replacement);
}
return input;
}
@Override
public @NonNull AudienceProvider audiences() {
return this.provider;
}
}
@@ -1,545 +0,0 @@
package net.draycia.carbon.common.channels;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.config.ChannelOptions;
import net.draycia.carbon.api.config.ColorPriority;
import net.draycia.carbon.api.users.ConsoleUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.common.utils.ColorUtils;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.ChatComponentEvent;
import net.draycia.carbon.api.events.ChatFormatEvent;
import net.draycia.carbon.api.events.MessageContextEvent;
import net.draycia.carbon.api.events.PreChatFormatEvent;
import net.draycia.carbon.api.events.ReceiverContextEvent;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.Context;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.luckperms.api.model.group.Group;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
public class CarbonChatChannel implements TextChannel {
private final @NonNull CarbonChat carbonChat;
private @NonNull ChannelOptions options;
public CarbonChatChannel(final @NonNull CarbonChat carbonChat, final @NonNull ChannelOptions options) {
this.carbonChat = carbonChat;
this.options = options;
}
@Override
public @NonNull ChannelOptions options() {
return this.options;
}
@Override
public void options(final @NonNull ChannelOptions options) {
this.options = options;
}
public @NonNull CarbonChat carbonChat() {
return this.carbonChat;
}
@Override
public boolean testContext(final @NonNull PlayerUser sender, final @NonNull PlayerUser target) {
final ReceiverContextEvent event = new ReceiverContextEvent(this, sender, target);
CarbonEvents.post(event);
return !event.cancelled();
}
@Override
public boolean canPlayerUse(final @NonNull PlayerUser user) {
return user.hasPermission("carbonchat.channels." + this.name() + ".use");
}
@Override
public @NonNull List<@NonNull PlayerUser> audiences() {
final List<PlayerUser> audience = new ArrayList<>();
for (final PlayerUser user : this.carbonChat.userService().onlineUsers()) {
if (this.canPlayerSee(user, true)) {
audience.add(user);
}
}
return audience;
}
// private void updateUserNickname(final @NonNull ChatUser user) {
// final Player player = Bukkit.getPlayer(user.uuid());
//
// if (player != null) {
// String nickname = user.nickname();
//
// if (nickname != null) {
// final Component component = this.carbonChat.messageProcessor().processMessage(nickname);
// nickname = CarbonChat.LEGACY.serialize(component);
//
// player.setDisplayName(nickname);
//
// if (this.carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
// player.setPlayerListName(nickname);
// }
// }
// }
// }
@Override
public @NonNull Map<CarbonUser, Component> parseMessage(final @NonNull PlayerUser user, final @NonNull Collection<@NonNull PlayerUser> recipients, final @NonNull String message) {
//this.updateUserNickname(user);
final MessageContextEvent event = new MessageContextEvent(this, user);
CarbonEvents.post(event);
if (event.cancelled()) {
return Collections.emptyMap();
}
// Get player's formatting
final String messageFormat = this.format(user);
// Call custom chat event
final PreChatFormatEvent preFormatEvent = new PreChatFormatEvent(user, this, messageFormat, message);
CarbonEvents.post(preFormatEvent);
// Return if cancelled or message is emptied
if (preFormatEvent.cancelled() || preFormatEvent.message().trim().isEmpty()) {
return Collections.emptyMap();
}
final Map<CarbonUser, Component> users = new HashMap<>();
// Iterate through players who should receive messages in this channel
for (final PlayerUser target : recipients) {
// Call second format event. Used for relational stuff (placeholders etc)
final ChatFormatEvent formatEvent = new ChatFormatEvent(user, target, this, preFormatEvent.format(), preFormatEvent.message());
CarbonEvents.post(formatEvent);
// Again, return if cancelled or message is emptied
if (formatEvent.cancelled() || formatEvent.message().trim().isEmpty()) {
continue;
}
final TextColor channelColor = this.channelColor(target);
final TextColor userColor = user.customChatColor();
final TextColor userChannelColor = user.channelSettings(this).color();
TextColor colorBuffer = null;
for (final ColorPriority colorPriority : this.options().colorPriorities()) {
if (colorPriority == ColorPriority.CHANNEL) {
colorBuffer = channelColor;
} else if (colorPriority == ColorPriority.PLAYER && userColor != null) {
colorBuffer = userColor;
} else if (colorPriority == ColorPriority.CUSTOM && userChannelColor != null) {
colorBuffer = userChannelColor;
}
}
final TextColor chosenColor;
if (colorBuffer == null) {
chosenColor = NamedTextColor.WHITE;
} else {
chosenColor = colorBuffer;
}
TextComponent formatComponent = (TextComponent) this.carbonChat.messageProcessor().processMessage(formatEvent.format(),
"nickname", user.nickname(),
"displayname", user.displayName(),
"username", user.name(),
"color", "<" + chosenColor.asHexString() + ">",
"playercolor", "<" + user.customChatColor(),
"phase", Long.toString(System.currentTimeMillis() % 25),
"message", formatEvent.message());
if (this.isUserSpying(user, target)) {
final String prefix = this.carbonChat.carbonSettings().spyPrefix();
formatComponent = (TextComponent) MiniMessage.get().parse(prefix, "color",
chosenColor.asHexString()).append(formatComponent);
}
final ChatComponentEvent newEvent = new ChatComponentEvent(user, target, this, formatComponent,
formatEvent.message());
CarbonEvents.post(newEvent);
final CarbonUser targetUser = newEvent.target();
if (targetUser != null) {
users.put(targetUser, newEvent.component());
}
}
final ConsoleUser consoleUser = this.carbonChat.userService().consoleUser();
final ChatFormatEvent consoleFormatEvent = new ChatFormatEvent(user, consoleUser, this, preFormatEvent.format(),
preFormatEvent.message());
CarbonEvents.post(consoleFormatEvent);
final TextColor channelColor = this.channelColor(user);
final TextComponent consoleFormat = (TextComponent) this.carbonChat.messageProcessor().processMessage(consoleFormatEvent.format(),
"nickname", user.nickname(),
"displayname", user.displayName(),
"username", user.name(),
"color", "<" + channelColor.asHexString() + ">",
"playercolor", "<" + user.customChatColor(),
"phase", Long.toString(System.currentTimeMillis() % 25),
"message", consoleFormatEvent.message());
final ChatComponentEvent consoleEvent = new ChatComponentEvent(user, consoleUser, this, consoleFormat,
consoleFormatEvent.message());
CarbonEvents.post(consoleEvent);
if (!consoleEvent.cancelled()) {
if (consoleUser != null) {
users.put(consoleUser, consoleEvent.component());
}
}
// TODO: Rethink how cross server messaging works. There should be no recursion inherent in the design.
if (user.online() && this.crossServer()) {
this.sendMessageToBungee(user.uuid(), consoleEvent.component());
}
return users;
}
@Override
public void sendComponents(final @NonNull Identity identity,
final @NonNull Map<? extends CarbonUser, Component> components) {
for (final Map.Entry<? extends CarbonUser, Component> entry : components.entrySet()) {
if (entry.getValue().equals(Component.empty())) {
continue;
}
entry.getKey().sendMessage(identity, entry.getValue());
}
}
@Override
public void sendComponentsAndLog(final @NonNull Identity identity,
final @NonNull Map<? extends CarbonUser, Component> components) {
for (final Map.Entry<? extends CarbonUser, Component> entry : components.entrySet()) {
if (entry.getValue().equals(Component.empty())) {
continue;
}
entry.getKey().sendMessage(identity, entry.getValue());
if (entry instanceof ConsoleUser) {
this.carbonChat.messageProcessor().audiences().console()
.sendMessage(identity, entry.getValue());
}
}
}
@Override
public @NonNull Map<CarbonUser, Component> parseMessage(final @NonNull PlayerUser user, final @NonNull String message) {
return this.parseMessage(user, this.audiences(), message);
}
public @NonNull String format(final @NonNull PlayerUser user) {
for (final String group : this.groupOverrides()) {
if (this.userHasGroup(user, group)) {
final String format = this.format(group);
if (format != null) {
return format;
}
}
}
if (this.primaryGroupOnly()) {
return this.primaryGroupFormat(user);
} else {
return this.firstFoundUserFormat(user);
}
}
private boolean userHasGroup(final @NonNull PlayerUser user, final @NonNull String group) {
if (user.hasGroup(group)) {
return true;
}
if (this.permissionGroupMatching()) {
return user.hasPermission("carbonchat.group." + group);
}
return false;
}
private @NonNull String firstFoundUserFormat(final @NonNull PlayerUser user) {
for (final Group group : user.groups()) {
final String groupFormat = this.format(group);
if (groupFormat != null) {
return groupFormat;
}
}
return this.defaultFormat();
}
private @NonNull String primaryGroupFormat(final @NonNull PlayerUser user) {
final Group primaryGroup = user.primaryGroup();
if (primaryGroup == null) {
return this.defaultFormat();
}
final String primaryGroupFormat = this.format(primaryGroup);
if (primaryGroupFormat != null) {
return primaryGroupFormat;
}
return this.defaultFormat();
}
private @NonNull String defaultFormat() {
final String defaultFormatName = this.defaultFormatName();
if (defaultFormatName == null) {
return "<<displayname>> <message>";
}
final String defaultFormat = this.format(defaultFormatName);
if (defaultFormat == null) {
return "<<displayname>> <message>";
}
return defaultFormat;
}
@Override
public @Nullable String format(final @NonNull Group group) {
return this.format(group.getName());
}
@Override
public @Nullable String format(final @NonNull String group) {
return this.options().format(group);
}
private boolean isUserSpying(final @NonNull PlayerUser sender, final @NonNull PlayerUser target) {
if (!this.canPlayerSee(sender, target, false)) {
return target.channelSettings(this).spying();
}
return false;
}
@Override
public void sendComponent(final @NonNull PlayerUser player, final @NonNull Component component) {
for (final PlayerUser user : this.audiences()) {
if (!user.ignoringUser(player)) {
user.sendMessage(player.identity(), component);
}
}
}
public void sendMessageToBungee(final @NonNull UUID uuid, final @NonNull Component component) {
this.carbonChat.messageService().sendMessage("channel-component", uuid, byteArray -> {
byteArray.writeUTF(this.key());
byteArray.writeUTF(this.carbonChat.gsonSerializer().serialize(component));
});
}
@Override
public boolean canPlayerSee(final @NonNull PlayerUser target, final boolean checkSpying) {
if (checkSpying && target.hasPermission("carbonchat.spy." + this.name())) {
if (target.channelSettings(this).spying()) {
return true;
}
}
if (!(target.hasPermission("carbonchat.channels." + this.name() + ".see"))) {
return false;
}
if (this.ignorable()) {
return !target.channelSettings(this).ignored();
}
return true;
}
public boolean canPlayerSee(final @NonNull PlayerUser sender, final @NonNull PlayerUser target, final boolean checkSpying) {
if (!this.canPlayerSee(target, checkSpying)) {
return false;
}
if (this.ignorable()) {
return !target.ignoringUser(sender) || target.hasPermission("carbonchat.ignore.exempt");
}
return true;
}
@Override
public @NonNull TextColor channelColor(final @NonNull CarbonUser user) {
final String input = this.options().color();
if (input != null) {
final TextColor color = ColorUtils.parseColor(user, input);
if (color != null) {
return color;
}
}
return NamedTextColor.WHITE;
}
public @Nullable String defaultFormatName() {
return this.options().defaultFormatName();
}
@Override
public boolean isDefault() {
return this.options().isDefault();
}
@Override
public boolean ignorable() {
return this.options().ignorable();
}
@Override
public boolean crossServer() {
return this.options().crossServer();
}
@Override
public boolean honorsRecipientList() {
return this.options().honorsRecipientList();
}
@Override
public boolean permissionGroupMatching() {
return this.options().permissionGroupMatching();
}
@Override
public @NonNull List<@NonNull String> groupOverrides() {
return this.options().groupOverrides();
}
@Override
public @NonNull String name() {
return this.options().name();
}
@Override
public @Nullable String messagePrefix() {
return this.options().messagePrefix();
}
@Override
public @NonNull String switchMessage() {
return this.options().switchMessage();
}
@Override
public @NonNull String switchOtherMessage() {
return this.options().switchOtherMessage();
}
@Override
public @NonNull String switchFailureMessage() {
return this.options().switchFailureMessage();
}
@Override
public @NonNull String cannotIgnoreMessage() {
return this.options().cannotIgnoreMessage();
}
@Override
public @NonNull String toggleOffMessage() {
return this.options().toggleOffMessage();
}
@Override
public @NonNull String toggleOnMessage() {
return this.options().toggleOnMessage();
}
@Override
public @NonNull String toggleOtherOnMessage() {
return this.options().toggleOtherOnMessage();
}
@Override
public @NonNull String toggleOtherOffMessage() {
return this.options().toggleOtherOffMessage();
}
@Override
public @NonNull String cannotUseMessage() {
return this.options().cannotUseMessage();
}
@Override
public boolean primaryGroupOnly() {
return this.options().primaryGroupOnly();
}
// @Override
// public boolean shouldCancelChatEvent() {
// return this.options().shouldCancelChatEvent();
// }
@Override
public @NonNull List<@NonNull Pattern> itemLinkPatterns() {
return this.carbonChat.carbonSettings().itemLinkPatterns();
}
@Override
public @NonNull List<String> aliases() {
return this.options().aliases();
}
@Override
public @Nullable Context context(final @NonNull String key) {
return this.options().context(key);
}
@Override
public @NonNull String key() {
return this.options().key();
}
}
@@ -1,291 +0,0 @@
package net.draycia.carbon.common.channels;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.WhisperChannel;
import net.draycia.carbon.api.config.ChannelOptions;
import net.draycia.carbon.api.events.ChatComponentEvent;
import net.draycia.carbon.api.events.ChatFormatEvent;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.ConsoleUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public class CarbonWhisperChannel implements WhisperChannel {
private final @NonNull CarbonChat carbonChat;
private final @NonNull PlayerUser sender;
private final @NonNull PlayerUser audience;
public CarbonWhisperChannel(final @NonNull PlayerUser sender, final @NonNull PlayerUser audience) {
this.carbonChat = CarbonChatProvider.carbonChat();
this.sender = sender;
this.audience = audience;
}
@Override
public @NonNull ChannelOptions options() {
return ChannelOptions.defaultChannel();
}
@Override
public void options(final @NonNull ChannelOptions options) {
}
@Override
public @NonNull PlayerUser sender() {
return this.sender;
}
@Override
public @NonNull PlayerUser audience() {
return this.audience;
}
@Override
public @NonNull TextColor channelColor(final @NonNull CarbonUser user) {
return NamedTextColor.WHITE;
}
@Override
public @NonNull Map<CarbonUser, Component> parseMessage(final @NonNull PlayerUser user, final @NonNull String message) {
return this.parseMessage(user, Collections.singleton(this.audience()), message);
}
@Override
public @NonNull Map<CarbonUser, Component> parseMessage(final @NonNull PlayerUser user,
final @NonNull Collection<@NonNull PlayerUser> recipients,
final @NonNull String message) {
final Map<CarbonUser, Component> result = new HashMap<>();
// Formats
final String senderFormat = this.senderFormat();
final String receiverFormat = this.receiverFormat();
if (senderFormat == null) {
throw new IllegalArgumentException("Sender format (whispers) not found!");
}
if (receiverFormat == null) {
throw new IllegalArgumentException("Receiver format (whispers) not found!");
}
final ChatFormatEvent senderFormatEvent = new ChatFormatEvent(this.sender, this.sender, this, senderFormat, message);
CarbonEvents.post(senderFormatEvent);
if (senderFormatEvent.cancelled() || senderFormatEvent.message().trim().isEmpty()) {
return Collections.emptyMap();
}
final ChatFormatEvent receiverFormatEvent = new ChatFormatEvent(this.sender, this.audience, this, receiverFormat, message);
CarbonEvents.post(receiverFormatEvent);
if (receiverFormatEvent.cancelled() || receiverFormatEvent.message().trim().isEmpty()) {
return Collections.emptyMap();
}
// Display names
final String senderName = this.sender.nickname();
final String receiverName = this.audience.nickname();
// Components
final TextComponent senderComponent = (TextComponent) this.carbonChat.messageProcessor().processMessage(
senderFormatEvent.format(),
"senderdisplayname", senderName,
"sender", this.sender.name(),
"receiverdisplayname", receiverName,
"receiver", this.audience.name(),
"phase", Long.toString(System.currentTimeMillis() % 25),
"message", senderFormatEvent.message());
final ChatComponentEvent senderComponentEvent = new ChatComponentEvent(this.sender, this.sender, this,
senderComponent, senderFormatEvent.message());
CarbonEvents.post(senderComponentEvent);
result.put(this.sender, senderComponentEvent.component());
final TextComponent receiverComponent = (TextComponent) this.carbonChat.messageProcessor().processMessage(
receiverFormatEvent.format(),
"senderdisplayname", senderName,
"sender", this.sender.name(),
"receiverdisplayname", receiverName,
"receiver", this.audience.name(),
"phase", Long.toString(System.currentTimeMillis() % 25),
"message", senderFormatEvent.message());
final ChatComponentEvent receiverComponentEvent = new ChatComponentEvent(this.sender, this.audience, this,
receiverComponent, receiverFormatEvent.message());
CarbonEvents.post(receiverComponentEvent);
result.put(this.audience, receiverComponentEvent.component());
final String consoleFormatString = this.consoleFormat();
if (consoleFormatString != null) {
final ChatFormatEvent consoleFormatEvent = new ChatFormatEvent(this.sender, null, this,
consoleFormatString, message);
CarbonEvents.post(consoleFormatEvent);
final TextComponent consoleFormat = (TextComponent) this.carbonChat.messageProcessor().processMessage(
consoleFormatEvent.format(),
"senderdisplayname", senderName,
"sender", this.sender.name(),
"receiverdisplayname", receiverName,
"receiver", this.audience.name(),
"phase", Long.toString(System.currentTimeMillis() % 25),
"message", senderFormatEvent.message());
final ChatComponentEvent consoleEvent = new ChatComponentEvent(this.sender, null, this, consoleFormat,
consoleFormatEvent.message());
CarbonEvents.post(consoleEvent);
if (!consoleEvent.cancelled()) {
final ConsoleUser consoleUser = this.carbonChat.userService().consoleUser();
if (consoleUser != null) {
result.put(consoleUser, consoleEvent.component());
}
}
}
this.sender.replyTarget(this.audience);
this.audience.replyTarget(this.sender);
return result;
}
@Override
public boolean canPlayerUse(final @NonNull PlayerUser user) {
return user.equals(this.sender);
}
@Override
public boolean canPlayerSee(final @NonNull PlayerUser sender, final @NonNull PlayerUser target, final boolean checkSpying) {
return (checkSpying && target.spyingWhispers()) || (sender.equals(this.sender) && target.equals(this.audience));
}
@Override
public boolean canPlayerSee(final @NonNull PlayerUser target, final boolean checkSpying) {
return false;
}
@Override
public void sendComponents(final @NonNull Identity identity,
final @NonNull Map<? extends CarbonUser, Component> components) {
for (final Map.Entry<? extends CarbonUser, Component> entry : components.entrySet()) {
entry.getKey().sendMessage(identity, entry.getValue());
}
}
@Override
public void sendComponentsAndLog(final @NonNull Identity identity,
final @NonNull Map<? extends CarbonUser, Component> components) {
for (final Map.Entry<? extends CarbonUser, Component> entry : components.entrySet()) {
entry.getKey().sendMessage(Identity.nil(), entry.getValue());
if (entry.getKey() instanceof ConsoleUser) {
this.carbonChat.messageProcessor().audiences().console()
.sendMessage(identity, entry.getValue());
}
}
}
@Override
public @NonNull String name() {
return "Whisper";
}
@Override
public @NonNull String key() {
return "whisper";
}
@Override
public boolean ignorable() {
return false;
}
@Override
public @NonNull List<@NonNull Pattern> itemLinkPatterns() {
return this.carbonChat.carbonSettings().itemLinkPatterns();
}
public @Nullable String senderFormat() {
return this.carbonChat.carbonSettings().whisperOptions().senderFormat();
}
public @Nullable String receiverFormat() {
return this.carbonChat.carbonSettings().whisperOptions().receiverFormat();
}
public @Nullable String consoleFormat() {
return this.carbonChat.carbonSettings().whisperOptions().consoleFormat();
}
@Override
public @NonNull String switchMessage() {
return this.carbonChat.carbonSettings().whisperOptions().switchMessage();
}
@Override
public @NonNull String switchOtherMessage() {
return this.carbonChat.carbonSettings().whisperOptions().switchOtherMessage();
}
@Override
public @NonNull String switchFailureMessage() {
return this.carbonChat.carbonSettings().whisperOptions().switchFailureMessage();
}
@Override
public @NonNull String cannotIgnoreMessage() {
return this.carbonChat.carbonSettings().whisperOptions().cannotIgnoreMessage();
}
@Override
public @NonNull String toggleOffMessage() {
return this.carbonChat.carbonSettings().whisperOptions().toggleOffMessage();
}
@Override
public @NonNull String toggleOnMessage() {
return this.carbonChat.carbonSettings().whisperOptions().toggleOnMessage();
}
@Override
public @NonNull String toggleOtherOnMessage() {
return this.carbonChat.carbonSettings().whisperOptions().toggleOtherOnMessage();
}
@Override
public @NonNull String toggleOtherOffMessage() {
return this.carbonChat.carbonSettings().whisperOptions().toggleOtherOffMessage();
}
@Override
public @NonNull String cannotUseMessage() {
return this.carbonChat.carbonSettings().whisperOptions().cannotUseMessage();
}
}
@@ -1,127 +0,0 @@
package net.draycia.carbon.common.channels;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.config.ChannelOptions;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.ChannelRegisterEvent;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Collections;
import java.util.Map;
public class ChannelManager {
private final @NonNull CarbonChat carbonChat;
private final @NonNull ChannelRegistry registry;
private @MonotonicNonNull String defaultChannelKey = null;
@SuppressWarnings("method.invocation.invalid")
public ChannelManager(final @NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.registry = new ChannelRegistry();
this.carbonChat.logger().info("Loading channels!");
this.loadChannels();
}
public @Nullable ChatChannel loadChannel(final @NonNull ChannelOptions settings) {
final ChatChannel channel = new CarbonChatChannel(this.carbonChat, settings);
final String name = settings.name();
if (name.length() > 16) {
this.carbonChat.logger().error("Channel name [" + name + "] too long! Max length: 16.");
this.carbonChat.logger().error("Skipping channel, please check your settings!");
return null;
}
return channel;
}
public void registerChannel(final @NonNull ChatChannel channel) {
this.registry().register(channel.key(), channel);
if (channel instanceof TextChannel) {
if (((TextChannel) channel).isDefault() && this.defaultChannelKey == null) {
this.carbonChat.logger().info("Default channel registered: " + channel.name());
this.defaultChannelKey = channel.key();
}
}
CarbonEvents.post(new ChannelRegisterEvent(Collections.singletonList(channel), this.registry()));
}
public @NonNull ChannelRegistry registry() {
return this.registry;
}
public @Nullable ChatChannel defaultChannel() {
if (this.defaultChannelKey != null) {
return this.registry.get(this.defaultChannelKey);
}
return null;
}
public @Nullable ChatChannel channelOrDefault(final @Nullable String key) {
if (key == null) {
return this.defaultChannel();
}
final ChatChannel channel = this.registry.get(key);
if (channel == null) {
return this.defaultChannel();
}
return channel;
}
private void loadChannels() {
this.carbonChat.logger().info("Channels found: " +
this.carbonChat.channelSettings().channelOptions().size());
for (final Map.Entry<String, ChannelOptions> options :
this.carbonChat.channelSettings().channelOptions().entrySet()) {
final ChatChannel channel = this.loadChannel(options.getValue());
if (channel != null) {
this.registerChannel(channel);
String prefix = null;
if (channel instanceof TextChannel) {
prefix = ((TextChannel) channel).messagePrefix();
}
if (prefix != null && !prefix.trim().isEmpty()) {
prefix = "(" + prefix + ") ";
} else {
prefix = "";
}
this.carbonChat.logger().info("Registering channel: " + prefix + channel.name());
}
}
}
public void reloadChannels() {
for (final Map.Entry<String, ChannelOptions> options :
this.carbonChat.channelSettings().channelOptions().entrySet()) {
final ChatChannel channel = this.registry().get(options.getValue().key());
if (channel != null) {
channel.options(options.getValue());
}
}
}
}
@@ -1,86 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.standard.StringArgument;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.identity.Identity;
import org.checkerframework.checker.nullness.qual.NonNull;
public class AliasedChannelCommand {
private final @NonNull CarbonChat carbonChat;
private final @NonNull TextChannel chatChannel;
private final @NonNull String commandName;
@SuppressWarnings("methodref.receiver.bound.invalid")
public AliasedChannelCommand(final @NonNull CommandManager<CarbonUser> commandManager, final @NonNull TextChannel chatChannel) {
this.carbonChat = CarbonChatProvider.carbonChat();
this.chatChannel = chatChannel;
this.commandName = chatChannel.key();
commandManager.command(
commandManager.commandBuilder(this.commandName, this.chatChannel.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.channel")
.handler(this::channel)
.build()
);
commandManager.command(
commandManager.commandBuilder(this.commandName, this.chatChannel.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.channel.message")
.argument(StringArgument.<CarbonUser>newBuilder("message").greedy().build())
.handler(this::sendMessage)
.build()
);
}
private void channel(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
if (!this.canUse(user)) return;
user.selectedChannel(this.chatChannel());
}
private void sendMessage(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
if (!this.canUse(user)) return;
context.<String>getOptional("message").ifPresent(message -> {
this.chatChannel().sendComponentsAndLog(
context.getSender().identity(),
this.chatChannel().parseMessage(user, message));
});
}
public @NonNull TextChannel chatChannel() {
return this.chatChannel;
}
public @NonNull String commandName() {
return this.commandName;
}
private boolean canUse(final PlayerUser user) {
if (user.channelSettings(this.chatChannel()).ignored() || !this.chatChannel().canPlayerUse(user)) {
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(this.chatChannel().cannotUseMessage(),
"color", "<" + this.chatChannel().channelColor(user).toString() + ">",
"channel", this.chatChannel().name()));
return false;
}
return true;
}
}
@@ -1,83 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.standard.StringArgument;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.common.commands.arguments.ChannelArgument;
import net.kyori.adventure.identity.Identity;
import org.checkerframework.checker.nullness.qual.NonNull;
public class ChannelCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public ChannelCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("channel");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.channel")
.argument(ChannelArgument.requiredChannelArgument())
.handler(this::channel)
.build()
);
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.channel.message")
.argument(ChannelArgument.requiredChannelArgument())
.argument(StringArgument.of("message")) // carbonchat.channel.message
.handler(this::sendMessage)
.build()
);
}
private void channel(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
final TextChannel channel = context.get("channel");
if (!this.canUse(user, channel)) return;
user.selectedChannel(channel);
}
private void sendMessage(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
final ChatChannel channel = context.get("channel");
final String message = context.get("message");
if (!this.canUse(user, channel)) return;
channel.sendComponentsAndLog(context.getSender().identity(), channel.parseMessage(user, message));
}
private boolean canUse(final PlayerUser user, final ChatChannel channel) {
if (user.channelSettings(channel).ignored() || !channel.canPlayerUse(user)) {
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(channel.cannotUseMessage(),
"color", "<" + channel.channelColor(user).toString() + ">",
"channel", channel.name()));
return false;
}
return true;
}
}
@@ -1,130 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.common.commands.arguments.PlayerUserArgument;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
public class ChannelListCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public ChannelListCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("channellist");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // console & player
.permission("carbonchat.channellist")
.handler(this::channelListSelf)
.build()
);
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // console & player
.permission("carbonchat.channellist.others")
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name())) // carbonchat.channellist.other
.handler(this::channelListOther)
.build()
);
}
public void channelListSelf(final @NonNull CommandContext<CarbonUser> context) {
this.listAndSend(context.getSender(), (PlayerUser) context.getSender(), this.carbonChat.channelRegistry().iterator());
}
public void channelListOther(final @NonNull CommandContext<CarbonUser> context) {
final CarbonUser sender = context.getSender();
final PlayerUser user = context.get("user");
if (!user.online()) {
final String mustBeOnline = this.carbonChat.translations().userMustBeOnline();
sender.sendMessage(Identity.nil(), this.carbonChat.messageProcessor()
.processMessage(mustBeOnline, "player", user.name()));
return;
}
final Iterator<ChatChannel> allChannels = this.carbonChat.channelRegistry().iterator();
this.listAndSend(sender, user, allChannels);
}
private void listAndSend(final @NonNull CarbonUser sender, final @NonNull PlayerUser user,
final @NonNull Iterator<ChatChannel> allChannels) {
ChatChannel channel;
final List<ChatChannel> canSee = new ArrayList<>();
final List<ChatChannel> cannotSee = new ArrayList<>();
while (allChannels.hasNext()) {
channel = allChannels.next();
if (channel.canPlayerSee(user, true)) {
canSee.add(channel);
} else {
cannotSee.add(channel);
}
}
final Iterator<ChatChannel> visibleChannels = canSee.iterator();
final TextComponent.Builder availableList = Component.text();
this.makeList(visibleChannels, availableList);
final String availableFormat = this.carbonChat.translations().availableChannelsList();
Component availableComponent = this.carbonChat.messageProcessor().processMessage(availableFormat, "br", "\n");
availableComponent = availableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), ac -> availableList);
sender.sendMessage(Identity.nil(), availableComponent);
if (sender.hasPermission("carbonchat.channellist.bypass") && !cannotSee.isEmpty()) {
final Iterator<ChatChannel> invisibleChannels = cannotSee.iterator();
final TextComponent.Builder unavailableList = Component.text();
this.makeList(invisibleChannels, unavailableList);
final String unavailableFormat = this.carbonChat.translations().unavailableChannelsList();
Component unavailableComponent = this.carbonChat.messageProcessor().processMessage(unavailableFormat, "br", "\n");
unavailableComponent = unavailableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), uac -> unavailableList);
sender.sendMessage(Identity.nil(), unavailableComponent);
}
}
private void makeList(final @NonNull Iterator<@NonNull ChatChannel> iterator, final TextComponent.@NonNull Builder list) {
final String listSeparator = this.carbonChat.translations().channelListSeparator();
final Component listSeparatorComponent = Component.text(listSeparator);
while (iterator.hasNext()) {
list.append(Component.text(iterator.next().name()));
if (iterator.hasNext()) {
list.append(listSeparatorComponent);
}
}
}
}
@@ -1,46 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.CarbonUser;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
public class ChatReloadCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public ChatReloadCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("chatreload");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // player & console
.permission("carbonchat.reload")
.handler(this::reloadConfig)
.build()
);
}
private void reloadConfig(final @NonNull CommandContext<CarbonUser> context) {
this.carbonChat.reload();
final Component message = this.carbonChat.messageProcessor()
.processMessage(this.carbonChat.translations().reloaded().replace("br", "\n"));
context.getSender().sendMessage(Identity.nil(), message);
}
}
@@ -1,86 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.common.commands.arguments.PlayerUserArgument;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
public class ClearChatCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public ClearChatCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("clearchat");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // player & console
.permission("carbonchat.clearchat.clear")
.handler(this::clearChat)
.build()
);
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // player & console
.permission("carbonchat.clearchat.clear.player")
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name()))
.handler(this::clearChatPlayer)
.build()
);
}
private void clearChat(final @NonNull CommandContext<CarbonUser> context) {
final String sender = context.getSender().name();
final String format = this.carbonChat.moderationSettings().clearChat().message();
final Component component = this.carbonChat.messageProcessor().processMessage(format, "br", "\n");
for (final CarbonUser user : this.carbonChat.userService().onlineUsers()) {
this.clearUserChat(user, component, sender);
}
}
private void clearChatPlayer(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser target = context.get("user");
final String sender = context.getSender().name();
final String format = this.carbonChat.moderationSettings().clearChat().message();
final Component component = this.carbonChat.messageProcessor().processMessage(format, "br", "\n");
this.clearUserChat(target, component, sender);
}
private void clearUserChat(final @NonNull CarbonUser user, final @NonNull Component component, final @NonNull String sender) {
if (user.hasPermission("carbonchat.clearchat.exempt")) {
final String message = this.carbonChat.translations().clearExempt();
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor()
.processMessage(message, "player", sender));
} else {
for (int i = 0; i < this.carbonChat.moderationSettings().clearChat().messageCount(); i++) {
user.sendMessage(Identity.nil(), component);
}
}
if (user.hasPermission("carbonchat.clearchat.notify")) {
final String message = this.carbonChat.translations().clearNotify();
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor()
.processMessage(message, "player", sender));
}
}
}
@@ -1,66 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.common.commands.arguments.PlayerUserArgument;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
public class IgnoreCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public IgnoreCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("ignore");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.ignore")
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name()))
.handler(this::ignoreUser)
.build()
);
}
private void ignoreUser(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser sender = (PlayerUser) context.getSender();
final PlayerUser targetUser = context.get("user");
if (sender.ignoringUser(targetUser)) {
sender.ignoringUser(targetUser, false);
sender.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(
this.carbonChat.translations().notIgnoringUser(), "player", targetUser.displayName()));
} else {
final String format;
if (targetUser.hasPermission("carbonchat.ignore.exempt")) {
format = this.carbonChat.translations().ignoreExempt();
} else {
sender.ignoringUser(targetUser, true);
format = this.carbonChat.translations().ignoringUser();
}
final Component message = this.carbonChat.messageProcessor().processMessage(format,
"sender", sender.displayName(), "player", targetUser.displayName());
sender.sendMessage(Identity.nil(), message);
}
}
}
@@ -1,65 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.standard.StringArgument;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
public class MeCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public MeCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("me");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.me")
.argument(StringArgument.<CarbonUser>newBuilder("message").greedy().build())
.handler(this::message)
.build()
);
}
private void message(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
final String message = context.<String>get("message").replace("</pre>", "");
String format = this.carbonChat.translations().roleplayFormat();
if (!user.hasPermission("carbonchat.me.formatting")) {
format = format.replace("<message>", "<pre><message></pre>");
}
final Component component = this.carbonChat.messageProcessor().processMessage(format,
"displayname", user.displayName(), "message", message);
if (user.shadowMuted()) {
user.sendMessage(user.identity(), component);
} else {
for (final PlayerUser onlineUser : this.carbonChat.userService().onlineUsers()) {
if (onlineUser.ignoringUser(user)) {
continue;
}
onlineUser.sendMessage(user.identity(), component);
}
}
}
}
@@ -1,105 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.standard.StringArgument;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.api.users.UserChannelSettings;
import net.draycia.carbon.common.channels.CarbonWhisperChannel;
import net.draycia.carbon.common.commands.arguments.PlayerUserArgument;
import net.kyori.adventure.identity.Identity;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Optional;
public class MessageCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public MessageCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CarbonChat carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = carbonChat.commandSettings().get("message");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
if (this.carbonChat.carbonSettings().whisperOptions().useEnhancedWhispers()) {
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.message")
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name()))
.argument(StringArgument.<CarbonUser>newBuilder("message").greedy().asOptional().build())
.handler(this::sendMessage)
.build()
);
} else {
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.message")
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name()))
.argument(StringArgument.<CarbonUser>newBuilder("message").greedy().asRequired().build())
.handler(this::sendMessage)
.build()
);
}
}
private void sendMessage(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser sender = (PlayerUser) context.getSender();
final PlayerUser receiver = context.get("user");
if (sender.equals(receiver)) {
final String message = this.carbonChat.translations().cannotWhisperSelf();
sender.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(message));
return;
}
if (!sender.hasPermission("carbonchat.msgtoggle.bypass")) {
final ChatChannel senderWhisperChannel = new CarbonWhisperChannel(sender, receiver);
final UserChannelSettings senderSettings = sender.channelSettings(senderWhisperChannel);
if (senderSettings.ignored()) {
final String message = this.carbonChat.carbonSettings().whisperOptions().senderToggledOff();
sender.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(message));
return;
}
final ChatChannel receiverWhisperChannel = new CarbonWhisperChannel(receiver, sender);
final UserChannelSettings receiverSettings = sender.channelSettings(receiverWhisperChannel);
if (receiverSettings.ignored()) {
final String message = this.carbonChat.carbonSettings().whisperOptions().receiverToggledOff();
sender.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(message));
return;
}
}
final Optional<String> message = context.getOptional("message");
if (message.isPresent()) {
receiver.sendMessage(sender, message.get());
} else {
sender.selectedChannel(new CarbonWhisperChannel(sender, receiver));
sender.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(
this.carbonChat.carbonSettings().whisperOptions().nowWhisperingPlayer(),
"player", receiver.name()
));
}
}
}
@@ -1,104 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.api.users.UserChannelSettings;
import net.draycia.carbon.common.commands.arguments.PlayerUserArgument;
import net.kyori.adventure.identity.Identity;
import org.checkerframework.checker.nullness.qual.NonNull;
public class MsgToggleCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public MsgToggleCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("msgtoggle");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.msgtoggle")
.handler(this::toggleSelf)
.build()
);
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // console & player
.permission("carbonchat.msgtoggle.others")
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name())) // carbonchat.channellist.other
.handler(this::toggleOther)
.build()
);
}
private void toggleSelf(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
final ChatChannel channel = this.carbonChat.channelRegistry().get("whisper");
if (channel == null) {
throw new IllegalArgumentException("Whisper channel not found!");
}
final String message;
final UserChannelSettings settings = user.channelSettings(channel);
if (!channel.ignorable()) {
message = channel.cannotIgnoreMessage();
} else if (settings.ignored()) {
settings.ignoring(false);
message = channel.toggleOffMessage();
} else {
settings.ignoring(true);
message = channel.toggleOnMessage();
}
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(message));
}
private void toggleOther(final @NonNull CommandContext<CarbonUser> context) {
final CarbonUser sender = context.getSender();
final PlayerUser user = context.get("user");
final ChatChannel channel = this.carbonChat.channelRegistry().get("whisper");
if (channel == null) {
throw new IllegalArgumentException("Whisper channel not found!");
}
final String message;
final String otherMessage;
final UserChannelSettings settings = user.channelSettings(channel);
if (settings.ignored()) {
settings.ignoring(false);
message = channel.toggleOffMessage();
otherMessage = channel.toggleOtherOffMessage();
} else {
settings.ignoring(true);
message = channel.toggleOnMessage();
otherMessage = channel.toggleOtherOnMessage();
}
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(message));
sender.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(otherMessage,
"player", user.name()));
}
}
@@ -1,68 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.common.commands.arguments.PlayerUserArgument;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
public class MuteCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public MuteCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("mute");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // player & console
.permission("carbonchat.mute")
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name()))
.handler(this::mute)
.build()
);
}
private void mute(final @NonNull CommandContext<CarbonUser> context) {
final CarbonUser user = context.getSender();
final PlayerUser target = context.get("user");
if (target.muted()) {
target.muted(false);
final String format = this.carbonChat.translations().noLongerMuted();
final Component message = this.carbonChat.messageProcessor().processMessage(format,
"player", target.name(), "sender", user.name());
user.sendMessage(Identity.nil(), message);
} else {
final String format;
if (target.hasPermission("carbonchat.mute.exempt")) {
format = this.carbonChat.translations().muteExempt();
} else {
target.muted(true);
format = this.carbonChat.translations().nowMuted();
}
final Component message = this.carbonChat.messageProcessor().processMessage(format,
"player", target.name(), "sender", user.name());
user.sendMessage(Identity.nil(), message);
}
}
}
@@ -1,98 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.standard.StringArgument;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.common.commands.arguments.PlayerUserArgument;
import net.kyori.adventure.identity.Identity;
import org.checkerframework.checker.nullness.qual.NonNull;
public class NicknameCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public NicknameCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("nickname");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.nickname")
.argument(StringArgument.of("nickname"))
.handler(this::nicknameSelf)
.build()
);
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // console & player
.permission("carbonchat.nickname.others")
.argument(StringArgument.of("nickname"))
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name())) // carbonchat.channellist.other
.handler(this::nicknameOther)
.build()
);
}
private void nicknameSelf(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
String nickname = context.get("nickname");
if (nickname.equalsIgnoreCase("off") || nickname.equalsIgnoreCase(user.name())) {
nickname = null;
}
user.nickname(nickname);
final String message;
if (nickname == null) {
message = this.carbonChat.translations().nicknameReset();
} else {
message = this.carbonChat.translations().nicknameSet();
}
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(
message, "nickname", nickname == null ? "" : nickname,
"user", user.name(), "sender", context.getSender().name()));
}
private void nicknameOther(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser target = context.get("user");
String nickname = context.get("nickname");
if (nickname.equalsIgnoreCase("off") ||
nickname.equalsIgnoreCase(target.name())) {
nickname = null;
}
target.nickname(nickname);
final String message;
if (nickname == null) {
message = this.carbonChat.translations().otherNicknameReset();
} else {
message = this.carbonChat.translations().otherNicknameSet();
}
context.getSender().sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(
message, "nickname", nickname == null ? "" : nickname,
"user", target.name(), "sender", context.getSender().name()));
}
}
@@ -1,81 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.StaticArgument;
import cloud.commandframework.arguments.standard.EnumArgument;
import cloud.commandframework.arguments.standard.FloatArgument;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.intellij.lang.annotations.Subst;
public class PingOptionsCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public PingOptionsCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("pingoptions");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.pingoptions.channels")
.argument(StaticArgument.of("channels"))
.argument(EnumArgument.of(Sound.Source.class, "sound"))
.argument(FloatArgument.<CarbonUser>newBuilder("volume").withMin(0).withMax(1).asRequired().build())
.argument(FloatArgument.<CarbonUser>newBuilder("pitch").withMin(0).withMax(1).asRequired().build())
.handler(this::channelOptions)
.build()
);
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.pingoptions.whispers")
.argument(StaticArgument.of("whispers"))
.argument(EnumArgument.of(Sound.Source.class, "sound"))
.argument(FloatArgument.<CarbonUser>newBuilder("volume").withMin(0).withMax(1).asRequired().build())
.argument(FloatArgument.<CarbonUser>newBuilder("pitch").withMin(0).withMax(1).asRequired().build())
.handler(this::whisperOptions)
.build()
);
}
@SuppressWarnings("NoLvTypeAnnotations")
private void channelOptions(final @NonNull CommandContext<CarbonUser> context) {
final @Subst("block.bell.resonate") String soundKey = context.get("sound");
((PlayerUser) context.getSender()).pingOptions().pingSound(Sound.sound(Key.key(soundKey),
Sound.Source.PLAYER, context.get("volume"), context.get("pitch")));
context.getSender().sendMessage(this.carbonChat.messageProcessor().processMessage(
this.carbonChat.translations().channelPingChanged()));
}
@SuppressWarnings("NoLvTypeAnnotations")
private void whisperOptions(final @NonNull CommandContext<CarbonUser> context) {
final @Subst("block.bell.resonate") String soundKey = context.get("sound");
((PlayerUser) context.getSender()).pingOptions().whisperSound(Sound.sound(Key.key(soundKey),
Sound.Source.PLAYER, context.get("volume"), context.get("pitch")));
context.getSender().sendMessage(this.carbonChat.messageProcessor().processMessage(
this.carbonChat.translations().whisperPingChanged()));
}
}
@@ -1,73 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.standard.StringArgument;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.UUID;
public class ReplyCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public ReplyCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("reply");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.reply")
.argument(StringArgument.<CarbonUser>newBuilder("message").greedy().build())
.handler(this::reply)
.build()
);
}
private void reply(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
final String input = context.get("message");
if (input.isEmpty()) {
final String message = this.carbonChat.translations().replyMessageBlank();
final Component component = this.carbonChat.messageProcessor().processMessage(message, "br", "\n");
user.sendMessage(Identity.nil(), component);
return;
}
final UUID replyTarget = user.replyTarget();
if (replyTarget == null) {
final String message = this.carbonChat.translations().noReplyTarget();
final Component component = this.carbonChat.messageProcessor().processMessage(message, "br", "\n");
user.sendMessage(Identity.nil(), component);
return;
}
final PlayerUser targetUser = this.carbonChat.userService().wrap(replyTarget);
if (targetUser != null) {
targetUser.sendMessage(user, input);
}
}
}
@@ -1,55 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.StaticArgument;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.api.users.UserChannelSettings;
import net.draycia.carbon.common.utils.TextColorArgument;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.format.TextColor;
import org.checkerframework.checker.nullness.qual.NonNull;
public class SetChannelColorCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public SetChannelColorCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("setchannelcolor");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
for (final ChatChannel channel : this.carbonChat.channelRegistry()) {
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.setchannelcolor." + channel.key())
.argument(StaticArgument.of(channel.key()))
.argument(TextColorArgument.of("color")) // remember to replace this when cloud 1.1.0 releases
.handler(context -> {
final PlayerUser user = (PlayerUser) context.getSender();
final TextColor color = context.get("color");
final UserChannelSettings settings = user.channelSettings(channel);
settings.color(color);
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(
this.carbonChat.translations().channelColorSet(),
"color", "<color:" + color.asHexString() + ">", "channel",
channel.name(), "hex", color.asHexString()));
}).build()
);
}
}
}
@@ -1,68 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.common.commands.arguments.PlayerUserArgument;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
public class ShadowMuteCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public ShadowMuteCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("shadowmute");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // player & console
.permission("carbonchat.shadowmute")
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name()))
.handler(this::shadowMute)
.build()
);
}
private void shadowMute(final @NonNull CommandContext<CarbonUser> context) {
final CarbonUser user = context.getSender();
final PlayerUser target = context.get("user");
if (target.shadowMuted()) {
target.shadowMuted(false);
final String format = this.carbonChat.translations().noLongerShadowMuted();
final Component message = this.carbonChat.messageProcessor().processMessage(format,
"player", target.name());
user.sendMessage(Identity.nil(), message);
} else {
final String format;
if (target.hasPermission("carbonchat.mute.exempt")) {
format = this.carbonChat.translations().shadowMuteExempt();
} else {
target.shadowMuted(true);
format = this.carbonChat.translations().nowShadowMuted();
}
final Component message = this.carbonChat.messageProcessor().processMessage(format,
"player", target.name());
user.sendMessage(Identity.nil(), message);
}
}
}
@@ -1,130 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.StaticArgument;
import cloud.commandframework.arguments.standard.BooleanArgument;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.api.users.UserChannelSettings;
import net.draycia.carbon.common.commands.arguments.ChannelArgument;
import net.kyori.adventure.identity.Identity;
import org.checkerframework.checker.nullness.qual.NonNull;
public class SpyChannelCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public SpyChannelCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("spy");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.spy")
.argument(StaticArgument.of("channel"))
.argument(ChannelArgument.requiredChannelArgument())
.handler(this::spyChannel)
.build()
);
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.spy")
.argument(StaticArgument.of("whispers"))
.handler(this::spyWhispers)
.build()
);
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.spy")
.argument(StaticArgument.of("everything"))
.argument(BooleanArgument.of("enabled"))
.handler(this::spyEverything)
.build()
);
}
private void spyChannel(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
final ChatChannel chatChannel = context.get("channel");
final String message;
final UserChannelSettings settings = user.channelSettings(chatChannel);
if (settings.spying()) {
settings.spying(false);
message = this.carbonChat.translations().spyToggledOff();
} else {
settings.spying(true);
message = this.carbonChat.translations().spyToggledOn();
}
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(message,
"color", "<color:" + chatChannel.channelColor(user).toString() + ">",
"channel", chatChannel.name()));
}
private void spyWhispers(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
final String message;
if (user.spyingWhispers()) {
user.spyingWhispers(false);
message = this.carbonChat.translations().spyWhispersOff();
} else {
user.spyingWhispers(true);
message = this.carbonChat.translations().spyWhispersOn();
}
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(message));
}
private void spyEverything(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
final Boolean shouldSpy = context.get("enabled");
final String message;
if (shouldSpy) {
user.spyingWhispers(true);
for (final ChatChannel channel : this.carbonChat.channelRegistry()) {
user.channelSettings(channel).spying(true);
}
message = this.carbonChat.translations().spyEverythingOff();
} else {
user.spyingWhispers(false);
for (final ChatChannel channel : this.carbonChat.channelRegistry()) {
user.channelSettings(channel).spying(false);
}
message = this.carbonChat.translations().spyEverythingOn();
}
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor()
.processMessage(message, "br", "\n"));
}
}
@@ -1,82 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.standard.StringArgument;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.common.commands.arguments.ChannelArgument;
import net.draycia.carbon.common.commands.arguments.PlayerUserArgument;
import net.kyori.adventure.identity.Identity;
import org.checkerframework.checker.nullness.qual.NonNull;
public class SudoChannelCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public SudoChannelCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("sudochannel");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // console & player
.permission("carbonchat.channel.others")
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name()))
.argument(ChannelArgument.requiredChannelArgument())
.handler(this::otherChannel)
.build()
);
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // console & player
.permission("carbonchat.channel.others.message")
.argument(PlayerUserArgument.requiredPlayerUserArgument(commandSettings.name()))
.argument(ChannelArgument.requiredChannelArgument())
.argument(StringArgument.<CarbonUser>newBuilder("message").greedy().asOptional().build())
.handler(this::sendMessageOther)
.build()
);
}
private void otherChannel(final @NonNull CommandContext<CarbonUser> context) {
final CarbonUser sender = context.getSender();
final PlayerUser user = context.get("user");
final ChatChannel channel = context.get("channel");
user.selectedChannel(channel);
final String message = channel.switchMessage();
final String otherMessage = channel.switchOtherMessage();
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(message,
"color", "<color:" + channel.channelColor(user).toString() + ">",
"channel", channel.name()));
sender.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(otherMessage,
"color", "<color:" + channel.channelColor(user).toString() + ">",
"channel", channel.name(), "player", user.name()));
}
private void sendMessageOther(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = context.get("user");
final ChatChannel channel = context.get("channel");
final String message = context.get("message");
channel.sendComponentsAndLog(user.identity(), channel.parseMessage(user, message));
}
}
@@ -1,104 +0,0 @@
package net.draycia.carbon.common.commands;
import cloud.commandframework.CommandManager;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.commands.settings.CommandSettings;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.api.users.UserChannelSettings;
import net.draycia.carbon.common.commands.arguments.ChannelArgument;
import net.draycia.carbon.common.commands.arguments.PlayerUserArgument;
import net.kyori.adventure.identity.Identity;
import org.checkerframework.checker.nullness.qual.NonNull;
public class ToggleCommand {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("methodref.receiver.bound.invalid")
public ToggleCommand(final @NonNull CommandManager<CarbonUser> commandManager) {
this.carbonChat = CarbonChatProvider.carbonChat();
final CommandSettings commandSettings = this.carbonChat.commandSettings().get("toggle");
if (commandSettings == null || !commandSettings.enabled()) {
return;
}
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(PlayerUser.class) // player
.permission("carbonchat.toggle")
.argument(ChannelArgument.requiredChannelArgument())
.handler(this::toggleSelf)
.build()
);
commandManager.command(
commandManager.commandBuilder(commandSettings.name(), commandSettings.aliases(),
commandManager.createDefaultCommandMeta())
.senderType(CarbonUser.class) // console & player
.permission("carbonchat.toggle.others")
.argument(ChannelArgument.requiredChannelArgument())
.argument(PlayerUserArgument.optionalPlayerUserArgument(commandSettings.name())) // carbonchat.toggle.other
.handler(this::toggleOther)
.build()
);
}
private void toggleSelf(final @NonNull CommandContext<CarbonUser> context) {
final PlayerUser user = (PlayerUser) context.getSender();
final ChatChannel channel = context.get("channel");
final String message;
final UserChannelSettings settings = user.channelSettings(channel);
if (!channel.ignorable()) {
message = channel.cannotIgnoreMessage();
} else if (settings.ignored()) {
settings.ignoring(false);
message = channel.toggleOffMessage();
} else {
settings.ignoring(true);
message = channel.toggleOnMessage();
}
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(message,
"color", "<color:" + channel.channelColor(user).toString() + ">",
"channel", channel.name()));
}
private void toggleOther(final @NonNull CommandContext<CarbonUser> context) {
final CarbonUser sender = context.getSender();
final PlayerUser user = context.get("user");
final ChatChannel channel = context.get("channel");
final String message;
final String otherMessage;
final UserChannelSettings settings = user.channelSettings(channel);
if (settings.ignored()) {
settings.ignoring(false);
message = channel.toggleOffMessage();
otherMessage = channel.toggleOtherOffMessage();
} else {
settings.ignoring(true);
message = channel.toggleOnMessage();
otherMessage = channel.toggleOtherOnMessage();
}
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(message,
"color", "<color:" + channel.channelColor(user).toString() + ">",
"channel", channel.name()));
sender.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(otherMessage,
"color", "<color:" + channel.channelColor(user).toString() + ">",
"channel", channel.name(), "player", user.name()));
}
}
@@ -1,60 +0,0 @@
package net.draycia.carbon.common.commands.arguments;
import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.arguments.parser.ArgumentParseResult;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.config.ExceptionMessages;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
public final class ChannelArgument<C> extends CommandArgument<C, TextChannel> {
private ChannelArgument(final boolean required) {
super(required, "channel", ChannelArgument::parser,
CarbonChatProvider.carbonChat().channelRegistry().defaultValue().key(),
TextChannel.class, ChannelArgument::suggestions);
}
private static <C> ArgumentParseResult<TextChannel> parser(final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<String> inputs) {
final String input = inputs.poll();
final ExceptionMessages exceptions = CarbonChatProvider.carbonChat().translations().exceptionMessages();
if (input == null) {
return ArgumentParseResult.failure(new IllegalArgumentException(exceptions.channelNotFound()));
}
final ChatChannel channel = CarbonChatProvider.carbonChat()
.channelRegistry().get(input);
if (channel instanceof TextChannel) {
return ArgumentParseResult.success((TextChannel) channel);
} else if (channel != null) {
return ArgumentParseResult.failure(new IllegalArgumentException(exceptions.channelNotPublic()));
} else {
return ArgumentParseResult.failure(new IllegalArgumentException(exceptions.channelNotFound()));
}
}
private static <C> List<String> suggestions(final @NonNull CommandContext<C> commandContext,
final @NonNull String input) {
return CarbonChatProvider.carbonChat().channelRegistry().stream()
.map(ChatChannel::key).collect(Collectors.toList());
}
public static <C> ChannelArgument<C> requiredChannelArgument() {
return new ChannelArgument<>(true);
}
public static <C> ChannelArgument<C> optionalChannelArgument() {
return new ChannelArgument<>(false);
}
}
@@ -1,59 +0,0 @@
package net.draycia.carbon.common.commands.arguments;
import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.arguments.parser.ArgumentParseResult;
import cloud.commandframework.context.CommandContext;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.UUID;
import java.util.stream.Collectors;
public final class PlayerUserArgument<C extends CarbonUser> extends CommandArgument<C, PlayerUser> {
private PlayerUserArgument(final @NonNull String command, final boolean required) {
super(required, "user", PlayerUserArgument::parser,
"",
PlayerUser.class, (context, input) -> {
final List<String> suggestions = CarbonChatProvider.carbonChat().userService().onlineUsers().stream()
.map(PlayerUser::name).collect(Collectors.toCollection(ArrayList::new));
if (context.getSender().hasPermission("carbonchat.command.completions." + command)) {
suggestions.addAll(CarbonChatProvider.carbonChat().userService().proxyPlayers());
}
return suggestions;
});
}
private static <C extends CarbonUser> @NonNull ArgumentParseResult<PlayerUser> parser(final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<String> inputs) {
final String input = inputs.poll();
if (input == null) {
final String playerNotFound = CarbonChatProvider.carbonChat().translations().exceptionMessages()
.playerNotFound();
return ArgumentParseResult.failure(new IllegalArgumentException(playerNotFound));
}
final UUID uuid = CarbonChatProvider.carbonChat().resolveUUID(input);
final PlayerUser user = CarbonChatProvider.carbonChat().userService().wrap(uuid);
return ArgumentParseResult.success(user);
}
public static <C extends CarbonUser> PlayerUserArgument<C> requiredPlayerUserArgument(final @NonNull String command) {
return new PlayerUserArgument<>(command, true);
}
public static <C extends CarbonUser> PlayerUserArgument<C> optionalPlayerUserArgument(final @NonNull String command) {
return new PlayerUserArgument<>(command, false);
}
}
@@ -1,58 +0,0 @@
package net.draycia.carbon.common.commands.misc;
import cloud.commandframework.CommandManager;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.common.commands.AliasedChannelCommand;
import net.draycia.carbon.common.commands.ChannelCommand;
import net.draycia.carbon.common.commands.ChannelListCommand;
import net.draycia.carbon.common.commands.ChatReloadCommand;
import net.draycia.carbon.common.commands.ClearChatCommand;
import net.draycia.carbon.common.commands.IgnoreCommand;
import net.draycia.carbon.common.commands.MeCommand;
import net.draycia.carbon.common.commands.MessageCommand;
import net.draycia.carbon.common.commands.MuteCommand;
import net.draycia.carbon.common.commands.NicknameCommand;
import net.draycia.carbon.common.commands.PingOptionsCommand;
import net.draycia.carbon.common.commands.ReplyCommand;
import net.draycia.carbon.common.commands.SetChannelColorCommand;
import net.draycia.carbon.common.commands.SpyChannelCommand;
import net.draycia.carbon.common.commands.SudoChannelCommand;
import net.draycia.carbon.common.commands.ToggleCommand;
import net.draycia.carbon.common.commands.ShadowMuteCommand;
import org.checkerframework.checker.nullness.qual.NonNull;
public final class CommandRegistrar {
private CommandRegistrar() {
}
public static void registerCommands(final @NonNull CommandManager<CarbonUser> commandManager) {
new ChannelCommand(commandManager);
new ChannelListCommand(commandManager);
new ChatReloadCommand(commandManager);
new ClearChatCommand(commandManager);
new IgnoreCommand(commandManager);
new MeCommand(commandManager);
new MessageCommand(commandManager);
new MuteCommand(commandManager);
new NicknameCommand(commandManager);
new PingOptionsCommand(commandManager);
new ReplyCommand(commandManager);
new SetChannelColorCommand(commandManager);
new ShadowMuteCommand(commandManager);
new SpyChannelCommand(commandManager);
new SudoChannelCommand(commandManager);
new ToggleCommand(commandManager);
for (final ChatChannel channel : CarbonChatProvider.carbonChat().channelRegistry()) {
if (channel instanceof TextChannel) {
new AliasedChannelCommand(commandManager, (TextChannel) channel);
}
}
}
}
@@ -1,88 +0,0 @@
package net.draycia.carbon.common.config;
import net.draycia.carbon.api.CarbonChatProvider;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.hocon.HoconConfigurationLoader;
import org.spongepowered.configurate.loader.AbstractConfigurationLoader;
import org.spongepowered.configurate.yaml.NodeStyle;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
public class ConfigLoader<L extends AbstractConfigurationLoader<CommentedConfigurationNode>> {
private final @NonNull Class<L> format;
public ConfigLoader(final @NonNull Class<L> format) {
this.format = format;
}
public <B extends AbstractConfigurationLoader.Builder<?, L>> CommentedConfigurationNode loadConfig(final @NonNull String file) throws ConfigurateException {
final B builder;
if (this.format == HoconConfigurationLoader.class) {
builder = (B) HoconConfigurationLoader.builder().prettyPrinting(true);
} else {
builder = (B) YamlConfigurationLoader.builder().nodeStyle(NodeStyle.BLOCK);
}
final File config = this.findAndCopyFile(this.fileInDataDir(file));
final L loader = this.loadConfigFile(builder, config);
final CommentedConfigurationNode node = loader.load();
if (!config.exists()) {
loader.save(node);
}
return node;
}
private @NonNull File fileInDataDir(final @NonNull String file) {
return new File(CarbonChatProvider.carbonChat().dataFolder().toFile(), file);
}
private <B extends AbstractConfigurationLoader.Builder<?, L>> L loadConfigFile(final B builder, final @NonNull File config) {
return builder
.defaultOptions(opts -> {
return opts.shouldCopyDefaults(true).serializers(serializerBuilder -> {
serializerBuilder.register(Key.class, KeySerializer.INSTANCE)
.register(Sound.class, SoundSerializer.INSTANCE);
});
})
.file(config)
.build();
}
private @NonNull File findAndCopyFile(final @NonNull File file) {
if (file.exists()) {
return file;
}
final String resource = "/" + file.getName();
final InputStream inputStream = this.getClass().getResourceAsStream(resource);
if (inputStream == null) {
return file;
}
return this.copyFileToDataDir(inputStream, file);
}
public @NonNull File copyFileToDataDir(final @NonNull InputStream source, final @NonNull File file) {
try {
Files.copy(source, file.toPath());
} catch (final IOException ex) {
ex.printStackTrace();
}
return file;
}
}
@@ -1,57 +0,0 @@
/*
* This file is part of adventure, licensed under the MIT License.
*
* Copyright (c) 2017-2020 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.draycia.carbon.common.config;
import java.lang.reflect.Type;
import java.util.function.Predicate;
import net.kyori.adventure.key.InvalidKeyException;
import net.kyori.adventure.key.Key;
import org.spongepowered.configurate.serialize.ScalarSerializer;
import org.spongepowered.configurate.serialize.SerializationException;
public final class KeySerializer extends ScalarSerializer<Key> {
public static final KeySerializer INSTANCE = new KeySerializer();
private KeySerializer() {
super(Key.class);
}
@Override
public Key deserialize(final Type type, final Object obj) throws SerializationException {
if (!(obj instanceof CharSequence)) {
throw new SerializationException("Invalid type presented to serializer: " + type);
}
try {
return Key.key(obj.toString());
} catch(final InvalidKeyException ex) {
throw new SerializationException(ex);
}
}
@Override
public Object serialize(final Key item, final Predicate<Class<?>> typeSupported) {
return item.asString();
}
}
@@ -1,82 +0,0 @@
/*
* This file is part of adventure, licensed under the MIT License.
*
* Copyright (c) 2017-2020 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.draycia.carbon.common.config;
import com.google.common.reflect.TypeToken;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import java.lang.reflect.Type;
public final class SoundSerializer implements TypeSerializer<Sound> {
static final Type TYPE = TypeToken.of(Sound.class).getType();
static final Type SOURCE_TYPE = TypeToken.of(Sound.Source.class).getType();
public static final SoundSerializer INSTANCE = new SoundSerializer();
static final String NAME = "name";
static final String SOURCE = "source";
static final String PITCH = "pitch";
static final String VOLUME = "volume";
private SoundSerializer() {
}
@Override
public @NonNull Sound deserialize(final @NonNull Type type, final @NonNull ConfigurationNode value) throws SerializationException {
if (value.empty()) {
throw new SerializationException("Value not found for sound!");
}
final Key name = value.node(NAME).get(KeySerializer.INSTANCE.type());
final Sound.Source source = (Sound.Source) value.node(SOURCE).get(SOURCE_TYPE); // unsure about this
final float volume = value.node(VOLUME).getFloat(1.0f);
final float pitch = value.node(PITCH).getFloat(1.0f);
if (name == null || source == null) {
throw new SerializationException("A name and source are required to deserialize a Sound");
}
return Sound.sound(name, source, volume, pitch);
}
@Override
public void serialize(final @NonNull Type type, final @Nullable Sound obj, final @NonNull ConfigurationNode value) throws SerializationException {
if (obj == null) {
value.set(null);
return;
}
value.node(NAME).set(KeySerializer.INSTANCE.type(), obj.name());
value.node(SOURCE).set(SOURCE_TYPE, obj.source());
value.node(VOLUME).set(obj.volume());
value.node(PITCH).set(obj.pitch());
}
}
@@ -1,45 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.PreChatFormatEvent;
import net.kyori.event.PostOrders;
public class CapsHandler {
public CapsHandler() {
final CarbonChat carbonChat = CarbonChatProvider.carbonChat();
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
if (!carbonChat.moderationSettings().capsProtection().enabled()) {
return;
}
if (!(event.message().length() >= carbonChat.moderationSettings().capsProtection().minimumLength())) {
return;
}
int amountOfCaps = 0;
for (final char letter : event.message().toCharArray()) {
if (Character.isUpperCase(letter)) {
amountOfCaps++;
}
}
final double capsPercentage = (amountOfCaps * 100.0) / event.message().length();
if (!(capsPercentage >= carbonChat.moderationSettings().capsProtection().percentCaps())) {
return;
}
if (carbonChat.moderationSettings().capsProtection().blockMessage()) {
event.cancelled(true);
} else {
event.message(event.message().toLowerCase());
}
});
}
}
@@ -1,23 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.PreChatFormatEvent;
import net.kyori.event.PostOrders;
import java.util.Map;
public class CustomPlaceholderHandler {
public CustomPlaceholderHandler() {
final CarbonChat carbonChat = CarbonChatProvider.carbonChat();
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
for (final Map.Entry<String, String> entry : carbonChat.channelSettings().customPlaceholders().entrySet()) {
event.format(event.format().replace("<" + entry.getKey() + ">", entry.getValue()));
}
});
}
}
@@ -1,25 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.ChatFormatEvent;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.PostOrders;
public class IgnoredPlayerHandler {
public IgnoredPlayerHandler() {
CarbonEvents.register(ChatFormatEvent.class, PostOrders.FIRST, false, event -> {
final CarbonUser target = event.target();
if (!(target instanceof PlayerUser)) {
return;
}
if (((PlayerUser) target).ignoringUser(event.sender())) {
event.cancelled(true);
}
});
}
}
@@ -1,16 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.events.PreChatFormatEvent;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.common.utils.ColorUtils;
import net.kyori.event.PostOrders;
public class LegacyFormatHandler {
public LegacyFormatHandler() {
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
event.format(ColorUtils.translateAlternateColors(event.format()));
});
}
}
@@ -1,23 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.PrivateMessageEvent;
import net.draycia.carbon.api.events.PreChatFormatEvent;
public class MuteHandler {
public MuteHandler() {
CarbonEvents.register(PrivateMessageEvent.class, event -> {
if (event.sender().muted()) {
event.cancelled(true);
}
});
CarbonEvents.register(PreChatFormatEvent.class, event -> {
if (event.user().muted()) {
event.cancelled(true);
}
});
}
}
@@ -1,104 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.events.ChatComponentEvent;
import net.draycia.carbon.api.events.ChatFormatEvent;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.sound.Sound;
import net.kyori.event.PostOrders;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PingHandler {
@SuppressWarnings("method.invocation.invalid")
public PingHandler() {
final CarbonChat carbonChat = CarbonChatProvider.carbonChat();
CarbonEvents.register(ChatComponentEvent.class, PostOrders.LAST, false, event -> {
if (!carbonChat.carbonSettings().channelPings().enabled()) {
return;
}
final CarbonUser target = event.target();
if (!(target instanceof PlayerUser)) {
return;
}
final String targetName = target.name();
final String prefix = carbonChat.carbonSettings().channelPings().prefix();
final boolean caseSensitive = carbonChat.carbonSettings().channelPings().caseSensitive();
final String ping = prefix + targetName;
if (caseSensitive) {
if (!event.originalMessage().contains(ping)) {
return;
}
} else {
if (!event.originalMessage().toLowerCase().contains(ping.toLowerCase())) {
return;
}
}
final Sound sound = ((PlayerUser) target).pingOptions().pingSound();
if (sound != null) {
target.playSound(sound);
} else {
target.playSound(carbonChat.carbonSettings().channelPings().sound());
}
});
CarbonEvents.register(ChatFormatEvent.class, PostOrders.LAST, false, event -> {
if (!carbonChat.carbonSettings().channelPings().enabled()) {
return;
}
final CarbonUser target = event.target();
if (!(target instanceof PlayerUser)) {
return;
}
final String targetName = target.name();
final String prefix = carbonChat.carbonSettings().channelPings().prefix();
final boolean caseSensitive = carbonChat.carbonSettings().channelPings().caseSensitive();
final String ping = prefix + targetName;
if (caseSensitive) {
if (!event.message().contains(ping)) {
return;
}
event.message(event.message().replace(ping,
carbonChat.carbonSettings().channelPings().display()
.replace("<ping>", ping)
.replace("<name>", targetName)
));
} else {
if (!event.message().toLowerCase().contains(ping.toLowerCase())) {
return;
}
event.message(this.replace(event.message(), ping,
carbonChat.carbonSettings().channelPings().display()
.replace("<ping>", ping)
.replace("<name>", targetName)
));
}
});
}
private String replace(final @NonNull String input, final @NonNull CharSequence target,
final @NonNull CharSequence replacement) {
return Pattern.compile("(?i)" + Pattern.quote(target.toString())).matcher(input)
.replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
}
@@ -1,47 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.UserEvent;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.users.PlayerUser;
public class PlayerJoinListener {
public PlayerJoinListener() {
final CarbonChat carbonChat = CarbonChatProvider.carbonChat();
CarbonEvents.register(UserEvent.Join.class, event -> {
final PlayerUser user = event.user();
carbonChat.userService().validate(user);
if (user.nickname() != null) {
user.nickname(user.nickname());
}
final String channel = carbonChat.carbonSettings().channelOnJoin();
if (channel == null || channel.isEmpty()) {
return;
}
if (channel.equals("DEFAULT")) {
user.selectedChannel(carbonChat.channelRegistry().defaultValue());
return;
}
final ChatChannel chatChannel = carbonChat.channelRegistry().get(channel);
if (chatChannel != null) {
user.selectedChannel(chatChannel);
}
});
CarbonEvents.register(UserEvent.Leave.class, event -> {
carbonChat.userService().invalidate(event.user());
});
}
}
@@ -1,36 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.ChatComponentEvent;
import net.draycia.carbon.api.events.ChatFormatEvent;
import net.kyori.event.PostOrders;
public class ShadowMuteHandler {
public ShadowMuteHandler() {
final CarbonChat carbonChat = CarbonChatProvider.carbonChat();
CarbonEvents.register(ChatComponentEvent.class, PostOrders.FIRST, false, event -> {
if (event.sender().shadowMuted() && event.sender().equals(event.target())) {
event.cancelled(true);
}
});
CarbonEvents.register(ChatFormatEvent.class, PostOrders.FIRST, false, event -> {
if (event.target() != null) {
return;
}
if (!event.sender().shadowMuted()) {
return;
}
final String prefix = carbonChat.moderationSettings().shadowMutePrefix();
event.format(prefix + event.format());
});
}
}
@@ -1,22 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.events.ChatFormatEvent;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.kyori.event.PostOrders;
import java.util.regex.Pattern;
public class UrlLinkHandler {
private static final Pattern URL_PATTERN = Pattern.compile("((?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?)");
public UrlLinkHandler() {
CarbonEvents.register(ChatFormatEvent.class, PostOrders.NORMAL, true, event -> {
if (event.sender().hasPermission("carbonchat.autourl")) {
event.message(URL_PATTERN.matcher(event.message()).replaceAll("<click:open_url:'$1'>$1</click>"));
// Reminder: Do not use this on event.format(), this breaks hover events when they contain URLs
}
});
}
}
@@ -1,25 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.PreChatFormatEvent;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.event.PostOrders;
public class UserFormattingHandler {
@SuppressWarnings("method.invocation.invalid")
public UserFormattingHandler() {
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
if (!event.user().hasPermission("carbonchat.formatting") &&
!event.user().hasPermission("carbonchat.channels." + event.channel().key() + ".formatting")) {
this.suppressFormatting(event);
}
// TODO: convert ALL color code formats
});
}
private void suppressFormatting(final PreChatFormatEvent event) {
event.message(MiniMessage.get().escapeTokens(event.message()));
}
}
@@ -1,36 +0,0 @@
package net.draycia.carbon.common.listeners.events;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.PrivateMessageEvent;
import net.kyori.adventure.sound.Sound;
import net.kyori.event.PostOrders;
public class WhisperPingHandler {
public WhisperPingHandler() {
final CarbonChat carbonChat = CarbonChatProvider.carbonChat();
CarbonEvents.register(PrivateMessageEvent.class, PostOrders.LAST, false, event -> {
if (event.sender().uuid().equals(event.target().uuid())) {
return;
}
if (!event.message().contains(event.sender().name())) {
return;
}
if (carbonChat.carbonSettings().whisperOptions().pings().enabled()) {
final Sound sound = event.target().pingOptions().whisperSound();
if (sound != null) {
event.target().playSound(sound);
} else {
event.target().playSound(carbonChat.carbonSettings().whisperOptions().pings().sound());
}
}
});
}
}
@@ -1,35 +0,0 @@
package net.draycia.carbon.common.messaging;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import net.draycia.carbon.api.messaging.MessageService;
import net.draycia.carbon.api.users.PlayerUser;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
public class EmptyMessageService implements MessageService {
@Override
public void registerUserMessageListener(final @NonNull String key, final @NonNull BiConsumer<@NonNull PlayerUser, @NonNull ByteArrayDataInput> listener) {
// do nothing
}
@Override
public void registerUUIDMessageListener(final @NonNull String key, final @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
// do nothing
}
@Override
public void unregisterMessageListener(final @NonNull String key) {
// do nothing
}
@Override
public void sendMessage(final @NonNull String key, final @NonNull UUID uuid, final @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer) {
// do nothing
}
}
@@ -1,81 +0,0 @@
package net.draycia.carbon.common.messaging;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.messaging.MessageService;
import com.google.common.io.ByteArrayDataOutput;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.UUID;
import java.util.function.Consumer;
public class MessageManager {
private final @NonNull CarbonChat carbonChat;
private final @NonNull MessageService messageService;
@SuppressWarnings("method.invocation.invalid")
public MessageManager(final @NonNull CarbonChat carbonChat, final @NonNull MessageService messageService) {
this.carbonChat = carbonChat;
this.messageService = messageService;
this.registerDefaultListeners();
}
private void registerDefaultListeners() {
this.messageService().registerUUIDMessageListener("channel-component", (uuid, byteArray) -> {
final ChatChannel channel = this.carbonChat.channelRegistry().get(byteArray.readUTF());
final PlayerUser user = this.carbonChat.userService().wrap(uuid);
if (user != null && channel instanceof TextChannel) {
final Component component = this.carbonChat.gsonSerializer().deserialize(byteArray.readUTF());
((TextChannel) channel).sendComponent(user, component);
this.carbonChat.messageProcessor().audiences().console().sendMessage(Identity.identity(uuid), component);
}
});
this.messageService().registerUUIDMessageListener("whisper-component", (uuid, byteArray) -> {
final UUID recipient = new UUID(byteArray.readLong(), byteArray.readLong());
final PlayerUser sender = this.carbonChat.userService().wrap(uuid);
final PlayerUser target = this.carbonChat.userService().wrap(recipient);
final String message = byteArray.readUTF();
if (!target.ignoringUser(uuid)) {
target.replyTarget(uuid);
target.sendMessage(Identity.identity(uuid), this.carbonChat.gsonSerializer().deserialize(message));
}
for (final PlayerUser user : this.carbonChat.userService().onlineUsers()) {
if (!user.spyingWhispers()) {
continue;
}
if (user.equals(target) || user.uuid().equals(uuid)) {
continue;
}
user.sendMessage(sender, this.carbonChat.messageProcessor()
.processMessage(this.carbonChat.translations().spyWhispers(), "message", message,
"target", target.displayName(), "sender", sender.displayName()));
}
});
}
public @NonNull MessageService messageService() {
return this.messageService;
}
public void sendMessage(final @NonNull String key, final @NonNull UUID uuid,
final @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer) {
this.messageService().sendMessage(key, uuid, consumer);
}
}
@@ -1,32 +0,0 @@
package net.draycia.carbon.common.messaging;
import io.lettuce.core.pubsub.RedisPubSubListener;
import org.checkerframework.checker.nullness.qual.NonNull;
@FunctionalInterface
public interface RedisListener extends RedisPubSubListener<String, String> {
@Override
void message(@NonNull String channel, @NonNull String message);
@Override
default void message(final @NonNull String pattern, final @NonNull String channel, final @NonNull String message) {
}
@Override
default void subscribed(final @NonNull String channel, final long count) {
}
@Override
default void psubscribed(final @NonNull String pattern, final long count) {
}
@Override
default void unsubscribed(final @NonNull String channel, final long count) {
}
@Override
default void punsubscribed(final @NonNull String pattern, final long count) {
}
}
@@ -1,146 +0,0 @@
package net.draycia.carbon.common.messaging;
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.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisStringCommands;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.pubsub.api.sync.RedisPubSubCommands;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.messaging.MessageService;
import net.draycia.carbon.api.config.RedisCredentials;
import net.draycia.carbon.api.users.PlayerUser;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
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 final @NonNull Map<@NonNull String, @NonNull BiConsumer<@NonNull PlayerUser, @NonNull ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
private final @NonNull Map<@NonNull String, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
private final @NonNull RedisPubSubCommands<@NonNull String, @NonNull String> subscribeSync;
private final @NonNull RedisPubSubCommands<@NonNull String, @NonNull String> publishSync;
private final @NonNull RedisStringCommands<@NonNull String, @NonNull String> getSetSync;
private final @NonNull UUID serverUUID = UUID.randomUUID();
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("method.invocation.invalid")
public RedisMessageService(final @NonNull CarbonChat carbonChat, final @NonNull RedisCredentials credentials) {
this.carbonChat = carbonChat;
final RedisURI.Builder builder = RedisURI.Builder.redis(credentials.host(), credentials.port());
final Integer database = credentials.database();
if (database != null) {
builder.withDatabase(database);
}
final String password = credentials.password();
if (password != null) {
builder.withPassword(password.toCharArray());
}
final RedisClient client = RedisClient.create(builder.build());
final StatefulRedisPubSubConnection<String, String> subscribeConnection = client.connectPubSub();
this.subscribeSync = subscribeConnection.sync();
final StatefulRedisPubSubConnection<String, String> publishConnection = client.connectPubSub();
this.publishSync = publishConnection.sync();
final StatefulRedisConnection<String, String> getSetConnection = client.connect();
this.getSetSync = getSetConnection.sync();
subscribeConnection.addListener((RedisListener) (channel, message) -> {
final ByteArrayDataInput input = ByteStreams.newDataInput(Base64.getDecoder().decode(message));
final UUID messageUUID = new UUID(input.readLong(), input.readLong());
if (messageUUID.equals(this.serverUUID)) {
return;
}
final UUID uuid = new UUID(input.readLong(), input.readLong());
this.receiveMessage(uuid, channel, input);
});
}
private void receiveMessage(final @NonNull UUID uuid, final @NonNull String key, final @NonNull ByteArrayDataInput value) {
final PlayerUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
if (user != null) {
for (final Map.Entry<String, BiConsumer<PlayerUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value);
}
}
}
for (final Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : this.userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value);
}
}
}
@Override
public void registerUserMessageListener(final @NonNull String key, final @NonNull BiConsumer<@NonNull PlayerUser, @NonNull ByteArrayDataInput> listener) {
this.userLoadedListeners.put(key, listener);
this.subscribeSync.subscribe(key);
}
@Override
public void registerUUIDMessageListener(final @NonNull String key, final @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
this.userNotLoadedListeners.put(key, listener);
this.subscribeSync.subscribe(key);
}
@Override
public void unregisterMessageListener(final @NonNull String key) {
this.userLoadedListeners.remove(key);
this.userNotLoadedListeners.remove(key);
this.subscribeSync.unsubscribe(key);
}
public @Nullable String get(final @NonNull String key) {
return this.getSetSync.get(key);
}
public void set(final @NonNull String key, final @NonNull String value) {
this.getSetSync.set(key, value);
}
@Override
public void sendMessage(final @NonNull String key, final @NonNull UUID uuid, final @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer) {
final ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeLong(this.serverUUID.getMostSignificantBits());
msg.writeLong(this.serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits());
msg.writeLong(uuid.getLeastSignificantBits());
consumer.accept(msg);
this.publishSync.publish(key, Base64.getEncoder().encodeToString(msg.toByteArray()));
}
}
@@ -1,176 +0,0 @@
package net.draycia.carbon.common.users;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalNotification;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.ConsoleUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.api.users.UserService;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.function.Supplier;
public class JSONUserService<T extends PlayerUser, C extends ConsoleUser> implements UserService<T> {
private final @NonNull CarbonChat carbonChat;
private final @NonNull Gson gson = new GsonBuilder().setPrettyPrinting().create();
private final @NonNull Type userType;
private final @NonNull Supplier<@NonNull Collection<@NonNull T>> supplier;
private final @NonNull Supplier<@NonNull Collection<@NonNull String>> nameSupplier;
private final @NonNull Function<UUID, T> userFactory;
private final @NonNull Supplier<C> consoleFactory;
@SuppressWarnings("methodref.receiver.bound.invalid")
private final @NonNull LoadingCache<@NonNull UUID, @NonNull T> userCache = CacheBuilder.newBuilder()
.removalListener(this::saveUser)
.build(CacheLoader.from(this::loadUser));
public JSONUserService(final @NonNull Class<? extends CarbonUser> userType,
final @NonNull CarbonChat carbonChat,
final @NonNull Supplier<@NonNull Collection<@NonNull T>> supplier,
final @NonNull Supplier<@NonNull Collection<@NonNull String>> nameSupplier,
final @NonNull Function<UUID, T> userFactory,
final @NonNull Supplier<C> consoleFactory) {
this.userType = userType;
this.carbonChat = carbonChat;
this.supplier = supplier;
this.nameSupplier = nameSupplier;
this.userFactory = userFactory;
this.consoleFactory = consoleFactory;
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
JSONUserService.this.userCache.cleanUp();
}
};
new Timer().schedule(timerTask, 300000L, 300000L);
}
@Override
public void onDisable() {
this.userCache.invalidateAll();
this.userCache.cleanUp();
}
@Override
public @NonNull T wrap(final @NonNull UUID uuid) {
try {
return this.userCache.get(uuid);
} catch (final ExecutionException exception) {
throw new IllegalStateException(exception);
}
}
@Override
public @NonNull CompletableFuture<T> wrapLater(final @NonNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> this.wrap(uuid));
}
@Override
public @Nullable C consoleUser() {
return this.consoleFactory.get();
}
@Override
public @Nullable T wrapIfLoaded(final @NonNull UUID uuid) {
return this.userCache.getIfPresent(uuid);
}
@Override
public @Nullable T refreshUser(final @NonNull UUID uuid) {
this.userCache.invalidate(uuid);
return this.wrap(uuid);
}
@Override
public void invalidate(final @NonNull T user) {
this.userCache.invalidate(user.uuid());
}
@Override
public void validate(final @NonNull T user) {
this.userCache.put(user.uuid(), user);
}
@Override
public @NonNull Collection<@NonNull T> onlineUsers() {
return this.supplier.get();
}
@Override
public @NonNull Collection<@NonNull String> proxyPlayers() {
return this.nameSupplier.get();
}
private @NonNull T loadUser(final @NonNull UUID uuid) {
final File userFile = new File(this.carbonChat.dataFolder().toFile(), "users/" + uuid.toString() + ".json");
this.ensureFileExists(userFile);
try (final JsonReader reader = this.gson.newJsonReader(new FileReader(userFile))) {
final T user = this.gson.fromJson(reader, this.userType);
if (user != null) {
return user;
}
} catch (final IOException exception) {
exception.printStackTrace();
}
return this.userFactory.apply(uuid);
}
private void saveUser(final @NonNull RemovalNotification<@NonNull UUID, @NonNull T> notification) {
final File userFile = new File(this.carbonChat.dataFolder().toFile(), "users/" + notification.getKey().toString() + ".json");
this.ensureFileExists(userFile);
try (final JsonWriter writer = this.gson.newJsonWriter(new FileWriter(userFile))) {
this.gson.toJson(notification.getValue(), this.userType, writer);
} catch (final IOException exception) {
exception.printStackTrace();
}
}
private void ensureFileExists(final @NonNull File file) {
final File parentFile = file.getParentFile();
if (parentFile == null) {
throw new IllegalStateException("Parent file not present!");
}
if (!parentFile.exists()) {
parentFile.mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (final IOException exception) {
exception.printStackTrace();
}
}
}
}
@@ -1,372 +0,0 @@
package net.draycia.carbon.common.users;
import co.aikar.idb.DatabaseOptions;
import co.aikar.idb.PooledDatabaseOptions;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.ConsoleUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.api.users.UserChannelSettings;
import co.aikar.idb.DB;
import co.aikar.idb.Database;
import co.aikar.idb.DbRow;
import co.aikar.idb.DbStatement;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalNotification;
import net.draycia.carbon.api.users.UserService;
import net.draycia.carbon.api.config.SQLCredentials;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.format.TextColor;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.function.Supplier;
public class MySQLUserService<T extends PlayerUser, C extends ConsoleUser> implements UserService<T> {
private final @NonNull CarbonChat carbonChat;
private final @NonNull Database database;
private final @NonNull Supplier<@NonNull Collection<@NonNull T>> supplier;
private final @NonNull Supplier<@NonNull Collection<@NonNull String>> nameSupplier;
private final @NonNull Function<UUID, T> userFactory;
private final @NonNull Supplier<C> consoleFactory;
@SuppressWarnings("methodref.receiver.bound.invalid")
private final @NonNull LoadingCache<@NonNull UUID, @NonNull T> userCache = CacheBuilder.newBuilder()
.removalListener(this::saveUser)
.build(CacheLoader.from(this::loadUser));
public MySQLUserService(final @NonNull CarbonChat carbonChat, final @NonNull SQLCredentials credentials,
final @NonNull Supplier<@NonNull Collection<@NonNull T>> supplier,
final @NonNull Supplier<@NonNull Collection<@NonNull String>> nameSupplier,
final @NonNull Function<UUID, T> userFactory,
final @NonNull Supplier<C> consoleFactory) {
this.carbonChat = carbonChat;
this.supplier = supplier;
this.nameSupplier = nameSupplier;
this.userFactory = userFactory;
this.consoleFactory = consoleFactory;
final String username = credentials.username();
final String password = credentials.password();
final String database = credentials.database();
final String host = credentials.host();
final int port = credentials.port();
final String hostAndPort = host + ":" + port;
final DatabaseOptions options = DatabaseOptions.builder().mysql(username, password, database, hostAndPort).build();
this.database = PooledDatabaseOptions.builder().options(options).createHikariDatabase();
DB.setGlobalDatabase(this.database);
try {
this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_users (uuid CHAR(36) PRIMARY KEY," +
"channel VARCHAR(16), muted BOOLEAN, shadowmuted BOOLEAN, spyingwhispers BOOLEAN," +
"nickname VARCHAR(512), customchatcolor VARCHAR(32), whisperpingkey VARCHAR(64), " +
"whisperpingvolume FLOAT, whisperpingpitch FLOAT, channelpingkey VARCHAR(64), " +
"channelpingvolume FLOAT, channelpingpitch FLOAT)");
// Ignore the exception, it's just saying the column already exists
try {
this.database.executeUpdate("ALTER TABLE sc_users ADD COLUMN " +
"spyingwhispers BOOLEAN DEFAULT false, " +
"nickname VARCHAR(512) DEFAULT false, " +
"customchatcolor VARCHAR(32) DEFAULT false, " +
"whisperpingkey VARCHAR(64) DEFAULT false, " +
"whisperpingvolume FLOAT DEFAULT false, " +
"whisperpingpitch FLOAT DEFAULT false, " +
"channelpingkey VARCHAR(64) DEFAULT false, " +
"channelpingvolume FLOAT DEFAULT false, " +
"channelpingpitch FLOAT DEFAULT false");
} catch (final SQLSyntaxErrorException ignored) {
}
this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_channel_settings (uuid CHAR(36), channel CHAR(16), spying BOOLEAN, ignored BOOLEAN, color TINYTEXT, PRIMARY KEY (uuid, channel))");
this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_ignored_users (uuid CHAR(36), user CHAR(36), PRIMARY KEY (uuid, user))");
} catch (final SQLException exception) {
exception.printStackTrace();
}
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
MySQLUserService.this.userCache.cleanUp();
}
};
new Timer().schedule(timerTask, 0L, 300000L);
}
@Override
public void onDisable() {
this.userCache.invalidateAll();
this.userCache.cleanUp();
this.database.close();
}
@Override
public @NonNull T wrap(final @NonNull UUID uuid) {
try {
return this.userCache.get(uuid);
} catch (final ExecutionException exception) {
throw new IllegalStateException(exception);
}
}
@Override
public @NonNull CompletableFuture<T> wrapLater(final @NonNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> this.wrap(uuid));
}
@Override
public @Nullable C consoleUser() {
return this.consoleFactory.get();
}
@Override
public @Nullable T wrapIfLoaded(final @NonNull UUID uuid) {
return this.userCache.getIfPresent(uuid);
}
@Override
public @Nullable T refreshUser(final @NonNull UUID uuid) {
this.userCache.invalidate(uuid);
return this.wrap(uuid);
}
@Override
public void invalidate(final @NonNull T user) {
this.userCache.invalidate(user.uuid());
}
@Override
public void validate(final @NonNull T user) {
this.userCache.put(user.uuid(), user);
}
@Override
public @NonNull Collection<@NonNull T> onlineUsers() {
return this.supplier.get();
}
@Override
public @NonNull Collection<@NonNull String> proxyPlayers() {
return this.nameSupplier.get();
}
@SuppressWarnings("NoLvTypeAnnotations")
private @Nullable T loadUser(final @NonNull UUID uuid) {
final T user = this.userFactory.apply(uuid);
try (final DbStatement statement = this.database.query("SELECT * from sc_users WHERE uuid = ?;")) {
statement.execute(uuid.toString());
final DbRow users = statement.getNextRow();
if (users == null) {
return user;
}
final List<DbRow> channelSettings = this.database.getResults("SELECT * from sc_channel_settings WHERE uuid = ?;", uuid.toString());
final List<DbRow> ignoredUsers = this.database.getResults("SELECT * from sc_ignored_users WHERE uuid = ?;", uuid.toString());
final ChatChannel channel = this.carbonChat.channelRegistry().getOrDefault(users.get("channel"));
user.selectedChannel(channel);
final String nickname = users.get("nickname");
if (nickname != null) {
user.nickname(nickname);
}
user.muted(users.get("muted"));
user.shadowMuted(users.get("shadowmuted"));
user.spyingWhispers(users.get("spyingwhispers"));
user.customChatColor(users.get("customchatcolor"));
final String whisperPingKey = users.get("whisperpingkey");
final Float whisperPingVolume = users.get("whisperpingvolume");
final Float whisperPingPitch = users.get("whisperpingpitch");
final Sound whisperSound;
if (whisperPingKey != null && whisperPingVolume != null && whisperPingPitch != null) {
whisperSound = Sound.sound(Key.key(whisperPingKey), Sound.Source.PLAYER, whisperPingVolume, whisperPingPitch);
} else {
whisperSound = null;
}
final String channelPingKey = users.get("channelpingkey");
final Float channelPingVolume = users.get("channelpingvolume");
final Float channelPingPitch = users.get("channelpingpitch");
final Sound channelSound;
if (channelPingKey != null && channelPingVolume != null && channelPingPitch != null) {
channelSound = Sound.sound(Key.key(channelPingKey), Sound.Source.PLAYER, channelPingVolume, channelPingPitch);
} else {
channelSound = null;
}
user.pingOptions(new PlayerUser.PingOptions(whisperSound, channelSound));
for (final DbRow channelSetting : channelSettings) {
final ChatChannel chatChannel = this.carbonChat.channelRegistry().get(channelSetting.get("channel"));
if (chatChannel != null) {
final UserChannelSettings settings = user.channelSettings(chatChannel);
settings.spying(channelSetting.<Boolean>get("spying"));
settings.ignoring(channelSetting.<Boolean>get("ignored"));
final String color = channelSetting.get("color");
if (color != null) {
settings.color(TextColor.fromHexString(color));
}
}
}
for (final DbRow ignoredUser : ignoredUsers) {
user.ignoringUser(UUID.fromString(ignoredUser.get("user")), true);
}
} catch (final SQLException exception) {
exception.printStackTrace();
}
return user;
}
@SuppressWarnings("argument.type.incompatible")
private void saveUser(final @NonNull RemovalNotification<@NonNull UUID, @NonNull T> notification) {
final T user = notification.getValue();
this.database.createTransaction(stm -> {
// Save user general data
String selectedName = null;
final ChatChannel channel = user.selectedChannel();
if (channel != null) {
selectedName = channel.key();
}
final Sound whisperSound = user.pingOptions().whisperSound();
final String whisperName;
final Float whisperVolume;
final Float whisperPitch;
if (whisperSound != null) {
whisperName = whisperSound.name().asString();
whisperVolume = whisperSound.volume();
whisperPitch = whisperSound.pitch();
} else {
whisperName = null;
whisperVolume = null;
whisperPitch = null;
}
final Sound channelSound = user.pingOptions().pingSound();
final String channelName;
final Float channelVolume;
final Float channelPitch;
if (channelSound != null) {
channelName = channelSound.name().asString();
channelVolume = channelSound.volume();
channelPitch = channelSound.pitch();
} else {
channelName = null;
channelVolume = null;
channelPitch = null;
}
this.carbonChat.logger().info("Saving user data!");
// TODO: Store in a nice format in a file, and load in?
stm.executeUpdateQuery("INSERT INTO" +
" sc_users (" +
" uuid," +
" channel," +
" muted," +
" shadowmuted," +
" spyingwhispers," +
" nickname," +
" customchatcolor," +
" whisperpingkey," +
" whisperpingvolume," +
" whisperpingpitch," +
" channelpingkey," +
" channelpingvolume," +
" channelpingpitch" +
" )" +
"VALUES" +
" (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY " +
"UPDATE" +
" channel = ?," +
" muted = ?," +
" shadowmuted = ?," +
" spyingwhispers = ?," +
" nickname = ?," +
" customchatcolor = ?," +
" whisperpingkey = ?," +
" whisperpingvolume = ?," +
" whisperpingpitch = ?," +
" channelpingkey = ?," +
" channelpingvolume = ?," +
" channelpingpitch = ?",
user.uuid().toString(),
selectedName, user.muted(), user.shadowMuted(), user.spyingWhispers(), user.nickname(), user.customChatColor(),
whisperName, whisperVolume, whisperPitch, channelName, channelVolume, channelPitch,
selectedName, user.muted(), user.shadowMuted(), user.spyingWhispers(), user.nickname(), user.customChatColor(),
whisperName, whisperVolume, whisperPitch, channelName, channelVolume, channelPitch);
this.carbonChat.logger().info("Saving user channel settings!");
// Save user channel settings
for (final Map.Entry<String, ? extends UserChannelSettings> entry : user.channelSettings().entrySet()) {
final UserChannelSettings value = entry.getValue();
String colorString = null;
final TextColor color = value.color();
if (color != null) {
colorString = color.asHexString();
}
stm.executeUpdateQuery("INSERT INTO sc_channel_settings (uuid, channel, spying, ignored, color) VALUES (?, ?, ?, ?, ?) " +
"ON DUPLICATE KEY UPDATE spying = ?, ignored = ?, color = ?",
user.uuid().toString(), entry.getKey(), value.spying(), value.ignored(), colorString,
value.spying(), value.ignored(), colorString);
}
this.carbonChat.logger().info("Saving user ignores!");
// Save user ignore list (remove old entries then add new ones)
// TODO: keep DB up to date with settings as settings are mutated
stm.executeUpdateQuery("DELETE FROM sc_ignored_users WHERE uuid = ?", user.uuid().toString());
for (final UUID entry : user.ignoredUsers()) {
stm.executeUpdateQuery("INSERT INTO sc_ignored_users (uuid, user) VALUES (?, ?)",
user.uuid().toString(), entry.toString());
}
return true;
});
}
}
@@ -1,7 +1,5 @@
package net.draycia.carbon.common.utils;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
@@ -18,15 +16,7 @@ public final class ColorUtils {
}
public static @Nullable TextColor parseColor(final @NonNull String input) {
return parseColor(null, input);
}
public static @Nullable TextColor parseColor(final @Nullable CarbonUser user, @NonNull String input) {
if (user instanceof PlayerUser) {
input = ((PlayerUser) user).parsePlaceholders(input);
}
public static @Nullable TextColor parseColor(@NonNull String input) {
if (input.isEmpty()) {
return NamedTextColor.WHITE;
}
@@ -1,52 +0,0 @@
// MIT License
//
// Copyright (c) 2020 Alexander Söderberg & Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
package net.draycia.carbon.common.utils;
import cloud.commandframework.captions.Caption;
import cloud.commandframework.context.CommandContext;
import cloud.commandframework.exceptions.parsing.ParserException;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* An exception which is thrown when an argument's input is unexpectedly null or empty
*/
public class NoInputProvidedException extends ParserException {
/**
* Construct a new NoInputProvidedException
*
* @param argumentParser Argument parser class
* @param context Command context
*/
public NoInputProvidedException(
final Class<?> argumentParser,
final @NonNull CommandContext<?> context
) {
super(
argumentParser,
context,
Caption.of("argument.parse.failure.no_input_was_provided")
);
}
}
@@ -1,231 +0,0 @@
//
// MIT License
//
// Copyright (c) 2020 Alexander Söderberg & Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
package net.draycia.carbon.common.utils;
import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.arguments.parser.ArgumentParseResult;
import cloud.commandframework.arguments.parser.ArgumentParser;
import cloud.commandframework.captions.Caption;
import cloud.commandframework.captions.CaptionVariable;
import cloud.commandframework.context.CommandContext;
import cloud.commandframework.exceptions.parsing.ParserException;
import cloud.commandframework.types.tuples.Pair;
import io.leangen.geantyref.TypeToken;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.regex.Pattern;
/**
* Parser for color codes.
* <p>
* Accepts {@link NamedTextColor NamedTextColors}, Legacy Minecraft {@literal &} color codes, Hex Codes (#RRGGBB)
*
* @param <C> Command sender type
*/
public final class TextColorArgument<C> extends CommandArgument<C, TextColor> {
private static final Pattern LEGACY_PREDICATE = Pattern.compile(
"&[0-9a-fA-F]"
);
private static final Pattern HEX_PREDICATE = Pattern.compile(
"#?([a-fA-F0-9]{1,6})"
);
private static final Collection<Pair<Character, NamedTextColor>> COLORS = Arrays.asList(
Pair.of('0', NamedTextColor.BLACK),
Pair.of('1', NamedTextColor.DARK_BLUE),
Pair.of('2', NamedTextColor.DARK_GREEN),
Pair.of('3', NamedTextColor.DARK_GREEN),
Pair.of('4', NamedTextColor.DARK_AQUA),
Pair.of('5', NamedTextColor.DARK_PURPLE),
Pair.of('6', NamedTextColor.GOLD),
Pair.of('7', NamedTextColor.GRAY),
Pair.of('8', NamedTextColor.DARK_GRAY),
Pair.of('9', NamedTextColor.BLUE),
Pair.of('a', NamedTextColor.GREEN),
Pair.of('b', NamedTextColor.AQUA),
Pair.of('c', NamedTextColor.RED),
Pair.of('d', NamedTextColor.LIGHT_PURPLE),
Pair.of('e', NamedTextColor.YELLOW),
Pair.of('f', NamedTextColor.WHITE)
);
private TextColorArgument(
final boolean required,
final @NonNull String name,
final @NonNull String defaultValue
) {
super(
required,
name,
new TextColorParser<>(),
defaultValue,
TypeToken.get(TextColor.class),
null,
new LinkedList<>()
);
}
/**
* Create a new required TextColor argument
*
* @param name Argument name
* @param <C> Command sender type
* @return Created argument
*/
public static <C> @NonNull TextColorArgument<C> of(final @NonNull String name) {
return new TextColorArgument<>(
true,
name,
""
);
}
/**
* Create a new optional TextColor argument
*
* @param name Argument name
* @param <C> Command sender type
* @return Created argument
*/
public static <C> @NonNull TextColorArgument<C> optional(final @NonNull String name) {
return new TextColorArgument<>(
false,
name,
""
);
}
/**
* Create a new optional TextColor argument
*
* @param name Argument name
* @param defaultValue Default value
* @param <C> Command sender type
* @return Created argument
*/
public static <C> @NonNull TextColorArgument<C> optionalWithDefault(
final @NonNull String name,
final @NonNull String defaultValue
) {
return new TextColorArgument<>(
false,
name,
defaultValue
);
}
public static final class TextColorParser<C> implements ArgumentParser<C, TextColor> {
@Override
public @NonNull ArgumentParseResult<@NonNull TextColor> parse(
final @NonNull CommandContext<@NonNull C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek();
if (input == null) {
return ArgumentParseResult.failure(new NoInputProvidedException(
TextColorParser.class,
commandContext
));
}
if (LEGACY_PREDICATE.matcher(input).matches()) {
final char code = input.substring(1).toLowerCase().charAt(0);
for (final Pair<Character, NamedTextColor> pair : COLORS) {
if (pair.getFirst() == code) {
inputQueue.remove();
return ArgumentParseResult.success(
pair.getSecond()
);
}
}
}
for (final Pair<Character, NamedTextColor> pair : COLORS) {
if (pair.getSecond().toString().equalsIgnoreCase(input)) {
inputQueue.remove();
return ArgumentParseResult.success(
pair.getSecond()
);
}
}
if (HEX_PREDICATE.matcher(input).matches()) {
return ArgumentParseResult.success(
TextColor.color(Integer.parseInt(input.startsWith("#") ? input.substring(1) : input, 16))
);
}
return ArgumentParseResult.failure(
new TextColorParseException(
commandContext,
input
)
);
}
@Override
public @NonNull List<@NonNull String> suggestions(
final @NonNull CommandContext<C> commandContext, final @NonNull String input
) {
final List<String> suggestions = new LinkedList<>();
if (input.isEmpty() || input.equals("#") || (HEX_PREDICATE.matcher(input).matches()
&& input.length() < (input.startsWith("#") ? 7 : 6))) {
for (char c = 'a'; c <= 'f'; c++) {
suggestions.add(String.format("%s%c", input, c));
suggestions.add(String.format("&%c", c));
}
for (char c = '0'; c <= '9'; c++) {
suggestions.add(String.format("%s%c", input, c));
suggestions.add(String.format("&%c", c));
}
}
suggestions.addAll(NamedTextColor.NAMES.keys());
return suggestions;
}
}
private static final class TextColorParseException extends ParserException {
private TextColorParseException(
final @NonNull CommandContext<?> commandContext,
final @NonNull String input
) {
super(
TextColorParser.class,
commandContext,
Caption.of("'{input}' is not a valid color"),
CaptionVariable.of("input", input)
);
}
}
}