Major rewrite of most of the plugin

This commit is contained in:
Josh (Vicarious) authored and GitHub committed 2020-12-15 19:13:25 -08:00
commit 7e222f11f1
197 files changed
+10596 -6282

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
plugins {
id 'java-library'
}
description 'CarbonChat-API'
dependencies {
api "org.checkerframework:checker-qual:${vers['checker-qual']}"
api "net.kyori:adventure-api:${vers['adventure']}"
api "net.kyori:adventure-nbt:${vers['adventure']}"
api "net.kyori:adventure-platform-api:${vers['adventure-platform']}"
api "net.kyori:adventure-text-serializer-plain:${vers['adventure']}"
api("net.kyori:adventure-text-serializer-gson:${vers['adventure']}") {
exclude group: 'com.google.code.gson'
}
api "net.kyori:adventure-text-serializer-legacy:${vers['adventure']}"
api "net.kyori:adventure-text-minimessage:${vers['minimessage']}"
api "de.themoep:minedown-adventure:${vers['minedown']}"
api("net.kyori:event-api:${vers['kyori-event-api']}")
api("net.kyori:registry:${vers['kyori-registry']}")
api "cloud.commandframework:cloud-core:${vers['cloud']}"
api "org.spongepowered:configurate-core:${vers['configurate']}"
api "com.google.guava:guava:${vers['guava']}"
compileOnlyApi "org.slf4j:slf4j-api:${vers['slf4j-api']}"
compileOnlyApi "net.luckperms:api:${vers['luckperms-api']}"
}
@@ -0,0 +1,68 @@
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);
@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();
}
@@ -0,0 +1,25 @@
package net.draycia.carbon.api;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public final class CarbonChatProvider {
private CarbonChatProvider() {
}
private static @Nullable CarbonChat instance;
public static void register(final @NonNull CarbonChat carbonChat) {
CarbonChatProvider.instance = carbonChat;
}
public static @NonNull CarbonChat carbonChat() {
if (CarbonChatProvider.instance == null) {
throw new IllegalStateException("CarbonChat not initialized!"); // LuckPerms design go brrrr
}
return CarbonChatProvider.instance;
}
}
@@ -0,0 +1,141 @@
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());
}
}
@@ -0,0 +1,20 @@
package net.draycia.carbon.api;
import net.kyori.registry.DefaultedRegistryGetter;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* An extension of the DefaultedRegistryGetter that declares a defaultValue method
* @param <K>
* @param <V>
*/
public interface DefaultedKeyValueRegistry<K, V> extends DefaultedRegistryGetter<K, V> {
/**
* Gets the default value.
*
* @return the default value
*/
@NonNull V defaultValue();
}
@@ -0,0 +1,8 @@
package net.draycia.carbon.api.adventure;
public enum FormatType {
MOJANG,
MINIMESSAGE_MARKDOWN,
MINIMESSAGE,
MINEDOWN
}
@@ -0,0 +1,16 @@
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();
@NonNull FormatType formatType();
}
@@ -0,0 +1,77 @@
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();
}
}
@@ -0,0 +1,80 @@
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, boolean fromRemote);
@NonNull
Map<CarbonUser, Component> parseMessage(@NonNull PlayerUser user, @NonNull Collection<@NonNull PlayerUser> recipients,
@NonNull String message, boolean fromRemote);
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);
}
@@ -0,0 +1,207 @@
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, final boolean fromRemote) {
return Collections.emptyMap();
}
@Override
public @NonNull Map<CarbonUser, Component> parseMessage(final @NonNull PlayerUser user, final @NonNull Collection<@NonNull PlayerUser> recipients, final @NonNull String message, final boolean fromRemote) {
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 "";
}
}
@@ -0,0 +1,16 @@
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();
}
@@ -0,0 +1,63 @@
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);
}
@@ -0,0 +1,28 @@
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";
}
}
@@ -0,0 +1,33 @@
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;
}
}
@@ -0,0 +1,73 @@
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();
}
}
@@ -0,0 +1,143 @@
package net.draycia.carbon.api.config;
import net.draycia.carbon.api.adventure.FormatType;
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("Options: MOJANG, MINIMESSAGE_MARKDOWN, MINIMESSAGE, MINEDOWN")
private @NonNull FormatType formatType = FormatType.MINIMESSAGE;
@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;
}
public @NonNull FormatType formatType() {
return this.formatType;
}
}
@@ -0,0 +1,227 @@
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;
}
}
@@ -0,0 +1,402 @@
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;
}
}
@@ -0,0 +1,58 @@
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;
}
}
@@ -0,0 +1,68 @@
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);
}
}
@@ -0,0 +1,7 @@
package net.draycia.carbon.api.config;
public enum ColorPriority {
PLAYER,
CUSTOM,
CHANNEL
}
@@ -0,0 +1,31 @@
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;
}
}
@@ -0,0 +1,26 @@
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;
}
}
@@ -0,0 +1,7 @@
package net.draycia.carbon.api.config;
public enum MessagingType {
NONE,
REDIS,
BUNGEECORD
}
@@ -0,0 +1,158 @@
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;
}
}
}
@@ -0,0 +1,32 @@
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 int database = 0;
public @NonNull String host() {
return this.host;
}
public @Nullable String password() {
return this.password;
}
public int port() {
return this.port;
}
public int database() {
return this.database;
}
}
@@ -0,0 +1,36 @@
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;
}
}
@@ -0,0 +1,124 @@
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;
}
}
@@ -0,0 +1,6 @@
package net.draycia.carbon.api.config;
public enum StorageType {
MYSQL,
JSON
}
@@ -0,0 +1,147 @@
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("")
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 @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;
}
}
@@ -0,0 +1,29 @@
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;
}
}
@@ -0,0 +1,28 @@
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;
}
}
@@ -0,0 +1,48 @@
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;
}
}
@@ -0,0 +1,70 @@
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;
}
}
@@ -0,0 +1,74 @@
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;
}
}
@@ -0,0 +1,44 @@
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;
}
}
@@ -0,0 +1,64 @@
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;
}
}
@@ -0,0 +1,59 @@
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;
}
}
@@ -0,0 +1,51 @@
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;
}
}
@@ -0,0 +1,43 @@
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);
}
}
}
@@ -0,0 +1,5 @@
package net.draycia.carbon.api.events.misc;
public interface CarbonEvent {
}
@@ -1,4 +1,4 @@
package net.draycia.carbon.events;
package net.draycia.carbon.api.events.misc;
import net.kyori.event.EventSubscriber;
import net.kyori.event.PostResult;
@@ -14,11 +14,11 @@ public final class CarbonEvents {
private static final SimpleEventBus<CarbonEvent> EVENT_BUS = new SimpleEventBus<>(CarbonEvent.class);
public static <T extends CarbonEvent> void register(@NonNull final Class<T> clazz, @NonNull final EventSubscriber<T> subscriber) {
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(@NonNull final Class<T> clazz, final int priority, final boolean consumeCancelled, @NonNull final Consumer<T> consumer) {
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() {
@@ -31,17 +31,17 @@ public final class CarbonEvents {
}
@Override
public void invoke(@NonNull final T event) {
public void invoke(final @NonNull T event) {
consumer.accept(event);
}
});
}
public static void unregister(@NonNull final EventSubscriber<? super CarbonEvent> subscriber) {
public static void unregister(final @NonNull EventSubscriber<? super CarbonEvent> subscriber) {
EVENT_BUS.unregister(subscriber);
}
public static PostResult post(@NonNull final CarbonEvent event) {
public static PostResult post(final @NonNull CarbonEvent event) {
return EVENT_BUS.post(event);
}
@@ -0,0 +1,22 @@
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);
}
@@ -0,0 +1,13 @@
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();
}
@@ -0,0 +1,4 @@
package net.draycia.carbon.api.users;
public interface ConsoleUser extends CarbonUser {
}
@@ -0,0 +1,166 @@
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();
default void nickname(final @Nullable String nickname) {
this.nickname(nickname, false);
}
void nickname(@Nullable String nickname, boolean fromRemote);
@NonNull String displayName();
void displayName(@Nullable String displayName);
@NonNull String name();
@Nullable TextColor customChatColor();
void customChatColor(@Nullable TextColor customChatColor, boolean fromRemote);
@NonNull String parsePlaceholders(@NonNull String input);
@NonNull UserChannelSettings channelSettings(@NonNull ChatChannel channel);
@NonNull Map<@NonNull String, @NonNull ? extends UserChannelSettings> channelSettings();
boolean spyingWhispers();
default void spyingWhispers(final boolean spyingWhispers) {
this.spyingWhispers(spyingWhispers, false);
}
void spyingWhispers(boolean spyingWhispers, boolean fromRemote);
boolean muted();
default void muted(final boolean muted) {
this.muted(muted, false);
}
void muted(boolean muted, boolean fromRemote);
boolean shadowMuted();
default void shadowMuted(final boolean shadowMuted) {
this.shadowMuted(shadowMuted, false);
}
void shadowMuted(boolean shadowMuted, boolean fromRemote);
@Nullable UUID replyTarget();
default void replyTarget(final @Nullable UUID target) {
this.replyTarget(target, false);
}
default void replyTarget(final @Nullable PlayerUser user) {
if (user == null) {
this.replyTarget((UUID) null, false);
} else {
this.replyTarget(user.uuid(), false);
}
}
void replyTarget(@Nullable UUID target, boolean fromRemote);
default void replyTarget(final @Nullable PlayerUser user, final boolean fromRemote) {
if (user == null) {
this.replyTarget((UUID) null, fromRemote);
} else {
this.replyTarget(user.uuid(), fromRemote);
}
}
boolean ignoringUser(@NonNull UUID uuid);
void ignoringUser(@NonNull UUID uuid, boolean ignoring, boolean fromRemote);
default void ignoringUser(final @NonNull UUID uuid, final boolean ignoring) {
this.ignoringUser(uuid, ignoring, false);
}
default boolean ignoringUser(final @NonNull PlayerUser user) {
return this.ignoringUser(user.uuid());
}
default void ignoringUser(final @NonNull PlayerUser user, final boolean ignoring, final boolean fromRemote) {
this.ignoringUser(user.uuid(), ignoring, fromRemote);
}
default void ignoringUser(final @NonNull PlayerUser user, final boolean ignoring) {
this.ignoringUser(user.uuid(), ignoring, false);
}
@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();
default void selectedChannel(final @NonNull ChatChannel channel) {
this.selectedChannel(channel, false);
}
void selectedChannel(@NonNull ChatChannel channel, boolean fromRemote);
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,4 +1,4 @@
package net.draycia.carbon.storage;
package net.draycia.carbon.api.users;
import net.kyori.adventure.text.format.TextColor;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -24,7 +24,7 @@ public interface UserChannelSettings {
@Nullable
TextColor color();
default void color(@Nullable final TextColor color) {
default void color(final @Nullable TextColor color) {
this.color(color, false);
}
@@ -0,0 +1,32 @@
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();
}
+119
View File
@@ -0,0 +1,119 @@
import java.nio.charset.StandardCharsets
plugins {
id 'com.github.johnrengelman.shadow' version '6.1.0'
id 'net.minecrell.plugin-yml.bukkit' version '0.3.0'
}
description = 'CarbonChat-Bukkit'
dependencies {
implementation project(":CarbonChat-Common")
// Server
compileOnly "com.destroystokyo.paper:paper-api:${vers['paper-api']}"
// Adventure
implementation "net.kyori:adventure-platform-bukkit:${vers['adventure-platform']}"
implementation "net.kyori:adventure-text-serializer-bungeecord:${vers['adventure-platform']}"
// Config
implementation "org.spongepowered:configurate-yaml:${vers['configurate']}"
implementation "org.spongepowered:configurate-hocon:${vers['configurate']}"
implementation "org.yaml:snakeyaml:${vers['snakeyaml']}"
// Commands
implementation "cloud.commandframework:cloud-paper:${vers['cloud']}"
// Plugins
compileOnly("com.gmail.nossr50.mcMMO:mcMMO:${vers['mcmmo']}") {
exclude group: 'org.jetbrains', module: 'annotations'
}
compileOnly "com.github.TownyAdvanced:Towny:${vers['towny']}"
compileOnly("com.sk89q.worldguard:worldguard-bukkit:${vers['worldguard']}") {
exclude group: 'org.spigotmc', module: 'spigot-api' // Honestly?
}
compileOnly "me.clip:placeholderapi:${vers['placeholder-api']}"
compileOnly "net.luckperms:api:${vers['luckperms-api']}"
compileOnly "com.github.MilkBowl:VaultAPI:${vers['vault']}"
}
// Generates plugin.yml automatically
bukkit {
name = "CarbonChat"
version = rootProject.version
main = 'net.draycia.carbon.bukkit.CarbonChatBukkit'
apiVersion = '1.13'
author = 'Draycia'
depend = ['PlaceholderAPI', 'Vault']
softDepend = ['LuckPerms', 'Towny', 'mcMMO', 'WorldGuard']
loadBefore = ["Essentials"]
permissions {
'carbonchat.channels.global.see' {
setDefault("TRUE")
}
'carbonchat.channels.global.use' {
setDefault("TRUE")
}
}
}
checkstyle {
def configRoot = new File(rootProject.projectDir, '.checkstyle')
toolVersion = vers['checkstyle']
configDirectory = configRoot
configProperties = [basedir: configRoot.getAbsolutePath()]
}
// Set output directory and encoding
tasks.withType(JavaCompile) {
options.encoding = StandardCharsets.UTF_8.name()
options.compilerArgs += ['-Xlint:all']
}
// Automatically shadowJar when building
tasks.build.dependsOn tasks.shadowJar
// Output a single jar
shadowJar {
minimize()
archiveFileName.set(project.description + "-" + project.property('projectVersion') + ".jar")
destinationDirectory = rootProject.getBuildDir()
relocate("org.yaml", "net.draycia.carbon.libs.org.yaml")
relocate("net.kyori", "net.draycia.carbon.libs.kyori")
relocate("org.spongepowered.configurate", "net.draycia.carbon.libs.configurate")
relocate("org.checkerframework", "net.draycia.carbon.libs.checkerframework")
relocate("org.reactivestreams", "net.draycia.carbon.libs.reactivestreams")
relocate("org.codehaus", "net.draycia.carbon.libs.codehaus")
relocate("org.slf4j", "net.draycia.carbon.libs.slf4j")
relocate("io.leangen.geantyref", "net.draycia.carbon.libs.typereference")
relocate("io.lettuce", "net.draycia.carbon.libs.lettuce")
relocate("co.aikar.idb", "net.draycia.carbon.libs.idb")
relocate("cloud.commandframework", "net.draycia.carbon.libs.cloud")
relocate("com.zaxxer.hikari", "net.draycia.carbon.libs.hikari")
relocate("com.typesafe.config", "net.draycia.carbon.libs.typesafe.config")
relocate("com.google", "net.draycia.carbon.libs.google")
relocate("de.themoep.minedown", "net.draycia.carbon.libs.minedown")
relocate("reactor", "net.draycia.carbon.libs.reactor")
relocate("javax.annotation", "net.draycia.carbon.libs.javax.annotation")
}
jar {
archiveFileName.set(project.description + "-" + project.property('projectVersion') + ".jar")
}
//// Automatically relocate all shaded dependencies
//import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation
//
//task relocateShadowJar(type: ConfigureShadowRelocation) {
// target = tasks.shadowJar
// prefix = "net.draycia.carbon.libs" // Default value is "shadow"
//}
//
//tasks.shadowJar.dependsOn tasks.relocateShadowJar
// Cleanup custom output directory on clean task
clean.doFirst {
delete "$rootDir/build/bundled"
}
@@ -0,0 +1,447 @@
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.BukkitChatListener;
import net.draycia.carbon.bukkit.listeners.events.ItemLinkHandler;
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.FunctionalityConstants;
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.bukkit.listeners.contexts.DistanceContext;
import net.draycia.carbon.bukkit.listeners.contexts.EconomyContext;
import net.draycia.carbon.common.listeners.contexts.FilterContext;
import net.draycia.carbon.bukkit.listeners.contexts.PAPIContext;
import net.draycia.carbon.bukkit.listeners.contexts.TownyContext;
import net.draycia.carbon.bukkit.listeners.contexts.WorldGuardContext;
import net.draycia.carbon.bukkit.listeners.contexts.mcMMOContext;
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 net.milkbowl.vault.economy.Economy;
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, this.carbonSettings.formatType());
// 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();
this.registerContexts();
// Setup PlaceholderAPI placeholders
new CarbonPlaceholders(this).register();
// Log missing functionality
if (this.carbonSettings().showTips() && !FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
this.logger().error("Item linking disabled! Please use Paper 1.16.2 #172 or newer.");
}
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 BukkitChatListener(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();
}
private void registerContexts() {
if (Bukkit.getPluginManager().isPluginEnabled("Towny")) {
this.getServer().getPluginManager().registerEvents(new TownyContext(this), this);
}
if (Bukkit.getPluginManager().isPluginEnabled("mcMMO")) {
this.getServer().getPluginManager().registerEvents(new mcMMOContext(this), this);
}
if (Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) {
new WorldGuardContext();
}
if (Bukkit.getServicesManager().isProvidedFor(Economy.class)) {
new EconomyContext(this);
}
new DistanceContext();
new FilterContext(this);
new PAPIContext();
}
@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();
}
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();
}
}
@@ -1,16 +1,17 @@
package net.draycia.carbon.listeners.contexts;
package net.draycia.carbon.bukkit.listeners.contexts;
import net.draycia.carbon.events.CarbonEvents;
import net.draycia.carbon.events.api.ReceiverContextEvent;
import net.draycia.carbon.util.Context;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.ReceiverContextEvent;
import net.draycia.carbon.api.Context;
import net.kyori.event.PostOrders;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
public class DistanceContext {
@NonNull
private static final String KEY = "distance";
private final static @NonNull String KEY = "distance";
public DistanceContext() {
CarbonEvents.register(ReceiverContextEvent.class, PostOrders.NORMAL, false, event -> {
@@ -24,13 +25,16 @@ public class DistanceContext {
return;
}
if (!event.sender().online() || !event.recipient().online()) {
final Player sender = Bukkit.getPlayer(event.sender().uuid());
final Player recipient = Bukkit.getPlayer(event.recipient().uuid());
if (sender == null || recipient == null) {
event.cancelled(true);
return;
}
final Location senderLocation = event.sender().player().getLocation();
final Location targetLocation = event.recipient().player().getLocation();
final Location senderLocation = sender.getLocation();
final Location targetLocation = recipient.getLocation();
if (!senderLocation.getWorld().equals(targetLocation.getWorld())) {
event.cancelled(true);
@@ -0,0 +1,105 @@
package net.draycia.carbon.bukkit.listeners.contexts;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.PreChatFormatEvent;
import net.draycia.carbon.api.Context;
import net.kyori.adventure.identity.Identity;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.checkerframework.checker.nullness.qual.NonNull;
public class EconomyContext {
private final @NonNull CarbonChatBukkit carbonChat;
private final @NonNull Economy economy;
public EconomyContext(final @NonNull CarbonChatBukkit carbonChat) {
this.carbonChat = carbonChat;
final RegisteredServiceProvider<Economy> provider =
this.carbonChat.getServer().getServicesManager().getRegistration(Economy.class);
if (provider == null) {
throw new IllegalArgumentException("Economy provider not found!");
}
this.economy = provider.getProvider();
CarbonEvents.register(PreChatFormatEvent.class, event -> {
if (!(event.channel() instanceof TextChannel)) {
return;
}
final TextChannel channel = (TextChannel) event.channel();
final Context context = channel.context("vault-balance");
if (context == null) {
return;
}
final Double requiredBal;
if (context.isNumber()) {
requiredBal = context.asNumber().doubleValue();
} else {
return;
}
if (requiredBal.equals(0.0)) {
return;
}
final OfflinePlayer player = Bukkit.getOfflinePlayer(event.user().uuid());
if (!this.economy.has(player, requiredBal)) {
event.cancelled(true);
event.user().sendMessage(Identity.nil(), this.carbonChat.messageProcessor()
.processMessage(this.carbonChat.translations().contextMessages().vaultBalanceNotEnough()));
}
});
CarbonEvents.register(PreChatFormatEvent.class, event -> {
if (!(event.channel() instanceof TextChannel)) {
return;
}
final TextChannel channel = (TextChannel) event.channel();
final Context context = channel.context("vault-cost");
if (context == null) {
return;
}
final Double cost;
if (context.isNumber()) {
cost = context.asNumber().doubleValue();
} else {
return;
}
if (cost.equals(0.0)) {
return;
}
final OfflinePlayer player = Bukkit.getOfflinePlayer(event.user().uuid());
if (!this.economy.has(player, cost)) {
event.cancelled(true);
event.user().sendMessage(Identity.nil(), this.carbonChat.messageProcessor()
.processMessage(this.carbonChat.translations().contextMessages().vaultCostNotEnough()));
return;
}
this.economy.withdrawPlayer(player, cost);
});
}
}
@@ -0,0 +1,77 @@
package net.draycia.carbon.bukkit.listeners.contexts;
import me.clip.placeholderapi.PlaceholderAPI;
import net.draycia.carbon.api.events.MessageContextEvent;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.ReceiverContextEvent;
import net.draycia.carbon.api.Context;
import net.kyori.event.PostOrders;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
public class PAPIContext {
private final static @NonNull String KEY = "placeholder";
private final static @NonNull String SENDER = "-sender";
private final static @NonNull String RECEIVER = "-receiver";
public PAPIContext() {
CarbonEvents.register(ReceiverContextEvent.class, PostOrders.NORMAL, false, event -> {
final Context context = event.channel().context(KEY + RECEIVER);
if (context == null) {
return;
}
if (!context.isString()) {
return;
}
final String[] pieces = context.asString().split("=");
if (pieces.length != 2) {
return;
}
final Player receiver = Bukkit.getPlayer(event.recipient().uuid());
if (receiver == null) {
return;
}
final String output = PlaceholderAPI.setPlaceholders(receiver, pieces[0]);
event.cancelled(output.equals(pieces[1]));
});
CarbonEvents.register(MessageContextEvent.class, PostOrders.NORMAL, false, event -> {
final Context context = event.channel().context(KEY + SENDER);
if (context == null) {
return;
}
if (!context.isString()) {
return;
}
final String[] pieces = context.asString().split("=");
if (pieces.length != 2) {
return;
}
final Player receiver = Bukkit.getPlayer(event.user().uuid());
if (receiver == null) {
return;
}
final String output = PlaceholderAPI.setPlaceholders(receiver, pieces[0]);
event.cancelled(output.equals(pieces[1]));
});
}
}
@@ -1,18 +1,20 @@
package net.draycia.carbon.listeners.contexts;
package net.draycia.carbon.bukkit.listeners.contexts;
import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.event.TownRemoveResidentEvent;
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
import com.palmergames.bukkit.towny.object.Resident;
import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.channels.ChatChannel;
import net.draycia.carbon.events.CarbonEvents;
import net.draycia.carbon.events.api.ChannelSwitchEvent;
import net.draycia.carbon.events.api.MessageContextEvent;
import net.draycia.carbon.events.api.ReceiverContextEvent;
import net.draycia.carbon.storage.ChatUser;
import net.draycia.carbon.util.Context;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.ChannelSwitchEvent;
import net.draycia.carbon.api.events.MessageContextEvent;
import net.draycia.carbon.api.events.ReceiverContextEvent;
import net.draycia.carbon.api.Context;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.PostOrders;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
@@ -20,13 +22,11 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public final class TownyContext implements Listener {
@NonNull
private static final String KEY = "towny-town";
private final static @NonNull String KEY = "towny-town";
@NonNull
private final CarbonChat carbonChat;
private final @NonNull CarbonChat carbonChat;
public TownyContext(@NonNull final CarbonChat carbonChat) {
public TownyContext(final @NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
CarbonEvents.register(ReceiverContextEvent.class, event -> {
@@ -38,22 +38,29 @@ public final class TownyContext implements Listener {
});
CarbonEvents.register(ChannelSwitchEvent.class, event -> {
final Context context = event.channel().context(KEY);
if (!(event.channel() instanceof TextChannel)) {
return;
}
final TextChannel channel = (TextChannel) event.channel();
final Context context = channel.context(KEY);
if (context != null && context.isBoolean() && context.asBoolean()) {
if (!this.isInTown(event.user())) {
event.failureMessage(carbonChat.getConfig().getString("contexts.Towny.cancellation-message"));
event.failureMessage(this.carbonChat.translations().contextMessages().townyTownNotInTown());
event.cancelled(true);
}
}
});
CarbonEvents.register(MessageContextEvent.class, PostOrders.NORMAL, false, event -> {
// TODO: event.setFailureMessage
final Context context = event.channel().context(KEY);
if (context != null && context.isBoolean() && context.asBoolean()) {
if (!this.isInTown(event.user())) {
event.user().sendMessage(this.carbonChat.messageProcessor().processMessage(
this.carbonChat.translations().contextMessages().townyTownNotInTown()));
event.cancelled(!this.isInTown(event.user()));
}
}
@@ -62,15 +69,15 @@ public final class TownyContext implements Listener {
@EventHandler
public void onResidentRemove(final TownRemoveResidentEvent event) {
final String name = event.getResident().getName();
final ChatUser user = this.carbonChat.userService().wrap(name);
final PlayerUser user = this.carbonChat.userService().wrap(event.getResident().getUUID());
final ChatChannel channel = user.selectedChannel();
if (channel == null) {
if (!(channel instanceof TextChannel)) {
return;
}
final Context context = channel.context(KEY);
final TextChannel textChannel = (TextChannel) channel;
final Context context = textChannel.context(KEY);
if (context != null && context.isBoolean() && context.asBoolean()) {
user.clearSelectedChannel();
@@ -79,23 +86,24 @@ public final class TownyContext implements Listener {
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
final PlayerUser user = this.carbonChat.userService().wrap(event.getPlayer().getUniqueId());
final ChatChannel channel = user.selectedChannel();
if (channel == null) {
if (!(channel instanceof TextChannel)) {
return;
}
final Context context = channel.context(KEY);
final TextChannel textChannel = (TextChannel) channel;
final Context context = textChannel.context(KEY);
if (context != null && context.isBoolean() && context.asBoolean() && !this.isInTown(user)) {
user.clearSelectedChannel();
}
}
public boolean isInTown(@NonNull final ChatUser user) {
public boolean isInTown(final @NonNull PlayerUser user) {
try {
return TownyAPI.getInstance().getDataSource().getResident(user.player().getName()).hasTown();
return TownyAPI.getInstance().getDataSource().getResident(user.name()).hasTown();
} catch (final NotRegisteredException exception) {
exception.printStackTrace();
}
@@ -103,16 +111,16 @@ public final class TownyContext implements Listener {
return false;
}
public boolean isInSameTown(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
if (!user1.online() || !user2.online()) {
public boolean isInSameTown(final @NonNull PlayerUser user1, final @NonNull PlayerUser user2) {
if (Bukkit.getPlayer(user1.uuid()) == null || Bukkit.getPlayer(user2.uuid()) == null) {
return false;
}
try {
final Resident resident = TownyAPI.getInstance().getDataSource().getResident(user1.player().getName());
final Resident resident = TownyAPI.getInstance().getDataSource().getResident(user1.name());
if (resident.hasTown()) {
return resident.getTown().hasResident(user2.player().getName());
return resident.getTown().hasResident(user2.name());
}
} catch (final NotRegisteredException exception) {
exception.printStackTrace();
@@ -1,47 +1,66 @@
package net.draycia.carbon.listeners.contexts;
package net.draycia.carbon.bukkit.listeners.contexts;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import net.draycia.carbon.events.CarbonEvents;
import net.draycia.carbon.events.api.MessageContextEvent;
import net.draycia.carbon.events.api.ReceiverContextEvent;
import net.draycia.carbon.storage.ChatUser;
import net.draycia.carbon.util.Context;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.MessageContextEvent;
import net.draycia.carbon.api.events.ReceiverContextEvent;
import net.draycia.carbon.api.Context;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
public final class WorldGuardContext {
@NonNull
private static final String KEY = "worldguard-region";
private final static @NonNull String KEY = "worldguard-region";
public WorldGuardContext() {
CarbonEvents.register(ReceiverContextEvent.class, event -> {
event.cancelled(this.testContext(event.sender(), event.recipient(), event.context(KEY)));
final Player senderPlayer = Bukkit.getPlayer(event.sender().uuid());
final Player recipientPlayer = Bukkit.getPlayer(event.recipient().uuid());
if (senderPlayer == null || recipientPlayer == null) {
return;
}
final Context context = event.context(KEY);
if (context == null) {
return;
}
event.cancelled(this.testContext(senderPlayer, recipientPlayer, context));
});
CarbonEvents.register(MessageContextEvent.class, event -> {
final Context value = event.channel().context(KEY);
final Player player = Bukkit.getPlayer(event.user().uuid());
if (value != null && (value.isString() || value.isList()) && !this.isInRegionOrRegions(value, event.user())) {
if (player == null) {
return;
}
if (value != null && (value.isString() || value.isList()) && !this.isInRegionOrRegions(value, player)) {
event.cancelled(true);
}
});
}
private boolean isInRegionOrRegions(@NonNull final Context context, @NonNull final ChatUser user) {
private boolean isInRegionOrRegions(final @NonNull Context context, final @NonNull Player player) {
if (context.isString()) {
return this.isInRegion(context.asString(), user);
return this.isInRegion(context.asString(), player);
}
if (context.isList()) {
for (final String region : context.<String>asList()) {
if (this.isInRegion(region, user)) {
if (this.isInRegion(region, player)) {
return true;
}
}
@@ -50,7 +69,7 @@ public final class WorldGuardContext {
return false;
}
public boolean testContext(@NonNull final ChatUser sender, @NonNull final ChatUser target, @NonNull final Context context) {
public boolean testContext(final @NonNull Player sender, final @NonNull Player target, final @NonNull Context context) {
boolean user1InRegion = false;
boolean user2InRegion = false;
@@ -76,13 +95,9 @@ public final class WorldGuardContext {
return user1InRegion && user2InRegion;
}
public boolean isInSameRegion(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
if (!user1.online() || !user2.online()) {
return false;
}
final Location user1Location = BukkitAdapter.adapt(user1.player().getLocation());
final Location user2Location = BukkitAdapter.adapt(user2.player().getLocation());
public boolean isInSameRegion(final @NonNull Player user1, final @NonNull Player user2) {
final Location user1Location = BukkitAdapter.adapt(user1.getLocation());
final Location user2Location = BukkitAdapter.adapt(user2.getLocation());
final RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
final RegionQuery regionQuery = container.createQuery();
@@ -99,16 +114,26 @@ public final class WorldGuardContext {
return false;
}
public boolean isInRegion(@NonNull final String region, @NonNull final ChatUser user) {
public boolean isInRegion(final @NonNull String region, final @NonNull Player player) {
final RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
final World world = BukkitAdapter.adapt(user.player().getWorld());
final ProtectedRegion protection = container.get(world).getRegion(region);
final World world = BukkitAdapter.adapt(player.getWorld());
final RegionManager regionManager = container.get(world);
return this.isInRegion(protection, user);
if (regionManager == null) {
return false;
}
final ProtectedRegion protection = regionManager.getRegion(region);
if (protection == null) {
return false;
}
return this.isInRegion(protection, player);
}
public boolean isInRegion(@NonNull final ProtectedRegion region, @NonNull final ChatUser user) {
final org.bukkit.Location location = user.player().getLocation();
public boolean isInRegion(final @NonNull ProtectedRegion region, final @NonNull Player player) {
final org.bukkit.Location location = player.getLocation();
return region.contains(location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
@@ -0,0 +1,121 @@
package net.draycia.carbon.bukkit.listeners.contexts;
import com.gmail.nossr50.api.PartyAPI;
import com.gmail.nossr50.events.party.McMMOPartyChangeEvent;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.ChannelSwitchEvent;
import net.draycia.carbon.api.events.MessageContextEvent;
import net.draycia.carbon.api.events.ReceiverContextEvent;
import net.draycia.carbon.api.Context;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.PostOrders;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
public final class mcMMOContext implements Listener {
private final @NonNull CarbonChat carbonChat;
private final static @NonNull String KEY = "mcmmo-party";
public mcMMOContext(final @NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
CarbonEvents.register(ReceiverContextEvent.class, PostOrders.NORMAL, false, event -> {
final Context context = event.channel().context(KEY);
if (context != null && context.isBoolean() && context.asBoolean()) {
event.cancelled(!this.isInSameParty(event.sender(), event.recipient()));
}
});
CarbonEvents.register(ChannelSwitchEvent.class, PostOrders.NORMAL, false, event -> {
if (!(event.channel() instanceof TextChannel)) {
return;
}
final TextChannel channel = (TextChannel) event.channel();
final Context context = channel.context(KEY);
if (context != null && context.isBoolean() && context.asBoolean()) {
if (!this.isInParty(event.user())) {
event.failureMessage(this.carbonChat.translations().contextMessages().mcmmoPartyNotInParty());
event.cancelled(true);
}
}
});
CarbonEvents.register(MessageContextEvent.class, PostOrders.NORMAL, false, event -> {
final Context context = event.channel().context(KEY);
if (context != null && context.isBoolean() && context.asBoolean()) {
event.user().sendMessage(this.carbonChat.messageProcessor().processMessage(
this.carbonChat.translations().contextMessages().mcmmoPartyNotInParty()));
event.cancelled(!this.isInParty(event.user()));
}
});
}
private static final McMMOPartyChangeEvent.EventReason LEFT = McMMOPartyChangeEvent.EventReason.LEFT_PARTY;
private static final McMMOPartyChangeEvent.EventReason KICKED = McMMOPartyChangeEvent.EventReason.KICKED_FROM_PARTY;
@EventHandler(ignoreCancelled = true)
public void onPartyLeave(final McMMOPartyChangeEvent event) {
if (event.getReason() != LEFT && event.getReason() != KICKED) {
return;
}
this.checkContext(event.getPlayer());
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
this.checkContext(event.getPlayer());
}
private void checkContext(final Player player) {
final PlayerUser user = this.carbonChat.userService().wrap(player.getUniqueId());
final ChatChannel channel = user.selectedChannel();
if (!(channel instanceof TextChannel)) {
return;
}
final TextChannel textChannel = (TextChannel) channel;
final Context context = textChannel.context(KEY);
if (context != null && context.isBoolean() && context.asBoolean() && !this.isInParty(user)) {
user.clearSelectedChannel();
}
}
public boolean isInParty(final @NonNull PlayerUser user) {
final Player player = Bukkit.getPlayer(user.uuid());
if (player == null) {
return false;
}
return PartyAPI.inParty(player);
}
public boolean isInSameParty(final @NonNull PlayerUser user1, final @NonNull PlayerUser user2) {
final Player player1 = Bukkit.getPlayer(user1.uuid());
final Player player2 = Bukkit.getPlayer(user2.uuid());
if (player1 == null || player2 == null) {
return false;
}
return PartyAPI.inSameParty(player1, player2);
}
}
@@ -0,0 +1,123 @@
package net.draycia.carbon.bukkit.listeners.events;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.events.UserEvent;
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.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.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Map;
public class BukkitChatListener implements Listener {
private final @NonNull CarbonChatBukkit carbonChat;
public BukkitChatListener(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.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(), false);
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(), false));
// 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.");
// }
});
}
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
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 PlayerQuitEvent event) {
this.carbonChat.userService().wrapLater(event.getPlayer().getUniqueId()).thenAcceptAsync(user -> {
final UserEvent.Leave leaveEvent = new UserEvent.Leave(user);
CarbonEvents.post(leaveEvent);
});
}
}
@@ -1,11 +1,13 @@
package net.draycia.carbon.listeners.events;
package net.draycia.carbon.bukkit.listeners.events;
import net.draycia.carbon.events.CarbonEvents;
import net.draycia.carbon.events.api.ChatComponentEvent;
import net.draycia.carbon.util.CarbonUtils;
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;
@@ -14,13 +16,13 @@ public class ItemLinkHandler {
public ItemLinkHandler() {
CarbonEvents.register(ChatComponentEvent.class, PostOrders.FIRST, false, event -> {
if (!event.sender().online()) {
// Handle item linking placeholders
final Player player = Bukkit.getPlayer(event.sender().uuid());
if (player == null) {
return;
}
// Handle item linking placeholders
final Player player = event.sender().player();
if (!player.hasPermission("carbonchat.itemlink")) {
return;
}
@@ -32,18 +34,21 @@ public class ItemLinkHandler {
}
for (final Pattern pattern : event.channel().itemLinkPatterns()) {
final String patternContent = pattern.toString().replace("\\Q", "").replace("\\E", "");
if (event.originalMessage().contains(patternContent)) {
final TextComponent component = (TextComponent) event.component().replaceFirstText(pattern, input -> {
return Component.text().append(itemComponent);
});
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>"));
}
});
}
}
@@ -0,0 +1,17 @@
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()));
});
}
}
@@ -0,0 +1,33 @@
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,12 +1,12 @@
package net.draycia.carbon.messaging.impl;
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 io.github.leonardosnt.bungeechannelapi.BungeeChannelApi;
import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.messaging.MessageService;
import net.draycia.carbon.storage.ChatUser;
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;
@@ -18,22 +18,18 @@ import java.util.function.Consumer;
public class BungeeMessageService implements MessageService {
@NonNull
private final CarbonChat carbonChat;
private final @NonNull CarbonChatBukkit carbonChat;
@NonNull
private final BungeeChannelApi api;
private final @NonNull BungeeChannelApi api;
@NonNull
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
private final @NonNull Map<@NonNull String, @NonNull BiConsumer<@NonNull PlayerUser, @NonNull ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
@NonNull
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
private final @NonNull Map<@NonNull String, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
@NonNull
private final UUID serverUUID = UUID.randomUUID();
private final @NonNull UUID serverUUID = UUID.randomUUID();
public BungeeMessageService(@NonNull final CarbonChat carbonChat) {
@SuppressWarnings("method.invocation.invalid")
public BungeeMessageService(final @NonNull CarbonChatBukkit carbonChat) {
this.carbonChat = carbonChat;
this.carbonChat.getServer().getMessenger().registerOutgoingPluginChannel(carbonChat, "BungeeCord");
@@ -65,11 +61,11 @@ public class BungeeMessageService implements MessageService {
});
}
private void receiveMessage(@NonNull final UUID uuid, @NonNull final String key, @NonNull final ByteArrayDataInput value) {
final ChatUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
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<ChatUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
for (final Map.Entry<String, BiConsumer<PlayerUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value);
}
@@ -84,23 +80,23 @@ public class BungeeMessageService implements MessageService {
}
@Override
public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
public void registerUserMessageListener(final @NonNull String key, final @NonNull BiConsumer<@NonNull PlayerUser, @NonNull ByteArrayDataInput> listener) {
this.userLoadedListeners.put(key, listener);
}
@Override
public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
public void registerUUIDMessageListener(final @NonNull String key, final @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
this.userNotLoadedListeners.put(key, listener);
}
@Override
public void unregisterMessageListener(@NonNull final String key) {
public void unregisterMessageListener(final @NonNull String key) {
this.userLoadedListeners.remove(key);
this.userNotLoadedListeners.remove(key);
}
@Override
public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<ByteArrayDataOutput> consumer) {
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());
@@ -0,0 +1,51 @@
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";
}
}
@@ -0,0 +1,541 @@
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, final boolean fromRemote) {
this.nickname = newNickname;
final OfflinePlayer player = Bukkit.getOfflinePlayer(this.uuid());
if (player.isOnline()) {
if (newNickname != null) {
final Component component = this.carbonChat.messageProcessor().processMessage(this.nickname);
newNickname = CarbonChatBukkit.LEGACY.serialize(component);
}
final Player onlinePlayer = player.getPlayer();
if (onlinePlayer != null) {
onlinePlayer.setDisplayName(newNickname);
}
// if (this.carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
// onlinePlayer.setPlayerListName(newNickname);
// }
}
if (!fromRemote) {
final String nick = this.nickname;
if (nick == null) {
this.carbonChat.messageManager().sendMessage("nickname-reset", this.uuid(), byteArray -> {
});
} else {
this.carbonChat.messageManager().sendMessage("nickname", this.uuid(), byteArray -> {
byteArray.writeUTF(nick);
});
}
}
}
@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, final boolean fromRemote) {
this.customChatColor = customChatColor;
if (!fromRemote) {
if (customChatColor == null) {
this.carbonChat.messageManager().sendMessage("custom-chat-color-reset", this.uuid(), byteArray -> {
});
} else {
this.carbonChat.messageManager().sendMessage("custom-chat-color", this.uuid(), byteArray -> {
byteArray.writeUTF(customChatColor.asHexString());
});
}
}
}
@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 boolean fromRemote) {
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;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("selected-channel", this.uuid(), byteArray -> {
byteArray.writeUTF(chatChannel.key());
});
}
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, final boolean fromRemote) {
if (ignoring) {
this.ignoredUsers.add(uuid);
} else {
this.ignoredUsers.remove(uuid);
}
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("ignoring-user", this.uuid(), byteArray -> {
byteArray.writeLong(uuid.getMostSignificantBits());
byteArray.writeLong(uuid.getLeastSignificantBits());
byteArray.writeBoolean(ignoring);
});
}
}
@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, final boolean fromRemote) {
this.muted = muted;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("muted", this.uuid(), byteArray -> {
byteArray.writeBoolean(muted);
});
}
}
@Override
public boolean muted() {
return this.muted;
}
@Override
public void shadowMuted(final boolean shadowMuted, final boolean fromRemote) {
this.shadowMuted = shadowMuted;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("shadow-muted", this.uuid(), byteArray -> {
byteArray.writeBoolean(shadowMuted);
});
}
}
@Override
public boolean shadowMuted() {
return this.shadowMuted;
}
@Override
public @Nullable UUID replyTarget() {
return this.replyTarget;
}
@Override
public void replyTarget(final @Nullable UUID target, final boolean fromRemote) {
this.replyTarget = target;
if (!fromRemote) {
if (target != null) {
this.carbonChat.messageManager().sendMessage("reply-target", this.uuid(), byteArray -> {
byteArray.writeLong(target.getMostSignificantBits());
byteArray.writeLong(target.getLeastSignificantBits());
});
} else {
this.carbonChat.messageManager().sendMessage("reply-target-reset", this.uuid(), byteArray -> {
});
}
}
}
@Override
public @NonNull UserChannelSettings channelSettings(final @NonNull ChatChannel channel) {
return this.channelSettings.computeIfAbsent(channel.key(), name -> {
return new SimpleUserChannelSettings(this.uuid, channel.key());
});
}
public @NonNull Map<@NonNull String, @NonNull ? extends UserChannelSettings> channelSettings() {
return this.channelSettings;
}
@Override
public void spyingWhispers(final boolean spyingWhispers, final boolean fromRemote) {
this.spyingWhispers = spyingWhispers;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("spying-whispers", this.uuid(), byteArray -> {
byteArray.writeBoolean(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, "sender", senderName);
final Component fromPlayerComponent = this.carbonChat.messageProcessor().processMessage(fromPlayerFormat,
"message", message, "target", 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,10 +1,10 @@
package net.draycia.carbon.storage.impl;
package net.draycia.carbon.bukkit.users;
import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.storage.UserChannelSettings;
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.bukkit.Bukkit;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -12,31 +12,21 @@ import java.util.UUID;
public class SimpleUserChannelSettings implements UserChannelSettings {
@NonNull
private final transient CarbonChat carbonChat;
private final transient @NonNull CarbonChat carbonChat = CarbonChatProvider.carbonChat();
private boolean spying;
private boolean ignored;
@Nullable
private String color;
@MonotonicNonNull // @NonNull but not initialised in all constructors.
private UUID uuid;
@MonotonicNonNull // @NonNull but not initialised in all constructors.
private String channel;
private @Nullable String color;
private @NonNull UUID uuid;
private @NonNull String channel;
private SimpleUserChannelSettings() {
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
}
public SimpleUserChannelSettings(@NonNull final UUID uuid, @NonNull final String channel) {
@SuppressWarnings("initialization.fields.uninitialized")
public SimpleUserChannelSettings(final @NonNull UUID uuid, final @NonNull String channel) {
this.uuid = uuid;
this.channel = channel;
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
}
@NonNull
private CarbonChatUser user() {
return (CarbonChatUser) this.carbonChat.userService().wrap(this.uuid);
private @NonNull CarbonUser user() {
return this.carbonChat.userService().wrap(this.uuid);
}
@Override
@@ -49,7 +39,7 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
this.spying = spying;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("spying-channel", this.uuid, byteArray -> {
this.carbonChat.messageService().sendMessage("spying-channel", this.uuid, byteArray -> {
byteArray.writeUTF(this.channel);
byteArray.writeBoolean(spying);
});
@@ -66,7 +56,7 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
this.ignored = ignored;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("ignoring-channel", this.uuid, byteArray -> {
this.carbonChat.messageService().sendMessage("ignoring-channel", this.uuid, byteArray -> {
byteArray.writeUTF(this.channel);
byteArray.writeBoolean(ignored);
});
@@ -74,8 +64,7 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
}
@Override
@Nullable
public TextColor color() {
public @Nullable TextColor color() {
if (this.color == null) {
return null;
}
@@ -84,7 +73,7 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
}
@Override
public void color(@Nullable final TextColor color, final boolean fromRemote) {
public void color(final @Nullable TextColor color, final boolean fromRemote) {
if (color == null) {
this.color = null;
} else {
@@ -92,9 +81,16 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
}
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("channel-color", this.uuid, byteArray -> {
byteArray.writeUTF(color.asHexString());
});
final String newColor = this.color;
if (newColor == null || newColor.isEmpty()) {
this.carbonChat.messageService().sendMessage("channel-color-reset", this.uuid, byteArray -> {
});
} else {
this.carbonChat.messageService().sendMessage("channel-color", this.uuid, byteArray -> {
byteArray.writeUTF(newColor);
});
}
}
}
@@ -0,0 +1,546 @@
/**
* 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,37 +1,32 @@
package net.draycia.carbon.util;
package net.draycia.carbon.bukkit.util;
import net.draycia.carbon.api.channels.ChatChannel;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.channels.ChatChannel;
import net.draycia.carbon.storage.ChatUser;
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;
import org.checkerframework.checker.nullness.qual.Nullable;
public class CarbonPlaceholders extends PlaceholderExpansion {
@NonNull
private final CarbonChat carbonChat;
private final @NonNull CarbonChatBukkit carbonChat;
public CarbonPlaceholders(@NonNull final CarbonChat carbonChat) {
public CarbonPlaceholders(final @NonNull CarbonChatBukkit carbonChat) {
this.carbonChat = carbonChat;
}
@Override
@NonNull
public String getIdentifier() {
public @NonNull String getIdentifier() {
return "carbonchat";
}
@Override
@NonNull
public String getAuthor() {
public @NonNull String getAuthor() {
return "Draycia (Vicarious#0001)";
}
@Override
@NonNull
public String getVersion() {
public @NonNull String getVersion() {
return "1.0.0";
}
@@ -41,53 +36,52 @@ public class CarbonPlaceholders extends PlaceholderExpansion {
}
@Override
@Nullable
public String onPlaceholderRequest(@NonNull final Player player, @NonNull final String identifier) {
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.channelManager().registry().channel(value);
final ChatChannel channel = this.carbonChat.channelRegistry().get(value);
if (channel == null) {
return "false";
}
final ChatUser user = this.carbonChat.userService().wrap(player);
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.channelManager().registry().channel(value);
final ChatChannel channel = this.carbonChat.channelRegistry().get(value);
if (channel == null) {
return "false";
}
final ChatUser user = this.carbonChat.userService().wrap(player);
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.channelManager().registry().channel(value);
final ChatChannel channel = this.carbonChat.channelRegistry().get(value);
if (channel == null) {
return "false";
}
final ChatUser user = this.carbonChat.userService().wrap(player);
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).selectedChannel();
final ChatChannel channel = this.carbonChat.userService().wrap(player.getUniqueId()).selectedChannel();
return channel == null ? this.carbonChat.channelManager().defaultChannel().name() : channel.name();
return channel == null ? this.carbonChat.channelRegistry().defaultValue().name() : channel.name();
}
return null;
return "";
}
}
@@ -0,0 +1,91 @@
/*
Simple channel based chat plugin for Spigot
Copyright (C) 2020 Alexander Söderberg
Copyright (C) 2020 Josua Parks (Draycia)
Modifications made to work with Kyori/Adventure
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.bukkit.util;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
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 org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.List;
public final class CarbonUtils {
private static final @NonNull String @NonNull [] colors;
private CarbonUtils() {
}
static {
final List<String> colorList = new ArrayList<>();
for (final NamedTextColor color : NamedTextColor.NAMES.values()) {
colorList.add(color.toString());
}
colors = colorList.toArray(new String[0]);
}
public static @NonNull Component createComponent(final @NonNull Player player) {
if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
return net.kyori.adventure.text.Component.empty();
}
final ItemStack itemStack = player.getInventory().getItemInMainHand();
if (itemStack.getType().isAir()) {
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 ComponentBuilder component = new ComponentBuilder();
component.event(event); // Let this be inherited by all coming components.
component.color(ChatColor.WHITE).append("[");
if (itemStack.getItemMeta().hasDisplayName()) {
component.append(TextComponent.fromLegacyText(itemStack.getItemMeta().getDisplayName()));
} 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));
}
component.color(ChatColor.WHITE).append("]");
return BungeeComponentSerializer.get().deserialize(component.create());
}
}
@@ -1,4 +1,4 @@
package net.draycia.carbon.util;
package net.draycia.carbon.bukkit.util;
import org.bukkit.inventory.ItemFactory;
import org.bukkit.inventory.ItemStack;
@@ -6,7 +6,7 @@ import org.checkerframework.checker.nullness.qual.NonNull;
import java.lang.reflect.Field;
@SuppressWarnings("ResultOfMethodCallIgnored") // This is a common pattern in this class.
@SuppressWarnings({"ResultOfMethodCallIgnored", "argument.type.incompatible"})
public final class FunctionalityConstants {
public static final boolean HAS_HOVER_EVENT_METHOD = noThrow(() -> ItemFactory.class.getMethod("hoverContentOf", ItemStack.class));
@@ -29,7 +29,7 @@ public final class FunctionalityConstants {
}
private static boolean noThrow(@NonNull final ThrowingRunnable runnable) {
private static boolean noThrow(final @NonNull ThrowingRunnable runnable) {
try {
runnable.run();
return true;
@@ -1,4 +1,4 @@
package net.draycia.carbon.util;
package net.draycia.carbon.bukkit.util;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
@@ -38,7 +38,7 @@ import java.util.zip.GZIPOutputStream;
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings({"WeakerAccess", "unused"})
@SuppressWarnings("ALL")
public class Metrics {
static {
@@ -193,7 +193,7 @@ public class Metrics {
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(Metrics.this.plugin, () -> Metrics.this.submitData());
Bukkit.getScheduler().runTask(Metrics.this.plugin, Metrics.this::submitData);
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
@@ -207,7 +207,7 @@ public class Metrics {
*
* @return The plugin specific data.
*/
public JsonObject getPluginData() {
public JsonObject pluginData() {
final JsonObject data = new JsonObject();
final String pluginName = this.plugin.getDescription().getName();
@@ -219,7 +219,7 @@ public class Metrics {
final JsonArray customCharts = new JsonArray();
for (final CustomChart customChart : this.charts) {
// Add the data of the custom charts
final JsonObject chart = customChart.getRequestJsonObject();
final JsonObject chart = customChart.requestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
@@ -235,7 +235,7 @@ public class Metrics {
*
* @return The server specific data.
*/
private JsonObject getServerData() {
private JsonObject serverData() {
// Minecraft specific data
int playerAmount;
try {
@@ -281,7 +281,7 @@ public class Metrics {
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JsonObject data = this.getServerData();
final JsonObject data = this.serverData();
final JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data
@@ -422,11 +422,11 @@ public class Metrics {
this.chartId = chartId;
}
private JsonObject getRequestJsonObject() {
private JsonObject requestJsonObject() {
final JsonObject chart = new JsonObject();
chart.addProperty("chartId", this.chartId);
try {
final JsonObject data = this.getChartData();
final JsonObject data = this.chartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
@@ -441,7 +441,7 @@ public class Metrics {
return chart;
}
protected abstract JsonObject getChartData() throws Exception;
protected abstract JsonObject chartData() throws Exception;
}
@@ -464,7 +464,7 @@ public class Metrics {
}
@Override
protected JsonObject getChartData() throws Exception {
protected JsonObject chartData() throws Exception {
final JsonObject data = new JsonObject();
final String value = this.callable.call();
if (value == null || value.isEmpty()) {
@@ -495,7 +495,7 @@ public class Metrics {
}
@Override
protected JsonObject getChartData() throws Exception {
protected JsonObject chartData() throws Exception {
final JsonObject data = new JsonObject();
final JsonObject values = new JsonObject();
final Map<String, Integer> map = this.callable.call();
@@ -539,7 +539,7 @@ public class Metrics {
}
@Override
public JsonObject getChartData() throws Exception {
public JsonObject chartData() throws Exception {
final JsonObject data = new JsonObject();
final JsonObject values = new JsonObject();
final Map<String, Map<String, Integer>> map = this.callable.call();
@@ -588,7 +588,7 @@ public class Metrics {
}
@Override
protected JsonObject getChartData() throws Exception {
protected JsonObject chartData() throws Exception {
final JsonObject data = new JsonObject();
final int value = this.callable.call();
if (value == 0) {
@@ -620,7 +620,7 @@ public class Metrics {
}
@Override
protected JsonObject getChartData() throws Exception {
protected JsonObject chartData() throws Exception {
final JsonObject data = new JsonObject();
final JsonObject values = new JsonObject();
final Map<String, Integer> map = this.callable.call();
@@ -665,7 +665,7 @@ public class Metrics {
}
@Override
protected JsonObject getChartData() throws Exception {
protected JsonObject chartData() throws Exception {
final JsonObject data = new JsonObject();
final JsonObject values = new JsonObject();
final Map<String, Integer> map = this.callable.call();
@@ -703,7 +703,7 @@ public class Metrics {
}
@Override
protected JsonObject getChartData() throws Exception {
protected JsonObject chartData() throws Exception {
final JsonObject data = new JsonObject();
final JsonObject values = new JsonObject();
final Map<String, int[]> map = this.callable.call();
+21
View File
@@ -0,0 +1,21 @@
description 'CarbonChat-Common'
dependencies {
checkstyle("ca.stellardrift:stylecheck:${vers['stylecheck']}")
api project(':CarbonChat-API')
implementation("io.lettuce:lettuce-core:${vers['lettuce-core']}") {
exclude group: 'io.netty'
}
implementation "org.spongepowered:configurate-hocon:${vers['configurate']}"
implementation "org.spongepowered:configurate-yaml:${vers['configurate']}"
implementation "co.aikar:idb-core:${vers['idb-core']}"
implementation "com.zaxxer:HikariCP:${vers['hikari']}"
compileOnly "com.google.code.gson:gson:${vers['gson']}"
compileOnly "org.slf4j:slf4j-api:${vers['slf4j-api']}"
}
@@ -0,0 +1,79 @@
package net.draycia.carbon.common.adventure;
import de.themoep.minedown.adventure.MineDown;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.adventure.FormatType;
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;
private final @NonNull FormatType formatType;
public AdventureManager(final @NonNull AudienceProvider provider, final @NonNull FormatType formatType) {
this.provider = provider;
this.formatType = formatType;
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);
switch (this.formatType) {
case MINEDOWN:
return MineDown.parse(format);
case MOJANG:
return this.processMojang(format);
case MINIMESSAGE_MARKDOWN:
return MiniMessage.markdown().parse(format);
case MINIMESSAGE:
default:
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 FormatType formatType() {
return this.formatType;
}
@Override
public @NonNull AudienceProvider audiences() {
return this.provider;
}
}
@@ -0,0 +1,546 @@
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, @NonNull String message, final boolean fromRemote) {
//this.updateUserNickname(user);
message = MiniMessage.get().escapeTokens(message);
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());
}
}
if (user.online() && !fromRemote && 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, final boolean fromRemote) {
return this.parseMessage(user, this.audiences(), message, fromRemote);
}
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();
}
}
@@ -0,0 +1,292 @@
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,
final boolean fromRemote) {
return this.parseMessage(user, Collections.singleton(this.audience()), message, fromRemote);
}
@Override
public @NonNull Map<CarbonUser, Component> parseMessage(final @NonNull PlayerUser user,
final @NonNull Collection<@NonNull PlayerUser> recipients,
final @NonNull String message, final boolean fromRemote) {
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();
}
}
@@ -0,0 +1,127 @@
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());
}
}
}
}
@@ -0,0 +1,77 @@
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 (user.channelSettings(this.chatChannel()).ignored()) {
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(this.chatChannel().cannotUseMessage(),
"color", "<" + this.chatChannel().channelColor(user).toString() + ">",
"channel", this.chatChannel().name()));
return;
}
user.selectedChannel(this.chatChannel());
}
private void sendMessage(final @NonNull CommandContext<CarbonUser> context) {
context.<String>getOptional("message").ifPresent(message -> {
this.chatChannel().sendComponentsAndLog(
context.getSender().identity(),
this.chatChannel().parseMessage((PlayerUser) context.getSender(), message, false));
});
}
public @NonNull TextChannel chatChannel() {
return this.chatChannel;
}
public @NonNull String commandName() {
return this.commandName;
}
}
@@ -0,0 +1,76 @@
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 (user.channelSettings(channel).ignored()) {
user.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(channel.cannotUseMessage(),
"color", "<" + channel.channelColor(user).toString() + ">",
"channel", channel.name()));
return;
}
user.selectedChannel(channel);
}
private void sendMessage(final @NonNull CommandContext<CarbonUser> context) {
final ChatChannel channel = context.get("channel");
final String message = context.get("message");
channel.sendComponentsAndLog(context.getSender().identity(), channel.parseMessage((PlayerUser) context.getSender(),
message, false));
}
}
@@ -0,0 +1,130 @@
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);
}
}
}
}
@@ -0,0 +1,46 @@
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);
}
}
@@ -0,0 +1,86 @@
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));
}
}
}
@@ -0,0 +1,66 @@
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);
}
}
}
@@ -0,0 +1,65 @@
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);
}
}
}
}
@@ -0,0 +1,92 @@
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;
}
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()
);
}
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()
));
}
}
}
@@ -0,0 +1,104 @@
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()));
}
}
@@ -0,0 +1,68 @@
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);
}
}
}
@@ -0,0 +1,98 @@
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()));
}
}
@@ -0,0 +1,74 @@
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;
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()
);
}
private void channelOptions(final @NonNull CommandContext<CarbonUser> context) {
((PlayerUser) context.getSender()).pingOptions().pingSound(Sound.sound(Key.key(context.get("sound")),
Sound.Source.PLAYER, context.get("volume"), context.get("pitch")));
context.getSender().sendMessage(this.carbonChat.messageProcessor().processMessage(
this.carbonChat.translations().channelPingChanged()));
}
private void whisperOptions(final @NonNull CommandContext<CarbonUser> context) {
((PlayerUser) context.getSender()).pingOptions().whisperSound(Sound.sound(Key.key(context.get("sound")),
Sound.Source.PLAYER, context.get("volume"), context.get("pitch")));
context.getSender().sendMessage(this.carbonChat.messageProcessor().processMessage(
this.carbonChat.translations().whisperPingChanged()));
}
}
@@ -0,0 +1,73 @@
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);
}
}
}
@@ -0,0 +1,55 @@
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()
);
}
}
}
@@ -0,0 +1,68 @@
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);
}
}
}
@@ -0,0 +1,130 @@
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"));
}
}
@@ -0,0 +1,82 @@
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, false));
}
}
@@ -0,0 +1,104 @@
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()));
}
}
@@ -0,0 +1,60 @@
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);
}
}
@@ -0,0 +1,59 @@
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();
final String playerNotFound = CarbonChatProvider.carbonChat().translations().exceptionMessages()
.playerNotFound();
if (input == null) {
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);
}
}
@@ -0,0 +1,58 @@
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);
}
}
}
}
@@ -0,0 +1,88 @@
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;
}
}
@@ -0,0 +1,57 @@
/*
* 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();
}
}
@@ -0,0 +1,82 @@
/*
* 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());
}
}
@@ -0,0 +1,79 @@
package net.draycia.carbon.common.listeners.contexts;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.PreChatFormatEvent;
import net.draycia.carbon.api.Context;
import net.kyori.event.PostOrders;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FilterContext {
private final @NonNull CarbonChat carbonChat;
@SuppressWarnings("method.invocation.invalid")
public FilterContext(final @NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
if (!carbonChat.moderationSettings().filters().enabled()) {
return;
}
if (event.user().hasPermission("carbonchat.filter.exempt")) {
return;
}
if (!this.channelUsesFilter(event.channel())) {
return;
}
String message = event.message();
for (final Map.Entry<String, List<Pattern>> entry :
this.carbonChat.moderationSettings().filters().replacements().entrySet()) {
for (final Pattern pattern : entry.getValue()) {
final Matcher matcher = pattern.matcher(message);
if (entry.getKey().equals("_")) {
message = matcher.replaceAll("");
} else {
message = matcher.replaceAll(entry.getKey());
}
}
}
event.message(message);
for (final Pattern blockedWord : this.carbonChat.moderationSettings().filters().blockedPatterns()) {
if (blockedWord.matcher(event.message()).find()) {
event.cancelled(true);
break;
}
}
});
}
private boolean channelUsesFilter(final @NonNull ChatChannel chatChannel) {
if (chatChannel instanceof TextChannel) {
final Context context = ((TextChannel) chatChannel).context("filter");
if (context == null) {
return false;
}
return context.isBoolean() && context.asBoolean();
}
return false;
}
}
@@ -0,0 +1,45 @@
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());
}
});
}
}
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff. Show more