Merge pull request #76 from Hexaoxide/checkstyle-format

Checkstyle format
This commit is contained in:
Josh (Vicarious) authored and GitHub committed 2020-09-10 02:36:49 -07:00
commit 5ba9f6d08e
77 files changed
+2056 -1709

No files matched your search

+172
View File
@@ -0,0 +1,172 @@
<?xml version="1.0" encoding="utf-8" ?>
<!-- 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.-->
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="error"/>
<property name="fileExtensions" value="java, properties, xml"/>
<!-- Excludes all 'module-info.java' files -->
<!-- See https://checkstyle.org/config_filefilters.html -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<!-- https://checkstyle.org/config_filters.html#SuppressionFilter -->
<module name="SuppressionFilter">
<property name="file" value="${basedir}/suppressions.xml"
default=".checkstyle/suppressions.xml" />
<property name="optional" value="true"/>
</module>
<!-- allow // CHECKSTYLE:OFF and // CHECKSTYLE:ON comments -->
<module name="SuppressWithPlainTextCommentFilter"/>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.org/config_whitespace.html -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="NewlineAtEndOfFile"/>
<module name="SuppressWarningsFilter" />
<module name="TreeWalker">
<!-- Make the @SuppressWarnings annotations available to Checkstyle -->
<module name="SuppressWarningsHolder" />
<!-- no space between parameters and parenthesis -->
<module name="EmptyForInitializerPad"/>
<module name="EmptyForIteratorPad"/>
<!-- one empty line between each class element -->
<module name="EmptyLineSeparator">
<!-- No new line after the license header -->
<property name="tokens"
value="IMPORT, STATIC_IMPORT, CLASS_DEF, INTERFACE_DEF, ENUM_DEF,
STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
<property name="allowNoEmptyLineBetweenFields" value="true"/>
<property name="allowMultipleEmptyLines" value="false"/>
<property name="allowMultipleEmptyLinesInsideClassMembers" value="false"/>
</module>
<module name="GenericWhitespace"/>
<!-- packages and imports must be on one line each -->
<module name="NoLineWrap"/>
<module name="SingleSpaceSeparator">
<property name="validateComments" value="true"/>
</module>
<module name="TypecastParenPad"/>
<module name="UnnecessaryParentheses"/>
<!-- field and method access qualified with `this` -->
<module name="FinalLocalVariable">
<property name="validateEnhancedForLoopVariable" value="true"/>
<property name="tokens" value="VARIABLE_DEF, PARAMETER_DEF"/>
</module>
<module name="RequireThis">
<property name="validateOnlyOverlapping" value="false"/>
</module>
<!-- coding practices -->
<module name="RedundantImport"/>
<module name="RedundantModifier">
<!-- Take out METHOD_DEF and RESOURCE so we can have finals -->
<property name="tokens"
value="VARIABLE_DEF, ANNOTATION_FIELD_DEF, INTERFACE_DEF, CTOR_DEF, CLASS_DEF, ENUM_DEF"/>
</module>
<module name="UnusedImports"/>
<module name="HideUtilityClassConstructor"/>
<module name="FinalClass"/>
<!-- no local variable type annotations -->
<module name="NoLvTypeAnnotations"/>
<!-- braces and parentheses on block statements on same line -->
<module name="LeftCurly"/>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE,
LITERAL_DO"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens"
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, STATIC_INIT,
INSTANCE_INIT, ANNOTATION_DEF, ENUM_DEF"/>
</module>
<!-- 2 space indentation -->
<module name="Indentation">
<property name="basicOffset" value="2"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="2"/>
<property name="throwsIndent" value="2"/>
<property name="lineWrappingIndentation" value="0"/>
<property name="arrayInitIndent" value="2"/>
</module>
<module name="CommentsIndentation"/>
<!-- some generally unwanted imports -->
<module name="IllegalImport">
<property name="illegalPkgs" value="sun, jdk, com.sun"/>
</module>
<!-- no get* or set* method names -->
<module name="MethodName">
<property name="format" value="^(?:(?:.{1,3})|(?:[gs]et[^A-Z].*)|(?:(?:[^gsA-Z]..|.[^e].|..[^t]).+))$"/>
</module>
<!-- misc formatting based on Google style -->
<!-- match filenames, don't use unicode escapes, no star imports -->
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format"
value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message"
value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="AvoidStarImport"/>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="FallThrough"/>
<module name="NoFinalizer"/>
<module name="MethodParamPad">
<property name="tokens"
value="CTOR_DEF, LITERAL_NEW, METHOD_CALL, METHOD_DEF,
SUPER_CTOR_CALL, ENUM_CONSTANT_DEF"/>
</module>
<module name="WhitespaceAfter"/>
</module>
</module>
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 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.-->
<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"http://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<!-- add any necessary suppressions here -->
<suppress files="src[\\/]test[\\/]java[\\/].*" checks="RequireExplicitVisibilityModifier"/>
<suppress files="Metrics\.java" checks="[a-zA-Z0-9]*"/>
</suppressions>
+30
View File
@@ -0,0 +1,30 @@
# 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.
root = true
[*]
charset = utf-8
indent_size = 2
indent_style = space
insert_final_newline = true
max_line_length = off
+11 -4
View File
@@ -1,4 +1,5 @@
plugins { plugins {
id 'checkstyle'
id 'java' id 'java'
id 'java-library' id 'java-library'
id 'maven' id 'maven'
@@ -17,6 +18,13 @@ group = 'net.draycia'
description = 'CarbonChat' description = 'CarbonChat'
version = project.property('projectVersion') + '-' + gitHash version = project.property('projectVersion') + '-' + gitHash
checkstyle {
def configRoot = new File(rootProject.projectDir, '.checkstyle')
toolVersion = '8.34'
configDirectory = configRoot
configProperties = [basedir: configRoot.getAbsolutePath()]
}
repositories { repositories {
mavenLocal() mavenLocal()
mavenCentral() mavenCentral()
@@ -35,6 +43,8 @@ repositories {
} }
dependencies { dependencies {
checkstyle("ca.stellardrift:stylecheck:0.1-SNAPSHOT")
// Components // Components
compile 'net.kyori:adventure-api:4.0.0-SNAPSHOT' compile 'net.kyori:adventure-api:4.0.0-SNAPSHOT'
compile 'net.kyori:adventure-nbt:4.0.0-SNAPSHOT' compile 'net.kyori:adventure-nbt:4.0.0-SNAPSHOT'
@@ -97,10 +107,7 @@ sourceCompatibility = '1.8'
// Set output directory and encoding // Set output directory and encoding
tasks.withType(JavaCompile) { tasks.withType(JavaCompile) {
options.encoding = 'UTF-8' options.encoding = 'UTF-8'
} options.compilerArgs += ['-Xlint:all']
tasks.withType(Jar) {
getDestinationDirectory().set(file("$rootDir/build"))
} }
// Automatically shadowJar when building // Automatically shadowJar when building
@@ -1,8 +1,27 @@
package net.draycia.carbon; package net.draycia.carbon;
import dev.jorel.commandapi.CommandAPI; import dev.jorel.commandapi.CommandAPI;
import net.draycia.carbon.channels.contexts.impl.*; import net.draycia.carbon.channels.contexts.impl.DistanceContext;
import net.draycia.carbon.listeners.*; import net.draycia.carbon.channels.contexts.impl.EconomyContext;
import net.draycia.carbon.channels.contexts.impl.TownyContext;
import net.draycia.carbon.channels.contexts.impl.WorldGuardContext;
import net.draycia.carbon.channels.contexts.impl.mcMMOContext;
import net.draycia.carbon.listeners.BukkitChatListener;
import net.draycia.carbon.listeners.CapsHandler;
import net.draycia.carbon.listeners.CustomPlaceholderHandler;
import net.draycia.carbon.listeners.FilterHandler;
import net.draycia.carbon.listeners.IgnoredPlayerHandler;
import net.draycia.carbon.listeners.ItemLinkHandler;
import net.draycia.carbon.listeners.LegacyFormatHandler;
import net.draycia.carbon.listeners.MuteHandler;
import net.draycia.carbon.listeners.OfflineNameHandler;
import net.draycia.carbon.listeners.PingHandler;
import net.draycia.carbon.listeners.PlaceholderHandler;
import net.draycia.carbon.listeners.PlayerJoinListener;
import net.draycia.carbon.listeners.RelationalPlaceholderHandler;
import net.draycia.carbon.listeners.ShadowMuteHandler;
import net.draycia.carbon.listeners.UserFormattingHandler;
import net.draycia.carbon.listeners.WhisperPingHandler;
import net.draycia.carbon.managers.AdventureManager; import net.draycia.carbon.managers.AdventureManager;
import net.draycia.carbon.managers.ChannelManager; import net.draycia.carbon.managers.ChannelManager;
import net.draycia.carbon.managers.CommandManager; import net.draycia.carbon.managers.CommandManager;
@@ -61,72 +80,72 @@ public final class CarbonChat extends JavaPlugin {
@Override @Override
public void onEnable() { public void onEnable() {
checkForBungee(); this.checkForBungee();
CommandAPI.onEnable(this); CommandAPI.onEnable(this);
Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID); final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
// Ensure config is present to be modified by the user // Ensure config is present to be modified by the user
if (!(new File(getDataFolder(), "config.yml").exists())) { if (!(new File(this.getDataFolder(), "config.yml").exists())) {
saveDefaultConfig(); this.saveDefaultConfig();
} }
if (!(new File(getDataFolder(), "moderation.yml").exists())) { if (!(new File(this.getDataFolder(), "moderation.yml").exists())) {
saveResource("moderation.yml", false); this.saveResource("moderation.yml", false);
} }
if (!(new File(getDataFolder(), "language.yml").exists())) { if (!(new File(this.getDataFolder(), "language.yml").exists())) {
saveResource("language.yml", false); this.saveResource("language.yml", false);
} }
if (!(new File(getDataFolder(), "commands.yml").exists())) { if (!(new File(this.getDataFolder(), "commands.yml").exists())) {
saveResource("commands.yml", false); this.saveResource("commands.yml", false);
} }
loadModConfig(); this.loadModConfig();
loadLanguage(); this.loadLanguage();
// Setup Adventure // Setup Adventure
adventureManager = new AdventureManager(this); this.adventureManager = new AdventureManager(this);
// Setup vault and permissions // Setup vault and permissions
permission = getServer().getServicesManager().getRegistration(Permission.class).getProvider(); this.permission = this.getServer().getServicesManager().getRegistration(Permission.class).getProvider();
// Initialize managers // Initialize managers
channelManager = new ChannelManager(this); this.channelManager = new ChannelManager(this);
contextManager = new ContextManager(); this.contextManager = new ContextManager();
messageManager = new MessageManager(this); this.messageManager = new MessageManager(this);
commandManager = new CommandManager(this); this.commandManager = new CommandManager(this);
String storageType = getConfig().getString("storage.type"); final String storageType = this.getConfig().getString("storage.type");
if (storageType.equalsIgnoreCase("mysql")) { if (storageType.equalsIgnoreCase("mysql")) {
getLogger().info("Enabling MySQL storage!"); this.getLogger().info("Enabling MySQL storage!");
userService = new MySQLUserService(this); this.userService = new MySQLUserService(this);
} else if (storageType.equalsIgnoreCase("json")) { } else if (storageType.equalsIgnoreCase("json")) {
getLogger().info("Enabling JSON storage!"); this.getLogger().info("Enabling JSON storage!");
userService = new JSONUserService(this); this.userService = new JSONUserService(this);
} else { } else {
getLogger().warning("Invalid storage type selected! Falling back to JSON."); this.getLogger().warning("Invalid storage type selected! Falling back to JSON.");
userService = new JSONUserService(this); this.userService = new JSONUserService(this);
} }
// Setup listeners // Setup listeners
setupListeners(); this.setupListeners();
registerContexts(); this.registerContexts();
new CarbonPlaceholders(this).register(); new CarbonPlaceholders(this).register();
if (Bukkit.getPluginManager().isPluginEnabled("Towny")) { if (Bukkit.getPluginManager().isPluginEnabled("Towny")) {
getServer().getPluginManager().registerEvents(new TownyContext(this), this); this.getServer().getPluginManager().registerEvents(new TownyContext(this), this);
} }
if (Bukkit.getPluginManager().isPluginEnabled("mcMMO")) { if (Bukkit.getPluginManager().isPluginEnabled("mcMMO")) {
getServer().getPluginManager().registerEvents(new mcMMOContext(this), this); this.getServer().getPluginManager().registerEvents(new mcMMOContext(this), this);
} }
if (Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) { if (Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) {
getServer().getPluginManager().registerEvents(new WorldGuardContext(this), this); this.getServer().getPluginManager().registerEvents(new WorldGuardContext(this), this);
} }
if (Bukkit.getServicesManager().isProvidedFor(Economy.class)) { if (Bukkit.getServicesManager().isProvidedFor(Economy.class)) {
@@ -134,25 +153,25 @@ public final class CarbonChat extends JavaPlugin {
} }
if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) { if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
getLogger().warning("Item linking disabled! Please use Paper 1.16.2 #172 or newer."); this.getLogger().warning("Item linking disabled! Please use Paper 1.16.2 #172 or newer.");
} }
} }
@Override @Override
public void onDisable() { public void onDisable() {
userService.onDisable(); this.userService.onDisable();
} }
private void setupListeners() { private void setupListeners() {
PluginManager pluginManager = getServer().getPluginManager(); final PluginManager pluginManager = this.getServer().getPluginManager();
filterHandler = new FilterHandler(this); this.filterHandler = new FilterHandler(this);
// Register chat listeners // Register chat listeners
pluginManager.registerEvents(new BukkitChatListener(this), this); pluginManager.registerEvents(new BukkitChatListener(this), this);
pluginManager.registerEvents(new CapsHandler(this), this); pluginManager.registerEvents(new CapsHandler(this), this);
pluginManager.registerEvents(new CustomPlaceholderHandler(this), this); pluginManager.registerEvents(new CustomPlaceholderHandler(this), this);
pluginManager.registerEvents(filterHandler, this); pluginManager.registerEvents(this.filterHandler, this);
pluginManager.registerEvents(new IgnoredPlayerHandler(), this); pluginManager.registerEvents(new IgnoredPlayerHandler(), this);
pluginManager.registerEvents(new ItemLinkHandler(), this); pluginManager.registerEvents(new ItemLinkHandler(), this);
pluginManager.registerEvents(new LegacyFormatHandler(), this); pluginManager.registerEvents(new LegacyFormatHandler(), this);
@@ -172,92 +191,93 @@ public final class CarbonChat extends JavaPlugin {
public void reloadConfig() { public void reloadConfig() {
super.reloadConfig(); super.reloadConfig();
loadModConfig(); this.loadModConfig();
loadLanguage(); this.loadLanguage();
loadCommandsConfig(); this.loadCommandsConfig();
} }
public void reloadFilters() { public void reloadFilters() {
filterHandler.reloadFilters(); this.filterHandler.reloadFilters();
} }
private boolean bungeeEnabled = false; private boolean bungeeEnabled = false;
private void checkForBungee() { private void checkForBungee() {
try { try {
Class<?> spigotConfig = Class.forName("org.spigotmc.Spigotconfig"); final Class<?> spigotConfig = Class.forName("org.spigotmc.Spigotconfig");
Field bungee = spigotConfig.getField("bungee"); final Field bungee = spigotConfig.getField("bungee");
bungeeEnabled = bungee.getBoolean(null); this.bungeeEnabled = bungee.getBoolean(null);
} catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ignored) { } } catch (final ClassNotFoundException | NoSuchFieldException | IllegalAccessException ignored) {
}
} }
public boolean isBungeeEnabled() { public boolean bungeeEnabled() {
return bungeeEnabled; return this.bungeeEnabled;
} }
private void loadModConfig() { private void loadModConfig() {
modConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "moderation.yml")); this.modConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "moderation.yml"));
} }
private void loadLanguage() { private void loadLanguage() {
languageConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "language.yml")); this.languageConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "language.yml"));
} }
private void loadCommandsConfig() { private void loadCommandsConfig() {
commandsConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "commands.yml")); this.commandsConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "commands.yml"));
} }
private void registerContexts() { private void registerContexts() {
getContextManager().register("distance", new DistanceContext()); this.contextManager().register("distance", new DistanceContext());
} }
@NonNull @NonNull
public YamlConfiguration getModConfig() { public YamlConfiguration moderationConfig() {
return modConfig; return this.modConfig;
} }
@NonNull @NonNull
public YamlConfiguration getCommandsConfig() { public YamlConfiguration commandsConfig() {
return commandsConfig; return this.commandsConfig;
} }
@NonNull @NonNull
public YamlConfiguration getLanguage() { public YamlConfiguration language() {
return languageConfig; return this.languageConfig;
} }
@NonNull @NonNull
public Permission getPermission() { public Permission permission() {
return permission; return this.permission;
} }
@NonNull @NonNull
public CommandManager getCommandManager() { public CommandManager commandManager() {
return commandManager; return this.commandManager;
} }
@NonNull @NonNull
public ChannelManager getChannelManager() { public ChannelManager channelManager() {
return channelManager; return this.channelManager;
} }
@NonNull @NonNull
public MessageManager getMessageManager() { public MessageManager messageManager() {
return messageManager; return this.messageManager;
} }
@NonNull @NonNull
public UserService getUserService() { public UserService userService() {
return userService; return this.userService;
} }
@NonNull @NonNull
public AdventureManager getAdventureManager() { public AdventureManager adventureManager() {
return adventureManager; return this.adventureManager;
} }
@NonNull @NonNull
public ContextManager getContextManager() { public ContextManager contextManager() {
return contextManager; return this.contextManager;
} }
} }
@@ -9,7 +9,11 @@ import org.bukkit.event.Listener;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.*; import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ChannelRegistry implements Registry<ChatChannel> { public class ChannelRegistry implements Registry<ChatChannel> {
@@ -22,21 +26,21 @@ public class ChannelRegistry implements Registry<ChatChannel> {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public ChannelRegistry(@NonNull CarbonChat carbonChat) { public ChannelRegistry(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
} }
@Override @Override
public boolean register(@NonNull String key, @NonNull ChatChannel value) { public boolean register(@NonNull final String key, @NonNull final ChatChannel value) {
boolean registerSuccessful = registry.putIfAbsent(key, value) == null; final boolean registerSuccessful = this.registry.putIfAbsent(key, value) == null;
if (registerSuccessful) { if (registerSuccessful) {
AliasedChannelCommand command = new AliasedChannelCommand(carbonChat, value); final AliasedChannelCommand command = new AliasedChannelCommand(this.carbonChat, value);
channelCommands.add(command); this.channelCommands.add(command);
if (value instanceof Listener) { if (value instanceof Listener) {
Bukkit.getPluginManager().registerEvents((Listener) value, carbonChat); Bukkit.getPluginManager().registerEvents((Listener) value, this.carbonChat);
} }
} }
@@ -46,22 +50,22 @@ public class ChannelRegistry implements Registry<ChatChannel> {
@Override @Override
@NonNull @NonNull
public Collection<@NonNull ChatChannel> values() { public Collection<@NonNull ChatChannel> values() {
return registry.values(); return this.registry.values();
} }
@Override @Override
@Nullable @Nullable
public ChatChannel get(@NonNull String key) { public ChatChannel channel(@NonNull final String key) {
return registry.get(key); return this.registry.get(key);
} }
@Override @Override
public void clearAll() { public void clearAll() {
registry.clear(); this.registry.clear();
for (AliasedChannelCommand command : channelCommands) { for (final AliasedChannelCommand command : this.channelCommands) {
carbonChat.getLogger().info("Unregistering command for channel: " + command.getChatChannel().getName()); this.carbonChat.getLogger().info("Unregistering command for channel: " + command.chatChannel().name());
CommandAPI.unregister(command.getCommandName()); CommandAPI.unregister(command.commandName());
} }
} }
@@ -14,17 +14,20 @@ import java.util.regex.Pattern;
public abstract class ChatChannel implements ForwardingAudience { public abstract class ChatChannel implements ForwardingAudience {
@NonNull
public abstract List<ChatUser> audiences();
/** /**
* @return The color that represents this channel. Optionally used in formatting. * @return The color that represents this channel. Optionally used in formatting.
*/ */
@Nullable @Nullable
public abstract TextColor getChannelColor(@NonNull ChatUser user); public abstract TextColor channelColor(@NonNull ChatUser user);
/** /**
* @return The MiniMessage styled format for the group in this channel. * @return The MiniMessage styled format for the group in this channel.
*/ */
@Nullable @Nullable
public abstract String getFormat(@NonNull String group); public abstract String format(@NonNull String group);
/** /**
* @return If this is the default (typically Global) channel players use when they're in no other channel. * @return If this is the default (typically Global) channel players use when they're in no other channel.
@@ -34,70 +37,70 @@ public abstract class ChatChannel implements ForwardingAudience {
/** /**
* @return If this channel can be toggled off and if players can ignore player messages in this channel. * @return If this channel can be toggled off and if players can ignore player messages in this channel.
*/ */
public abstract boolean isIgnorable(); public abstract boolean ignorable();
/** /**
* @return If this channel should be synced cross server * @return If this channel should be synced cross server
* @deprecated Use {@link #isCrossServer()} instead * @deprecated Use {@link #crossServer()} instead
*/ */
@Deprecated @Deprecated
public abstract boolean shouldBungee(); public abstract boolean bungee();
/** /**
* @return If this channel should be synced cross server * @return If this channel should be synced cross server
*/ */
public abstract boolean isCrossServer(); public abstract boolean crossServer();
/** /**
* @return The name of this channel. * @return The name of this channel.
*/ */
@NonNull @NonNull
public abstract String getName(); public abstract String name();
@NonNull @NonNull
public abstract String getKey(); public abstract String key();
@Nullable @Nullable
public abstract String getMessagePrefix(); public abstract String messagePrefix();
@Nullable @Nullable
public abstract String getAliases(); public abstract String aliases();
/** /**
* @return The message to be sent to the player when switching to this channel. * @return The message to be sent to the player when switching to this channel.
*/ */
@Nullable @Nullable
public abstract String getSwitchMessage(); public abstract String switchMessage();
@Nullable @Nullable
public abstract String getSwitchOtherMessage(); public abstract String switchOtherMessage();
@Nullable @Nullable
public abstract String getSwitchFailureMessage(); public abstract String switchFailureMessage();
@Nullable @Nullable
public abstract String getCannotIgnoreMessage(); public abstract String cannotIgnoreMessage();
/** /**
* @return The message to be send to the player when toggling this channel off. * @return The message to be send to the player when toggling this channel off.
*/ */
@Nullable @Nullable
public abstract String getToggleOffMessage(); public abstract String toggleOffMessage();
/** /**
* @return The message to be send to the player when toggling this channel on. * @return The message to be send to the player when toggling this channel on.
*/ */
@Nullable @Nullable
public abstract String getToggleOnMessage(); public abstract String toggleOnMessage();
@Nullable @Nullable
public abstract String getToggleOtherOnMessage(); public abstract String toggleOtherOnMessage();
@Nullable @Nullable
public abstract String getToggleOtherOffMessage(); public abstract String toggleOtherOffMessage();
@Nullable @Nullable
public abstract String getCannotUseMessage(); public abstract String cannotUseMessage();
public abstract boolean primaryGroupOnly(); public abstract boolean primaryGroupOnly();
@@ -105,13 +108,18 @@ public abstract class ChatChannel implements ForwardingAudience {
public abstract boolean permissionGroupMatching(); public abstract boolean permissionGroupMatching();
public abstract boolean shouldCancelChatEvent();
public abstract boolean testContext(@NonNull ChatUser sender, @NonNull ChatUser target); public abstract boolean testContext(@NonNull ChatUser sender, @NonNull ChatUser target);
@NonNull
public abstract List<@NonNull Pattern> itemLinkPatterns();
@Nullable @Nullable
public abstract Object getContext(@NonNull String key); public abstract Object context(@NonNull String key);
@NonNull @NonNull
public abstract List<@NonNull String> getGroupOverrides(); public abstract List<@NonNull String> groupOverrides();
/** /**
* @return If the player can use this channel. * @return If the player can use this channel.
@@ -122,16 +130,6 @@ public abstract class ChatChannel implements ForwardingAudience {
public abstract boolean canPlayerSee(@NonNull ChatUser target, boolean checkSpying); public abstract boolean canPlayerSee(@NonNull ChatUser target, boolean checkSpying);
/**
* @return If the channel should forward its formatting / formatted message to other servers
*/
public boolean shouldForwardFormatting() {
return true;
}
@NonNull
public abstract List<@NonNull Pattern> getItemLinkPatterns();
/** /**
* Parses the specified message, calls a {@link PreChatFormatEvent}, and sends the message to everyone who can view this channel. * Parses the specified message, calls a {@link PreChatFormatEvent}, and sends the message to everyone who can view this channel.
* *
@@ -147,8 +145,8 @@ public abstract class ChatChannel implements ForwardingAudience {
public abstract void sendComponent(@NonNull ChatUser user, @NonNull Component component); public abstract void sendComponent(@NonNull ChatUser user, @NonNull Component component);
@Nullable @Nullable
public String processPlaceholders(@NonNull ChatUser user, @Nullable String input) { return input; } public String processPlaceholders(@NonNull final ChatUser user, @Nullable final String input) {
return input;
public abstract boolean shouldCancelChatEvent(); }
} }
@@ -7,45 +7,45 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public interface MessageContext { public interface MessageContext {
@NonNull @NonNull
ChatUser getSender(); ChatUser sender();
@NonNull @NonNull
ChatUser getTarget(); ChatUser target();
ChatChannel getChatChannel(); ChatChannel chatChannel();
Object getValue(); Object value();
default boolean isDouble() { default boolean isDouble() {
return getValue() instanceof Double; return this.value() instanceof Double;
} }
default boolean isString() { default boolean isString() {
return getValue() instanceof String; return this.value() instanceof String;
} }
default boolean isInteger() { default boolean isInteger() {
return getValue() instanceof Integer; return this.value() instanceof Integer;
} }
default boolean isBoolean() { default boolean isBoolean() {
return getValue() instanceof Boolean; return this.value() instanceof Boolean;
} }
default Double asDouble() { default Double asDouble() {
return (Double)getValue(); return (Double) this.value();
} }
default String asString() { default String asString() {
return (String)getValue(); return (String) this.value();
} }
default Integer asInteger() { default Integer asInteger() {
return (Integer)getValue(); return (Integer) this.value();
} }
default Boolean asBoolean() { default Boolean asBoolean() {
return (Boolean)getValue(); return (Boolean) this.value();
} }
} }
@@ -10,8 +10,8 @@ public class DistanceContext implements Function<MessageContext, Boolean> {
@Override @Override
@NonNull @NonNull
public Boolean apply(@NonNull MessageContext context) { public Boolean apply(@NonNull final MessageContext context) {
if (!context.getSender().isOnline() || !context.getTarget().isOnline()) { if (!context.sender().online() || !context.target().online()) {
return false; return false;
} }
@@ -19,15 +19,15 @@ public class DistanceContext implements Function<MessageContext, Boolean> {
return true; return true;
} }
Location senderLocation = context.getSender().asPlayer().getLocation(); final Location senderLocation = context.sender().player().getLocation();
Location targetLocation = context.getTarget().asPlayer().getLocation(); final Location targetLocation = context.target().player().getLocation();
if (!senderLocation.getWorld().equals(targetLocation.getWorld())) { if (!senderLocation.getWorld().equals(targetLocation.getWorld())) {
return false; return false;
} }
if (context.isDouble()) { if (context.isDouble()) {
Double value = context.asDouble(); final Double value = context.asDouble();
if (value > 0) { if (value > 0) {
return senderLocation.distance(targetLocation) <= value; return senderLocation.distance(targetLocation) <= value;
@@ -15,16 +15,16 @@ public class EconomyContext implements Listener {
@NonNull @NonNull
private final Economy economy; private final Economy economy;
public EconomyContext(@NonNull CarbonChat carbonChat) { public EconomyContext(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.economy = carbonChat.getServer().getServicesManager().getRegistration(Economy.class).getProvider(); this.economy = this.carbonChat.getServer().getServicesManager().getRegistration(Economy.class).getProvider();
} }
@EventHandler @EventHandler
public void onChatReqBal(PreChatFormatEvent event) { public void onChatReqBal(final PreChatFormatEvent event) {
Object requiredBalObject = event.getChannel().getContext("vault-balance"); final Object requiredBalObject = event.channel().context("vault-balance");
Double requiredBal; final Double requiredBal;
if (requiredBalObject instanceof Double) { if (requiredBalObject instanceof Double) {
requiredBal = (Double) requiredBalObject; requiredBal = (Double) requiredBalObject;
@@ -38,22 +38,22 @@ public class EconomyContext implements Listener {
return; return;
} }
Player player = event.getUser().asPlayer(); final Player player = event.user().player();
if (!economy.has(player, requiredBal)) { if (!this.economy.has(player, requiredBal)) {
event.setCancelled(true); event.setCancelled(true);
event.getUser().sendMessage(carbonChat.getAdventureManager() event.user().sendMessage(this.carbonChat.adventureManager()
.processMessageWithPapi(player, event.getChannel().getCannotUseMessage())); .processMessageWithPapi(player, event.channel().cannotUseMessage()));
} }
} }
@EventHandler @EventHandler
public void onChatCost(PreChatFormatEvent event) { public void onChatCost(final PreChatFormatEvent event) {
Object costObject = event.getChannel().getContext("vault-cost"); final Object costObject = event.channel().context("vault-cost");
Double cost; final Double cost;
if (costObject instanceof Double) { if (costObject instanceof Double) {
cost = (Double) costObject; cost = (Double) costObject;
@@ -67,17 +67,17 @@ public class EconomyContext implements Listener {
return; return;
} }
Player player = event.getUser().asPlayer(); final Player player = event.user().player();
if (!economy.has(player, cost)) { if (!this.economy.has(player, cost)) {
event.setCancelled(true); event.setCancelled(true);
event.getUser().sendMessage(carbonChat.getAdventureManager() event.user().sendMessage(this.carbonChat.adventureManager()
.processMessageWithPapi(player, event.getChannel().getCannotUseMessage())); .processMessageWithPapi(player, event.channel().cannotUseMessage()));
return; return;
} }
economy.withdrawPlayer(player, cost); this.economy.withdrawPlayer(player, cost);
} }
} }
@@ -6,6 +6,7 @@ import net.draycia.carbon.storage.ChatUser;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
public class SimpleMessageContext implements MessageContext { public class SimpleMessageContext implements MessageContext {
@NonNull @NonNull
private final ChatUser sender; private final ChatUser sender;
@@ -15,7 +16,8 @@ public class SimpleMessageContext implements MessageContext {
private final ChatChannel chatChannel; private final ChatChannel chatChannel;
private final Object value; private final Object value;
public SimpleMessageContext(@NonNull ChatUser sender, @NonNull ChatUser target, ChatChannel chatChannel, Object value) { public SimpleMessageContext(@NonNull final ChatUser sender, @NonNull final ChatUser target,
@NonNull final ChatChannel chatChannel, @NonNull final Object value) {
this.sender = sender; this.sender = sender;
this.target = target; this.target = target;
this.chatChannel = chatChannel; this.chatChannel = chatChannel;
@@ -24,23 +26,24 @@ public class SimpleMessageContext implements MessageContext {
@Override @Override
@NonNull @NonNull
public ChatUser getSender() { public ChatUser sender() {
return sender; return this.sender;
} }
@Override @Override
@NonNull @NonNull
public ChatUser getTarget() { public ChatUser target() {
return target; return this.target;
} }
@Override @Override
public ChatChannel getChatChannel() { public ChatChannel chatChannel() {
return chatChannel; return this.chatChannel;
} }
@Override @Override
public Object getValue() { public Object value() {
return value; return this.value;
} }
} }
@@ -21,12 +21,12 @@ public final class TownyContext implements Listener {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public TownyContext(@NonNull CarbonChat carbonChat) { public TownyContext(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.carbonChat.getContextManager().register(KEY, (context) -> { this.carbonChat.contextManager().register(KEY, context -> {
if ((context.getValue() instanceof Boolean) && ((Boolean) context.getValue())) { if ((context.value() instanceof Boolean) && ((Boolean) context.value())) {
return isInSameTown(context.getSender(), context.getTarget()); return this.isInSameTown(context.sender(), context.target());
} }
return true; return true;
@@ -34,34 +34,34 @@ public final class TownyContext implements Listener {
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onChannelSwitch(ChannelSwitchEvent event) { public void onChannelSwitch(final ChannelSwitchEvent event) {
Object town = event.getChannel().getContext(KEY); final Object town = event.channel().context(KEY);
if ((town instanceof Boolean) && ((Boolean) town)) { if ((town instanceof Boolean) && ((Boolean) town)) {
if (!isInTown(event.getUser())) { if (!this.isInTown(event.user())) {
event.setCancelled(true); event.setCancelled(true);
event.setFailureMessage(carbonChat.getConfig().getString("contexts.Towny.cancellation-message")); event.failureMessage(this.carbonChat.getConfig().getString("contexts.Towny.cancellation-message"));
} }
} }
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onChannelMessage(PreChatFormatEvent event) { public void onChannelMessage(final PreChatFormatEvent event) {
// TODO: event.setFailureMessage // TODO: event.setFailureMessage
Object town = event.getChannel().getContext(KEY); final Object town = event.channel().context(KEY);
if ((town instanceof Boolean) && ((Boolean) town)) { if ((town instanceof Boolean) && ((Boolean) town)) {
if (!isInTown(event.getUser())) { if (!this.isInTown(event.user())) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
@EventHandler @EventHandler
public void onResidentRemove(TownRemoveResidentEvent event) { public void onResidentRemove(final TownRemoveResidentEvent event) {
String name = event.getResident().getName(); final String name = event.getResident().getName();
ChatUser user = carbonChat.getUserService().wrap(name); final ChatUser user = this.carbonChat.userService().wrap(name);
Object town = user.getSelectedChannel().getContext(KEY); final Object town = user.selectedChannel().context(KEY);
if ((town instanceof Boolean) && ((Boolean) town)) { if ((town instanceof Boolean) && ((Boolean) town)) {
user.clearSelectedChannel(); user.clearSelectedChannel();
@@ -69,38 +69,38 @@ public final class TownyContext implements Listener {
} }
@EventHandler @EventHandler
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(final PlayerJoinEvent event) {
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
Object town = user.getSelectedChannel().getContext(KEY); final Object town = user.selectedChannel().context(KEY);
if ((town instanceof Boolean) && ((Boolean) town) && !isInTown(user)) { if ((town instanceof Boolean) && ((Boolean) town) && !this.isInTown(user)) {
user.clearSelectedChannel(); user.clearSelectedChannel();
} }
} }
public boolean isInTown(@NonNull ChatUser user) { public boolean isInTown(@NonNull final ChatUser user) {
try { try {
return TownyAPI.getInstance().getDataSource().getResident(user.asPlayer().getName()).hasTown(); return TownyAPI.getInstance().getDataSource().getResident(user.player().getName()).hasTown();
} catch (NotRegisteredException e) { } catch (final NotRegisteredException exception) {
e.printStackTrace(); exception.printStackTrace();
} }
return false; return false;
} }
public boolean isInSameTown(@NonNull ChatUser user1, @NonNull ChatUser user2) { public boolean isInSameTown(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
if (!user1.isOnline() || !user2.isOnline()) { if (!user1.online() || !user2.online()) {
return false; return false;
} }
try { try {
Resident resident = TownyAPI.getInstance().getDataSource().getResident(user1.asPlayer().getName()); final Resident resident = TownyAPI.getInstance().getDataSource().getResident(user1.player().getName());
if (resident.hasTown()) { if (resident.hasTown()) {
return resident.getTown().hasResident(user2.asPlayer().getName()); return resident.getTown().hasResident(user2.player().getName());
} }
} catch (NotRegisteredException e) { } catch (final NotRegisteredException exception) {
e.printStackTrace(); exception.printStackTrace();
} }
return false; return false;
@@ -24,40 +24,40 @@ public final class WorldGuardContext implements Listener {
@NonNull @NonNull
private static final String KEY = "worldguard-region"; private static final String KEY = "worldguard-region";
public WorldGuardContext(@NonNull CarbonChat carbonChat) { public WorldGuardContext(@NonNull final CarbonChat carbonChat) {
carbonChat.getContextManager().register(KEY, (context) -> { carbonChat.contextManager().register(KEY, context -> {
return this.testContext(context.getSender(), context.getTarget(), context.getValue()); return this.testContext(context.sender(), context.target(), context.value());
}); });
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onChannelSwitch(ChannelSwitchEvent event) { public void onChannelSwitch(final ChannelSwitchEvent event) {
// TODO: cancellation message // TODO: cancellation message
Object value = event.getChannel().getContext(KEY); final Object value = event.channel().context(KEY);
if ((value instanceof String || value instanceof List) && !isInRegionOrRegions(value, event.getUser())) { if ((value instanceof String || value instanceof List) && !this.isInRegionOrRegions(value, event.user())) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onChannelMessage(PreChatFormatEvent event) { public void onChannelMessage(final PreChatFormatEvent event) {
// TODO: cancellation message // TODO: cancellation message
Object value = event.getChannel().getContext(KEY); final Object value = event.channel().context(KEY);
if ((value instanceof String || value instanceof List) && !isInRegionOrRegions(value, event.getUser())) { if ((value instanceof String || value instanceof List) && !this.isInRegionOrRegions(value, event.user())) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
private boolean isInRegionOrRegions(@Nullable Object value, @NonNull ChatUser user) { private boolean isInRegionOrRegions(@Nullable final Object value, @NonNull final ChatUser user) {
if (value instanceof String) { if (value instanceof String) {
return isInRegion((String) value, user); return this.isInRegion((String) value, user);
} }
if (value instanceof List) { if (value instanceof List) {
for (String region : ((List<String>) value)) { for (final String region : (List<String>) value) {
if (isInRegion(region, user)) { if (this.isInRegion(region, user)) {
return true; return true;
} }
} }
@@ -66,23 +66,23 @@ public final class WorldGuardContext implements Listener {
return false; return false;
} }
public boolean testContext(@NonNull ChatUser sender, @NonNull ChatUser target, @Nullable Object value) { public boolean testContext(@NonNull final ChatUser sender, @NonNull final ChatUser target, @Nullable final Object value) {
boolean user1InRegion = false; boolean user1InRegion = false;
boolean user2InRegion = false; boolean user2InRegion = false;
if (value instanceof Boolean && (Boolean) value) { if (value instanceof Boolean && (Boolean) value) {
return isInSameRegion(sender, target); return this.isInSameRegion(sender, target);
} else if (value instanceof String) { } else if (value instanceof String) {
user1InRegion = isInRegion((String) value, sender); user1InRegion = this.isInRegion((String) value, sender);
user2InRegion = isInRegion((String) value, target); user2InRegion = this.isInRegion((String) value, target);
} else if (value instanceof List) { } else if (value instanceof List) {
for (String item : (List<String>) value) { for (final String item : (List<String>) value) {
if (!user1InRegion) { if (!user1InRegion) {
user1InRegion = isInRegion(item, sender); user1InRegion = this.isInRegion(item, sender);
} }
if (!user2InRegion) { if (!user2InRegion) {
user2InRegion = isInRegion(item, target); user2InRegion = this.isInRegion(item, target);
} }
} }
} else { } else {
@@ -92,21 +92,21 @@ public final class WorldGuardContext implements Listener {
return user1InRegion && user2InRegion; return user1InRegion && user2InRegion;
} }
public boolean isInSameRegion(@NonNull ChatUser user1, @NonNull ChatUser user2) { public boolean isInSameRegion(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
if (!user1.isOnline() || !user2.isOnline()) { if (!user1.online() || !user2.online()) {
return false; return false;
} }
Location user1Location = BukkitAdapter.adapt(user1.asPlayer().getLocation()); final Location user1Location = BukkitAdapter.adapt(user1.player().getLocation());
Location user2Location = BukkitAdapter.adapt(user2.asPlayer().getLocation()); final Location user2Location = BukkitAdapter.adapt(user2.player().getLocation());
RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); final RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
RegionQuery regionQuery = container.createQuery(); final RegionQuery regionQuery = container.createQuery();
ApplicableRegionSet user1Regions = regionQuery.getApplicableRegions(user1Location); final ApplicableRegionSet user1Regions = regionQuery.getApplicableRegions(user1Location);
ApplicableRegionSet user2Regions = regionQuery.getApplicableRegions(user2Location); final ApplicableRegionSet user2Regions = regionQuery.getApplicableRegions(user2Location);
for (ProtectedRegion region : user1Regions) { for (final ProtectedRegion region : user1Regions) {
if (user2Regions.getRegions().contains(region)) { if (user2Regions.getRegions().contains(region)) {
return true; return true;
} }
@@ -115,16 +115,16 @@ public final class WorldGuardContext implements Listener {
return false; return false;
} }
public boolean isInRegion(@NonNull String region, @NonNull ChatUser user) { public boolean isInRegion(@NonNull final String region, @NonNull final ChatUser user) {
RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); final RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
World world = BukkitAdapter.adapt(user.asPlayer().getWorld()); final World world = BukkitAdapter.adapt(user.player().getWorld());
ProtectedRegion protection = container.get(world).getRegion(region); final ProtectedRegion protection = container.get(world).getRegion(region);
return isInRegion(protection, user); return this.isInRegion(protection, user);
} }
public boolean isInRegion(@NonNull ProtectedRegion region, @NonNull ChatUser user) { public boolean isInRegion(@NonNull final ProtectedRegion region, @NonNull final ChatUser user) {
Location location = BukkitAdapter.adapt(user.asPlayer().getLocation()); final org.bukkit.Location location = user.player().getLocation();
return region.contains(location.getBlockX(), location.getBlockY(), location.getBlockZ()); return region.contains(location.getBlockX(), location.getBlockY(), location.getBlockZ());
} }
@@ -16,12 +16,12 @@ public final class mcMMOContext implements Listener {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public mcMMOContext(@NonNull CarbonChat carbonChat) { public mcMMOContext(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.carbonChat.getContextManager().register("mcmmo-party", (context) -> { this.carbonChat.contextManager().register("mcmmo-party", context -> {
if ((context.getValue() instanceof Boolean) && ((Boolean) context.getValue())) { if ((context.value() instanceof Boolean) && ((Boolean) context.value())) {
return isInSameParty(context.getSender(), context.getTarget()); return this.isInSameParty(context.sender(), context.target());
} }
return true; return true;
@@ -29,39 +29,39 @@ public final class mcMMOContext implements Listener {
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onChannelSwitch(ChannelSwitchEvent event) { public void onChannelSwitch(final ChannelSwitchEvent event) {
Object party = event.getChannel().getContext("mcmmo-party"); final Object party = event.channel().context("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party)) { if ((party instanceof Boolean) && ((Boolean) party)) {
if (!isInParty(event.getUser())) { if (!this.isInParty(event.user())) {
event.setCancelled(true); event.setCancelled(true);
event.setFailureMessage(carbonChat.getConfig().getString("contexts.mcMMO.cancellation-message")); event.failureMessage(this.carbonChat.getConfig().getString("contexts.mcMMO.cancellation-message"));
} }
} }
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onChannelMessage(PreChatFormatEvent event) { public void onChannelMessage(final PreChatFormatEvent event) {
Object party = event.getChannel().getContext("mcmmo-party"); final Object party = event.channel().context("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party)) { if ((party instanceof Boolean) && ((Boolean) party)) {
if (!isInParty(event.getUser())) { if (!this.isInParty(event.user())) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
private final McMMOPartyChangeEvent.EventReason LEFT = McMMOPartyChangeEvent.EventReason.LEFT_PARTY; private static final McMMOPartyChangeEvent.EventReason LEFT = McMMOPartyChangeEvent.EventReason.LEFT_PARTY;
private final McMMOPartyChangeEvent.EventReason KICKED = McMMOPartyChangeEvent.EventReason.KICKED_FROM_PARTY; private static final McMMOPartyChangeEvent.EventReason KICKED = McMMOPartyChangeEvent.EventReason.KICKED_FROM_PARTY;
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onPartyLeave(McMMOPartyChangeEvent event) { public void onPartyLeave(final McMMOPartyChangeEvent event) {
if (event.getReason() != LEFT && event.getReason() != KICKED) { if (event.getReason() != LEFT && event.getReason() != KICKED) {
return; return;
} }
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
Object party = user.getSelectedChannel().getContext("mcmmo-party"); final Object party = user.selectedChannel().context("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party)) { if ((party instanceof Boolean) && ((Boolean) party)) {
user.clearSelectedChannel(); user.clearSelectedChannel();
@@ -69,25 +69,25 @@ public final class mcMMOContext implements Listener {
} }
@EventHandler @EventHandler
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(final PlayerJoinEvent event) {
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
Object party = user.getSelectedChannel().getContext("mcmmo-party"); final Object party = user.selectedChannel().context("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party) && !isInParty(user)) { if ((party instanceof Boolean) && ((Boolean) party) && !this.isInParty(user)) {
user.clearSelectedChannel(); user.clearSelectedChannel();
} }
} }
public boolean isInParty(@NonNull ChatUser user) { public boolean isInParty(@NonNull final ChatUser user) {
return PartyAPI.inParty(user.asPlayer()); return PartyAPI.inParty(user.player());
} }
public boolean isInSameParty(@NonNull ChatUser user1, @NonNull ChatUser user2) { public boolean isInSameParty(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
if (!user1.isOnline() || !user2.isOnline()) { if (!user1.online() || !user2.online()) {
return false; return false;
} }
return PartyAPI.inSameParty(user1.asPlayer(), user2.asPlayer()); return PartyAPI.inSameParty(user1.player(), user2.player());
} }
} }
@@ -38,36 +38,36 @@ public class CarbonChatChannel extends ChatChannel {
@Nullable @Nullable
private final ConfigurationSection config; private final ConfigurationSection config;
public CarbonChatChannel(@NonNull String key, @NonNull CarbonChat carbonChat, @Nullable ConfigurationSection config) { public CarbonChatChannel(@NonNull final String key, @NonNull final CarbonChat carbonChat, @Nullable final ConfigurationSection config) {
this.key = key; this.key = key;
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.config = config; this.config = config;
} }
@NonNull @NonNull
public CarbonChat getCarbonChat() { public CarbonChat carbonChat() {
return carbonChat; return this.carbonChat;
} }
@Override @Override
public boolean testContext(@NonNull ChatUser sender, @NonNull ChatUser target) { public boolean testContext(@NonNull final ChatUser sender, @NonNull final ChatUser target) {
return carbonChat.getContextManager().testContext(sender, target, this); return this.carbonChat.contextManager().testContext(sender, target, this);
} }
@Override @Override
public boolean canPlayerUse(@NonNull ChatUser user) { public boolean canPlayerUse(@NonNull final ChatUser user) {
return user.asPlayer().hasPermission("carbonchat.channels." + getName() + ".use"); return user.player().hasPermission("carbonchat.channels." + this.name() + ".use");
} }
@Override @Override
@NonNull @NonNull
public List<@NonNull ChatUser> audiences() { public List<@NonNull ChatUser> audiences() {
List<ChatUser> audience = new ArrayList<>(); final List<ChatUser> audience = new ArrayList<>();
for (Player player : Bukkit.getOnlinePlayers()) { for (final Player player : Bukkit.getOnlinePlayers()) {
ChatUser playerUser = carbonChat.getUserService().wrap(player); final ChatUser playerUser = this.carbonChat.userService().wrap(player);
if (canPlayerSee(playerUser, true)) { if (this.canPlayerSee(playerUser, true)) {
audience.add(playerUser); audience.add(playerUser);
} }
} }
@@ -75,18 +75,18 @@ public class CarbonChatChannel extends ChatChannel {
return audience; return audience;
} }
private void updateUserNickname(@NonNull ChatUser user) { private void updateUserNickname(@NonNull final ChatUser user) {
if (user.isOnline()) { if (user.online()) {
String nickname = user.getNickname(); String nickname = user.nickname();
if (nickname != null) { if (nickname != null) {
Component component = carbonChat.getAdventureManager().processMessage(nickname); final Component component = this.carbonChat.adventureManager().processMessage(nickname);
nickname = CarbonChat.LEGACY.serialize(component); nickname = CarbonChat.LEGACY.serialize(component);
user.asPlayer().setDisplayName(nickname); user.player().setDisplayName(nickname);
if (carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) { if (this.carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
user.asPlayer().setPlayerListName(nickname); user.player().setPlayerListName(nickname);
} }
} }
} }
@@ -94,111 +94,111 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@NonNull @NonNull
public Component sendMessage(@NonNull ChatUser user, @NonNull Collection<@NonNull ChatUser> recipients, @NonNull String message, boolean fromRemote) { public Component sendMessage(@NonNull final ChatUser user, @NonNull final Collection<@NonNull ChatUser> recipients, @NonNull final String message, final boolean fromRemote) {
updateUserNickname(user); this.updateUserNickname(user);
// Get player's formatting // Get player's formatting
String messageFormat = getFormat(user); final String messageFormat = this.format(user);
// Call custom chat event // Call custom chat event
PreChatFormatEvent preFormatEvent = new PreChatFormatEvent(user, this, messageFormat, message); final PreChatFormatEvent preFormatEvent = new PreChatFormatEvent(user, this, messageFormat, message);
Bukkit.getPluginManager().callEvent(preFormatEvent); Bukkit.getPluginManager().callEvent(preFormatEvent);
// Return if cancelled or message is emptied // Return if cancelled or message is emptied
if (preFormatEvent.isCancelled() || preFormatEvent.getMessage().trim().isEmpty()) { if (preFormatEvent.isCancelled() || preFormatEvent.message().trim().isEmpty()) {
return TextComponent.empty(); return TextComponent.empty();
} }
String displayName; final String displayName;
if (user.getNickname() != null) { if (user.nickname() != null) {
displayName = user.getNickname(); displayName = user.nickname();
} else { } else {
if (user.isOnline()) { if (user.online()) {
displayName = user.asPlayer().getDisplayName(); displayName = user.player().getDisplayName();
} else { } else {
displayName = user.asOfflinePlayer().getName(); displayName = user.offlinePlayer().getName();
} }
} }
// Iterate through players who should receive messages in this channel // Iterate through players who should receive messages in this channel
for (ChatUser target : recipients) { for (final ChatUser target : recipients) {
// Call second format event. Used for relational stuff (placeholders etc) // Call second format event. Used for relational stuff (placeholders etc)
ChatFormatEvent formatEvent = new ChatFormatEvent(user, target, this, preFormatEvent.getFormat(), preFormatEvent.getMessage()); final ChatFormatEvent formatEvent = new ChatFormatEvent(user, target, this, preFormatEvent.format(), preFormatEvent.message());
Bukkit.getPluginManager().callEvent(formatEvent); Bukkit.getPluginManager().callEvent(formatEvent);
// Again, return if cancelled or message is emptied // Again, return if cancelled or message is emptied
if (formatEvent.isCancelled() || formatEvent.getMessage().trim().isEmpty()) { if (formatEvent.isCancelled() || formatEvent.message().trim().isEmpty()) {
continue; continue;
} }
TextColor targetColor = getChannelColor(target); final TextColor targetColor = this.channelColor(target);
TextComponent formatComponent = (TextComponent) carbonChat.getAdventureManager().processMessage(formatEvent.getFormat(), TextComponent formatComponent = (TextComponent) this.carbonChat.adventureManager().processMessage(formatEvent.format(),
"br", "\n", "br", "\n",
"displayname", displayName, "displayname", displayName,
"color", "<" + targetColor.asHexString() + ">", "color", "<" + targetColor.asHexString() + ">",
"phase", Long.toString(System.currentTimeMillis() % 25), "phase", Long.toString(System.currentTimeMillis() % 25),
"server", carbonChat.getConfig().getString("server-name", "Server"), "server", this.carbonChat.getConfig().getString("server-name", "Server"),
"message", formatEvent.getMessage()); "message", formatEvent.message());
if (isUserSpying(user, target)) { if (this.isUserSpying(user, target)) {
String prefix = processPlaceholders(user, carbonChat.getConfig().getString("spy-prefix")); final String prefix = this.processPlaceholders(user, this.carbonChat.getConfig().getString("spy-prefix"));
formatComponent = (TextComponent) MiniMessage.get().parse(prefix, "color", formatComponent = (TextComponent) MiniMessage.get().parse(prefix, "color",
targetColor.asHexString()).append(formatComponent); targetColor.asHexString()).append(formatComponent);
} }
ChatComponentEvent newEvent = new ChatComponentEvent(user, target, this, formatComponent, final ChatComponentEvent newEvent = new ChatComponentEvent(user, target, this, formatComponent,
formatEvent.getMessage()); formatEvent.message());
Bukkit.getPluginManager().callEvent(newEvent); Bukkit.getPluginManager().callEvent(newEvent);
target.sendMessage(newEvent.getComponent()); target.sendMessage(newEvent.component());
} }
ChatFormatEvent consoleFormatEvent = new ChatFormatEvent(user, null, this, preFormatEvent.getFormat(), final ChatFormatEvent consoleFormatEvent = new ChatFormatEvent(user, null, this, preFormatEvent.format(),
preFormatEvent.getMessage()); preFormatEvent.message());
Bukkit.getPluginManager().callEvent(consoleFormatEvent); Bukkit.getPluginManager().callEvent(consoleFormatEvent);
TextColor targetColor = getChannelColor(user); final TextColor targetColor = this.channelColor(user);
TextComponent consoleFormat = (TextComponent) carbonChat.getAdventureManager().processMessage(consoleFormatEvent.getFormat(), final TextComponent consoleFormat = (TextComponent) this.carbonChat.adventureManager().processMessage(consoleFormatEvent.format(),
"br", "\n", "br", "\n",
"displayname", displayName, "displayname", displayName,
"color", "<" + targetColor.asHexString() + ">", "color", "<" + targetColor.asHexString() + ">",
"phase", Long.toString(System.currentTimeMillis() % 25), "phase", Long.toString(System.currentTimeMillis() % 25),
"server", carbonChat.getConfig().getString("server-name", "Server"), "server", this.carbonChat.getConfig().getString("server-name", "Server"),
"message", consoleFormatEvent.getMessage()); "message", consoleFormatEvent.message());
ChatComponentEvent consoleEvent = new ChatComponentEvent(user, null, this, consoleFormat, final ChatComponentEvent consoleEvent = new ChatComponentEvent(user, null, this, consoleFormat,
consoleFormatEvent.getMessage()); consoleFormatEvent.message());
Bukkit.getPluginManager().callEvent(consoleEvent); Bukkit.getPluginManager().callEvent(consoleEvent);
// Route message to bungee / discord (if message originates from this server) // Route message to bungee / discord (if message originates from this server)
// Use instanceof and not isOnline, if this message originates from another then the instanceof will // Use instanceof and not isOnline, if this message originates from another then the instanceof will
// fail, but isOnline may succeed if the player is online on both servers (somehow). // fail, but isOnline may succeed if the player is online on both servers (somehow).
if (user.isOnline() && !fromRemote && (shouldBungee() || isCrossServer())) { if (user.online() && !fromRemote && (this.bungee() || this.crossServer())) {
sendMessageToBungee(user.asPlayer(), consoleEvent.getComponent()); this.sendMessageToBungee(user.player(), consoleEvent.component());
} }
return consoleEvent.getComponent(); return consoleEvent.component();
} }
@Override @Override
@NonNull @NonNull
public Component sendMessage(@NonNull ChatUser user, @NonNull String message, boolean fromRemote) { public Component sendMessage(@NonNull final ChatUser user, @NonNull final String message, final boolean fromRemote) {
return this.sendMessage(user, this.audiences(), message, fromRemote); return this.sendMessage(user, this.audiences(), message, fromRemote);
} }
@Nullable @Nullable
public String getFormat(@NonNull ChatUser user) { public String format(@NonNull final ChatUser user) {
for (String group : this.getGroupOverrides()) { for (final String group : this.groupOverrides()) {
if (userHasGroup(user, group)) { if (this.userHasGroup(user, group)) {
String format = getFormat(group); final String format = this.format(group);
if (format != null) { if (format != null) {
return format; return format;
@@ -206,136 +206,136 @@ public class CarbonChatChannel extends ChatChannel {
} }
} }
if (primaryGroupOnly()) { if (this.primaryGroupOnly()) {
return getPrimaryGroupFormat(user); return this.primaryGroupFormat(user);
} else { } else {
return getFirstFoundUserFormat(user); return this.firstFoundUserFormat(user);
} }
} }
private boolean userHasGroup(@NonNull ChatUser user, @NonNull String group) { private boolean userHasGroup(@NonNull final ChatUser user, @NonNull final String group) {
if (user.isOnline()) { if (user.online()) {
if (carbonChat.getPermission().playerInGroup(user.asPlayer(), group)) { if (this.carbonChat.permission().playerInGroup(user.player(), group)) {
return true; return true;
} }
} else { } else {
if (carbonChat.getPermission().playerInGroup(null, user.asOfflinePlayer(), group)) { if (this.carbonChat.permission().playerInGroup(null, user.offlinePlayer(), group)) {
return true; return true;
} }
} }
if (user.isOnline() && this.permissionGroupMatching()) { if (user.online() && this.permissionGroupMatching()) {
return user.asPlayer().hasPermission("carbonchat.group." + group); return user.player().hasPermission("carbonchat.group." + group);
} }
return false; return false;
} }
@Nullable @Nullable
private String getFirstFoundUserFormat(@NonNull ChatUser user) { private String firstFoundUserFormat(@NonNull final ChatUser user) {
String[] playerGroups; final String[] playerGroups;
if (user.isOnline()) { if (user.online()) {
playerGroups = carbonChat.getPermission().getPlayerGroups(user.asPlayer()); playerGroups = this.carbonChat.permission().getPlayerGroups(user.player());
} else { } else {
playerGroups = carbonChat.getPermission().getPlayerGroups(null, user.asOfflinePlayer()); playerGroups = this.carbonChat.permission().getPlayerGroups(null, user.offlinePlayer());
} }
for (String group : playerGroups) { for (final String group : playerGroups) {
String groupFormat = getFormat(group); final String groupFormat = this.format(group);
if (groupFormat != null) { if (groupFormat != null) {
return groupFormat; return groupFormat;
} }
} }
return getDefaultFormat(); return this.defaultFormat();
} }
@Nullable @Nullable
private String getPrimaryGroupFormat(@NonNull ChatUser user) { private String primaryGroupFormat(@NonNull final ChatUser user) {
String primaryGroup; final String primaryGroup;
if (user.isOnline()) { if (user.online()) {
primaryGroup = carbonChat.getPermission().getPrimaryGroup(user.asPlayer()); primaryGroup = this.carbonChat.permission().getPrimaryGroup(user.player());
} else { } else {
primaryGroup = carbonChat.getPermission().getPrimaryGroup(null, user.asOfflinePlayer()); primaryGroup = this.carbonChat.permission().getPrimaryGroup(null, user.offlinePlayer());
} }
String primaryGroupFormat = getFormat(primaryGroup); final String primaryGroupFormat = this.format(primaryGroup);
if (primaryGroupFormat != null) { if (primaryGroupFormat != null) {
return primaryGroupFormat; return primaryGroupFormat;
} }
return getDefaultFormat(); return this.defaultFormat();
} }
@Nullable @Nullable
private String getDefaultFormat() { private String defaultFormat() {
return getFormat(getDefaultFormatName()); return this.format(this.defaultFormatName());
} }
@Override @Override
@Nullable @Nullable
public String getFormat(@NonNull String group) { public String format(@NonNull final String group) {
return getString("formats." + group); return this.getString("formats." + group);
} }
private boolean isUserSpying(@NonNull ChatUser sender, @NonNull ChatUser target) { private boolean isUserSpying(@NonNull final ChatUser sender, @NonNull final ChatUser target) {
if (!canPlayerSee(sender, target, false)) { if (!this.canPlayerSee(sender, target, false)) {
return target.getChannelSettings(this).isSpying(); return target.channelSettings(this).spying();
} }
return false; return false;
} }
@Override @Override
public void sendComponent(@NonNull ChatUser player, @NonNull Component component) { public void sendComponent(@NonNull final ChatUser player, @NonNull final Component component) {
for (ChatUser user : audiences()) { for (final ChatUser user : this.audiences()) {
if (!user.isIgnoringUser(player)) { if (!user.ignoringUser(player)) {
user.sendMessage(component); user.sendMessage(component);
} }
} }
} }
public void sendMessageToBungee(@NonNull Player player, @NonNull Component component) { public void sendMessageToBungee(@NonNull final Player player, @NonNull final Component component) {
carbonChat.getMessageManager().sendMessage("channel-component", player.getUniqueId(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("channel-component", player.getUniqueId(), byteArray -> {
byteArray.writeUTF(this.getKey()); byteArray.writeUTF(this.key());
byteArray.writeUTF(carbonChat.getAdventureManager().getAudiences().gsonSerializer().serialize(component)); byteArray.writeUTF(this.carbonChat.adventureManager().audiences().gsonSerializer().serialize(component));
}); });
} }
@Override @Override
public boolean canPlayerSee(@NonNull ChatUser target, boolean checkSpying) { public boolean canPlayerSee(@NonNull final ChatUser target, final boolean checkSpying) {
Player targetPlayer = target.asPlayer(); final Player targetPlayer = target.player();
if (checkSpying && targetPlayer.hasPermission("carbonchat.spy." + getName())) { if (checkSpying && targetPlayer.hasPermission("carbonchat.spy." + this.name())) {
if (target.getChannelSettings(this).isSpying()) { if (target.channelSettings(this).spying()) {
return true; return true;
} }
} }
if (!targetPlayer.hasPermission("carbonchat.channels." + getName() + ".see")) { if (!targetPlayer.hasPermission("carbonchat.channels." + this.name() + ".see")) {
return false; return false;
} }
if (isIgnorable()) { if (this.ignorable()) {
return !target.getChannelSettings(this).isIgnored(); return !target.channelSettings(this).ignored();
} }
return true; return true;
} }
public boolean canPlayerSee(@NonNull ChatUser sender, @NonNull ChatUser target, boolean checkSpying) { public boolean canPlayerSee(@NonNull final ChatUser sender, @NonNull final ChatUser target, final boolean checkSpying) {
Player targetPlayer = target.asPlayer(); final Player targetPlayer = target.player();
if (!canPlayerSee(target, checkSpying)) { if (!this.canPlayerSee(target, checkSpying)) {
return false; return false;
} }
if (isIgnorable()) { if (this.ignorable()) {
return !target.isIgnoringUser(sender) || targetPlayer.hasPermission("carbonchat.ignore.exempt"); return !target.ignoringUser(sender) || targetPlayer.hasPermission("carbonchat.ignore.exempt");
} }
return true; return true;
@@ -343,21 +343,21 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@Nullable @Nullable
public TextColor getChannelColor(@NonNull ChatUser user) { public TextColor channelColor(@NonNull final ChatUser user) {
TextColor userColor = user.getChannelSettings(this).getColor(); final TextColor userColor = user.channelSettings(this).color();
if (userColor != null) { if (userColor != null) {
System.out.println("user color found!"); System.out.println("user color found!");
return userColor; return userColor;
} }
String input = getString("color"); final String input = this.getString("color");
TextColor color = CarbonUtils.parseColor(user, input); final TextColor color = CarbonUtils.parseColor(user, input);
if (color == null && carbonChat.getConfig().getBoolean("show-tips")) { if (color == null && this.carbonChat.getConfig().getBoolean("show-tips")) {
carbonChat.getLogger().warning("Tip: Channel color found (" + color + ") is invalid!"); this.carbonChat.getLogger().warning("Tip: Channel color found (" + color + ") is invalid!");
carbonChat.getLogger().warning("Falling back to #FFFFFF"); this.carbonChat.getLogger().warning("Falling back to #FFFFFF");
return NamedTextColor.WHITE; return NamedTextColor.WHITE;
} }
@@ -366,63 +366,63 @@ public class CarbonChatChannel extends ChatChannel {
} }
@Nullable @Nullable
private String getDefaultFormatName() { private String defaultFormatName() {
return getString("default-group"); return this.getString("default-group");
} }
@Override @Override
public boolean isDefault() { public boolean isDefault() {
if (config != null && config.contains("default")) { if (this.config != null && this.config.contains("default")) {
return config.getBoolean("default"); return this.config.getBoolean("default");
} }
return false; return false;
} }
@Override @Override
public boolean isIgnorable() { public boolean ignorable() {
return getBoolean("ignorable"); return this.getBoolean("ignorable");
} }
@Override @Override
@Deprecated @Deprecated
public boolean shouldBungee() { public boolean bungee() {
return getBoolean("should-bungee"); return this.getBoolean("should-bungee");
} }
@Override @Override
public boolean isCrossServer() { public boolean crossServer() {
return getBoolean("is-cross-server"); return this.getBoolean("is-cross-server");
} }
@Override @Override
public boolean honorsRecipientList() { public boolean honorsRecipientList() {
return getBoolean("honors-recipient-list"); return this.getBoolean("honors-recipient-list");
} }
@Override @Override
public boolean permissionGroupMatching() { public boolean permissionGroupMatching() {
return getBoolean("permission-group-matching"); return this.getBoolean("permission-group-matching");
} }
@Override @Override
@NonNull @NonNull
public List<@NonNull String> getGroupOverrides() { public List<@NonNull String> groupOverrides() {
return getStringList("group-overrides"); return this.getStringList("group-overrides");
} }
@Override @Override
@NonNull @NonNull
public String getName() { public String name() {
String name = getString("name"); final String name = this.getString("name");
return name == null ? key : name; return name == null ? this.key : name;
} }
@Override @Override
@Nullable @Nullable
public String getMessagePrefix() { public String messagePrefix() {
if (config != null && config.contains("message-prefix")) { if (this.config != null && this.config.contains("message-prefix")) {
return config.getString("message-prefix"); return this.config.getString("message-prefix");
} }
return null; return null;
@@ -430,74 +430,74 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@Nullable @Nullable
public String getSwitchMessage() { public String switchMessage() {
return getString("switch-message"); return this.getString("switch-message");
} }
@Override @Override
@Nullable @Nullable
public String getSwitchOtherMessage() { public String switchOtherMessage() {
return getString("switch-other-message"); return this.getString("switch-other-message");
} }
@Override @Override
@Nullable @Nullable
public String getSwitchFailureMessage() { public String switchFailureMessage() {
return getString("switch-failure-message"); return this.getString("switch-failure-message");
} }
@Override @Override
@Nullable @Nullable
public String getCannotIgnoreMessage() { public String cannotIgnoreMessage() {
return getString("cannot-ignore-message"); return this.getString("cannot-ignore-message");
} }
@Override @Override
@Nullable @Nullable
public String getToggleOffMessage() { public String toggleOffMessage() {
return getString("toggle-off-message"); return this.getString("toggle-off-message");
} }
@Override @Override
@Nullable @Nullable
public String getToggleOnMessage() { public String toggleOnMessage() {
return getString("toggle-on-message"); return this.getString("toggle-on-message");
} }
@Override @Override
@Nullable @Nullable
public String getToggleOtherOnMessage() { public String toggleOtherOnMessage() {
return getString("toggle-other-on"); return this.getString("toggle-other-on");
} }
@Override @Override
@Nullable @Nullable
public String getToggleOtherOffMessage() { public String toggleOtherOffMessage() {
return getString("toggle-other-off"); return this.getString("toggle-other-off");
} }
@Override @Override
@Nullable @Nullable
public String getCannotUseMessage() { public String cannotUseMessage() {
return getString("cannot-use-channel"); return this.getString("cannot-use-channel");
}
@Override
public boolean shouldForwardFormatting() {
return getBoolean("forward-format");
} }
@Override @Override
public boolean primaryGroupOnly() { public boolean primaryGroupOnly() {
return getBoolean("primary-group-only"); return this.getBoolean("primary-group-only");
}
@Override
public boolean shouldCancelChatEvent() {
return this.getBoolean("cancel-message-event");
} }
@Override @Override
@NonNull @NonNull
public List<@NonNull Pattern> getItemLinkPatterns() { public List<@NonNull Pattern> itemLinkPatterns() {
ArrayList<Pattern> itemPatterns = new ArrayList<>(); final ArrayList<Pattern> itemPatterns = new ArrayList<>();
for (String entry : carbonChat.getConfig().getStringList("item-link-placeholders")) { for (final String entry : this.carbonChat.getConfig().getStringList("item-link-placeholders")) {
itemPatterns.add(Pattern.compile(Pattern.quote(entry))); itemPatterns.add(Pattern.compile(Pattern.quote(entry)));
} }
@@ -506,17 +506,17 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@Nullable @Nullable
public Object getContext(@NonNull String key) { public Object context(@NonNull final String key) {
ConfigurationSection section = config == null ? null : config.getConfigurationSection("contexts"); final ConfigurationSection section = this.config == null ? null : this.config.getConfigurationSection("contexts");
if (section == null) { if (section == null) {
ConfigurationSection defaultSection = carbonChat.getConfig().getConfigurationSection("default"); final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
if (defaultSection == null) { if (defaultSection == null) {
return null; return null;
} }
ConfigurationSection defaultContexts = defaultSection.getConfigurationSection("contexts"); final ConfigurationSection defaultContexts = defaultSection.getConfigurationSection("contexts");
if (defaultContexts == null) { if (defaultContexts == null) {
return null; return null;
@@ -529,12 +529,13 @@ public class CarbonChatChannel extends ChatChannel {
} }
@Nullable @Nullable
private String getString(@NonNull String key) { @SuppressWarnings("checkstyle:MethodName")
if (config != null && config.contains(key)) { private String getString(@NonNull final String key) {
return config.getString(key); if (this.config != null && this.config.contains(key)) {
return this.config.getString(key);
} }
ConfigurationSection defaultSection = carbonChat.getConfig().getConfigurationSection("default"); final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
if (defaultSection != null && defaultSection.contains(key)) { if (defaultSection != null && defaultSection.contains(key)) {
return defaultSection.getString(key); return defaultSection.getString(key);
@@ -544,12 +545,13 @@ public class CarbonChatChannel extends ChatChannel {
} }
@NonNull @NonNull
private List<@NonNull String> getStringList(@NonNull String key) { @SuppressWarnings("checkstyle:MethodName")
if (config != null && config.contains(key)) { private List<@NonNull String> getStringList(@NonNull final String key) {
return config.getStringList(key); if (this.config != null && this.config.contains(key)) {
return this.config.getStringList(key);
} }
ConfigurationSection defaultSection = carbonChat.getConfig().getConfigurationSection("default"); final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
if (defaultSection != null && defaultSection.contains(key)) { if (defaultSection != null && defaultSection.contains(key)) {
return defaultSection.getStringList(key); return defaultSection.getStringList(key);
@@ -558,12 +560,13 @@ public class CarbonChatChannel extends ChatChannel {
return Collections.emptyList(); return Collections.emptyList();
} }
private boolean getBoolean(@NonNull String key) { @SuppressWarnings("checkstyle:MethodName")
if (config != null && config.contains(key)) { private boolean getBoolean(@NonNull final String key) {
return config.getBoolean(key); if (this.config != null && this.config.contains(key)) {
return this.config.getBoolean(key);
} }
ConfigurationSection defaultSection = carbonChat.getConfig().getConfigurationSection("default"); final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
if (defaultSection != null && defaultSection.contains(key)) { if (defaultSection != null && defaultSection.contains(key)) {
return defaultSection.getBoolean(key); return defaultSection.getBoolean(key);
@@ -572,12 +575,13 @@ public class CarbonChatChannel extends ChatChannel {
return false; return false;
} }
private double getDouble(@NonNull String key) { @SuppressWarnings("checkstyle:MethodName")
if (config != null && config.contains(key)) { private double getDouble(@NonNull final String key) {
return config.getDouble(key); if (this.config != null && this.config.contains(key)) {
return this.config.getDouble(key);
} }
ConfigurationSection defaultSection = carbonChat.getConfig().getConfigurationSection("default"); final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
if (defaultSection != null && defaultSection.contains(key)) { if (defaultSection != null && defaultSection.contains(key)) {
return defaultSection.getDouble(key); return defaultSection.getDouble(key);
@@ -588,24 +592,19 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@NonNull @NonNull
public String getKey() { public String key() {
return key; return this.key;
} }
@Override @Override
@Nullable @Nullable
public String getAliases() { public String aliases() {
String aliases = getString("aliases"); final String aliases = this.getString("aliases");
if (aliases == null) { if (aliases == null) {
return getKey(); return this.key();
} }
return aliases; return aliases;
} }
@Override
public boolean shouldCancelChatEvent() {
return getBoolean("cancel-message-event");
}
} }
@@ -24,66 +24,66 @@ public class AliasedChannelCommand {
@NonNull @NonNull
private final String commandName; private final String commandName;
public AliasedChannelCommand(@NonNull CarbonChat carbonChat, @NonNull ChatChannel chatChannel) { public AliasedChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final ChatChannel chatChannel) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.chatChannel = chatChannel; this.chatChannel = chatChannel;
this.commandName = chatChannel.getKey(); this.commandName = chatChannel.key();
LinkedHashMap<String, Argument> setChannelArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> setChannelArguments = new LinkedHashMap<>();
new CommandAPICommand(commandName) new CommandAPICommand(this.commandName)
.withArguments(setChannelArguments) .withArguments(setChannelArguments)
.withPermission(CommandPermission.fromString("carbonchat.channel")) .withPermission(CommandPermission.fromString("carbonchat.channel"))
.executesPlayer(this::setChannel) .executesPlayer(this::channel)
.register(); .register();
LinkedHashMap<String, Argument> sendMessageArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> sendMessageArguments = new LinkedHashMap<>();
sendMessageArguments.put("message", new GreedyStringArgument()); sendMessageArguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandName) new CommandAPICommand(this.commandName)
.withArguments(sendMessageArguments) .withArguments(sendMessageArguments)
.withPermission(CommandPermission.fromString("carbonchat.channel.message")) .withPermission(CommandPermission.fromString("carbonchat.channel.message"))
.executesPlayer(this::sendMessage) .executesPlayer(this::sendMessage)
.register(); .register();
} }
private void setChannel(@NonNull Player player, @NonNull Object @NonNull [] args) { private void channel(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (user.getChannelSettings(getChatChannel()).isIgnored()) { if (user.channelSettings(this.chatChannel()).ignored()) {
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, getChatChannel().getCannotUseMessage(), user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, this.chatChannel().cannotUseMessage(),
"br", "\n", "br", "\n",
"color", "<" + getChatChannel().getChannelColor(user).toString() + ">", "color", "<" + this.chatChannel().channelColor(user).toString() + ">",
"channel", getChatChannel().getName())); "channel", this.chatChannel().name()));
return; return;
} }
user.setSelectedChannel(getChatChannel()); user.selectedChannel(this.chatChannel());
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, getChatChannel().getSwitchMessage(), user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, this.chatChannel().switchMessage(),
"br", "\n", "br", "\n",
"color", "<" + getChatChannel().getChannelColor(user).toString() + ">", "color", "<" + this.chatChannel().channelColor(user).toString() + ">",
"channel", getChatChannel().getName())); "channel", this.chatChannel().name()));
} }
private void sendMessage(@NonNull Player player, @NonNull Object @NonNull [] args) { private void sendMessage(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
String message = (String) args[0]; final String message = (String) args[0];
Component component = getChatChannel().sendMessage(user, message, false); final Component component = this.chatChannel().sendMessage(user, message, false);
carbonChat.getAdventureManager().getAudiences().console().sendMessage(component); this.carbonChat.adventureManager().audiences().console().sendMessage(component);
} }
@NonNull @NonNull
public ChatChannel getChatChannel() { public ChatChannel chatChannel() {
return chatChannel; return this.chatChannel;
} }
@NonNull @NonNull
public String getCommandName() { public String commandName() {
return commandName; return this.commandName;
} }
} }
@@ -21,66 +21,66 @@ public class ChannelCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public ChannelCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public ChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> setChannelArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> setChannelArguments = new LinkedHashMap<>();
setChannelArguments.put("channel", CarbonUtils.channelArgument()); setChannelArguments.put("channel", CarbonUtils.channelArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(setChannelArguments) .withArguments(setChannelArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channel")) .withPermission(CommandPermission.fromString("carbonchat.channel"))
.executesPlayer(this::setChannel) .executesPlayer(this::channel)
.register(); .register();
LinkedHashMap<String, Argument> sendMessageArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> sendMessageArguments = new LinkedHashMap<>();
sendMessageArguments.put("channel", CarbonUtils.channelArgument()); sendMessageArguments.put("channel", CarbonUtils.channelArgument());
sendMessageArguments.put("message", new GreedyStringArgument()); sendMessageArguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(sendMessageArguments) .withArguments(sendMessageArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channel.message")) .withPermission(CommandPermission.fromString("carbonchat.channel.message"))
.executesPlayer(this::sendMessage) .executesPlayer(this::sendMessage)
.register(); .register();
} }
private void setChannel(@NonNull Player player, @NonNull Object @NonNull [] args) { private void channel(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
ChatChannel channel = (ChatChannel) args[0]; final ChatChannel channel = (ChatChannel) args[0];
if (user.getChannelSettings(channel).isIgnored()) { if (user.channelSettings(channel).ignored()) {
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, channel.getCannotUseMessage(), user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, channel.cannotUseMessage(),
"br", "\n", "br", "\n",
"color", "<" + channel.getChannelColor(user).toString() + ">", "color", "<" + channel.channelColor(user).toString() + ">",
"channel", channel.getName())); "channel", channel.name()));
return; return;
} }
user.setSelectedChannel(channel); user.selectedChannel(channel);
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, channel.getSwitchMessage(), user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, channel.switchMessage(),
"br", "\n", "br", "\n",
"color", "<" + channel.getChannelColor(user).toString() + ">", "color", "<" + channel.channelColor(user).toString() + ">",
"channel", channel.getName())); "channel", channel.name()));
} }
private void sendMessage(@NonNull Player player, @NonNull Object @NonNull [] args) { private void sendMessage(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
ChatChannel channel = (ChatChannel) args[0]; final ChatChannel channel = (ChatChannel) args[0];
String message = (String) args[1]; final String message = (String) args[1];
Component component = channel.sendMessage(user, message, false); final Component component = channel.sendMessage(user, message, false);
carbonChat.getAdventureManager().getAudiences().console().sendMessage(component); this.carbonChat.adventureManager().audiences().console().sendMessage(component);
} }
} }
@@ -27,60 +27,61 @@ public class ChannelListCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public ChannelListCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public ChannelListCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(channelArguments) .withArguments(channelArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channellist")) .withPermission(CommandPermission.fromString("carbonchat.channellist"))
.executesPlayer(this::executeSelf) .executesPlayer(this::executeSelf)
.register(); .register();
LinkedHashMap<String, Argument> argumentsOther = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> argumentsOther = new LinkedHashMap<>();
argumentsOther.put("player", CarbonUtils.onlineChatUserArgument()); argumentsOther.put("player", CarbonUtils.onlineChatUserArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(argumentsOther) .withArguments(argumentsOther)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channellist.other")) .withPermission(CommandPermission.fromString("carbonchat.channellist.other"))
.executes(this::executeOther) .executes(this::executeOther)
.register(); .register();
} }
public void executeSelf(@NonNull Player player, @NonNull Object @NonNull [] args) { public void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
Iterator<ChatChannel> allChannels = carbonChat.getChannelManager().getRegistry().values().iterator(); final Iterator<ChatChannel> allChannels = this.carbonChat.channelManager().registry().values().iterator();
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
getListAndSend(player, user, allChannels); this.listAndSend(player, user, allChannels);
} }
public void executeOther(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) { public void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
Audience cmdSender = carbonChat.getAdventureManager().getAudiences().audience(sender); final Audience cmdSender = this.carbonChat.adventureManager().audiences().audience(sender);
ChatUser user = (ChatUser) args[0]; final ChatUser user = (ChatUser) args[0];
if (!user.isOnline()) { if (!user.online()) {
String mustBeOnline = carbonChat.getLanguage().getString("user-must-be-online"); final String mustBeOnline = this.carbonChat.language().getString("user-must-be-online");
cmdSender.sendMessage(carbonChat.getAdventureManager().processMessage(mustBeOnline, "br", "\n", "player", user.asOfflinePlayer().getName())); cmdSender.sendMessage(this.carbonChat.adventureManager().processMessage(mustBeOnline, "br", "\n", "player", user.offlinePlayer().getName()));
return; return;
} }
Iterator<ChatChannel> allChannels = carbonChat.getChannelManager().getRegistry().values().iterator(); final Iterator<ChatChannel> allChannels = this.carbonChat.channelManager().registry().values().iterator();
getListAndSend(sender, user, allChannels); this.listAndSend(sender, user, allChannels);
} }
private void getListAndSend(@NonNull CommandSender sender, @NonNull ChatUser user, @NonNull Iterator<ChatChannel> allChannels) { private void listAndSend(@NonNull final CommandSender sender, @NonNull final ChatUser user,
@NonNull final Iterator<ChatChannel> allChannels) {
ChatChannel channel; ChatChannel channel;
List<ChatChannel> canSee = new ArrayList<>(); final List<ChatChannel> canSee = new ArrayList<>();
List<ChatChannel> cannotSee = new ArrayList<>(); final List<ChatChannel> cannotSee = new ArrayList<>();
while (allChannels.hasNext()) { while (allChannels.hasNext()) {
channel = allChannels.next(); channel = allChannels.next();
@@ -92,42 +93,41 @@ public class ChannelListCommand {
} }
} }
Iterator<ChatChannel> visibleChannels = canSee.iterator(); final Iterator<ChatChannel> visibleChannels = canSee.iterator();
TextComponent.Builder availableList = TextComponent.builder(""); final TextComponent.Builder availableList = TextComponent.builder("");
makeList(visibleChannels, availableList); this.makeList(visibleChannels, availableList);
String availableFormat = carbonChat.getLanguage().getString("available-channels-list"); final String availableFormat = this.carbonChat.language().getString("available-channels-list");
Component availableComponent = carbonChat.getAdventureManager().processMessage(availableFormat, "br", "\n"); Component availableComponent = this.carbonChat.adventureManager().processMessage(availableFormat, "br", "\n");
availableComponent = availableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), (ac) -> availableList); availableComponent = availableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), ac -> availableList);
Audience audience = carbonChat.getAdventureManager().getAudiences().audience(sender); final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
audience.sendMessage(availableComponent); audience.sendMessage(availableComponent);
if (sender.hasPermission("carbonchat.channellist.bypass") && !cannotSee.isEmpty()) { if (sender.hasPermission("carbonchat.channellist.bypass") && !cannotSee.isEmpty()) {
final Iterator<ChatChannel> invisibleChannels = cannotSee.iterator();
final TextComponent.Builder unavailableList = TextComponent.builder("");
Iterator<ChatChannel> invisibleChannels = cannotSee.iterator(); this.makeList(invisibleChannels, unavailableList);
TextComponent.Builder unavailableList = TextComponent.builder("");
makeList(invisibleChannels, unavailableList); final String unavailableFormat = this.carbonChat.language().getString("unavailable-channels-list");
Component unavailableComponent = this.carbonChat.adventureManager().processMessage(unavailableFormat, "br", "\n");
String unavailableFormat = carbonChat.getLanguage().getString("unavailable-channels-list"); unavailableComponent = unavailableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), uac -> unavailableList);
Component unavailableComponent = carbonChat.getAdventureManager().processMessage(unavailableFormat, "br", "\n");
unavailableComponent = unavailableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), (uac) -> unavailableList);
audience.sendMessage(unavailableComponent); audience.sendMessage(unavailableComponent);
} }
} }
private void makeList(@NonNull Iterator<@NonNull ChatChannel> iterator, TextComponent.@NonNull Builder list) { private void makeList(@NonNull final Iterator<@NonNull ChatChannel> iterator, final TextComponent.@NonNull Builder list) {
String listSeparator = carbonChat.getLanguage().getString("channel-list-separator", ", "); final String listSeparator = this.carbonChat.language().getString("channel-list-separator", ", ");
// TODO: Larry, why did you double assign the listSeparatorComponent? // TODO: Larry, why did you double assign the listSeparatorComponent?
Component listSeparatorComponent = TextComponent.of(listSeparator); final Component listSeparatorComponent = TextComponent.of(listSeparator);
while (iterator.hasNext()) { while (iterator.hasNext()) {
ChatChannel channel = iterator.next(); list.append(TextComponent.of(iterator.next().name()));
list.append(TextComponent.of(channel.getName()));
if (iterator.hasNext()) { if (iterator.hasNext()) {
list.append(listSeparatorComponent); list.append(listSeparatorComponent);
} }
@@ -14,30 +14,30 @@ public class ChatReloadCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public ChatReloadCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public ChatReloadCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.reload")) .withPermission(CommandPermission.fromString("carbonchat.reload"))
.executes(this::execute) .executes(this::execute)
.register(); .register();
} }
private void execute(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) { private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
carbonChat.reloadConfig(); this.carbonChat.reloadConfig();
carbonChat.reloadFilters(); this.carbonChat.reloadFilters();
Component message = carbonChat.getAdventureManager().processMessage(carbonChat.getLanguage().getString("reloaded"), final Component message = this.carbonChat.adventureManager()
"br", "\n"); .processMessage(this.carbonChat.language().getString("reloaded"), "br", "\n");
carbonChat.getAdventureManager().getAudiences().audience(sender).sendMessage(message); this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(message);
} }
} }
@@ -1,6 +1,5 @@
package net.draycia.carbon.commands; package net.draycia.carbon.commands;
import dev.jorel.commandapi.CommandAPICommand; import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.CommandPermission; import dev.jorel.commandapi.CommandPermission;
import net.draycia.carbon.CarbonChat; import net.draycia.carbon.CarbonChat;
@@ -18,41 +17,41 @@ public class ClearChatCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public ClearChatCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public ClearChatCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.clearchat.clear")) .withPermission(CommandPermission.fromString("carbonchat.clearchat.clear"))
.executes(this::execute) .executes(this::execute)
.register(); .register();
} }
private void execute(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) { private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
String format = carbonChat.getModConfig().getString("clear-chat.message", ""); final String format = this.carbonChat.moderationConfig().getString("clear-chat.message", "");
Component component = carbonChat.getAdventureManager().processMessage(format, "br", "\n"); final Component component = this.carbonChat.adventureManager().processMessage(format, "br", "\n");
for (Player player : Bukkit.getOnlinePlayers()) { for (final Player player : Bukkit.getOnlinePlayers()) {
ChatUser audience = carbonChat.getUserService().wrap(player); final ChatUser audience = this.carbonChat.userService().wrap(player);
if (player.hasPermission("carbonchat.clearchat.exempt")) { if (player.hasPermission("carbonchat.clearchat.exempt")) {
String message = carbonChat.getLanguage().getString("clear-exempt"); final String message = this.carbonChat.language().getString("clear-exempt");
audience.sendMessage(carbonChat.getAdventureManager().processMessage(message, "player", sender.getName())); audience.sendMessage(this.carbonChat.adventureManager().processMessage(message, "player", sender.getName()));
} else { } else {
for (int i = 0; i < carbonChat.getModConfig().getInt("clear-chat.message-count", 100); i++) { for (int i = 0; i < this.carbonChat.moderationConfig().getInt("clear-chat.message-count", 100); i++) {
audience.sendMessage(component); audience.sendMessage(component);
} }
} }
if (player.hasPermission("carbonchat.clearchat.notify")) { if (player.hasPermission("carbonchat.clearchat.notify")) {
String message = carbonChat.getLanguage().getString("clear-notify"); final String message = this.carbonChat.language().getString("clear-notify");
audience.sendMessage(carbonChat.getAdventureManager().processMessage(message, "player", sender.getName())); audience.sendMessage(this.carbonChat.adventureManager().processMessage(message, "player", sender.getName()));
} }
} }
} }
@@ -21,50 +21,50 @@ public class IgnoreCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public IgnoreCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public IgnoreCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("player", CarbonUtils.chatUserArgument()); channelArguments.put("player", CarbonUtils.chatUserArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(channelArguments) .withArguments(channelArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.ignore")) .withPermission(CommandPermission.fromString("carbonchat.ignore"))
.executesPlayer(this::execute) .executesPlayer(this::execute)
.register(); .register();
} }
private void execute(@NonNull Player player, @NonNull Object @NonNull [] args) { private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
ChatUser targetUser = (ChatUser) args[0]; final ChatUser targetUser = (ChatUser) args[0];
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (user.isIgnoringUser(targetUser)) { if (user.ignoringUser(targetUser)) {
user.setIgnoringUser(targetUser, false); user.ignoringUser(targetUser, false);
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player,
carbonChat.getLanguage().getString("not-ignoring-user"), this.carbonChat.language().getString("not-ignoring-user"),
"br", "\n", "player", targetUser.asOfflinePlayer().getName())); "br", "\n", "player", targetUser.offlinePlayer().getName()));
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
Permission permission = carbonChat.getPermission(); final Permission permission = this.carbonChat.permission();
String format; final String format;
if (permission.playerHas(null, targetUser.asOfflinePlayer(), "carbonchat.ignore.exempt")) { if (permission.playerHas(null, targetUser.offlinePlayer(), "carbonchat.ignore.exempt")) {
format = carbonChat.getLanguage().getString("ignore-exempt"); format = this.carbonChat.language().getString("ignore-exempt");
} else { } else {
user.setIgnoringUser(targetUser, true); user.ignoringUser(targetUser, true);
format = carbonChat.getLanguage().getString("ignoring-user"); format = this.carbonChat.language().getString("ignoring-user");
} }
Component message = carbonChat.getAdventureManager().processMessageWithPapi(player, format, final Component message = this.carbonChat.adventureManager().processMessageWithPapi(player, format,
"br", "\n", "sender", player.getDisplayName(), "player", "br", "\n", "sender", player.getDisplayName(), "player",
targetUser.asOfflinePlayer().getName()); targetUser.offlinePlayer().getName());
user.sendMessage(message); user.sendMessage(message);
}); });
@@ -21,48 +21,48 @@ public class MeCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public MeCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public MeCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("message", new GreedyStringArgument()); channelArguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(channelArguments) .withArguments(channelArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.me")) .withPermission(CommandPermission.fromString("carbonchat.me"))
.executesPlayer(this::execute) .executesPlayer(this::execute)
.register(); .register();
} }
private void execute(@NonNull Player player, @NonNull Object @NonNull [] args) { private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
String message = ((String) args[0]).replace("</pre>", ""); final String message = ((String) args[0]).replace("</pre>", "");
String format = PlaceholderAPI.setPlaceholders(player, carbonChat.getLanguage().getString("me")); String format = PlaceholderAPI.setPlaceholders(player, this.carbonChat.language().getString("me"));
if (!player.hasPermission("carbonchat.me.formatting")) { if (!player.hasPermission("carbonchat.me.formatting")) {
format = format.replace("<message>", "<pre><message></pre>"); format = format.replace("<message>", "<pre><message></pre>");
} }
Component component = carbonChat.getAdventureManager().processMessage(format, "br", "\n", final Component component = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"displayname", player.getDisplayName(), "message", message); "displayname", player.getDisplayName(), "message", message);
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (user.isShadowMuted()) { if (user.shadowMuted()) {
user.sendMessage(component); user.sendMessage(component);
} else { } else {
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { for (final Player onlinePlayer : Bukkit.getOnlinePlayers()) {
if (carbonChat.getUserService().wrap(onlinePlayer).isIgnoringUser(user)) { if (this.carbonChat.userService().wrap(onlinePlayer).ignoringUser(user)) {
continue; continue;
} }
carbonChat.getAdventureManager().getAudiences().player(onlinePlayer).sendMessage(component); this.carbonChat.adventureManager().audiences().player(onlinePlayer).sendMessage(component);
} }
} }
} }
@@ -19,32 +19,32 @@ public class MessageCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public MessageCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public MessageCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("player", CarbonUtils.chatUserArgument()); arguments.put("player", CarbonUtils.chatUserArgument());
arguments.put("message", new GreedyStringArgument()); arguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(arguments) .withArguments(arguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.message")) .withPermission(CommandPermission.fromString("carbonchat.message"))
.executesPlayer(this::execute) .executesPlayer(this::execute)
.register(); .register();
} }
private void execute(@NonNull Player player, @NonNull Object @NonNull [] args) { private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
ChatUser targetUser = (ChatUser) args[0]; final ChatUser targetUser = (ChatUser) args[0];
String message = (String) args[1]; final String message = (String) args[1];
ChatUser sender = carbonChat.getUserService().wrap(player); final ChatUser sender = this.carbonChat.userService().wrap(player);
targetUser.sendMessage(sender, message); targetUser.sendMessage(sender, message);
} }
@@ -22,52 +22,52 @@ public class MuteCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public MuteCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public MuteCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("player", CarbonUtils.chatUserArgument()); arguments.put("player", CarbonUtils.chatUserArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(arguments) .withArguments(arguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.mute")) .withPermission(CommandPermission.fromString("carbonchat.mute"))
.executes(this::execute) .executes(this::execute)
.register(); .register();
} }
private void execute(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) { private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
ChatUser user = (ChatUser) args[0]; final ChatUser user = (ChatUser) args[0];
Audience audience = carbonChat.getAdventureManager().getAudiences().audience(sender); final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
if (user.isShadowMuted()) { if (user.shadowMuted()) {
user.setMuted(false); user.muted(false);
String format = carbonChat.getLanguage().getString("no-longer-muted"); final String format = this.carbonChat.language().getString("no-longer-muted");
Component message = carbonChat.getAdventureManager().processMessage(format, "br", "\n", final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.asOfflinePlayer().getName()); "player", user.offlinePlayer().getName());
audience.sendMessage(message); audience.sendMessage(message);
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
Permission permission = carbonChat.getPermission(); final Permission permission = this.carbonChat.permission();
String format; final String format;
if (permission.playerHas(null, user.asOfflinePlayer(), "carbonchat.mute.exempt")) { if (permission.playerHas(null, user.offlinePlayer(), "carbonchat.mute.exempt")) {
format = carbonChat.getLanguage().getString("mute-exempt"); format = this.carbonChat.language().getString("mute-exempt");
} else { } else {
user.setMuted(true); user.muted(true);
format = carbonChat.getLanguage().getString("is-now-muted"); format = this.carbonChat.language().getString("is-now-muted");
} }
Component message = carbonChat.getAdventureManager().processMessage(format, "br", "\n", final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.asOfflinePlayer().getName()); "player", user.offlinePlayer().getName());
audience.sendMessage(message); audience.sendMessage(message);
}); });
@@ -21,83 +21,83 @@ public class NicknameCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public NicknameCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public NicknameCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> selfArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> selfArguments = new LinkedHashMap<>();
selfArguments.put("nickname", new StringArgument()); selfArguments.put("nickname", new StringArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(selfArguments) .withArguments(selfArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.nickname")) .withPermission(CommandPermission.fromString("carbonchat.nickname"))
.executesPlayer(this::executeSelf) .executesPlayer(this::executeSelf)
.register(); .register();
LinkedHashMap<String, Argument> otherArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> otherArguments = new LinkedHashMap<>();
otherArguments.put("player", CarbonUtils.chatUserArgument()); otherArguments.put("player", CarbonUtils.chatUserArgument());
otherArguments.put("nickname", new StringArgument()); otherArguments.put("nickname", new StringArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(otherArguments) .withArguments(otherArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.nickname.others")) .withPermission(CommandPermission.fromString("carbonchat.nickname.others"))
.executes(this::executeOther) .executes(this::executeOther)
.register(); .register();
} }
private void executeSelf(@NonNull Player player, @NonNull Object @NonNull [] args) { private void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
String nickname = (String) args[0]; String nickname = (String) args[0];
ChatUser sender = carbonChat.getUserService().wrap(player); final ChatUser sender = this.carbonChat.userService().wrap(player);
if (nickname.equalsIgnoreCase("off") || nickname.equalsIgnoreCase(player.getName())) { if (nickname.equalsIgnoreCase("off") || nickname.equalsIgnoreCase(player.getName())) {
nickname = null; nickname = null;
} }
sender.setNickname(nickname); sender.nickname(nickname);
String message; final String message;
if (nickname == null) { if (nickname == null) {
message = carbonChat.getLanguage().getString("nickname-reset"); message = this.carbonChat.language().getString("nickname-reset");
} else { } else {
message = carbonChat.getLanguage().getString("nickname-set"); message = this.carbonChat.language().getString("nickname-set");
} }
sender.sendMessage(carbonChat.getAdventureManager().processMessage( sender.sendMessage(this.carbonChat.adventureManager().processMessage(
message, "nickname", nickname == null ? "" : nickname, message, "nickname", nickname == null ? "" : nickname,
"user", sender.asOfflinePlayer().getName())); "user", sender.offlinePlayer().getName()));
} }
private void executeOther(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) { private void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
Audience user = carbonChat.getAdventureManager().getAudiences().audience(sender); final Audience user = this.carbonChat.adventureManager().audiences().audience(sender);
ChatUser target = (ChatUser) args[0]; final ChatUser target = (ChatUser) args[0];
String nickname = (String) args[1]; String nickname = (String) args[1];
if (nickname.equalsIgnoreCase("off") || if (nickname.equalsIgnoreCase("off") ||
nickname.equalsIgnoreCase(target.asOfflinePlayer().getName())) { nickname.equalsIgnoreCase(target.offlinePlayer().getName())) {
nickname = null; nickname = null;
} }
target.setNickname(nickname); target.nickname(nickname);
String message; final String message;
if (nickname == null) { if (nickname == null) {
message = carbonChat.getLanguage().getString("other-nickname-reset"); message = this.carbonChat.language().getString("other-nickname-reset");
} else { } else {
message = carbonChat.getLanguage().getString("other-nickname-set"); message = this.carbonChat.language().getString("other-nickname-set");
} }
user.sendMessage(carbonChat.getAdventureManager().processMessage( user.sendMessage(this.carbonChat.adventureManager().processMessage(
message, "nickname", nickname == null ? "" : nickname, message, "nickname", nickname == null ? "" : nickname,
"user", target.asOfflinePlayer().getName())); "user", target.offlinePlayer().getName()));
} }
} }
@@ -19,46 +19,50 @@ public class ReplyCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public ReplyCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public ReplyCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("message", new GreedyStringArgument()); arguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(arguments) .withArguments(arguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.reply")) .withPermission(CommandPermission.fromString("carbonchat.reply"))
.executesPlayer(this::execute) .executesPlayer(this::execute)
.register(); .register();
} }
private void execute(@NonNull Player player, @NonNull Object @NonNull [] args) { private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
String input = (String) args[0]; final String input = (String) args[0];
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (input.isEmpty()) {
final String message = this.carbonChat.language().getString("reply-message-blank");
final Component component = this.carbonChat.adventureManager().processMessage(message, "br", "\n");
if (input == null || input.isEmpty()) {
String message = carbonChat.getLanguage().getString("reply-message-blank");
Component component = carbonChat.getAdventureManager().processMessage(message, "br", "\n");
user.sendMessage(component); user.sendMessage(component);
return; return;
} }
if (user.getReplyTarget() == null) { if (user.replyTarget() == null) {
String message = carbonChat.getLanguage().getString("no-reply-target"); final String message = this.carbonChat.language().getString("no-reply-target");
Component component = carbonChat.getAdventureManager().processMessage(message, "br", "\n"); final Component component = this.carbonChat.adventureManager().processMessage(message, "br", "\n");
user.sendMessage(component); user.sendMessage(component);
return; return;
} }
ChatUser targetUser = carbonChat.getUserService().wrap(user.getReplyTarget()); final ChatUser targetUser = this.carbonChat.userService().wrap(user.replyTarget());
targetUser.sendMessage(user, input); targetUser.sendMessage(user, input);
} }
@@ -2,7 +2,8 @@ package net.draycia.carbon.commands;
import dev.jorel.commandapi.CommandAPICommand; import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.CommandPermission; import dev.jorel.commandapi.CommandPermission;
import dev.jorel.commandapi.arguments.*; import dev.jorel.commandapi.arguments.Argument;
import dev.jorel.commandapi.arguments.LiteralArgument;
import net.draycia.carbon.CarbonChat; import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.channels.ChatChannel; import net.draycia.carbon.channels.ChatChannel;
import net.draycia.carbon.storage.ChatUser; import net.draycia.carbon.storage.ChatUser;
@@ -20,45 +21,45 @@ public class SetColorCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public SetColorCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public SetColorCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
for (ChatChannel channel : carbonChat.getChannelManager().getRegistry().values()) { for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("channel", new LiteralArgument(channel.getKey())); arguments.put("channel", new LiteralArgument(channel.key()));
arguments.put("color", CarbonUtils.textColorArgument()); arguments.put("color", CarbonUtils.textColorArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(arguments) .withArguments(arguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.setcolor")) .withPermission(CommandPermission.fromString("carbonchat.setcolor"))
.executesPlayer((player, args) -> { .executesPlayer((player, args) -> {
TextColor color = (TextColor)args[0]; final TextColor color = (TextColor) args[0];
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (!player.hasPermission("carbonchat.setcolor." + channel.getKey())) { if (!player.hasPermission("carbonchat.setcolor." + channel.key())) {
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, user.sendMessage(carbonChat.adventureManager().processMessageWithPapi(player,
carbonChat.getLanguage().getString("cannot-set-color"), this.carbonChat.language().getString("cannot-set-color"),
"br", "\n", "input", color.asHexString(), "br", "\n", "input", color.asHexString(),
"channel", channel.getName())); "channel", channel.name()));
return; return;
} }
UserChannelSettings settings = user.getChannelSettings(channel); final UserChannelSettings settings = user.channelSettings(channel);
settings.setColor(color); settings.color(color);
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, user.sendMessage(carbonChat.adventureManager().processMessageWithPapi(player,
carbonChat.getLanguage().getString("channel-color-set"), this.carbonChat.language().getString("channel-color-set"),
"br", "\n", "color", "<color:" + color.asHexString() + ">", "channel", "br", "\n", "color", "<color:" + color.asHexString() + ">", "channel",
channel.getName(), "hex", color.asHexString())); channel.name(), "hex", color.asHexString()));
}) })
.register(); .register();
} }
@@ -22,52 +22,52 @@ public class ShadowMuteCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public ShadowMuteCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public ShadowMuteCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("player", CarbonUtils.chatUserArgument()); arguments.put("player", CarbonUtils.chatUserArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(arguments) .withArguments(arguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.shadowmute")) .withPermission(CommandPermission.fromString("carbonchat.shadowmute"))
.executes(this::execute) .executes(this::execute)
.register(); .register();
} }
private void execute(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) { private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
ChatUser user = (ChatUser) args[0]; final ChatUser user = (ChatUser) args[0];
Audience audience = carbonChat.getAdventureManager().getAudiences().audience(sender); final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
if (user.isShadowMuted()) { if (user.shadowMuted()) {
user.setShadowMuted(false); user.shadowMuted(false);
String format = carbonChat.getLanguage().getString("no-longer-shadow-muted"); final String format = this.carbonChat.language().getString("no-longer-shadow-muted");
Component message = carbonChat.getAdventureManager().processMessage(format, "br", "\n", final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.asOfflinePlayer().getName()); "player", user.offlinePlayer().getName());
audience.sendMessage(message); audience.sendMessage(message);
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
Permission permission = carbonChat.getPermission(); final Permission permission = this.carbonChat.permission();
String format; final String format;
if (permission.playerHas(null, user.asOfflinePlayer(), "carbonchat.shadowmute.exempt")) { if (permission.playerHas(null, user.offlinePlayer(), "carbonchat.shadowmute.exempt")) {
format = carbonChat.getLanguage().getString("shadow-mute-exempt"); format = this.carbonChat.language().getString("shadow-mute-exempt");
} else { } else {
user.setShadowMuted(true); user.shadowMuted(true);
format = carbonChat.getLanguage().getString("is-now-shadow-muted"); format = this.carbonChat.language().getString("is-now-shadow-muted");
} }
Component message = carbonChat.getAdventureManager().processMessage(format, "br", "\n", final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.asOfflinePlayer().getName()); "player", user.offlinePlayer().getName());
audience.sendMessage(message); audience.sendMessage(message);
}); });
@@ -22,109 +22,109 @@ public class SpyChannelCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public SpyChannelCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public SpyChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("channel", CarbonUtils.channelArgument()); channelArguments.put("channel", CarbonUtils.channelArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(channelArguments) .withArguments(channelArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.spy")) .withPermission(CommandPermission.fromString("carbonchat.spy"))
.executesPlayer(this::execute) .executesPlayer(this::execute)
.register(); .register();
LinkedHashMap<String, Argument> whisperArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> whisperArguments = new LinkedHashMap<>();
whisperArguments.put("channel", new LiteralArgument("whispers")); whisperArguments.put("channel", new LiteralArgument("whispers"));
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(whisperArguments) .withArguments(whisperArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.spy")) .withPermission(CommandPermission.fromString("carbonchat.spy"))
.executesPlayer(this::executeWhispers) .executesPlayer(this::executeWhispers)
.register(); .register();
LinkedHashMap<String, Argument> everythingArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> everythingArguments = new LinkedHashMap<>();
everythingArguments.put("channel", new LiteralArgument("*")); everythingArguments.put("channel", new LiteralArgument("*"));
everythingArguments.put("should-spy", new BooleanArgument()); everythingArguments.put("should-spy", new BooleanArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(everythingArguments) .withArguments(everythingArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.spy")) .withPermission(CommandPermission.fromString("carbonchat.spy"))
.executesPlayer(this::executeEverything) // lul .executesPlayer(this::executeEverything) // lul
.register(); .register();
} }
private void execute(@NonNull Player player, @NonNull Object @NonNull [] args) { private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
ChatChannel chatChannel = (ChatChannel) args[0]; final ChatChannel chatChannel = (ChatChannel) args[0];
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
String message; final String message;
UserChannelSettings settings = user.getChannelSettings(chatChannel); final UserChannelSettings settings = user.channelSettings(chatChannel);
if (settings.isSpying()) { if (settings.spying()) {
settings.setSpying(false); settings.spying(false);
message = carbonChat.getLanguage().getString("spy-toggled-off"); message = this.carbonChat.language().getString("spy-toggled-off");
} else { } else {
settings.setSpying(true); settings.spying(true);
message = carbonChat.getLanguage().getString("spy-toggled-on"); message = this.carbonChat.language().getString("spy-toggled-on");
} }
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n", user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n",
"color", "<color:" + chatChannel.getChannelColor(user).toString() + ">", "channel", chatChannel.getName())); "color", "<color:" + chatChannel.channelColor(user).toString() + ">", "channel", chatChannel.name()));
} }
private void executeWhispers(@NonNull Player player, @NonNull Object @NonNull [] args) { private void executeWhispers(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
String message; final String message;
if (user.isSpyingWhispers()) { if (user.spyingwhispers()) {
user.setSpyingWhispers(false); user.spyingWhispers(false);
message = carbonChat.getLanguage().getString("spy-whispers-off"); message = this.carbonChat.language().getString("spy-whispers-off");
} else { } else {
user.setSpyingWhispers(true); user.spyingWhispers(true);
message = carbonChat.getLanguage().getString("spy-whispers-on"); message = this.carbonChat.language().getString("spy-whispers-on");
} }
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n")); user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n"));
} }
private void executeEverything(@NonNull Player player, @NonNull Object @NonNull [] args) { private void executeEverything(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
Boolean shouldSpy = (Boolean) args[0]; final Boolean shouldSpy = (Boolean) args[0];
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
String message; final String message;
if (shouldSpy) { if (shouldSpy) {
user.setSpyingWhispers(true); user.spyingWhispers(true);
for (ChatChannel channel : carbonChat.getChannelManager().getRegistry().values()) { for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
user.getChannelSettings(channel).setSpying(true); user.channelSettings(channel).spying(true);
} }
message = carbonChat.getLanguage().getString("spy-everything-off"); message = this.carbonChat.language().getString("spy-everything-off");
} else { } else {
user.setSpyingWhispers(false); user.spyingWhispers(false);
for (ChatChannel channel : carbonChat.getChannelManager().getRegistry().values()) { for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
user.getChannelSettings(channel).setSpying(false); user.channelSettings(channel).spying(false);
} }
message = carbonChat.getLanguage().getString("spy-everything-on"); message = this.carbonChat.language().getString("spy-everything-on");
} }
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n")); user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n"));
} }
} }
@@ -21,57 +21,63 @@ public class SudoChannelCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public SudoChannelCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public SudoChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> setOtherChannelArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> setOtherChannelArguments = new LinkedHashMap<>();
setOtherChannelArguments.put("player", CarbonUtils.onlineChatUserArgument()); setOtherChannelArguments.put("player", CarbonUtils.onlineChatUserArgument());
setOtherChannelArguments.put("channel", CarbonUtils.channelArgument()); setOtherChannelArguments.put("channel", CarbonUtils.channelArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(setOtherChannelArguments) .withArguments(setOtherChannelArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channel.others")) .withPermission(CommandPermission.fromString("carbonchat.channel.others"))
.executes((sender, args) -> { this.setOtherChannel(sender, (ChatUser) args[0], (ChatChannel) args[1]); }) .executes((sender, args) -> {
this.otherChannel(sender, (ChatUser) args[0], (ChatChannel) args[1]);
})
.register(); .register();
LinkedHashMap<String, Argument> sendMessageOtherArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> sendMessageOtherArguments = new LinkedHashMap<>();
sendMessageOtherArguments.put("player", CarbonUtils.onlineChatUserArgument()); sendMessageOtherArguments.put("player", CarbonUtils.onlineChatUserArgument());
sendMessageOtherArguments.put("channel", CarbonUtils.channelArgument()); sendMessageOtherArguments.put("channel", CarbonUtils.channelArgument());
sendMessageOtherArguments.put("message", new GreedyStringArgument()); sendMessageOtherArguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(sendMessageOtherArguments) .withArguments(sendMessageOtherArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channel.others.message")) .withPermission(CommandPermission.fromString("carbonchat.channel.others.message"))
.executes((sender, args) -> { this.sendMessageOther(sender, (ChatUser) args[0], (ChatChannel) args[1], (String) args[2]); }) .executes((sender, args) -> {
this.sendMessageOther(sender, (ChatUser) args[0], (ChatChannel) args[1], (String) args[2]);
})
.register(); .register();
} }
private void setOtherChannel(@NonNull CommandSender sender, @NonNull ChatUser user, @NonNull ChatChannel channel) { private void otherChannel(@NonNull final CommandSender sender, @NonNull final ChatUser user, @NonNull final ChatChannel channel) {
user.setSelectedChannel(channel); user.selectedChannel(channel);
String message = channel.getSwitchMessage(); final String message = channel.switchMessage();
String otherMessage = channel.getSwitchOtherMessage(); final String otherMessage = channel.switchOtherMessage();
user.sendMessage(carbonChat.getAdventureManager().processMessage(message, "br", "\n", user.sendMessage(this.carbonChat.adventureManager().processMessage(message, "br", "\n",
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName())); "color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
carbonChat.getAdventureManager().getAudiences().audience(sender).sendMessage(carbonChat.getAdventureManager().processMessage(otherMessage, "br", "\n", this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName(), this.carbonChat.adventureManager().processMessage(otherMessage, "br", "\n",
"player", user.asOfflinePlayer().getName())); "color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name(),
"player", user.offlinePlayer().getName()));
} }
private void sendMessageOther(@NonNull CommandSender sender, @NonNull ChatUser user, @NonNull ChatChannel channel, @NonNull String message) { private void sendMessageOther(@NonNull final CommandSender sender, @NonNull final ChatUser user,
Component component = channel.sendMessage(user, message, false); @NonNull final ChatChannel channel, @NonNull final String message) {
final Component component = channel.sendMessage(user, message, false);
carbonChat.getAdventureManager().getAudiences().console().sendMessage(component); this.carbonChat.adventureManager().audiences().console().sendMessage(component);
} }
} }
@@ -21,83 +21,84 @@ public class ToggleCommand {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public ToggleCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) { public ToggleCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) { if (!commandSettings.enabled()) {
return; return;
} }
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("channel", CarbonUtils.channelArgument()); channelArguments.put("channel", CarbonUtils.channelArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(channelArguments) .withArguments(channelArguments)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.toggle")) .withPermission(CommandPermission.fromString("carbonchat.toggle"))
.executesPlayer(this::executeSelf) .executesPlayer(this::executeSelf)
.register(); .register();
LinkedHashMap<String, Argument> argumentsOther = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> argumentsOther = new LinkedHashMap<>();
argumentsOther.put("players", CarbonUtils.chatUserArgument()); argumentsOther.put("players", CarbonUtils.chatUserArgument());
argumentsOther.put("channel", CarbonUtils.channelArgument()); argumentsOther.put("channel", CarbonUtils.channelArgument());
new CommandAPICommand(commandSettings.getName()) new CommandAPICommand(commandSettings.name())
.withArguments(argumentsOther) .withArguments(argumentsOther)
.withAliases(commandSettings.getAliasesArray()) .withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.toggle")) .withPermission(CommandPermission.fromString("carbonchat.toggle"))
.executes(this::executeOther) .executes(this::executeOther)
.register(); .register();
} }
private void executeSelf(@NonNull Player player, @NonNull Object @NonNull [] args) { private void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
ChatChannel channel = (ChatChannel) args[0]; final ChatChannel channel = (ChatChannel) args[0];
String message; final String message;
UserChannelSettings settings = user.getChannelSettings(channel); final UserChannelSettings settings = user.channelSettings(channel);
if (!channel.isIgnorable()) { if (!channel.ignorable()) {
message = channel.getCannotIgnoreMessage(); message = channel.cannotIgnoreMessage();
} else if (settings.isIgnored()) { } else if (settings.ignored()) {
settings.setIgnoring(false); settings.ignoring(false);
message = channel.getToggleOffMessage(); message = channel.toggleOffMessage();
} else { } else {
settings.setIgnoring(true); settings.ignoring(true);
message = channel.getToggleOnMessage(); message = channel.toggleOnMessage();
} }
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n", user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n",
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName())); "color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
} }
private void executeOther(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) { private void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
ChatUser user = (ChatUser) args[0]; final ChatUser user = (ChatUser) args[0];
ChatChannel channel = (ChatChannel) args[1]; final ChatChannel channel = (ChatChannel) args[1];
String message; final String message;
String otherMessage; final String otherMessage;
UserChannelSettings settings = user.getChannelSettings(channel); final UserChannelSettings settings = user.channelSettings(channel);
if (settings.isIgnored()) { if (settings.ignored()) {
settings.setIgnoring(false); settings.ignoring(false);
message = channel.getToggleOffMessage(); message = channel.toggleOffMessage();
otherMessage = channel.getToggleOtherOffMessage(); otherMessage = channel.toggleOtherOffMessage();
} else { } else {
settings.setIgnoring(true); settings.ignoring(true);
message = channel.getToggleOnMessage(); message = channel.toggleOnMessage();
otherMessage = channel.getToggleOtherOnMessage(); otherMessage = channel.toggleOtherOnMessage();
} }
user.sendMessage(carbonChat.getAdventureManager().processMessage(message, "br", "\n", user.sendMessage(this.carbonChat.adventureManager().processMessage(message, "br", "\n",
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName())); "color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
carbonChat.getAdventureManager().getAudiences().audience(sender).sendMessage(carbonChat.getAdventureManager().processMessage(otherMessage, this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(
"br", "\n", "color", "<color:" + channel.getChannelColor(user).toString() + ">", this.carbonChat.adventureManager().processMessage(otherMessage,
"channel", channel.getName(), "player", user.asOfflinePlayer().getName())); "br", "\n", "color", "<color:" + channel.channelColor(user).toString() + ">",
"channel", channel.name(), "player", user.offlinePlayer().getName()));
} }
} }
@@ -24,6 +24,7 @@ public class ChannelRegisterEvent extends Event {
} }
@NonNull @NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@@ -37,19 +38,19 @@ public class ChannelRegisterEvent extends Event {
@NonNull @NonNull
private final Registry<ChatChannel> registry; private final Registry<ChatChannel> registry;
public ChannelRegisterEvent(@NonNull List<@NonNull ChatChannel> registeredChannels, @NonNull Registry<ChatChannel> registry) { public ChannelRegisterEvent(@NonNull final List<@NonNull ChatChannel> registeredChannels, @NonNull final Registry<ChatChannel> registry) {
super(!Bukkit.isPrimaryThread()); super(!Bukkit.isPrimaryThread());
this.registeredChannels = registeredChannels; this.registeredChannels = registeredChannels;
this.registry = registry; this.registry = registry;
} }
public void register(@NonNull ChatChannel chatChannel) { public void register(@NonNull final ChatChannel chatChannel) {
registry.register(chatChannel.getKey(), chatChannel); this.registry.register(chatChannel.key(), chatChannel);
} }
@NonNull @NonNull
public List<@NonNull ChatChannel> getRegisteredChannels() { public List<@NonNull ChatChannel> registeredChannels() {
return registeredChannels; return this.registeredChannels;
} }
} }
@@ -25,17 +25,18 @@ public class ChannelSwitchEvent extends Event implements Cancellable {
} }
@NonNull @NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(boolean cancelled) { public void setCancelled(final boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
@@ -51,7 +52,7 @@ public class ChannelSwitchEvent extends Event implements Cancellable {
@Nullable @Nullable
private String failureMessage; private String failureMessage;
public ChannelSwitchEvent(@NonNull ChatChannel channel, @NonNull ChatUser user, @Nullable String failureMessage) { public ChannelSwitchEvent(@NonNull final ChatChannel channel, @NonNull final ChatUser user, @Nullable final String failureMessage) {
super(!Bukkit.isPrimaryThread()); super(!Bukkit.isPrimaryThread());
this.channel = channel; this.channel = channel;
@@ -60,21 +61,21 @@ public class ChannelSwitchEvent extends Event implements Cancellable {
} }
@NonNull @NonNull
public ChatUser getUser() { public ChatUser user() {
return user; return this.user;
} }
@NonNull @NonNull
public ChatChannel getChannel() { public ChatChannel channel() {
return channel; return this.channel;
} }
@Nullable @Nullable
public String getFailureMessage() { public String failureMessage() {
return failureMessage; return this.failureMessage;
} }
public void setFailureMessage(@Nullable String failureMessage) { public void failureMessage(@Nullable final String failureMessage) {
this.failureMessage = failureMessage; this.failureMessage = failureMessage;
} }
} }
@@ -31,7 +31,10 @@ public class ChatComponentEvent extends Event implements Cancellable {
@NonNull @NonNull
private final String originalMessage; private final String originalMessage;
public ChatComponentEvent(@NonNull ChatUser sender, @Nullable ChatUser target, @NonNull ChatChannel chatChannel, @NonNull TextComponent component, @NonNull String originalMessage) { public ChatComponentEvent(@NonNull final ChatUser sender, @Nullable final ChatUser target,
@NonNull final ChatChannel chatChannel, @NonNull final TextComponent component,
@NonNull final String originalMessage) {
super(!Bukkit.isPrimaryThread()); super(!Bukkit.isPrimaryThread());
this.sender = sender; this.sender = sender;
@@ -43,11 +46,11 @@ public class ChatComponentEvent extends Event implements Cancellable {
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return isCancelled; return this.isCancelled;
} }
@Override @Override
public void setCancelled(boolean cancelled) { public void setCancelled(final boolean cancelled) {
this.isCancelled = cancelled; this.isCancelled = cancelled;
} }
@@ -58,41 +61,42 @@ public class ChatComponentEvent extends Event implements Cancellable {
} }
@NonNull @NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return HANDLERS_LIST; return HANDLERS_LIST;
} }
@NonNull @NonNull
public ChatUser getSender() { public ChatUser sender() {
return sender; return this.sender;
} }
@Nullable @Nullable
public ChatUser getTarget() { public ChatUser target() {
return target; return this.target;
} }
@NonNull @NonNull
public ChatChannel getChannel() { public ChatChannel channel() {
return chatChannel; return this.chatChannel;
} }
public void setChannel(@NonNull ChatChannel chatChannel) { public void channel(@NonNull final ChatChannel chatChannel) {
this.chatChannel = chatChannel; this.chatChannel = chatChannel;
} }
@NonNull @NonNull
public TextComponent getComponent() { public TextComponent component() {
return component; return this.component;
} }
public void setComponent(@NonNull TextComponent component) { public void component(@NonNull final TextComponent component) {
this.component = component; this.component = component;
} }
@NonNull @NonNull
public String getOriginalMessage() { public String originalMessage() {
return originalMessage; return this.originalMessage;
} }
} }
@@ -30,7 +30,9 @@ public class ChatFormatEvent extends Event implements Cancellable {
@NonNull @NonNull
private String message; private String message;
public ChatFormatEvent(@NonNull ChatUser sender, @Nullable ChatUser target, @NonNull ChatChannel chatChannel, @Nullable String format, @NonNull String message) { public ChatFormatEvent(@NonNull final ChatUser sender, @Nullable final ChatUser target,
@NonNull final ChatChannel chatChannel, @Nullable final String format,
@NonNull final String message) {
super(!Bukkit.isPrimaryThread()); super(!Bukkit.isPrimaryThread());
this.sender = sender; this.sender = sender;
@@ -43,11 +45,11 @@ public class ChatFormatEvent extends Event implements Cancellable {
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return isCancelled; return this.isCancelled;
} }
@Override @Override
public void setCancelled(boolean cancelled) { public void setCancelled(final boolean cancelled) {
this.isCancelled = cancelled; this.isCancelled = cancelled;
} }
@@ -58,44 +60,45 @@ public class ChatFormatEvent extends Event implements Cancellable {
} }
@NonNull @NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return HANDLERS_LIST; return HANDLERS_LIST;
} }
@NonNull @NonNull
public ChatUser getSender() { public ChatUser sender() {
return sender; return this.sender;
} }
@Nullable @Nullable
public ChatUser getTarget() { public ChatUser target() {
return target; return this.target;
} }
@NonNull @NonNull
public ChatChannel getChannel() { public ChatChannel channel() {
return chatChannel; return this.chatChannel;
} }
public void setChannel(@NonNull ChatChannel chatChannel) { public void channel(@NonNull final ChatChannel chatChannel) {
this.chatChannel = chatChannel; this.chatChannel = chatChannel;
} }
@Nullable @Nullable
public String getFormat() { public String format() {
return format; return this.format;
} }
public void setFormat(@Nullable String format) { public void format(@Nullable final String format) {
this.format = format; this.format = format;
} }
@NonNull @NonNull
public String getMessage() { public String message() {
return message; return this.message;
} }
public void setMessage(@NonNull String message) { public void message(@NonNull final String message) {
this.message = message; this.message = message;
} }
} }
@@ -27,7 +27,8 @@ public class PreChatFormatEvent extends Event implements Cancellable {
@NonNull @NonNull
private String message; private String message;
public PreChatFormatEvent(@NonNull ChatUser user, @NonNull ChatChannel chatChannel, @Nullable String format, @NonNull String message) { public PreChatFormatEvent(@NonNull final ChatUser user, @NonNull final ChatChannel chatChannel,
@Nullable final String format, @NonNull final String message) {
super(!Bukkit.isPrimaryThread()); super(!Bukkit.isPrimaryThread());
this.user = user; this.user = user;
@@ -38,11 +39,11 @@ public class PreChatFormatEvent extends Event implements Cancellable {
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return isCancelled; return this.isCancelled;
} }
@Override @Override
public void setCancelled(boolean cancelled) { public void setCancelled(final boolean cancelled) {
this.isCancelled = cancelled; this.isCancelled = cancelled;
} }
@@ -53,39 +54,40 @@ public class PreChatFormatEvent extends Event implements Cancellable {
} }
@NonNull @NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return HANDLERS_LIST; return HANDLERS_LIST;
} }
@NonNull @NonNull
public ChatUser getUser() { public ChatUser user() {
return user; return this.user;
} }
@NonNull @NonNull
public ChatChannel getChannel() { public ChatChannel channel() {
return chatChannel; return this.chatChannel;
} }
public void setChannel(@NonNull ChatChannel chatChannel) { public void channel(@NonNull final ChatChannel chatChannel) {
this.chatChannel = chatChannel; this.chatChannel = chatChannel;
} }
@Nullable @Nullable
public String getFormat() { public String format() {
return format; return this.format;
} }
public void setFormat(@Nullable String format) { public void format(@Nullable final String format) {
this.format = format; this.format = format;
} }
@NonNull @NonNull
public String getMessage() { public String message() {
return message; return this.message;
} }
public void setMessage(@NonNull String message) { public void message(@NonNull final String message) {
this.message = message; this.message = message;
} }
@@ -24,17 +24,18 @@ public class PrivateMessageEvent extends Event implements Cancellable {
} }
@NonNull @NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(boolean cancelled) { public void setCancelled(final boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
@@ -56,7 +57,10 @@ public class PrivateMessageEvent extends Event implements Cancellable {
@NonNull @NonNull
private final String message; private final String message;
public PrivateMessageEvent(@NonNull ChatUser sender, @NonNull ChatUser target, @NonNull Component senderComponent, @NonNull Component targetComponent, @NonNull String message) { public PrivateMessageEvent(@NonNull final ChatUser sender, @NonNull final ChatUser target,
@NonNull final Component senderComponent, @NonNull final Component targetComponent,
@NonNull final String message) {
super(!Bukkit.isPrimaryThread()); super(!Bukkit.isPrimaryThread());
this.sender = sender; this.sender = sender;
@@ -67,28 +71,28 @@ public class PrivateMessageEvent extends Event implements Cancellable {
} }
@NonNull @NonNull
public ChatUser getSender() { public ChatUser sender() {
return sender; return this.sender;
} }
@NonNull @NonNull
public ChatUser getTarget() { public ChatUser target() {
return target; return this.target;
} }
@NonNull @NonNull
public Component getSenderComponent() { public Component senderComponent() {
return senderComponent; return this.senderComponent;
} }
@NonNull @NonNull
public Component getTargetComponent() { public Component targetComponent() {
return targetComponent; return this.targetComponent;
} }
@NonNull @NonNull
public String getMessage() { public String message() {
return message; return this.message;
} }
} }
@@ -14,35 +14,34 @@ import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
public class BukkitChatListener implements Listener { public class BukkitChatListener implements Listener {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public BukkitChatListener(@NonNull CarbonChat carbonChat) { public BukkitChatListener(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
} }
// Chat messages // Chat messages
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerchat(AsyncPlayerChatEvent event) { public void onPlayerchat(@NonNull final AsyncPlayerChatEvent event) {
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
ChatChannel channel = user.getSelectedChannel(); ChatChannel channel = user.selectedChannel();
if (channel.shouldCancelChatEvent()) { if (channel.shouldCancelChatEvent()) {
event.setCancelled(true); event.setCancelled(true);
} }
for (ChatChannel entry : carbonChat.getChannelManager().getRegistry().values()) { for (final ChatChannel entry : this.carbonChat.channelManager().registry().values()) {
if (entry.getMessagePrefix() == null || entry.getMessagePrefix().isEmpty()) { if (entry.messagePrefix() == null || entry.messagePrefix().isEmpty()) {
continue; continue;
} }
if (event.getMessage().startsWith(entry.getMessagePrefix())) { if (event.getMessage().startsWith(entry.messagePrefix())) {
if (entry.canPlayerUse(user)) { if (entry.canPlayerUse(user)) {
event.setMessage(event.getMessage().substring(entry.getMessagePrefix().length())); event.setMessage(event.getMessage().substring(entry.messagePrefix().length()));
channel = entry; channel = entry;
break; break;
} }
@@ -60,30 +59,30 @@ public class BukkitChatListener implements Listener {
if (selectedChannel.honorsRecipientList()) { if (selectedChannel.honorsRecipientList()) {
recipients = new HashSet<>(); recipients = new HashSet<>();
for (Player recipient : event.getRecipients()) { for (final Player recipient : event.getRecipients()) {
recipients.add(carbonChat.getUserService().wrap(recipient)); recipients.add(this.carbonChat.userService().wrap(recipient));
} }
} else { } else {
recipients = (List<ChatUser>) selectedChannel.audiences(); recipients = selectedChannel.audiences();
} }
event.getRecipients().clear(); event.getRecipients().clear();
if (event.isAsynchronous()) { if (event.isAsynchronous()) {
Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false); final Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false);
event.setFormat(CarbonChat.LEGACY.serialize(component) event.setFormat(CarbonChat.LEGACY.serialize(component)
.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%")); .replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%"));
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false); final Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false);
carbonChat.getAdventureManager().getAudiences().console().sendMessage(component); this.carbonChat.adventureManager().audiences().console().sendMessage(component);
if (carbonChat.getConfig().getBoolean("show-tips")) { if (this.carbonChat.getConfig().getBoolean("show-tips")) {
carbonChat.getLogger().info("Tip: Sync chat event! I cannot set the message format due to this. :("); this.carbonChat.getLogger().info("Tip: Sync chat event! I cannot set the message format due to this. :(");
carbonChat.getLogger().info("Tip: To 'solve' this, do a binary search and see which plugin is triggering"); this.carbonChat.getLogger().info("Tip: To 'solve' this, do a binary search and see which plugin is triggering");
carbonChat.getLogger().info("Tip: sync chat events and causing this, and let that plugin author know."); this.carbonChat.getLogger().info("Tip: sync chat events and causing this, and let that plugin author know.");
} }
}); });
} }
@@ -12,38 +12,38 @@ public class CapsHandler implements Listener {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public CapsHandler(@NonNull CarbonChat carbonChat) { public CapsHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
} }
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onMessage(PreChatFormatEvent event) { public void onMessage(final PreChatFormatEvent event) {
if (!carbonChat.getModConfig().getBoolean("caps-protection.enabled")) { if (!this.carbonChat.moderationConfig().getBoolean("caps-protection.enabled")) {
return; return;
} }
if (!(event.getMessage().length() >= carbonChat.getModConfig().getInt("caps-protection.minimum-length"))) { if (!(event.message().length() >= this.carbonChat.moderationConfig().getInt("caps-protection.minimum-length"))) {
return; return;
} }
int amountOfCaps = 0; int amountOfCaps = 0;
for (char letter : event.getMessage().toCharArray()) { for (final char letter : event.message().toCharArray()) {
if (Character.isUpperCase(letter)) { if (Character.isUpperCase(letter)) {
amountOfCaps++; amountOfCaps++;
} }
} }
double capsPercentage = (amountOfCaps * 100.0) / event.getMessage().length(); final double capsPercentage = (amountOfCaps * 100.0) / event.message().length();
if (!(capsPercentage >= carbonChat.getModConfig().getDouble("caps-protection.percent-caps"))) { if (!(capsPercentage >= this.carbonChat.moderationConfig().getDouble("caps-protection.percent-caps"))) {
return; return;
} }
if (carbonChat.getModConfig().getBoolean("block-message")) { if (this.carbonChat.moderationConfig().getBoolean("block-message")) {
event.setCancelled(true); event.setCancelled(true);
} else { } else {
event.setMessage(event.getMessage().toLowerCase()); event.message(event.message().toLowerCase());
} }
} }
@@ -6,23 +6,24 @@ import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.checkerframework.checker.nullness.qual.NonNull;
public class CustomPlaceholderHandler implements Listener { public class CustomPlaceholderHandler implements Listener {
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public CustomPlaceholderHandler(CarbonChat carbonChat) { public CustomPlaceholderHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(PreChatFormatEvent event) { public void onPapiPlaceholder(final PreChatFormatEvent event) {
ConfigurationSection placeholders = carbonChat.getConfig().getConfigurationSection("placeholders"); final ConfigurationSection placeholders = this.carbonChat.getConfig().getConfigurationSection("placeholders");
for (String key : placeholders.getKeys(false)) { for (final String key : placeholders.getKeys(false)) {
String value = placeholders.getString(key); final String value = placeholders.getString(key);
event.setFormat(event.getFormat().replace("<" + key + ">", value)); event.format(event.format().replace("<" + key + ">", value));
} }
} }
@@ -23,70 +23,69 @@ public class FilterHandler implements Listener {
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
@NonNull @NonNull
private final Map<String, List<Pattern>> patternReplacements = new HashMap<>(); private final Map<String, List<@NonNull Pattern>> patternReplacements = new HashMap<>();
@NonNull @NonNull
private final List<Pattern> blockedWords = new ArrayList<>(); private final List<@NonNull Pattern> blockedWords = new ArrayList<>();
public FilterHandler(@NonNull CarbonChat carbonChat) { public FilterHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
reloadFilters(); this.reloadFilters();
} }
public void reloadFilters() { public void reloadFilters() {
patternReplacements.clear(); this.patternReplacements.clear();
blockedWords.clear(); this.blockedWords.clear();
FileConfiguration config = carbonChat.getModConfig(); final FileConfiguration config = this.carbonChat.moderationConfig();
ConfigurationSection filters = config.getConfigurationSection("filters.filters"); final ConfigurationSection filters = config.getConfigurationSection("filters.filters");
if (filters != null) { if (filters != null) {
for (String replacement : filters.getKeys(false)) { for (final String replacement : filters.getKeys(false)) {
List<Pattern> patterns = new ArrayList<>(); final List<Pattern> patterns = new ArrayList<>();
for (String word : filters.getStringList(replacement)) { for (final String word : filters.getStringList(replacement)) {
if (carbonChat.getModConfig().getBoolean("filters.case-sensitive")) { if (this.carbonChat.moderationConfig().getBoolean("filters.case-sensitive")) {
patterns.add(Pattern.compile(word)); patterns.add(Pattern.compile(word));
} else { } else {
patterns.add(Pattern.compile(word, Pattern.CASE_INSENSITIVE)); patterns.add(Pattern.compile(word, Pattern.CASE_INSENSITIVE));
} }
} }
patternReplacements.put(replacement, patterns); this.patternReplacements.put(replacement, patterns);
} }
} }
for (String replacement : config.getStringList("filters.blocked-words")) { for (final String replacement : config.getStringList("filters.blocked-words")) {
if (carbonChat.getModConfig().getBoolean("filters.case-sensitive")) { if (this.carbonChat.moderationConfig().getBoolean("filters.case-sensitive")) {
blockedWords.add(Pattern.compile(replacement)); this.blockedWords.add(Pattern.compile(replacement));
} else { } else {
blockedWords.add(Pattern.compile(replacement, Pattern.CASE_INSENSITIVE)); this.blockedWords.add(Pattern.compile(replacement, Pattern.CASE_INSENSITIVE));
} }
} }
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onFilter(PreChatFormatEvent event) { public void onFilter(final PreChatFormatEvent event) {
if (!carbonChat.getModConfig().getBoolean("filters.enabled")) { if (!this.carbonChat.moderationConfig().getBoolean("filters.enabled")) {
return; return;
} }
if (event.getUser().isOnline()) { if (event.user().online()) {
if (event.getUser().asPlayer().hasPermission("carbonchat.filter.exempt")) { if (event.user().player().hasPermission("carbonchat.filter.exempt")) {
return; return;
} }
} }
if (!channelUsesFilter(event.getChannel())) { if (!this.channelUsesFilter(event.channel())) {
return; return;
} }
String message = event.getMessage(); String message = event.message();
//Matcher matcher;
for (Map.Entry<String, List<Pattern>> entry : patternReplacements.entrySet()) { for (final Map.Entry<String, List<Pattern>> entry : this.patternReplacements.entrySet()) {
for (Pattern pattern : entry.getValue()) { for (final Pattern pattern : entry.getValue()) {
Matcher matcher = pattern.matcher(message); final Matcher matcher = pattern.matcher(message);
if (entry.getKey().equals("_")) { if (entry.getKey().equals("_")) {
message = matcher.replaceAll(""); message = matcher.replaceAll("");
@@ -96,18 +95,18 @@ public class FilterHandler implements Listener {
} }
} }
event.setMessage(message); event.message(message);
for (Pattern blockedWord : blockedWords) { for (final Pattern blockedWord : this.blockedWords) {
if (blockedWord.matcher(event.getMessage()).find()) { if (blockedWord.matcher(event.message()).find()) {
event.setCancelled(true); event.setCancelled(true);
break; break;
} }
} }
} }
private boolean channelUsesFilter(@NonNull ChatChannel chatChannel) { private boolean channelUsesFilter(@NonNull final ChatChannel chatChannel) {
Object filter = chatChannel.getContext("filter"); final Object filter = chatChannel.context("filter");
return filter instanceof Boolean && ((Boolean) filter); return filter instanceof Boolean && ((Boolean) filter);
} }
@@ -8,12 +8,12 @@ import org.bukkit.event.Listener;
public class IgnoredPlayerHandler implements Listener { public class IgnoredPlayerHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(ChatFormatEvent event) { public void onPapiPlaceholder(final ChatFormatEvent event) {
if (event.getTarget() == null) { if (event.target() == null) {
return; return;
} }
if (event.getTarget().isIgnoringUser(event.getSender())) { if (event.target().ignoringUser(event.sender())) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@@ -14,30 +14,30 @@ import java.util.regex.Pattern;
public class ItemLinkHandler implements Listener { public class ItemLinkHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onItemLink(ChatComponentEvent event) { public void onItemLink(final ChatComponentEvent event) {
// Handle item linking placeholders // Handle item linking placeholders
if (event.getSender().isOnline()) { if (event.sender().online()) {
Player player = event.getSender().asPlayer(); final Player player = event.sender().player();
if (!player.hasPermission("carbonchat.itemlink")) { if (!player.hasPermission("carbonchat.itemlink")) {
return; return;
} }
Component itemComponent = CarbonUtils.createComponent(player); final Component itemComponent = CarbonUtils.createComponent(player);
if (itemComponent.equals(TextComponent.empty())) { if (itemComponent.equals(TextComponent.empty())) {
return; return;
} }
for (Pattern pattern : event.getChannel().getItemLinkPatterns()) { for (final Pattern pattern : event.channel().itemLinkPatterns()) {
String patternContent = pattern.toString().replace("\\Q", "").replace("\\E", ""); final String patternContent = pattern.toString().replace("\\Q", "").replace("\\E", "");
if (event.getOriginalMessage().contains(patternContent)) { if (event.originalMessage().contains(patternContent)) {
TextComponent component = (TextComponent) event.getComponent().replaceFirstText(pattern, (input) -> { final TextComponent component = (TextComponent) event.component().replaceFirstText(pattern, input -> {
return TextComponent.builder().append(itemComponent); return TextComponent.builder().append(itemComponent);
}); });
event.setComponent(component); event.component(component);
break; break;
} }
} }
@@ -11,9 +11,9 @@ import org.bukkit.event.Listener;
public class LegacyFormatHandler implements Listener { public class LegacyFormatHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onLegacyFormat(PreChatFormatEvent event) { public void onLegacyFormat(final PreChatFormatEvent event) {
Component component = CarbonChat.LEGACY.deserialize(event.getFormat()); final Component component = CarbonChat.LEGACY.deserialize(event.format());
event.setFormat(MiniMessage.get().serialize(component)); event.format(MiniMessage.get().serialize(component));
} }
} }
@@ -7,8 +7,8 @@ import org.bukkit.event.Listener;
public class MuteHandler implements Listener { public class MuteHandler implements Listener {
@EventHandler @EventHandler
public void onMute(PreChatFormatEvent event) { public void onMute(final PreChatFormatEvent event) {
if (event.getUser().isMuted()) { if (event.user().muted()) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@@ -8,10 +8,10 @@ import org.bukkit.event.Listener;
public class OfflineNameHandler implements Listener { public class OfflineNameHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onOfflineMessage(PreChatFormatEvent event) { public void onOfflineMessage(final PreChatFormatEvent event) {
// If the player isn't online (cross server message), use their normal name // If the player isn't online (cross server message), use their normal name
if (!event.getUser().isOnline()) { if (!event.user().online()) {
event.setFormat(event.getFormat().replace("%player_displayname%", "%player_name%")); event.format(event.format().replace("%player_displayname%", "%player_name%"));
} }
} }
@@ -14,44 +14,44 @@ public class PingHandler implements Listener {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public PingHandler(@NonNull CarbonChat carbonChat) { public PingHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPing(ChatComponentEvent event) { public void onPing(final ChatComponentEvent event) {
if (!carbonChat.getConfig().getBoolean("pings.enabled")) { if (!this.carbonChat.getConfig().getBoolean("pings.enabled")) {
return; return;
} }
if (event.getTarget() == null) { if (event.target() == null) {
return; return;
} }
String targetName = event.getTarget().asOfflinePlayer().getName(); final String targetName = event.target().offlinePlayer().getName();
String prefix = carbonChat.getConfig().getString("pings.prefix", ""); final String prefix = this.carbonChat.getConfig().getString("pings.prefix", "");
boolean caseSensitive = carbonChat.getConfig().getBoolean("pings.case-sensitive", false); final boolean caseSensitive = this.carbonChat.getConfig().getBoolean("pings.case-sensitive", false);
if (targetName == null) { if (targetName == null) {
return; return;
} }
if (caseSensitive) { if (caseSensitive) {
if (!event.getOriginalMessage().contains(prefix + targetName)) { if (!event.originalMessage().contains(prefix + targetName)) {
return; return;
} }
} else { } else {
if (!event.getOriginalMessage().toLowerCase().contains((prefix + targetName).toLowerCase())) { if (!event.originalMessage().toLowerCase().contains((prefix + targetName).toLowerCase())) {
return; return;
} }
} }
Key key = Key.of(carbonChat.getConfig().getString("pings.sound")); final Key key = Key.of(this.carbonChat.getConfig().getString("pings.sound"));
Sound.Source source = Sound.Source.valueOf(carbonChat.getConfig().getString("pings.source")); final Sound.Source source = Sound.Source.valueOf(this.carbonChat.getConfig().getString("pings.source"));
float volume = (float) carbonChat.getConfig().getDouble("pings.volume"); final float volume = (float) this.carbonChat.getConfig().getDouble("pings.volume");
float pitch = (float) carbonChat.getConfig().getDouble("pings.pitch"); final float pitch = (float) this.carbonChat.getConfig().getDouble("pings.pitch");
event.getTarget().playSound(Sound.of(key, source, volume, pitch)); event.target().playSound(Sound.of(key, source, volume, pitch));
} }
} }
@@ -9,8 +9,8 @@ import org.bukkit.event.Listener;
public class PlaceholderHandler implements Listener { public class PlaceholderHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(PreChatFormatEvent event) { public void onPapiPlaceholder(final PreChatFormatEvent event) {
event.setFormat(PlaceholderAPI.setPlaceholders(event.getUser().asOfflinePlayer(), event.getFormat())); event.format(PlaceholderAPI.setPlaceholders(event.user().offlinePlayer(), event.format()));
} }
} }
@@ -14,44 +14,44 @@ public class PlayerJoinListener implements Listener {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public PlayerJoinListener(@NonNull CarbonChat carbonChat) { public PlayerJoinListener(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
} }
@EventHandler @EventHandler
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(final PlayerJoinEvent event) {
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
carbonChat.getUserService().validate(user); this.carbonChat.userService().validate(user);
if (user.getNickname() != null) { if (user.nickname() != null) {
user.setNickname(user.getNickname()); user.nickname(user.nickname());
} }
String channel = carbonChat.getConfig().getString("channel-on-join"); final String channel = this.carbonChat.getConfig().getString("channel-on-join");
if (channel == null || channel.isEmpty()) { if (channel == null || channel.isEmpty()) {
return; return;
} }
if (channel.equals("DEFAULT")) { if (channel.equals("DEFAULT")) {
user.setSelectedChannel(carbonChat.getChannelManager().getDefaultChannel()); user.selectedChannel(this.carbonChat.channelManager().defaultChannel());
return; return;
} }
ChatChannel chatChannel = carbonChat.getChannelManager().getRegistry().get(channel); final ChatChannel chatChannel = this.carbonChat.channelManager().registry().channel(channel);
if (chatChannel != null) { if (chatChannel != null) {
user.setSelectedChannel(chatChannel); user.selectedChannel(chatChannel);
} }
} }
@EventHandler @EventHandler
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(final PlayerQuitEvent event) {
ChatUser user = carbonChat.getUserService().wrapIfLoaded(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrapIfLoaded(event.getPlayer());
if (user != null) { if (user != null) {
carbonChat.getUserService().invalidate(user); this.carbonChat.userService().invalidate(user);
} }
} }
@@ -10,19 +10,19 @@ import org.bukkit.event.Listener;
public class RelationalPlaceholderHandler implements Listener { public class RelationalPlaceholderHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(ChatFormatEvent event) { public void onPapiPlaceholder(final ChatFormatEvent event) {
if (event.getTarget() == null) { if (event.target() == null) {
return; return;
} }
if (!event.getSender().isOnline() || !event.getTarget().isOnline()) { if (!event.sender().online() || !event.target().online()) {
return; return;
} }
Player sender = event.getSender().asPlayer(); final Player sender = event.sender().player();
Player target = event.getTarget().asPlayer(); final Player target = event.target().player();
event.setFormat(PlaceholderAPI.setRelationalPlaceholders(sender, target, event.getFormat())); event.format(PlaceholderAPI.setRelationalPlaceholders(sender, target, event.format()));
} }
} }
@@ -13,32 +13,32 @@ public class ShadowMuteHandler implements Listener {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public ShadowMuteHandler(@NonNull CarbonChat carbonChat) { public ShadowMuteHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onComponent(ChatComponentEvent event) { public void onComponent(final ChatComponentEvent event) {
if (event.getSender().isShadowMuted()) { if (event.sender().shadowMuted()) {
if (!event.getSender().equals(event.getTarget())) { if (!event.sender().equals(event.target())) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
@EventHandler @EventHandler
public void on(ChatFormatEvent event) { public void on(final ChatFormatEvent event) {
if (event.getTarget() != null) { if (event.target() != null) {
return; return;
} }
if (!event.getSender().isShadowMuted()) { if (!event.sender().shadowMuted()) {
return; return;
} }
String prefix = carbonChat.getModConfig().getString("shadow-mute-prefix", "[SM] "); final String prefix = this.carbonChat.moderationConfig().getString("shadow-mute-prefix", "[SM] ");
event.setFormat(prefix + event.getFormat()); event.format(prefix + event.format());
} }
} }
@@ -10,25 +10,25 @@ import org.bukkit.event.Listener;
public class UserFormattingHandler implements Listener { public class UserFormattingHandler implements Listener {
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onFormat(PreChatFormatEvent event) { public void onFormat(final PreChatFormatEvent event) {
if (!event.getUser().isOnline()) { if (!event.user().online()) {
suppressFormatting(event); this.suppressFormatting(event);
return; return;
} }
Player player = event.getUser().asPlayer(); final Player player = event.user().player();
if (!player.hasPermission("carbonchat.formatting") && if (!player.hasPermission("carbonchat.formatting") &&
!player.hasPermission("carbonchat.channels." + event.getChannel().getKey() + ".formatting")) { !player.hasPermission("carbonchat.channels." + event.channel().key() + ".formatting")) {
suppressFormatting(event); this.suppressFormatting(event);
} else { } else {
// Swap the &-style codes for minimessage-compatible strings // Swap the &-style codes for minimessage-compatible strings
event.setMessage(MiniMessage.get().serialize(CarbonChat.LEGACY.deserialize(event.getMessage()))); event.message(MiniMessage.get().serialize(CarbonChat.LEGACY.deserialize(event.message())));
} }
} }
private void suppressFormatting(PreChatFormatEvent event) { private void suppressFormatting(final PreChatFormatEvent event) {
event.setFormat(event.getFormat().replace("<message>", "<pre><message></pre>")); event.format(event.format().replace("<message>", "<pre><message></pre>"));
} }
} }
@@ -14,32 +14,32 @@ public class WhisperPingHandler implements Listener {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public WhisperPingHandler(@NonNull CarbonChat carbonChat) { public WhisperPingHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPing(PrivateMessageEvent event) { public void onPing(final PrivateMessageEvent event) {
if (event.getSender().getUUID().equals(event.getTarget().getUUID())) { if (event.sender().uuid().equals(event.target().uuid())) {
return; return;
} }
String senderName = event.getSender().asOfflinePlayer().getName(); final String senderName = event.sender().offlinePlayer().getName();
if (senderName == null || !event.getMessage().contains(senderName)) { if (senderName == null || !event.message().contains(senderName)) {
return; return;
} }
if (!carbonChat.getConfig().getBoolean("whisper.pings.enabled")) { if (!this.carbonChat.getConfig().getBoolean("whisper.pings.enabled")) {
return; return;
} }
Key key = Key.of(carbonChat.getConfig().getString("whisper.pings.sound")); final Key key = Key.of(this.carbonChat.getConfig().getString("whisper.pings.sound"));
Sound.Source source = Sound.Source.valueOf(carbonChat.getConfig().getString("whisper.pings.source")); final Sound.Source source = Sound.Source.valueOf(this.carbonChat.getConfig().getString("whisper.pings.source"));
float volume = (float) carbonChat.getConfig().getDouble("whisper.pings.volume"); final float volume = (float) this.carbonChat.getConfig().getDouble("whisper.pings.volume");
float pitch = (float) carbonChat.getConfig().getDouble("whisper.pings.pitch"); final float pitch = (float) this.carbonChat.getConfig().getDouble("whisper.pings.pitch");
event.getSender().playSound(Sound.of(key, source, volume, pitch)); event.sender().playSound(Sound.of(key, source, volume, pitch));
} }
} }
@@ -19,33 +19,34 @@ public class AdventureManager {
@NonNull @NonNull
private final BukkitAudiences audiences; private final BukkitAudiences audiences;
public AdventureManager(@NonNull CarbonChat carbonChat) { public AdventureManager(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.audiences = BukkitAudiences.create(carbonChat); this.audiences = BukkitAudiences.create(carbonChat);
} }
@NonNull @NonNull
public Component processMessageWithPapi(@NonNull Player player, @Nullable String input, @NonNull String @NonNull ... placeholders) { public Component processMessageWithPapi(@NonNull final Player player, @Nullable final String input,
@NonNull final String @NonNull ... placeholders) {
if (input == null || input.trim().isEmpty()) { if (input == null || input.trim().isEmpty()) {
return TextComponent.empty(); return TextComponent.empty();
} }
return processMessage(PlaceholderAPI.setPlaceholders(player, input), placeholders); return this.processMessage(PlaceholderAPI.setPlaceholders(player, input), placeholders);
} }
@NonNull @NonNull
public Component processMessage(@Nullable String input, @NonNull String @NonNull ... placeholders) { public Component processMessage(@Nullable final String input, @NonNull final String @NonNull ... placeholders) {
if (input == null || input.trim().isEmpty()) { if (input == null || input.trim().isEmpty()) {
return TextComponent.empty(); return TextComponent.empty();
} }
switch (carbonChat.getLanguage().getString("formatting.type", "minimessage").toLowerCase()) { switch (this.carbonChat.language().getString("formatting.type", "minimessage").toLowerCase()) {
case "minedown": case "minedown":
return MineDown.parse(input, placeholders); return MineDown.parse(input, placeholders);
case "mojang": case "mojang":
case "mojangson": case "mojangson":
case "json": case "json":
return processMojang(input, placeholders); return this.processMojang(input, placeholders);
case "minimessage-markdown": case "minimessage-markdown":
return MiniMessage.markdown().parse(input, placeholders); return MiniMessage.markdown().parse(input, placeholders);
case "minimessage": case "minimessage":
@@ -55,19 +56,19 @@ public class AdventureManager {
} }
@NonNull @NonNull
private Component processMojang(@NonNull String input, @NonNull String @NonNull ... placeholders) { private Component processMojang(@NonNull String input, @NonNull final String @NonNull ... placeholders) {
for (int i = 0; i < placeholders.length; i += 2) { for (int i = 0; i < placeholders.length; i += 2) {
String placeholder = placeholders[i]; final String placeholder = placeholders[i];
String replacement = placeholders[i + 1]; final String replacement = placeholders[i + 1];
input = input.replace("<" + placeholder + ">", replacement); input = input.replace("<" + placeholder + ">", replacement);
} }
return getAudiences().gsonSerializer().deserialize(input); return this.audiences().gsonSerializer().deserialize(input);
} }
@NonNull @NonNull
public BukkitAudiences getAudiences() { public BukkitAudiences audiences() {
return audiences; return this.audiences;
} }
} }
@@ -26,87 +26,88 @@ public class ChannelManager {
@MonotonicNonNull @MonotonicNonNull
private String defaultChannelKey = null; private String defaultChannelKey = null;
public ChannelManager(CarbonChat carbonChat) { public ChannelManager(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.registry = new ChannelRegistry(carbonChat); this.registry = new ChannelRegistry(carbonChat);
reload(); this.reload();
} }
public @Nullable ChatChannel loadChannel(String key, @NonNull ConfigurationSection section) { public @Nullable ChatChannel loadChannel(@NonNull final String key, @NonNull final ConfigurationSection section) {
ChatChannel channel = new CarbonChatChannel(key, carbonChat, section); final ChatChannel channel = new CarbonChatChannel(key, this.carbonChat, section);
String name = section.getString("name"); final String name = section.getString("name");
if (name != null && name.length() > 16) { if (name != null && name.length() > 16) {
carbonChat.getLogger().warning("Channel name [" + name + "] too long! Max length: 16."); this.carbonChat.getLogger().warning("Channel name [" + name + "] too long! Max length: 16.");
carbonChat.getLogger().warning("Skipping channel, please check your settings!"); this.carbonChat.getLogger().warning("Skipping channel, please check your settings!");
return null; return null;
} }
return channel; return channel;
} }
public boolean registerChannel(@NonNull ChatChannel channel) { public boolean registerChannel(@NonNull final ChatChannel channel) {
boolean success = getRegistry().register(channel.getKey(), channel); final boolean success = this.registry().register(channel.key(), channel);
if (success) { if (success) {
if (channel.isDefault() && defaultChannelKey == null) { if (channel.isDefault() && this.defaultChannelKey == null) {
carbonChat.getLogger().info("Default channel registered: " + channel.getName()); this.carbonChat.getLogger().info("Default channel registered: " + channel.name());
defaultChannelKey = channel.getKey(); this.defaultChannelKey = channel.key();
} }
Bukkit.getPluginManager().callEvent(new ChannelRegisterEvent(Collections.singletonList(channel), getRegistry())); Bukkit.getPluginManager().callEvent(new ChannelRegisterEvent(Collections.singletonList(channel), this.registry()));
} }
return success; return success;
} }
public @NonNull Registry<ChatChannel> getRegistry() { public @NonNull Registry<ChatChannel> registry() {
return registry; return this.registry;
} }
public @Nullable ChatChannel getDefaultChannel() { public @Nullable ChatChannel defaultChannel() {
if (defaultChannelKey != null) { if (this.defaultChannelKey != null) {
return registry.get(defaultChannelKey); return this.registry.channel(this.defaultChannelKey);
} }
return null; return null;
} }
public @Nullable ChatChannel getChannelOrDefault(@Nullable String key) { public @Nullable ChatChannel channelOrDefault(@Nullable final String key) {
if (key == null) { if (key == null) {
return getDefaultChannel(); return this.defaultChannel();
} }
ChatChannel channel = registry.get(key); final ChatChannel channel = this.registry.channel(key);
if (channel == null) { if (channel == null) {
return getDefaultChannel(); return this.defaultChannel();
} }
return channel; return channel;
} }
private void reload() { private void reload() {
registry.clearAll(); this.registry.clearAll();
for (String key : carbonChat.getConfig().getConfigurationSection("channels").getKeys(false)) { for (final String key : this.carbonChat.getConfig().getConfigurationSection("channels").getKeys(false)) {
ConfigurationSection section = carbonChat.getConfig().getConfigurationSection("channels").getConfigurationSection(key); final ConfigurationSection section =
this.carbonChat.getConfig().getConfigurationSection("channels").getConfigurationSection(key);
ChatChannel channel = loadChannel(key, section); final ChatChannel channel = this.loadChannel(key, section);
if (channel != null) { if (channel != null) {
if (registerChannel(channel)) { if (this.registerChannel(channel)) {
String prefix = channel.getMessagePrefix(); String prefix = channel.messagePrefix();
if (prefix != null && !prefix.trim().isEmpty()) { if (prefix != null && !prefix.trim().isEmpty()) {
prefix = ("(" + prefix + ") "); prefix = "(" + prefix + ") ";
} else { } else {
prefix = ""; prefix = "";
} }
carbonChat.getLogger().info("Registering channel: " + prefix + channel.getName()); this.carbonChat.getLogger().info("Registering channel: " + prefix + channel.name());
} }
} }
} }
@@ -1,7 +1,21 @@
package net.draycia.carbon.managers; package net.draycia.carbon.managers;
import net.draycia.carbon.CarbonChat; import net.draycia.carbon.CarbonChat;
import net.draycia.carbon.commands.*; import net.draycia.carbon.commands.ChannelCommand;
import net.draycia.carbon.commands.ChannelListCommand;
import net.draycia.carbon.commands.ChatReloadCommand;
import net.draycia.carbon.commands.ClearChatCommand;
import net.draycia.carbon.commands.IgnoreCommand;
import net.draycia.carbon.commands.MeCommand;
import net.draycia.carbon.commands.MessageCommand;
import net.draycia.carbon.commands.MuteCommand;
import net.draycia.carbon.commands.NicknameCommand;
import net.draycia.carbon.commands.ReplyCommand;
import net.draycia.carbon.commands.SetColorCommand;
import net.draycia.carbon.commands.ShadowMuteCommand;
import net.draycia.carbon.commands.SpyChannelCommand;
import net.draycia.carbon.commands.SudoChannelCommand;
import net.draycia.carbon.commands.ToggleCommand;
import net.draycia.carbon.storage.CommandSettings; import net.draycia.carbon.storage.CommandSettings;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
@@ -11,32 +25,33 @@ public class CommandManager {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public CommandManager(@NonNull CarbonChat carbonChat) { public CommandManager(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
reloadCommands();
this.reloadCommands();
} }
private void reloadCommands() { private void reloadCommands() {
new ChannelCommand(carbonChat, getCommandSettings("channel")); new ChannelCommand(this.carbonChat, this.commandSettings("channel"));
new ChannelListCommand(carbonChat, getCommandSettings("channellist")); new ChannelListCommand(this.carbonChat, this.commandSettings("channellist"));
new ChatReloadCommand(carbonChat, getCommandSettings("chatreload")); new ChatReloadCommand(this.carbonChat, this.commandSettings("chatreload"));
new ClearChatCommand(carbonChat, getCommandSettings("clearchat")); new ClearChatCommand(this.carbonChat, this.commandSettings("clearchat"));
new IgnoreCommand(carbonChat, getCommandSettings("ignore")); new IgnoreCommand(this.carbonChat, this.commandSettings("ignore"));
new MeCommand(carbonChat, getCommandSettings("me")); new MeCommand(this.carbonChat, this.commandSettings("me"));
new MessageCommand(carbonChat, getCommandSettings("message")); new MessageCommand(this.carbonChat, this.commandSettings("message"));
new MuteCommand(carbonChat, getCommandSettings("mute")); new MuteCommand(this.carbonChat, this.commandSettings("mute"));
new NicknameCommand(carbonChat, getCommandSettings("nickname")); new NicknameCommand(this.carbonChat, this.commandSettings("nickname"));
new ReplyCommand(carbonChat, getCommandSettings("reply")); new ReplyCommand(this.carbonChat, this.commandSettings("reply"));
new SetColorCommand(carbonChat, getCommandSettings("setcolor")); new SetColorCommand(this.carbonChat, this.commandSettings("setcolor"));
new ShadowMuteCommand(carbonChat, getCommandSettings("shadowmute")); new ShadowMuteCommand(this.carbonChat, this.commandSettings("shadowmute"));
new SpyChannelCommand(carbonChat, getCommandSettings("spy")); new SpyChannelCommand(this.carbonChat, this.commandSettings("spy"));
new SudoChannelCommand(carbonChat, getCommandSettings("sudochannel")); new SudoChannelCommand(this.carbonChat, this.commandSettings("sudochannel"));
new ToggleCommand(carbonChat, getCommandSettings("toggle")); new ToggleCommand(this.carbonChat, this.commandSettings("toggle"));
} }
@NonNull @NonNull
private CommandSettings getCommandSettings(@NonNull String command) { private CommandSettings commandSettings(@NonNull final String command) {
ConfigurationSection section = carbonChat.getCommandsConfig().getConfigurationSection(command); final ConfigurationSection section = this.carbonChat.commandsConfig().getConfigurationSection(command);
return new CommandSettings(section.getBoolean("enabled"), section.getString("name"), return new CommandSettings(section.getBoolean("enabled"), section.getString("name"),
section.getStringList("aliases")); section.getStringList("aliases"));
@@ -15,7 +15,7 @@ public class ContextManager {
@NonNull @NonNull
private final Map<@NonNull String, @NonNull Function<@NonNull MessageContext, @NonNull Boolean>> handlers = new HashMap<>(); private final Map<@NonNull String, @NonNull Function<@NonNull MessageContext, @NonNull Boolean>> handlers = new HashMap<>();
public boolean register(@NonNull String key, @NonNull Function<@NonNull MessageContext, @NonNull Boolean> handler) { public boolean register(@NonNull final String key, @NonNull final Function<@NonNull MessageContext, @NonNull Boolean> handler) {
if (this.handlers.containsKey(key)) { if (this.handlers.containsKey(key)) {
return false; return false;
} }
@@ -24,17 +24,17 @@ public class ContextManager {
return true; return true;
} }
public boolean testContext(@NonNull ChatUser user, @NonNull ChatUser target, @NonNull ChatChannel channel) { public boolean testContext(@NonNull final ChatUser user, @NonNull final ChatUser target, @NonNull final ChatChannel channel) {
for (Map.Entry<String, Function<MessageContext, Boolean>> handler : handlers.entrySet()) { for (final Map.Entry<String, Function<MessageContext, Boolean>> handler : this.handlers.entrySet()) {
String key = handler.getKey(); final String key = handler.getKey();
Object value = channel.getContext(key); final Object value = channel.context(key);
if (value == null) { if (value == null) {
continue; continue;
} }
MessageContext context = new SimpleMessageContext(user, target, channel, value); final MessageContext context = new SimpleMessageContext(user, target, channel, value);
return handler.getValue().apply(context); return handler.getValue().apply(context);
} }
@@ -26,11 +26,11 @@ public class MessageManager {
@NonNull @NonNull
private final GsonComponentSerializer gsonSerializer; private final GsonComponentSerializer gsonSerializer;
public MessageManager(@NonNull CarbonChat carbonChat) { public MessageManager(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.gsonSerializer = carbonChat.getAdventureManager().getAudiences().gsonSerializer(); this.gsonSerializer = this.carbonChat.adventureManager().audiences().gsonSerializer();
String messageSystem = carbonChat.getConfig().getString("message-system", "none"); String messageSystem = this.carbonChat.getConfig().getString("message-system", "none");
if (messageSystem == null) { if (messageSystem == null) {
messageSystem = "none"; messageSystem = "none";
@@ -38,19 +38,19 @@ public class MessageManager {
switch (messageSystem.toLowerCase()) { switch (messageSystem.toLowerCase()) {
case "bungee": case "bungee":
carbonChat.getLogger().info("Using Bungee Plugin Messaging for message forwarding!"); this.carbonChat.getLogger().info("Using Bungee Plugin Messaging for message forwarding!");
messageService = new BungeeMessageService(carbonChat); this.messageService = new BungeeMessageService(this.carbonChat);
break; break;
case "redis": case "redis":
carbonChat.getLogger().info("Using Redis for message forwarding!"); this.carbonChat.getLogger().info("Using Redis for message forwarding!");
messageService = new RedisMessageService(carbonChat); this.messageService = new RedisMessageService(this.carbonChat);
break; break;
case "none": case "none":
messageService = new EmptyMessageService(); this.messageService = new EmptyMessageService();
break; break;
default: default:
carbonChat.getLogger().info("Invalid message service selected! Disabling syncing until next restart!"); this.carbonChat.getLogger().info("Invalid message service selected! Disabling syncing until next restart!");
messageService = new EmptyMessageService(); this.messageService = new EmptyMessageService();
break; break;
} }
@@ -58,106 +58,107 @@ public class MessageManager {
} }
private void registerDefaultListeners() { private void registerDefaultListeners() {
getMessageService().registerUserMessageListener("nickname", (user, byteArray) -> { this.messageService().registerUserMessageListener("nickname", (user, byteArray) -> {
String nickname = byteArray.readUTF(); final String nickname = byteArray.readUTF();
user.setNickname(nickname, true); user.nickname(nickname, true);
if (user.isOnline()) { if (user.online()) {
String message = carbonChat.getLanguage().getString("nickname-set"); final String message = this.carbonChat.language().getString("nickname-set");
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(user.asPlayer(), user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(user.player(),
message, "nickname", nickname)); message, "nickname", nickname));
} }
}); });
getMessageService().registerUserMessageListener("nickname-reset", (user, byteArray) -> { this.messageService().registerUserMessageListener("nickname-reset", (user, byteArray) -> {
user.setNickname(null, true); user.nickname(null, true);
if (user.isOnline()) { if (user.online()) {
String message = carbonChat.getLanguage().getString("nickname-reset"); final String message = this.carbonChat.language().getString("nickname-reset");
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(user.asPlayer(), message)); user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(user.player(), message));
} }
}); });
getMessageService().registerUserMessageListener("selected-channel", (user, byteArray) -> { this.messageService().registerUserMessageListener("selected-channel", (user, byteArray) -> {
user.setSelectedChannel(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()), true); user.selectedChannel(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()), true);
}); });
getMessageService().registerUserMessageListener("spying-whispers", (user, byteArray) -> { this.messageService().registerUserMessageListener("spying-whispers", (user, byteArray) -> {
user.setSpyingWhispers(byteArray.readBoolean(), true); user.spyingWhispers(byteArray.readBoolean(), true);
}); });
getMessageService().registerUserMessageListener("muted", (user, byteArray) -> { this.messageService().registerUserMessageListener("muted", (user, byteArray) -> {
user.setMuted(byteArray.readBoolean(), true); user.muted(byteArray.readBoolean(), true);
}); });
getMessageService().registerUserMessageListener("shadow-muted", (user, byteArray) -> { this.messageService().registerUserMessageListener("shadow-muted", (user, byteArray) -> {
user.setShadowMuted(byteArray.readBoolean(), true); user.shadowMuted(byteArray.readBoolean(), true);
}); });
getMessageService().registerUserMessageListener("reply-target", (user, byteArray) -> { this.messageService().registerUserMessageListener("reply-target", (user, byteArray) -> {
user.setReplyTarget(new UUID(byteArray.readLong(), byteArray.readLong()), true); user.replyTarget(new UUID(byteArray.readLong(), byteArray.readLong()), true);
}); });
getMessageService().registerUserMessageListener("ignoring-user", (user, byteArray) -> { this.messageService().registerUserMessageListener("ignoring-user", (user, byteArray) -> {
user.setIgnoringUser(new UUID(byteArray.readLong(), byteArray.readLong()), byteArray.readBoolean(), true); user.ignoringUser(new UUID(byteArray.readLong(), byteArray.readLong()), byteArray.readBoolean(), true);
}); });
getMessageService().registerUserMessageListener("ignoring-channel", (user, byteArray) -> { this.messageService().registerUserMessageListener("ignoring-channel", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF())) user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.setIgnoring(byteArray.readBoolean(), true); .ignoring(byteArray.readBoolean(), true);
}); });
getMessageService().registerUserMessageListener("spying-channel", (user, byteArray) -> { this.messageService().registerUserMessageListener("spying-channel", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF())) user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.setSpying(byteArray.readBoolean(), true); .spying(byteArray.readBoolean(), true);
}); });
getMessageService().registerUserMessageListener("channel-color", (user, byteArray) -> { this.messageService().registerUserMessageListener("channel-color", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF())) user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.setColor(TextColor.fromHexString(byteArray.readUTF()), true); .color(TextColor.fromHexString(byteArray.readUTF()), true);
}); });
getMessageService().registerUserMessageListener("channel-color-reset", (user, byteArray) -> { this.messageService().registerUserMessageListener("channel-color-reset", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF())) user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.setColor(null, true); .color(null, true);
}); });
getMessageService().registerUUIDMessageListener("channel-component", (uuid, byteArray) -> { this.messageService().registerUUIDMessageListener("channel-component", (uuid, byteArray) -> {
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()); final ChatChannel channel = this.carbonChat.channelManager().registry().channel(byteArray.readUTF());
ChatUser user = carbonChat.getUserService().wrap(uuid); final ChatUser user = this.carbonChat.userService().wrap(uuid);
if (channel != null) { if (channel != null) {
Component component = gsonSerializer.deserialize(byteArray.readUTF()); final Component component = this.gsonSerializer.deserialize(byteArray.readUTF());
channel.sendComponent(user, component); channel.sendComponent(user, component);
carbonChat.getAdventureManager().getAudiences().console().sendMessage(component); this.carbonChat.adventureManager().audiences().console().sendMessage(component);
} }
}); });
getMessageService().registerUUIDMessageListener("whisper-component", (uuid, byteArray) -> { this.messageService().registerUUIDMessageListener("whisper-component", (uuid, byteArray) -> {
UUID recipient = new UUID(byteArray.readLong(), byteArray.readLong()); final UUID recipient = new UUID(byteArray.readLong(), byteArray.readLong());
ChatUser target = carbonChat.getUserService().wrap(recipient); final ChatUser target = this.carbonChat.userService().wrap(recipient);
String message = byteArray.readUTF(); final String message = byteArray.readUTF();
if (!target.isIgnoringUser(uuid)) { if (!target.ignoringUser(uuid)) {
target.setReplyTarget(uuid); target.replyTarget(uuid);
target.sendMessage(gsonSerializer.deserialize(message)); target.sendMessage(this.gsonSerializer.deserialize(message));
} }
}); });
} }
@NonNull @NonNull
public MessageService getMessageService() { public MessageService messageService() {
return messageService; return this.messageService;
} }
public void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer) { public void sendMessage(@NonNull final String key, @NonNull final UUID uuid,
getMessageService().sendMessage(key, uuid, consumer); @NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer) {
this.messageService().sendMessage(key, uuid, consumer);
} }
} }
@@ -11,12 +11,12 @@ import java.util.function.Consumer;
public interface MessageService { public interface MessageService {
void registerUserMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener); void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener);
void registerUUIDMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener); void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener);
void unregisterMessageListener(@NonNull String key); void unregisterMessageListener(@NonNull final String key);
void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer); void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer);
} }
@@ -33,49 +33,50 @@ public class BungeeMessageService implements MessageService {
@NonNull @NonNull
private final UUID serverUUID = UUID.randomUUID(); private final UUID serverUUID = UUID.randomUUID();
public BungeeMessageService(@NonNull CarbonChat carbonChat) { public BungeeMessageService(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
carbonChat.getServer().getMessenger().registerOutgoingPluginChannel(carbonChat, "BungeeCord"); this.carbonChat.getServer().getMessenger().registerOutgoingPluginChannel(carbonChat, "BungeeCord");
api = BungeeChannelApi.of(carbonChat); this.api = BungeeChannelApi.of(carbonChat);
api.registerForwardListener((String channel, Player player, byte[] bytes) -> { this.api.registerForwardListener((String channel, Player player, byte[] bytes) -> {
try { try {
ByteArrayDataInput input = ByteStreams.newDataInput(bytes); final ByteArrayDataInput input = ByteStreams.newDataInput(bytes);
// Separated out for ease of debugging. // Separated out for ease of debugging.
long mostServer = input.readLong(); final long mostServer = input.readLong();
long leastServer = input.readLong(); final long leastServer = input.readLong();
UUID messageUUID = new UUID(mostServer, leastServer); final UUID messageUUID = new UUID(mostServer, leastServer);
if (messageUUID.equals(serverUUID)) { if (messageUUID.equals(this.serverUUID)) {
return; return;
} }
long mostUser = input.readLong(); final long mostUser = input.readLong();
long leastUser = input.readLong(); final long leastUser = input.readLong();
UUID userUUID = new UUID(mostUser, leastUser); final UUID userUUID = new UUID(mostUser, leastUser);
this.receiveMessage(userUUID, channel, input); this.receiveMessage(userUUID, channel, input);
} catch (IllegalStateException ignored) {} } catch (final IllegalStateException ignored) {
}
}); });
} }
private void receiveMessage(@NonNull UUID uuid, @NonNull String key, @NonNull ByteArrayDataInput value) { private void receiveMessage(@NonNull final UUID uuid, @NonNull final String key, @NonNull final ByteArrayDataInput value) {
ChatUser user = carbonChat.getUserService().wrapIfLoaded(uuid); final ChatUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
if (user != null) { if (user != null) {
for (Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : userLoadedListeners.entrySet()) { for (final Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) { if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value); listener.getValue().accept(user, value);
} }
} }
} }
for (Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : userNotLoadedListeners.entrySet()) { for (final Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : this.userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) { if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value); listener.getValue().accept(uuid, value);
} }
@@ -83,33 +84,33 @@ public class BungeeMessageService implements MessageService {
} }
@Override @Override
public void registerUserMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) { public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
userLoadedListeners.put(key, listener); this.userLoadedListeners.put(key, listener);
} }
@Override @Override
public void registerUUIDMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) { public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
userNotLoadedListeners.put(key, listener); this.userNotLoadedListeners.put(key, listener);
} }
@Override @Override
public void unregisterMessageListener(@NonNull String key) { public void unregisterMessageListener(@NonNull final String key) {
userLoadedListeners.remove(key); this.userLoadedListeners.remove(key);
userNotLoadedListeners.remove(key); this.userNotLoadedListeners.remove(key);
} }
@Override @Override
public void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<ByteArrayDataOutput> consumer) { public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<ByteArrayDataOutput> consumer) {
ByteArrayDataOutput msg = ByteStreams.newDataOutput(); final ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeLong(serverUUID.getMostSignificantBits()); msg.writeLong(this.serverUUID.getMostSignificantBits());
msg.writeLong(serverUUID.getLeastSignificantBits()); msg.writeLong(this.serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits()); msg.writeLong(uuid.getMostSignificantBits());
msg.writeLong(uuid.getLeastSignificantBits()); msg.writeLong(uuid.getLeastSignificantBits());
consumer.accept(msg); consumer.accept(msg);
api.forward("ALL", key, msg.toByteArray()); this.api.forward("ALL", key, msg.toByteArray());
} }
} }
@@ -13,22 +13,22 @@ import java.util.function.Consumer;
public class EmptyMessageService implements MessageService { public class EmptyMessageService implements MessageService {
@Override @Override
public void registerUserMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) { public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
// do nothing // do nothing
} }
@Override @Override
public void registerUUIDMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) { public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
// do nothing // do nothing
} }
@Override @Override
public void unregisterMessageListener(@NonNull String key) { public void unregisterMessageListener(@NonNull final String key) {
// do nothing // do nothing
} }
@Override @Override
public void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer) { public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer) {
// do nothing // do nothing
} }
@@ -40,56 +40,56 @@ public class RedisMessageService implements MessageService {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public RedisMessageService(@NonNull CarbonChat carbonChat) { public RedisMessageService(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
String host = carbonChat.getConfig().getString("redis.host"); final String host = this.carbonChat.getConfig().getString("redis.host");
String password = carbonChat.getConfig().getString("redis.password"); final String password = this.carbonChat.getConfig().getString("redis.password");
int port = carbonChat.getConfig().getInt("redis.port"); final int port = this.carbonChat.getConfig().getInt("redis.port");
int database = carbonChat.getConfig().getInt("redis.database"); final int database = this.carbonChat.getConfig().getInt("redis.database");
RedisURI.Builder builder = RedisURI.Builder.redis(host, port) final RedisURI.Builder builder = RedisURI.Builder.redis(host, port)
.withDatabase(database); .withDatabase(database);
if (password != null) { if (password != null) {
builder.withPassword(password.toCharArray()); builder.withPassword(password.toCharArray());
} }
RedisClient client = RedisClient.create(builder.build()); final RedisClient client = RedisClient.create(builder.build());
StatefulRedisPubSubConnection<String, String> subscribeConnection = client.connectPubSub(); final StatefulRedisPubSubConnection<String, String> subscribeConnection = client.connectPubSub();
this.subscribeSync = subscribeConnection.sync(); this.subscribeSync = subscribeConnection.sync();
StatefulRedisPubSubConnection<String, String> publishConnection = client.connectPubSub(); final StatefulRedisPubSubConnection<String, String> publishConnection = client.connectPubSub();
this.publishSync = publishConnection.sync(); this.publishSync = publishConnection.sync();
subscribeConnection.addListener((RedisListener) (channel, message) -> { subscribeConnection.addListener((RedisListener) (channel, message) -> {
ByteArrayDataInput input = ByteStreams.newDataInput(Base64.getDecoder().decode(message)); final ByteArrayDataInput input = ByteStreams.newDataInput(Base64.getDecoder().decode(message));
UUID messageUUID = new UUID(input.readLong(), input.readLong()); final UUID messageUUID = new UUID(input.readLong(), input.readLong());
if (messageUUID.equals(serverUUID)) { if (messageUUID.equals(this.serverUUID)) {
return; return;
} }
UUID uuid = new UUID(input.readLong(), input.readLong()); final UUID uuid = new UUID(input.readLong(), input.readLong());
this.receiveMessage(uuid, channel, input); this.receiveMessage(uuid, channel, input);
}); });
} }
private void receiveMessage(@NonNull UUID uuid, @NonNull String key, @NonNull ByteArrayDataInput value) { private void receiveMessage(@NonNull final UUID uuid, @NonNull final String key, @NonNull final ByteArrayDataInput value) {
ChatUser user = carbonChat.getUserService().wrapIfLoaded(uuid); final ChatUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
if (user != null) { if (user != null) {
for (Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : userLoadedListeners.entrySet()) { for (final Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) { if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value); listener.getValue().accept(user, value);
} }
} }
} }
for (Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : userNotLoadedListeners.entrySet()) { for (final Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : this.userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) { if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value); listener.getValue().accept(uuid, value);
} }
@@ -97,37 +97,37 @@ public class RedisMessageService implements MessageService {
} }
@Override @Override
public void registerUserMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) { public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
userLoadedListeners.put(key, listener); this.userLoadedListeners.put(key, listener);
subscribeSync.subscribe(key); this.subscribeSync.subscribe(key);
} }
@Override @Override
public void registerUUIDMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) { public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
userNotLoadedListeners.put(key, listener); this.userNotLoadedListeners.put(key, listener);
subscribeSync.subscribe(key); this.subscribeSync.subscribe(key);
} }
@Override @Override
public void unregisterMessageListener(@NonNull String key) { public void unregisterMessageListener(@NonNull final String key) {
userLoadedListeners.remove(key); this.userLoadedListeners.remove(key);
userNotLoadedListeners.remove(key); this.userNotLoadedListeners.remove(key);
subscribeSync.unsubscribe(key); this.subscribeSync.unsubscribe(key);
} }
@Override @Override
public void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer) { public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer) {
ByteArrayDataOutput msg = ByteStreams.newDataOutput(); final ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeLong(serverUUID.getMostSignificantBits()); msg.writeLong(this.serverUUID.getMostSignificantBits());
msg.writeLong(serverUUID.getLeastSignificantBits()); msg.writeLong(this.serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits()); msg.writeLong(uuid.getMostSignificantBits());
msg.writeLong(uuid.getLeastSignificantBits()); msg.writeLong(uuid.getLeastSignificantBits());
consumer.accept(msg); consumer.accept(msg);
publishSync.publish(key, Base64.getEncoder().encodeToString(msg.toByteArray())); this.publishSync.publish(key, Base64.getEncoder().encodeToString(msg.toByteArray()));
} }
} }
@@ -12,100 +12,100 @@ import java.util.UUID;
public interface ChatUser extends Audience { public interface ChatUser extends Audience {
@Nullable @Nullable
Player asPlayer(); Player player();
@NonNull @NonNull
OfflinePlayer asOfflinePlayer(); OfflinePlayer offlinePlayer();
@NonNull @NonNull
UUID getUUID(); UUID uuid();
boolean isOnline(); boolean online();
@Nullable @Nullable
String getNickname(); String nickname();
default void setNickname(@NonNull String nickname) { default void nickname(@NonNull final String nickname) {
this.setNickname(nickname, false); this.nickname(nickname, false);
} }
void setNickname(@Nullable String nickname, boolean fromRemote); void nickname(@Nullable String nickname, boolean fromRemote);
@Nullable @Nullable
ChatChannel getSelectedChannel(); ChatChannel selectedChannel();
default void setSelectedChannel(@NonNull ChatChannel channel) { default void selectedChannel(@NonNull final ChatChannel channel) {
this.setSelectedChannel(channel, false); this.selectedChannel(channel, false);
} }
void setSelectedChannel(@NonNull ChatChannel channel, boolean fromRemote); void selectedChannel(@NonNull ChatChannel channel, boolean fromRemote);
void clearSelectedChannel(); void clearSelectedChannel();
@NonNull @NonNull
UserChannelSettings getChannelSettings(@NonNull ChatChannel channel); UserChannelSettings channelSettings(@NonNull ChatChannel channel);
boolean isSpyingWhispers(); boolean spyingwhispers();
default void setSpyingWhispers(boolean spyingWhispers) { default void spyingWhispers(final boolean spyingWhispers) {
this.setSpyingWhispers(spyingWhispers, false); this.spyingWhispers(spyingWhispers, false);
} }
void setSpyingWhispers(boolean spyingWhispers, boolean fromRemote); void spyingWhispers(boolean spyingWhispers, boolean fromRemote);
boolean isMuted(); boolean muted();
default void setMuted(boolean muted) { default void muted(final boolean muted) {
this.setMuted(muted, false); this.muted(muted, false);
} }
void setMuted(boolean muted, boolean fromRemote); void muted(boolean muted, boolean fromRemote);
boolean isShadowMuted(); boolean shadowMuted();
default void setShadowMuted(boolean shadowMuted) { default void shadowMuted(final boolean shadowMuted) {
this.setShadowMuted(shadowMuted, false); this.shadowMuted(shadowMuted, false);
} }
void setShadowMuted(boolean shadowMuted, boolean fromRemote); void shadowMuted(boolean shadowMuted, boolean fromRemote);
@Nullable @Nullable
UUID getReplyTarget(); UUID replyTarget();
default void setReplyTarget(@Nullable UUID target) { default void replyTarget(@Nullable final UUID target) {
this.setReplyTarget(target, false); this.replyTarget(target, false);
} }
default void setReplyTarget(@Nullable ChatUser user) { default void replyTarget(@Nullable final ChatUser user) {
this.setReplyTarget(user.getUUID(), false); this.replyTarget(user.uuid(), false);
} }
void setReplyTarget(@Nullable UUID target, boolean fromRemote); void replyTarget(@Nullable UUID target, boolean fromRemote);
default void setReplyTarget(@Nullable ChatUser user, boolean fromRemote) { default void replyTarget(@Nullable final ChatUser user, final boolean fromRemote) {
this.setReplyTarget(user.getUUID(), fromRemote); this.replyTarget(user.uuid(), fromRemote);
} }
boolean isIgnoringUser(@NonNull UUID uuid); boolean ignoringUser(@NonNull UUID uuid);
void setIgnoringUser(@NonNull UUID uuid, boolean ignoring, boolean fromRemote); void ignoringUser(@NonNull UUID uuid, boolean ignoring, boolean fromRemote);
default void setIgnoringUser(@NonNull UUID uuid, boolean ignoring) { default void ignoringUser(@NonNull final UUID uuid, final boolean ignoring) {
this.setIgnoringUser(uuid, ignoring, false); this.ignoringUser(uuid, ignoring, false);
} }
default boolean isIgnoringUser(@NonNull ChatUser user) { default boolean ignoringUser(@NonNull final ChatUser user) {
return this.isIgnoringUser(user.getUUID()); return this.ignoringUser(user.uuid());
} }
default void setIgnoringUser(@NonNull ChatUser user, boolean ignoring, boolean fromRemote) { default void ignoringUser(@NonNull final ChatUser user, final boolean ignoring, final boolean fromRemote) {
this.setIgnoringUser(user.getUUID(), ignoring, fromRemote); this.ignoringUser(user.uuid(), ignoring, fromRemote);
} }
default void setIgnoringUser(@NonNull ChatUser user, boolean ignoring) { default void ignoringUser(@NonNull final ChatUser user, final boolean ignoring) {
this.setIgnoringUser(user.getUUID(), ignoring, false); this.ignoringUser(user.uuid(), ignoring, false);
} }
void sendMessage(@NonNull ChatUser sender, @NonNull String message); void sendMessage(@NonNull final ChatUser sender, @NonNull String message);
} }
@@ -14,27 +14,22 @@ public class CommandSettings {
@NonNull @NonNull
private final List<@NonNull String> aliases; private final List<@NonNull String> aliases;
public CommandSettings(boolean enabled, @NonNull String name, @NonNull List<@NonNull String> aliases) { public CommandSettings(final boolean enabled, @NonNull final String name, @NonNull final List<@NonNull String> aliases) {
this.enabled = enabled; this.enabled = enabled;
this.name = name; this.name = name;
this.aliases = aliases; this.aliases = aliases;
} }
public @NonNull String @NonNull [] getAliasesArray() { public @NonNull String @NonNull [] aliases() {
return aliases.toArray(new String[0]); return this.aliases.toArray(new String[0]);
} }
@NonNull @NonNull
public List<@NonNull String> getAliases() { public String name() {
return aliases; return this.name;
} }
@NonNull public boolean enabled() {
public String getName() { return this.enabled;
return name;
}
public boolean isEnabled() {
return enabled;
} }
} }
@@ -5,29 +5,29 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public interface UserChannelSettings { public interface UserChannelSettings {
boolean isSpying(); boolean spying();
default void setSpying(boolean spying) { default void spying(final boolean spying) {
this.setSpying(spying, false); this.spying(spying, false);
} }
void setSpying(boolean spying, boolean fromRemote); void spying(boolean spying, boolean fromRemote);
boolean isIgnored(); boolean ignored();
void setIgnoring(boolean ignored, boolean fromRemote); void ignoring(boolean ignored, boolean fromRemote);
default void setIgnoring(boolean ignored) { default void ignoring(final boolean ignored) {
this.setIgnoring(ignored, false); this.ignoring(ignored, false);
} }
@Nullable @Nullable
TextColor getColor(); TextColor color();
default void setColor(@Nullable TextColor color) { default void color(@Nullable final TextColor color) {
this.setColor(color, false); this.color(color, false);
} }
void setColor(@Nullable TextColor color, boolean fromRemote); void color(@Nullable TextColor color, boolean fromRemote);
} }
@@ -18,8 +18,8 @@ public interface UserService {
ChatUser wrap(UUID uuid); ChatUser wrap(UUID uuid);
@Nullable @Nullable
default ChatUser wrapIfLoaded(@NonNull OfflinePlayer player) { default ChatUser wrapIfLoaded(@NonNull final OfflinePlayer player) {
return wrapIfLoaded(player.getUniqueId()); return this.wrapIfLoaded(player.getUniqueId());
} }
@Nullable @Nullable
@@ -19,7 +19,12 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.*; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class CarbonChatUser implements ChatUser, ForwardingAudience { public class CarbonChatUser implements ChatUser, ForwardingAudience {
@@ -47,7 +52,7 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat"); this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
} }
public CarbonChatUser(@NonNull UUID uuid) { public CarbonChatUser(@NonNull final UUID uuid) {
this(); this();
this.uuid = uuid; this.uuid = uuid;
} }
@@ -55,60 +60,61 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override @Override
@NonNull @NonNull
public Iterable<@NonNull ? extends Audience> audiences() { public Iterable<@NonNull ? extends Audience> audiences() {
return Collections.singleton(carbonChat.getAdventureManager().getAudiences().player(uuid)); return Collections.singleton(this.carbonChat.adventureManager().audiences().player(this.uuid));
} }
@Override @Override
@Nullable @Nullable
public Player asPlayer() { public Player player() {
return Bukkit.getPlayer(uuid); return Bukkit.getPlayer(this.uuid);
} }
@Override @Override
@NonNull @NonNull
public OfflinePlayer asOfflinePlayer() { public OfflinePlayer offlinePlayer() {
return Bukkit.getOfflinePlayer(uuid); return Bukkit.getOfflinePlayer(this.uuid);
} }
@Override @Override
public boolean isOnline() { public boolean online() {
return asOfflinePlayer().isOnline(); return this.offlinePlayer().isOnline();
} }
@Override @Override
@NonNull @NonNull
public UUID getUUID() { public UUID uuid() {
return uuid; return this.uuid;
} }
@Override @Override
@Nullable @Nullable
public String getNickname() { public String nickname() {
return nickname; return this.nickname;
} }
@Override @Override
public void setNickname(@Nullable String newNickname, boolean fromRemote) { public void nickname(@Nullable String newNickname, final boolean fromRemote) {
this.nickname = newNickname; this.nickname = newNickname;
if (isOnline()) { if (this.online()) {
if (newNickname != null) { if (newNickname != null) {
Component component = carbonChat.getAdventureManager().processMessage(nickname); final Component component = this.carbonChat.adventureManager().processMessage(this.nickname);
newNickname = CarbonChat.LEGACY.serialize(component); newNickname = this.carbonChat.LEGACY.serialize(component);
} }
this.asPlayer().setDisplayName(newNickname); this.player().setDisplayName(newNickname);
if (carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) { if (this.carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
this.asPlayer().setPlayerListName(newNickname); this.player().setPlayerListName(newNickname);
} }
} }
if (!fromRemote) { if (!fromRemote) {
if (nickname == null) { if (this.nickname == null) {
carbonChat.getMessageManager().sendMessage("nickname-reset", this.getUUID(), (byteArray) -> {}); this.carbonChat.messageManager().sendMessage("nickname-reset", this.uuid(), byteArray -> {
});
} else { } else {
carbonChat.getMessageManager().sendMessage("nickname", this.getUUID(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("nickname", this.uuid(), byteArray -> {
byteArray.writeUTF(this.nickname); byteArray.writeUTF(this.nickname);
}); });
} }
@@ -117,54 +123,54 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override @Override
@Nullable @Nullable
public ChatChannel getSelectedChannel() { public ChatChannel selectedChannel() {
return carbonChat.getChannelManager().getChannelOrDefault(selectedChannel); return this.carbonChat.channelManager().channelOrDefault(this.selectedChannel);
} }
@Override @Override
public void setSelectedChannel(@NonNull ChatChannel chatChannel, boolean fromRemote) { public void selectedChannel(@NonNull final ChatChannel chatChannel, final boolean fromRemote) {
String failureMessage = chatChannel.getSwitchFailureMessage(); final String failureMessage = chatChannel.switchFailureMessage();
ChannelSwitchEvent event = new ChannelSwitchEvent(chatChannel, this, failureMessage); final ChannelSwitchEvent event = new ChannelSwitchEvent(chatChannel, this, failureMessage);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {
sendMessage(carbonChat.getAdventureManager().processMessage(event.getFailureMessage(), this.sendMessage(this.carbonChat.adventureManager().processMessage(event.failureMessage(),
"channel", chatChannel.getName())); "channel", chatChannel.name()));
return; return;
} }
this.selectedChannel = chatChannel.getKey(); this.selectedChannel = chatChannel.key();
if (!fromRemote) { if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("selected-channel", this.getUUID(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("selected-channel", this.uuid(), byteArray -> {
byteArray.writeUTF(chatChannel.getKey()); byteArray.writeUTF(chatChannel.key());
}); });
} }
} }
@Override @Override
public void clearSelectedChannel() { public void clearSelectedChannel() {
setSelectedChannel(carbonChat.getChannelManager().getDefaultChannel()); this.selectedChannel(this.carbonChat.channelManager().defaultChannel());
} }
@Override @Override
public boolean isIgnoringUser(@NonNull UUID uuid) { public boolean ignoringUser(@NonNull final UUID uuid) {
return ignoredUsers.contains(uuid); return this.ignoredUsers.contains(uuid);
} }
@Override @Override
public void setIgnoringUser(@NonNull UUID uuid, boolean ignoring, boolean fromRemote) { public void ignoringUser(@NonNull final UUID uuid, final boolean ignoring, final boolean fromRemote) {
if (ignoring) { if (ignoring) {
ignoredUsers.add(uuid); this.ignoredUsers.add(uuid);
} else { } else {
ignoredUsers.remove(uuid); this.ignoredUsers.remove(uuid);
} }
if (!fromRemote) { if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("ignoring-user", this.getUUID(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("ignoring-user", this.uuid(), byteArray -> {
byteArray.writeLong(uuid.getMostSignificantBits()); byteArray.writeLong(uuid.getMostSignificantBits());
byteArray.writeLong(uuid.getLeastSignificantBits()); byteArray.writeLong(uuid.getLeastSignificantBits());
byteArray.writeBoolean(ignoring); byteArray.writeBoolean(ignoring);
@@ -173,54 +179,54 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
} }
@NonNull @NonNull
public List<@NonNull UUID> getIgnoredUsers() { public List<@NonNull UUID> ignoredUsers() {
return ignoredUsers; return this.ignoredUsers;
} }
@Override @Override
public void setMuted(boolean muted, boolean fromRemote) { public void muted(final boolean muted, final boolean fromRemote) {
this.muted = muted; this.muted = muted;
if (!fromRemote) { if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("muted", this.getUUID(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("muted", this.uuid(), byteArray -> {
byteArray.writeBoolean(muted); byteArray.writeBoolean(muted);
}); });
} }
} }
@Override @Override
public boolean isMuted() { public boolean muted() {
return muted; return this.muted;
} }
@Override @Override
public void setShadowMuted(boolean shadowMuted, boolean fromRemote) { public void shadowMuted(final boolean shadowMuted, final boolean fromRemote) {
this.shadowMuted = shadowMuted; this.shadowMuted = shadowMuted;
if (!fromRemote) { if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("shadow-muted", this.getUUID(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("shadow-muted", this.uuid(), byteArray -> {
byteArray.writeBoolean(shadowMuted); byteArray.writeBoolean(shadowMuted);
}); });
} }
} }
@Override @Override
public boolean isShadowMuted() { public boolean shadowMuted() {
return shadowMuted; return this.shadowMuted;
} }
@Override @Override
@Nullable @Nullable
public UUID getReplyTarget() { public UUID replyTarget() {
return replyTarget; return this.replyTarget;
} }
@Override @Override
public void setReplyTarget(@Nullable UUID target, boolean fromRemote) { public void replyTarget(@Nullable final UUID target, final boolean fromRemote) {
this.replyTarget = target; this.replyTarget = target;
if (!fromRemote) { if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("reply-target", this.getUUID(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("reply-target", this.uuid(), byteArray -> {
byteArray.writeLong(target.getMostSignificantBits()); byteArray.writeLong(target.getMostSignificantBits());
byteArray.writeLong(target.getLeastSignificantBits()); byteArray.writeLong(target.getLeastSignificantBits());
}); });
@@ -229,67 +235,67 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override @Override
@NonNull @NonNull
public UserChannelSettings getChannelSettings(@NonNull ChatChannel channel) { public UserChannelSettings channelSettings(@NonNull final ChatChannel channel) {
return channelSettings.computeIfAbsent(channel.getKey(), (name) -> { return this.channelSettings.computeIfAbsent(channel.key(), name -> {
return new SimpleUserChannelSettings(uuid, channel.getKey()); return new SimpleUserChannelSettings(this.uuid, channel.key());
}); });
} }
@NonNull @NonNull
public Map<@NonNull String, @NonNull ? extends UserChannelSettings> getChannelSettings() { public Map<@NonNull String, @NonNull ? extends UserChannelSettings> channelSettings() {
return channelSettings; return this.channelSettings;
} }
@Override @Override
public void setSpyingWhispers(boolean spyingWhispers, boolean fromRemote) { public void spyingWhispers(final boolean spyingWhispers, final boolean fromRemote) {
this.spyingWhispers = spyingWhispers; this.spyingWhispers = spyingWhispers;
if (!fromRemote) { if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("spying-whispers", this.getUUID(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("spying-whispers", this.uuid(), byteArray -> {
byteArray.writeBoolean(spyingWhispers); byteArray.writeBoolean(spyingWhispers);
}); });
} }
} }
@Override @Override
public boolean isSpyingWhispers() { public boolean spyingwhispers() {
return spyingWhispers; return this.spyingWhispers;
} }
@Override @Override
public void sendMessage(@NonNull ChatUser sender, @NonNull String message) { public void sendMessage(@NonNull final ChatUser sender, @NonNull final String message) {
if (isIgnoringUser(sender) || sender.isIgnoringUser(this)) { if (this.ignoringUser(sender) || sender.ignoringUser(this)) {
return; return;
} }
String toPlayerFormat = carbonChat.getLanguage().getString("message-to-other"); final String toPlayerFormat = this.carbonChat.language().getString("message-to-other");
String fromPlayerFormat = carbonChat.getLanguage().getString("message-from-other"); final String fromPlayerFormat = this.carbonChat.language().getString("message-from-other");
String senderName = sender.asOfflinePlayer().getName(); String senderName = sender.offlinePlayer().getName();
String senderOfflineName = senderName; final String senderOfflineName = senderName;
String targetName = this.asOfflinePlayer().getName(); String targetName = this.offlinePlayer().getName();
String targetOfflineName = targetName; final String targetOfflineName = targetName;
if (sender.isOnline()) { if (sender.online()) {
senderName = sender.asPlayer().getDisplayName(); senderName = sender.player().getDisplayName();
} }
if (this.isOnline()) { if (this.online()) {
targetName = this.asPlayer().getDisplayName(); targetName = this.player().getDisplayName();
} }
Component toPlayerComponent = carbonChat.getAdventureManager().processMessage(toPlayerFormat, "br", "\n", final Component toPlayerComponent = this.carbonChat.adventureManager().processMessage(toPlayerFormat, "br", "\n",
"message", message, "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName); "target", targetName, "sender", senderName);
Component fromPlayerComponent = carbonChat.getAdventureManager().processMessage(fromPlayerFormat, "br", "\n", final Component fromPlayerComponent = this.carbonChat.adventureManager().processMessage(fromPlayerFormat, "br", "\n",
"message", message, "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName); "target", targetName, "sender", senderName);
PrivateMessageEvent event = new PrivateMessageEvent(sender, this, toPlayerComponent, fromPlayerComponent, message); final PrivateMessageEvent event = new PrivateMessageEvent(sender, this, toPlayerComponent, fromPlayerComponent, message);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
@@ -297,36 +303,36 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
return; return;
} }
if (this.isOnline()) { if (this.online()) {
if (sender.isOnline()) { if (sender.online()) {
sender.sendMessage(toPlayerComponent); sender.sendMessage(toPlayerComponent);
if (sender.isShadowMuted()) { if (sender.shadowMuted()) {
return; return;
} }
this.sendMessage(fromPlayerComponent); this.sendMessage(fromPlayerComponent);
sender.setReplyTarget(this); sender.replyTarget(this);
this.setReplyTarget(sender); this.replyTarget(sender);
if (carbonChat.getConfig().getBoolean("pings.on-whisper")) { if (this.carbonChat.getConfig().getBoolean("pings.on-whisper")) {
Key key = Key.of(carbonChat.getConfig().getString("pings.sound")); final Key key = Key.of(this.carbonChat.getConfig().getString("pings.sound"));
Sound.Source source = Sound.Source.valueOf(carbonChat.getConfig().getString("pings.source")); final Sound.Source source = Sound.Source.valueOf(this.carbonChat.getConfig().getString("pings.source"));
float volume = (float) carbonChat.getConfig().getDouble("pings.volume"); final float volume = (float) this.carbonChat.getConfig().getDouble("pings.volume");
float pitch = (float) carbonChat.getConfig().getDouble("pings.pitch"); final float pitch = (float) this.carbonChat.getConfig().getDouble("pings.pitch");
this.playSound(Sound.of(key, source, volume, pitch)); this.playSound(Sound.of(key, source, volume, pitch));
} }
} }
} else if (sender.isOnline()) { } else if (sender.online()) {
final String targetNameFinal = targetName; final String targetNameFinal = targetName;
final String senderNameFinal = senderName; final String senderNameFinal = senderName;
if (!carbonChat.isBungeeEnabled()) { if (!this.carbonChat.bungeeEnabled()) {
String playerOfflineFormat = carbonChat.getLanguage().getString("other-player-offline"); final String playerOfflineFormat = this.carbonChat.language().getString("other-player-offline");
Component playerOfflineComponent = carbonChat.getAdventureManager().processMessage(playerOfflineFormat, final Component playerOfflineComponent = this.carbonChat.adventureManager().processMessage(playerOfflineFormat,
"br", "\n", "br", "\n",
"message", message, "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "targetname", targetOfflineName, "sendername", senderOfflineName,
@@ -337,11 +343,11 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
return; return;
} }
BungeeChannelApi.of(carbonChat).getPlayerList("ALL").thenAccept(list -> { BungeeChannelApi.of(this.carbonChat).getPlayerList("ALL").thenAccept(list -> {
if (!list.contains(this.asOfflinePlayer().getName())) { if (!list.contains(this.offlinePlayer().getName())) {
String playerOfflineFormat = carbonChat.getLanguage().getString("other-player-offline"); final String playerOfflineFormat = this.carbonChat.language().getString("other-player-offline");
Component playerOfflineComponent = carbonChat.getAdventureManager().processMessage(playerOfflineFormat, final Component playerOfflineComponent = this.carbonChat.adventureManager().processMessage(playerOfflineFormat,
"br", "\n", "br", "\n",
"message", message, "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "targetname", targetOfflineName, "sendername", senderOfflineName,
@@ -354,26 +360,26 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
sender.sendMessage(toPlayerComponent); sender.sendMessage(toPlayerComponent);
carbonChat.getMessageManager().sendMessage("whisper-component", sender.getUUID(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("whisper-component", sender.uuid(), byteArray -> {
byteArray.writeLong(this.getUUID().getMostSignificantBits()); byteArray.writeLong(this.uuid().getMostSignificantBits());
byteArray.writeLong(this.getUUID().getLeastSignificantBits()); byteArray.writeLong(this.uuid().getLeastSignificantBits());
byteArray.writeUTF(carbonChat.getAdventureManager().getAudiences().gsonSerializer().serialize(fromPlayerComponent)); byteArray.writeUTF(this.carbonChat.adventureManager().audiences().gsonSerializer().serialize(fromPlayerComponent));
}); });
}); });
} }
for (Player player : Bukkit.getOnlinePlayers()) { for (final Player player : Bukkit.getOnlinePlayers()) {
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (!user.isSpyingWhispers()) { if (!user.spyingwhispers()) {
continue; continue;
} }
if (user.getUUID().equals(sender.getUUID()) || user.getUUID().equals(getUUID())) { if (user.uuid().equals(sender.uuid()) || user.uuid().equals(this.uuid())) {
continue; continue;
} }
user.sendMessage(carbonChat.getAdventureManager().processMessage(carbonChat.getLanguage().getString("spy-whispers"), user.sendMessage(this.carbonChat.adventureManager().processMessage(this.carbonChat.language().getString("spy-whispers"),
"br", "\n", "message", message, "br", "\n", "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName)); "target", targetName, "sender", senderName));
@@ -39,101 +39,101 @@ public class JSONUserService implements UserService {
.removalListener(this::saveUser) .removalListener(this::saveUser)
.build(CacheLoader.from(this::loadUser)); .build(CacheLoader.from(this::loadUser));
public JSONUserService(@NonNull CarbonChat carbonChat) { public JSONUserService(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
Bukkit.getScheduler().scheduleSyncRepeatingTask(carbonChat, userCache::cleanUp, 0L, 20 * 60 * 10); Bukkit.getScheduler().scheduleSyncRepeatingTask(carbonChat, this.userCache::cleanUp, 0L, 20 * 60 * 10);
} }
@Override @Override
public void onDisable() { public void onDisable() {
userCache.invalidateAll(); this.userCache.invalidateAll();
userCache.cleanUp(); this.userCache.cleanUp();
} }
@Override @Override
@Nullable @Nullable
public ChatUser wrap(@NonNull String name) { public ChatUser wrap(@NonNull final String name) {
Player player = Bukkit.getPlayer(name); final Player player = Bukkit.getPlayer(name);
if (player != null) { if (player != null) {
return wrap(player); return this.wrap(player);
} }
return wrap(Bukkit.getOfflinePlayer(name)); return this.wrap(Bukkit.getOfflinePlayer(name));
} }
@Override @Override
@Nullable @Nullable
public ChatUser wrap(@NonNull OfflinePlayer player) { public ChatUser wrap(@NonNull final OfflinePlayer player) {
return wrap(player.getUniqueId()); return this.wrap(player.getUniqueId());
} }
@Override @Override
@Nullable @Nullable
public ChatUser wrap(@NonNull UUID uuid) { public ChatUser wrap(@NonNull final UUID uuid) {
try { try {
return userCache.get(uuid); return this.userCache.get(uuid);
} catch (ExecutionException e) { } catch (final ExecutionException exception) {
e.printStackTrace(); exception.printStackTrace();
return null; return null;
} }
} }
@Override @Override
@Nullable @Nullable
public ChatUser wrapIfLoaded(@NonNull UUID uuid) { public ChatUser wrapIfLoaded(@NonNull final UUID uuid) {
return userCache.getIfPresent(uuid); return this.userCache.getIfPresent(uuid);
} }
@Override @Override
@Nullable @Nullable
public ChatUser refreshUser(@NonNull UUID uuid) { public ChatUser refreshUser(@NonNull final UUID uuid) {
userCache.invalidate(uuid); this.userCache.invalidate(uuid);
return this.wrap(uuid); return this.wrap(uuid);
} }
@Override @Override
public void invalidate(@NonNull ChatUser user) { public void invalidate(@NonNull final ChatUser user) {
userCache.invalidate(user.getUUID()); this.userCache.invalidate(user.uuid());
} }
@Override @Override
public void validate(@NonNull ChatUser user) { public void validate(@NonNull final ChatUser user) {
userCache.put(user.getUUID(), (CarbonChatUser) user); this.userCache.put(user.uuid(), (CarbonChatUser) user);
} }
@NonNull @NonNull
private CarbonChatUser loadUser(@NonNull UUID uuid) { private CarbonChatUser loadUser(@NonNull final UUID uuid) {
File userFile = new File(carbonChat.getDataFolder(), "users/" + uuid.toString() + ".json"); final File userFile = new File(this.carbonChat.getDataFolder(), "users/" + uuid.toString() + ".json");
ensureFileExists(userFile); this.ensureFileExists(userFile);
try (JsonReader reader = gson.newJsonReader(new FileReader(userFile))) { try (final JsonReader reader = this.gson.newJsonReader(new FileReader(userFile))) {
CarbonChatUser user = gson.fromJson(reader, userType); final CarbonChatUser user = this.gson.fromJson(reader, this.userType);
if (user != null) { if (user != null) {
return user; return user;
} }
} catch (IOException e) { } catch (final IOException exception) {
e.printStackTrace(); exception.printStackTrace();
} }
return new CarbonChatUser(uuid); return new CarbonChatUser(uuid);
} }
private void saveUser(@NonNull RemovalNotification<@NonNull UUID, @NonNull CarbonChatUser> notification) { private void saveUser(@NonNull final RemovalNotification<@NonNull UUID, @NonNull CarbonChatUser> notification) {
File userFile = new File(carbonChat.getDataFolder(), "users/" + notification.getKey().toString() + ".json"); final File userFile = new File(this.carbonChat.getDataFolder(), "users/" + notification.getKey().toString() + ".json");
ensureFileExists(userFile); this.ensureFileExists(userFile);
try (JsonWriter writer = gson.newJsonWriter(new FileWriter(userFile))) { try (final JsonWriter writer = this.gson.newJsonWriter(new FileWriter(userFile))) {
gson.toJson(notification.getValue(), userType, writer); this.gson.toJson(notification.getValue(), this.userType, writer);
} catch (IOException e) { } catch (final IOException exception) {
e.printStackTrace(); exception.printStackTrace();
} }
} }
private void ensureFileExists(@NonNull File file) { private void ensureFileExists(@NonNull final File file) {
if (!file.getParentFile().exists()) { if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
} }
@@ -141,8 +141,8 @@ public class JSONUserService implements UserService {
if (!file.exists()) { if (!file.exists()) {
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch (final IOException exception) {
e.printStackTrace(); exception.printStackTrace();
} }
} }
} }
@@ -1,6 +1,11 @@
package net.draycia.carbon.storage.impl; package net.draycia.carbon.storage.impl;
import co.aikar.idb.*; import co.aikar.idb.BukkitDB;
import co.aikar.idb.DB;
import co.aikar.idb.Database;
import co.aikar.idb.DbRow;
import co.aikar.idb.DbStatement;
import co.aikar.idb.HikariPooledDatabase;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; import com.google.common.cache.LoadingCache;
@@ -36,205 +41,205 @@ public class MySQLUserService implements UserService {
.removalListener(this::saveUser) .removalListener(this::saveUser)
.build(CacheLoader.from(this::loadUser)); .build(CacheLoader.from(this::loadUser));
public MySQLUserService(@NonNull CarbonChat carbonChat) { public MySQLUserService(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
ConfigurationSection section = carbonChat.getConfig().getConfigurationSection("storage"); final ConfigurationSection section = this.carbonChat.getConfig().getConfigurationSection("storage");
if (section == null) { if (section == null) {
throw new IllegalStateException("Missing Database Credentials!"); throw new IllegalStateException("Missing Database Credentials!");
} }
String username = section.getString("username", "username"); final String username = section.getString("username", "username");
String password = section.getString("password", "password"); final String password = section.getString("password", "password");
String dbname = section.getString("database", "0"); final String dbname = section.getString("database", "0");
String hostandport = section.getString("hostname", "hostname") + ":" + section.getString("port", "0"); final String hostandport = section.getString("hostname", "hostname") + ":" + section.getString("port", "0");
database = new HikariPooledDatabase(BukkitDB.getRecommendedOptions(carbonChat, username, password, dbname, hostandport)); this.database = new HikariPooledDatabase(BukkitDB.getRecommendedOptions(carbonChat, username, password, dbname, hostandport));
DB.setGlobalDatabase(database); DB.setGlobalDatabase(this.database);
try { try {
database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_users (uuid CHAR(36) PRIMARY KEY," + this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_users (uuid CHAR(36) PRIMARY KEY," +
"channel VARCHAR(16), muted BOOLEAN, shadowmuted BOOLEAN, spyingwhispers BOOLEAN," + "channel VARCHAR(16), muted BOOLEAN, shadowmuted BOOLEAN, spyingwhispers BOOLEAN," +
"nickname VARCHAR(512))"); "nickname VARCHAR(512))");
// Ignore the exception, it's just saying the column already exists // Ignore the exception, it's just saying the column already exists
try { try {
database.executeUpdate("ALTER TABLE sc_users ADD COLUMN spyingwhispers BOOLEAN DEFAULT false"); this.database.executeUpdate("ALTER TABLE sc_users ADD COLUMN spyingwhispers BOOLEAN DEFAULT false");
database.executeUpdate("ALTER TABLE sc_users ADD COLUMN nickname VARCHAR(512) DEFAULT false"); this.database.executeUpdate("ALTER TABLE sc_users ADD COLUMN nickname VARCHAR(512) DEFAULT false");
} catch (SQLSyntaxErrorException ignored) { } catch (final SQLSyntaxErrorException ignored) {
} }
database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_channel_settings (uuid CHAR(36), channel CHAR(16), spying BOOLEAN, ignored BOOLEAN, color TINYTEXT, PRIMARY KEY (uuid, channel))"); this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_channel_settings (uuid CHAR(36), channel CHAR(16), spying BOOLEAN, ignored BOOLEAN, color TINYTEXT, PRIMARY KEY (uuid, channel))");
database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_ignored_users (uuid CHAR(36), user CHAR(36), PRIMARY KEY (uuid, user))"); this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_ignored_users (uuid CHAR(36), user CHAR(36), PRIMARY KEY (uuid, user))");
} catch (SQLException e) { } catch (final SQLException exception) {
e.printStackTrace(); exception.printStackTrace();
} }
} }
@Override @Override
public void onDisable() { public void onDisable() {
userCache.invalidateAll(); this.userCache.invalidateAll();
userCache.cleanUp(); this.userCache.cleanUp();
database.close(); this.database.close();
} }
@Override @Override
@Nullable @Nullable
public ChatUser wrap(@NonNull String name) { public ChatUser wrap(@NonNull final String name) {
Player player = Bukkit.getPlayer(name); final Player player = Bukkit.getPlayer(name);
if (player != null) { if (player != null) {
return wrap(player); return this.wrap(player);
} }
return wrap(Bukkit.getOfflinePlayer(name)); return this.wrap(Bukkit.getOfflinePlayer(name));
} }
@Override @Override
@Nullable @Nullable
public ChatUser wrap(@NonNull OfflinePlayer player) { public ChatUser wrap(@NonNull final OfflinePlayer player) {
return wrap(player.getUniqueId()); return this.wrap(player.getUniqueId());
} }
@Override @Override
@Nullable @Nullable
public ChatUser wrap(@NonNull UUID uuid) { public ChatUser wrap(@NonNull final UUID uuid) {
try { try {
return userCache.get(uuid); return this.userCache.get(uuid);
} catch (ExecutionException e) { } catch (final ExecutionException exception) {
e.printStackTrace(); exception.printStackTrace();
return null; return null;
} }
} }
@Override @Override
@Nullable @Nullable
public ChatUser wrapIfLoaded(@NonNull UUID uuid) { public ChatUser wrapIfLoaded(@NonNull final UUID uuid) {
return userCache.getIfPresent(uuid); return this.userCache.getIfPresent(uuid);
} }
@Override @Override
@Nullable @Nullable
public ChatUser refreshUser(@NonNull UUID uuid) { public ChatUser refreshUser(@NonNull final UUID uuid) {
userCache.invalidate(uuid); this.userCache.invalidate(uuid);
return this.wrap(uuid); return this.wrap(uuid);
} }
@Override @Override
public void invalidate(@NonNull ChatUser user) { public void invalidate(@NonNull final ChatUser user) {
userCache.invalidate(user.getUUID()); this.userCache.invalidate(user.uuid());
} }
@Override @Override
public void validate(@NonNull ChatUser user) { public void validate(@NonNull final ChatUser user) {
userCache.put(user.getUUID(), (CarbonChatUser) user); this.userCache.put(user.uuid(), (CarbonChatUser) user);
} }
@NonNull @NonNull
private CarbonChatUser loadUser(@NonNull UUID uuid) { private CarbonChatUser loadUser(@NonNull final UUID uuid) {
CarbonChatUser user = new CarbonChatUser(uuid); final CarbonChatUser user = new CarbonChatUser(uuid);
try (DbStatement statement = database.query("SELECT * from sc_users WHERE uuid = ?;")) { try (final DbStatement statement = this.database.query("SELECT * from sc_users WHERE uuid = ?;")) {
statement.execute(uuid.toString()); statement.execute(uuid.toString());
DbRow users = statement.getNextRow(); final DbRow users = statement.getNextRow();
if (users == null) { if (users == null) {
return user; return user;
} }
List<DbRow> channelSettings = database.getResults("SELECT * from sc_channel_settings WHERE uuid = ?;", uuid.toString()); final List<DbRow> channelSettings = this.database.getResults("SELECT * from sc_channel_settings WHERE uuid = ?;", uuid.toString());
List<DbRow> ignoredUsers = database.getResults("SELECT * from sc_ignored_users WHERE uuid = ?;", uuid.toString()); final List<DbRow> ignoredUsers = this.database.getResults("SELECT * from sc_ignored_users WHERE uuid = ?;", uuid.toString());
ChatChannel channel = carbonChat.getChannelManager().getChannelOrDefault(users.getString("channel")); final ChatChannel channel = this.carbonChat.channelManager().channelOrDefault(users.getString("channel"));
if (channel != null) { if (channel != null) {
user.setSelectedChannel(channel, true); user.selectedChannel(channel, true);
} }
String nickname = users.getString("nickname"); final String nickname = users.getString("nickname");
if (nickname != null) { if (nickname != null) {
user.setNickname(nickname, true); user.nickname(nickname, true);
} }
user.setMuted(users.<Boolean>get("muted"), true); user.muted(users.<Boolean>get("muted"), true);
user.setShadowMuted(users.<Boolean>get("shadowmuted"), true); user.shadowMuted(users.<Boolean>get("shadowmuted"), true);
user.setSpyingWhispers(users.<Boolean>get("spyingwhispers"), true); user.spyingWhispers(users.<Boolean>get("spyingwhispers"), true);
for (DbRow channelSetting : channelSettings) { for (final DbRow channelSetting : channelSettings) {
ChatChannel chatChannel = carbonChat.getChannelManager().getRegistry().get(channelSetting.getString("channel")); final ChatChannel chatChannel = this.carbonChat.channelManager().registry().channel(channelSetting.getString("channel"));
if (chatChannel != null) { if (chatChannel != null) {
UserChannelSettings settings = user.getChannelSettings(chatChannel); final UserChannelSettings settings = user.channelSettings(chatChannel);
settings.setSpying(channelSetting.<Boolean>get("spying"), true); settings.spying(channelSetting.<Boolean>get("spying"), true);
settings.setIgnoring(channelSetting.<Boolean>get("ignored"), true); settings.ignoring(channelSetting.<Boolean>get("ignored"), true);
String color = channelSetting.getString("color"); final String color = channelSetting.getString("color");
if (color != null) { if (color != null) {
settings.setColor(TextColor.fromHexString(color), true); settings.color(TextColor.fromHexString(color), true);
} }
} }
} }
for (DbRow ignoredUser : ignoredUsers) { for (final DbRow ignoredUser : ignoredUsers) {
user.setIgnoringUser(UUID.fromString(ignoredUser.getString("user")), true, true); user.ignoringUser(UUID.fromString(ignoredUser.getString("user")), true, true);
} }
} catch (SQLException e) { } catch (final SQLException exception) {
e.printStackTrace(); exception.printStackTrace();
} }
return user; return user;
} }
private void saveUser(@NonNull RemovalNotification<@NonNull UUID, @NonNull CarbonChatUser> notification) { private void saveUser(@NonNull final RemovalNotification<@NonNull UUID, @NonNull CarbonChatUser> notification) {
CarbonChatUser user = notification.getValue(); final CarbonChatUser user = notification.getValue();
database.createTransaction(stm -> { this.database.createTransaction(stm -> {
// Save user general data // Save user general data
String selectedName = null; String selectedName = null;
if (user.getSelectedChannel() != null) { if (user.selectedChannel() != null) {
selectedName = user.getSelectedChannel().getKey(); selectedName = user.selectedChannel().key();
} }
carbonChat.getLogger().info("Saving user data!"); this.carbonChat.getLogger().info("Saving user data!");
stm.executeUpdateQuery("INSERT INTO sc_users (uuid, channel, muted, shadowmuted, spyingwhispers, nickname) VALUES (?, ?, ?, ?, ?, ?) " + stm.executeUpdateQuery("INSERT INTO sc_users (uuid, channel, muted, shadowmuted, spyingwhispers, nickname) VALUES (?, ?, ?, ?, ?, ?) " +
"ON DUPLICATE KEY UPDATE channel = ?, muted = ?, shadowmuted = ?, spyingwhispers = ?, nickname =?", "ON DUPLICATE KEY UPDATE channel = ?, muted = ?, shadowmuted = ?, spyingwhispers = ?, nickname =?",
user.getUUID().toString(), selectedName, user.isMuted(), user.isShadowMuted(), user.isSpyingWhispers(), user.getNickname(), user.uuid().toString(), selectedName, user.muted(), user.shadowMuted(), user.spyingwhispers(), user.nickname(),
selectedName, user.isMuted(), user.isShadowMuted(), user.isSpyingWhispers(), user.getNickname()); selectedName, user.muted(), user.shadowMuted(), user.spyingwhispers(), user.nickname());
carbonChat.getLogger().info("Saving user channel settings!"); this.carbonChat.getLogger().info("Saving user channel settings!");
// Save user channel settings // Save user channel settings
for (Map.Entry<String, ? extends UserChannelSettings> entry : user.getChannelSettings().entrySet()) { for (final Map.Entry<String, ? extends UserChannelSettings> entry : user.channelSettings().entrySet()) {
UserChannelSettings value = entry.getValue(); final UserChannelSettings value = entry.getValue();
String colorString = null; String colorString = null;
if (value.getColor() != null) { if (value.color() != null) {
colorString = value.getColor().asHexString(); colorString = value.color().asHexString();
} }
stm.executeUpdateQuery("INSERT INTO sc_channel_settings (uuid, channel, spying, ignored, color) VALUES (?, ?, ?, ?, ?) " + stm.executeUpdateQuery("INSERT INTO sc_channel_settings (uuid, channel, spying, ignored, color) VALUES (?, ?, ?, ?, ?) " +
"ON DUPLICATE KEY UPDATE spying = ?, ignored = ?, color = ?", "ON DUPLICATE KEY UPDATE spying = ?, ignored = ?, color = ?",
user.getUUID().toString(), entry.getKey(), value.isSpying(), value.isIgnored(), colorString, user.uuid().toString(), entry.getKey(), value.spying(), value.ignored(), colorString,
value.isSpying(), value.isIgnored(), colorString); value.spying(), value.ignored(), colorString);
} }
carbonChat.getLogger().info("Saving user ignores!"); this.carbonChat.getLogger().info("Saving user ignores!");
// Save user ignore list (remove old entries then add new ones) // Save user ignore list (remove old entries then add new ones)
// TODO: keep DB up to date with settings as settings are mutated // TODO: keep DB up to date with settings as settings are mutated
stm.executeUpdateQuery("DELETE FROM sc_ignored_users WHERE uuid = ?", user.getUUID().toString()); stm.executeUpdateQuery("DELETE FROM sc_ignored_users WHERE uuid = ?", user.uuid().toString());
for (UUID entry : user.getIgnoredUsers()) { for (final UUID entry : user.ignoredUsers()) {
stm.executeUpdateQuery("INSERT INTO sc_ignored_users (uuid, user) VALUES (?, ?)", stm.executeUpdateQuery("INSERT INTO sc_ignored_users (uuid, user) VALUES (?, ?)",
user.getUUID().toString(), entry.toString()); user.uuid().toString(), entry.toString());
} }
return true; return true;
@@ -24,50 +24,50 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
private String channel; private String channel;
private SimpleUserChannelSettings() { private SimpleUserChannelSettings() {
carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat"); this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
} }
public SimpleUserChannelSettings(@NonNull UUID uuid, @NonNull String channel) { public SimpleUserChannelSettings(@NonNull final UUID uuid, @NonNull final String channel) {
this.uuid = uuid; this.uuid = uuid;
this.channel = channel; this.channel = channel;
carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat"); this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
} }
@NonNull @NonNull
private CarbonChatUser getUser() { private CarbonChatUser user() {
return (CarbonChatUser) carbonChat.getUserService().wrap(uuid); return (CarbonChatUser) this.carbonChat.userService().wrap(this.uuid);
} }
@Override @Override
public boolean isSpying() { public boolean spying() {
return this.spying; return this.spying;
} }
@Override @Override
public void setSpying(boolean spying, boolean fromRemote) { public void spying(final boolean spying, final boolean fromRemote) {
this.spying = spying; this.spying = spying;
if (!fromRemote) { if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("spying-channel", uuid, (byteArray) -> { this.carbonChat.messageManager().sendMessage("spying-channel", this.uuid, byteArray -> {
byteArray.writeUTF(channel); byteArray.writeUTF(this.channel);
byteArray.writeBoolean(spying); byteArray.writeBoolean(spying);
}); });
} }
} }
@Override @Override
public boolean isIgnored() { public boolean ignored() {
return ignored; return this.ignored;
} }
@Override @Override
public void setIgnoring(boolean ignored, boolean fromRemote) { public void ignoring(final boolean ignored, final boolean fromRemote) {
this.ignored = ignored; this.ignored = ignored;
if (!fromRemote) { if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("ignoring-channel", uuid, (byteArray) -> { this.carbonChat.messageManager().sendMessage("ignoring-channel", this.uuid, byteArray -> {
byteArray.writeUTF(channel); byteArray.writeUTF(this.channel);
byteArray.writeBoolean(ignored); byteArray.writeBoolean(ignored);
}); });
} }
@@ -75,16 +75,16 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
@Override @Override
@Nullable @Nullable
public TextColor getColor() { public TextColor color() {
if (color == null) { if (this.color == null) {
return null; return null;
} }
return TextColor.fromHexString(color); return TextColor.fromHexString(this.color);
} }
@Override @Override
public void setColor(@Nullable TextColor color, boolean fromRemote) { public void color(@Nullable final TextColor color, final boolean fromRemote) {
if (color == null) { if (color == null) {
this.color = null; this.color = null;
} else { } else {
@@ -92,7 +92,7 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
} }
if (!fromRemote) { if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("channel-color", uuid, (byteArray) -> { this.carbonChat.messageManager().sendMessage("channel-color", this.uuid, byteArray -> {
byteArray.writeUTF(color.asHexString()); byteArray.writeUTF(color.asHexString());
}); });
} }
@@ -13,7 +13,7 @@ public class CarbonPlaceholders extends PlaceholderExpansion {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public CarbonPlaceholders(@NonNull CarbonChat carbonChat) { public CarbonPlaceholders(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
} }
@@ -43,48 +43,48 @@ public class CarbonPlaceholders extends PlaceholderExpansion {
@Override @Override
@Nullable @Nullable
public String onPlaceholderRequest(@NonNull final Player player, @NonNull final String identifier) { public String onPlaceholderRequest(@NonNull final Player player, @NonNull final String identifier) {
String key = identifier.toLowerCase(); final String key = identifier.toLowerCase();
if (key.startsWith("can_use_")) { if (key.startsWith("can_use_")) {
String value = key.replace("can_use_", ""); final String value = key.replace("can_use_", "");
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(value); final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
if (channel == null) { if (channel == null) {
return "false"; return "false";
} }
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
return String.valueOf(channel.canPlayerUse(user)); return String.valueOf(channel.canPlayerUse(user));
} else if (key.startsWith("can_see_")) { } else if (key.startsWith("can_see_")) {
String value = key.replace("can_see_", ""); final String value = key.replace("can_see_", "");
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(value); final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
if (channel == null) { if (channel == null) {
return "false"; return "false";
} }
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
return String.valueOf(channel.canPlayerSee(user, true)); return String.valueOf(channel.canPlayerSee(user, true));
} else if (key.startsWith("ignoring_channel_")) { } else if (key.startsWith("ignoring_channel_")) {
String value = key.replace("ignoring_channel_", ""); final String value = key.replace("ignoring_channel_", "");
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(value); final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
if (channel == null) { if (channel == null) {
return "false"; return "false";
} }
ChatUser user = carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
return String.valueOf(user.getChannelSettings(channel).isIgnored()); return String.valueOf(user.channelSettings(channel).ignored());
} else if (key.startsWith("selected_channel")) { } else if (key.startsWith("selected_channel")) {
ChatChannel channel = carbonChat.getUserService().wrap(player).getSelectedChannel(); final ChatChannel channel = this.carbonChat.userService().wrap(player).selectedChannel();
return channel == null ? carbonChat.getChannelManager().getDefaultChannel().getName() : channel.getName(); return channel == null ? this.carbonChat.channelManager().defaultChannel().name() : channel.name();
} }
return null; return null;
@@ -51,10 +51,14 @@ public final class CarbonUtils {
private static final @NonNull String @NonNull [] colors; private static final @NonNull String @NonNull [] colors;
static { private CarbonUtils() {
List<String> colorList = new ArrayList<>();
for (NamedTextColor color : NamedTextColor.values()) { }
static {
final List<String> colorList = new ArrayList<>();
for (final NamedTextColor color : NamedTextColor.values()) {
colorList.add(color.toString()); colorList.add(color.toString());
} }
@@ -73,17 +77,17 @@ public final class CarbonUtils {
return net.kyori.adventure.text.TextComponent.empty(); return net.kyori.adventure.text.TextComponent.empty();
} }
Content content = Bukkit.getItemFactory().hoverContentOf(itemStack); final Content content = Bukkit.getItemFactory().hoverContentOf(itemStack);
HoverEvent event = new HoverEvent(HoverEvent.Action.SHOW_ITEM, content); final HoverEvent event = new HoverEvent(HoverEvent.Action.SHOW_ITEM, content);
ComponentBuilder component = new ComponentBuilder(); final ComponentBuilder component = new ComponentBuilder();
component.event(event); // Let this be inherited by all coming components. component.event(event); // Let this be inherited by all coming components.
component.color(ChatColor.WHITE).append("["); component.color(ChatColor.WHITE).append("[");
if (itemStack.getItemMeta().hasDisplayName()) { if (itemStack.getItemMeta().hasDisplayName()) {
component.append(TextComponent.fromLegacyText(itemStack.getItemMeta().getDisplayName())); component.append(TextComponent.fromLegacyText(itemStack.getItemMeta().getDisplayName()));
} else { } else {
String name = itemStack.getItemMeta().hasDisplayName() final String name = itemStack.getItemMeta().hasDisplayName()
? itemStack.getItemMeta().getDisplayName() ? itemStack.getItemMeta().getDisplayName()
: "item.minecraft." + itemStack.getType().name().toLowerCase(); // As of 1.13, Material is 1:1 with MC's names : "item.minecraft." + itemStack.getType().name().toLowerCase(); // As of 1.13, Material is 1:1 with MC's names
component.append(new TranslatableComponent(name)); component.append(new TranslatableComponent(name));
@@ -95,21 +99,21 @@ public final class CarbonUtils {
} }
@Nullable @Nullable
public static TextColor parseColor(@Nullable String input) { public static TextColor parseColor(@Nullable final String input) {
return parseColor(null, input); return parseColor(null, input);
} }
@Nullable @Nullable
public static TextColor parseColor(@Nullable ChatUser user, @Nullable String input) { public static TextColor parseColor(@Nullable final ChatUser user, @Nullable String input) {
if (input == null) { if (input == null) {
input = "white"; input = "white";
} }
if (user != null && user.isOnline()) { if (user != null && user.online()) {
input = PlaceholderAPI.setPlaceholders(user.asPlayer(), input); input = PlaceholderAPI.setPlaceholders(user.player(), input);
} }
for (NamedTextColor namedColor : NamedTextColor.values()) { for (final NamedTextColor namedColor : NamedTextColor.values()) {
if (namedColor.toString().equalsIgnoreCase(input)) { if (namedColor.toString().equalsIgnoreCase(input)) {
return namedColor; return namedColor;
} }
@@ -126,16 +130,16 @@ public final class CarbonUtils {
@NonNull @NonNull
public static Argument onlineChatUserArgument() { public static Argument onlineChatUserArgument() {
return new CustomArgument<>((input) -> { return new CustomArgument<>(input -> {
CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat"); final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
Player player = Bukkit.getPlayer(input); final Player player = Bukkit.getPlayer(input);
if (player == null) { if (player == null) {
throw new CustomArgument.CustomArgumentException("Invalid player for input (" + input + ")"); throw new CustomArgument.CustomArgumentException("Invalid player for input (" + input + ")");
} }
return carbonChat.getUserService().wrap(player); return carbonChat.userService().wrap(player);
// }).overrideSuggestions((sender, args) -> { // }).overrideSuggestions((sender, args) -> {
// ArrayList<String> players = new ArrayList<>(); // ArrayList<String> players = new ArrayList<>();
// //
@@ -149,10 +153,10 @@ public final class CarbonUtils {
@NonNull @NonNull
public static Argument chatUserArgument() { public static Argument chatUserArgument() {
return new CustomArgument<>((input) -> { return new CustomArgument<>(input -> {
CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat"); final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
return carbonChat.getUserService().wrap(input); return carbonChat.userService().wrap(input);
// }).overrideSuggestions((sender, args) -> { // }).overrideSuggestions((sender, args) -> {
// ArrayList<String> players = new ArrayList<>(); // ArrayList<String> players = new ArrayList<>();
// //
@@ -166,8 +170,8 @@ public final class CarbonUtils {
@NonNull @NonNull
public static Argument textColorArgument() { public static Argument textColorArgument() {
return new CustomArgument<>((input) -> { return new CustomArgument<>(input -> {
TextColor color = parseColor(input); final TextColor color = parseColor(input);
if (color == null) { if (color == null) {
throw new CustomArgument.CustomArgumentException("Invalid color for input (" + input + ")"); throw new CustomArgument.CustomArgumentException("Invalid color for input (" + input + ")");
@@ -179,10 +183,10 @@ public final class CarbonUtils {
@NonNull @NonNull
public static Argument channelArgument() { public static Argument channelArgument() {
return new CustomArgument<>((input) -> { return new CustomArgument<>(input -> {
CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat"); final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(input); final ChatChannel channel = carbonChat.channelManager().registry().channel(input);
if (channel == null) { if (channel == null) {
throw new CustomArgument.CustomArgumentException("Invalid channel for input (" + input + ")"); throw new CustomArgument.CustomArgumentException("Invalid channel for input (" + input + ")");
@@ -194,7 +198,7 @@ public final class CarbonUtils {
// //
// ArrayList<String> channels = new ArrayList<>(); // ArrayList<String> channels = new ArrayList<>();
// //
// for (ChatChannel channel : carbonChat.getChannelManager().getRegistry().values()) { // for (ChatChannel channel : this.carbonChat.getChannelManager().getRegistry().values()) {
// channels.add(channel.getKey()); // channels.add(channel.getKey());
// } // }
// //
@@ -4,12 +4,16 @@ import dev.jorel.commandapi.CommandAPI;
import net.draycia.carbon.storage.CommandSettings; import net.draycia.carbon.storage.CommandSettings;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
public class CommandUtils { public final class CommandUtils {
public static void handleDuplicateCommands(@NonNull CommandSettings settings) { private CommandUtils() {
CommandAPI.unregister(settings.getName());
for (String command : settings.getAliases()) { }
public static void handleDuplicateCommands(@NonNull final CommandSettings settings) {
CommandAPI.unregister(settings.name());
for (final String command : settings.aliases()) {
CommandAPI.unregister(command); CommandAPI.unregister(command);
} }
} }
@@ -9,11 +9,15 @@ public final class FunctionalityConstants {
public static final boolean HAS_HOVER_EVENT_METHOD = noThrow(() -> ItemFactory.class.getMethod("hoverContentOf", ItemStack.class)); public static final boolean HAS_HOVER_EVENT_METHOD = noThrow(() -> ItemFactory.class.getMethod("hoverContentOf", ItemStack.class));
private static boolean noThrow(@NonNull ThrowingRunnable runnable) { private FunctionalityConstants() {
}
private static boolean noThrow(@NonNull final ThrowingRunnable runnable) {
try { try {
runnable.run(); runnable.run();
return true; return true;
} catch (Exception ex) { } catch (final Exception ex) {
return false; return false;
} }
} }
+115 -100
View File
@@ -12,12 +12,23 @@ import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority; import org.bukkit.plugin.ServicePriority;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import java.io.*; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
@@ -81,7 +92,7 @@ public class Metrics {
* @param pluginId The id of the plugin. * @param pluginId The id of the plugin.
* It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a> * It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
*/ */
public Metrics(Plugin plugin, int pluginId) { public Metrics(final Plugin plugin, final int pluginId) {
if (plugin == null) { if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!"); throw new IllegalArgumentException("Plugin cannot be null!");
} }
@@ -89,9 +100,9 @@ public class Metrics {
this.pluginId = pluginId; this.pluginId = pluginId;
// Get the config file // Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); final File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml"); final File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); final YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists // Check if the config file exists
if (!config.isSet("serverUuid")) { if (!config.isSet("serverUuid")) {
@@ -116,31 +127,33 @@ public class Metrics {
).copyDefaults(true); ).copyDefaults(true);
try { try {
config.save(configFile); config.save(configFile);
} catch (IOException ignored) { } } catch (final IOException ignored) {
}
} }
// Load the data // Load the data
enabled = config.getBoolean("enabled", true); this.enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid"); serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false); logFailedRequests = config.getBoolean("logFailedRequests", false);
logSentData = config.getBoolean("logSentData", false); logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false); logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) { if (this.enabled) {
boolean found = false; boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one // Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) { for (final Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try { try {
service.getField("B_STATS_VERSION"); // Our identifier :) service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first found = true; // We aren't the first
break; break;
} catch (NoSuchFieldException ignored) { } } catch (final NoSuchFieldException ignored) {
}
} }
// Register our service // Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) { if (!found) {
// We are the first! // We are the first!
startSubmitting(); this.startSubmitting();
} }
} }
} }
@@ -151,7 +164,7 @@ public class Metrics {
* @return Whether bStats is enabled or not. * @return Whether bStats is enabled or not.
*/ */
public boolean isEnabled() { public boolean isEnabled() {
return enabled; return this.enabled;
} }
/** /**
@@ -159,11 +172,11 @@ public class Metrics {
* *
* @param chart The chart to add. * @param chart The chart to add.
*/ */
public void addCustomChart(CustomChart chart) { public void addCustomChart(final CustomChart chart) {
if (chart == null) { if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!"); throw new IllegalArgumentException("Chart cannot be null!");
} }
charts.add(chart); this.charts.add(chart);
} }
/** /**
@@ -174,13 +187,13 @@ public class Metrics {
timer.scheduleAtFixedRate(new TimerTask() { timer.scheduleAtFixedRate(new TimerTask() {
@Override @Override
public void run() { public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled if (!Metrics.this.plugin.isEnabled()) { // Plugin was disabled
timer.cancel(); timer.cancel();
return; return;
} }
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler // 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 ;) // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData()); Bukkit.getScheduler().runTask(Metrics.this.plugin, () -> Metrics.this.submitData());
} }
}, 1000 * 60 * 5, 1000 * 60 * 30); }, 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 // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
@@ -195,18 +208,18 @@ public class Metrics {
* @return The plugin specific data. * @return The plugin specific data.
*/ */
public JsonObject getPluginData() { public JsonObject getPluginData() {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
String pluginName = plugin.getDescription().getName(); final String pluginName = this.plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion(); final String pluginVersion = this.plugin.getDescription().getVersion();
data.addProperty("pluginName", pluginName); // Append the name of the plugin data.addProperty("pluginName", pluginName); // Append the name of the plugin
data.addProperty("id", pluginId); // Append the id of the plugin data.addProperty("id", this.pluginId); // Append the id of the plugin
data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
JsonArray customCharts = new JsonArray(); final JsonArray customCharts = new JsonArray();
for (CustomChart customChart : charts) { for (final CustomChart customChart : this.charts) {
// Add the data of the custom charts // Add the data of the custom charts
JsonObject chart = customChart.getRequestJsonObject(); final JsonObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it if (chart == null) { // If the chart is null, we skip it
continue; continue;
} }
@@ -228,25 +241,25 @@ public class Metrics {
try { try {
// Around MC 1.8 the return type was changed to a collection from an array, // Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); final Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size() ? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) { } catch (final Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
} }
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; final int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion(); final String bukkitVersion = Bukkit.getVersion();
String bukkitName = Bukkit.getName(); final String bukkitName = Bukkit.getName();
// OS/Java specific data // OS/Java specific data
String javaVersion = System.getProperty("java.version"); final String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name"); final String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch"); final String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version"); final String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors(); final int coreCount = Runtime.getRuntime().availableProcessors();
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
data.addProperty("serverUUID", serverUUID); data.addProperty("serverUUID", serverUUID);
@@ -268,39 +281,41 @@ public class Metrics {
* Collects the data and sends it afterwards. * Collects the data and sends it afterwards.
*/ */
private void submitData() { private void submitData() {
final JsonObject data = getServerData(); final JsonObject data = this.getServerData();
JsonArray pluginData = new JsonArray(); final JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data // Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) { for (final Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try { try {
service.getField("B_STATS_VERSION"); // Our identifier :) service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) { for (final RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try { try {
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); final Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
if (plugin instanceof JsonObject) { if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin); pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility } else { // old bstats version compatibility
try { try {
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); final Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); final Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
jsonStringGetter.setAccessible(true); jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin); final String jsonString = (String) jsonStringGetter.invoke(plugin);
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); final JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
pluginData.add(object); pluginData.add(object);
} }
} catch (ClassNotFoundException e) { } catch (final ClassNotFoundException e) {
// minecraft version 1.14+ // minecraft version 1.14+
if (logFailedRequests) { if (logFailedRequests) {
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
} }
} }
} }
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } } catch (final NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
} catch (final NoSuchFieldException ignored) {
} }
} catch (NoSuchFieldException ignored) { }
} }
data.add("plugins", pluginData); data.add("plugins", pluginData);
@@ -309,11 +324,11 @@ public class Metrics {
new Thread(() -> { new Thread(() -> {
try { try {
// Send the data // Send the data
sendData(plugin, data); sendData(this.plugin, data);
} catch (Exception e) { } catch (final Exception e) {
// Something went wrong! :( // Something went wrong! :(
if (logFailedRequests) { if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); this.plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + this.plugin.getName(), e);
} }
} }
}).start(); }).start();
@@ -326,7 +341,7 @@ public class Metrics {
* @param data The data to send. * @param data The data to send.
* @throws Exception If the request failed. * @throws Exception If the request failed.
*/ */
private static void sendData(Plugin plugin, JsonObject data) throws Exception { private static void sendData(final Plugin plugin, final JsonObject data) throws Exception {
if (data == null) { if (data == null) {
throw new IllegalArgumentException("Data cannot be null!"); throw new IllegalArgumentException("Data cannot be null!");
} }
@@ -336,10 +351,10 @@ public class Metrics {
if (logSentData) { if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data); plugin.getLogger().info("Sending data to bStats: " + data);
} }
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); final HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth // Compress the data to save bandwidth
byte[] compressedData = compress(data.toString()); final byte[] compressedData = compress(data.toString());
// Add headers // Add headers
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
@@ -352,12 +367,12 @@ public class Metrics {
// Send data // Send data
connection.setDoOutput(true); connection.setDoOutput(true);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { try (final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(compressedData); outputStream.write(compressedData);
} }
StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line; String line;
while ((line = bufferedReader.readLine()) != null) { while ((line = bufferedReader.readLine()) != null) {
builder.append(line); builder.append(line);
@@ -380,8 +395,8 @@ public class Metrics {
if (str == null) { if (str == null) {
return null; return null;
} }
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { try (final GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
gzip.write(str.getBytes(StandardCharsets.UTF_8)); gzip.write(str.getBytes(StandardCharsets.UTF_8));
} }
return outputStream.toByteArray(); return outputStream.toByteArray();
@@ -400,7 +415,7 @@ public class Metrics {
* *
* @param chartId The id of the chart. * @param chartId The id of the chart.
*/ */
CustomChart(String chartId) { CustomChart(final String chartId) {
if (chartId == null || chartId.isEmpty()) { if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!"); throw new IllegalArgumentException("ChartId cannot be null or empty!");
} }
@@ -408,18 +423,18 @@ public class Metrics {
} }
private JsonObject getRequestJsonObject() { private JsonObject getRequestJsonObject() {
JsonObject chart = new JsonObject(); final JsonObject chart = new JsonObject();
chart.addProperty("chartId", chartId); chart.addProperty("chartId", this.chartId);
try { try {
JsonObject data = getChartData(); final JsonObject data = this.getChartData();
if (data == null) { if (data == null) {
// If the data is null we don't send the chart. // If the data is null we don't send the chart.
return null; return null;
} }
chart.add("data", data); chart.add("data", data);
} catch (Throwable t) { } catch (final Throwable t) {
if (logFailedRequests) { if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + this.chartId, t);
} }
return null; return null;
} }
@@ -443,15 +458,15 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public SimplePie(String chartId, Callable<String> callable) { public SimplePie(final String chartId, final Callable<String> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
String value = callable.call(); final String value = this.callable.call();
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
@@ -474,22 +489,22 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) { public AdvancedPie(final String chartId, final Callable<Map<String, Integer>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
JsonObject values = new JsonObject(); final JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call(); final Map<String, Integer> map = this.callable.call();
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
} }
boolean allSkipped = true; boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) { for (final Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) { if (entry.getValue() == 0) {
continue; // Skip this invalid continue; // Skip this invalid
} }
@@ -518,25 +533,25 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) { public DrilldownPie(final String chartId, final Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
public JsonObject getChartData() throws Exception { public JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
JsonObject values = new JsonObject(); final JsonObject values = new JsonObject();
Map<String, Map<String, Integer>> map = callable.call(); final Map<String, Map<String, Integer>> map = this.callable.call();
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
} }
boolean reallyAllSkipped = true; boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) { for (final Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObject value = new JsonObject(); final JsonObject value = new JsonObject();
boolean allSkipped = true; boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) { for (final Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.addProperty(valueEntry.getKey(), valueEntry.getValue()); value.addProperty(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false; allSkipped = false;
} }
@@ -567,15 +582,15 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public SingleLineChart(String chartId, Callable<Integer> callable) { public SingleLineChart(final String chartId, final Callable<Integer> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
int value = callable.call(); final int value = this.callable.call();
if (value == 0) { if (value == 0) {
// Null = skip the chart // Null = skip the chart
return null; return null;
@@ -599,22 +614,22 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) { public MultiLineChart(final String chartId, final Callable<Map<String, Integer>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
JsonObject values = new JsonObject(); final JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call(); final Map<String, Integer> map = this.callable.call();
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
} }
boolean allSkipped = true; boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) { for (final Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) { if (entry.getValue() == 0) {
continue; // Skip this invalid continue; // Skip this invalid
} }
@@ -644,22 +659,22 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) { public SimpleBarChart(final String chartId, final Callable<Map<String, Integer>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
JsonObject values = new JsonObject(); final JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call(); final Map<String, Integer> map = this.callable.call();
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
} }
for (Map.Entry<String, Integer> entry : map.entrySet()) { for (final Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray(); final JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue())); categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues); values.add(entry.getKey(), categoryValues);
} }
@@ -682,28 +697,28 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) { public AdvancedBarChart(final String chartId, final Callable<Map<String, int[]>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
JsonObject values = new JsonObject(); final JsonObject values = new JsonObject();
Map<String, int[]> map = callable.call(); final Map<String, int[]> map = this.callable.call();
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
} }
boolean allSkipped = true; boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) { for (final Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) { if (entry.getValue().length == 0) {
continue; // Skip this invalid continue; // Skip this invalid
} }
allSkipped = false; allSkipped = false;
JsonArray categoryValues = new JsonArray(); final JsonArray categoryValues = new JsonArray();
for (int categoryValue : entry.getValue()) { for (final int categoryValue : entry.getValue()) {
categoryValues.add(new JsonPrimitive(categoryValue)); categoryValues.add(new JsonPrimitive(categoryValue));
} }
values.add(entry.getKey(), categoryValues); values.add(entry.getKey(), categoryValues);
@@ -10,18 +10,23 @@ public interface RedisListener extends RedisPubSubListener<String, String> {
void message(@NonNull String channel, @NonNull String message); void message(@NonNull String channel, @NonNull String message);
@Override @Override
default void message(@NonNull String pattern, @NonNull String channel, @NonNull String message) { } default void message(@NonNull final String pattern, @NonNull final String channel, @NonNull final String message) {
}
@Override @Override
default void subscribed(@NonNull String channel, long count) { } default void subscribed(@NonNull final String channel, final long count) {
}
@Override @Override
default void psubscribed(@NonNull String pattern, long count) { } default void psubscribed(@NonNull final String pattern, final long count) {
}
@Override @Override
default void unsubscribed(@NonNull String channel, long count) { } default void unsubscribed(@NonNull final String channel, final long count) {
}
@Override @Override
default void punsubscribed(@NonNull String pattern, long count) { } default void punsubscribed(@NonNull final String pattern, final long count) {
}
} }
@@ -31,7 +31,7 @@ public interface Registry<@NonNull T> {
* @return The entry associated with the key or {@code null} if unassociated * @return The entry associated with the key or {@code null} if unassociated
*/ */
@Nullable @Nullable
T get(@NonNull String key); T channel(@NonNull String key);
/** /**
* Clears all registered entries from the registry * Clears all registered entries from the registry