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,72 +1,5 @@
package net.draycia.carbon.api;
import cloud.commandframework.CommandManager;
import net.draycia.carbon.api.config.CarbonTranslations;
import net.draycia.carbon.api.adventure.MessageProcessor;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.commands.settings.CommandSettingsRegistry;
import net.draycia.carbon.api.config.CarbonSettings;
import net.draycia.carbon.api.config.ChannelSettings;
import net.draycia.carbon.api.config.ModerationSettings;
import net.draycia.carbon.api.messaging.MessageService;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.api.users.UserService;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import java.io.File;
import java.nio.file.Path;
import java.util.UUID;
public interface CarbonChat {
LegacyComponentSerializer LEGACY =
LegacyComponentSerializer.builder()
.extractUrls()
.hexColors()
.character(LegacyComponentSerializer.SECTION_CHAR)
.useUnusualXRepeatedCharacterHexFormat()
.build();
void reload();
@NonNull File dataDirectory();
@NonNull UUID resolveUUID(@NonNull String name);
void cacheUUID(@NonNull String name, @NonNull UUID uuid);
@NonNull String resolveName(@NonNull UUID uuid);
@NonNull Logger logger();
@NonNull Path dataFolder();
@NonNull <T extends PlayerUser> UserService<T> userService();
@NonNull MessageProcessor messageProcessor();
@NonNull MessageService messageService();
@NonNull CarbonSettings carbonSettings();
@NonNull ChannelSettings channelSettings();
@NonNull ChannelRegistry channelRegistry();
@NonNull CommandSettingsRegistry commandSettings();
@NonNull CarbonTranslations translations();
@NonNull ModerationSettings moderationSettings();
@NonNull GsonComponentSerializer gsonSerializer();
@NonNull CommandManager<CarbonUser> commandManager();
@NonNull String version();
}
@@ -1,141 +0,0 @@
package net.draycia.carbon.api;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import java.util.Arrays;
import java.util.List;
@ConfigSerializable
public class Context {
@Setting private final @NonNull String key;
@Setting private final @NonNull String value;
public Context(final @NonNull String key, final @NonNull String value) {
this.key = key;
this.value = value;
}
public @NonNull String key() {
return this.key;
}
public @NonNull String value() {
return this.value;
}
public boolean isFloat() {
try {
Float.valueOf(this.value);
} catch (final NumberFormatException ignored) {
return false;
}
return true;
}
public boolean isDouble() {
try {
Double.valueOf(this.value);
} catch (final NumberFormatException ignored) {
return false;
}
return true;
}
public boolean isByte() {
try {
Byte.valueOf(this.value);
} catch (final NumberFormatException ignored) {
return false;
}
return true;
}
public boolean isInteger() {
try {
Integer.valueOf(this.value);
} catch (final NumberFormatException ignored) {
return false;
}
return true;
}
public boolean isLong() {
try {
Long.valueOf(this.value);
} catch (final NumberFormatException ignored) {
return false;
}
return true;
}
public boolean isString() {
return true;
}
public boolean isBoolean() {
try {
Boolean.valueOf(this.value);
} catch (final NumberFormatException ignored) {
return false;
}
return true;
}
public boolean isList() {
return true;
}
public boolean isListChecked(final Class<?> type) {
if (!this.isList()) {
return false;
}
final List<?> list = this.asList();
if (list.size() > 0) {
final Object value = list.get(0);
if (value != null) {
return value.getClass().isAssignableFrom(type);
}
}
return false;
}
public boolean isNumber() {
try {
Double.valueOf(this.value);
} catch (final NumberFormatException ignored) {
return false;
}
return true;
}
public String asString() {
return this.value();
}
public Boolean asBoolean() {
return Boolean.valueOf(this.value());
}
public List<String> asList() {
return Arrays.asList(this.value.split(","));
}
public Number asNumber() {
return Double.valueOf(this.value());
}
}
@@ -1,14 +0,0 @@
package net.draycia.carbon.api.adventure;
import net.kyori.adventure.platform.AudienceProvider;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public interface MessageProcessor {
@NonNull Component processMessage(final @Nullable String input, final @NonNull String @NonNull ... placeholders);
@NonNull AudienceProvider audiences();
}
@@ -1,77 +0,0 @@
package net.draycia.carbon.api.channels;
import net.draycia.carbon.api.DefaultedKeyValueRegistry;
import net.kyori.registry.Registry;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ChannelRegistry implements Registry<String, ChatChannel>, DefaultedKeyValueRegistry<String, ChatChannel> {
private final @NonNull Map<@NonNull String, @NonNull ChatChannel> registry = new HashMap<>();
private @NonNull ChatChannel defaultChannel = new EmptyTextChannel();
@Override
public @NonNull ChatChannel register(final @NonNull String key, final @NonNull ChatChannel value) {
this.registry.putIfAbsent(key, value);
if (value instanceof TextChannel) {
if (this.defaultChannel instanceof EmptyTextChannel && ((TextChannel) value).isDefault()) {
this.defaultChannel = value;
}
}
return value;
}
@Override
public @Nullable ChatChannel get(final @NonNull String key) {
return this.registry.get(key);
}
@Override
public @Nullable String key(final @NonNull ChatChannel value) {
for (final Map.Entry<String, ChatChannel> entry : this.registry.entrySet()) {
if (entry.getValue().equals(value)) {
return entry.getKey();
}
}
return null;
}
@Override
public @NonNull Set<String> keySet() {
return (Set<String>) this.registry.keySet(); // https://github.com/typetools/checker-framework/issues/3638
}
@Override
public @NonNull Iterator<ChatChannel> iterator() {
return this.registry.values().iterator();
}
@Override
public @NonNull String defaultKey() {
return this.defaultChannel.key();
}
@Override
public @NonNull ChatChannel defaultValue() {
return this.defaultChannel;
}
@Override
public @NonNull ChatChannel getOrDefault(final @NonNull String key) {
return this.registry.getOrDefault(key, this.defaultValue());
}
public void clear() {
this.registry.clear();
}
}
@@ -1,80 +0,0 @@
package net.draycia.carbon.api.channels;
import net.draycia.carbon.api.config.ChannelOptions;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextColor;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public interface ChatChannel extends Audience {
/**
* Gets the {@link TextColor} the supplied {@link CarbonUser} has set for this channel.
* If none is set, returns this channel's set color with the "color" config option.
* @param user The user that may have a color set.
* @return The color the user may have set, otherwise the channel's color.
*/
@NonNull TextColor channelColor(@NonNull CarbonUser user);
@NonNull
Map<CarbonUser, Component> parseMessage(@NonNull PlayerUser user, @NonNull String message);
@NonNull
Map<CarbonUser, Component> parseMessage(@NonNull PlayerUser user, @NonNull Collection<@NonNull PlayerUser> recipients,
@NonNull String message);
boolean canPlayerUse(@NonNull PlayerUser user);
boolean canPlayerSee(@NonNull PlayerUser sender, @NonNull PlayerUser target, boolean checkSpying);
boolean canPlayerSee(@NonNull PlayerUser target, boolean checkSpying);
void sendComponents(final @NonNull Identity identity,
final @NonNull Map<? extends CarbonUser, Component> components);
void sendComponentsAndLog(final @NonNull Identity identity,
final @NonNull Map<? extends CarbonUser, Component> components);
@NonNull String name();
@NonNull String key();
/**
* If this channel can be ignored, such as through the /toggle command.
* @return IF this channel can be ignored / toggled.
*/
boolean ignorable();
@NonNull List<@NonNull Pattern> itemLinkPatterns();
@NonNull String switchMessage();
@NonNull String switchOtherMessage();
@NonNull String switchFailureMessage();
@NonNull String cannotIgnoreMessage();
@NonNull String toggleOffMessage();
@NonNull String toggleOnMessage();
@NonNull String toggleOtherOnMessage();
@NonNull String toggleOtherOffMessage();
@NonNull String cannotUseMessage();
@NonNull ChannelOptions options();
void options(@NonNull ChannelOptions options);
}
@@ -1,207 +0,0 @@
package net.draycia.carbon.api.channels;
import net.draycia.carbon.api.Context;
import net.draycia.carbon.api.config.ChannelOptions;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import net.luckperms.api.model.group.Group;
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.List;
import java.util.Map;
import java.util.regex.Pattern;
public class EmptyTextChannel implements TextChannel {
@Override
public @NonNull List<@NonNull PlayerUser> audiences() {
return Collections.emptyList();
}
@Override
public @NonNull ChannelOptions options() {
return ChannelOptions.defaultChannel();
}
@Override
public void options(final @NonNull ChannelOptions options) {
}
@Override
public @Nullable String format(final @NonNull Group group) {
return null;
}
@Override
public @Nullable String format(final @NonNull String group) {
return null;
}
@Override
public boolean isDefault() {
return true;
}
@Override
public boolean crossServer() {
return false;
}
@Override
public @Nullable String messagePrefix() {
return null;
}
@Override
public @NonNull List<String> aliases() {
return Collections.emptyList();
}
@Override
public boolean primaryGroupOnly() {
return false;
}
@Override
public boolean honorsRecipientList() {
return false;
}
@Override
public boolean permissionGroupMatching() {
return false;
}
@Override
public boolean testContext(final @NonNull PlayerUser sender, final @NonNull PlayerUser target) {
return false;
}
@Override
public @Nullable Context context(final @NonNull String key) {
return null;
}
@Override
public @NonNull List<@NonNull String> groupOverrides() {
return Collections.emptyList();
}
@Override
public void sendComponent(final @NonNull PlayerUser user, final @NonNull Component component) {
}
@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 Collections.emptyMap();
}
@Override
public @NonNull Map<CarbonUser, Component> parseMessage(final @NonNull PlayerUser user, final @NonNull Collection<@NonNull PlayerUser> recipients, final @NonNull String message) {
return Collections.emptyMap();
}
@Override
public boolean canPlayerUse(final @NonNull PlayerUser user) {
return false;
}
@Override
public boolean canPlayerSee(final @NonNull PlayerUser sender, final @NonNull PlayerUser target, final boolean checkSpying) {
return false;
}
@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) {
}
@Override
public void sendComponentsAndLog(final @NonNull Identity identity, final @NonNull Map<? extends CarbonUser, Component> components) {
}
@Override
public @NonNull String name() {
return "default";
}
@Override
public @NonNull String key() {
return "default";
}
@Override
public boolean ignorable() {
return false;
}
@Override
public @NonNull List<@NonNull Pattern> itemLinkPatterns() {
return Collections.emptyList();
}
@Override
public @NonNull String switchMessage() {
return "";
}
@Override
public @NonNull String switchOtherMessage() {
return "";
}
@Override
public @NonNull String switchFailureMessage() {
return "";
}
@Override
public @NonNull String cannotIgnoreMessage() {
return "";
}
@Override
public @NonNull String toggleOffMessage() {
return "";
}
@Override
public @NonNull String toggleOnMessage() {
return "";
}
@Override
public @NonNull String toggleOtherOnMessage() {
return "";
}
@Override
public @NonNull String toggleOtherOffMessage() {
return "";
}
@Override
public @NonNull String cannotUseMessage() {
return "";
}
}
@@ -1,16 +0,0 @@
package net.draycia.carbon.api.channels;
import net.draycia.carbon.api.users.CarbonUser;
import net.kyori.adventure.audience.ForwardingAudience;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Collection;
public interface GroupChannel extends ChatChannel, ForwardingAudience {
@NonNull CarbonUser owner();
@Override
@NonNull Collection<@NonNull CarbonUser> audiences();
}
@@ -1,63 +0,0 @@
package net.draycia.carbon.api.channels;
import net.draycia.carbon.api.Context;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.text.Component;
import net.luckperms.api.model.group.Group;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.List;
public interface TextChannel extends ChatChannel, ForwardingAudience {
@Override
@NonNull List<@NonNull PlayerUser> audiences();
/**
* Gets the string format for the specified group.
* @param group The group.
* @return The string format for the specified group.
*/
@Nullable String format(@NonNull Group group);
/**
* Gets the string format for the specified group.
* @param group The group.
* @return The string format for the specified group.
*/
@Nullable String format(@NonNull String group);
/**
* If this channel is the channel players get when they join for the first time.
* Also the fallback channel in case the code is unable to find any given channel.
* @return If this is the default channel.
*/
boolean isDefault();
/**
* If this channel syncs between servers, typically through the messaging service.
* @return If this channel syncs between servers, typically through the messaging service.
*/
boolean crossServer();
@Nullable String messagePrefix();
@NonNull List<String> aliases();
boolean primaryGroupOnly();
boolean honorsRecipientList();
boolean permissionGroupMatching();
boolean testContext(@NonNull PlayerUser sender, @NonNull PlayerUser target);
@Nullable Context context(@NonNull String key);
@NonNull List<@NonNull String> groupOverrides();
void sendComponent(@NonNull PlayerUser user, @NonNull Component component);
}
@@ -1,28 +0,0 @@
package net.draycia.carbon.api.channels;
import net.draycia.carbon.api.users.CarbonUser;
import net.kyori.adventure.audience.ForwardingAudience;
import org.checkerframework.checker.nullness.qual.NonNull;
public interface WhisperChannel extends ChatChannel, ForwardingAudience.Single {
@NonNull CarbonUser sender();
/**
* The recipient for this channel, where messages are sent to.
* @return The channel recipient.
*/
@Override
@NonNull CarbonUser audience();
@Override
default @NonNull String name() {
return "Whisper";
}
@Override
default @NonNull String key() {
return "whisper";
}
}
@@ -1,33 +0,0 @@
package net.draycia.carbon.api.commands.settings;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import java.util.Collections;
import java.util.Set;
@ConfigSerializable
public class CommandSettings {
@Setting
private boolean enabled = true;
@Setting
private @NonNull String name = "command";
@Setting
private @NonNull Set<@NonNull String> aliases = Collections.emptySet();
public @NonNull Set<@NonNull String> aliases() {
return this.aliases;
}
public @NonNull String name() {
return this.name;
}
public boolean enabled() {
return this.enabled;
}
}
@@ -1,73 +0,0 @@
package net.draycia.carbon.api.commands.settings;
import net.draycia.carbon.api.channels.ChatChannel;
import net.kyori.registry.Registry;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import org.spongepowered.configurate.serialize.SerializationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@ConfigSerializable
public class CommandSettingsRegistry implements Registry<String, CommandSettings> {
@Setting
private final @NonNull Map<@NonNull String, @NonNull CommandSettings> registry = new HashMap<>();
private static final ObjectMapper<CommandSettingsRegistry> MAPPER;
static {
try {
MAPPER = ObjectMapper.factory().get(CommandSettingsRegistry.class);
} catch (final SerializationException e) {
throw new ExceptionInInitializerError(e);
}
}
public static CommandSettingsRegistry loadFrom(final CommentedConfigurationNode node) throws SerializationException {
return MAPPER.load(node);
}
public void saveTo(final CommentedConfigurationNode node) throws SerializationException {
MAPPER.save(this, node);
}
@Override
public @NonNull CommandSettings register(final @NonNull String key, final @NonNull CommandSettings value) {
this.registry.putIfAbsent(key, value);
return value;
}
@Override
public @Nullable CommandSettings get(final @NonNull String key) {
return this.registry.get(key);
}
public @Nullable CommandSettings get(final @NonNull ChatChannel channel) {
return this.get(channel.key());
}
@Override
public @Nullable String key(final @NonNull CommandSettings value) {
return null;
}
@Override
public @NonNull Set<String> keySet() {
return (Set<String>) this.registry.keySet(); // https://github.com/typetools/checker-framework/issues/3638
}
@Override
public @NonNull Iterator<CommandSettings> iterator() {
return this.registry.values().iterator();
}
}
@@ -1,134 +0,0 @@
package net.draycia.carbon.api.config;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import org.spongepowered.configurate.serialize.SerializationException;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
@ConfigSerializable
public final class CarbonSettings {
private static final ObjectMapper<CarbonSettings> MAPPER;
static {
try {
MAPPER = ObjectMapper.factory().get(CarbonSettings.class);
} catch (final SerializationException e) {
throw new ExceptionInInitializerError(e);
}
}
public static CarbonSettings loadFrom(final CommentedConfigurationNode node) throws SerializationException {
return MAPPER.load(node);
}
public void saveTo(final CommentedConfigurationNode node) throws SerializationException {
MAPPER.save(this, node);
}
@Setting
@Comment("The prefix shown when spying on a user's message")
private @NonNull String spyPrefix = "<color>[SPY] ";
@Setting
@Comment("Used for <server> placeholder in channel formats")
private @NonNull String serverName = "Server";
@Setting
@Comment("Set this to false to disable warnings and tips when the plugin thinks there may be configuration issues.")
private boolean showTips = true;
@Setting
@Comment("Options: JSON, MYSQL")
private @Nullable StorageType storageType = StorageType.JSON;
@Setting
@Comment("The credentials used to connect to your database. Requires storageType=MYSQL")
private @NonNull SQLCredentials sqlCredentials = new SQLCredentials();
@Setting
@Comment("Options: NONE, REDIS, BUNGEECORD\n" +
" 'BUNGEECORD' - Uses bungee plugin messaging, requires BungeeCord or another proxy which supports it (Velocity, Waterfall!)\n" +
" 'REDIS' - Uses redis for cross server syncing, does not require a server proxy\n" +
" 'NONE' - Do not sync anything cross server, this is the default\n" +
"Note: In order for channels to sync cross server, you'll need to enable is-cross-server for the\n" +
" channel as well as this setting.")
private @NonNull MessagingType messagingType = MessagingType.NONE;
@Setting
@Comment("The credentials necessary to connect to your redis server")
private @NonNull RedisCredentials redisCredentials = new RedisCredentials();
@Setting
@Comment("Plays a sound and highlights the message when someone types your name")
private @NonNull ChannelPings channelPings = new ChannelPings();
@Setting
@Comment("Various options relating to the /whisper command")
private @NonNull WhisperOptions whisperOptions = new WhisperOptions();
@Setting
@Comment("Sets the player's channel to the specified channel when they join" +
"\nSet to \"\" or remove to disable" +
"\nSet to DEFAULT to set the player's channel to the default channel on join" +
"\nOtherwise, set to a channel to set the player's channel to it on join" +
"\nFor example, channel-on-join: \"global\" sets their channel to global on join")
private @Nullable String channelOnJoin = "";
@Setting
@Comment("The list of regex patterns to show items in chat. '\\\\Q' and '\\\\E' just denote that the content isn't regex.")
private List<Pattern> itemLinkPatterns =
Collections.singletonList(Pattern.compile(Pattern.quote("[item]")));
public @NonNull List<@NonNull Pattern> itemLinkPatterns() {
return this.itemLinkPatterns;
}
public @NonNull String spyPrefix() {
return this.spyPrefix;
}
public @NonNull String serverName() {
return this.serverName;
}
public boolean showTips() {
return this.showTips;
}
public @Nullable StorageType storageType() {
return this.storageType;
}
public SQLCredentials sqlCredentials() {
return this.sqlCredentials;
}
public @NonNull MessagingType messagingType() {
return this.messagingType;
}
public @NonNull RedisCredentials redisCredentials() {
return this.redisCredentials;
}
public @Nullable String channelOnJoin() {
return this.channelOnJoin;
}
public @NonNull ChannelPings channelPings() {
return this.channelPings;
}
public @NonNull WhisperOptions whisperOptions() {
return this.whisperOptions;
}
}
@@ -1,227 +0,0 @@
package net.draycia.carbon.api.config;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import org.spongepowered.configurate.serialize.SerializationException;
@ConfigSerializable
public final class CarbonTranslations {
private static final ObjectMapper<CarbonTranslations> MAPPER;
static {
try {
MAPPER = ObjectMapper.factory().get(CarbonTranslations.class);
} catch (final SerializationException e) {
throw new ExceptionInInitializerError(e);
}
}
public static CarbonTranslations loadFrom(final CommentedConfigurationNode node) throws SerializationException {
return MAPPER.load(node);
}
public void saveTo(final CommentedConfigurationNode node) throws SerializationException {
MAPPER.save(this, node);
}
private ExceptionMessages exceptionMessages = new ExceptionMessages();
private ContextMessages contextMessages = new ContextMessages();
@Setting private String reloaded = "<yellow>Chat config has been reloaded!";
@Setting private String otherPlayerOffline = "<red>That player is offline!";
@Setting private String spyWhispers = "<yellow>Spy [<gray><sender><reset> <gold>-> <gray><target><reset><yellow>] <message>";
@Setting private String noReplyTarget = "<red>You have no one to reply to!";
@Setting private String otherNicknameSet = "<green><user><reset>''s nickname was set to <nickname><green>!";
@Setting private String otherNicknameReset = "<green><user><reset>'s nickname was reset!";
@Setting private String availableChannelsList = "<green>Available Channels:<reset> <list>.";
@Setting private String unavailableChannelsList = "<red>Unavailable Channels:<reset> <list>.";
@Setting private String channelListSeparator = ", ";
@Setting private String userMustBeOnline = "<red><player> must be online!";
@Setting private String replyMessageBlank = "<red>Your reply message was blank!";
@Setting private String invalidColor = "<red>The input <input> is not a valid color!";
@Setting private String cannotSetColor = "<red>You do not have permission to set a color for this channel!";
@Setting private String roleplayFormat = "<italic><dark_purple>*<displayname> <reset><message>*</dark_purple></italic>";
@Setting private String ignoringUser = "<green>You are now ignoring <gold><player><reset><green>!";
@Setting private String notIgnoringUser = "<green>You are no longer ignoring <gold><player><reset><green>!";
@Setting private String ignoreExempt = "<red>User <player> <red>is exempt from being ignored!";
@Setting private String channelColorSet = "<green>You have set <color><channel> <green>color to <hex>!";
@Setting private String spyToggledOn = "<gray>You are now spying on <color><channel> <gray>chat!";
@Setting private String spyToggledOff = "<gray>You are no longer spying on <color><channel> <gray>chat!";
@Setting private String spyWhispersOn = "<gray>You are now spying on whispers!";
@Setting private String spyWhispersOff = "<gray>You are no longer spying on whispers!";
@Setting private String spyEverythingOn = "<gray>All spying toggled on!";
@Setting private String spyEverythingOff = "<gray>All spying toggled off!";
@Setting private String nicknameSet = "<green>Your nickname was set to <nickname><reset><green>!";
@Setting private String nicknameReset = "<green>Your nickname was reset!";
@Setting private String nowShadowMuted = "<yellow>Player <player> is now shadow muted!";
@Setting private String noLongerShadowMuted = "<yellow>Player <player> is no longer shadow muted!";
@Setting private String shadowMuteExempt = "<red>Player <player> is exempt from being shadow muted!";
@Setting private String nowMuted = "<yellow>Player <player> is now muted!";
@Setting private String noLongerMuted = "<yellow>Player <player> is no longer muted!";
@Setting private String muteExempt = "<red>Player <player> is exempt from being muted!";
@Setting private String clearNotify = "<yellow>Chat has been cleared by <player>.";
@Setting private String clearExempt = "<yellow>You were exempt from the clear due to your permissions!";
@Setting private String cannotWhisperSelf = "<yellow>You cannot whisper yourself!";
@Setting private String whisperPingChanged = "<green>Whisper ping settings changed!";
@Setting private String channelPingChanged = "<green>Channel ping settings changed!";
public ExceptionMessages exceptionMessages() {
return this.exceptionMessages;
}
public ContextMessages contextMessages() {
return this.contextMessages;
}
public String reloaded() {
return this.reloaded;
}
public String otherPlayerOffline() {
return this.otherPlayerOffline;
}
public String spyWhispers() {
return this.spyWhispers;
}
public String noReplyTarget() {
return this.noReplyTarget;
}
public String otherNicknameSet() {
return this.otherNicknameSet;
}
public String otherNicknameReset() {
return this.otherNicknameReset;
}
public String availableChannelsList() {
return this.availableChannelsList;
}
public String unavailableChannelsList() {
return this.unavailableChannelsList;
}
public String channelListSeparator() {
return this.channelListSeparator;
}
public String userMustBeOnline() {
return this.userMustBeOnline;
}
public String replyMessageBlank() {
return this.replyMessageBlank;
}
public String invalidColor() {
return this.invalidColor;
}
public String cannotSetColor() {
return this.cannotSetColor;
}
public String roleplayFormat() {
return this.roleplayFormat;
}
public String ignoringUser() {
return this.ignoringUser;
}
public String notIgnoringUser() {
return this.notIgnoringUser;
}
public String ignoreExempt() {
return this.ignoreExempt;
}
public String channelColorSet() {
return this.channelColorSet;
}
public String spyToggledOn() {
return this.spyToggledOn;
}
public String spyToggledOff() {
return this.spyToggledOff;
}
public String spyWhispersOn() {
return this.spyWhispersOn;
}
public String spyWhispersOff() {
return this.spyWhispersOff;
}
public String spyEverythingOn() {
return this.spyEverythingOn;
}
public String spyEverythingOff() {
return this.spyEverythingOff;
}
public String nicknameSet() {
return this.nicknameSet;
}
public String nicknameReset() {
return this.nicknameReset;
}
public String nowShadowMuted() {
return this.nowShadowMuted;
}
public String noLongerShadowMuted() {
return this.noLongerShadowMuted;
}
public String shadowMuteExempt() {
return this.shadowMuteExempt;
}
public String nowMuted() {
return this.nowMuted;
}
public String noLongerMuted() {
return this.noLongerMuted;
}
public String muteExempt() {
return this.muteExempt;
}
public String clearNotify() {
return this.clearNotify;
}
public String clearExempt() {
return this.clearExempt;
}
public String cannotWhisperSelf() {
return this.cannotWhisperSelf;
}
public String channelPingChanged() {
return this.channelPingChanged;
}
public String whisperPingChanged() {
return this.whisperPingChanged;
}
}
@@ -1,402 +0,0 @@
package net.draycia.carbon.api.config;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.Context;
import net.kyori.adventure.text.format.NamedTextColor;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ConfigSerializable
@SuppressWarnings("initialization.fields.uninitialized")
public final class ChannelOptions {
@Setting
@Comment("What this channel is identified as. This is used in command arguments (/channel global)")
private @NonNull String key = "channel";
@Setting
@Comment("This is what the <color> placeholder will typically be replaced with.\n" +
"Hex RGB (#B19CD9), named colors (light_purple), legacy (&d), and legacy RGB (&x&b&1&2&c&d&9) are all supported.\n" +
"If on a platform that supports PlaceholderAPI, this option will be ran through that as well.\n" +
"Note that the <color> placeholder is also used for personal and global user colors.")
private @Nullable String color = NamedTextColor.WHITE.asHexString();
@Setting
@Comment("The contexts for this channel, which can modify the behaviour of channels and how/when players can use them.")
private @Nullable Map<@NonNull String, @NonNull Context> contexts = new HashMap<>();
@Setting
@Comment("The formats for this channel. The key is the name of the group as your permissions plugin reports it.")
private @Nullable Map<String, String> formats = ImmutableMap.of("default", "<color><<displayname><reset><color>> <message>");
@Setting
@Comment("The name of the format that the plugin will fall back to when it cannot find a matching format for the player's groups.")
private @Nullable String defaultFormatName;
@Setting
@Comment("If this channel is the default channel players join in.\n" +
"Also used as a fallback in case the player's selected channel cannot be found.")
private boolean isDefault = false; // primitive because missing = false
@Setting
@Comment("If this channel can be ignored / hidden with the /ignore command")
private Boolean ignorable; // boxed because missing = use defaults
@Setting
@Comment("If this channel syncs to other servers (cross-server chat), requires a messaging system setup")
private Boolean crossServer;
@Setting
@Comment("If this channel should respect the bukkit recipient list, you normally shouldn't touch this")
private Boolean honorsRecipientList;
@Setting
@Comment("If players with the permission carbonchat.group.groupname are considered to have the group groupname")
private Boolean permissionGroupMatching;
@Setting
@Comment("A custom (ordered) list of group priorities")
private List<String> groupOverrides;
@Setting
@Comment("# The display name of this channel, supports minimessage. Used in command feedback (\"You switched to the Global channel\")")
private String name = "";
@Setting
@Comment("If the player's chat message starts with whatever this is set to, the player speaks in this channel instead of their selected one")
private String messagePrefix = "";
@Setting
@Comment("The command aliases for this channel (/global /g)")
private List<String> aliases = new ArrayList<>();
@Setting
@Comment("If the bukkit chat event should be cancelled, you probably don't want to change this")
private Boolean shouldCancelChatEvent;
@Setting
@Comment("If the player's format should be decided by their primary group only")
private Boolean primaryGroupOnly;
@Setting
@Comment("The message that's sent when switching to this channel")
private String switchMessage;
@Setting
@Comment("The message that's sent when forcing other players to switch to this channel")
private String switchOtherMessage;
@Setting
@Comment("The message that's sent when you're unable to switch to a channel")
private String switchFailureMessage;
@Setting
@Comment("The message that's sent when you are now able to see messages in a channel")
private String toggleOnMessage;
@Setting
@Comment("The message that's sent when you can no longer see messages in a channel")
private String toggleOffMessage;
@Setting
@Comment("The message that's sent when you toggle another player's channel visibility on")
private String toggleOtherOnMessage;
@Setting
@Comment("The message that's sent when you toggle another player's channel visibility off")
private String toggleOtherOffMessage;
@Setting
@Comment("The message that's sent when you cannot speak in a channel")
private String cannotUseMessage;
@Setting
@Comment("The message that's sent when you attempt to ignore a channel but are unable to do so")
private String cannotIgnoreMessage;
@Setting
@Comment("The order in which colors are chosen for the <color> tag.\n" +
"Options:\n" +
" PLAYER: The color the player has set with /setcolor\n" +
" CUSTOM: The color the player has set with /setchannelcolor\n" +
" CHANNEL: The color the channel has set in its settings")
private List<@NonNull ColorPriority> colorPriorities = ImmutableList.of(
ColorPriority.PLAYER, ColorPriority.CUSTOM, ColorPriority.CHANNEL);
private @NonNull SharedChannelOptions defaultOptions() {
return CarbonChatProvider.carbonChat().channelSettings().defaultChannelOptions();
}
public static ChannelOptions defaultChannel() {
final ChannelOptions settings = new ChannelOptions();
settings.key = "global";
settings.isDefault = true;
settings.name = "Global";
settings.color = "#FFFFFF";
settings.defaultFormatName = "default";
settings.formats = Collections.singletonMap("default", "<color><<displayname><reset><color>> <message>");
settings.aliases = Lists.newArrayList("global", "g");
settings.contexts = Collections.singletonMap("distance", new Context("filter", "true"));
return settings;
}
public @NonNull String key() {
return this.key;
}
public @NonNull String color() {
if (this.color == null) {
return this.defaultOptions().color();
}
return this.color;
}
public @Nullable Context context(final @NonNull String key) {
final Context localContext;
if (this.contexts != null) {
localContext = this.contexts.get(key);
} else {
localContext = null;
}
if (localContext == null) {
return this.defaultOptions().contexts().get(key);
}
return localContext;
}
public @NonNull Map<String, Context> contexts() {
if (this.contexts == null) {
return this.defaultOptions().contexts();
}
return this.contexts;
}
public @NonNull Map<String, Context> contextsAndDefault() {
if (this.contexts == null) {
return this.defaultOptions().contexts();
}
final Map<String, Context> contexts = new HashMap<>(this.defaultOptions().contexts());
if (this.contexts != null) {
contexts.putAll(this.contexts);
}
return contexts;
}
public @Nullable String format(final @NonNull String key) {
final String localFormat = this.formats().get(key);
if (localFormat == null) {
return this.defaultOptions().formats().get(key);
}
return localFormat;
}
public @NonNull Map<@NonNull String, @NonNull String> formats() {
if (this.formats == null) {
return this.defaultOptions().formats();
}
return this.formats;
}
public @NonNull Map<@NonNull String, @NonNull String> formatsAndDefault() {
if (this.formats == null) {
return this.defaultOptions().formats();
}
final Map<String, String> formats = new HashMap<>(this.defaultOptions().formats());
if (this.formats != null) {
formats.putAll(this.formats);
}
return formats;
}
public @NonNull String defaultFormatName() {
if (this.defaultFormatName == null || this.defaultFormatName.isEmpty()) {
return this.defaultOptions().defaultFormatName();
}
return this.defaultFormatName;
}
public boolean isDefault() {
return this.isDefault;
}
public Boolean ignorable() {
if (this.ignorable == null) {
return this.defaultOptions().ignorable();
}
return this.ignorable;
}
public Boolean crossServer() {
if (this.crossServer == null) {
return this.defaultOptions().crossServer();
}
return this.crossServer;
}
public Boolean honorsRecipientList() {
if (this.honorsRecipientList == null) {
return this.defaultOptions().honorsRecipientList();
}
return this.honorsRecipientList;
}
public Boolean permissionGroupMatching() {
if (this.permissionGroupMatching == null) {
return this.defaultOptions().permissionGroupMatching();
}
return this.permissionGroupMatching;
}
public @NonNull List<@NonNull String> groupOverrides() {
if (this.groupOverrides == null || this.groupOverrides.isEmpty()) {
return this.defaultOptions().groupOverrides();
}
return this.groupOverrides;
}
public @NonNull String name() {
if (this.name == null) {
return this.key;
}
return this.name;
}
public @Nullable String messagePrefix() {
return this.messagePrefix;
}
public @NonNull String switchMessage() {
if (this.switchMessage == null) {
return this.defaultOptions().switchMessage();
}
return this.switchMessage;
}
public @NonNull String switchOtherMessage() {
if (this.switchOtherMessage == null) {
return this.defaultOptions().switchOtherMessage();
}
return this.switchOtherMessage;
}
public @NonNull String switchFailureMessage() {
if (this.switchFailureMessage == null) {
return this.defaultOptions().switchFailureMessage();
}
return this.switchFailureMessage;
}
public @NonNull String cannotIgnoreMessage() {
if (this.cannotIgnoreMessage == null) {
return this.defaultOptions().cannotIgnoreMessage();
}
return this.cannotIgnoreMessage;
}
public @NonNull String toggleOffMessage() {
if (this.toggleOffMessage == null) {
return this.defaultOptions().toggleOffMessage();
}
return this.toggleOffMessage;
}
public @NonNull String toggleOnMessage() {
if (this.toggleOnMessage == null) {
return this.defaultOptions().toggleOnMessage();
}
return this.toggleOnMessage;
}
public @NonNull String toggleOtherOnMessage() {
if (this.toggleOtherOnMessage == null) {
return this.defaultOptions().toggleOtherOnMessage();
}
return this.toggleOtherOnMessage;
}
public @NonNull String toggleOtherOffMessage() {
if (this.toggleOtherOffMessage == null) {
return this.defaultOptions().toggleOtherOffMessage();
}
return this.toggleOtherOffMessage;
}
public @NonNull String cannotUseMessage() {
if (this.cannotUseMessage == null) {
return this.defaultOptions().cannotUseMessage();
}
return this.cannotUseMessage;
}
public Boolean primaryGroupOnly() {
if (this.primaryGroupOnly == null) {
return this.defaultOptions().primaryGroupOnly();
}
return this.primaryGroupOnly;
}
public Boolean shouldCancelChatEvent() {
if (this.shouldCancelChatEvent == null) {
return this.defaultOptions().shouldCancelChatEvent();
}
return this.shouldCancelChatEvent;
}
public List<ColorPriority> colorPriorities() {
if (this.colorPriorities == null) {
return this.defaultOptions().colorPriorities();
}
return this.colorPriorities;
}
public @NonNull List<String> aliases() {
return this.aliases;
}
}
@@ -1,58 +0,0 @@
package net.draycia.carbon.api.config;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public final class ChannelPings {
@Setting
@Comment("Determines if this feature is enabled")
private boolean enabled = true;
@Setting
@Comment("The text that pings must begin with. A prefix of '@' means you have to type '@Player' to ping Player")
private @NonNull String prefix = "";
@Setting
@Comment("If player names are case sensitive, if true you must type Player to ping Player, 'player' will not work")
private boolean caseSensitive = false;
@Setting
@Comment("The sound played to the pinged player")
private @NonNull Sound sound = Sound.sound(
Key.key(Key.MINECRAFT_NAMESPACE, "entity.experience_orb.pickup"),
Sound.Source.PLAYER,
10.0F,
1.0F
);
@Setting
@Comment("The way players will see the ping")
private @NonNull String display = "<bold><red><ping></red><bold>";
public boolean enabled() {
return this.enabled;
}
public String prefix() {
return this.prefix;
}
public boolean caseSensitive() {
return this.caseSensitive;
}
public Sound sound() {
return this.sound;
}
public String display() {
return this.display;
}
}
@@ -1,68 +0,0 @@
package net.draycia.carbon.api.config;
import com.google.common.collect.ImmutableMap;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import org.spongepowered.configurate.serialize.SerializationException;
import java.util.Collections;
import java.util.Map;
@ConfigSerializable
public final class ChannelSettings {
private static final ObjectMapper<ChannelSettings> MAPPER;
static {
try {
MAPPER = ObjectMapper.factory().get(ChannelSettings.class);
} catch (final SerializationException e) {
throw new ExceptionInInitializerError(e);
}
}
public static ChannelSettings loadFrom(final CommentedConfigurationNode node) throws SerializationException {
return MAPPER.load(node);
}
public void saveTo(final CommentedConfigurationNode node) throws SerializationException {
MAPPER.save(this, node);
}
@Setting
@Comment("All options here act like the defaults for all channels.\n" +
"Adding any of these options to any channel overrides the relevant defaults.")
private SharedChannelOptions sharedChannelOptions = new SharedChannelOptions();
@Setting
private Map<@NonNull String, @NonNull ChannelOptions> channelOptions =
Collections.singletonMap("global", ChannelOptions.defaultChannel());
@Setting
@Comment("Used for message formats - custom tags that are replaced in descending order" +
"\nFor example, in the default config, <group> wil be replaced with <green>%vault_group%")
private @NonNull Map<@NonNull String, @NonNull String> customPlaceholders =
ImmutableMap.of("prefix", "<gray>[<group><gray>]", "group", "<green>%vault_group%");
public SharedChannelOptions defaultChannelOptions() {
return this.sharedChannelOptions;
}
public Map<String, ChannelOptions> channelOptions() {
return this.channelOptions;
}
public Map<String, String> customPlaceholders() {
return this.customPlaceholders;
}
public @Nullable ChannelOptions channelOptions(final @NonNull String name) {
return this.channelOptions.get(name);
}
}
@@ -1,7 +0,0 @@
package net.draycia.carbon.api.config;
public enum ColorPriority {
PLAYER,
CUSTOM,
CHANNEL
}
@@ -1,31 +0,0 @@
package net.draycia.carbon.api.config;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public final class ContextMessages {
@Setting private @NonNull String vaultBalanceNotEnough = "<red>You do not have enough balance, required: <balance><red>.";
@Setting private @NonNull String vaultCostNotEnough = "<red>You do not have enough balance, cost: <balance><red>.";
@Setting private @NonNull String mcmmoPartyNotInParty = "<red>You are not in a party!";
@Setting private @NonNull String townyTownNotInTown = "<red>You are not in a town!";
public String vaultBalanceNotEnough() {
return this.vaultBalanceNotEnough;
}
public String vaultCostNotEnough() {
return this.vaultCostNotEnough;
}
public String mcmmoPartyNotInParty() {
return this.mcmmoPartyNotInParty;
}
public String townyTownNotInTown() {
return this.townyTownNotInTown;
}
}
@@ -1,26 +0,0 @@
package net.draycia.carbon.api.config;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public final class ExceptionMessages {
@Setting private @NonNull String channelNotFound = "Channel not found!";
@Setting private @NonNull String channelNotPublic = "Channel is not public!";
@Setting private @NonNull String playerNotFound = "Player not found!";
public String channelNotFound() {
return this.channelNotFound;
}
public String channelNotPublic() {
return this.channelNotPublic;
}
public String playerNotFound() {
return this.playerNotFound;
}
}
@@ -1,7 +0,0 @@
package net.draycia.carbon.api.config;
public enum MessagingType {
NONE,
REDIS,
BUNGEECORD
}
@@ -1,158 +0,0 @@
package net.draycia.carbon.api.config;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import org.spongepowered.configurate.serialize.SerializationException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
@ConfigSerializable
public final class ModerationSettings {
private static final ObjectMapper<ModerationSettings> MAPPER;
static {
try {
MAPPER = ObjectMapper.factory().get(ModerationSettings.class);
} catch (final SerializationException e) {
throw new ExceptionInInitializerError(e);
}
}
public static ModerationSettings loadFrom(final CommentedConfigurationNode node) throws SerializationException {
return MAPPER.load(node);
}
public void saveTo(final CommentedConfigurationNode node) throws SerializationException {
MAPPER.save(this, node);
}
@Setting
@Comment("The text that's prepended to someone else's shadowmuted messages.")
private String shadowMutePrefix = "[SM] ";
public String shadowMutePrefix() {
return this.shadowMutePrefix;
}
@Setting
@Comment("If true, muted users will be unable to use /whisper /msg")
private boolean muteStopsWhispers = true;
public boolean muteStopsWhispers() {
return this.muteStopsWhispers;
}
@Setting
private ClearChat clearChat = new ClearChat();
public ClearChat clearChat() {
return this.clearChat;
}
@ConfigSerializable
public static class ClearChat {
@Setting
@Comment("The message sent to clear chat, you probably want to leave this blank")
private String message = "";
@Setting
@Comment("How many messages will be sent in order to clear chat")
private int messageCount = 100;
public String message() {
return this.message;
}
public int messageCount() {
return this.messageCount;
}
}
@Setting
private CapsProtection capsProtection = new CapsProtection();
public CapsProtection capsProtection() {
return this.capsProtection;
}
@ConfigSerializable
public static class CapsProtection {
@Setting
@Comment("If caps protection is enabled")
private boolean enabled = true;
@Setting
@Comment("The minimum message length for caps protection to activate")
private int minimumLength = 10;
@Setting
@Comment("The amount of letters in the message for it to trigger the protection")
private float percentCaps = 0.80F;
@Setting
@Comment("If true, stops message from sending. If false, simply changes the message to lowercase")
private boolean blockMessage = false;
public boolean enabled() {
return this.enabled;
}
public int minimumLength() {
return this.minimumLength;
}
public float percentCaps() {
return this.percentCaps;
}
public boolean blockMessage() {
return this.blockMessage;
}
}
@Setting
private Filters filters = new Filters();
public Filters filters() {
return this.filters;
}
@ConfigSerializable
public static class Filters {
@Setting
private boolean enabled = true;
@Setting
@Comment("The keys (\"****\" for example) are what the text is replaced with.\n" +
"The strings in the lists (\"lag\" etc) are what's replaced.\n" +
"Set to filters: {} if you want to disable the filter feature.\n" +
"Set the key to \"_\" for the replacement to be blank (remove the filtered pattern).")
private Map<String, List<Pattern>> replacements =
Collections.singletonMap("****", Collections.singletonList(Pattern.compile("la[g]+")));
@Setting
@Comment("Anything in blocked-words will prevent the message from being sent at all.\n" +
"Set to blocked-patterns: [] if you want to disable the blocked words feature.")
private List<Pattern> blockedPatterns = Collections.singletonList(Pattern.compile("pineapple doesn't belong on pizza"));
public boolean enabled() {
return this.enabled;
}
public Map<String, List<Pattern>> replacements() {
return this.replacements;
}
public List<Pattern> blockedPatterns() {
return this.blockedPatterns;
}
}
}
@@ -1,32 +0,0 @@
package net.draycia.carbon.api.config;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public final class RedisCredentials {
@Setting private @NonNull String host = "localhost";
@Setting private @Nullable String password = "";
@Setting private int port = 6379;
@Setting private @Nullable Integer database = null;
public @NonNull String host() {
return this.host;
}
public @Nullable String password() {
return this.password;
}
public int port() {
return this.port;
}
public @Nullable Integer database() {
return this.database;
}
}
@@ -1,36 +0,0 @@
package net.draycia.carbon.api.config;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public final class SQLCredentials {
@Setting private @NonNull String username = "username";
@Setting private @NonNull String password = "password";
@Setting private @NonNull String database = "database";
@Setting private @NonNull String host = "host";
@Setting private int port = 3306;
public @NonNull String username() {
return this.username;
}
public @NonNull String password() {
return this.password;
}
public @NonNull String database() {
return this.database;
}
public @NonNull String host() {
return this.host;
}
public int port() {
return this.port;
}
}
@@ -1,124 +0,0 @@
package net.draycia.carbon.api.config;
import com.google.common.collect.ImmutableMap;
import net.draycia.carbon.api.Context;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ConfigSerializable
public final class SharedChannelOptions {
@Setting private @NonNull String color = "#FFFFFF";
@Setting private @NonNull Map<String, Context> contexts = new HashMap<>();
@Setting private @NonNull Map<@NonNull String, @NonNull String> formats =
ImmutableMap.of("default", "<color><<displayname><reset><color>> <message>",
"staff", "<#00CED1>[Staff] <color><<displayname><reset><color>> <message>");
@Setting private @NonNull String defaultFormatName = "default";
@Setting private boolean ignorable = true;
@Setting private boolean crossServer = true;
@Setting private boolean honorsRecipientList = false;
@Setting private boolean permissionGroupMatching = false;
@Setting private @NonNull List<String> groupOverrides = new ArrayList<>();
@Setting private boolean shouldCancelChatEvent = false;
@Setting private boolean primaryGroupOnly = false;
@Setting private @NonNull String switchMessage = "<gray>You are now in <color><channel> <gray>chat!";
@Setting private @NonNull String switchOtherMessage = "<gray><player> <reset><gray>is now in <color><channel> <gray>chat!";
@Setting private @NonNull String switchFailureMessage = "<red>You cannot use channel <channel>!";
@Setting private @NonNull String toggleOnMessage = "<gray>You can now see <color><channel> <gray>chat!";
@Setting private @NonNull String toggleOffMessage = "<gray>You can no longer see <color><channel> <gray>chat!";
@Setting private @NonNull String toggleOtherOnMessage = "<gray><player> <reset><gray>can now see <color><channel> <gray>chat!";
@Setting private @NonNull String toggleOtherOffMessage = "<gray><player> <reset><gray>can no longer see <color><channel> <gray>chat!";
@Setting private @NonNull String cannotUseMessage = "You cannot use that channel!";
@Setting private @NonNull String cannotIgnoreMessage = "<red>You cannot ignore that channel!";
@Setting private @NonNull List<@NonNull ColorPriority> colorPriorities = new ArrayList<>();
public @NonNull String color() {
return this.color;
}
public @NonNull Map<String, Context> contexts() {
return this.contexts;
}
public @NonNull Map<String, String> formats() {
return this.formats;
}
public @NonNull String defaultFormatName() {
return this.defaultFormatName;
}
public boolean ignorable() {
return this.ignorable;
}
public boolean crossServer() {
return this.crossServer;
}
public boolean honorsRecipientList() {
return this.honorsRecipientList;
}
public boolean permissionGroupMatching() {
return this.permissionGroupMatching;
}
public @NonNull List<@NonNull String> groupOverrides() {
return this.groupOverrides;
}
public @NonNull String switchMessage() {
return this.switchMessage;
}
public @NonNull String switchOtherMessage() {
return this.switchOtherMessage;
}
public @NonNull String switchFailureMessage() {
return this.switchFailureMessage;
}
public @NonNull String cannotIgnoreMessage() {
return this.cannotIgnoreMessage;
}
public @NonNull String toggleOffMessage() {
return this.toggleOffMessage;
}
public @NonNull String toggleOnMessage() {
return this.toggleOnMessage;
}
public @NonNull String toggleOtherOnMessage() {
return this.toggleOtherOnMessage;
}
public @NonNull String toggleOtherOffMessage() {
return this.toggleOtherOffMessage;
}
public @NonNull String cannotUseMessage() {
return this.cannotUseMessage;
}
public boolean primaryGroupOnly() {
return this.primaryGroupOnly;
}
public boolean shouldCancelChatEvent() {
return this.shouldCancelChatEvent;
}
public @NonNull List<@NonNull ColorPriority> colorPriorities() {
return this.colorPriorities;
}
}
@@ -1,6 +0,0 @@
package net.draycia.carbon.api.config;
public enum StorageType {
MYSQL,
JSON
}
@@ -1,156 +0,0 @@
package net.draycia.carbon.api.config;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public final class WhisperOptions {
@Setting
@Comment("Plays a sound when receiving private messages with /whisper /msg")
private @NonNull WhisperPings pings = new WhisperPings();
@Setting
@Comment("If enabled, players will be able to whisper other players as if they had their own private channel, " +
"without the need to type /r or /msg each message. /msg [player]")
private boolean useEnhancedWhispers = false;
@Setting
@Comment("")
private @NonNull String switchMessage = "<gray>You are now in <color><channel> <gray>chat!";
@Setting
@Comment("")
private @NonNull String switchOtherMessage = "<gray><player> <reset><gray>is now in <color><channel> <gray>chat!";
@Setting
@Comment("")
private @NonNull String switchFailureMessage = "<red>You cannot use channel <channel>!";
@Setting
@Comment("")
private @NonNull String toggleOnMessage = "<gray>You can now see <color><channel> <gray>chat!";
@Setting
@Comment("")
private @NonNull String toggleOffMessage = "<gray>You can no longer see <color><channel> <gray>chat!";
@Setting
@Comment("")
private @NonNull String toggleOtherOnMessage = "<gray><player> <reset><gray>can now see <color><channel> <gray>chat!";
@Setting
@Comment("")
private @NonNull String toggleOtherOffMessage = "<gray><player> <reset><gray>can no longer see <color><channel> <gray>chat!";
@Setting
@Comment("")
private @NonNull String cannotUseMessage = "You cannot use that channel!";
@Setting
@Comment("")
private @NonNull String cannotIgnoreMessage = "<red>You cannot ignore that channel!";
@Setting
@Comment("")
private @NonNull String senderFormat = "<gold>[<white>Me <gray>-> <white><receiver><gold>] <message>";
@Setting
@Comment("")
private @NonNull String receiverFormat = "<gold>[<white><sender> <gray>-> <white>Me<gold>] <message>";
@Setting
@Comment("")
private @NonNull String consoleFormat = "<gold>[<white><sender> <gray>-> <white><receiver><gold>] <message>";
@Setting
@Comment("")
private @NonNull String nowWhisperingPlayer = "<white>You are now whispering <green><player><white>!";
@Setting
@Comment("The message that's sent when attempting to message someone when you have whispers toggled off.")
private @NonNull String senderToggledOff = "<red>You have whispers toggled off!";
@Setting
@Comment("The message that's sent when attempting to message someone who has whispers toggled off.")
private @NonNull String receiverToggledOff = "<red><receiver> <red>has whispers toggled off!";
@Setting
@Comment("")
private boolean logToConsole = true;
public boolean logToConsole() {
return this.logToConsole;
}
public @NonNull WhisperPings pings() {
return this.pings;
}
public boolean useEnhancedWhispers() {
return this.useEnhancedWhispers;
}
public @NonNull String consoleFormat() {
return this.consoleFormat;
}
public @NonNull String senderFormat() {
return this.senderFormat;
}
public @NonNull String receiverFormat() {
return this.receiverFormat;
}
public @NonNull String switchMessage() {
return this.switchMessage;
}
public @NonNull String switchOtherMessage() {
return this.switchOtherMessage;
}
public @NonNull String switchFailureMessage() {
return this.switchFailureMessage;
}
public @NonNull String cannotIgnoreMessage() {
return this.cannotIgnoreMessage;
}
public @NonNull String toggleOffMessage() {
return this.toggleOffMessage;
}
public @NonNull String toggleOnMessage() {
return this.toggleOnMessage;
}
public @NonNull String toggleOtherOnMessage() {
return this.toggleOtherOnMessage;
}
public @NonNull String toggleOtherOffMessage() {
return this.toggleOtherOffMessage;
}
public @NonNull String cannotUseMessage() {
return this.cannotUseMessage;
}
public @NonNull String nowWhisperingPlayer() {
return this.nowWhisperingPlayer;
}
public @NonNull String senderToggledOff() {
return this.senderToggledOff;
}
public @NonNull String receiverToggledOff() {
return this.receiverToggledOff;
}
}
@@ -1,29 +0,0 @@
package net.draycia.carbon.api.config;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public final class WhisperPings {
@Setting private boolean enabled = true;
@Setting private @NonNull Sound sound = Sound.sound(
Key.key(Key.MINECRAFT_NAMESPACE, "entity.experience_orb.pickup"),
Sound.Source.PLAYER,
10.0F,
1.0F
);
public boolean enabled() {
return this.enabled;
}
public Sound sound() {
return this.sound;
}
}
@@ -1,28 +0,0 @@
package net.draycia.carbon.api.events;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.misc.CarbonEvent;
import net.kyori.registry.Registry;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
public class ChannelRegisterEvent implements CarbonEvent {
private final @NonNull List<@NonNull ChatChannel> registeredChannels;
private final @NonNull Registry<String, ChatChannel> registry;
public ChannelRegisterEvent(final @NonNull List<@NonNull ChatChannel> registeredChannels, final @NonNull Registry<String, ChatChannel> registry) {
this.registeredChannels = registeredChannels;
this.registry = registry;
}
public void register(final @NonNull ChatChannel chatChannel) {
this.registry.register(chatChannel.key(), chatChannel);
}
public @NonNull List<@NonNull ChatChannel> registeredChannels() {
return this.registeredChannels;
}
}
@@ -1,48 +0,0 @@
package net.draycia.carbon.api.events;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.misc.CarbonEvent;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.Cancellable;
import org.checkerframework.checker.nullness.qual.NonNull;
public class ChannelSwitchEvent implements CarbonEvent, Cancellable {
private final @NonNull ChatChannel channel;
private final @NonNull PlayerUser user;
private @NonNull String failureMessage;
private boolean cancelled = false;
public ChannelSwitchEvent(final @NonNull ChatChannel channel, final @NonNull PlayerUser user, final @NonNull String failureMessage) {
this.channel = channel;
this.user = user;
this.failureMessage = failureMessage;
}
public @NonNull PlayerUser user() {
return this.user;
}
public @NonNull ChatChannel channel() {
return this.channel;
}
public @NonNull String failureMessage() {
return this.failureMessage;
}
public void failureMessage(final @NonNull String failureMessage) {
this.failureMessage = failureMessage;
}
@Override
public boolean cancelled() {
return this.cancelled;
}
@Override
public void cancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
}
@@ -1,70 +0,0 @@
package net.draycia.carbon.api.events;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.misc.CarbonEvent;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.text.TextComponent;
import net.kyori.event.Cancellable;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public class ChatComponentEvent implements CarbonEvent, Cancellable {
private boolean isCancelled = false;
private final @NonNull PlayerUser sender;
private final @Nullable CarbonUser target;
private @NonNull ChatChannel chatChannel;
private @NonNull TextComponent component;
private final @NonNull String originalMessage;
public ChatComponentEvent(final @NonNull PlayerUser sender, final @Nullable CarbonUser target,
final @NonNull ChatChannel chatChannel, final @NonNull TextComponent component,
final @NonNull String originalMessage) {
this.sender = sender;
this.target = target;
this.chatChannel = chatChannel;
this.component = component;
this.originalMessage = originalMessage;
}
@Override
public boolean cancelled() {
return this.isCancelled;
}
@Override
public void cancelled(final boolean cancelled) {
this.isCancelled = cancelled;
}
public @NonNull PlayerUser sender() {
return this.sender;
}
public @Nullable CarbonUser target() {
return this.target;
}
public @NonNull ChatChannel channel() {
return this.chatChannel;
}
public void channel(final @NonNull ChatChannel chatChannel) {
this.chatChannel = chatChannel;
}
public @NonNull TextComponent component() {
return this.component;
}
public void component(final @NonNull TextComponent component) {
this.component = component;
}
public @NonNull String originalMessage() {
return this.originalMessage;
}
}
@@ -1,74 +0,0 @@
package net.draycia.carbon.api.events;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.misc.CarbonEvent;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.Cancellable;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public class ChatFormatEvent implements CarbonEvent, Cancellable {
private boolean isCancelled = false;
private final @NonNull PlayerUser sender;
private final @Nullable CarbonUser target;
private @NonNull ChatChannel chatChannel;
private @NonNull String format;
private @NonNull String message;
public ChatFormatEvent(final @NonNull PlayerUser sender, final @Nullable CarbonUser target,
final @NonNull ChatChannel chatChannel, final @NonNull String format,
final @NonNull String message) {
this.sender = sender;
this.target = target;
this.chatChannel = chatChannel;
this.format = format;
this.message = message;
}
@Override
public boolean cancelled() {
return this.isCancelled;
}
@Override
public void cancelled(final boolean cancelled) {
this.isCancelled = cancelled;
}
public @NonNull PlayerUser sender() {
return this.sender;
}
public @Nullable CarbonUser target() {
return this.target;
}
public @NonNull ChatChannel channel() {
return this.chatChannel;
}
public void channel(final @NonNull ChatChannel chatChannel) {
this.chatChannel = chatChannel;
}
public @NonNull String format() {
return this.format;
}
public void format(final @NonNull String format) {
this.format = format;
}
public @NonNull String message() {
return this.message;
}
public void message(final @NonNull String message) {
this.message = message;
}
}
@@ -1,44 +0,0 @@
package net.draycia.carbon.api.events;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.Context;
import net.draycia.carbon.api.events.misc.CarbonEvent;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.Cancellable;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public class MessageContextEvent implements CarbonEvent, Cancellable {
private final @NonNull TextChannel channel;
private final @NonNull PlayerUser user;
private boolean cancelled = false;
public MessageContextEvent(final @NonNull TextChannel channel, final @NonNull PlayerUser user) {
this.channel = channel;
this.user = user;
}
@Override
public boolean cancelled() {
return this.cancelled;
}
@Override
public void cancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
public @Nullable Context context(final @NonNull String key) {
return this.channel.context(key);
}
public @NonNull TextChannel channel() {
return this.channel;
}
public @NonNull PlayerUser user() {
return this.user;
}
}
@@ -1,64 +0,0 @@
package net.draycia.carbon.api.events;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.misc.CarbonEvent;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.Cancellable;
import org.checkerframework.checker.nullness.qual.NonNull;
public class PreChatFormatEvent implements CarbonEvent, Cancellable {
private boolean isCancelled = false;
private final @NonNull PlayerUser user;
private @NonNull ChatChannel chatChannel;
private @NonNull String format;
private @NonNull String message;
public PreChatFormatEvent(final @NonNull PlayerUser user, final @NonNull ChatChannel chatChannel,
final @NonNull String format, final @NonNull String message) {
this.user = user;
this.chatChannel = chatChannel;
this.format = format;
this.message = message;
}
@Override
public boolean cancelled() {
return this.isCancelled;
}
@Override
public void cancelled(final boolean cancelled) {
this.isCancelled = cancelled;
}
public @NonNull PlayerUser user() {
return this.user;
}
public @NonNull ChatChannel channel() {
return this.chatChannel;
}
public void channel(final @NonNull ChatChannel chatChannel) {
this.chatChannel = chatChannel;
}
public @NonNull String format() {
return this.format;
}
public void format(final @NonNull String format) {
this.format = format;
}
public @NonNull String message() {
return this.message;
}
public void message(final @NonNull String message) {
this.message = message;
}
}
@@ -1,59 +0,0 @@
package net.draycia.carbon.api.events;
import net.draycia.carbon.api.events.misc.CarbonEvent;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.text.Component;
import net.kyori.event.Cancellable;
import org.checkerframework.checker.nullness.qual.NonNull;
public class PrivateMessageEvent implements CarbonEvent, Cancellable {
private final @NonNull PlayerUser sender;
private final @NonNull PlayerUser target;
private final @NonNull Component senderComponent;
private final @NonNull Component targetComponent;
private final @NonNull String message;
private boolean cancelled = false;
public PrivateMessageEvent(final @NonNull PlayerUser sender, final @NonNull PlayerUser target,
final @NonNull Component senderComponent, final @NonNull Component targetComponent,
final @NonNull String message) {
this.sender = sender;
this.target = target;
this.senderComponent = senderComponent;
this.targetComponent = targetComponent;
this.message = message;
}
@Override
public boolean cancelled() {
return this.cancelled;
}
@Override
public void cancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
public @NonNull PlayerUser sender() {
return this.sender;
}
public @NonNull PlayerUser target() {
return this.target;
}
public @NonNull Component senderComponent() {
return this.senderComponent;
}
public @NonNull Component targetComponent() {
return this.targetComponent;
}
public @NonNull String message() {
return this.message;
}
}
@@ -1,51 +0,0 @@
package net.draycia.carbon.api.events;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.Context;
import net.draycia.carbon.api.events.misc.CarbonEvent;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.Cancellable;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public class ReceiverContextEvent implements CarbonEvent, Cancellable {
private final @NonNull TextChannel channel;
private final @NonNull PlayerUser sender;
private final @NonNull PlayerUser recipient;
private boolean cancelled = false;
public ReceiverContextEvent(final @NonNull TextChannel channel, final @NonNull PlayerUser sender,
final @NonNull PlayerUser recipient) {
this.channel = channel;
this.sender = sender;
this.recipient = recipient;
}
public @Nullable Context context(final @NonNull String key) {
return this.channel.context(key);
}
@Override
public boolean cancelled() {
return this.cancelled;
}
@Override
public void cancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
public @NonNull TextChannel channel() {
return this.channel;
}
public @NonNull PlayerUser sender() {
return this.sender;
}
public @NonNull PlayerUser recipient() {
return this.recipient;
}
}
@@ -1,43 +0,0 @@
package net.draycia.carbon.api.events;
import net.draycia.carbon.api.events.misc.CarbonEvent;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.Cancellable;
import org.checkerframework.checker.nullness.qual.NonNull;
public class UserEvent implements CarbonEvent, Cancellable {
private final @NonNull PlayerUser user;
private boolean cancelled = false;
public UserEvent(final @NonNull PlayerUser user) {
this.user = user;
}
public @NonNull PlayerUser user() {
return this.user;
}
@Override
public boolean cancelled() {
return this.cancelled;
}
@Override
public void cancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
public static class Join extends UserEvent {
public Join(final @NonNull PlayerUser user) {
super(user);
}
}
public static class Leave extends UserEvent {
public Leave(final @NonNull PlayerUser user) {
super(user);
}
}
}
@@ -1,5 +0,0 @@
package net.draycia.carbon.api.events.misc;
public interface CarbonEvent {
}
@@ -1,48 +0,0 @@
package net.draycia.carbon.api.events.misc;
import net.kyori.event.EventSubscriber;
import net.kyori.event.PostResult;
import net.kyori.event.SimpleEventBus;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.function.Consumer;
public final class CarbonEvents {
private CarbonEvents() {
}
private static final SimpleEventBus<CarbonEvent> EVENT_BUS = new SimpleEventBus<>(CarbonEvent.class);
public static <T extends CarbonEvent> void register(final @NonNull Class<T> clazz, final @NonNull EventSubscriber<T> subscriber) {
EVENT_BUS.register(clazz, subscriber);
}
public static <T extends CarbonEvent> void register(final @NonNull Class<T> clazz, final int priority, final boolean consumeCancelled, final @NonNull Consumer<T> consumer) {
EVENT_BUS.register(clazz, new EventSubscriber<T>() {
@Override
public int postOrder() {
return priority;
}
@Override
public boolean consumeCancelledEvents() {
return consumeCancelled;
}
@Override
public void invoke(final @NonNull T event) {
consumer.accept(event);
}
});
}
public static void unregister(final @NonNull EventSubscriber<? super CarbonEvent> subscriber) {
EVENT_BUS.unregister(subscriber);
}
public static PostResult post(final @NonNull CarbonEvent event) {
return EVENT_BUS.post(event);
}
}
@@ -1,22 +0,0 @@
package net.draycia.carbon.api.messaging;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
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 interface MessageService {
void registerUserMessageListener(final @NonNull String key, final @NonNull BiConsumer<@NonNull PlayerUser, @NonNull ByteArrayDataInput> listener);
void registerUUIDMessageListener(final @NonNull String key, final @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener);
void unregisterMessageListener(final @NonNull String key);
void sendMessage(final @NonNull String key, final @NonNull UUID uuid, final @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer);
}
@@ -1,13 +0,0 @@
package net.draycia.carbon.api.users;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.identity.Identified;
import org.checkerframework.checker.nullness.qual.NonNull;
public interface CarbonUser extends Audience, Identified {
boolean hasPermission(@NonNull String permission);
@NonNull String name();
}
@@ -1,4 +0,0 @@
package net.draycia.carbon.api.users;
public interface ConsoleUser extends CarbonUser {
}
@@ -1,126 +0,0 @@
package net.draycia.carbon.api.users;
import net.draycia.carbon.api.channels.ChatChannel;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.format.TextColor;
import net.luckperms.api.model.group.Group;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
public interface PlayerUser extends CarbonUser {
@NonNull UUID uuid();
boolean online();
@NonNull String nickname();
void nickname(@Nullable String nickname);
@NonNull String displayName();
void displayName(@Nullable String displayName);
@NonNull String name();
@Nullable TextColor customChatColor();
void customChatColor(@Nullable TextColor customChatColor);
@NonNull String parsePlaceholders(@NonNull String input);
@NonNull UserChannelSettings channelSettings(@NonNull ChatChannel channel);
@NonNull Map<@NonNull String, @NonNull ? extends UserChannelSettings> channelSettings();
boolean spyingWhispers();
void spyingWhispers(boolean spyingWhispers);
boolean muted();
void muted(boolean muted);
boolean shadowMuted();
void shadowMuted(boolean shadowMuted);
@Nullable UUID replyTarget();
default void replyTarget(final @Nullable PlayerUser user) {
if (user == null) {
this.replyTarget((UUID) null);
} else {
this.replyTarget(user.uuid());
}
}
void replyTarget(@Nullable UUID target);
boolean ignoringUser(@NonNull UUID uuid);
void ignoringUser(@NonNull UUID uuid, boolean ignoring);
default boolean ignoringUser(final @NonNull PlayerUser user) {
return this.ignoringUser(user.uuid());
}
default void ignoringUser(final @NonNull PlayerUser user, boolean ignoring) {
this.ignoringUser(user.uuid(), ignoring);
}
@NonNull Iterable<CarbonUser> ignoredChatUsers();
@NonNull Iterable<UUID> ignoredUsers();
boolean hasGroup(@NonNull String group);
boolean hasGroup(@NonNull Group group);
@NonNull Collection<@NonNull Group> groups();
@Nullable Group primaryGroup();
void sendMessage(@NonNull PlayerUser sender, @NonNull String message);
@Nullable ChatChannel selectedChannel();
void selectedChannel(@NonNull ChatChannel channel);
void clearSelectedChannel();
@NonNull PingOptions pingOptions();
void pingOptions(@NonNull PingOptions pingOptions);
class PingOptions {
public @Nullable Sound whisperSound;
public @Nullable Sound pingSound;
public PingOptions(final @Nullable Sound whisperSound, final @Nullable Sound pingSound) {
this.whisperSound = whisperSound;
this.pingSound = pingSound;
}
public @Nullable Sound whisperSound() {
return this.whisperSound;
}
public void whisperSound(final @Nullable Sound whisperSound) {
this.whisperSound = whisperSound;
}
public @Nullable Sound pingSound() {
return this.pingSound;
}
public void pingSound(final @Nullable Sound pingSound) {
this.pingSound = pingSound;
}
}
}
@@ -1,21 +0,0 @@
package net.draycia.carbon.api.users;
import net.kyori.adventure.text.format.TextColor;
import org.checkerframework.checker.nullness.qual.Nullable;
public interface UserChannelSettings {
boolean spying();
void spying(boolean spying);
boolean ignored();
void ignoring(boolean ignored);
@Nullable
TextColor color();
void color(@Nullable TextColor color);
}
@@ -1,32 +0,0 @@
package net.draycia.carbon.api.users;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public interface UserService<T extends PlayerUser> {
@Nullable <C extends ConsoleUser> C consoleUser();
@NonNull T wrap(@NonNull UUID uuid);
@NonNull CompletableFuture<T> wrapLater(@NonNull UUID uuid);
@Nullable T wrapIfLoaded(@NonNull UUID uuid);
@Nullable T refreshUser(@NonNull UUID uuid);
void onDisable();
void invalidate(@NonNull T user);
void validate(@NonNull T user);
@NonNull Collection<@NonNull T> onlineUsers();
@NonNull Collection<@NonNull String> proxyPlayers();
}
@@ -1,421 +1,10 @@
package net.draycia.carbon.bukkit;
import cloud.commandframework.CommandManager;
import cloud.commandframework.execution.CommandExecutionCoordinator;
import cloud.commandframework.paper.PaperCommandManager;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.bukkit.listeners.events.ItemLinkHandler;
import net.draycia.carbon.bukkit.listeners.BukkitChatHandler;
import net.draycia.carbon.bukkit.messaging.BungeeMessageService;
import net.draycia.carbon.bukkit.users.BukkitConsoleUser;
import net.draycia.carbon.bukkit.users.BukkitPlayerUser;
import net.draycia.carbon.bukkit.util.BungeeChannelApi;
import net.draycia.carbon.bukkit.util.CarbonPlaceholders;
import net.draycia.carbon.bukkit.util.Metrics;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.config.CarbonTranslations;
import net.draycia.carbon.api.adventure.MessageProcessor;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.commands.settings.CommandSettingsRegistry;
import net.draycia.carbon.api.config.CarbonSettings;
import net.draycia.carbon.api.config.ChannelSettings;
import net.draycia.carbon.api.config.MessagingType;
import net.draycia.carbon.api.config.ModerationSettings;
import net.draycia.carbon.api.config.StorageType;
import net.draycia.carbon.api.messaging.MessageService;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.common.channels.ChannelManager;
import net.draycia.carbon.common.config.ConfigLoader;
import net.draycia.carbon.common.messaging.EmptyMessageService;
import net.draycia.carbon.api.config.SQLCredentials;
import net.draycia.carbon.common.messaging.RedisMessageService;
import net.draycia.carbon.common.listeners.events.CapsHandler;
import net.draycia.carbon.common.listeners.events.CustomPlaceholderHandler;
import net.draycia.carbon.common.listeners.events.IgnoredPlayerHandler;
import net.draycia.carbon.common.listeners.events.LegacyFormatHandler;
import net.draycia.carbon.common.listeners.events.MuteHandler;
import net.draycia.carbon.common.listeners.events.PingHandler;
import net.draycia.carbon.bukkit.listeners.events.PlaceholderHandler;
import net.draycia.carbon.common.listeners.events.PlayerJoinListener;
import net.draycia.carbon.bukkit.listeners.events.RelationalPlaceholderHandler;
import net.draycia.carbon.common.listeners.events.ShadowMuteHandler;
import net.draycia.carbon.common.listeners.events.UrlLinkHandler;
import net.draycia.carbon.common.listeners.events.UserFormattingHandler;
import net.draycia.carbon.common.listeners.events.WhisperPingHandler;
import net.draycia.carbon.common.adventure.AdventureManager;
import net.draycia.carbon.common.commands.misc.CommandRegistrar;
import net.draycia.carbon.common.messaging.MessageManager;
import net.draycia.carbon.api.users.UserService;
import net.draycia.carbon.common.users.JSONUserService;
import net.draycia.carbon.common.users.MySQLUserService;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.text.serializer.craftbukkit.BukkitComponentSerializer;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.messaging.ChannelNotRegisteredException;
import org.bukkit.scheduler.BukkitRunnable;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
@SuppressWarnings("initialization.fields.uninitialized")
public final class CarbonChatBukkit extends JavaPlugin implements CarbonChat {
private static final int BSTATS_PLUGIN_ID = 8720;
private ChannelManager channelManager;
private AdventureManager messageProcessor;
private CommandSettingsRegistry commandSettings;
private ModerationSettings moderationSettings;
private CarbonSettings carbonSettings;
private ChannelSettings channelSettings;
private UserService<BukkitPlayerUser> userService;
private MessageManager messageManager;
private CarbonTranslations translations;
private CommandManager<CarbonUser> commandManager;
private Logger logger;
private @NonNull Collection<@NonNull String> proxyPlayerNames = new ArrayList<>();
public static final LegacyComponentSerializer LEGACY =
LegacyComponentSerializer.builder()
.extractUrls()
.hexColors()
.character('§')
.useUnusualXRepeatedCharacterHexFormat()
.build();
@Override
public void onLoad() {
CarbonChatProvider.register(this);
}
@Override
public void onEnable() {
this.logger = LoggerFactory.getLogger(this.getName());
// Setup metrics
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
this.loadConfigs();
// Setup Adventure
final BukkitAudiences audiences = BukkitAudiences.create(this);
this.messageProcessor = new AdventureManager(audiences);
// Initialize managers
this.channelManager = new ChannelManager(this);
// Handle messaging service
final MessagingType messagingType = this.carbonSettings().messagingType();
final MessageService messageService;
if (messagingType == MessagingType.REDIS) {
messageService = new RedisMessageService(this, this.carbonSettings.redisCredentials());
} else if (messagingType == MessagingType.BUNGEECORD) {
messageService = new BungeeMessageService(this); // TODO: only support this if bukkit
} else {
messageService = new EmptyMessageService();
}
this.messageManager = new MessageManager(this, messageService);
new BukkitRunnable() {
@Override
public void run() {
try {
if (Bukkit.getOnlinePlayers().size() > 0) {
BungeeChannelApi.of(CarbonChatBukkit.this).getPlayerList("ALL")
.thenAccept(value -> CarbonChatBukkit.this.proxyPlayerNames = value);
}
} catch (final ChannelNotRegisteredException exception) {
CarbonChatBukkit.this.logger().info("Exception thrown when gathering proxy player list!");
CarbonChatBukkit.this.logger().info("Aborting attempts to communicate to the proxy.");
CarbonChatBukkit.this.logger().info("This is merely for command completions, don't worry.");
this.cancel();
}
}
}.runTaskTimer(this, 20, 5*20);
// Handle storage service
final StorageType storageType = this.carbonSettings().storageType();
final Supplier<Collection<BukkitPlayerUser>> supplier = () -> {
final List<BukkitPlayerUser> users = new ArrayList<>();
for (final Player player : Bukkit.getOnlinePlayers()) {
users.add(this.userService.wrap(player.getUniqueId()));
}
return users;
};
if (storageType == StorageType.MYSQL) {
this.logger().info("Enabling MySQL storage!");
final SQLCredentials credentials = this.carbonSettings().sqlCredentials();
this.userService = new MySQLUserService<>(this, credentials, supplier, () -> this.proxyPlayerNames,
BukkitPlayerUser::new, BukkitConsoleUser::new);
} else if (storageType == StorageType.JSON) {
this.logger().info("Enabling JSON storage!");
this.userService = new JSONUserService<>(BukkitPlayerUser.class, this, supplier, () -> this.proxyPlayerNames,
BukkitPlayerUser::new, BukkitConsoleUser::new);
} else {
this.logger().error("Invalid storage type selected! Falling back to JSON.");
this.userService = new JSONUserService<>(BukkitPlayerUser.class, this, supplier, () -> this.proxyPlayerNames,
BukkitPlayerUser::new, BukkitConsoleUser::new);
}
// Setup listeners
this.setupCommands();
this.setupListeners();
// Setup PlaceholderAPI placeholders
new CarbonPlaceholders(this).register();
this.logger().info("CarbonChat startup finished! Enjoy :)");
}
@Override
public void onDisable() {
this.userService.onDisable();
}
private void setupListeners() {
final PluginManager pluginManager = this.getServer().getPluginManager();
// Register chat listeners
pluginManager.registerEvents(new BukkitChatHandler(this), this);
new CapsHandler();
new CustomPlaceholderHandler();
new IgnoredPlayerHandler();
new ItemLinkHandler();
new LegacyFormatHandler();
new MuteHandler();
new PingHandler();
new PlaceholderHandler();
new PlayerJoinListener();
new RelationalPlaceholderHandler();
new ShadowMuteHandler();
new UrlLinkHandler();
new UserFormattingHandler();
new WhisperPingHandler();
}
@SuppressWarnings("return.type.incompatible")
private void setupCommands() {
try {
this.commandManager = new PaperCommandManager<>(this,
CommandExecutionCoordinator
.simpleCoordinator(), sender -> {
if (sender instanceof Player) {
return this.userService().wrap(((Player) sender).getUniqueId());
} else {
return new BukkitConsoleUser((ConsoleCommandSender) sender);
}
}, user -> {
if (user instanceof PlayerUser) {
return Bukkit.getPlayer(((PlayerUser) user).uuid());
} else {
return Bukkit.getConsoleSender();
}
});
CommandRegistrar.registerCommands(this.commandManager);
} catch (final Exception e) {
e.printStackTrace();
}
}
@Override
public void reload() {
this.loadConfigs();
this.channelManager.reloadChannels();
final ChatChannel defaultChannel = this.channelManager.defaultChannel();
for (final PlayerUser user : this.userService().onlineUsers()) {
final ChatChannel selectedChannel = user.selectedChannel();
if (selectedChannel != null) {
final ChatChannel channel = this.channelManager.channelOrDefault(selectedChannel.key());
if (channel != null) {
user.selectedChannel(channel);
} else if (defaultChannel != null) {
user.selectedChannel(defaultChannel);
}
}
}
}
private void loadConfigs() {
this.getDataFolder().mkdir();
try {
final ConfigLoader<YamlConfigurationLoader> loader = new ConfigLoader<>(YamlConfigurationLoader.class);
this.carbonSettings = CarbonSettings.loadFrom(loader.loadConfig("config.yml"));
this.commandSettings = CommandSettingsRegistry.loadFrom(loader.loadConfig("commands.yml"));
this.channelSettings = ChannelSettings.loadFrom(loader.loadConfig("channels.yml"));
this.translations = CarbonTranslations.loadFrom(loader.loadConfig("language.yml"));
this.moderationSettings = ModerationSettings.loadFrom(loader.loadConfig("moderation.yml"));
} catch(final ConfigurateException ex) {
ex.printStackTrace();
}
}
@Override
public File dataDirectory() {
return this.getDataFolder();
}
@Override
public @NonNull String resolveName(final @NonNull UUID uuid) {
if (this.messageService() instanceof RedisMessageService) {
final RedisMessageService redis = (RedisMessageService) this.messageService();
final String value = redis.get("UUID:" + uuid.toString());
if (value != null) {
return value;
} else {
final String name = Bukkit.getOfflinePlayer(uuid).getName();
if (name != null) {
redis.set("UUID:" + uuid.toString(), name);
return name;
}
}
}
final String name = Bukkit.getOfflinePlayer(uuid).getName();
if (name != null) {
return name;
}
return uuid.toString();
}
@Override
public @NonNull UUID resolveUUID(final @NonNull String name) {
if (this.messageService() instanceof RedisMessageService) {
final RedisMessageService redis = (RedisMessageService) this.messageService();
final String value = redis.get("Name:" + name);
if (value != null) {
return UUID.fromString(value);
} else {
final UUID uuid = Bukkit.getOfflinePlayer(name).getUniqueId();
redis.set("UUID:" + uuid.toString(), name);
return uuid;
}
}
return Bukkit.getOfflinePlayer(name).getUniqueId();
}
@Override
public void cacheUUID(final @NonNull String name, final @NonNull UUID uuid) {
if (this.messageService() instanceof RedisMessageService) {
((RedisMessageService) this.messageService()).set(name, uuid.toString());
}
}
public @NonNull MessageManager messageManager() {
return this.messageManager;
}
@Override
public @NonNull UserService<BukkitPlayerUser> userService() {
return this.userService;
}
@Override
public @NonNull ChannelRegistry channelRegistry() {
return this.channelManager.registry();
}
@Override
public @NonNull CarbonTranslations translations() {
return this.translations;
}
@Override
public @NonNull ModerationSettings moderationSettings() {
return this.moderationSettings;
}
@Override
public @NonNull CarbonSettings carbonSettings() {
return this.carbonSettings;
}
@Override
public @NonNull ChannelSettings channelSettings() {
return this.channelSettings;
}
@Override
public @NonNull CommandSettingsRegistry commandSettings() {
return this.commandSettings;
}
@Override
public @NonNull CommandManager<CarbonUser> commandManager() {
return this.commandManager;
}
@Override
public @NonNull MessageProcessor messageProcessor() {
return this.messageProcessor;
}
@Override
public @NonNull MessageService messageService() {
return this.messageManager().messageService();
}
@Override
public @NonNull Logger logger() {
return this.logger;
}
@Override
public @NonNull Path dataFolder() {
return this.getDataFolder().toPath();
}
@Override
public @NonNull GsonComponentSerializer gsonSerializer() {
return BukkitComponentSerializer.gson();
}
@Override
public @NonNull String version() {
return this.getDescription().getVersion();
}
}
@@ -1,101 +0,0 @@
package net.draycia.carbon.bukkit.listeners;
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.api.users.ConsoleUser;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Map;
public class BukkitChatHandler implements Listener {
private final @NonNull CarbonChatBukkit carbonChat;
public BukkitChatHandler(final @NonNull CarbonChatBukkit carbonChat) {
this.carbonChat = carbonChat;
}
// Chat messages
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerChat(final @NonNull AsyncPlayerChatEvent event) {
final PlayerUser user = this.carbonChat.userService().wrap(event.getPlayer().getUniqueId());
ChatChannel channel = user.selectedChannel();
if (channel == null) {
channel = this.carbonChat.channelRegistry().defaultValue();
}
if (channel.options().shouldCancelChatEvent()) {
event.setCancelled(true);
}
for (final ChatChannel entry : this.carbonChat.channelRegistry()) {
if (!(entry instanceof TextChannel)) {
continue;
}
final TextChannel textChannel = (TextChannel) entry;
final String prefix = textChannel.messagePrefix();
if (prefix == null || prefix.isEmpty()) {
continue;
}
if (event.getMessage().startsWith(prefix)) {
if (entry.canPlayerUse(user)) {
event.setMessage(event.getMessage().substring(prefix.length()));
channel = entry;
break;
}
}
}
final ChatChannel selectedChannel = channel;
if (!selectedChannel.canPlayerUse(user)) {
return;
}
event.getRecipients().clear();
if (event.isAsynchronous()) {
final Map<CarbonUser, Component> messages =
selectedChannel.parseMessage(user, event.getMessage());
for (final Map.Entry<CarbonUser, Component> entry : messages.entrySet()) {
if (entry.getValue().equals(Component.empty())) {
continue;
}
if (user instanceof ConsoleUser) {
event.setFormat(PlainComponentSerializer.plain().serialize(entry.getValue())
.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%"));
} else {
entry.getKey().sendMessage(user.identity(), entry.getValue());
}
}
} else {
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
selectedChannel.sendComponentsAndLog(user.identity(),
selectedChannel.parseMessage(user, event.getMessage()));
// if (this.carbonChat.getConfig().getBoolean("show-tips")) {
// this.carbonChat.logger().info("Tip: Sync chat event! I cannot set the message format due to this. :(");
// this.carbonChat.logger().info("Tip: To 'solve' this, do a binary search and see which plugin is triggering");
// this.carbonChat.logger().info("Tip: sync chat events and causing this, and let that plugin author know.");
// }
});
}
}
}
@@ -1,41 +0,0 @@
package net.draycia.carbon.bukkit.listeners;
import net.draycia.carbon.api.events.UserEvent;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
public class BukkitLoginHandler implements Listener {
private final @NonNull CarbonChatBukkit carbonChat;
public BukkitLoginHandler(final @NonNull CarbonChatBukkit carbonChat) {
this.carbonChat = carbonChat;
}
@SuppressWarnings("argument.type.incompatible")
@EventHandler
public void onPlayerJoin(final @NonNull PlayerJoinEvent event) {
this.carbonChat.cacheUUID(event.getPlayer().getName(), event.getPlayer().getUniqueId());
this.carbonChat.userService().wrapLater(event.getPlayer().getUniqueId()).thenAcceptAsync(user -> {
final UserEvent.Join joinEvent = new UserEvent.Join(user);
CarbonEvents.post(joinEvent);
});
}
@EventHandler
public void onPlayerLeave(final @NonNull PlayerQuitEvent event) {
this.carbonChat.userService().wrapLater(event.getPlayer().getUniqueId()).thenAcceptAsync(user -> {
final UserEvent.Leave leaveEvent = new UserEvent.Leave(user);
CarbonEvents.post(leaveEvent);
});
}
}
@@ -1,54 +0,0 @@
package net.draycia.carbon.bukkit.listeners.events;
import net.draycia.carbon.api.events.ChatFormatEvent;
import net.draycia.carbon.bukkit.util.CarbonUtils;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.ChatComponentEvent;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.event.PostOrders;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.regex.Pattern;
public class ItemLinkHandler {
public ItemLinkHandler() {
CarbonEvents.register(ChatComponentEvent.class, PostOrders.FIRST, false, event -> {
// Handle item linking placeholders
final Player player = Bukkit.getPlayer(event.sender().uuid());
if (player == null) {
return;
}
if (!player.hasPermission("carbonchat.itemlink")) {
return;
}
final Component itemComponent = CarbonUtils.createComponent(player);
if (itemComponent.equals(Component.empty())) {
return;
}
for (final Pattern pattern : event.channel().itemLinkPatterns()) {
if (pattern.matcher(event.originalMessage()).find()) {
final TextComponent component = (TextComponent) event.component()
.replaceText(configurer -> configurer.once().match(pattern).replacement(itemComponent));
event.component(component);
break;
}
}
});
CarbonEvents.register(ChatFormatEvent.class, PostOrders.EARLY, false, event -> {
for (final Pattern pattern : event.channel().itemLinkPatterns()) {
event.message(pattern.matcher(event.message()).replaceAll("<white>$1</white>"));
}
});
}
}
@@ -1,17 +0,0 @@
package net.draycia.carbon.bukkit.listeners.events;
import me.clip.placeholderapi.PlaceholderAPI;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.PreChatFormatEvent;
import net.kyori.event.PostOrders;
import org.bukkit.Bukkit;
public class PlaceholderHandler {
public PlaceholderHandler() {
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
event.format(PlaceholderAPI.setPlaceholders(Bukkit.getOfflinePlayer(event.user().uuid()), event.format()));
});
}
}
@@ -1,33 +0,0 @@
package net.draycia.carbon.bukkit.listeners.events;
import me.clip.placeholderapi.PlaceholderAPI;
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;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class RelationalPlaceholderHandler {
public RelationalPlaceholderHandler() {
CarbonEvents.register(ChatFormatEvent.class, PostOrders.FIRST, false, event -> {
final CarbonUser targetUser = event.target();
if (!(targetUser instanceof PlayerUser)) {
return;
}
final Player sender = Bukkit.getPlayer(event.sender().uuid());
final Player target = Bukkit.getPlayer(((PlayerUser) targetUser).uuid());
if (sender == null || target == null) {
return;
}
event.format(PlaceholderAPI.setRelationalPlaceholders(sender, target, event.format()));
});
}
}
@@ -1,112 +0,0 @@
package net.draycia.carbon.bukkit.messaging;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
import net.draycia.carbon.api.messaging.MessageService;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.bukkit.util.BungeeChannelApi;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
public class BungeeMessageService implements MessageService {
private final @NonNull CarbonChatBukkit carbonChat;
private final @NonNull BungeeChannelApi api;
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 UUID serverUUID = UUID.randomUUID();
@SuppressWarnings("method.invocation.invalid")
public BungeeMessageService(final @NonNull CarbonChatBukkit carbonChat) {
this.carbonChat = carbonChat;
this.carbonChat.getServer().getMessenger().registerOutgoingPluginChannel(carbonChat, "BungeeCord");
this.api = BungeeChannelApi.of(carbonChat);
this.api.registerForwardListener((String channel, Player player, byte[] bytes) -> {
try {
final ByteArrayDataInput input = ByteStreams.newDataInput(bytes);
// Separated out for ease of debugging.
final long mostServer = input.readLong();
final long leastServer = input.readLong();
final UUID messageUUID = new UUID(mostServer, leastServer);
if (messageUUID.equals(this.serverUUID)) {
return;
}
final long mostUser = input.readLong();
final long leastUser = input.readLong();
final UUID userUUID = new UUID(mostUser, leastUser);
this.receiveMessage(userUUID, channel, input);
} catch (final IllegalStateException ignored) {
}
});
}
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);
}
@Override
public void registerUUIDMessageListener(final @NonNull String key, final @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
this.userNotLoadedListeners.put(key, listener);
}
@Override
public void unregisterMessageListener(final @NonNull String key) {
this.userLoadedListeners.remove(key);
this.userNotLoadedListeners.remove(key);
}
@Override
public void sendMessage(final @NonNull String key, final @NonNull UUID uuid, final @NonNull Consumer<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.api.forward("ONLINE", key, msg.toByteArray());
}
}
@@ -1,51 +0,0 @@
package net.draycia.carbon.bukkit.users;
import net.draycia.carbon.api.users.ConsoleUser;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.Plugin;
import org.checkerframework.checker.nullness.qual.NonNull;
public class BukkitConsoleUser implements ConsoleUser, ForwardingAudience.Single {
private final @NonNull Audience audience;
public BukkitConsoleUser(final @NonNull ConsoleCommandSender sender) {
final Plugin plugin = Bukkit.getPluginManager().getPlugin("CarbonChat");
if (plugin == null) {
throw new IllegalArgumentException("CarbonChat plugin cannot be found!");
}
this.audience = BukkitAudiences.create(plugin).sender(sender);
}
public BukkitConsoleUser() {
this(Bukkit.getConsoleSender());
}
@Override
public @NonNull Identity identity() {
return Identity.nil();
}
@Override
public @NonNull Audience audience() {
return this.audience;
}
@Override
public boolean hasPermission(final @NonNull String permission) {
return true;
}
@Override
public @NonNull String name() {
return "Console";
}
}
@@ -1,470 +0,0 @@
package net.draycia.carbon.bukkit.users;
import me.clip.placeholderapi.PlaceholderAPI;
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.api.users.UserChannelSettings;
import net.draycia.carbon.bukkit.util.BungeeChannelApi;
import net.draycia.carbon.common.channels.CarbonWhisperChannel;
import net.draycia.carbon.bukkit.util.FunctionalityConstants;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.ChannelSwitchEvent;
import net.draycia.carbon.api.events.PrivateMessageEvent;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextColor;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.LuckPermsProvider;
import net.luckperms.api.model.group.Group;
import net.luckperms.api.model.user.User;
import net.luckperms.api.query.QueryOptions;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
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;
public class BukkitPlayerUser implements PlayerUser, ForwardingAudience.Single {
private final transient @NonNull CarbonChatBukkit carbonChat;
private final @NonNull Map<@NonNull String, @NonNull SimpleUserChannelSettings> channelSettings = new HashMap<>();
private final @NonNull List<@NonNull UUID> ignoredUsers = new ArrayList<>();
private @NonNull UUID uuid;
private boolean muted = false;
private boolean shadowMuted = false;
private boolean spyingWhispers = false;
private @Nullable String nickname = null;
private @Nullable UUID replyTarget = null;
private @Nullable TextColor customChatColor = null;
private @NonNull PingOptions pingOptions = new PingOptions(null, null);
private @Nullable String selectedChannelKey = null;
private transient @Nullable ChatChannel selectedChannel = null;
private transient @Nullable Audience audience;
@SuppressWarnings({"initialization.fields.uninitialized", "method.invocation.invalid"})
public BukkitPlayerUser() {
final CarbonChatBukkit carbonChatBukkit =
(CarbonChatBukkit) Bukkit.getPluginManager().getPlugin("CarbonChat");
if (carbonChatBukkit == null) {
throw new IllegalArgumentException("CarbonChat plugin not present.");
}
this.carbonChat = carbonChatBukkit;
}
public BukkitPlayerUser(final @NonNull UUID uuid) {
this();
this.uuid = uuid;
}
@Override
public @NonNull Identity identity() {
if (this.hasPermission("carbonchat.hideidentity")) {
return Identity.nil();
}
return Identity.identity(this.uuid());
}
@Override
public @NonNull Audience audience() {
if (this.audience == null) {
this.audience = this.carbonChat.messageProcessor().audiences().player(this.uuid());
}
return this.audience;
}
@Override
public @NonNull String parsePlaceholders(final @NonNull String input) {
final Player player = Bukkit.getPlayer(this.uuid());
if (player == null) {
return input;
}
return PlaceholderAPI.setPlaceholders(player, input);
}
@Override
public @NonNull PingOptions pingOptions() {
return this.pingOptions;
}
@Override
public void pingOptions(final @NonNull PingOptions pingOptions) {
this.pingOptions = pingOptions;
}
@Override
public boolean online() {
return Bukkit.getPlayer(this.uuid()) != null;
}
@Override
public @NonNull UUID uuid() {
return this.uuid;
}
@Override
public @NonNull String nickname() {
if (this.nickname != null) {
return this.nickname;
}
return this.displayName();
}
@Override
public boolean hasPermission(final @NonNull String permission) {
final User user = LuckPermsProvider.get().getUserManager().getUser(this.uuid());
if (user == null) {
return false;
}
return user.getCachedData().getPermissionData().checkPermission(permission).asBoolean();
}
@Override
public void nickname(@Nullable String newNickname) {
this.nickname = newNickname;
final OfflinePlayer player = Bukkit.getOfflinePlayer(this.uuid());
if (player.isOnline()) {
if (newNickname != null) {
final Component component = this.carbonChat.messageProcessor().processMessage(newNickname);
newNickname = CarbonChatBukkit.LEGACY.serialize(component);
}
final Player onlinePlayer = player.getPlayer();
if (onlinePlayer != null) {
onlinePlayer.setDisplayName(newNickname);
onlinePlayer.setPlayerListName(newNickname);
}
}
}
@Override
public @NonNull String displayName() {
final Player player = Bukkit.getPlayer(this.uuid());
if (player != null) {
return player.getDisplayName();
}
return this.name();
}
public void displayName(final @Nullable String displayName) {
final Player player = Bukkit.getPlayer(this.uuid());
if (player != null) {
player.setDisplayName(displayName);
}
}
public @NonNull String name() {
return this.carbonChat.resolveName(this.uuid);
}
@Override
public @Nullable TextColor customChatColor() {
return this.customChatColor;
}
@Override
public void customChatColor(final @Nullable TextColor customChatColor) {
this.customChatColor = customChatColor;
}
@Override
@SuppressWarnings("argument.type.incompatible")
public @Nullable ChatChannel selectedChannel() {
if (this.selectedChannel != null) {
return this.selectedChannel;
}
if (this.selectedChannelKey != null) {
if (this.selectedChannelKey.equals("whisper") && this.replyTarget != null) {
this.selectedChannel = new CarbonWhisperChannel(this,
this.carbonChat.userService().wrap(this.replyTarget));
return this.selectedChannel;
}
return this.carbonChat.channelRegistry().getOrDefault(this.selectedChannelKey);
}
return null;
}
@Override
public void selectedChannel(final @NonNull ChatChannel chatChannel) {
final String failureMessage = chatChannel.switchFailureMessage();
final ChannelSwitchEvent event = new ChannelSwitchEvent(chatChannel, this, failureMessage);
CarbonEvents.post(event);
if (event.cancelled()) {
this.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(event.failureMessage(),
"channel", chatChannel.name()));
return;
}
this.selectedChannelKey = chatChannel.key();
this.selectedChannel = chatChannel;
final OfflinePlayer player = Bukkit.getOfflinePlayer(this.uuid());
if (player.isOnline()) {
this.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(chatChannel.switchMessage(),
"color", "<" + chatChannel.channelColor(this).toString() + ">",
"channel", chatChannel.name()));
}
}
@Override
public void clearSelectedChannel() {
this.selectedChannel(this.carbonChat.channelRegistry().defaultValue());
}
@Override
public boolean ignoringUser(final @NonNull UUID uuid) {
return this.ignoredUsers.contains(uuid);
}
@Override
public void ignoringUser(final @NonNull UUID uuid, final boolean ignoring) {
if (ignoring) {
this.ignoredUsers.add(uuid);
} else {
this.ignoredUsers.remove(uuid);
}
}
@Override
public @NonNull Iterable<@NonNull UUID> ignoredUsers() {
return this.ignoredUsers;
}
private transient final LuckPerms luckPerms = LuckPermsProvider.get();
@Override
public boolean hasGroup(final @NonNull String groupName) {
final Group group = this.luckPerms.getGroupManager().getGroup(groupName);
if (group == null) {
return false;
}
return this.hasGroup(group);
}
@Override
public boolean hasGroup(final @NonNull Group group) {
return this.groups().contains(group);
}
@Override
public @NonNull Collection<@NonNull Group> groups() {
final User user = this.luckPerms.getUserManager().getUser(this.uuid());
if (user != null) {
return user.getInheritedGroups(QueryOptions.nonContextual());
} else {
return Collections.emptyList();
}
}
@Override
public @Nullable Group primaryGroup() {
final User user = this.luckPerms.getUserManager().getUser(this.uuid());
if (user == null) {
return null;
}
return this.luckPerms.getGroupManager().getGroup(user.getPrimaryGroup());
}
@Override
public @NonNull Iterable<@NonNull CarbonUser> ignoredChatUsers() {
final List<CarbonUser> users = new ArrayList<>();
for (final UUID uuid : this.ignoredUsers) {
users.add(this.carbonChat.userService().wrap(uuid));
}
return users;
}
@Override
public void muted(final boolean muted) {
this.muted = muted;
}
@Override
public boolean muted() {
return this.muted;
}
@Override
public void shadowMuted(final boolean shadowMuted) {
this.shadowMuted = shadowMuted;
}
@Override
public boolean shadowMuted() {
return this.shadowMuted;
}
@Override
public @Nullable UUID replyTarget() {
return this.replyTarget;
}
@Override
public void replyTarget(final @Nullable UUID target) {
this.replyTarget = target;
}
@Override
public @NonNull UserChannelSettings channelSettings(final @NonNull ChatChannel channel) {
return this.channelSettings.computeIfAbsent(channel.key(), name -> {
return new SimpleUserChannelSettings(this.uuid);
});
}
public @NonNull Map<@NonNull String, @NonNull ? extends UserChannelSettings> channelSettings() {
return this.channelSettings;
}
@Override
public void spyingWhispers(final boolean spyingWhispers) {
this.spyingWhispers = spyingWhispers;
}
@Override
public boolean spyingWhispers() {
return this.spyingWhispers;
}
@Override
public void sendMessage(final @NonNull PlayerUser sender, final @NonNull String message) {
if (this.ignoringUser(sender) || sender.ignoringUser(this)) {
return;
}
final String toPlayerFormat = this.carbonChat.carbonSettings().whisperOptions().senderFormat();
final String fromPlayerFormat = this.carbonChat.carbonSettings().whisperOptions().receiverFormat();
final OfflinePlayer offlineSender = Bukkit.getOfflinePlayer(sender.uuid());
final String senderName = sender.nickname();
final OfflinePlayer offlineTarget = Bukkit.getOfflinePlayer(this.uuid());
final String targetName = this.nickname();
final Component toPlayerComponent = this.carbonChat.messageProcessor().processMessage(toPlayerFormat,
"message", message, "target", targetName, "receiver", targetName, "sender", senderName);
final Component fromPlayerComponent = this.carbonChat.messageProcessor().processMessage(fromPlayerFormat,
"message", message, "target", targetName, "receiver", targetName, "sender", senderName);
final PrivateMessageEvent event = new PrivateMessageEvent(sender, this, toPlayerComponent, fromPlayerComponent, message);
CarbonEvents.post(event);
if (event.cancelled()) {
return;
}
if (offlineTarget.isOnline()) {
if (offlineSender.isOnline()) {
sender.sendMessage(sender.identity(), toPlayerComponent);
if (sender.shadowMuted()) {
return;
}
this.sendMessage(sender.identity(), fromPlayerComponent);
sender.replyTarget(this);
this.replyTarget(sender);
}
} else if (offlineSender.isOnline()) {
final String targetNameFinal = targetName;
final String senderNameFinal = senderName;
if (!FunctionalityConstants.HAS_PROXY) {
final String playerOfflineFormat = this.carbonChat.translations().otherPlayerOffline();
final Component playerOfflineComponent = this.carbonChat.messageProcessor().processMessage(playerOfflineFormat,
"message", message, "target", targetNameFinal, "sender", senderNameFinal);
sender.sendMessage(Identity.nil(), playerOfflineComponent);
return;
}
BungeeChannelApi.of(this.carbonChat).getPlayerList("ALL").thenAccept(list -> {
final OfflinePlayer player = Bukkit.getOfflinePlayer(this.uuid());
final String name = player.getName();
if (name == null || !list.contains(name)) {
final String playerOfflineFormat = this.carbonChat.translations().otherPlayerOffline();
final Component playerOfflineComponent = this.carbonChat.messageProcessor().processMessage(playerOfflineFormat,
"message", message, "target", targetNameFinal, "sender", senderNameFinal);
sender.sendMessage(Identity.nil(), playerOfflineComponent);
return;
}
sender.sendMessage(sender.identity(), toPlayerComponent);
this.carbonChat.messageManager().sendMessage("whisper-component", sender.uuid(), byteArray -> {
byteArray.writeLong(this.uuid().getMostSignificantBits());
byteArray.writeLong(this.uuid().getLeastSignificantBits());
byteArray.writeUTF(this.carbonChat.gsonSerializer().serialize(fromPlayerComponent));
});
});
}
for (final Player player : Bukkit.getOnlinePlayers()) {
final PlayerUser user = this.carbonChat.userService().wrap(player.getUniqueId());
if (!user.spyingWhispers()) {
continue;
}
if (user.uuid().equals(sender.uuid()) || user.uuid().equals(this.uuid())) {
continue;
}
user.sendMessage(sender.identity(), this.carbonChat.messageProcessor()
.processMessage(this.carbonChat.translations().spyWhispers(), "message", message,
"target", targetName, "sender", senderName));
}
}
}
@@ -1,68 +0,0 @@
package net.draycia.carbon.bukkit.users;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.UserChannelSettings;
import net.kyori.adventure.text.format.TextColor;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
public class SimpleUserChannelSettings implements UserChannelSettings {
private final transient @NonNull CarbonChat carbonChat = CarbonChatProvider.carbonChat();
private boolean spying;
private boolean ignored;
private @Nullable String color;
private @NonNull UUID uuid;
@SuppressWarnings("initialization.fields.uninitialized")
public SimpleUserChannelSettings(final @NonNull UUID uuid) {
this.uuid = uuid;
}
private @NonNull CarbonUser user() {
return this.carbonChat.userService().wrap(this.uuid);
}
@Override
public boolean spying() {
return this.spying;
}
@Override
public void spying(final boolean spying) {
this.spying = spying;
}
@Override
public boolean ignored() {
return this.ignored;
}
@Override
public void ignoring(final boolean ignored) {
this.ignored = ignored;
}
@Override
public @Nullable TextColor color() {
if (this.color == null) {
return null;
}
return TextColor.fromHexString(this.color);
}
@Override
public void color(final @Nullable TextColor color) {
if (color == null) {
this.color = null;
} else {
this.color = color.asHexString();
}
}
}
@@ -1,546 +0,0 @@
/**
* https://github.com/leonardosnt/bungeechannelapi
*
* Copyright (C) 2017 leonardosnt <[email protected]>
* Licensed under the MIT License. See LICENSE file in the project root for full license information.
*/
package net.draycia.carbon.bukkit.util;
import java.net.InetSocketAddress;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.WeakHashMap;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.messaging.Messenger;
import org.bukkit.plugin.messaging.PluginMessageListener;
import com.google.common.collect.Iterables;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
/**
* Documentation copied from https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/
*
* @author leonardosnt ([email protected])
* @see <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/</a>
*/
@SuppressWarnings("all")
public class BungeeChannelApi {
private static WeakHashMap<Plugin, BungeeChannelApi> registeredInstances = new WeakHashMap<>();
private final PluginMessageListener messageListener;
private final Plugin plugin;
private final Map<String, Queue<CompletableFuture<?>>> callbackMap;
private Map<String, ForwardConsumer> forwardListeners;
private ForwardConsumer globalForwardListener;
/**
* Get or create new BungeeChannelApi instance
*
* @param plugin the plugin instance.
* @return the BungeeChannelApi instance for the {@code plugin}
* @throws NullPointerException if the {@code plugin} is {@code null}
*/
public synchronized static BungeeChannelApi of(Plugin plugin) {
return registeredInstances.compute(plugin, (k, v) -> {
if (v == null) v = new BungeeChannelApi(plugin);
return v;
});
}
public BungeeChannelApi(Plugin plugin) {
this.plugin = Objects.requireNonNull(plugin, "plugin cannot be null");
this.callbackMap = new HashMap<>();
// Prevent dev's from registering multiple channel listeners,
// by unregistering the old instance.
synchronized (registeredInstances) {
registeredInstances.compute(plugin, (k, oldInstance) -> {
if (oldInstance != null) oldInstance.unregister();
return this;
});
}
this.messageListener = this::onPluginMessageReceived;
Messenger messenger = Bukkit.getServer().getMessenger();
messenger.registerOutgoingPluginChannel(plugin, "BungeeCord");
messenger.registerIncomingPluginChannel(plugin, "BungeeCord", messageListener);
}
/**
* Set a global listener for all 'forwarded' messages.
*
* @param globalListener the listener
* @see <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/#forward">https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/#forward</a>
*/
public void registerForwardListener(ForwardConsumer globalListener) {
this.globalForwardListener = globalListener;
}
/**
* Set a listener for all 'forwarded' messages in a specific subchannel.
*
* @param channelName the subchannel name
* @param listener the listener
* @see <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/#forward">https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/#forward</a>
*/
public void registerForwardListener(String channelName, ForwardConsumer listener) {
if (forwardListeners == null) {
forwardListeners = new HashMap<>();
}
synchronized (forwardListeners) {
forwardListeners.put(channelName, listener);
}
}
/**
* Get the amount of players on a certain server, or on ALL the servers.
*
* @param serverName the server name of the server to get the player count of, or ALL to get the global player count
* @return A {@link CompletableFuture} that, when completed, will return
* the amount of players on a certain server, or on ALL the servers.
* @throws IllegalArgumentException if there is no players online.
*/
public CompletableFuture<Integer> getPlayerCount(String serverName) {
Player player = getFirstPlayer();
CompletableFuture<Integer> future = new CompletableFuture<>();
synchronized (callbackMap) {
callbackMap.compute("PlayerCount-" + serverName, this.computeQueueValue(future));
}
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("PlayerCount");
output.writeUTF(serverName);
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
return future;
}
/**
* Get a list of players connected on a certain server, or on ALL the servers.
*
* @param serverName the name of the server to get the list of connected players, or ALL for global online player list
* @return A {@link CompletableFuture} that, when completed, will return a
* list of players connected on a certain server, or on ALL the servers.
* @throws IllegalArgumentException if there is no players online.
*/
public CompletableFuture<List<String>> getPlayerList(String serverName) {
Player player = getFirstPlayer();
CompletableFuture<List<String>> future = new CompletableFuture<>();
synchronized (callbackMap) {
callbackMap.compute("PlayerList-" + serverName, this.computeQueueValue(future));
}
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("PlayerList");
output.writeUTF(serverName);
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
return future;
}
/**
* Get a list of server name strings, as defined in BungeeCord's config.yml.
*
* @return A {@link CompletableFuture} that, when completed, will return a
* list of server name strings, as defined in BungeeCord's config.yml.
* @throws IllegalArgumentException if there is no players online.
*/
public CompletableFuture<List<String>> getServers() {
Player player = getFirstPlayer();
CompletableFuture<List<String>> future = new CompletableFuture<>();
synchronized (callbackMap) {
callbackMap.compute("GetServers", this.computeQueueValue(future));
}
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("GetServers");
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
return future;
}
/**
* Connects a player to said subserver.
*
* @param player the player you want to teleport.
* @param serverName the name of server to connect to, as defined in BungeeCord config.yml.
*/
public void connect(Player player, String serverName) {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("Connect");
output.writeUTF(serverName);
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
}
/**
* Connect a named player to said subserver.
*
* @param playerName name of the player to teleport.
* @param server name of server to connect to, as defined in BungeeCord config.yml.
* @throws IllegalArgumentException if there is no players online.
*/
public void connectOther(String playerName, String server) {
Player player = getFirstPlayer();
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("ConnectOther");
output.writeUTF(playerName);
output.writeUTF(server);
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
}
/**
* Get the (real) IP of a player.
*
* @param player The player you wish to get the IP of.
* @return A {@link CompletableFuture} that, when completed, will return the (real) IP of {@code player}.
*/
public CompletableFuture<InetSocketAddress> getIp(Player player) {
CompletableFuture<InetSocketAddress> future = new CompletableFuture<>();
synchronized (callbackMap) {
callbackMap.compute("IP", this.computeQueueValue(future));
}
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("IP");
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
return future;
}
/**
* Send a message (as in, a chat message) to the specified player.
*
* @param playerName the name of the player to send the chat message.
* @param message the message to send to the player.
* @throws IllegalArgumentException if there is no players online.
*/
public void sendMessage(String playerName, String message) {
Player player = getFirstPlayer();
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("Message");
output.writeUTF(playerName);
output.writeUTF(message);
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
}
/**
* Get this server's name, as defined in BungeeCord's config.yml
*
* @return A {@link CompletableFuture} that, when completed, will return
* the {@code server's} name, as defined in BungeeCord's config.yml.
* @throws IllegalArgumentException if there is no players online.
*/
public CompletableFuture<String> getServer() {
Player player = getFirstPlayer();
CompletableFuture<String> future = new CompletableFuture<>();
synchronized (callbackMap) {
callbackMap.compute("GetServer", this.computeQueueValue(future));
}
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("GetServer");
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
return future;
}
/**
* Request the UUID of this player.
*
* @param player The player whose UUID you requested.
* @return A {@link CompletableFuture} that, when completed, will return the UUID of {@code player}.
*/
public CompletableFuture<String> getUUID(Player player) {
CompletableFuture<String> future = new CompletableFuture<>();
synchronized (callbackMap) {
callbackMap.compute("UUID", this.computeQueueValue(future));
}
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("UUID");
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
return future;
}
/**
* Request the UUID of any player connected to the BungeeCord proxy.
*
* @param playerName the name of the player whose UUID you would like.
* @return A {@link CompletableFuture} that, when completed, will return the UUID of {@code playerName}.
* @throws IllegalArgumentException if there is no players online.
*/
public CompletableFuture<String> getUUID(String playerName) {
Player player = getFirstPlayer();
CompletableFuture<String> future = new CompletableFuture<>();
synchronized (callbackMap) {
callbackMap.compute("UUIDOther-" + playerName, this.computeQueueValue(future));
}
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("UUIDOther");
output.writeUTF(playerName);
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
return future;
}
/**
* Request the IP of any server on this proxy.
*
* @param serverName the name of the server.
* @return A {@link CompletableFuture} that, when completed, will return the requested ip.
* @throws IllegalArgumentException if there is no players online.
*/
public CompletableFuture<InetSocketAddress> getServerIp(String serverName) {
Player player = getFirstPlayer();
CompletableFuture<InetSocketAddress> future = new CompletableFuture<>();
synchronized (callbackMap) {
callbackMap.compute("ServerIP-" + serverName, this.computeQueueValue(future));
}
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("ServerIP");
output.writeUTF(serverName);
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
return future;
}
/**
* Kick any player on this proxy.
*
* @param playerName the name of the player.
* @param kickMessage the reason the player is kicked with.
* @throws IllegalArgumentException if there is no players online.
*/
public void kickPlayer(String playerName, String kickMessage) {
Player player = getFirstPlayer();
CompletableFuture<InetSocketAddress> future = new CompletableFuture<>();
synchronized (callbackMap) {
callbackMap.compute("KickPlayer", this.computeQueueValue(future));
}
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("KickPlayer");
output.writeUTF(playerName);
output.writeUTF(kickMessage);
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
}
/**
* Send a custom plugin message to said server. This is one of the most useful channels ever.
* <b>Remember, the sending and receiving server(s) need to have a player online.</b>
*
* @param server the name of the server to send to,
* ALL to send to every server (except the one sending the plugin message),
* or ONLINE to send to every server that's online (except the one sending the plugin message).
*
* @param channelName Subchannel for plugin usage.
* @param data data to send.
* @throws IllegalArgumentException if there is no players online.
*/
public void forward(String server, String channelName, byte[] data) {
Player player = getFirstPlayer();
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("Forward");
output.writeUTF(server);
output.writeUTF(channelName);
output.writeShort(data.length);
output.write(data);
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
}
/**
* Send a custom plugin message to specific player.
*
* @param playerName the name of the player to send to.
* @param channelName Subchannel for plugin usage.
* @param data data to send.
* @throws IllegalArgumentException if there is no players online.
*/
public void forwardToPlayer(String playerName, String channelName, byte[] data) {
Player player = getFirstPlayer();
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("ForwardToPlayer");
output.writeUTF(playerName);
output.writeUTF(channelName);
output.writeShort(data.length);
output.write(data);
player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
}
@SuppressWarnings("unchecked")
private void onPluginMessageReceived(String channel, Player player, byte[] message) {
if (!channel.equalsIgnoreCase("BungeeCord")) return;
ByteArrayDataInput input = ByteStreams.newDataInput(message);
String subchannel = input.readUTF();
synchronized (callbackMap) {
Queue<CompletableFuture<?>> callbacks;
if (subchannel.equals("PlayerCount") || subchannel.equals("PlayerList") ||
subchannel.equals("UUIDOther") || subchannel.equals("ServerIP")) {
String identifier = input.readUTF(); // Server/player name
callbacks = callbackMap.get(subchannel + "-" + identifier);
if (callbacks == null || callbacks.isEmpty()) {
return;
}
CompletableFuture<?> callback = callbacks.poll();
try {
switch (subchannel) {
case "PlayerCount":
((CompletableFuture<Integer>) callback).complete(Integer.valueOf(input.readInt()));
break;
case "PlayerList":
((CompletableFuture<List<String>>) callback).complete(Arrays.asList(input.readUTF().split(", ")));
break;
case "UUIDOther":
((CompletableFuture<String>) callback).complete(input.readUTF());
break;
case "ServerIP": {
String ip = input.readUTF();
int port = input.readUnsignedShort();
((CompletableFuture<InetSocketAddress>) callback).complete(new InetSocketAddress(ip, port));
break;
}
}
} catch(Exception ex) {
callback.completeExceptionally(ex);
}
return;
}
callbacks = callbackMap.get(subchannel);
if (callbacks == null) {
short dataLength = input.readShort();
byte[] data = new byte[dataLength];
input.readFully(data);
if (globalForwardListener != null) {
globalForwardListener.accept(subchannel, player, data);
}
if (forwardListeners != null) {
synchronized (forwardListeners) {
ForwardConsumer listener = forwardListeners.get(subchannel);
if (listener != null) {
listener.accept(subchannel, player, data);
}
}
}
return;
}
if (callbacks.isEmpty()) {
return;
}
final CompletableFuture<?> callback = callbacks.poll();
try {
switch (subchannel) {
case "GetServers":
((CompletableFuture<List<String>>) callback).complete(Arrays.asList(input.readUTF().split(", ")));
break;
case "GetServer":
case "UUID":
((CompletableFuture<String>) callback).complete(input.readUTF());
break;
case "IP": {
String ip = input.readUTF();
int port = input.readInt();
((CompletableFuture<InetSocketAddress>) callback).complete(new InetSocketAddress(ip, port));
break;
}
default:
break;
}
} catch(Exception ex) {
callback.completeExceptionally(ex);
}
}
}
/**
* Unregister message channels.
*/
public void unregister() {
Messenger messenger = Bukkit.getServer().getMessenger();
messenger.unregisterIncomingPluginChannel(plugin, "BungeeCord", messageListener);
messenger.unregisterOutgoingPluginChannel(plugin);
callbackMap.clear();
}
private BiFunction<String, Queue<CompletableFuture<?>>, Queue<CompletableFuture<?>>> computeQueueValue(CompletableFuture<?> queueValue) {
return (key, value) -> {
if (value == null) value = new ArrayDeque<CompletableFuture<?>>();
value.add(queueValue);
return value;
};
}
private Player getFirstPlayer() {
/**
* if Bukkit Version < 1.7.10 then Bukkit.getOnlinePlayers() will return
* a Player[] otherwise it'll return a Collection<? extends Player>.
*/
Player firstPlayer = getFirstPlayer0(Bukkit.getOnlinePlayers());
if (firstPlayer == null) {
throw new IllegalArgumentException("Bungee Messaging Api requires at least one player to be online.");
}
return firstPlayer;
}
@SuppressWarnings("unused")
private Player getFirstPlayer0(Player[] playerArray) {
return playerArray.length > 0 ? playerArray[0] : null;
}
private Player getFirstPlayer0(Collection<? extends Player> playerCollection) {
return Iterables.getFirst(playerCollection, null);
}
@FunctionalInterface
public interface ForwardConsumer {
void accept(String channel, Player player, byte[] data);
}
}
@@ -1,87 +0,0 @@
package net.draycia.carbon.bukkit.util;
import net.draycia.carbon.api.channels.ChatChannel;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
import net.draycia.carbon.api.users.PlayerUser;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
public class CarbonPlaceholders extends PlaceholderExpansion {
private final @NonNull CarbonChatBukkit carbonChat;
public CarbonPlaceholders(final @NonNull CarbonChatBukkit carbonChat) {
this.carbonChat = carbonChat;
}
@Override
public @NonNull String getIdentifier() {
return "carbonchat";
}
@Override
public @NonNull String getAuthor() {
return "Draycia (Vicarious#0001)";
}
@Override
public @NonNull String getVersion() {
return "1.0.0";
}
@Override
public boolean persist() {
return true;
}
@Override
public @NonNull String onPlaceholderRequest(final @NonNull Player player, final @NonNull String identifier) {
final String key = identifier.toLowerCase();
if (key.startsWith("can_use_")) {
final String value = key.replace("can_use_", "");
final ChatChannel channel = this.carbonChat.channelRegistry().get(value);
if (channel == null) {
return "false";
}
final PlayerUser user = this.carbonChat.userService().wrap(player.getUniqueId());
return String.valueOf(channel.canPlayerUse(user));
} else if (key.startsWith("can_see_")) {
final String value = key.replace("can_see_", "");
final ChatChannel channel = this.carbonChat.channelRegistry().get(value);
if (channel == null) {
return "false";
}
final PlayerUser user = this.carbonChat.userService().wrap(player.getUniqueId());
return String.valueOf(channel.canPlayerSee(user, true));
} else if (key.startsWith("ignoring_channel_")) {
final String value = key.replace("ignoring_channel_", "");
final ChatChannel channel = this.carbonChat.channelRegistry().get(value);
if (channel == null) {
return "false";
}
final PlayerUser user = this.carbonChat.userService().wrap(player.getUniqueId());
return String.valueOf(user.channelSettings(channel).ignored());
} else if (key.startsWith("selected_channel")) {
final ChatChannel channel = this.carbonChat.userService().wrap(player.getUniqueId()).selectedChannel();
return channel == null ? this.carbonChat.channelRegistry().defaultValue().name() : channel.name();
}
return "";
}
}
@@ -21,14 +21,8 @@
package net.draycia.carbon.bukkit.util;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.chat.TranslatableComponent;
import net.md_5.bungee.api.chat.hover.content.Content;
import org.bukkit.Bukkit;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -46,26 +40,20 @@ public final class CarbonUtils {
return net.kyori.adventure.text.Component.empty();
}
final Content content = Bukkit.getItemFactory().hoverContentOf(itemStack);
final HoverEvent event = new HoverEvent(HoverEvent.Action.SHOW_ITEM, content);
final TextComponent.Builder builder = Component.text();
final ComponentBuilder component = new ComponentBuilder();
component.event(event); // Let this be inherited by all coming components.
component.color(ChatColor.WHITE).append("[");
builder.hoverEvent(itemStack); // Let this be inherited by all coming components.
builder.append(Component.text("[", NamedTextColor.WHITE));
if (itemStack.getItemMeta().hasDisplayName()) {
component.append(TextComponent.fromLegacyText(itemStack.getItemMeta().getDisplayName()));
builder.append(itemStack.getItemMeta().displayName());
} else {
// As of 1.13, Material is 1:1 with MC's names
final String prefix = itemStack.getType().isBlock() ? "block" : "item";
final String name = prefix + ".minecraft." + itemStack.getType().name().toLowerCase();
component.append(new TranslatableComponent(name));
builder.append(Component.translatable(itemStack.getType().getTranslationKey()));
}
component.color(ChatColor.WHITE).append("]");
builder.append(Component.text("]", NamedTextColor.WHITE));
return BungeeComponentSerializer.get().deserialize(component.create());
return builder.build();
}
}
@@ -1,43 +0,0 @@
package net.draycia.carbon.bukkit.util;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.lang.reflect.Field;
@SuppressWarnings("argument.type.incompatible")
public final class FunctionalityConstants {
public static final boolean HAS_PROXY;
static {
boolean hasProxy = false;
try {
final Class<?> spigotConfig = Class.forName("org.spigotmc.SpigotConfig");
final Field bungee = spigotConfig.getField("bungee");
hasProxy = bungee.getBoolean(null);
} catch (final ClassNotFoundException | NoSuchFieldException | IllegalAccessException ignored) {
}
HAS_PROXY = hasProxy;
}
private FunctionalityConstants() {
}
private static boolean noThrow(final @NonNull ThrowingRunnable runnable) {
try {
runnable.run();
return true;
} catch (final Exception ex) {
return false;
}
}
@FunctionalInterface
private interface ThrowingRunnable {
void run() throws Exception;
}
}
@@ -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) {
}
}
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more